sla_test_utils.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. #include "sla_test_utils.hpp"
  2. #include "libslic3r/SLA/AGGRaster.hpp"
  3. void test_support_model_collision(const std::string &obj_filename,
  4. const sla::SupportTreeConfig &input_supportcfg,
  5. const sla::HollowingConfig &hollowingcfg,
  6. const sla::DrainHoles &drainholes)
  7. {
  8. SupportByproducts byproducts;
  9. sla::SupportTreeConfig supportcfg = input_supportcfg;
  10. // Set head penetration to a small negative value which should ensure that
  11. // the supports will not touch the model body.
  12. supportcfg.head_penetration_mm = -0.15;
  13. test_supports(obj_filename, supportcfg, hollowingcfg, drainholes, byproducts);
  14. // Slice the support mesh given the slice grid of the model.
  15. std::vector<ExPolygons> support_slices =
  16. byproducts.supporttree.slice(byproducts.slicegrid, CLOSING_RADIUS);
  17. // The slices originate from the same slice grid so the numbers must match
  18. bool support_mesh_is_empty =
  19. byproducts.supporttree.retrieve_mesh(sla::MeshType::Pad).empty() &&
  20. byproducts.supporttree.retrieve_mesh(sla::MeshType::Support).empty();
  21. if (support_mesh_is_empty)
  22. REQUIRE(support_slices.empty());
  23. else
  24. REQUIRE(support_slices.size() == byproducts.model_slices.size());
  25. bool notouch = true;
  26. for (size_t n = 0; notouch && n < support_slices.size(); ++n) {
  27. const ExPolygons &sup_slice = support_slices[n];
  28. const ExPolygons &mod_slice = byproducts.model_slices[n];
  29. Polygons intersections = intersection(sup_slice, mod_slice);
  30. double pinhead_r = scaled(input_supportcfg.head_front_radius_mm);
  31. // TODO:: make it strict without a threshold of PI * pihead_radius ^ 2
  32. notouch = notouch && area(intersections) < PI * pinhead_r * pinhead_r;
  33. }
  34. /*if (!notouch) */export_failed_case(support_slices, byproducts);
  35. REQUIRE(notouch);
  36. }
  37. void export_failed_case(const std::vector<ExPolygons> &support_slices, const SupportByproducts &byproducts)
  38. {
  39. for (size_t n = 0; n < support_slices.size(); ++n) {
  40. const ExPolygons &sup_slice = support_slices[n];
  41. const ExPolygons &mod_slice = byproducts.model_slices[n];
  42. Polygons intersections = intersection(sup_slice, mod_slice);
  43. std::stringstream ss;
  44. if (!intersections.empty()) {
  45. ss << byproducts.obj_fname << std::setprecision(4) << n << ".svg";
  46. SVG svg(ss.str());
  47. svg.draw(sup_slice, "green");
  48. svg.draw(mod_slice, "blue");
  49. svg.draw(intersections, "red");
  50. svg.Close();
  51. }
  52. }
  53. TriangleMesh m;
  54. byproducts.supporttree.retrieve_full_mesh(m);
  55. m.merge(byproducts.input_mesh);
  56. m.repair();
  57. m.require_shared_vertices();
  58. m.WriteOBJFile((Catch::getResultCapture().getCurrentTestName() + "_" +
  59. byproducts.obj_fname).c_str());
  60. }
  61. void test_supports(const std::string &obj_filename,
  62. const sla::SupportTreeConfig &supportcfg,
  63. const sla::HollowingConfig &hollowingcfg,
  64. const sla::DrainHoles &drainholes,
  65. SupportByproducts &out)
  66. {
  67. using namespace Slic3r;
  68. TriangleMesh mesh = load_model(obj_filename);
  69. REQUIRE_FALSE(mesh.empty());
  70. if (hollowingcfg.enabled) {
  71. auto inside = sla::generate_interior(mesh, hollowingcfg);
  72. REQUIRE(inside);
  73. mesh.merge(*inside);
  74. mesh.require_shared_vertices();
  75. }
  76. TriangleMeshSlicer slicer{ CLOSING_RADIUS,0 };
  77. slicer.init(&mesh, [] {});
  78. auto bb = mesh.bounding_box();
  79. double zmin = bb.min.z();
  80. double zmax = bb.max.z();
  81. double gnd = zmin - supportcfg.object_elevation_mm;
  82. auto layer_h = 0.05f;
  83. out.slicegrid = grid(float(gnd), float(zmax), layer_h);
  84. slicer.slice(out.slicegrid, SlicingMode::Regular, &out.model_slices, []{});
  85. sla::cut_drainholes(out.model_slices, out.slicegrid, CLOSING_RADIUS, drainholes, []{});
  86. // Create the special index-triangle mesh with spatial indexing which
  87. // is the input of the support point and support mesh generators
  88. sla::IndexedMesh emesh{mesh};
  89. #ifdef SLIC3R_HOLE_RAYCASTER
  90. if (hollowingcfg.enabled)
  91. emesh.load_holes(drainholes);
  92. #endif
  93. // TODO: do the cgal hole cutting...
  94. // Create the support point generator
  95. sla::SupportPointGenerator::Config autogencfg;
  96. autogencfg.head_diameter = float(2 * supportcfg.head_front_radius_mm);
  97. sla::SupportPointGenerator point_gen{emesh, autogencfg, [] {}, [](int) {}};
  98. point_gen.seed(0); // Make the test repeatable
  99. point_gen.execute(out.model_slices, out.slicegrid);
  100. // Get the calculated support points.
  101. std::vector<sla::SupportPoint> support_points = point_gen.output();
  102. int validityflags = ASSUME_NO_REPAIR;
  103. // If there is no elevation, support points shall be removed from the
  104. // bottom of the object.
  105. if (std::abs(supportcfg.object_elevation_mm) < EPSILON) {
  106. sla::remove_bottom_points(support_points, zmin + supportcfg.base_height_mm);
  107. } else {
  108. // Should be support points at least on the bottom of the model
  109. REQUIRE_FALSE(support_points.empty());
  110. // Also the support mesh should not be empty.
  111. validityflags |= ASSUME_NO_EMPTY;
  112. }
  113. // Generate the actual support tree
  114. sla::SupportTreeBuilder treebuilder;
  115. sla::SupportableMesh sm{emesh, support_points, supportcfg};
  116. sla::SupportTreeBuildsteps::execute(treebuilder, sm);
  117. check_support_tree_integrity(treebuilder, supportcfg);
  118. const TriangleMesh &output_mesh = treebuilder.retrieve_mesh();
  119. check_validity(output_mesh, validityflags);
  120. // Quick check if the dimensions and placement of supports are correct
  121. auto obb = output_mesh.bounding_box();
  122. double allowed_zmin = zmin - supportcfg.object_elevation_mm;
  123. if (std::abs(supportcfg.object_elevation_mm) < EPSILON)
  124. allowed_zmin = zmin - 2 * supportcfg.head_back_radius_mm;
  125. REQUIRE(obb.min.z() >= Approx(allowed_zmin));
  126. REQUIRE(obb.max.z() <= Approx(zmax));
  127. // Move out the support tree into the byproducts, we can examine it further
  128. // in various tests.
  129. out.obj_fname = std::move(obj_filename);
  130. out.supporttree = std::move(treebuilder);
  131. out.input_mesh = std::move(mesh);
  132. }
  133. void check_support_tree_integrity(const sla::SupportTreeBuilder &stree,
  134. const sla::SupportTreeConfig &cfg)
  135. {
  136. double gnd = stree.ground_level;
  137. double H1 = cfg.max_solo_pillar_height_mm;
  138. double H2 = cfg.max_dual_pillar_height_mm;
  139. for (const sla::Head &head : stree.heads()) {
  140. REQUIRE((!head.is_valid() || head.pillar_id != sla::SupportTreeNode::ID_UNSET ||
  141. head.bridge_id != sla::SupportTreeNode::ID_UNSET));
  142. }
  143. for (const sla::Pillar &pillar : stree.pillars()) {
  144. if (std::abs(pillar.endpoint().z() - gnd) < EPSILON) {
  145. double h = pillar.height;
  146. if (h > H1) REQUIRE(pillar.links >= 1);
  147. else if(h > H2) { REQUIRE(pillar.links >= 2); }
  148. }
  149. REQUIRE(pillar.links <= cfg.pillar_cascade_neighbors);
  150. REQUIRE(pillar.bridges <= cfg.max_bridges_on_pillar);
  151. }
  152. double max_bridgelen = 0.;
  153. auto chck_bridge = [&cfg](const sla::Bridge &bridge, double &max_brlen) {
  154. Vec3d n = bridge.endp - bridge.startp;
  155. double d = sla::distance(n);
  156. max_brlen = std::max(d, max_brlen);
  157. double z = n.z();
  158. double polar = std::acos(z / d);
  159. double slope = -polar + PI / 2.;
  160. REQUIRE(std::abs(slope) >= cfg.bridge_slope - EPSILON);
  161. };
  162. for (auto &bridge : stree.bridges()) chck_bridge(bridge, max_bridgelen);
  163. REQUIRE(max_bridgelen <= Approx(cfg.max_bridge_length_mm));
  164. max_bridgelen = 0;
  165. for (auto &bridge : stree.crossbridges()) chck_bridge(bridge, max_bridgelen);
  166. double md = cfg.max_pillar_link_distance_mm / std::cos(-cfg.bridge_slope);
  167. REQUIRE(max_bridgelen <= md);
  168. }
  169. void test_pad(const std::string &obj_filename, const sla::PadConfig &padcfg, PadByproducts &out)
  170. {
  171. REQUIRE(padcfg.validate().empty());
  172. TriangleMesh mesh = load_model(obj_filename);
  173. REQUIRE_FALSE(mesh.empty());
  174. // Create pad skeleton only from the model
  175. Slic3r::sla::pad_blueprint(mesh, out.model_contours);
  176. test_concave_hull(out.model_contours);
  177. REQUIRE_FALSE(out.model_contours.empty());
  178. // Create the pad geometry for the model contours only
  179. Slic3r::sla::create_pad({}, out.model_contours, out.mesh, padcfg);
  180. check_validity(out.mesh);
  181. auto bb = out.mesh.bounding_box();
  182. REQUIRE(bb.max.z() - bb.min.z() == Approx(padcfg.full_height()));
  183. }
  184. static void _test_concave_hull(const Polygons &hull, const ExPolygons &polys)
  185. {
  186. REQUIRE(polys.size() >=hull.size());
  187. double polys_area = 0;
  188. for (const ExPolygon &p : polys) polys_area += p.area();
  189. double cchull_area = 0;
  190. for (const Slic3r::Polygon &p : hull) cchull_area += p.area();
  191. REQUIRE(cchull_area >= Approx(polys_area));
  192. size_t cchull_holes = 0;
  193. for (const Slic3r::Polygon &p : hull)
  194. cchull_holes += p.is_clockwise() ? 1 : 0;
  195. REQUIRE(cchull_holes == 0);
  196. Polygons intr = diff(to_polygons(polys), hull);
  197. REQUIRE(intr.empty());
  198. }
  199. void test_concave_hull(const ExPolygons &polys) {
  200. sla::PadConfig pcfg;
  201. Slic3r::sla::ConcaveHull cchull{polys, pcfg.max_merge_dist_mm, []{}};
  202. _test_concave_hull(cchull.polygons(), polys);
  203. coord_t delta = scaled(pcfg.brim_size_mm + pcfg.wing_distance());
  204. ExPolygons wafflex = sla::offset_waffle_style_ex(cchull, delta);
  205. Polygons waffl = sla::offset_waffle_style(cchull, delta);
  206. _test_concave_hull(to_polygons(wafflex), polys);
  207. _test_concave_hull(waffl, polys);
  208. }
  209. void check_validity(const TriangleMesh &input_mesh, int flags)
  210. {
  211. TriangleMesh mesh{input_mesh};
  212. if (flags & ASSUME_NO_EMPTY) {
  213. REQUIRE_FALSE(mesh.empty());
  214. } else if (mesh.empty())
  215. return; // If it can be empty and it is, there is nothing left to do.
  216. REQUIRE(stl_validate(&mesh.stl));
  217. bool do_update_shared_vertices = false;
  218. mesh.repair(do_update_shared_vertices);
  219. if (flags & ASSUME_NO_REPAIR) {
  220. REQUIRE_FALSE(mesh.needed_repair());
  221. }
  222. if (flags & ASSUME_MANIFOLD) {
  223. mesh.require_shared_vertices();
  224. if (!mesh.is_manifold()) mesh.WriteOBJFile("non_manifold.obj");
  225. REQUIRE(mesh.is_manifold());
  226. }
  227. }
  228. void check_raster_transformations(sla::RasterBase::Orientation o, sla::RasterBase::TMirroring mirroring)
  229. {
  230. double disp_w = 120., disp_h = 68.;
  231. sla::RasterBase::Resolution res{2560, 1440};
  232. sla::RasterBase::PixelDim pixdim{disp_w / res.width_px, disp_h / res.height_px};
  233. auto bb = BoundingBox({0, 0}, {scaled(disp_w), scaled(disp_h)});
  234. sla::RasterBase::Trafo trafo{o, mirroring};
  235. trafo.center_x = bb.center().x();
  236. trafo.center_y = bb.center().y();
  237. double gamma = 1.;
  238. sla::RasterGrayscaleAAGammaPower raster{res, pixdim, trafo, gamma};
  239. // create box of size 32x32 pixels (not 1x1 to avoid antialiasing errors)
  240. coord_t pw = 32 * coord_t(std::ceil(scaled<double>(pixdim.w_mm)));
  241. coord_t ph = 32 * coord_t(std::ceil(scaled<double>(pixdim.h_mm)));
  242. ExPolygon box;
  243. box.contour.points = {{-pw, -ph}, {pw, -ph}, {pw, ph}, {-pw, ph}};
  244. double tr_x = scaled<double>(20.), tr_y = tr_x;
  245. box.translate(tr_x, tr_y);
  246. ExPolygon expected_box = box;
  247. // Now calculate the position of the translated box according to output
  248. // trafo.
  249. if (o == sla::RasterBase::Orientation::roPortrait) expected_box.rotate(PI / 2.);
  250. if (mirroring[X])
  251. for (auto &p : expected_box.contour.points) p.x() = -p.x();
  252. if (mirroring[Y])
  253. for (auto &p : expected_box.contour.points) p.y() = -p.y();
  254. raster.draw(box);
  255. Point expected_coords = expected_box.contour.bounding_box().center();
  256. double rx = unscaled(expected_coords.x() + bb.center().x()) / pixdim.w_mm;
  257. double ry = unscaled(expected_coords.y() + bb.center().y()) / pixdim.h_mm;
  258. auto w = size_t(std::floor(rx));
  259. auto h = res.height_px - size_t(std::floor(ry));
  260. REQUIRE((w < res.width_px && h < res.height_px));
  261. auto px = raster.read_pixel(w, h);
  262. if (px != FullWhite) {
  263. std::fstream outf("out.png", std::ios::out);
  264. outf << raster.encode(sla::PNGRasterEncoder());
  265. }
  266. REQUIRE(px == FullWhite);
  267. }
  268. ExPolygon square_with_hole(double v)
  269. {
  270. ExPolygon poly;
  271. coord_t V = scaled(v / 2.);
  272. poly.contour.points = {{-V, -V}, {V, -V}, {V, V}, {-V, V}};
  273. poly.holes.emplace_back();
  274. V = V / 2;
  275. poly.holes.front().points = {{-V, V}, {V, V}, {V, -V}, {-V, -V}};
  276. return poly;
  277. }
  278. long raster_pxsum(const sla::RasterGrayscaleAA &raster)
  279. {
  280. auto res = raster.resolution();
  281. long a = 0;
  282. for (size_t x = 0; x < res.width_px; ++x)
  283. for (size_t y = 0; y < res.height_px; ++y)
  284. a += raster.read_pixel(x, y);
  285. return a;
  286. }
  287. double raster_white_area(const sla::RasterGrayscaleAA &raster)
  288. {
  289. if (raster.resolution().pixels() == 0) return std::nan("");
  290. auto res = raster.resolution();
  291. double a = 0;
  292. for (size_t x = 0; x < res.width_px; ++x)
  293. for (size_t y = 0; y < res.height_px; ++y) {
  294. auto px = raster.read_pixel(x, y);
  295. a += pixel_area(px, raster.pixel_dimensions());
  296. }
  297. return a;
  298. }
  299. double predict_error(const ExPolygon &p, const sla::RasterBase::PixelDim &pd)
  300. {
  301. auto lines = p.lines();
  302. double pix_err = pixel_area(FullWhite, pd) / 2.;
  303. // Worst case is when a line is parallel to the shorter axis of one pixel,
  304. // when the line will be composed of the max number of pixels
  305. double pix_l = std::min(pd.h_mm, pd.w_mm);
  306. double error = 0.;
  307. for (auto &l : lines)
  308. error += (unscaled(l.length()) / pix_l) * pix_err;
  309. return error;
  310. }
  311. // Make a 3D pyramid
  312. TriangleMesh make_pyramid(float base, float height)
  313. {
  314. float a = base / 2.f;
  315. TriangleMesh mesh(
  316. {
  317. {-a, -a, 0}, {a, -a, 0}, {a, a, 0},
  318. {-a, a, 0}, {0.f, 0.f, height}
  319. },
  320. {
  321. {0, 1, 2},
  322. {0, 2, 3},
  323. {0, 1, 4},
  324. {1, 2, 4},
  325. {2, 3, 4},
  326. {3, 0, 4}
  327. });
  328. mesh.repair();
  329. return mesh;
  330. }
  331. TriangleMesh make_prism(double width, double length, double height)
  332. {
  333. // We need two upward facing triangles
  334. double x = width / 2., y = length / 2.;
  335. TriangleMesh mesh(
  336. {
  337. {-x, -y, 0.}, {x, -y, 0.}, {0., -y, height},
  338. {-x, y, 0.}, {x, y, 0.}, {0., y, height},
  339. },
  340. {
  341. {0, 1, 2}, // side 1
  342. {4, 3, 5}, // side 2
  343. {1, 4, 2}, {2, 4, 5}, // roof 1
  344. {0, 2, 5}, {0, 5, 3}, // roof 2
  345. {3, 4, 1}, {3, 1, 0} // bottom
  346. });
  347. return mesh;
  348. }
  349. sla::SupportPoints calc_support_pts(
  350. const TriangleMesh & mesh,
  351. const sla::SupportPointGenerator::Config &cfg)
  352. {
  353. // Prepare the slice grid and the slices
  354. std::vector<ExPolygons> slices;
  355. auto bb = cast<float>(mesh.bounding_box());
  356. std::vector<float> heights = grid(bb.min.z(), bb.max.z(), 0.1f);
  357. slice_mesh(mesh, heights, slices, CLOSING_RADIUS, [] {});
  358. // Prepare the support point calculator
  359. sla::IndexedMesh emesh{mesh};
  360. sla::SupportPointGenerator spgen{emesh, cfg, []{}, [](int){}};
  361. // Calculate the support points
  362. spgen.seed(0);
  363. spgen.execute(slices, heights);
  364. return spgen.output();
  365. }