sla_test_utils.cpp 14 KB

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