sla_test_utils.cpp 15 KB

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