sla_print_tests.cpp 21 KB

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