forked from MatterHackers/MatterSlice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfffProcessor.cs
1323 lines (1138 loc) · 47.4 KB
/
fffProcessor.cs
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
/*
This file is part of MatterSlice. A command line utility for
generating 3D printing GCode.
Copyright (C) 2013 David Braam
Copyright (c) 2014, Lars Brubaker
MatterSlice is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using MSClipperLib;
namespace MatterHackers.MatterSlice
{
using Pathfinding;
using QuadTree;
using Polygon = List<IntPoint>;
using Polygons = List<List<IntPoint>>;
// Fused Filament Fabrication processor.
public class fffProcessor
{
private long maxObjectHeight;
private int fileNumber;
private GCodeExport gcode = new GCodeExport();
private ConfigSettings config;
private Stopwatch timeKeeper = new Stopwatch();
private SimpleMeshCollection simpleMeshCollection = new SimpleMeshCollection();
private OptimizedMeshCollection optomizedMeshCollection;
private LayerDataStorage slicingData = new LayerDataStorage();
private GCodePathConfig skirtConfig = new GCodePathConfig("skirtConfig");
private GCodePathConfig inset0Config = new GCodePathConfig("inset0Config")
{
DoSeamHiding = true,
};
private GCodePathConfig insetXConfig = new GCodePathConfig("insetXConfig");
private GCodePathConfig fillConfig = new GCodePathConfig("fillConfig");
private GCodePathConfig topFillConfig = new GCodePathConfig("topFillConfig");
private GCodePathConfig bottomFillConfig = new GCodePathConfig("bottomFillConfig");
private GCodePathConfig airGappedBottomConfig = new GCodePathConfig("airGappedBottomConfig");
private GCodePathConfig bridgeConfig = new GCodePathConfig("bridgeConfig");
private GCodePathConfig supportNormalConfig = new GCodePathConfig("supportNormalConfig");
private GCodePathConfig supportInterfaceConfig = new GCodePathConfig("supportInterfaceConfig");
public fffProcessor(ConfigSettings config)
{
this.config = config;
fileNumber = 1;
maxObjectHeight = 0;
}
public bool SetTargetFile(string filename)
{
gcode.SetFilename(filename);
{
gcode.WriteComment("Generated with MatterSlice {0}".FormatWith(ConfigConstants.VERSION));
}
return gcode.IsOpened();
}
public void DoProcessing()
{
if (!gcode.IsOpened()
|| simpleMeshCollection.SimpleMeshes.Count == 0)
{
return;
}
timeKeeper.Restart();
LogOutput.Log("Analyzing and optimizing model...\n");
optomizedMeshCollection = new OptimizedMeshCollection(simpleMeshCollection);
if (MatterSlice.Canceled)
{
return;
}
optomizedMeshCollection.SetPositionAndSize(simpleMeshCollection, config.PositionToPlaceObjectCenter_um.X, config.PositionToPlaceObjectCenter_um.Y, -config.BottomClipAmount_um, config.CenterObjectInXy);
for (int meshIndex = 0; meshIndex < simpleMeshCollection.SimpleMeshes.Count; meshIndex++)
{
LogOutput.Log(" Face counts: {0} . {1} {2:0.0}%\n".FormatWith((int)simpleMeshCollection.SimpleMeshes[meshIndex].faceTriangles.Count, (int)optomizedMeshCollection.OptimizedMeshes[meshIndex].facesTriangle.Count, (double)(optomizedMeshCollection.OptimizedMeshes[meshIndex].facesTriangle.Count) / (double)(simpleMeshCollection.SimpleMeshes[meshIndex].faceTriangles.Count) * 100));
LogOutput.Log(" Vertex counts: {0} . {1} {2:0.0}%\n".FormatWith((int)simpleMeshCollection.SimpleMeshes[meshIndex].faceTriangles.Count * 3, (int)optomizedMeshCollection.OptimizedMeshes[meshIndex].vertices.Count, (double)(optomizedMeshCollection.OptimizedMeshes[meshIndex].vertices.Count) / (double)(simpleMeshCollection.SimpleMeshes[meshIndex].faceTriangles.Count * 3) * 100));
}
LogOutput.Log("Optimize model {0:0.0}s \n".FormatWith(timeKeeper.Elapsed.TotalSeconds));
timeKeeper.Reset();
Stopwatch timeKeeperTotal = new Stopwatch();
timeKeeperTotal.Start();
preSetup(config.ExtrusionWidth_um);
SliceModels(slicingData);
ProcessSliceData(slicingData);
if (MatterSlice.Canceled)
{
return;
}
WriteGCode(slicingData);
if (MatterSlice.Canceled)
{
return;
}
LogOutput.logProgress("process", 1, 1); //Report to the GUI that a file has been fully processed.
LogOutput.Log("Total time elapsed {0:0.00}s.\n".FormatWith(timeKeeperTotal.Elapsed.TotalSeconds));
}
public bool LoadStlFile(string input_filename)
{
preSetup(config.ExtrusionWidth_um);
timeKeeper.Restart();
LogOutput.Log("Loading {0} from disk...\n".FormatWith(input_filename));
if (!SimpleMeshCollection.LoadModelFromFile(simpleMeshCollection, input_filename, config.ModelRotationMatrix))
{
LogOutput.LogError("Failed to load model: {0}\n".FormatWith(input_filename));
return false;
}
LogOutput.Log("Loaded from disk in {0:0.0}s\n".FormatWith(timeKeeper.Elapsed.TotalSeconds));
return true;
}
public void finalize()
{
if (!gcode.IsOpened())
{
return;
}
gcode.Finalize(maxObjectHeight, config.TravelSpeed, config.EndCode);
gcode.Close();
}
private void preSetup(int extrusionWidth)
{
skirtConfig.SetData(config.InsidePerimetersSpeed, extrusionWidth, "SKIRT");
inset0Config.SetData(config.OutsidePerimeterSpeed, config.OutsideExtrusionWidth_um, "WALL-OUTER");
insetXConfig.SetData(config.InsidePerimetersSpeed, extrusionWidth, "WALL-INNER");
fillConfig.SetData(config.InfillSpeed, extrusionWidth, "FILL", false);
topFillConfig.SetData(config.TopInfillSpeed, extrusionWidth, "TOP-FILL", false);
bottomFillConfig.SetData(config.InfillSpeed, extrusionWidth, "BOTTOM-FILL", false);
airGappedBottomConfig.SetData(config.FirstLayerSpeed, extrusionWidth, "AIR-GAP", false);
bridgeConfig.SetData(config.BridgeSpeed, extrusionWidth, "BRIDGE");
supportNormalConfig.SetData(config.SupportMaterialSpeed, extrusionWidth, "SUPPORT");
supportInterfaceConfig.SetData(config.SupportMaterialSpeed - 1, extrusionWidth, "SUPPORT-INTERFACE");
for (int extruderIndex = 0; extruderIndex < ConfigConstants.MAX_EXTRUDERS; extruderIndex++)
{
gcode.SetExtruderOffset(extruderIndex, config.ExtruderOffsets[extruderIndex], -config.ZOffset_um);
}
gcode.SetRetractionSettings(config.RetractionOnTravel, config.RetractionSpeed, config.RetractionOnExtruderSwitch, config.MinimumExtrusionBeforeRetraction, config.RetractionZHop, config.WipeAfterRetraction, config.UnretractExtraExtrusion, config.UnretractExtraOnExtruderSwitch);
gcode.SetToolChangeCode(config.ToolChangeCode, config.BeforeToolchangeCode);
gcode.SetLayerChangeCode(config.LayerChangeCode);
}
private void SliceModels(LayerDataStorage slicingData)
{
timeKeeper.Restart();
#if false
optomizedModel.saveDebugSTL("debug_output.stl");
#endif
LogOutput.Log("Slicing model...\n");
List<ExtruderData> extruderList = new List<ExtruderData>();
for (int optimizedMeshIndex = 0; optimizedMeshIndex < optomizedMeshCollection.OptimizedMeshes.Count; optimizedMeshIndex++)
{
ExtruderData extruderData = new ExtruderData(optomizedMeshCollection.OptimizedMeshes[optimizedMeshIndex], config);
extruderList.Add(extruderData);
}
#if false
slicerList[0].DumpSegmentsToGcode("Volume 0 Segments.gcode");
slicerList[0].DumpPolygonsToGcode("Volume 0 Polygons.gcode");
//slicerList[0].DumpPolygonsToHTML("Volume 0 Polygons.html");
#endif
LogOutput.Log("Sliced model in {0:0.0}s\n".FormatWith(timeKeeper.Elapsed.TotalSeconds));
timeKeeper.Restart();
slicingData.modelSize = optomizedMeshCollection.size_um;
slicingData.modelMin = optomizedMeshCollection.minXYZ_um;
slicingData.modelMax = optomizedMeshCollection.maxXYZ_um;
var extraPathingConsideration = new Polygons();
foreach (var polygons in slicingData.wipeShield)
{
extraPathingConsideration.AddRange(polygons);
}
extraPathingConsideration.AddRange(slicingData.wipeTower);
for (int extruderIndex = 0; extruderIndex < extruderList.Count; extruderIndex++)
{
slicingData.Extruders.Add(new ExtruderLayers());
slicingData.Extruders[extruderIndex].InitializeLayerData(extruderList[extruderIndex], config, extruderIndex, extruderList.Count, extraPathingConsideration);
if (config.EnableRaft)
{
//Add the raft offset to each layer.
for (int layerIndex = 0; layerIndex < slicingData.Extruders[extruderIndex].Layers.Count; layerIndex++)
{
slicingData.Extruders[extruderIndex].Layers[layerIndex].LayerZ += config.RaftBaseThickness_um + config.RaftInterfaceThicknes_um;
}
}
}
LogOutput.Log("Generated layer parts in {0:0.0}s\n".FormatWith(timeKeeper.Elapsed.TotalSeconds));
timeKeeper.Restart();
}
private void ProcessSliceData(LayerDataStorage slicingData)
{
if (config.ContinuousSpiralOuterPerimeter)
{
config.NumberOfTopLayers = 0;
config.InfillPercent = 0;
}
MultiExtruders.ProcessBooleans(slicingData.Extruders, config.BooleanOpperations);
config.SetExtruderCount(slicingData.Extruders.Count);
MultiExtruders.RemoveExtruderIntersections(slicingData.Extruders);
MultiExtruders.OverlapMultipleExtrudersSlightly(slicingData.Extruders, config.MultiExtruderOverlapPercent);
#if False
LayerPart.dumpLayerparts(slicingData, "output.html");
#endif
if (config.GenerateSupport && !config.ContinuousSpiralOuterPerimeter)
{
LogOutput.Log("Generating support map...\n");
slicingData.support = new NewSupport(config, slicingData.Extruders, 1);
}
slicingData.CreateIslandData();
int totalLayers = slicingData.Extruders[0].Layers.Count;
if (config.outputOnlyFirstLayer)
{
totalLayers = 1;
}
#if DEBUG
for (int extruderIndex = 1; extruderIndex < slicingData.Extruders.Count; extruderIndex++)
{
if (totalLayers != slicingData.Extruders[extruderIndex].Layers.Count)
{
throw new Exception("All the extruders must have the same number of layers (they just can have empty layers).");
}
}
#endif
for (int layerIndex = 0; layerIndex < totalLayers; layerIndex++)
{
for (int extruderIndex = 0; extruderIndex < slicingData.Extruders.Count; extruderIndex++)
{
if (MatterSlice.Canceled)
{
return;
}
int insetCount = config.NumberOfPerimeters;
if (config.ContinuousSpiralOuterPerimeter && (int)(layerIndex) < config.NumberOfBottomLayers && layerIndex % 2 == 1)
{
//Add extra insets every 2 layers when spiralizing, this makes bottoms of cups watertight.
insetCount += 1;
}
SliceLayer layer = slicingData.Extruders[extruderIndex].Layers[layerIndex];
if (layerIndex == 0)
{
layer.GenerateInsets(config.FirstLayerExtrusionWidth_um, config.FirstLayerExtrusionWidth_um, insetCount, config.ExpandThinWalls && !config.ContinuousSpiralOuterPerimeter);
}
else
{
layer.GenerateInsets(config.ExtrusionWidth_um, config.OutsideExtrusionWidth_um, insetCount, config.ExpandThinWalls && !config.ContinuousSpiralOuterPerimeter);
}
}
LogOutput.Log("Creating Insets {0}/{1}\n".FormatWith(layerIndex + 1, totalLayers));
}
slicingData.CreateWipeShield(totalLayers, config);
LogOutput.Log("Generated inset in {0:0.0}s\n".FormatWith(timeKeeper.Elapsed.TotalSeconds));
timeKeeper.Restart();
for (int layerIndex = 0; layerIndex < totalLayers; layerIndex++)
{
if (MatterSlice.Canceled)
{
return;
}
//Only generate bottom and top layers and infill for the first X layers when spiralize is chosen.
if (!config.ContinuousSpiralOuterPerimeter || (int)(layerIndex) < config.NumberOfBottomLayers)
{
for (int extruderIndex = 0; extruderIndex < slicingData.Extruders.Count; extruderIndex++)
{
if (layerIndex == 0)
{
slicingData.Extruders[extruderIndex].GenerateTopAndBottoms(layerIndex, config.FirstLayerExtrusionWidth_um, config.FirstLayerExtrusionWidth_um, config.NumberOfBottomLayers, config.NumberOfTopLayers);
}
else
{
slicingData.Extruders[extruderIndex].GenerateTopAndBottoms(layerIndex, config.ExtrusionWidth_um, config.OutsideExtrusionWidth_um, config.NumberOfBottomLayers, config.NumberOfTopLayers);
}
}
}
LogOutput.Log("Creating Top & Bottom Layers {0}/{1}\n".FormatWith(layerIndex + 1, totalLayers));
}
LogOutput.Log("Generated top bottom layers in {0:0.0}s\n".FormatWith(timeKeeper.Elapsed.TotalSeconds));
timeKeeper.Restart();
slicingData.CreateWipeTower(totalLayers, config);
if (config.EnableRaft)
{
slicingData.GenerateRaftOutlines(config.RaftExtraDistanceAroundPart_um, config);
slicingData.GenerateSkirt(
config.SkirtDistance_um + config.RaftBaseExtrusionWidth_um,
config.RaftBaseExtrusionWidth_um,
config.NumberOfSkirtLoops,
config.NumberOfBrimLoops,
config.SkirtMinLength_um,
config);
}
else
{
slicingData.GenerateSkirt(
config.SkirtDistance_um,
config.FirstLayerExtrusionWidth_um,
config.NumberOfSkirtLoops,
config.NumberOfBrimLoops,
config.SkirtMinLength_um,
config);
}
}
private void WriteGCode(LayerDataStorage slicingData)
{
gcode.WriteComment("filamentDiameter = {0}".FormatWith(config.FilamentDiameter));
gcode.WriteComment("extrusionWidth = {0}".FormatWith(config.ExtrusionWidth));
gcode.WriteComment("firstLayerExtrusionWidth = {0}".FormatWith(config.FirstLayerExtrusionWidth));
gcode.WriteComment("layerThickness = {0}".FormatWith(config.LayerThickness));
if (config.EnableRaft)
{
gcode.WriteComment("firstLayerThickness = {0}".FormatWith(config.RaftBaseThickness_um / 1000.0));
}
else
{
gcode.WriteComment("firstLayerThickness = {0}".FormatWith(config.FirstLayerThickness));
}
if (fileNumber == 1)
{
gcode.WriteCode(config.StartCode);
}
else
{
gcode.WriteFanCommand(0);
gcode.ResetExtrusionValue();
gcode.WriteRetraction();
gcode.SetZ(maxObjectHeight + 5000);
gcode.WriteMove(gcode.GetPosition(), config.TravelSpeed, 0);
gcode.WriteMove(new IntPoint(slicingData.modelMin.X, slicingData.modelMin.Y, gcode.CurrentZ), config.TravelSpeed, 0);
}
fileNumber++;
int totalLayers = slicingData.Extruders[0].Layers.Count;
if (config.outputOnlyFirstLayer)
{
totalLayers = 1;
}
// let's remove any of the layers on top that are empty
{
for (int layerIndex = totalLayers - 1; layerIndex >= 0; layerIndex--)
{
bool layerHasData = false;
foreach (ExtruderLayers currentExtruder in slicingData.Extruders)
{
SliceLayer currentLayer = currentExtruder.Layers[layerIndex];
for (int partIndex = 0; partIndex < currentExtruder.Layers[layerIndex].Islands.Count; partIndex++)
{
LayerIsland currentIsland = currentLayer.Islands[partIndex];
if (currentIsland.IslandOutline.Count > 0)
{
layerHasData = true;
break;
}
}
}
if (layerHasData)
{
break;
}
totalLayers--;
}
}
gcode.WriteComment("Layer count: {0}".FormatWith(totalLayers));
// keep the raft generation code inside of raft
slicingData.WriteRaftGCodeIfRequired(gcode, config);
for (int layerIndex = 0; layerIndex < totalLayers; layerIndex++)
{
if (MatterSlice.Canceled)
{
return;
}
if (config.outputOnlyFirstLayer && layerIndex > 0)
{
break;
}
LogOutput.Log("Writing Layers {0}/{1}\n".FormatWith(layerIndex + 1, totalLayers));
LogOutput.logProgress("export", layerIndex + 1, totalLayers);
if (layerIndex == 0)
{
skirtConfig.SetData(config.FirstLayerSpeed, config.FirstLayerExtrusionWidth_um, "SKIRT");
inset0Config.SetData(config.FirstLayerSpeed, config.FirstLayerExtrusionWidth_um, "WALL-OUTER");
insetXConfig.SetData(config.FirstLayerSpeed, config.FirstLayerExtrusionWidth_um, "WALL-INNER");
fillConfig.SetData(config.FirstLayerSpeed, config.FirstLayerExtrusionWidth_um, "FILL", false);
topFillConfig.SetData(config.FirstLayerSpeed, config.FirstLayerExtrusionWidth_um, "TOP-FILL", false);
bottomFillConfig.SetData(config.FirstLayerSpeed, config.FirstLayerExtrusionWidth_um, "BOTTOM-FILL", false);
airGappedBottomConfig.SetData(config.FirstLayerSpeed, config.FirstLayerExtrusionWidth_um, "AIR-GAP", false);
bridgeConfig.SetData(config.FirstLayerSpeed, config.FirstLayerExtrusionWidth_um, "BRIDGE");
supportNormalConfig.SetData(config.FirstLayerSpeed, config.SupportExtrusionWidth_um, "SUPPORT");
supportInterfaceConfig.SetData(config.FirstLayerSpeed, config.ExtrusionWidth_um, "SUPPORT-INTERFACE");
}
else
{
skirtConfig.SetData(config.InsidePerimetersSpeed, config.ExtrusionWidth_um, "SKIRT");
inset0Config.SetData(config.OutsidePerimeterSpeed, config.OutsideExtrusionWidth_um, "WALL-OUTER");
insetXConfig.SetData(config.InsidePerimetersSpeed, config.ExtrusionWidth_um, "WALL-INNER");
fillConfig.SetData(config.InfillSpeed, config.ExtrusionWidth_um, "FILL", false);
topFillConfig.SetData(config.TopInfillSpeed, config.ExtrusionWidth_um, "TOP-FILL", false);
bottomFillConfig.SetData(config.InfillSpeed, config.ExtrusionWidth_um, "BOTTOM-FILL", false);
airGappedBottomConfig.SetData(config.FirstLayerSpeed, config.ExtrusionWidth_um, "AIR-GAP", false);
bridgeConfig.SetData(config.BridgeSpeed, config.ExtrusionWidth_um, "BRIDGE");
supportNormalConfig.SetData(config.SupportMaterialSpeed, config.SupportExtrusionWidth_um, "SUPPORT");
supportInterfaceConfig.SetData(config.FirstLayerSpeed - 1, config.ExtrusionWidth_um, "SUPPORT-INTERFACE");
}
if (layerIndex == 0)
{
gcode.SetExtrusion(config.FirstLayerThickness_um, config.FilamentDiameter_um, config.ExtrusionMultiplier);
}
else
{
gcode.SetExtrusion(config.LayerThickness_um, config.FilamentDiameter_um, config.ExtrusionMultiplier);
}
GCodePlanner layerGcodePlanner = new GCodePlanner(gcode, config.TravelSpeed, config.MinimumTravelToCauseRetraction_um, config.PerimeterStartEndOverlapRatio);
if (layerIndex == 0
&& config.RetractionZHop > 0)
{
layerGcodePlanner.ForceRetract();
}
// get the correct height for this layer
int z = config.FirstLayerThickness_um + layerIndex * config.LayerThickness_um;
if (config.EnableRaft)
{
z += config.RaftBaseThickness_um + config.RaftInterfaceThicknes_um + config.RaftSurfaceLayers * config.RaftSurfaceThickness_um;
if (layerIndex == 0)
{
// We only raise the first layer of the print up by the air gap.
// To give it:
// Less press into the raft
// More time to cool
// more surface area to air while extruding
z += config.RaftAirGap_um;
}
}
gcode.SetZ(z);
gcode.LayerChanged(layerIndex);
// We only create the skirt if we are on layer 0.
if (layerIndex == 0 && !config.ShouldGenerateRaft())
{
QueueSkirtToGCode(slicingData, layerGcodePlanner, layerIndex);
}
int fanSpeedPercent = GetFanSpeed(layerIndex, layerGcodePlanner);
for (int extruderIndex = 0; extruderIndex < config.MaxExtruderCount(); extruderIndex++)
{
int prevExtruder = layerGcodePlanner.GetExtruder();
bool extruderChanged = layerGcodePlanner.SetExtruder(extruderIndex);
if (extruderChanged
&& slicingData.HaveWipeTower(config)
&& layerIndex < slicingData.LastLayerWithChange(config))
{
slicingData.PrimeOnWipeTower(extruderIndex, layerIndex, layerGcodePlanner, fillConfig, config);
//Make sure we wipe the old extruder on the wipe tower.
layerGcodePlanner.QueueTravel(slicingData.wipePoint - config.ExtruderOffsets[prevExtruder] + config.ExtruderOffsets[layerGcodePlanner.GetExtruder()]);
}
if (layerIndex == 0)
{
QueueExtruderLayerToGCode(slicingData, layerGcodePlanner, extruderIndex, layerIndex, config.FirstLayerExtrusionWidth_um, z);
}
else
{
QueueExtruderLayerToGCode(slicingData, layerGcodePlanner, extruderIndex, layerIndex, config.ExtrusionWidth_um, z);
}
if (config.AvoidCrossingPerimeters
&& slicingData.Extruders != null
&& slicingData.Extruders.Count > extruderIndex)
{
// set the path planner to avoid islands
SliceLayer layer = slicingData.Extruders[extruderIndex].Layers[layerIndex];
layerGcodePlanner.PathFinder = layer.PathFinder;
}
if (slicingData.support != null)
{
if ((config.SupportExtruder <= 0 && extruderIndex == 0)
|| config.SupportExtruder == extruderIndex)
{
if (slicingData.support.QueueNormalSupportLayer(config, layerGcodePlanner, layerIndex, supportNormalConfig))
{
// we move out of the island so we aren't in it.
islandCurrentlyInside = null;
}
}
if ((config.SupportInterfaceExtruder <= 0 && extruderIndex == 0)
|| config.SupportInterfaceExtruder == extruderIndex)
{
if(slicingData.support.QueueInterfaceSupportLayer(config, layerGcodePlanner, layerIndex, supportInterfaceConfig))
{
// we move out of the island so we aren't in it.
islandCurrentlyInside = null;
}
}
}
}
slicingData.EnsureWipeTowerIsSolid(layerIndex, layerGcodePlanner, fillConfig, config);
if (slicingData.support != null)
{
z += config.SupportAirGap_um;
gcode.SetZ(z);
for (int extruderIndex = 0; extruderIndex < slicingData.Extruders.Count; extruderIndex++)
{
QueueAirGappedExtruderLayerToGCode(slicingData, layerGcodePlanner, extruderIndex, layerIndex, config.ExtrusionWidth_um, z);
}
slicingData.support.QueueAirGappedBottomLayer(config, layerGcodePlanner, layerIndex, airGappedBottomConfig);
}
//Finish the layer by applying speed corrections for minimum layer times.
layerGcodePlanner.ForceMinimumLayerTime(config.MinimumLayerTimeSeconds, config.MinimumPrintingSpeed);
gcode.WriteFanCommand(fanSpeedPercent);
int currentLayerThickness_um = config.LayerThickness_um;
if (layerIndex <= 0)
{
currentLayerThickness_um = config.FirstLayerThickness_um;
}
layerGcodePlanner.WriteQueuedGCode(currentLayerThickness_um, fanSpeedPercent, config.BridgeFanSpeedPercent);
}
LogOutput.Log("Wrote layers in {0:0.00}s.\n".FormatWith(timeKeeper.Elapsed.TotalSeconds));
timeKeeper.Restart();
gcode.TellFileSize();
gcode.WriteFanCommand(0);
//Store the object height for when we are printing multiple objects, as we need to clear every one of them when moving to the next position.
maxObjectHeight = Math.Max(maxObjectHeight, slicingData.modelSize.Z);
}
void QueuePerimeterWithMergOverlaps(Polygon perimeterToCheckForMerge, int layerIndex, GCodePlanner gcodeLayer, GCodePathConfig config)
{
Polygons pathsWithOverlapsRemoved = null;
bool pathHadOverlaps = false;
bool pathIsClosed = true;
if (perimeterToCheckForMerge.Count > 2)
{
pathHadOverlaps = perimeterToCheckForMerge.MergePerimeterOverlaps(config.lineWidth_um, out pathsWithOverlapsRemoved, pathIsClosed)
&& pathsWithOverlapsRemoved.Count > 0;
}
if (pathHadOverlaps)
{
bool oldClosedLoop = config.closedLoop;
config.closedLoop = false;
QueuePolygonsConsideringSupport(layerIndex, gcodeLayer, pathsWithOverlapsRemoved, config, SupportWriteType.UnsupportedAreas);
config.closedLoop = oldClosedLoop;
}
else
{
QueuePolygonsConsideringSupport(layerIndex, gcodeLayer, new Polygons() { perimeterToCheckForMerge }, config, SupportWriteType.UnsupportedAreas);
}
}
private int GetFanSpeed(int layerIndex, GCodePlanner gcodeLayer)
{
int fanSpeedPercent = config.FanSpeedMinPercent;
if (gcodeLayer.getExtrudeSpeedFactor() <= 50)
{
fanSpeedPercent = config.FanSpeedMaxPercent;
}
else
{
int n = gcodeLayer.getExtrudeSpeedFactor() - 50;
fanSpeedPercent = config.FanSpeedMinPercent * n / 50 + config.FanSpeedMaxPercent * (50 - n) / 50;
}
if (layerIndex < config.FirstLayerToAllowFan)
{
// Don't allow the fan below this layer
fanSpeedPercent = 0;
}
return fanSpeedPercent;
}
private void QueueSkirtToGCode(LayerDataStorage slicingData, GCodePlanner gcodeLayer, int layerIndex)
{
if (slicingData.skirt.Count > 0
&& slicingData.skirt[0].Count > 0)
{
IntPoint lowestPoint = slicingData.skirt[0][0];
// lets make sure we start with the most outside loop
foreach (Polygon polygon in slicingData.skirt)
{
foreach (IntPoint position in polygon)
{
if (position.Y < lowestPoint.Y)
{
lowestPoint = polygon[0];
}
}
}
gcodeLayer.QueueTravel(lowestPoint);
}
gcodeLayer.QueuePolygonsByOptimizer(slicingData.skirt, skirtConfig);
}
LayerIsland islandCurrentlyInside = null;
//Add a single layer from a single extruder to the GCode
private void QueueExtruderLayerToGCode(LayerDataStorage slicingData, GCodePlanner layerGcodePlanner, int extruderIndex, int layerIndex, int extrusionWidth_um, long currentZ_um)
{
if (extruderIndex > slicingData.Extruders.Count - 1)
{
return;
}
SliceLayer layer = slicingData.Extruders[extruderIndex].Layers[layerIndex];
if (layer.AllOutlines.Count == 0
&& config.WipeShieldDistanceFromObject == 0)
{
// don't do anything on this layer
return;
}
if (slicingData.wipeShield.Count > 0 && slicingData.Extruders.Count > 1)
{
layerGcodePlanner.ForceRetract();
layerGcodePlanner.QueuePolygonsByOptimizer(slicingData.wipeShield[layerIndex], skirtConfig);
layerGcodePlanner.ForceRetract();
}
PathOrderOptimizer islandOrderOptimizer = new PathOrderOptimizer(new IntPoint());
for (int partIndex = 0; partIndex < layer.Islands.Count; partIndex++)
{
if (config.ContinuousSpiralOuterPerimeter && partIndex > 0)
{
continue;
}
if (config.ExpandThinWalls && !config.ContinuousSpiralOuterPerimeter)
{
islandOrderOptimizer.AddPolygon(layer.Islands[partIndex].IslandOutline[0]);
}
else
{
islandOrderOptimizer.AddPolygon(layer.Islands[partIndex].InsetToolPaths[0][0]);
}
}
islandOrderOptimizer.Optimize();
List<Polygons> bottomFillIslandPolygons = new List<Polygons>();
for (int islandOrderIndex = 0; islandOrderIndex < islandOrderOptimizer.bestIslandOrderIndex.Count; islandOrderIndex++)
{
if (config.ContinuousSpiralOuterPerimeter && islandOrderIndex > 0)
{
continue;
}
LayerIsland island = layer.Islands[islandOrderOptimizer.bestIslandOrderIndex[islandOrderIndex]];
if (config.AvoidCrossingPerimeters)
{
MoveToIsland(layerGcodePlanner, layer, island);
}
else
{
if(config.RetractWhenChangingIslands) layerGcodePlanner.ForceRetract();
}
Polygons fillPolygons = new Polygons();
Polygons topFillPolygons = new Polygons();
Polygons bridgePolygons = new Polygons();
Polygons bottomFillPolygons = new Polygons();
CalculateInfillData(slicingData, extruderIndex, layerIndex, island, bottomFillPolygons, fillPolygons, topFillPolygons, bridgePolygons);
bottomFillIslandPolygons.Add(bottomFillPolygons);
if (config.NumberOfPerimeters > 0)
{
if (config.ContinuousSpiralOuterPerimeter
&& layerIndex >= config.NumberOfBottomLayers)
{
inset0Config.spiralize = true;
}
// Put all the insets into a new list so we can keep track of what has been printed.
// The island could be a rectangle with 4 screew holes. So, with 3 perimeters that colud be the outside 3 + the foles 4 * 3, 15 polygons.
List<Polygons> insetsForThisIsland = new List<Polygons>(island.InsetToolPaths.Count);
for (int insetIndex = 0; insetIndex < island.InsetToolPaths.Count; insetIndex++)
{
insetsForThisIsland.Add(new Polygons());
for (int polygonIndex = 0; polygonIndex < island.InsetToolPaths[insetIndex].Count; polygonIndex++)
{
if (island.InsetToolPaths[insetIndex][polygonIndex].Count > 0)
{
insetsForThisIsland[insetIndex].Add(island.InsetToolPaths[insetIndex][polygonIndex]);
}
}
}
// If we are on the very first layer we always start with the outside so that we can stick to the bed better.
if (config.OutsidePerimetersFirst || layerIndex == 0 || inset0Config.spiralize)
{
if (inset0Config.spiralize)
{
if (island.InsetToolPaths.Count > 0)
{
Polygon outsideSinglePolygon = island.InsetToolPaths[0][0];
layerGcodePlanner.QueuePolygonsByOptimizer(new Polygons() { outsideSinglePolygon }, inset0Config);
}
}
else
{
int insetCount = CountInsetsToPrint(insetsForThisIsland);
while (insetCount > 0)
{
bool limitDistance = false;
if (island.InsetToolPaths.Count > 0)
{
QueueClosetsInset(insetsForThisIsland[0], limitDistance, inset0Config, layerIndex, layerGcodePlanner);
}
// Move to the closest inset 1 and print it
for (int insetIndex = 1; insetIndex < island.InsetToolPaths.Count; insetIndex++)
{
limitDistance = QueueClosetsInset(insetsForThisIsland[insetIndex], limitDistance, insetXConfig, layerIndex, layerGcodePlanner);
}
insetCount = CountInsetsToPrint(insetsForThisIsland);
}
}
}
else // This is so we can do overhangs better (the outside can stick a bit to the inside).
{
int insetCount = CountInsetsToPrint(insetsForThisIsland);
if(insetCount == 0
&& config.ExpandThinWalls
&& island.IslandOutline.Count > 0
&& island.IslandOutline[0].Count > 0)
{
// There are no insets but we should still try to go to the start position of the first perimeter if we are expanding thin walls
layerGcodePlanner.QueueTravel(island.IslandOutline[0][0]);
}
while (insetCount > 0)
{
bool limitDistance = false;
if (island.InsetToolPaths.Count > 0)
{
// Print the insets from inside to out (count - 1 to 0).
for (int insetIndex = island.InsetToolPaths.Count - 1; insetIndex >= 0; insetIndex--)
{
if (!config.ContinuousSpiralOuterPerimeter
&& insetIndex == island.InsetToolPaths.Count - 1)
{
var closestInsetStart = FindBestPoint(insetsForThisIsland[0], layerGcodePlanner.LastPosition);
if(closestInsetStart.X != long.MinValue)
{
layerGcodePlanner.QueueTravel(closestInsetStart);
}
}
limitDistance = QueueClosetsInset(
insetsForThisIsland[insetIndex],
limitDistance,
insetIndex == 0 ? inset0Config : insetXConfig,
layerIndex,
layerGcodePlanner);
// Figure out if there is another inset
}
}
insetCount = CountInsetsToPrint(insetsForThisIsland);
}
}
// Find the thin lines for this layer and add them to the queue
if (config.FillThinGaps && !config.ContinuousSpiralOuterPerimeter)
{
for (int perimeter = 0; perimeter < config.NumberOfPerimeters; perimeter++)
{
Polygons thinLines = null;
if (island.IslandOutline.Offset(-extrusionWidth_um * (1 + perimeter)).FindThinLines(extrusionWidth_um + 2, extrusionWidth_um / 5, out thinLines, true))
{
fillPolygons.AddRange(thinLines);
}
}
}
if (config.ExpandThinWalls && !config.ContinuousSpiralOuterPerimeter)
{
Polygons thinLines = null;
// Collect all of the lines up to one third the extrusion diameter
//string perimeterString = Newtonsoft.Json.JsonConvert.SerializeObject(island.IslandOutline);
if (island.IslandOutline.FindThinLines(extrusionWidth_um + 2, extrusionWidth_um / 3, out thinLines, true))
{
for(int polyIndex=thinLines.Count-1; polyIndex>=0; polyIndex--)
{
var polygon = thinLines[polyIndex];
if (polygon.Count == 2
&& (polygon[0] - polygon[1]).Length() < config.ExtrusionWidth_um / 4)
{
thinLines.RemoveAt(polyIndex);
}
else
{
for (int i = 0; i < polygon.Count; i++)
{
if (polygon[i].Width > 0)
{
polygon[i] = new IntPoint(polygon[i])
{
Width = extrusionWidth_um,
};
}
}
}
}
fillPolygons.AddRange(thinLines);
}
}
}
// Write the bridge polygons after the perimeter so they will have more to hold to while bridging the gaps.
// It would be even better to slow down the perimeters that are part of bridges but that is for later.
if (bridgePolygons.Count > 0)
{
QueuePolygonsConsideringSupport(layerIndex, layerGcodePlanner, bridgePolygons, bridgeConfig, SupportWriteType.UnsupportedAreas);
}
// TODO: Put all of these segments into a list that can be queued together and still preserver their individual config settings.
// This will make the total amount of travel while printing infill much less.
layerGcodePlanner.QueuePolygonsByOptimizer(fillPolygons, fillConfig);
QueuePolygonsConsideringSupport(layerIndex, layerGcodePlanner, bottomFillPolygons, bottomFillConfig, SupportWriteType.UnsupportedAreas);
layerGcodePlanner.QueuePolygonsByOptimizer(topFillPolygons, topFillConfig);
}
}
private void MoveToIsland(GCodePlanner layerGcodePlanner, SliceLayer layer, LayerIsland island)
{
if(config.ContinuousSpiralOuterPerimeter)
{
return;
}
if (island.IslandOutline.Count > 0)
{
// If we are already in the island we are going to, don't go there.
if (island.PathFinder.OutlinePolygons.PointIsInside(layerGcodePlanner.LastPosition, island.PathFinder.OutlineEdgeQuadTrees))
{
islandCurrentlyInside = island;
layerGcodePlanner.PathFinder = island.PathFinder;
return;
}
var closestPointOnNextIsland = island.IslandOutline.FindClosestPoint(layerGcodePlanner.LastPosition);
IntPoint closestNextIslandPoint = island.IslandOutline[closestPointOnNextIsland.Item1][closestPointOnNextIsland.Item2];
if (islandCurrentlyInside?.PathFinder?.OutlinePolygons.Count > 0
&& islandCurrentlyInside?.PathFinder?.OutlinePolygons?[0]?.Count > 3)
{
// start by moving within the last island to the closet point to the next island
var polygons = islandCurrentlyInside.PathFinder.OutlinePolygons;
if (polygons.Count > 0)
{
var closestPointOnLastIsland = polygons.FindClosestPoint(closestNextIslandPoint);
IntPoint closestLastIslandPoint = polygons[closestPointOnLastIsland.Item1][closestPointOnLastIsland.Item2];
// make sure we are planning within the last island we were using
layerGcodePlanner.PathFinder = islandCurrentlyInside.PathFinder;
layerGcodePlanner.QueueTravel(closestLastIslandPoint);
}
}
// let's move to this island avoiding running into any other islands
layerGcodePlanner.PathFinder = layer.PathFinder;
// find the closest point to where we are now
// and do a move to there
if (config.RetractWhenChangingIslands) layerGcodePlanner.ForceRetract();
layerGcodePlanner.QueueTravel(closestNextIslandPoint);
// and remember that we are now in the new island
islandCurrentlyInside = island;
// set the path planner to the current island
layerGcodePlanner.PathFinder = island.PathFinder;
}
}
public IntPoint FindBestPoint(Polygons boundaryPolygons, IntPoint position)
{
IntPoint polyPointPosition = new IntPoint(long.MinValue, long.MinValue);
long bestDist = long.MaxValue;
for (int polygonIndex = 0; polygonIndex < boundaryPolygons.Count; polygonIndex++)
{
IntPoint closestToPoly = boundaryPolygons[polygonIndex].FindGreatestTurnPosition(config.ExtrusionWidth_um);
if (closestToPoly != null)
{
long length = (closestToPoly - position).Length();
if (length < bestDist)
{
bestDist = length;
polyPointPosition = closestToPoly;
}
}
}
return polyPointPosition;
}
private bool QueueClosetsInset(Polygons insetsToConsider, bool limitDistance, GCodePathConfig pathConfig, int layerIndex, GCodePlanner gcodeLayer)
{
// This is the furthest away we will accept a new starting point
long maxDist_um = long.MaxValue;
if (limitDistance)
{
// Make it relative to the size of the nozzle
maxDist_um = config.ExtrusionWidth_um * 4;