sla_print_tests.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. #define CATCH_CONFIG_MAIN
  2. #include <catch2/catch.hpp>
  3. #include <unordered_set>
  4. #include <unordered_map>
  5. #include <random>
  6. // Debug
  7. #include <fstream>
  8. #include "libslic3r/libslic3r.h"
  9. #include "libslic3r/Format/OBJ.hpp"
  10. #include "libslic3r/SLAPrint.hpp"
  11. #include "libslic3r/TriangleMesh.hpp"
  12. #include "libslic3r/SLA/SLAPad.hpp"
  13. #include "libslic3r/SLA/SLASupportTreeBuilder.hpp"
  14. #include "libslic3r/SLA/SLASupportTreeBuildsteps.hpp"
  15. #include "libslic3r/SLA/SLAAutoSupports.hpp"
  16. #include "libslic3r/SLA/SLARaster.hpp"
  17. #include "libslic3r/SLA/ConcaveHull.hpp"
  18. #include "libslic3r/MTUtils.hpp"
  19. #include "libslic3r/SVG.hpp"
  20. #include "libslic3r/Format/OBJ.hpp"
  21. #if defined(WIN32) || defined(_WIN32)
  22. #define PATH_SEPARATOR R"(\)"
  23. #else
  24. #define PATH_SEPARATOR R"(/)"
  25. #endif
  26. namespace {
  27. using namespace Slic3r;
  28. TriangleMesh load_model(const std::string &obj_filename)
  29. {
  30. TriangleMesh mesh;
  31. auto fpath = TEST_DATA_DIR PATH_SEPARATOR + obj_filename;
  32. load_obj(fpath.c_str(), &mesh);
  33. return mesh;
  34. }
  35. enum e_validity {
  36. ASSUME_NO_EMPTY = 1,
  37. ASSUME_MANIFOLD = 2,
  38. ASSUME_NO_REPAIR = 4
  39. };
  40. void check_validity(const TriangleMesh &input_mesh,
  41. int flags = ASSUME_NO_EMPTY | ASSUME_MANIFOLD |
  42. ASSUME_NO_REPAIR)
  43. {
  44. TriangleMesh mesh{input_mesh};
  45. if (flags & ASSUME_NO_EMPTY) {
  46. REQUIRE_FALSE(mesh.empty());
  47. } else if (mesh.empty())
  48. return; // If it can be empty and it is, there is nothing left to do.
  49. REQUIRE(stl_validate(&mesh.stl));
  50. bool do_update_shared_vertices = false;
  51. mesh.repair(do_update_shared_vertices);
  52. if (flags & ASSUME_NO_REPAIR) {
  53. REQUIRE_FALSE(mesh.needed_repair());
  54. }
  55. if (flags & ASSUME_MANIFOLD) {
  56. mesh.require_shared_vertices();
  57. if (!mesh.is_manifold()) mesh.WriteOBJFile("non_manifold.obj");
  58. REQUIRE(mesh.is_manifold());
  59. }
  60. }
  61. struct PadByproducts
  62. {
  63. ExPolygons model_contours;
  64. ExPolygons support_contours;
  65. TriangleMesh mesh;
  66. };
  67. void _test_concave_hull(const Polygons &hull, const ExPolygons &polys)
  68. {
  69. REQUIRE(polys.size() >=hull.size());
  70. double polys_area = 0;
  71. for (const ExPolygon &p : polys) polys_area += p.area();
  72. double cchull_area = 0;
  73. for (const Slic3r::Polygon &p : hull) cchull_area += p.area();
  74. REQUIRE(cchull_area >= Approx(polys_area));
  75. size_t cchull_holes = 0;
  76. for (const Slic3r::Polygon &p : hull)
  77. cchull_holes += p.is_clockwise() ? 1 : 0;
  78. REQUIRE(cchull_holes == 0);
  79. Polygons intr = diff(to_polygons(polys), hull);
  80. REQUIRE(intr.empty());
  81. }
  82. void test_concave_hull(const ExPolygons &polys) {
  83. sla::PadConfig pcfg;
  84. Slic3r::sla::ConcaveHull cchull{polys, pcfg.max_merge_dist_mm, []{}};
  85. _test_concave_hull(cchull.polygons(), polys);
  86. coord_t delta = scaled(pcfg.brim_size_mm + pcfg.wing_distance());
  87. ExPolygons wafflex = sla::offset_waffle_style_ex(cchull, delta);
  88. Polygons waffl = sla::offset_waffle_style(cchull, delta);
  89. _test_concave_hull(to_polygons(wafflex), polys);
  90. _test_concave_hull(waffl, polys);
  91. }
  92. void test_pad(const std::string & obj_filename,
  93. const sla::PadConfig &padcfg,
  94. PadByproducts & out)
  95. {
  96. REQUIRE(padcfg.validate().empty());
  97. TriangleMesh mesh = load_model(obj_filename);
  98. REQUIRE_FALSE(mesh.empty());
  99. // Create pad skeleton only from the model
  100. Slic3r::sla::pad_blueprint(mesh, out.model_contours);
  101. test_concave_hull(out.model_contours);
  102. REQUIRE_FALSE(out.model_contours.empty());
  103. // Create the pad geometry for the model contours only
  104. Slic3r::sla::create_pad({}, out.model_contours, out.mesh, padcfg);
  105. check_validity(out.mesh);
  106. auto bb = out.mesh.bounding_box();
  107. REQUIRE(bb.max.z() - bb.min.z() == Approx(padcfg.full_height()));
  108. }
  109. void test_pad(const std::string & obj_filename,
  110. const sla::PadConfig &padcfg = {})
  111. {
  112. PadByproducts byproducts;
  113. test_pad(obj_filename, padcfg, byproducts);
  114. }
  115. struct SupportByproducts
  116. {
  117. std::string obj_fname;
  118. std::vector<float> slicegrid;
  119. std::vector<ExPolygons> model_slices;
  120. sla::SupportTreeBuilder supporttree;
  121. TriangleMesh input_mesh;
  122. };
  123. const constexpr float CLOSING_RADIUS = 0.005f;
  124. void check_support_tree_integrity(const sla::SupportTreeBuilder &stree,
  125. const sla::SupportConfig &cfg)
  126. {
  127. double gnd = stree.ground_level;
  128. double H1 = cfg.max_solo_pillar_height_mm;
  129. double H2 = cfg.max_dual_pillar_height_mm;
  130. for (const sla::Head &head : stree.heads()) {
  131. REQUIRE((!head.is_valid() || head.pillar_id != sla::ID_UNSET ||
  132. head.bridge_id != sla::ID_UNSET));
  133. }
  134. for (const sla::Pillar &pillar : stree.pillars()) {
  135. if (std::abs(pillar.endpoint().z() - gnd) < EPSILON) {
  136. double h = pillar.height;
  137. if (h > H1) REQUIRE(pillar.links >= 1);
  138. else if(h > H2) { REQUIRE(pillar.links >= 2); }
  139. }
  140. REQUIRE(pillar.links <= cfg.pillar_cascade_neighbors);
  141. REQUIRE(pillar.bridges <= cfg.max_bridges_on_pillar);
  142. }
  143. double max_bridgelen = 0.;
  144. auto chck_bridge = [&cfg](const sla::Bridge &bridge, double &max_brlen) {
  145. Vec3d n = bridge.endp - bridge.startp;
  146. double d = sla::distance(n);
  147. max_brlen = std::max(d, max_brlen);
  148. double z = n.z();
  149. double polar = std::acos(z / d);
  150. double slope = -polar + PI / 2.;
  151. REQUIRE(std::abs(slope) >= cfg.bridge_slope - EPSILON);
  152. };
  153. for (auto &bridge : stree.bridges()) chck_bridge(bridge, max_bridgelen);
  154. REQUIRE(max_bridgelen <= cfg.max_bridge_length_mm);
  155. max_bridgelen = 0;
  156. for (auto &bridge : stree.crossbridges()) chck_bridge(bridge, max_bridgelen);
  157. double md = cfg.max_pillar_link_distance_mm / std::cos(-cfg.bridge_slope);
  158. REQUIRE(max_bridgelen <= md);
  159. }
  160. void test_supports(const std::string & obj_filename,
  161. const sla::SupportConfig &supportcfg,
  162. SupportByproducts & out)
  163. {
  164. using namespace Slic3r;
  165. TriangleMesh mesh = load_model(obj_filename);
  166. REQUIRE_FALSE(mesh.empty());
  167. TriangleMeshSlicer slicer{&mesh};
  168. auto bb = mesh.bounding_box();
  169. double zmin = bb.min.z();
  170. double zmax = bb.max.z();
  171. double gnd = zmin - supportcfg.object_elevation_mm;
  172. auto layer_h = 0.05f;
  173. out.slicegrid = grid(float(gnd), float(zmax), layer_h);
  174. slicer.slice(out.slicegrid , CLOSING_RADIUS, &out.model_slices, []{});
  175. // Create the special index-triangle mesh with spatial indexing which
  176. // is the input of the support point and support mesh generators
  177. sla::EigenMesh3D emesh{mesh};
  178. // Create the support point generator
  179. sla::SLAAutoSupports::Config autogencfg;
  180. autogencfg.head_diameter = float(2 * supportcfg.head_front_radius_mm);
  181. sla::SLAAutoSupports point_gen{emesh, out.model_slices, out.slicegrid,
  182. autogencfg, [] {}, [](int) {}};
  183. // Get the calculated support points.
  184. std::vector<sla::SupportPoint> support_points = point_gen.output();
  185. int validityflags = ASSUME_NO_REPAIR;
  186. // If there is no elevation, support points shall be removed from the
  187. // bottom of the object.
  188. if (std::abs(supportcfg.object_elevation_mm) < EPSILON) {
  189. sla::remove_bottom_points(support_points, zmin,
  190. supportcfg.base_height_mm);
  191. } else {
  192. // Should be support points at least on the bottom of the model
  193. REQUIRE_FALSE(support_points.empty());
  194. // Also the support mesh should not be empty.
  195. validityflags |= ASSUME_NO_EMPTY;
  196. }
  197. // Generate the actual support tree
  198. sla::SupportTreeBuilder treebuilder;
  199. treebuilder.build(sla::SupportableMesh{emesh, support_points, supportcfg});
  200. check_support_tree_integrity(treebuilder, supportcfg);
  201. const TriangleMesh &output_mesh = treebuilder.retrieve_mesh();
  202. check_validity(output_mesh, validityflags);
  203. // Quick check if the dimensions and placement of supports are correct
  204. auto obb = output_mesh.bounding_box();
  205. double allowed_zmin = zmin - supportcfg.object_elevation_mm;
  206. if (std::abs(supportcfg.object_elevation_mm) < EPSILON)
  207. allowed_zmin = zmin - 2 * supportcfg.head_back_radius_mm;
  208. REQUIRE(obb.min.z() >= allowed_zmin);
  209. REQUIRE(obb.max.z() <= zmax);
  210. // Move out the support tree into the byproducts, we can examine it further
  211. // in various tests.
  212. out.obj_fname = std::move(obj_filename);
  213. out.supporttree = std::move(treebuilder);
  214. out.input_mesh = std::move(mesh);
  215. }
  216. void test_supports(const std::string & obj_filename,
  217. const sla::SupportConfig &supportcfg = {})
  218. {
  219. SupportByproducts byproducts;
  220. test_supports(obj_filename, supportcfg, byproducts);
  221. }
  222. void export_failed_case(const std::vector<ExPolygons> &support_slices,
  223. const SupportByproducts &byproducts)
  224. {
  225. for (size_t n = 0; n < support_slices.size(); ++n) {
  226. const ExPolygons &sup_slice = support_slices[n];
  227. const ExPolygons &mod_slice = byproducts.model_slices[n];
  228. Polygons intersections = intersection(sup_slice, mod_slice);
  229. std::stringstream ss;
  230. if (!intersections.empty()) {
  231. ss << byproducts.obj_fname << std::setprecision(4) << n << ".svg";
  232. SVG svg(ss.str());
  233. svg.draw(sup_slice, "green");
  234. svg.draw(mod_slice, "blue");
  235. svg.draw(intersections, "red");
  236. svg.Close();
  237. }
  238. }
  239. TriangleMesh m;
  240. byproducts.supporttree.retrieve_full_mesh(m);
  241. m.merge(byproducts.input_mesh);
  242. m.repair();
  243. m.require_shared_vertices();
  244. m.WriteOBJFile(byproducts.obj_fname.c_str());
  245. }
  246. void test_support_model_collision(
  247. const std::string & obj_filename,
  248. const sla::SupportConfig &input_supportcfg = {})
  249. {
  250. SupportByproducts byproducts;
  251. sla::SupportConfig supportcfg = input_supportcfg;
  252. // Set head penetration to a small negative value which should ensure that
  253. // the supports will not touch the model body.
  254. supportcfg.head_penetration_mm = -0.15;
  255. // TODO: currently, the tailheads penetrating into the model body do not
  256. // respect the penetration parameter properly. No issues were reported so
  257. // far but we should definitely fix this.
  258. supportcfg.ground_facing_only = true;
  259. test_supports(obj_filename, supportcfg, byproducts);
  260. // Slice the support mesh given the slice grid of the model.
  261. std::vector<ExPolygons> support_slices =
  262. byproducts.supporttree.slice(byproducts.slicegrid, CLOSING_RADIUS);
  263. // The slices originate from the same slice grid so the numbers must match
  264. bool support_mesh_is_empty =
  265. byproducts.supporttree.retrieve_mesh(sla::MeshType::Pad).empty() &&
  266. byproducts.supporttree.retrieve_mesh(sla::MeshType::Support).empty();
  267. if (support_mesh_is_empty)
  268. REQUIRE(support_slices.empty());
  269. else
  270. REQUIRE(support_slices.size() == byproducts.model_slices.size());
  271. bool notouch = true;
  272. for (size_t n = 0; notouch && n < support_slices.size(); ++n) {
  273. const ExPolygons &sup_slice = support_slices[n];
  274. const ExPolygons &mod_slice = byproducts.model_slices[n];
  275. Polygons intersections = intersection(sup_slice, mod_slice);
  276. notouch = notouch && intersections.empty();
  277. }
  278. if (!notouch) export_failed_case(support_slices, byproducts);
  279. REQUIRE(notouch);
  280. }
  281. const char * const BELOW_PAD_TEST_OBJECTS[] = {
  282. "20mm_cube.obj",
  283. "V.obj",
  284. };
  285. const char * const AROUND_PAD_TEST_OBJECTS[] = {
  286. "20mm_cube.obj",
  287. "V.obj",
  288. "frog_legs.obj",
  289. "cube_with_concave_hole_enlarged.obj",
  290. };
  291. const char *const SUPPORT_TEST_MODELS[] = {
  292. "cube_with_concave_hole_enlarged_standing.obj",
  293. "A_upsidedown.obj",
  294. "extruder_idler.obj"
  295. };
  296. } // namespace
  297. // Test pair hash for 'nums' random number pairs.
  298. template <class I, class II> void test_pairhash()
  299. {
  300. const constexpr size_t nums = 1000;
  301. I A[nums] = {0}, B[nums] = {0};
  302. std::unordered_set<I> CH;
  303. std::unordered_map<II, std::pair<I, I>> ints;
  304. std::random_device rd;
  305. std::mt19937 gen(rd());
  306. const I Ibits = int(sizeof(I) * CHAR_BIT);
  307. const II IIbits = int(sizeof(II) * CHAR_BIT);
  308. int bits = IIbits / 2 < Ibits ? Ibits / 2 : Ibits;
  309. if (std::is_signed<I>::value) bits -= 1;
  310. const I Imin = 0;
  311. const I Imax = I(std::pow(2., bits) - 1);
  312. std::uniform_int_distribution<I> dis(Imin, Imax);
  313. for (size_t i = 0; i < nums;) {
  314. I a = dis(gen);
  315. if (CH.find(a) == CH.end()) { CH.insert(a); A[i] = a; ++i; }
  316. }
  317. for (size_t i = 0; i < nums;) {
  318. I b = dis(gen);
  319. if (CH.find(b) == CH.end()) { CH.insert(b); B[i] = b; ++i; }
  320. }
  321. for (size_t i = 0; i < nums; ++i) {
  322. I a = A[i], b = B[i];
  323. REQUIRE(a != b);
  324. II hash_ab = sla::pairhash<I, II>(a, b);
  325. II hash_ba = sla::pairhash<I, II>(b, a);
  326. REQUIRE(hash_ab == hash_ba);
  327. auto it = ints.find(hash_ab);
  328. if (it != ints.end()) {
  329. REQUIRE((
  330. (it->second.first == a && it->second.second == b) ||
  331. (it->second.first == b && it->second.second == a)
  332. ));
  333. } else
  334. ints[hash_ab] = std::make_pair(a, b);
  335. }
  336. }
  337. TEST_CASE("Pillar pairhash should be unique", "[SLASupportGeneration]") {
  338. test_pairhash<int, int>();
  339. test_pairhash<int, long>();
  340. test_pairhash<unsigned, unsigned>();
  341. test_pairhash<unsigned, unsigned long>();
  342. }
  343. TEST_CASE("Flat pad geometry is valid", "[SLASupportGeneration]") {
  344. sla::PadConfig padcfg;
  345. // Disable wings
  346. padcfg.wall_height_mm = .0;
  347. for (auto &fname : BELOW_PAD_TEST_OBJECTS) test_pad(fname, padcfg);
  348. }
  349. TEST_CASE("WingedPadGeometryIsValid", "[SLASupportGeneration]") {
  350. sla::PadConfig padcfg;
  351. // Add some wings to the pad to test the cavity
  352. padcfg.wall_height_mm = 1.;
  353. for (auto &fname : BELOW_PAD_TEST_OBJECTS) test_pad(fname, padcfg);
  354. }
  355. TEST_CASE("FlatPadAroundObjectIsValid", "[SLASupportGeneration]") {
  356. sla::PadConfig padcfg;
  357. // Add some wings to the pad to test the cavity
  358. padcfg.wall_height_mm = 0.;
  359. // padcfg.embed_object.stick_stride_mm = 0.;
  360. padcfg.embed_object.enabled = true;
  361. padcfg.embed_object.everywhere = true;
  362. for (auto &fname : AROUND_PAD_TEST_OBJECTS) test_pad(fname, padcfg);
  363. }
  364. TEST_CASE("WingedPadAroundObjectIsValid", "[SLASupportGeneration]") {
  365. sla::PadConfig padcfg;
  366. // Add some wings to the pad to test the cavity
  367. padcfg.wall_height_mm = 1.;
  368. padcfg.embed_object.enabled = true;
  369. padcfg.embed_object.everywhere = true;
  370. for (auto &fname : AROUND_PAD_TEST_OBJECTS) test_pad(fname, padcfg);
  371. }
  372. TEST_CASE("ElevatedSupportGeometryIsValid", "[SLASupportGeneration]") {
  373. sla::SupportConfig supportcfg;
  374. supportcfg.object_elevation_mm = 5.;
  375. for (auto fname : SUPPORT_TEST_MODELS) test_supports(fname);
  376. }
  377. TEST_CASE("FloorSupportGeometryIsValid", "[SLASupportGeneration]") {
  378. sla::SupportConfig supportcfg;
  379. supportcfg.object_elevation_mm = 0;
  380. for (auto &fname: SUPPORT_TEST_MODELS) test_supports(fname, supportcfg);
  381. }
  382. TEST_CASE("ElevatedSupportsDoNotPierceModel", "[SLASupportGeneration]") {
  383. sla::SupportConfig supportcfg;
  384. for (auto fname : SUPPORT_TEST_MODELS)
  385. test_support_model_collision(fname, supportcfg);
  386. }
  387. TEST_CASE("FloorSupportsDoNotPierceModel", "[SLASupportGeneration]") {
  388. sla::SupportConfig supportcfg;
  389. supportcfg.object_elevation_mm = 0;
  390. for (auto fname : SUPPORT_TEST_MODELS)
  391. test_support_model_collision(fname, supportcfg);
  392. }
  393. TEST_CASE("DefaultRasterShouldBeEmpty", "[SLARasterOutput]") {
  394. sla::Raster raster;
  395. REQUIRE(raster.empty());
  396. }
  397. TEST_CASE("InitializedRasterShouldBeNONEmpty", "[SLARasterOutput]") {
  398. // Default Prusa SL1 display parameters
  399. sla::Raster::Resolution res{2560, 1440};
  400. sla::Raster::PixelDim pixdim{120. / res.width_px, 68. / res.height_px};
  401. sla::Raster raster;
  402. raster.reset(res, pixdim);
  403. REQUIRE_FALSE(raster.empty());
  404. REQUIRE(raster.resolution().width_px == res.width_px);
  405. REQUIRE(raster.resolution().height_px == res.height_px);
  406. REQUIRE(raster.pixel_dimensions().w_mm == Approx(pixdim.w_mm));
  407. REQUIRE(raster.pixel_dimensions().h_mm == Approx(pixdim.h_mm));
  408. }
  409. using TPixel = uint8_t;
  410. static constexpr const TPixel FullWhite = 255;
  411. static constexpr const TPixel FullBlack = 0;
  412. template <class A, int N> constexpr int arraysize(const A (&)[N]) { return N; }
  413. static void check_raster_transformations(sla::Raster::Orientation o,
  414. sla::Raster::TMirroring mirroring)
  415. {
  416. double disp_w = 120., disp_h = 68.;
  417. sla::Raster::Resolution res{2560, 1440};
  418. sla::Raster::PixelDim pixdim{disp_w / res.width_px, disp_h / res.height_px};
  419. auto bb = BoundingBox({0, 0}, {scaled(disp_w), scaled(disp_h)});
  420. sla::Raster::Trafo trafo{o, mirroring};
  421. trafo.origin_x = bb.center().x();
  422. trafo.origin_y = bb.center().y();
  423. sla::Raster raster{res, pixdim, trafo};
  424. // create box of size 32x32 pixels (not 1x1 to avoid antialiasing errors)
  425. coord_t pw = 32 * coord_t(std::ceil(scaled<double>(pixdim.w_mm)));
  426. coord_t ph = 32 * coord_t(std::ceil(scaled<double>(pixdim.h_mm)));
  427. ExPolygon box;
  428. box.contour.points = {{-pw, -ph}, {pw, -ph}, {pw, ph}, {-pw, ph}};
  429. double tr_x = scaled<double>(20.), tr_y = tr_x;
  430. box.translate(tr_x, tr_y);
  431. ExPolygon expected_box = box;
  432. // Now calculate the position of the translated box according to output
  433. // trafo.
  434. if (o == sla::Raster::Orientation::roPortrait) expected_box.rotate(PI / 2.);
  435. if (mirroring[X])
  436. for (auto &p : expected_box.contour.points) p.x() = -p.x();
  437. if (mirroring[Y])
  438. for (auto &p : expected_box.contour.points) p.y() = -p.y();
  439. raster.draw(box);
  440. Point expected_coords = expected_box.contour.bounding_box().center();
  441. double rx = unscaled(expected_coords.x() + bb.center().x()) / pixdim.w_mm;
  442. double ry = unscaled(expected_coords.y() + bb.center().y()) / pixdim.h_mm;
  443. auto w = size_t(std::floor(rx));
  444. auto h = res.height_px - size_t(std::floor(ry));
  445. REQUIRE((w < res.width_px && h < res.height_px));
  446. auto px = raster.read_pixel(w, h);
  447. if (px != FullWhite) {
  448. sla::PNGImage img;
  449. std::fstream outf("out.png", std::ios::out);
  450. outf << img.serialize(raster);
  451. }
  452. REQUIRE(px == FullWhite);
  453. }
  454. TEST_CASE("MirroringShouldBeCorrect", "[SLARasterOutput]") {
  455. sla::Raster::TMirroring mirrorings[] = {sla::Raster::NoMirror,
  456. sla::Raster::MirrorX,
  457. sla::Raster::MirrorY,
  458. sla::Raster::MirrorXY};
  459. sla::Raster::Orientation orientations[] = {sla::Raster::roLandscape,
  460. sla::Raster::roPortrait};
  461. for (auto orientation : orientations)
  462. for (auto &mirror : mirrorings)
  463. check_raster_transformations(orientation, mirror);
  464. }
  465. static ExPolygon square_with_hole(double v)
  466. {
  467. ExPolygon poly;
  468. coord_t V = scaled(v / 2.);
  469. poly.contour.points = {{-V, -V}, {V, -V}, {V, V}, {-V, V}};
  470. poly.holes.emplace_back();
  471. V = V / 2;
  472. poly.holes.front().points = {{-V, V}, {V, V}, {V, -V}, {-V, -V}};
  473. return poly;
  474. }
  475. static double pixel_area(TPixel px, const sla::Raster::PixelDim &pxdim)
  476. {
  477. return (pxdim.h_mm * pxdim.w_mm) * px * 1. / (FullWhite - FullBlack);
  478. }
  479. static double raster_white_area(const sla::Raster &raster)
  480. {
  481. if (raster.empty()) return std::nan("");
  482. auto res = raster.resolution();
  483. double a = 0;
  484. for (size_t x = 0; x < res.width_px; ++x)
  485. for (size_t y = 0; y < res.height_px; ++y) {
  486. auto px = raster.read_pixel(x, y);
  487. a += pixel_area(px, raster.pixel_dimensions());
  488. }
  489. return a;
  490. }
  491. static double predict_error(const ExPolygon &p, const sla::Raster::PixelDim &pd)
  492. {
  493. auto lines = p.lines();
  494. double pix_err = pixel_area(FullWhite, pd) / 2.;
  495. // Worst case is when a line is parallel to the shorter axis of one pixel,
  496. // when the line will be composed of the max number of pixels
  497. double pix_l = std::min(pd.h_mm, pd.w_mm);
  498. double error = 0.;
  499. for (auto &l : lines)
  500. error += (unscaled(l.length()) / pix_l) * pix_err;
  501. return error;
  502. }
  503. TEST_CASE("RasterizedPolygonAreaShouldMatch", "[SLARasterOutput]") {
  504. double disp_w = 120., disp_h = 68.;
  505. sla::Raster::Resolution res{2560, 1440};
  506. sla::Raster::PixelDim pixdim{disp_w / res.width_px, disp_h / res.height_px};
  507. sla::Raster raster{res, pixdim};
  508. auto bb = BoundingBox({0, 0}, {scaled(disp_w), scaled(disp_h)});
  509. ExPolygon poly = square_with_hole(10.);
  510. poly.translate(bb.center().x(), bb.center().y());
  511. raster.draw(poly);
  512. double a = poly.area() / (scaled<double>(1.) * scaled(1.));
  513. double ra = raster_white_area(raster);
  514. double diff = std::abs(a - ra);
  515. REQUIRE(diff <= predict_error(poly, pixdim));
  516. raster.clear();
  517. poly = square_with_hole(60.);
  518. poly.translate(bb.center().x(), bb.center().y());
  519. raster.draw(poly);
  520. a = poly.area() / (scaled<double>(1.) * scaled(1.));
  521. ra = raster_white_area(raster);
  522. diff = std::abs(a - ra);
  523. REQUIRE(diff <= predict_error(poly, pixdim));
  524. }