sla_test_utils.cpp 16 KB

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