-
-
Notifications
You must be signed in to change notification settings - Fork 919
Expand file tree
/
Copy pathLayerPlan.cpp
More file actions
4173 lines (3727 loc) · 181 KB
/
LayerPlan.cpp
File metadata and controls
4173 lines (3727 loc) · 181 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2023 UltiMaker
// CuraEngine is released under the terms of the AGPLv3 or higher
#include "LayerPlan.h"
#include <algorithm>
#include <cstring>
#include <numeric>
#include <optional>
#include <boost/mpl/distance.hpp>
#include <boost/range/distance.hpp>
#include <range/v3/algorithm/max_element.hpp>
#include <scripta/logger.h>
#include <spdlog/spdlog.h>
#include "Application.h" //To communicate layer view data.
#include "BeadingStrategy/BeadingStrategyFactory.h"
#include "ExtruderTrain.h"
#include "PathAdapter.h"
#include "PathOrderMonotonic.h" //Monotonic ordering of skin lines.
#include "Slice.h"
#include "TravelAntiOozing.h"
#include "WipeScriptConfig.h"
#include "arachne/SkeletalTrapezoidation.h"
#include "arachne/SkeletalTrapezoidationGraph.h"
#include "bridge/bridge.h"
#include "communication/Communication.h"
#include "geometry/OpenPolyline.h"
#include "geometry/conversions/Point2D_Point2LL.h"
#include "gradual_flow/Processor.h"
#include "pathPlanning/Comb.h"
#include "pathPlanning/CombPaths.h"
#include "plugins/slots.h"
#include "raft.h" // getTotalExtraLayers
#include "range/v3/view/chunk_by.hpp"
#include "settings/types/Ratio.h"
#include "sliceDataStorage.h"
#include "utils/Simplify.h"
#include "utils/linearAlg2D.h"
#include "utils/math.h"
#include "utils/polygonUtils.h"
#include "utils/section_type.h"
namespace cura
{
constexpr int MINIMUM_LINE_LENGTH = 5; // in uM. Generated lines shorter than this may be discarded
constexpr int MINIMUM_SQUARED_LINE_LENGTH = MINIMUM_LINE_LENGTH * MINIMUM_LINE_LENGTH;
GCodePath* LayerPlan::getLatestPathWithConfig(
const GCodePathConfig& config,
const SpaceFillType space_fill_type,
const coord_t z_offset,
const Ratio flow,
const Ratio width_factor,
const bool spiralize,
const Ratio speed_factor)
{
std::vector<GCodePath>& paths = extruder_plans_.back().paths_;
if (paths.size() > 0 && paths.back().config == config && ! paths.back().done && paths.back().flow == flow && paths.back().width_factor == width_factor
&& paths.back().speed_factor == speed_factor && paths.back().z_offset == z_offset
&& paths.back().mesh == current_mesh_) // spiralize can only change when a travel path is in between
{
return &paths.back();
}
paths.emplace_back(GCodePath{ .z_offset = z_offset,
.config = config,
.mesh = current_mesh_,
.space_fill_type = space_fill_type,
.flow = flow,
.width_factor = width_factor,
.spiralize = spiralize,
.speed_factor = speed_factor });
GCodePath* ret = &paths.back();
return ret;
}
const Shape* LayerPlan::getCombBoundaryInside() const
{
return &comb_boundary_preferred_;
}
void LayerPlan::forceNewPathStart()
{
std::vector<GCodePath>& paths = extruder_plans_.back().paths_;
if (paths.size() > 0)
paths[paths.size() - 1].done = true;
}
LayerPlan::LayerPlan(
const SliceDataStorage& storage,
LayerIndex layer_nr,
coord_t z,
coord_t layer_thickness,
size_t start_extruder,
const std::vector<FanSpeedLayerTimeSettings>& fan_speed_layer_time_settings_per_extruder,
coord_t comb_boundary_offset,
coord_t comb_move_inside_distance,
coord_t travel_avoid_distance)
: configs_storage_(storage, layer_nr, layer_thickness)
, z_(z)
, final_travel_z_(z)
, storage_(storage)
, layer_nr_(layer_nr)
, is_initial_layer_(layer_nr == 0 - static_cast<LayerIndex>(Raft::getTotalExtraLayers()))
, layer_type_(Raft::getLayerType(layer_nr))
, layer_thickness_(layer_thickness)
, has_prime_tower_planned_per_extruder_(Application::getInstance().current_slice_->scene.extruders.size(), false)
, current_mesh_(nullptr)
, last_extruder_previous_layer_(start_extruder)
, last_planned_extruder_(&Application::getInstance().current_slice_->scene.extruders[start_extruder])
, first_travel_destination_is_inside_(false)
, // set properly when addTravel is called for the first time (otherwise not set properly)
comb_boundary_minimum_(computeCombBoundary(CombBoundary::MINIMUM))
, comb_boundary_preferred_(computeCombBoundary(CombBoundary::PREFERRED))
, comb_move_inside_distance_(comb_move_inside_distance)
, fan_speed_layer_time_settings_per_extruder_(fan_speed_layer_time_settings_per_extruder)
{
size_t current_extruder = start_extruder;
was_inside_ = true; // not used, because the first travel move is bogus
is_inside_ = false; // assumes the next move will not be to inside a layer part (overwritten just before going into a layer part)
const auto& local_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings;
if (local_settings.get<CombingMode>("retraction_combing") != CombingMode::OFF && local_settings.get<coord_t>("retraction_combing_avoid_distance") > 0)
{
comb_ = new Comb(storage, layer_nr, comb_boundary_minimum_, comb_boundary_preferred_, comb_boundary_offset, travel_avoid_distance, comb_move_inside_distance);
}
else
{
comb_ = nullptr;
}
for (const ExtruderTrain& extruder : Application::getInstance().current_slice_->scene.extruders)
{
layer_start_pos_per_extruder_.emplace_back(extruder.settings_.get<coord_t>("layer_start_x"), extruder.settings_.get<coord_t>("layer_start_y"), 0);
}
extruder_plans_.reserve(Application::getInstance().current_slice_->scene.extruders.size());
const auto is_raft_layer = layer_type_ == Raft::LayerType::RaftBase || layer_type_ == Raft::LayerType::RaftInterface || layer_type_ == Raft::LayerType::RaftSurface;
extruder_plans_.emplace_back(
current_extruder,
layer_nr,
is_initial_layer_,
is_raft_layer,
layer_thickness,
fan_speed_layer_time_settings_per_extruder[current_extruder],
storage.retraction_wipe_config_per_extruder[current_extruder].retraction_config);
for (size_t extruder_nr = 0; extruder_nr < Application::getInstance().current_slice_->scene.extruders.size(); extruder_nr++)
{ // Skirt and brim.
skirt_brim_is_processed_[extruder_nr] = false;
}
}
LayerPlan::~LayerPlan()
{
if (comb_)
delete comb_;
}
ExtruderTrain* LayerPlan::getLastPlannedExtruderTrain()
{
return last_planned_extruder_;
}
Shape LayerPlan::computeCombBoundary(const CombBoundary boundary_type)
{
Shape comb_boundary;
const CombingMode mesh_combing_mode = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get<CombingMode>("retraction_combing");
if (mesh_combing_mode != CombingMode::OFF && (layer_nr_ >= 0 || mesh_combing_mode != CombingMode::NO_SKIN))
{
switch (layer_type_)
{
case Raft::LayerType::RaftBase:
comb_boundary = storage_.raft_base_outline.offset(MM2INT(0.1));
break;
case Raft::LayerType::RaftInterface:
comb_boundary = storage_.raft_interface_outline.offset(MM2INT(0.1));
break;
case Raft::LayerType::RaftSurface:
comb_boundary = storage_.raft_surface_outline.offset(MM2INT(0.1));
break;
case Raft::LayerType::Airgap:
// do nothing for airgap
break;
case Raft::LayerType::Model:
for (const std::shared_ptr<SliceMeshStorage>& mesh_ptr : storage_.meshes)
{
const auto& mesh = *mesh_ptr;
const SliceLayer& layer = mesh.layers[static_cast<size_t>(layer_nr_)];
// don't process infill_mesh or anti_overhang_mesh
if (mesh.settings.get<bool>("infill_mesh") || mesh.settings.get<bool>("anti_overhang_mesh"))
{
continue;
}
constexpr coord_t extra_offset = 10; // Additional offset to avoid zero-width polygons remains
coord_t offset;
switch (boundary_type)
{
case CombBoundary::MINIMUM:
offset = -(mesh.settings.get<coord_t>("machine_nozzle_size") / 2 + mesh.settings.get<coord_t>("wall_line_width_0") / 2 + extra_offset);
break;
case CombBoundary::PREFERRED:
offset = -(mesh.settings.get<coord_t>("retraction_combing_avoid_distance") + mesh.settings.get<coord_t>("wall_line_width_0") / 2 + extra_offset);
break;
default:
offset = 0;
spdlog::warn("Unknown combing boundary type. Did you forget to configure the comb offset for a new boundary type?");
break;
}
const CombingMode combing_mode = mesh.settings.get<CombingMode>("retraction_combing");
for (const SliceLayerPart& part : layer.parts)
{
Shape part_combing_boundary;
if (combing_mode == CombingMode::INFILL)
{
part_combing_boundary = part.infill_area;
}
else
{
part_combing_boundary = part.outline.offset(10).offset(offset - 10);
if (combing_mode == CombingMode::NO_SKIN) // Add the increased outline offset, subtract skin (infill and part of the inner walls)
{
part_combing_boundary = part_combing_boundary.difference(part.inner_area.difference(part.infill_area));
}
else if (combing_mode == CombingMode::NO_OUTER_SURFACES)
{
for (const SliceLayerPart& outer_surface_part : layer.parts)
{
part_combing_boundary = part_combing_boundary.difference(outer_surface_part.top_most_surface);
part_combing_boundary = part_combing_boundary.difference(outer_surface_part.bottom_most_surface);
}
}
}
comb_boundary.push_back(part_combing_boundary);
}
}
break;
}
}
return comb_boundary;
}
void LayerPlan::setIsInside(bool _is_inside)
{
is_inside_ = _is_inside;
}
bool LayerPlan::setExtruder(const size_t extruder_nr)
{
if (extruder_nr == getExtruder())
{
return false;
}
setIsInside(false);
{ // handle end position of the prev extruder
ExtruderTrain* extruder = getLastPlannedExtruderTrain();
const bool end_pos_absolute = extruder->settings_.get<bool>("machine_extruder_end_pos_abs");
Point2LL end_pos(extruder->settings_.get<coord_t>("machine_extruder_end_pos_x"), extruder->settings_.get<coord_t>("machine_extruder_end_pos_y"));
if (! end_pos_absolute)
{
end_pos += getLastPlannedPositionOrStartingPosition();
}
else
{
const Point2LL extruder_offset(extruder->settings_.get<coord_t>("machine_nozzle_offset_x"), extruder->settings_.get<coord_t>("machine_nozzle_offset_y"));
end_pos += extruder_offset; // absolute end pos is given as a head position
}
if (end_pos_absolute || last_planned_position_)
{
GCodePath& path = addTravel(end_pos); // + extruder_offset cause it
path.retract_for_nozzle_switch = true;
}
}
if (extruder_plans_.back().paths_.empty() && extruder_plans_.back().inserts_.empty())
{ // first extruder plan in a layer might be empty, cause it is made with the last extruder planned in the previous layer
extruder_plans_.back().extruder_nr_ = extruder_nr;
}
const auto is_raft_layer = layer_type_ == Raft::LayerType::RaftBase || layer_type_ == Raft::LayerType::RaftInterface || layer_type_ == Raft::LayerType::RaftSurface;
extruder_plans_.emplace_back(
extruder_nr,
layer_nr_,
is_initial_layer_,
is_raft_layer,
layer_thickness_,
fan_speed_layer_time_settings_per_extruder_[extruder_nr],
storage_.retraction_wipe_config_per_extruder[extruder_nr].retraction_config);
assert(extruder_plans_.size() <= Application::getInstance().current_slice_->scene.extruders.size() && "Never use the same extruder twice on one layer!");
last_planned_extruder_ = &Application::getInstance().current_slice_->scene.extruders[extruder_nr];
{ // handle starting pos of the new extruder
ExtruderTrain* extruder = getLastPlannedExtruderTrain();
const bool start_pos_absolute = extruder->settings_.get<bool>("machine_extruder_start_pos_abs");
Point3LL start_pos(extruder->settings_.get<coord_t>("machine_extruder_start_pos_x"), extruder->settings_.get<coord_t>("machine_extruder_start_pos_y"), 0);
if (! start_pos_absolute)
{
start_pos += getLastPlannedPositionOrStartingPosition();
}
else
{
Point3LL extruder_offset(extruder->settings_.get<coord_t>("machine_nozzle_offset_x"), extruder->settings_.get<coord_t>("machine_nozzle_offset_y"), 0);
start_pos += extruder_offset; // absolute start pos is given as a head position
}
if (start_pos_absolute || last_planned_position_)
{
last_planned_position_ = start_pos;
}
}
return true;
}
void LayerPlan::setMesh(const std::shared_ptr<const SliceMeshStorage>& mesh)
{
current_mesh_ = mesh;
}
void LayerPlan::moveInsideCombBoundary(const coord_t distance, const std::optional<SliceLayerPart>& part, GCodePath* path)
{
constexpr coord_t max_dist2 = MM2INT(2.0) * MM2INT(2.0); // if we are further than this distance, we conclude we are not inside even though we thought we were.
// this function is to be used to move from the boundary of a part to inside the part
Point2LL p = getLastPlannedPositionOrStartingPosition(); // copy, since we are going to move p
if (PolygonUtils::moveInside(comb_boundary_preferred_, p, distance, max_dist2) != NO_INDEX)
{
// Move inside again, so we move out of tight 90deg corners
PolygonUtils::moveInside(comb_boundary_preferred_, p, distance, max_dist2);
if (comb_boundary_preferred_.inside(p) && (part == std::nullopt || part->outline.inside(p)))
{
addTravel_simple(p, path);
// Make sure the that any retraction happens after this move, not before it by starting a new move path.
forceNewPathStart();
}
}
}
bool LayerPlan::getPrimeTowerIsPlanned(size_t extruder_nr) const
{
return has_prime_tower_planned_per_extruder_[extruder_nr];
}
void LayerPlan::setPrimeTowerIsPlanned(size_t extruder_nr)
{
has_prime_tower_planned_per_extruder_[extruder_nr] = true;
}
std::optional<std::pair<Point2LL, bool>> LayerPlan::getFirstTravelDestinationState() const
{
std::optional<std::pair<Point2LL, bool>> ret;
if (first_travel_destination_)
{
ret = std::make_pair(*first_travel_destination_, first_travel_destination_is_inside_);
}
return ret;
}
GCodePath& LayerPlan::addTravel(const Point2LL& p, const ForceRetract force_retract, const coord_t z_offset)
{
const GCodePathConfig& travel_config = configs_storage_.travel_config_per_extruder[getExtruder()];
const RetractionConfig& retraction_config
= current_mesh_ ? current_mesh_->retraction_wipe_config.retraction_config : storage_.retraction_wipe_config_per_extruder[getExtruder()].retraction_config;
GCodePath* path = getLatestPathWithConfig(travel_config, SpaceFillType::None, z_offset);
bool combed = false;
const ExtruderTrain* extruder = getLastPlannedExtruderTrain();
const Settings& mesh_or_extruder_settings = current_mesh_ ? current_mesh_->settings : extruder->settings_;
const bool is_first_travel_of_extruder_after_switch
= extruder_plans_.back().paths_.size() == 1 && (extruder_plans_.size() > 1 || last_extruder_previous_layer_ != getExtruder());
bool bypass_combing = is_first_travel_of_extruder_after_switch && mesh_or_extruder_settings.get<bool>("retraction_hop_after_extruder_switch");
const bool is_first_travel_of_layer = ! static_cast<bool>(last_planned_position_);
const bool retraction_enable = mesh_or_extruder_settings.get<bool>("retraction_enable");
if (is_first_travel_of_layer)
{
bypass_combing = true; // first travel move is bogus; it is added after this and the previous layer have been planned in LayerPlanBuffer::addConnectingTravelMove
first_travel_destination_ = p;
first_travel_destination_is_inside_ = is_inside_;
if (layer_nr_ == 0 && retraction_enable && mesh_or_extruder_settings.get<bool>("retraction_hop_enabled"))
{
path->retract = true;
path->perform_z_hop = true;
}
forceNewPathStart(); // force a new travel path after this first bogus move
}
else if (
force_retract == ForceRetract::RETRACTED && last_planned_position_
&& ! shorterThen(last_planned_position_.value().toPoint2LL() - p, retraction_config.retraction_min_travel_distance))
{
// path is not shorter than min travel distance, force a retraction
path->retract = true;
if (comb_ == nullptr)
{
path->perform_z_hop = mesh_or_extruder_settings.get<bool>("retraction_hop_enabled");
}
}
if (comb_ != nullptr && ! bypass_combing)
{
CombPaths combPaths;
// Divide by 2 to get the radius
// Multiply by 2 because if two lines start and end points places very close then will be applied combing with retractions. (Ex: for brim)
const coord_t max_distance_ignored = mesh_or_extruder_settings.get<coord_t>("machine_nozzle_tip_outer_diameter") / 2 * 2;
bool unretract_before_last_travel_move = false; // Decided when calculating the combing
bool do_retracted_combing_move = false; // Decided when calculating the combing
const bool perform_z_hops = mesh_or_extruder_settings.get<bool>("retraction_hop_enabled");
const bool perform_z_hops_only_when_collides = mesh_or_extruder_settings.get<bool>("retraction_hop_only_when_collides");
combed = comb_->calc(
perform_z_hops,
perform_z_hops_only_when_collides,
*extruder,
last_planned_position_.value().toPoint2LL(),
p,
combPaths,
was_inside_,
is_inside_,
max_distance_ignored,
unretract_before_last_travel_move,
do_retracted_combing_move);
if (combed)
{
bool retract = path->retract || ((combPaths.size() > 1 || do_retracted_combing_move) && retraction_enable);
if (! retract)
{ // check whether we want to retract
if (combPaths.throughAir)
{
retract = retraction_enable;
}
else
{
for (CombPath& combPath : combPaths)
{ // retract when path moves through a boundary
if (combPath.cross_boundary)
{
retract = retraction_enable;
break;
}
}
}
}
const coord_t maximum_travel_resolution = mesh_or_extruder_settings.get<coord_t>("meshfix_maximum_travel_resolution");
coord_t distance = 0;
Point2LL last_point((last_planned_position_) ? last_planned_position_.value().toPoint2LL() : Point2LL(0, 0));
for (CombPath& combPath : combPaths)
{ // add all comb paths (don't do anything special for paths which are moving through air)
if (combPath.empty())
{
continue;
}
for (Point2LL& comb_point : combPath)
{
if (path->points.empty() || (path->points.back() - comb_point).vSize2() > maximum_travel_resolution * maximum_travel_resolution)
{
path->points.push_back(comb_point);
distance += vSize(last_point - comb_point);
last_point = comb_point;
}
}
distance += vSize(last_point - p);
const coord_t retract_threshold = mesh_or_extruder_settings.get<coord_t>("retraction_combing_max_distance");
path->retract = retract || (retract_threshold > 0 && distance > retract_threshold && retraction_enable);
// don't perform a z-hop
}
// Whether to unretract before the last travel move of the travel path, which comes before the wall to be printed.
// This should be true when traveling towards an outer wall to make sure that the unretraction will happen before the
// last travel move BEFORE going to that wall. This way, the nozzle doesn't sit still on top of the outer wall's
// path while it is unretracting, avoiding possible blips.
path->unretract_before_last_travel_move = path->retract && unretract_before_last_travel_move;
}
}
if (force_retract == ForceRetract::NOT_RETRACTED)
{
path->retract = false;
}
// CURA-6675:
// Retraction Minimal Travel Distance should work for all travel moves. If the travel move is shorter than the
// Retraction Minimal Travel Distance, retraction should be disabled.
if (! is_first_travel_of_layer && last_planned_position_ && shorterThen(last_planned_position_.value().toPoint2LL() - p, retraction_config.retraction_min_travel_distance))
{
path->retract = false;
path->perform_z_hop = false;
}
// no combing? retract only when path is not shorter than minimum travel distance
if (! combed && ! is_first_travel_of_layer && last_planned_position_
&& ! shorterThen(last_planned_position_.value().toPoint2LL() - p, retraction_config.retraction_min_travel_distance))
{
if (was_inside_) // when the previous location was from printing something which is considered inside (not support or prime tower etc)
{ // then move inside the printed part, so that we don't ooze on the outer wall while retraction, but on the inside of the print.
assert(extruder != nullptr);
coord_t innermost_wall_line_width
= mesh_or_extruder_settings.get<coord_t>((mesh_or_extruder_settings.get<size_t>("wall_line_count") > 1) ? "wall_line_width_x" : "wall_line_width_0");
if (layer_nr_ == 0)
{
innermost_wall_line_width *= mesh_or_extruder_settings.get<Ratio>("initial_layer_line_width_factor");
}
moveInsideCombBoundary(innermost_wall_line_width, std::nullopt, path);
}
path->retract = retraction_enable;
path->perform_z_hop = retraction_enable && mesh_or_extruder_settings.get<bool>("retraction_hop_enabled");
}
// must start new travel path as retraction can be enabled or not depending on path length, etc.
forceNewPathStart();
GCodePath& ret = addTravel_simple(p, path);
was_inside_ = is_inside_;
return ret;
}
GCodePath& LayerPlan::addTravel_simple(const Point2LL& p, GCodePath* path)
{
bool is_first_travel_of_layer = ! static_cast<bool>(last_planned_position_);
if (is_first_travel_of_layer)
{ // spiralize calls addTravel_simple directly as the first travel move in a layer
first_travel_destination_ = p;
first_travel_destination_is_inside_ = is_inside_;
}
if (path == nullptr)
{
path = getLatestPathWithConfig(configs_storage_.travel_config_per_extruder[getExtruder()], SpaceFillType::None);
}
path->points.push_back(p);
last_planned_position_ = p;
return *path;
}
void LayerPlan::planPrime(double prime_blob_wipe_length)
{
forceNewPathStart();
GCodePath& prime_travel = addTravel_simple(getLastPlannedPositionOrStartingPosition() + Point2LL(0, MM2INT(prime_blob_wipe_length)));
prime_travel.retract = false;
prime_travel.perform_z_hop = false;
prime_travel.perform_prime = true;
forceNewPathStart();
}
void LayerPlan::setGeneratedInfillLines(const SliceMeshStorage* mesh, const MixedLinesSet& infill_lines)
{
infill_lines_[mesh].push_back(infill_lines);
}
const MixedLinesSet LayerPlan::getGeneratedInfillLines(const SliceMeshStorage* mesh) const
{
auto iterator = infill_lines_.find(mesh);
if (iterator != infill_lines_.end())
{
return iterator->second;
}
return MixedLinesSet();
}
void LayerPlan::addExtrusionMove(
const Point3LL& p,
const GCodePathConfig& config,
const SpaceFillType space_fill_type,
const Ratio& flow,
const Ratio width_factor,
const bool spiralize,
const Ratio speed_factor,
const double fan_speed,
const bool travel_to_z)
{
GCodePath* path = getLatestPathWithConfig(config, space_fill_type, config.z_offset, flow, width_factor, spiralize, speed_factor);
path->points.push_back(p);
path->setFanSpeed(fan_speed);
path->travel_to_z = travel_to_z;
if (! static_cast<bool>(first_extrusion_acc_jerk_))
{
first_extrusion_acc_jerk_ = std::make_pair(path->config.getAcceleration(), path->config.getJerk());
}
last_planned_position_ = p;
}
void LayerPlan::addExtrusionMoveWithGradualOverhang(
const Point3LL& p,
const GCodePathConfig& config,
const SpaceFillType space_fill_type,
const Ratio& flow,
const Ratio width_factor,
const bool spiralize,
const Ratio speed_factor,
const double fan_speed,
const bool travel_to_z)
{
const auto add_extrusion_move = [&](const Point3LL& target, const std::optional<size_t> speed_region_index = std::nullopt)
{
const Ratio overhang_speed_factor = speed_region_index.has_value() ? overhang_masks_[speed_region_index.value()].speed_ratio : 1.0_r;
addExtrusionMove(target, config, space_fill_type, flow, width_factor, spiralize, speed_factor * overhang_speed_factor, fan_speed, travel_to_z);
};
const auto update_is_overhanging = [this](const Point3LL& target, std::optional<Point3LL> current_position, const bool is_overhanging = false)
{
if (is_overhanging != currently_overhanging_)
{
max_overhang_length_ = std::max(current_overhang_length_, max_overhang_length_);
current_overhang_length_ = 0;
}
if (is_overhanging && current_position.has_value())
{
current_overhang_length_ += (target - current_position.value()).vSize();
}
currently_overhanging_ = is_overhanging;
};
if (overhang_masks_.empty() || ! last_planned_position_.has_value())
{
// Unable to apply gradual overhanging (probably just disabled), just add the basic extrusion move
update_is_overhanging(p, last_planned_position_);
add_extrusion_move(p);
return;
}
// First, find the speed region where the segment starts
const Point3LL start = last_planned_position_.value();
const Point2LL start_flat = start.toPoint2LL();
size_t actual_speed_region_index = overhang_masks_.size() - 1; // Default to last region, which is infinity and beyond
for (const auto& [index, overhang_region] : overhang_masks_ | ranges::views::drop_last(1) | ranges::views::enumerate)
{
if (overhang_region.supported_region.inside(start_flat, true))
{
actual_speed_region_index = index;
break;
}
}
// Pre-calculate the intersections of the segment with all regions (except last one, you cannot intersect an infinite plane)
const Point3LL end = p;
const Point2LL end_flat = end.toPoint2LL();
const Point3LL vector = end - start;
std::vector<std::vector<float>> speed_regions_intersections;
speed_regions_intersections.reserve(overhang_masks_.size() - 1);
for (const OverhangMask& overhang_region : overhang_masks_ | ranges::views::drop_last(1))
{
std::vector<float> intersections = overhang_region.supported_region.intersectionsWithSegment(start_flat, end_flat);
ranges::stable_sort(intersections);
speed_regions_intersections.push_back(intersections);
}
const auto remove_previous_intersections = [&speed_regions_intersections](const float current_intersection)
{
for (std::vector<float>& intersections : speed_regions_intersections)
{
auto iterator = ranges::find_if(
intersections,
[¤t_intersection](const float next_intersection)
{
return next_intersection > current_intersection;
});
intersections.erase(intersections.begin(), iterator);
}
};
struct SegmentExtrusionMove
{
Point3LL position;
size_t speed_region_index;
};
std::vector<SegmentExtrusionMove> extrusion_moves;
// Now move along segment and split it where we cross speed regions
while (true)
{
// First, see if we cross either the border or our current region (go out) or the border of the inner region (go in)
auto get_first_intersection = [](const std::vector<float>* intersections) -> std::optional<float>
{
return intersections != nullptr && ! intersections->empty() ? std::make_optional(intersections->front()) : std::nullopt;
};
std::vector<float>* intersections_current_region
= actual_speed_region_index < speed_regions_intersections.size() ? &speed_regions_intersections[actual_speed_region_index] : nullptr;
const std::optional<float> first_intersection_current_region = get_first_intersection(intersections_current_region);
std::vector<float>* intersections_inner_region = actual_speed_region_index > 0 ? &speed_regions_intersections[actual_speed_region_index - 1] : nullptr;
const std::optional<float> first_intersection_inner_region = get_first_intersection(intersections_inner_region);
if (first_intersection_current_region.has_value() || first_intersection_inner_region.has_value())
{
float intersection_parameter;
size_t next_speed_region_index;
if (first_intersection_current_region.has_value()
&& (! first_intersection_inner_region.has_value() || first_intersection_inner_region.value() > first_intersection_current_region.value()))
{
// We crossed the border of the current region, which means we are getting out of it to an outer region
intersection_parameter = first_intersection_current_region.value();
next_speed_region_index = actual_speed_region_index + 1;
}
else
{
// We crossed the border of the inner region, which means we are getting inside of it
intersection_parameter = first_intersection_inner_region.value();
next_speed_region_index = actual_speed_region_index - 1;
}
// Move to intersection at current region speed
const Point3LL split_position = start + vector * intersection_parameter;
extrusion_moves.push_back(SegmentExtrusionMove{ split_position, actual_speed_region_index });
// Prepare for next move in different region
actual_speed_region_index = next_speed_region_index;
remove_previous_intersections(intersection_parameter);
}
else
{
// We cross no border, which means we can reach the end of the segment within the current speed region, so we are done
extrusion_moves.push_back(SegmentExtrusionMove{ p, actual_speed_region_index });
break;
}
}
// Filter out micro-segments
std::vector<SegmentExtrusionMove> extrusion_moves_filtered;
extrusion_moves_filtered.reserve(extrusion_moves.size());
Point3LL current_position = start;
for (const SegmentExtrusionMove& extrusion_move : extrusion_moves | ranges::views::drop_last(1))
{
if ((extrusion_move.position - current_position).vSize2() >= MINIMUM_SQUARED_LINE_LENGTH)
{
extrusion_moves_filtered.push_back(extrusion_move);
}
current_position = extrusion_move.position;
}
if (extrusion_moves_filtered.empty() || (extrusion_moves.back().position - current_position).vSize2() >= MINIMUM_SQUARED_LINE_LENGTH)
{
extrusion_moves_filtered.push_back(extrusion_moves.back());
}
else
{
extrusion_moves_filtered.back().position = extrusion_moves.back().position;
}
// Calculate max consecutive overhanging segment length
current_position = start;
for (const SegmentExtrusionMove& extrusion_move : extrusion_moves_filtered)
{
const bool is_overhanging = extrusion_move.speed_region_index > 0;
update_is_overhanging(extrusion_move.position, current_position, is_overhanging);
current_position = extrusion_move.position;
}
// Merge consecutive sub-segments that in the end have the same speed
std::vector<SegmentExtrusionMove> extrusion_moves_merged;
extrusion_moves_merged.reserve(extrusion_moves_filtered.size());
extrusion_moves_merged.push_back(extrusion_moves_filtered.front());
for (const SegmentExtrusionMove& extrusion_move : extrusion_moves_filtered | ranges::views::drop(1))
{
const Ratio previous_speed_factor = overhang_masks_[extrusion_moves_merged.back().speed_region_index].speed_ratio;
const Ratio next_speed_factor = overhang_masks_[extrusion_move.speed_region_index].speed_ratio;
if (next_speed_factor == previous_speed_factor)
{
extrusion_moves_merged.back().position = extrusion_move.position;
}
else
{
extrusion_moves_merged.push_back(extrusion_move);
}
}
// Finally, add extrusion moves
for (const SegmentExtrusionMove& extrusion_move : extrusion_moves_merged)
{
add_extrusion_move(extrusion_move.position, extrusion_move.speed_region_index);
}
}
template<class PathType>
void LayerPlan::addWipeTravel(const PathAdapter<PathType>& path, const coord_t wipe_distance, const bool backwards, const size_t start_index, const Point2LL& last_path_position)
{
if (path.size() >= 2 && wipe_distance > 0)
{
const int direction = backwards ? -1 : 1;
Point2LL p0 = last_path_position;
int distance_traversed = 0;
size_t index = start_index;
while (distance_traversed < wipe_distance)
{
index = static_cast<size_t>((index + direction + path.size()) % path.size());
if (index == start_index && distance_traversed == 0)
{
// Wall has a total circumference of 0. This loop would never end.
break;
}
const Point2LL& p1 = path.pointAt(index);
const int p0p1_dist = vSize(p1 - p0);
if (distance_traversed + p0p1_dist >= wipe_distance)
{
Point2LL vector = p1 - p0;
Point2LL half_way = p0 + normal(vector, wipe_distance - distance_traversed);
addTravel_simple(half_way);
}
else
{
addTravel_simple(p1);
}
distance_traversed += p0p1_dist;
p0 = p1;
}
forceNewPathStart();
}
}
void LayerPlan::addPolygon(
const Polygon& polygon,
int start_idx,
const bool backwards,
const Settings& settings,
const GCodePathConfig& config,
coord_t wall_0_wipe_dist,
bool spiralize,
const Ratio& flow_ratio,
const ForceRetract force_retract,
bool scarf_seam,
bool smooth_speed)
{
constexpr bool is_closed = true;
constexpr bool is_candidate_small_feature = false;
const PathAdapter path_adapter(polygon, config.getLineWidth());
Point2LL p0 = polygon[start_idx];
addTravel(p0, force_retract, config.z_offset);
const std::tuple<size_t, Point2LL> add_wall_result = addWallWithScarfSeam<Polygon>(
path_adapter,
start_idx,
settings,
config,
flow_ratio,
force_retract,
is_closed,
backwards,
is_candidate_small_feature,
scarf_seam,
smooth_speed,
[this, &config, &spiralize](
const PathAdapter<Polygon>& /*wall*/,
const size_t /*segment_index*/,
const Ratio& /*segment_start_ratio*/,
const Ratio& /*segment_end_ratio*/,
const Point3LL& /*start*/,
const Point3LL& end,
const Ratio& speed_factor,
const Ratio& actual_flow_ratio,
const Ratio& line_width_ratio,
const coord_t /*distance_to_bridge_start*/)
{
constexpr double fan_speed = GCodePathConfig::FAN_SPEED_DEFAULT;
constexpr bool travel_to_z = false;
addExtrusionMove(end, config, SpaceFillType::Polygons, actual_flow_ratio, line_width_ratio, spiralize, speed_factor, fan_speed, travel_to_z);
});
if (polygon.size() > 2)
{
addWipeTravel(path_adapter, wall_0_wipe_dist, backwards, get<0>(add_wall_result), get<1>(add_wall_result));
}
else
{
spdlog::warn("line added as polygon! (LayerPlan)");
}
}
void LayerPlan::addPolygonsByOptimizer(
const Shape& polygons,
const GCodePathConfig& config,
const Settings& settings,
const ZSeamConfig& z_seam_config,
coord_t wall_0_wipe_dist,
bool spiralize,
const Ratio flow_ratio,
const ForceRetract force_retract,
bool reverse_order,
const std::optional<Point2LL> start_near_location,
bool scarf_seam,
bool smooth_speed,
const std::shared_ptr<TextureDataProvider>& texture_data_provider)
{
if (polygons.empty())
{
return;
}
constexpr bool detect_loops = false;
constexpr Shape* combing_boundary = nullptr;
constexpr bool reverse_direction = false;
const std::unordered_multimap<const Polygon*, const Polygon*>& order_requirements = PathOrderOptimizer<const Polygon*>::no_order_requirements_;
constexpr bool group_outer_walls = false;
const Shape disallowed_areas_for_seams = {}; // <- The Mac compiler we use in builds can't handle this as a `constexpr`, put back when that's updated.
constexpr bool use_shortest_for_inner_walls = false;
const Shape overhang_areas = Shape(); // <- The Mac compiler we use in builds can't handle this as a `constexpr`, put back when that's updated.
PathOrderOptimizer<const Polygon*> orderOptimizer(
start_near_location.value_or(getLastPlannedPositionOrStartingPosition()),
z_seam_config,
detect_loops,
combing_boundary,
reverse_direction,
order_requirements,
group_outer_walls,
disallowed_areas_for_seams,
use_shortest_for_inner_walls,
overhang_areas,
texture_data_provider);
for (size_t poly_idx = 0; poly_idx < polygons.size(); poly_idx++)
{
orderOptimizer.addPolygon(&polygons[poly_idx]);
}
orderOptimizer.optimize();
addPolygonsInGivenOrder(
orderOptimizer.paths_,
config,
settings,
z_seam_config,
wall_0_wipe_dist,
spiralize,
flow_ratio,
force_retract,
reverse_order,
scarf_seam,
smooth_speed);
}
void LayerPlan::addInfillPolygonsByOptimizer(
const Shape& polygons,
OpenLinesSet& remaining_lines,
const GCodePathConfig& config,
const Settings& settings,
const bool add_extra_inwards_move,
const std::optional<Point2LL>& near_start_location,
const bool reverse_print_direction)
{
if (polygons.empty())
{
return;
}
const ZSeamConfig seam_config = ZSeamConfig();
constexpr bool detect_loops = false;
constexpr Shape* combing_boundary = nullptr;
PathOrderOptimizer<const Polygon*>
orderOptimizer(near_start_location.value_or(getLastPlannedPositionOrStartingPosition()), seam_config, detect_loops, combing_boundary, reverse_print_direction);
for (size_t poly_idx = 0; poly_idx < polygons.size(); poly_idx++)
{
orderOptimizer.addPolygon(&polygons[poly_idx]);
}
orderOptimizer.optimize();
if (! add_extra_inwards_move)
{
addTravel(orderOptimizer.paths_[0].vertices_->at(orderOptimizer.paths_[0].start_vertex_));
addPolygonsInGivenOrder(orderOptimizer.paths_, config, settings);
return;
}
// In order to add the inwards moves, we will have to un-close the polygons to open lines
for (const PathOrdering<const Polygon*>& ordered_polygon : orderOptimizer.paths_)
{
const Polygon& polygon = *ordered_polygon.vertices_;
const size_t start_index = ordered_polygon.start_vertex_;
ClosedPolyline split_polygon(polygon);
split_polygon.shiftVerticesToStartPoint(start_index);
remaining_lines.push_back(split_polygon.toPseudoOpenPolyline());
}
}
static constexpr double max_non_bridge_line_volume = MM2INT(100); // limit to accumulated "volume" of non-bridge lines which is proportional to distance x extrusion rate
void LayerPlan::addWallLine(
const PathAdapter<ExtrusionLine>& wall,
const size_t segment_index,
const Ratio& segment_start_ratio,