PerimeterGenerator.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. #include "PerimeterGenerator.hpp"
  2. #include "ClipperUtils.hpp"
  3. #include "ExtrusionEntityCollection.hpp"
  4. #include "ShortestPath.hpp"
  5. #include "clipper/clipper_z.hpp"
  6. #include "Arachne/WallToolPaths.hpp"
  7. #include "Arachne/utils/ExtrusionLine.hpp"
  8. #include <cmath>
  9. #include <cassert>
  10. #include <stack>
  11. #include <unordered_map>
  12. namespace Slic3r {
  13. ExtrusionPaths thick_polyline_to_extrusion_paths(const ThickPolyline &thick_polyline, ExtrusionRole role, const Flow &flow, const float tolerance, const float merge_tolerance)
  14. {
  15. ExtrusionPaths paths;
  16. ExtrusionPath path(role);
  17. ThickLines lines = thick_polyline.thicklines();
  18. for (int i = 0; i < (int)lines.size(); ++i) {
  19. const ThickLine& line = lines[i];
  20. assert(line.a_width >= SCALED_EPSILON && line.b_width >= SCALED_EPSILON);
  21. const coordf_t line_len = line.length();
  22. if (line_len < SCALED_EPSILON) {
  23. // The line is so tiny that we don't care about its width when we connect it to another line.
  24. if (!path.empty())
  25. path.polyline.points.back() = line.b; // If the variable path is non-empty, connect this tiny line to it.
  26. else if (i + 1 < (int)lines.size()) // If there is at least one following line, connect this tiny line to it.
  27. lines[i + 1].a = line.a;
  28. else if (!paths.empty())
  29. paths.back().polyline.points.back() = line.b; // Connect this tiny line to the last finished path.
  30. // If any of the above isn't satisfied, then remove this tiny line.
  31. continue;
  32. }
  33. double thickness_delta = fabs(line.a_width - line.b_width);
  34. if (thickness_delta > tolerance) {
  35. const auto segments = (unsigned int)ceil(thickness_delta / tolerance);
  36. const coordf_t seg_len = line_len / segments;
  37. Points pp;
  38. std::vector<coordf_t> width;
  39. {
  40. pp.push_back(line.a);
  41. width.push_back(line.a_width);
  42. for (size_t j = 1; j < segments; ++j) {
  43. pp.push_back((line.a.cast<double>() + (line.b - line.a).cast<double>().normalized() * (j * seg_len)).cast<coord_t>());
  44. coordf_t w = line.a_width + (j*seg_len) * (line.b_width-line.a_width) / line_len;
  45. width.push_back(w);
  46. width.push_back(w);
  47. }
  48. pp.push_back(line.b);
  49. width.push_back(line.b_width);
  50. assert(pp.size() == segments + 1u);
  51. assert(width.size() == segments*2);
  52. }
  53. // delete this line and insert new ones
  54. lines.erase(lines.begin() + i);
  55. for (size_t j = 0; j < segments; ++j) {
  56. ThickLine new_line(pp[j], pp[j+1]);
  57. new_line.a_width = width[2*j];
  58. new_line.b_width = width[2*j+1];
  59. lines.insert(lines.begin() + i + j, new_line);
  60. }
  61. -- i;
  62. continue;
  63. }
  64. const double w = fmax(line.a_width, line.b_width);
  65. const Flow new_flow = (role == erOverhangPerimeter && flow.bridge()) ? flow : flow.with_width(unscale<float>(w) + flow.height() * float(1. - 0.25 * PI));
  66. if (path.polyline.points.empty()) {
  67. path.polyline.append(line.a);
  68. path.polyline.append(line.b);
  69. // Convert from spacing to extrusion width based on the extrusion model
  70. // of a square extrusion ended with semi circles.
  71. #ifdef SLIC3R_DEBUG
  72. printf(" filling %f gap\n", flow.width);
  73. #endif
  74. path.mm3_per_mm = new_flow.mm3_per_mm();
  75. path.width = new_flow.width();
  76. path.height = new_flow.height();
  77. } else {
  78. assert(path.width >= EPSILON);
  79. thickness_delta = scaled<double>(fabs(path.width - new_flow.width()));
  80. if (thickness_delta <= merge_tolerance) {
  81. // the width difference between this line and the current flow
  82. // (of the previous line) width is within the accepted tolerance
  83. path.polyline.append(line.b);
  84. } else {
  85. // we need to initialize a new line
  86. paths.emplace_back(std::move(path));
  87. path = ExtrusionPath(role);
  88. -- i;
  89. }
  90. }
  91. }
  92. if (path.polyline.is_valid())
  93. paths.emplace_back(std::move(path));
  94. return paths;
  95. }
  96. static void variable_width(const ThickPolylines& polylines, ExtrusionRole role, const Flow &flow, std::vector<ExtrusionEntity*> &out)
  97. {
  98. // This value determines granularity of adaptive width, as G-code does not allow
  99. // variable extrusion within a single move; this value shall only affect the amount
  100. // of segments, and any pruning shall be performed before we apply this tolerance.
  101. const auto tolerance = float(scale_(0.05));
  102. for (const ThickPolyline &p : polylines) {
  103. ExtrusionPaths paths = thick_polyline_to_extrusion_paths(p, role, flow, tolerance, tolerance);
  104. // Append paths to collection.
  105. if (!paths.empty()) {
  106. for (auto it = std::next(paths.begin()); it != paths.end(); ++it) {
  107. assert(it->polyline.points.size() >= 2);
  108. assert(std::prev(it)->polyline.last_point() == it->polyline.first_point());
  109. }
  110. if (paths.front().first_point() == paths.back().last_point()) {
  111. out.emplace_back(new ExtrusionLoop(std::move(paths)));
  112. } else {
  113. for (ExtrusionPath &path : paths)
  114. out.emplace_back(new ExtrusionPath(std::move(path)));
  115. }
  116. }
  117. }
  118. }
  119. // Hierarchy of perimeters.
  120. class PerimeterGeneratorLoop {
  121. public:
  122. // Polygon of this contour.
  123. Polygon polygon;
  124. // Is it a contour or a hole?
  125. // Contours are CCW oriented, holes are CW oriented.
  126. bool is_contour;
  127. // Depth in the hierarchy. External perimeter has depth = 0. An external perimeter could be both a contour and a hole.
  128. unsigned short depth;
  129. // Should this contur be fuzzyfied on path generation?
  130. bool fuzzify;
  131. // Children contour, may be both CCW and CW oriented (outer contours or holes).
  132. std::vector<PerimeterGeneratorLoop> children;
  133. PerimeterGeneratorLoop(const Polygon &polygon, unsigned short depth, bool is_contour, bool fuzzify) :
  134. polygon(polygon), is_contour(is_contour), depth(depth), fuzzify(fuzzify) {}
  135. // External perimeter. It may be CCW or CW oriented (outer contour or hole contour).
  136. bool is_external() const { return this->depth == 0; }
  137. // An island, which may have holes, but it does not have another internal island.
  138. bool is_internal_contour() const;
  139. };
  140. // Thanks Cura developers for this function.
  141. static void fuzzy_polygon(Polygon &poly, double fuzzy_skin_thickness, double fuzzy_skin_point_dist)
  142. {
  143. const double min_dist_between_points = fuzzy_skin_point_dist * 3. / 4.; // hardcoded: the point distance may vary between 3/4 and 5/4 the supplied value
  144. const double range_random_point_dist = fuzzy_skin_point_dist / 2.;
  145. double dist_left_over = double(rand()) * (min_dist_between_points / 2) / double(RAND_MAX); // the distance to be traversed on the line before making the first new point
  146. Point* p0 = &poly.points.back();
  147. Points out;
  148. out.reserve(poly.points.size());
  149. for (Point &p1 : poly.points)
  150. { // 'a' is the (next) new point between p0 and p1
  151. Vec2d p0p1 = (p1 - *p0).cast<double>();
  152. double p0p1_size = p0p1.norm();
  153. // so that p0p1_size - dist_last_point evaulates to dist_left_over - p0p1_size
  154. double dist_last_point = dist_left_over + p0p1_size * 2.;
  155. for (double p0pa_dist = dist_left_over; p0pa_dist < p0p1_size;
  156. p0pa_dist += min_dist_between_points + double(rand()) * range_random_point_dist / double(RAND_MAX))
  157. {
  158. double r = double(rand()) * (fuzzy_skin_thickness * 2.) / double(RAND_MAX) - fuzzy_skin_thickness;
  159. out.emplace_back(*p0 + (p0p1 * (p0pa_dist / p0p1_size) + perp(p0p1).cast<double>().normalized() * r).cast<coord_t>());
  160. dist_last_point = p0pa_dist;
  161. }
  162. dist_left_over = p0p1_size - dist_last_point;
  163. p0 = &p1;
  164. }
  165. while (out.size() < 3) {
  166. size_t point_idx = poly.size() - 2;
  167. out.emplace_back(poly[point_idx]);
  168. if (point_idx == 0)
  169. break;
  170. -- point_idx;
  171. }
  172. if (out.size() >= 3)
  173. poly.points = std::move(out);
  174. }
  175. // Thanks Cura developers for this function.
  176. static void fuzzy_extrusion_line(Arachne::ExtrusionLine &ext_lines, double fuzzy_skin_thickness, double fuzzy_skin_point_dist)
  177. {
  178. const double min_dist_between_points = fuzzy_skin_point_dist * 3. / 4.; // hardcoded: the point distance may vary between 3/4 and 5/4 the supplied value
  179. const double range_random_point_dist = fuzzy_skin_point_dist / 2.;
  180. double dist_left_over = double(rand()) * (min_dist_between_points / 2) / double(RAND_MAX); // the distance to be traversed on the line before making the first new point
  181. auto *p0 = &ext_lines.front();
  182. std::vector<Arachne::ExtrusionJunction> out;
  183. out.reserve(ext_lines.size());
  184. for (auto &p1 : ext_lines) {
  185. if (p0->p == p1.p) { // Connect endpoints.
  186. out.emplace_back(p1.p, p1.w, p1.perimeter_index);
  187. continue;
  188. }
  189. // 'a' is the (next) new point between p0 and p1
  190. Vec2d p0p1 = (p1.p - p0->p).cast<double>();
  191. double p0p1_size = p0p1.norm();
  192. // so that p0p1_size - dist_last_point evaulates to dist_left_over - p0p1_size
  193. double dist_last_point = dist_left_over + p0p1_size * 2.;
  194. for (double p0pa_dist = dist_left_over; p0pa_dist < p0p1_size; p0pa_dist += min_dist_between_points + double(rand()) * range_random_point_dist / double(RAND_MAX)) {
  195. double r = double(rand()) * (fuzzy_skin_thickness * 2.) / double(RAND_MAX) - fuzzy_skin_thickness;
  196. out.emplace_back(p0->p + (p0p1 * (p0pa_dist / p0p1_size) + perp(p0p1).cast<double>().normalized() * r).cast<coord_t>(), p1.w, p1.perimeter_index);
  197. dist_last_point = p0pa_dist;
  198. }
  199. dist_left_over = p0p1_size - dist_last_point;
  200. p0 = &p1;
  201. }
  202. while (out.size() < 3) {
  203. size_t point_idx = ext_lines.size() - 2;
  204. out.emplace_back(ext_lines[point_idx].p, ext_lines[point_idx].w, ext_lines[point_idx].perimeter_index);
  205. if (point_idx == 0)
  206. break;
  207. -- point_idx;
  208. }
  209. if (ext_lines.back().p == ext_lines.front().p) // Connect endpoints.
  210. out.back().p = out.front().p;
  211. if (out.size() >= 3)
  212. ext_lines.junctions = std::move(out);
  213. }
  214. using PerimeterGeneratorLoops = std::vector<PerimeterGeneratorLoop>;
  215. static ExtrusionEntityCollection traverse_loops(const PerimeterGenerator &perimeter_generator, const PerimeterGeneratorLoops &loops, ThickPolylines &thin_walls)
  216. {
  217. // loops is an arrayref of ::Loop objects
  218. // turn each one into an ExtrusionLoop object
  219. ExtrusionEntityCollection coll;
  220. Polygon fuzzified;
  221. for (const PerimeterGeneratorLoop &loop : loops) {
  222. bool is_external = loop.is_external();
  223. ExtrusionRole role;
  224. ExtrusionLoopRole loop_role;
  225. role = is_external ? erExternalPerimeter : erPerimeter;
  226. if (loop.is_internal_contour()) {
  227. // Note that we set loop role to ContourInternalPerimeter
  228. // also when loop is both internal and external (i.e.
  229. // there's only one contour loop).
  230. loop_role = elrContourInternalPerimeter;
  231. } else {
  232. loop_role = elrDefault;
  233. }
  234. // detect overhanging/bridging perimeters
  235. ExtrusionPaths paths;
  236. const Polygon &polygon = loop.fuzzify ? fuzzified : loop.polygon;
  237. if (loop.fuzzify) {
  238. fuzzified = loop.polygon;
  239. fuzzy_polygon(fuzzified, scaled<float>(perimeter_generator.config->fuzzy_skin_thickness.value), scaled<float>(perimeter_generator.config->fuzzy_skin_point_dist.value));
  240. }
  241. if (perimeter_generator.config->overhangs && perimeter_generator.layer_id > perimeter_generator.object_config->raft_layers
  242. && ! ((perimeter_generator.object_config->support_material || perimeter_generator.object_config->support_material_enforce_layers > 0) &&
  243. perimeter_generator.object_config->support_material_contact_distance.value == 0)) {
  244. // get non-overhang paths by intersecting this loop with the grown lower slices
  245. extrusion_paths_append(
  246. paths,
  247. intersection_pl({ polygon }, perimeter_generator.lower_slices_polygons()),
  248. role,
  249. is_external ? perimeter_generator.ext_mm3_per_mm() : perimeter_generator.mm3_per_mm(),
  250. is_external ? perimeter_generator.ext_perimeter_flow.width() : perimeter_generator.perimeter_flow.width(),
  251. (float)perimeter_generator.layer_height);
  252. // get overhang paths by checking what parts of this loop fall
  253. // outside the grown lower slices (thus where the distance between
  254. // the loop centerline and original lower slices is >= half nozzle diameter
  255. extrusion_paths_append(
  256. paths,
  257. diff_pl({ polygon }, perimeter_generator.lower_slices_polygons()),
  258. erOverhangPerimeter,
  259. perimeter_generator.mm3_per_mm_overhang(),
  260. perimeter_generator.overhang_flow.width(),
  261. perimeter_generator.overhang_flow.height());
  262. // Reapply the nearest point search for starting point.
  263. // We allow polyline reversal because Clipper may have randomly reversed polylines during clipping.
  264. chain_and_reorder_extrusion_paths(paths, &paths.front().first_point());
  265. } else {
  266. ExtrusionPath path(role);
  267. path.polyline = polygon.split_at_first_point();
  268. path.mm3_per_mm = is_external ? perimeter_generator.ext_mm3_per_mm() : perimeter_generator.mm3_per_mm();
  269. path.width = is_external ? perimeter_generator.ext_perimeter_flow.width() : perimeter_generator.perimeter_flow.width();
  270. path.height = (float)perimeter_generator.layer_height;
  271. paths.push_back(path);
  272. }
  273. coll.append(ExtrusionLoop(std::move(paths), loop_role));
  274. }
  275. // Append thin walls to the nearest-neighbor search (only for first iteration)
  276. if (! thin_walls.empty()) {
  277. variable_width(thin_walls, erExternalPerimeter, perimeter_generator.ext_perimeter_flow, coll.entities);
  278. thin_walls.clear();
  279. }
  280. // Traverse children and build the final collection.
  281. Point zero_point(0, 0);
  282. std::vector<std::pair<size_t, bool>> chain = chain_extrusion_entities(coll.entities, &zero_point);
  283. ExtrusionEntityCollection out;
  284. for (const std::pair<size_t, bool> &idx : chain) {
  285. assert(coll.entities[idx.first] != nullptr);
  286. if (idx.first >= loops.size()) {
  287. // This is a thin wall.
  288. out.entities.reserve(out.entities.size() + 1);
  289. out.entities.emplace_back(coll.entities[idx.first]);
  290. coll.entities[idx.first] = nullptr;
  291. if (idx.second)
  292. out.entities.back()->reverse();
  293. } else {
  294. const PerimeterGeneratorLoop &loop = loops[idx.first];
  295. assert(thin_walls.empty());
  296. ExtrusionEntityCollection children = traverse_loops(perimeter_generator, loop.children, thin_walls);
  297. out.entities.reserve(out.entities.size() + children.entities.size() + 1);
  298. ExtrusionLoop *eloop = static_cast<ExtrusionLoop*>(coll.entities[idx.first]);
  299. coll.entities[idx.first] = nullptr;
  300. if (loop.is_contour) {
  301. eloop->make_counter_clockwise();
  302. out.append(std::move(children.entities));
  303. out.entities.emplace_back(eloop);
  304. } else {
  305. eloop->make_clockwise();
  306. out.entities.emplace_back(eloop);
  307. out.append(std::move(children.entities));
  308. }
  309. }
  310. }
  311. return out;
  312. }
  313. static ClipperLib_Z::Paths clip_extrusion(const ClipperLib_Z::Path &subject, const ClipperLib_Z::Paths &clip, ClipperLib_Z::ClipType clipType)
  314. {
  315. ClipperLib_Z::Clipper clipper;
  316. clipper.ZFillFunction([](const ClipperLib_Z::IntPoint &e1bot, const ClipperLib_Z::IntPoint &e1top, const ClipperLib_Z::IntPoint &e2bot,
  317. const ClipperLib_Z::IntPoint &e2top, ClipperLib_Z::IntPoint &pt) {
  318. ClipperLib_Z::IntPoint start = e1bot;
  319. ClipperLib_Z::IntPoint end = e1top;
  320. if (start.z() <= 0 && end.z() <= 0) {
  321. start = e2bot;
  322. end = e2top;
  323. }
  324. assert(start.z() > 0 && end.z() > 0);
  325. // Interpolate extrusion line width.
  326. double length_sqr = (end - start).cast<double>().squaredNorm();
  327. double dist_sqr = (pt - start).cast<double>().squaredNorm();
  328. double t = std::sqrt(dist_sqr / length_sqr);
  329. pt.z() = start.z() + coord_t((end.z() - start.z()) * t);
  330. });
  331. clipper.AddPath(subject, ClipperLib_Z::ptSubject, false);
  332. clipper.AddPaths(clip, ClipperLib_Z::ptClip, true);
  333. ClipperLib_Z::PolyTree clipped_polytree;
  334. ClipperLib_Z::Paths clipped_paths;
  335. clipper.Execute(clipType, clipped_polytree, ClipperLib_Z::pftNonZero, ClipperLib_Z::pftNonZero);
  336. ClipperLib_Z::PolyTreeToPaths(clipped_polytree, clipped_paths);
  337. // Clipped path could contain vertices from the clip with a Z coordinate equal to zero.
  338. // For those vertices, we must assign value based on the subject.
  339. // This happens only in sporadic cases.
  340. for (ClipperLib_Z::Path &path : clipped_paths)
  341. for (ClipperLib_Z::IntPoint &c_pt : path)
  342. if (c_pt.z() == 0) {
  343. // Now we must find the corresponding line on with this point is located and compute line width (Z coordinate).
  344. if (subject.size() <= 2)
  345. continue;
  346. const Point pt(c_pt.x(), c_pt.y());
  347. Point projected_pt_min;
  348. auto it_min = subject.begin();
  349. auto dist_sqr_min = std::numeric_limits<double>::max();
  350. Point prev(subject.front().x(), subject.front().y());
  351. for (auto it = std::next(subject.begin()); it != subject.end(); ++it) {
  352. Point curr(it->x(), it->y());
  353. Point projected_pt = pt.projection_onto(Line(prev, curr));
  354. if (double dist_sqr = (projected_pt - pt).cast<double>().squaredNorm(); dist_sqr < dist_sqr_min) {
  355. dist_sqr_min = dist_sqr;
  356. projected_pt_min = projected_pt;
  357. it_min = std::prev(it);
  358. }
  359. prev = curr;
  360. }
  361. assert(dist_sqr_min <= SCALED_EPSILON);
  362. assert(std::next(it_min) != subject.end());
  363. const Point pt_a(it_min->x(), it_min->y());
  364. const Point pt_b(std::next(it_min)->x(), std::next(it_min)->y());
  365. const double line_len = (pt_b - pt_a).cast<double>().norm();
  366. const double dist = (projected_pt_min - pt_a).cast<double>().norm();
  367. c_pt.z() = coord_t(double(it_min->z()) + (dist / line_len) * double(std::next(it_min)->z() - it_min->z()));
  368. }
  369. assert([&clipped_paths = std::as_const(clipped_paths)]() -> bool {
  370. for (const ClipperLib_Z::Path &path : clipped_paths)
  371. for (const ClipperLib_Z::IntPoint &pt : path)
  372. if (pt.z() <= 0)
  373. return false;
  374. return true;
  375. }());
  376. return clipped_paths;
  377. }
  378. struct PerimeterGeneratorArachneExtrusion
  379. {
  380. Arachne::ExtrusionLine *extrusion = nullptr;
  381. // Indicates if closed ExtrusionLine is a contour or a hole. Used it only when ExtrusionLine is a closed loop.
  382. bool is_contour = false;
  383. // Should this extrusion be fuzzyfied on path generation?
  384. bool fuzzify = false;
  385. };
  386. static ExtrusionEntityCollection traverse_extrusions(const PerimeterGenerator &perimeter_generator, std::vector<PerimeterGeneratorArachneExtrusion> &pg_extrusions)
  387. {
  388. ExtrusionEntityCollection extrusion_coll;
  389. for (PerimeterGeneratorArachneExtrusion &pg_extrusion : pg_extrusions) {
  390. Arachne::ExtrusionLine *extrusion = pg_extrusion.extrusion;
  391. if (extrusion->empty())
  392. continue;
  393. const bool is_external = extrusion->inset_idx == 0;
  394. ExtrusionRole role = is_external ? erExternalPerimeter : erPerimeter;
  395. if (pg_extrusion.fuzzify)
  396. fuzzy_extrusion_line(*extrusion, scaled<float>(perimeter_generator.config->fuzzy_skin_thickness.value), scaled<float>(perimeter_generator.config->fuzzy_skin_point_dist.value));
  397. ExtrusionPaths paths;
  398. // detect overhanging/bridging perimeters
  399. if (perimeter_generator.config->overhangs && perimeter_generator.layer_id > perimeter_generator.object_config->raft_layers
  400. && ! ((perimeter_generator.object_config->support_material || perimeter_generator.object_config->support_material_enforce_layers > 0) &&
  401. perimeter_generator.object_config->support_material_contact_distance.value == 0)) {
  402. ClipperLib_Z::Path extrusion_path;
  403. extrusion_path.reserve(extrusion->size());
  404. for (const Arachne::ExtrusionJunction &ej : extrusion->junctions)
  405. extrusion_path.emplace_back(ej.p.x(), ej.p.y(), ej.w);
  406. ClipperLib_Z::Paths lower_slices_paths;
  407. lower_slices_paths.reserve(perimeter_generator.lower_slices_polygons().size());
  408. for (const Polygon &poly : perimeter_generator.lower_slices_polygons()) {
  409. lower_slices_paths.emplace_back();
  410. ClipperLib_Z::Path &out = lower_slices_paths.back();
  411. out.reserve(poly.points.size());
  412. for (const Point &pt : poly.points)
  413. out.emplace_back(pt.x(), pt.y(), 0);
  414. }
  415. // get non-overhang paths by intersecting this loop with the grown lower slices
  416. extrusion_paths_append(paths, clip_extrusion(extrusion_path, lower_slices_paths, ClipperLib_Z::ctIntersection), role,
  417. is_external ? perimeter_generator.ext_perimeter_flow : perimeter_generator.perimeter_flow);
  418. // get overhang paths by checking what parts of this loop fall
  419. // outside the grown lower slices (thus where the distance between
  420. // the loop centerline and original lower slices is >= half nozzle diameter
  421. extrusion_paths_append(paths, clip_extrusion(extrusion_path, lower_slices_paths, ClipperLib_Z::ctDifference), erOverhangPerimeter,
  422. perimeter_generator.overhang_flow);
  423. // Reapply the nearest point search for starting point.
  424. // We allow polyline reversal because Clipper may have randomly reversed polylines during clipping.
  425. // Arachne sometimes creates extrusion with zero-length (just two same endpoints);
  426. if (!paths.empty()) {
  427. Point start_point = paths.front().first_point();
  428. if (!extrusion->is_closed) {
  429. // Especially for open extrusion, we need to select a starting point that is at the start
  430. // or the end of the extrusions to make one continuous line. Also, we prefer a non-overhang
  431. // starting point.
  432. struct PointInfo
  433. {
  434. size_t occurrence = 0;
  435. bool is_overhang = false;
  436. };
  437. std::unordered_map<Point, PointInfo, PointHash> point_occurrence;
  438. for (const ExtrusionPath &path : paths) {
  439. ++point_occurrence[path.polyline.first_point()].occurrence;
  440. ++point_occurrence[path.polyline.last_point()].occurrence;
  441. if (path.role() == erOverhangPerimeter) {
  442. point_occurrence[path.polyline.first_point()].is_overhang = true;
  443. point_occurrence[path.polyline.last_point()].is_overhang = true;
  444. }
  445. }
  446. // Prefer non-overhang point as a starting point.
  447. for (const std::pair<Point, PointInfo> pt : point_occurrence)
  448. if (pt.second.occurrence == 1) {
  449. start_point = pt.first;
  450. if (!pt.second.is_overhang) {
  451. start_point = pt.first;
  452. break;
  453. }
  454. }
  455. }
  456. chain_and_reorder_extrusion_paths(paths, &start_point);
  457. }
  458. } else {
  459. extrusion_paths_append(paths, *extrusion, role, is_external ? perimeter_generator.ext_perimeter_flow : perimeter_generator.perimeter_flow);
  460. }
  461. // Append paths to collection.
  462. if (!paths.empty()) {
  463. if (extrusion->is_closed) {
  464. ExtrusionLoop extrusion_loop(std::move(paths));
  465. // Restore the orientation of the extrusion loop.
  466. if (pg_extrusion.is_contour)
  467. extrusion_loop.make_counter_clockwise();
  468. else
  469. extrusion_loop.make_clockwise();
  470. extrusion_coll.append(std::move(extrusion_loop));
  471. } else
  472. for (ExtrusionPath &path : paths)
  473. extrusion_coll.append(ExtrusionPath(std::move(path)));
  474. }
  475. }
  476. return extrusion_coll;
  477. }
  478. // Thanks, Cura developers, for implementing an algorithm for generating perimeters with variable width (Arachne) that is based on the paper
  479. // "A framework for adaptive width control of dense contour-parallel toolpaths in fused deposition modeling"
  480. void PerimeterGenerator::process_arachne()
  481. {
  482. // other perimeters
  483. m_mm3_per_mm = this->perimeter_flow.mm3_per_mm();
  484. coord_t perimeter_spacing = this->perimeter_flow.scaled_spacing();
  485. // external perimeters
  486. m_ext_mm3_per_mm = this->ext_perimeter_flow.mm3_per_mm();
  487. coord_t ext_perimeter_width = this->ext_perimeter_flow.scaled_width();
  488. coord_t ext_perimeter_spacing = this->ext_perimeter_flow.scaled_spacing();
  489. coord_t ext_perimeter_spacing2 = scaled<coord_t>(0.5f * (this->ext_perimeter_flow.spacing() + this->perimeter_flow.spacing()));
  490. // overhang perimeters
  491. m_mm3_per_mm_overhang = this->overhang_flow.mm3_per_mm();
  492. // solid infill
  493. coord_t solid_infill_spacing = this->solid_infill_flow.scaled_spacing();
  494. // prepare grown lower layer slices for overhang detection
  495. if (this->lower_slices != nullptr && this->config->overhangs) {
  496. // We consider overhang any part where the entire nozzle diameter is not supported by the
  497. // lower layer, so we take lower slices and offset them by half the nozzle diameter used
  498. // in the current layer
  499. double nozzle_diameter = this->print_config->nozzle_diameter.get_at(this->config->perimeter_extruder-1);
  500. m_lower_slices_polygons = offset(*this->lower_slices, float(scale_(+nozzle_diameter/2)));
  501. }
  502. // we need to process each island separately because we might have different
  503. // extra perimeters for each one
  504. for (const Surface &surface : this->slices->surfaces) {
  505. // detect how many perimeters must be generated for this island
  506. int loop_number = this->config->perimeters + surface.extra_perimeters - 1; // 0-indexed loops
  507. ExPolygons last = offset_ex(surface.expolygon.simplify_p(m_scaled_resolution), - float(ext_perimeter_width / 2. - ext_perimeter_spacing / 2.));
  508. Polygons last_p = to_polygons(last);
  509. Arachne::WallToolPaths wallToolPaths(last_p, ext_perimeter_spacing, perimeter_spacing, coord_t(loop_number + 1), 0, *this->object_config, *this->print_config);
  510. std::vector<Arachne::VariableWidthLines> perimeters = wallToolPaths.getToolPaths();
  511. loop_number = int(perimeters.size()) - 1;
  512. // All closed ExtrusionLine should have the same the first and the last point.
  513. // But in rare cases, Arachne produce ExtrusionLine marked as closed but without
  514. // equal the first and the last point.
  515. assert([&perimeters = std::as_const(perimeters)]() -> bool {
  516. for (const Arachne::VariableWidthLines &perimeter : perimeters)
  517. for (const Arachne::ExtrusionLine &el : perimeter)
  518. if (el.is_closed && el.junctions.front().p != el.junctions.back().p)
  519. return false;
  520. return true;
  521. }());
  522. int start_perimeter = int(perimeters.size()) - 1;
  523. int end_perimeter = -1;
  524. int direction = -1;
  525. if (this->config->external_perimeters_first) {
  526. start_perimeter = 0;
  527. end_perimeter = int(perimeters.size());
  528. direction = 1;
  529. }
  530. std::vector<Arachne::ExtrusionLine *> all_extrusions;
  531. for (int perimeter_idx = start_perimeter; perimeter_idx != end_perimeter; perimeter_idx += direction) {
  532. if (perimeters[perimeter_idx].empty())
  533. continue;
  534. for (Arachne::ExtrusionLine &wall : perimeters[perimeter_idx])
  535. all_extrusions.emplace_back(&wall);
  536. }
  537. // Find topological order with constraints from extrusions_constrains.
  538. std::vector<size_t> blocked(all_extrusions.size(), 0); // Value indicating how many extrusions it is blocking (preceding extrusions) an extrusion.
  539. std::vector<std::vector<size_t>> blocking(all_extrusions.size()); // Each extrusion contains a vector of extrusions that are blocked by this extrusion.
  540. std::unordered_map<const Arachne::ExtrusionLine *, size_t> map_extrusion_to_idx;
  541. for (size_t idx = 0; idx < all_extrusions.size(); idx++)
  542. map_extrusion_to_idx.emplace(all_extrusions[idx], idx);
  543. auto extrusions_constrains = Arachne::WallToolPaths::getRegionOrder(all_extrusions, this->config->external_perimeters_first);
  544. for (auto [before, after] : extrusions_constrains) {
  545. auto after_it = map_extrusion_to_idx.find(after);
  546. ++blocked[after_it->second];
  547. blocking[map_extrusion_to_idx.find(before)->second].emplace_back(after_it->second);
  548. }
  549. std::vector<bool> processed(all_extrusions.size(), false); // Indicate that the extrusion was already processed.
  550. Point current_position = all_extrusions.empty() ? Point::Zero() : all_extrusions.front()->junctions.front().p; // Some starting position.
  551. std::vector<PerimeterGeneratorArachneExtrusion> ordered_extrusions; // To store our result in. At the end we'll std::swap.
  552. ordered_extrusions.reserve(all_extrusions.size());
  553. while (ordered_extrusions.size() < all_extrusions.size()) {
  554. size_t best_candidate = 0;
  555. double best_distance_sqr = std::numeric_limits<double>::max();
  556. bool is_best_closed = false;
  557. std::vector<size_t> available_candidates;
  558. for (size_t candidate = 0; candidate < all_extrusions.size(); ++candidate) {
  559. if (processed[candidate] || blocked[candidate])
  560. continue; // Not a valid candidate.
  561. available_candidates.push_back(candidate);
  562. }
  563. std::sort(available_candidates.begin(), available_candidates.end(), [&all_extrusions](const size_t a_idx, const size_t b_idx) -> bool {
  564. return all_extrusions[a_idx]->is_closed < all_extrusions[b_idx]->is_closed;
  565. });
  566. for (const size_t candidate_path_idx : available_candidates) {
  567. auto& path = all_extrusions[candidate_path_idx];
  568. if (path->junctions.empty()) { // No vertices in the path. Can't find the start position then or really plan it in. Put that at the end.
  569. if (best_distance_sqr == std::numeric_limits<double>::max()) {
  570. best_candidate = candidate_path_idx;
  571. is_best_closed = path->is_closed;
  572. }
  573. continue;
  574. }
  575. const Point candidate_position = path->junctions.front().p;
  576. double distance_sqr = (current_position - candidate_position).cast<double>().norm();
  577. if (distance_sqr < best_distance_sqr) { // Closer than the best candidate so far.
  578. if (path->is_closed || (!path->is_closed && best_distance_sqr != std::numeric_limits<double>::max()) || (!path->is_closed && !is_best_closed)) {
  579. best_candidate = candidate_path_idx;
  580. best_distance_sqr = distance_sqr;
  581. is_best_closed = path->is_closed;
  582. }
  583. }
  584. }
  585. auto &best_path = all_extrusions[best_candidate];
  586. ordered_extrusions.push_back({best_path, best_path->is_contour(), false});
  587. processed[best_candidate] = true;
  588. for (size_t unlocked_idx : blocking[best_candidate])
  589. blocked[unlocked_idx]--;
  590. if(!best_path->junctions.empty()) { //If all paths were empty, the best path is still empty. We don't upate the current position then.
  591. if(best_path->is_closed)
  592. current_position = best_path->junctions[0].p; //We end where we started.
  593. else
  594. current_position = best_path->junctions.back().p; //Pick the other end from where we started.
  595. }
  596. }
  597. if (this->layer_id > 0 && this->config->fuzzy_skin != FuzzySkinType::None) {
  598. std::vector<PerimeterGeneratorArachneExtrusion *> closed_loop_extrusions;
  599. for (PerimeterGeneratorArachneExtrusion &extrusion : ordered_extrusions)
  600. if (extrusion.extrusion->inset_idx == 0) {
  601. if (extrusion.extrusion->is_closed && this->config->fuzzy_skin == FuzzySkinType::External) {
  602. closed_loop_extrusions.emplace_back(&extrusion);
  603. } else {
  604. extrusion.fuzzify = true;
  605. }
  606. }
  607. if (this->config->fuzzy_skin == FuzzySkinType::External) {
  608. ClipperLib_Z::Paths loops_paths;
  609. loops_paths.reserve(closed_loop_extrusions.size());
  610. for (const auto &cl_extrusion : closed_loop_extrusions) {
  611. assert(cl_extrusion->extrusion->junctions.front() == cl_extrusion->extrusion->junctions.back());
  612. size_t loop_idx = &cl_extrusion - &closed_loop_extrusions.front();
  613. ClipperLib_Z::Path loop_path;
  614. loop_path.reserve(cl_extrusion->extrusion->junctions.size() - 1);
  615. for (auto junction_it = cl_extrusion->extrusion->junctions.begin(); junction_it != std::prev(cl_extrusion->extrusion->junctions.end()); ++junction_it)
  616. loop_path.emplace_back(junction_it->p.x(), junction_it->p.y(), loop_idx);
  617. loops_paths.emplace_back(loop_path);
  618. }
  619. ClipperLib_Z::Clipper clipper;
  620. clipper.AddPaths(loops_paths, ClipperLib_Z::ptSubject, true);
  621. ClipperLib_Z::PolyTree loops_polytree;
  622. clipper.Execute(ClipperLib_Z::ctUnion, loops_polytree, ClipperLib_Z::pftEvenOdd, ClipperLib_Z::pftEvenOdd);
  623. for (const ClipperLib_Z::PolyNode *child_node : loops_polytree.Childs) {
  624. // The whole contour must have the same index.
  625. coord_t polygon_idx = child_node->Contour.front().z();
  626. bool has_same_idx = std::all_of(child_node->Contour.begin(), child_node->Contour.end(),
  627. [&polygon_idx](const ClipperLib_Z::IntPoint &point) -> bool { return polygon_idx == point.z(); });
  628. if (has_same_idx)
  629. closed_loop_extrusions[polygon_idx]->fuzzify = true;
  630. }
  631. }
  632. }
  633. if (ExtrusionEntityCollection extrusion_coll = traverse_extrusions(*this, ordered_extrusions); !extrusion_coll.empty())
  634. this->loops->append(extrusion_coll);
  635. ExPolygons infill_contour = union_ex(wallToolPaths.getInnerContour());
  636. const coord_t spacing = (perimeters.size() == 1) ? ext_perimeter_spacing2 : perimeter_spacing;
  637. if (offset_ex(infill_contour, -float(spacing / 2.)).empty())
  638. infill_contour.clear(); // Infill region is too small, so let's filter it out.
  639. // create one more offset to be used as boundary for fill
  640. // we offset by half the perimeter spacing (to get to the actual infill boundary)
  641. // and then we offset back and forth by half the infill spacing to only consider the
  642. // non-collapsing regions
  643. coord_t inset =
  644. (loop_number < 0) ? 0 :
  645. (loop_number == 0) ?
  646. // one loop
  647. ext_perimeter_spacing:
  648. // two or more loops?
  649. perimeter_spacing;
  650. inset = coord_t(scale_(this->config->get_abs_value("infill_overlap", unscale<double>(inset))));
  651. Polygons pp;
  652. for (ExPolygon &ex : infill_contour)
  653. ex.simplify_p(m_scaled_resolution, &pp);
  654. // collapse too narrow infill areas
  655. const auto min_perimeter_infill_spacing = coord_t(solid_infill_spacing * (1. - INSET_OVERLAP_TOLERANCE));
  656. // append infill areas to fill_surfaces
  657. this->fill_surfaces->append(
  658. offset2_ex(
  659. union_ex(pp),
  660. float(- min_perimeter_infill_spacing / 2.),
  661. float(inset + min_perimeter_infill_spacing / 2.)),
  662. stInternal);
  663. }
  664. }
  665. void PerimeterGenerator::process_classic()
  666. {
  667. // other perimeters
  668. m_mm3_per_mm = this->perimeter_flow.mm3_per_mm();
  669. coord_t perimeter_width = this->perimeter_flow.scaled_width();
  670. coord_t perimeter_spacing = this->perimeter_flow.scaled_spacing();
  671. // external perimeters
  672. m_ext_mm3_per_mm = this->ext_perimeter_flow.mm3_per_mm();
  673. coord_t ext_perimeter_width = this->ext_perimeter_flow.scaled_width();
  674. coord_t ext_perimeter_spacing = this->ext_perimeter_flow.scaled_spacing();
  675. coord_t ext_perimeter_spacing2 = scaled<coord_t>(0.5f * (this->ext_perimeter_flow.spacing() + this->perimeter_flow.spacing()));
  676. // overhang perimeters
  677. m_mm3_per_mm_overhang = this->overhang_flow.mm3_per_mm();
  678. // solid infill
  679. coord_t solid_infill_spacing = this->solid_infill_flow.scaled_spacing();
  680. // Calculate the minimum required spacing between two adjacent traces.
  681. // This should be equal to the nominal flow spacing but we experiment
  682. // with some tolerance in order to avoid triggering medial axis when
  683. // some squishing might work. Loops are still spaced by the entire
  684. // flow spacing; this only applies to collapsing parts.
  685. // For ext_min_spacing we use the ext_perimeter_spacing calculated for two adjacent
  686. // external loops (which is the correct way) instead of using ext_perimeter_spacing2
  687. // which is the spacing between external and internal, which is not correct
  688. // and would make the collapsing (thus the details resolution) dependent on
  689. // internal flow which is unrelated.
  690. coord_t min_spacing = coord_t(perimeter_spacing * (1 - INSET_OVERLAP_TOLERANCE));
  691. coord_t ext_min_spacing = coord_t(ext_perimeter_spacing * (1 - INSET_OVERLAP_TOLERANCE));
  692. bool has_gap_fill = this->config->gap_fill_enabled.value && this->config->gap_fill_speed.value > 0;
  693. // prepare grown lower layer slices for overhang detection
  694. if (this->lower_slices != NULL && this->config->overhangs) {
  695. // We consider overhang any part where the entire nozzle diameter is not supported by the
  696. // lower layer, so we take lower slices and offset them by half the nozzle diameter used
  697. // in the current layer
  698. double nozzle_diameter = this->print_config->nozzle_diameter.get_at(this->config->perimeter_extruder-1);
  699. m_lower_slices_polygons = offset(*this->lower_slices, float(scale_(+nozzle_diameter/2)));
  700. }
  701. // we need to process each island separately because we might have different
  702. // extra perimeters for each one
  703. for (const Surface &surface : this->slices->surfaces) {
  704. // detect how many perimeters must be generated for this island
  705. int loop_number = this->config->perimeters + surface.extra_perimeters - 1; // 0-indexed loops
  706. ExPolygons last = union_ex(surface.expolygon.simplify_p(m_scaled_resolution));
  707. ExPolygons gaps;
  708. if (loop_number >= 0) {
  709. // In case no perimeters are to be generated, loop_number will equal to -1.
  710. std::vector<PerimeterGeneratorLoops> contours(loop_number+1); // depth => loops
  711. std::vector<PerimeterGeneratorLoops> holes(loop_number+1); // depth => loops
  712. ThickPolylines thin_walls;
  713. // we loop one time more than needed in order to find gaps after the last perimeter was applied
  714. for (int i = 0;; ++ i) { // outer loop is 0
  715. // Calculate next onion shell of perimeters.
  716. ExPolygons offsets;
  717. if (i == 0) {
  718. // the minimum thickness of a single loop is:
  719. // ext_width/2 + ext_spacing/2 + spacing/2 + width/2
  720. offsets = this->config->thin_walls ?
  721. offset2_ex(
  722. last,
  723. - float(ext_perimeter_width / 2. + ext_min_spacing / 2. - 1),
  724. + float(ext_min_spacing / 2. - 1)) :
  725. offset_ex(last, - float(ext_perimeter_width / 2.));
  726. // look for thin walls
  727. if (this->config->thin_walls) {
  728. // the following offset2 ensures almost nothing in @thin_walls is narrower than $min_width
  729. // (actually, something larger than that still may exist due to mitering or other causes)
  730. coord_t min_width = coord_t(scale_(this->ext_perimeter_flow.nozzle_diameter() / 3));
  731. ExPolygons expp = opening_ex(
  732. // medial axis requires non-overlapping geometry
  733. diff_ex(last, offset(offsets, float(ext_perimeter_width / 2.) + ClipperSafetyOffset)),
  734. float(min_width / 2.));
  735. // the maximum thickness of our thin wall area is equal to the minimum thickness of a single loop
  736. for (ExPolygon &ex : expp)
  737. ex.medial_axis(ext_perimeter_width + ext_perimeter_spacing2, min_width, &thin_walls);
  738. }
  739. if (m_spiral_vase && offsets.size() > 1) {
  740. // Remove all but the largest area polygon.
  741. keep_largest_contour_only(offsets);
  742. }
  743. } else {
  744. //FIXME Is this offset correct if the line width of the inner perimeters differs
  745. // from the line width of the infill?
  746. coord_t distance = (i == 1) ? ext_perimeter_spacing2 : perimeter_spacing;
  747. offsets = this->config->thin_walls ?
  748. // This path will ensure, that the perimeters do not overfill, as in
  749. // prusa3d/Slic3r GH #32, but with the cost of rounding the perimeters
  750. // excessively, creating gaps, which then need to be filled in by the not very
  751. // reliable gap fill algorithm.
  752. // Also the offset2(perimeter, -x, x) may sometimes lead to a perimeter, which is larger than
  753. // the original.
  754. offset2_ex(last,
  755. - float(distance + min_spacing / 2. - 1.),
  756. float(min_spacing / 2. - 1.)) :
  757. // If "detect thin walls" is not enabled, this paths will be entered, which
  758. // leads to overflows, as in prusa3d/Slic3r GH #32
  759. offset_ex(last, - float(distance));
  760. // look for gaps
  761. if (has_gap_fill)
  762. // not using safety offset here would "detect" very narrow gaps
  763. // (but still long enough to escape the area threshold) that gap fill
  764. // won't be able to fill but we'd still remove from infill area
  765. append(gaps, diff_ex(
  766. offset(last, - float(0.5 * distance)),
  767. offset(offsets, float(0.5 * distance + 10)))); // safety offset
  768. }
  769. if (offsets.empty()) {
  770. // Store the number of loops actually generated.
  771. loop_number = i - 1;
  772. // No region left to be filled in.
  773. last.clear();
  774. break;
  775. } else if (i > loop_number) {
  776. // If i > loop_number, we were looking just for gaps.
  777. break;
  778. }
  779. {
  780. const bool fuzzify_contours = this->config->fuzzy_skin != FuzzySkinType::None && i == 0 && this->layer_id > 0;
  781. const bool fuzzify_holes = fuzzify_contours && this->config->fuzzy_skin == FuzzySkinType::All;
  782. for (const ExPolygon &expolygon : offsets) {
  783. // Outer contour may overlap with an inner contour,
  784. // inner contour may overlap with another inner contour,
  785. // outer contour may overlap with itself.
  786. //FIXME evaluate the overlaps, annotate each point with an overlap depth,
  787. // compensate for the depth of intersection.
  788. contours[i].emplace_back(expolygon.contour, i, true, fuzzify_contours);
  789. if (! expolygon.holes.empty()) {
  790. holes[i].reserve(holes[i].size() + expolygon.holes.size());
  791. for (const Polygon &hole : expolygon.holes)
  792. holes[i].emplace_back(hole, i, false, fuzzify_holes);
  793. }
  794. }
  795. }
  796. last = std::move(offsets);
  797. if (i == loop_number && (! has_gap_fill || this->config->fill_density.value == 0)) {
  798. // The last run of this loop is executed to collect gaps for gap fill.
  799. // As the gap fill is either disabled or not
  800. break;
  801. }
  802. }
  803. // nest loops: holes first
  804. for (int d = 0; d <= loop_number; ++ d) {
  805. PerimeterGeneratorLoops &holes_d = holes[d];
  806. // loop through all holes having depth == d
  807. for (int i = 0; i < (int)holes_d.size(); ++ i) {
  808. const PerimeterGeneratorLoop &loop = holes_d[i];
  809. // find the hole loop that contains this one, if any
  810. for (int t = d + 1; t <= loop_number; ++ t) {
  811. for (int j = 0; j < (int)holes[t].size(); ++ j) {
  812. PerimeterGeneratorLoop &candidate_parent = holes[t][j];
  813. if (candidate_parent.polygon.contains(loop.polygon.first_point())) {
  814. candidate_parent.children.push_back(loop);
  815. holes_d.erase(holes_d.begin() + i);
  816. -- i;
  817. goto NEXT_LOOP;
  818. }
  819. }
  820. }
  821. // if no hole contains this hole, find the contour loop that contains it
  822. for (int t = loop_number; t >= 0; -- t) {
  823. for (int j = 0; j < (int)contours[t].size(); ++ j) {
  824. PerimeterGeneratorLoop &candidate_parent = contours[t][j];
  825. if (candidate_parent.polygon.contains(loop.polygon.first_point())) {
  826. candidate_parent.children.push_back(loop);
  827. holes_d.erase(holes_d.begin() + i);
  828. -- i;
  829. goto NEXT_LOOP;
  830. }
  831. }
  832. }
  833. NEXT_LOOP: ;
  834. }
  835. }
  836. // nest contour loops
  837. for (int d = loop_number; d >= 1; -- d) {
  838. PerimeterGeneratorLoops &contours_d = contours[d];
  839. // loop through all contours having depth == d
  840. for (int i = 0; i < (int)contours_d.size(); ++ i) {
  841. const PerimeterGeneratorLoop &loop = contours_d[i];
  842. // find the contour loop that contains it
  843. for (int t = d - 1; t >= 0; -- t) {
  844. for (size_t j = 0; j < contours[t].size(); ++ j) {
  845. PerimeterGeneratorLoop &candidate_parent = contours[t][j];
  846. if (candidate_parent.polygon.contains(loop.polygon.first_point())) {
  847. candidate_parent.children.push_back(loop);
  848. contours_d.erase(contours_d.begin() + i);
  849. -- i;
  850. goto NEXT_CONTOUR;
  851. }
  852. }
  853. }
  854. NEXT_CONTOUR: ;
  855. }
  856. }
  857. // at this point, all loops should be in contours[0]
  858. ExtrusionEntityCollection entities = traverse_loops(*this, contours.front(), thin_walls);
  859. // if brim will be printed, reverse the order of perimeters so that
  860. // we continue inwards after having finished the brim
  861. // TODO: add test for perimeter order
  862. if (this->config->external_perimeters_first ||
  863. (this->layer_id == 0 && this->object_config->brim_width.value > 0))
  864. entities.reverse();
  865. // append perimeters for this slice as a collection
  866. if (! entities.empty())
  867. this->loops->append(entities);
  868. } // for each loop of an island
  869. // fill gaps
  870. if (! gaps.empty()) {
  871. // collapse
  872. double min = 0.2 * perimeter_width * (1 - INSET_OVERLAP_TOLERANCE);
  873. double max = 2. * perimeter_spacing;
  874. ExPolygons gaps_ex = diff_ex(
  875. //FIXME offset2 would be enough and cheaper.
  876. opening_ex(gaps, float(min / 2.)),
  877. offset2_ex(gaps, - float(max / 2.), float(max / 2. + ClipperSafetyOffset)));
  878. ThickPolylines polylines;
  879. for (const ExPolygon &ex : gaps_ex)
  880. ex.medial_axis(max, min, &polylines);
  881. if (! polylines.empty()) {
  882. ExtrusionEntityCollection gap_fill;
  883. variable_width(polylines, erGapFill, this->solid_infill_flow, gap_fill.entities);
  884. /* Make sure we don't infill narrow parts that are already gap-filled
  885. (we only consider this surface's gaps to reduce the diff() complexity).
  886. Growing actual extrusions ensures that gaps not filled by medial axis
  887. are not subtracted from fill surfaces (they might be too short gaps
  888. that medial axis skips but infill might join with other infill regions
  889. and use zigzag). */
  890. //FIXME Vojtech: This grows by a rounded extrusion width, not by line spacing,
  891. // therefore it may cover the area, but no the volume.
  892. last = diff_ex(last, gap_fill.polygons_covered_by_width(10.f));
  893. this->gap_fill->append(std::move(gap_fill.entities));
  894. }
  895. }
  896. // create one more offset to be used as boundary for fill
  897. // we offset by half the perimeter spacing (to get to the actual infill boundary)
  898. // and then we offset back and forth by half the infill spacing to only consider the
  899. // non-collapsing regions
  900. coord_t inset =
  901. (loop_number < 0) ? 0 :
  902. (loop_number == 0) ?
  903. // one loop
  904. ext_perimeter_spacing / 2 :
  905. // two or more loops?
  906. perimeter_spacing / 2;
  907. // only apply infill overlap if we actually have one perimeter
  908. if (inset > 0)
  909. inset -= coord_t(scale_(this->config->get_abs_value("infill_overlap", unscale<double>(inset + solid_infill_spacing / 2))));
  910. // simplify infill contours according to resolution
  911. Polygons pp;
  912. for (ExPolygon &ex : last)
  913. ex.simplify_p(m_scaled_resolution, &pp);
  914. // collapse too narrow infill areas
  915. coord_t min_perimeter_infill_spacing = coord_t(solid_infill_spacing * (1. - INSET_OVERLAP_TOLERANCE));
  916. // append infill areas to fill_surfaces
  917. this->fill_surfaces->append(
  918. offset2_ex(
  919. union_ex(pp),
  920. float(- inset - min_perimeter_infill_spacing / 2.),
  921. float(min_perimeter_infill_spacing / 2.)),
  922. stInternal);
  923. } // for each island
  924. }
  925. bool PerimeterGeneratorLoop::is_internal_contour() const
  926. {
  927. // An internal contour is a contour containing no other contours
  928. if (! this->is_contour)
  929. return false;
  930. for (const PerimeterGeneratorLoop &loop : this->children)
  931. if (loop.is_contour)
  932. return false;
  933. return true;
  934. }
  935. }