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
/**
  Copyright (C) 2012-2025 by Autodesk, Inc.
  All rights reserved.
 
  Prusa post processor configuration.
 
  $Revision: 44161 f187ea25b82f4dac92873cf91c53c80db78df59a $
  $Date: 2025-01-22 11:35:28 $
 
  FORKID {FEF3D431-E19A-4541-8E5C-A32A33348505}
*/
 
description = "Prusa";
vendor = "Prusa";
legal = "Copyright (C) 2012-2025 by Autodesk, Inc.";
certificationLevel = 2;
minimumRevision = 45917;
 
longDescription = "Post for exporting toolpath to the Prusa i3 family or mini in gcode format (i3, i3 MK2, i3 MK3, mini, Mk4, XL)";
 
extension = "gcode";
setCodePage("ascii");
 
capabilities = CAPABILITY_ADDITIVE;
tolerance = spatial(0.002, MM);
 
highFeedrate = toPreciseUnit(12000, MM);
minimumChordLength = spatial(0.25, MM);
minimumCircularRadius = spatial(0.4, MM);
maximumCircularRadius = spatial(1000, MM);
minimumCircularSweep = toRad(0.01);
maximumCircularSweep = toRad(180);
allowHelicalMoves = false; // disable helical support
allowSpiralMoves = false; // disable spiral support
allowedCircularPlanes = 1 << PLANE_XY; // allow XY circular motion
 
// user-defined properties
properties = {
  printerModel: {
    title      : "Printer model",
    description: "Select the printer model for generating the gcode.",
    type       : "enum",
    values     : [
      {title:"i3 MK2, i3 MK3", id:"i3mk2mk3"},
      {title:"MINI", id:"mini"},
      {title:"MK4", id:"mk4"},
      {title:"XL", id:"xl"}
    ],
    value: "i3mk2mk3",
    scope: "machine"
  }
};
 
// included properties
if (typeof properties != "object") {
  properties = {};
}
if (typeof groupDefinitions != "object") {
  groupDefinitions = {};
}
// >>>>> INCLUDED FROM ../common/propertyTemperatureTower.cpi
properties._trigger = {
  title      : "Trigger",
  description: "Specifies whether to use the Z-height or layer number as the trigger to change temperature of the active Extruder.",
  type       : "enum",
  values     : [
    {title:"Disabled", id:"disabled"},
    {title:"by Height", id:"height"},
    {title:"by Layer", id:"layer"}
  ],
  value: "disabled",
  scope: "post",
  group: "temperatureTower"
};
properties._triggerValue = {
  title      : "Trigger Value",
  description: "This number specifies either the Z-height or the layer number increment on when a change should be triggered.",
  type       : "number",
  value      : 10,
  scope      : "post",
  group      : "temperatureTower"
};
properties.tempStart = {
  title      : "Start Temperature",
  description: "Specifies the starting temperature for the active Extruder (degrees C). Note that the temperature specified in the print settings will be overridden by this value.",
  type       : "integer",
  value      : 190,
  range      : [50, 450],
  scope      : "post",
  group      : "temperatureTower"
};
properties.tempInterval = {
  title      : "Temperature Interval",
  description: "Every step, increase the temperature of the active Extruder by this amount (degrees C).",
  type       : "integer",
  value      : 5,
  range      : [-30, 30],
  scope      : "post",
  group      : "temperatureTower"
};
 
groupDefinitions.temperatureTower = {
  title      : "Temperature Tower",
  description: "Temperature Towers are used to test new filaments in order to identify the best printing temperature. " +
      "When utilized, this functionality generates a Gcode file where the temperature increases by a set amount, every step in height or layer number.",
  collapsed: true,
  order    : 0
};
// <<<<< INCLUDED FROM ../common/propertyTemperatureTower.cpi
// >>>>> INCLUDED FROM ../common/propertyRelativeExtrusion.cpi
properties.relativeExtrusion = {
  title      : "Relative extrusion mode",
  description: "Select the filament extrusion mode, either absolute or relative.",
  type       : "boolean",
  value      : true,
  scope      : "post"
};
// <<<<< INCLUDED FROM ../common/propertyRelativeExtrusion.cpi
// >>>>> INCLUDED FROM ../common/propertyPause.cpi
properties.pauseLayers = {
  title      : "Layer number(s) pause print",
  description: "Comma separated list containing the layer numbers to pause printing.",
  type       : "string",
  value      : "",
  scope      : "post",
  group      : "pauseFeature"
};
properties.pauseMessage = {
  title      : "Message for pause print",
  description: "The message displayed when pausing the print to inform the user.",
  type       : "string",
  value      : "",
  scope      : "post",
  group      : "pauseFeature"
};
 
groupDefinitions.pauseFeature = {
  title      : "Pause Print",
  description: "Pauses the print at the start of the user defined layer(s) and displays a message. Used for pausing the print to insert / embed objects to the part during printing.",
  collapsed  : true,
  order      : 1
};
// <<<<< INCLUDED FROM ../common/propertyPause.cpi
// >>>>> INCLUDED FROM ../common/propertyChangeFilament.cpi
properties.changeLayers = {
  title      : "Layer number(s) filament change",
  description: "Comma separated list containing the layer numbers to stop printing and changing the filament.",
  type       : "string",
  value      : "",
  scope      : "post",
  group      : "changeFilament"
};
properties.changeMessage = {
  title      : "Message for filament change",
  description: "Message displayed when pausing the print to inform the user.",
  type       : "string",
  value      : "",
  scope      : "post",
  group      : "changeFilament"
};
/*
properties.useFirmwareConfiguration = {
  title      : "Use Firmware configuration",
  description: "Specifies to use the firmware default options for a filament change.",
  type       : "boolean",
  value      : true,
  scope      : "post",
  group      : "changeFilament"
};
properties.initialRetract = {
  title      : "Extruder initial retract",
  description: "Specifies the initial extruder retract.",
  type       : "number",
  value      : 0,
  scope      : "post",
  group      : "changeFilament"
};
properties.removalRetract = {
  title      : "Extruder removal retract",
  description: "Specifies the retract distance for removing the filament.",
  type       : "number",
  value      : 0,
  scope      : "post",
  group      : "changeFilament"
};
properties.zPosition = {
  title      : "Z position relative",
  description: "Z relative lift for the filament change.",
  type       : "number",
  value      : 0,
  scope      : "post",
  group      : "changeFilament"
};
*/
 
groupDefinitions.changeFilament = {
  title      : "Filament Change",
  description: "Pauses the print at the start of the user defined layer(s) and displays a message. Used for switching to a different color filament of the same material.",
  collapsed  : true,
  order      : 2
};
// <<<<< INCLUDED FROM ../common/propertyChangeFilament.cpi
 
var gFormat = createFormat({prefix:"G", width:1, decimals:0});
var mFormat = createFormat({prefix:"M", width:2, zeropad:true, decimals:1});
var tFormat = createFormat({prefix:"T", width:1, decimals:0});
var integerFormat = createFormat({decimals:0});
var gMotionModal = createOutputVariable({control:CONTROL_FORCE}, gFormat); // modal group 1 - G0-G3
var gAbsIncModal = createOutputVariable({}, gFormat); // modal group 3 - G90-91
 
// Specify the required commands for your printer below.
var commands = {
  extruderChangeCommand : undefined, // command to change the extruder
  setExtruderTemperature: mFormat.format(104), // command to set the extruder temperature
  waitExtruder          : mFormat.format(109), // wait command for the extruder temperature
  setBedTemperature     : mFormat.format(140), // command to set the bed temperature
  waitBed               : mFormat.format(190), // wait command for the bed temperature
  reportTemperatures    : undefined, // command to report the temperatures to the printer
  fan                   : {on:mFormat.format(106), off:mFormat.format(107)}, // command turn the fan on/off
  extrusionMode         : {relative:mFormat.format(83), absolute:mFormat.format(82)}, // commands for relative / absolute filament extrusion mode
  displayCommand        : mFormat.format(117), // command to display a message on the printer screen
  pauseCommand          : mFormat.format(601), // command to pause the print, waiting for user manual restart
  changeFilament        : {
    command: mFormat.format(600)
    // initialRetract: "E",
    // removalRetract: "L"
  }
};
 
var settings = {
  useG0           : true, // specifies to either use G0 or G1 commands for rapid movements
  skipParkPosition: false, // set to true to avoid output of the park position at the end of the program
  comments        : {
    permittedCommentChars: " abcdefghijklmnopqrstuvwxyz0123456789.,=_-*+:/'", // letters are not case sensitive, use option 'outputFormat' below. Set to 'undefined' to allow any character
    prefix               : ";", // specifies the prefix for the comment
    suffix               : "", // specifies the suffix for the comment
    outputFormat         : "ignoreCase", // can be set to "upperCase", "lowerCase" and "ignoreCase". Set to "ignoreCase" to write comments without upper/lower case formatting
    maximumLineLength    : 80 // the maximum number of characters allowed in a line
  }
};
 
// collected state
var activeExtruder = 0; // track the active extruder.
 
var model;
function onOpen() {
  model = getProperty("printerModel");
  setFormats(MM); // machine require input code in MM
  initializeMachineParameters();
  if (typeof writeProgramHeader == "function") {
    writeProgramHeader();
  }
  writeBlock(gFormat.format(unit == MM ? 21 : 20)); // set unit
  if ((model != "xl") && (model != "mk4")) {
    writeBlock("M115 U3.0.10", formatComment(localize("tell printer latest fw version")));
  } else {
    writeBlock(mFormat.format(17), formatComment(localize("enable steppers")));
    writeBlock(mFormat.format(862.3), "P \"" + model.toUpperCase(model) + "\"", formatComment(localize("printer model check")));
    writeComment(localize("inform about nozzle diameter"));
    writeBlock(mFormat.format(862.1), tFormat.format(activeExtruder), "P" + getExtruder(activeExtruder + 1).nozzleDiameter);
    writeBlock("M115 U6.0.2+14873", formatComment(localize("tell printer minimum fw version")));
 
    writeBlock(gAbsIncModal.format(90));
    var globalBoundaries = getSection(0).getBoundingBox();
    writeBlock(mFormat.format(555), xOutput.format(globalBoundaries.lower.x), yOutput.format(globalBoundaries.lower.y),
      "W" + xyzFormat.format(globalBoundaries.upper.x - globalBoundaries.lower.x),
      "H" + xyzFormat.format(globalBoundaries.upper.y - globalBoundaries.lower.y));
    forceXYZE();
  }
 
  if ((model == "i3mk2mk3") || (model == "mini")) {
    writeBlock(gFormat.format(28), (model == "i3mk2mk3") ? "W" : "", formatComment(localize("home all without mesh bed level")));
  }
}
 
function onSection() {
  // probe bed after heating
  if (model == "i3mk2mk3") {
    writeBlock(gFormat.format(80), formatComment(localize("mesh bed leveling")));
  else if (model == "mini") {
    writeBlock(gFormat.format(29), formatComment(localize("mesh bed leveling")));
  } else if (model == "mk4") {
    writeBlock(mFormat.format(84), "E", formatComment(localize("turn off E motor")));
    writeBlock(gFormat.format(28), formatComment(localize("home all without mesh bed level")));
    writeBlock(gMotionModal.format(1), xOutput.format(toPreciseUnit(42, MM)), yOutput.format(toPreciseUnit(-4, MM)), zOutput.format(toPreciseUnit(5, MM)), feedOutput.format(toPreciseUnit(4800, MM)));
    writeBlock(mFormat.format(302), sOutput.format(160), formatComment(localize("lower cold extrusion limit to 160C")));
    forceXYZE();
    writeBlock(gMotionModal.format(1), eOutput.format(toPreciseUnit(-2, MM)), feedOutput.format(toPreciseUnit(2400, MM)), formatComment(localize("retraction")));
    writeBlock(mFormat.format(84), "E", formatComment(localize("turn off E motor")));
    writeBlock(gFormat.format(29), "P" + xyzFormat.format(9), xOutput.format(toPreciseUnit(10, MM)), yOutput.format(toPreciseUnit(-4, MM)), "W" + xyzFormat.format(toPreciseUnit(32, MM)), "H" + xyzFormat.format(toPreciseUnit(4, MM)));
    writeBlock(gMotionModal.format(0), zOutput.format(toPreciseUnit(40, MM)), feedOutput.format(toPreciseUnit(10000, MM)));
    writeComment(" MBL");
    writeBlock(mFormat.format(84), "E");
    writeBlock(gFormat.format(29), "P" + xyzFormat.format(1), formatComment(localize("invalidate mbl & probe print area")));
    writeBlock(gFormat.format(29), "P" + xyzFormat.format(1), xOutput.format(0), yOutput.format(0), "W" + xyzFormat.format(toPreciseUnit(50, MM)), "H" + xyzFormat.format(toPreciseUnit(20, MM)), "C", formatComment(localize("probe")));
    writeBlock(gFormat.format(29), "P" + xyzFormat.format(3.2), formatComment(localize("interpolate mbl probes")));
    writeBlock(gFormat.format(29), "P" + xyzFormat.format(3.13), formatComment(localize("extrapolate mbl outside probe area")));
    writeBlock(gFormat.format(29), "A", formatComment(localize("activate mbl")));
    writeComment("prepare for priming line");
    forceXYZE();
    writeBlock(gMotionModal.format(0), xOutput.format(0), yOutput.format(toPreciseUnit(-4, MM)), zOutput.format(toPreciseUnit(15, MM)), feedOutput.format(toPreciseUnit(4800, MM)), formatComment(localize(" move away and ready for the purge")));
    onExtrusionReset(0);
    eOutput.reset();
    writeBlock(mFormat.format(569), sOutput.format(0), "E", formatComment(localize("set spreadcycle mode for extruder")));
    writeBlock(mFormat.format(221), sOutput.format(100), formatComment(localize("set flow to 100%")));
  } else if (model == "xl") {
    var globalBoundaries = getSection(0).getBoundingBox();
    writeComment("home carriage, pick tool, home all");
    writeBlock(gFormat.format(28), "XY");
    gMotionModal.reset();
    writeBlock(mFormat.format(84), "E", formatComment(localize("turn off E motor")));
    writeBlock(gFormat.format(28), "Z");
    writeBlock(gFormat.format(29), "G", formatComment(localize("absorb heat")));
    writeComment("move to the nozzle cleanup area");
 
    var xLocation;
    if (globalBoundaries.lower.x < toPreciseUnit(5, MM)) {
      xLocation = toPreciseUnit(260, MM);
    } else {
      xLocation = Math.min(machineConfiguration.getWidth(), (globalBoundaries.lower.x + toPreciseUnit(32, MM))) - toPreciseUnit(32, MM);
    }
    writeBlock(gMotionModal.format(1), xOutput.format(xLocation + toPreciseUnit(32, MM)), yOutput.format(globalBoundaries.lower.y - toPreciseUnit(7, MM)), zOutput.format(toPreciseUnit(50, MM)), feedOutput.format(toPreciseUnit(4800, MM)));
    forceXYZE();
    writeBlock(mFormat.format(302), sOutput.format(160), formatComment(localize("lower cold extrusion limit to 160C")));
    writeBlock(gMotionModal.format(1), eOutput.format(toPreciseUnit(-2, MM)), feedOutput.format(toPreciseUnit(2400, MM)), formatComment(localize("retraction for nozzle cleanup")));
    writeComment("nozzle cleanup");
    writeBlock(mFormat.format(84), "E");
    writeBlock(gFormat.format(29), "P" + xyzFormat.format(9), xOutput.format(xLocation), yOutput.format(globalBoundaries.lower.y - toPreciseUnit(7, MM)), "W" + xyzFormat.format(toPreciseUnit(32, MM)), "H" + xyzFormat.format(toPreciseUnit(7, MM)));
    forceXYZE();
    writeBlock(gMotionModal.format(0), zOutput.format(toPreciseUnit(70, MM)), feedOutput.format(toPreciseUnit(480, MM)), formatComment(localize("move away in Z")));
    writeBlock(gMotionModal.format(0), xOutput.format(toPreciseUnit(30, MM)), yOutput.format(0), feedOutput.format(toPreciseUnit(6000, MM)), formatComment(localize("move away in X/Y")));
    writeComment(" MBL");
    writeBlock(mFormat.format(84), "E");
    writeBlock(gFormat.format(29), "P" + xyzFormat.format(1), formatComment(localize("invalidate mbl and probe print area")));
    forceXYZE();
    writeBlock(gFormat.format(29), "P" + xyzFormat.format(1), xOutput.format(toPreciseUnit(30, MM)), yOutput.format(0), "W" + xyzFormat.format(toPreciseUnit(50, MM)), "H" + xyzFormat.format(toPreciseUnit(20, MM)), "C", formatComment(localize("probe")));
    writeBlock(gFormat.format(29), "P" + xyzFormat.format(3.2), formatComment(localize("interpolate mbl probes")));
    writeBlock(gFormat.format(29), "P" + xyzFormat.format(3.13), formatComment(localize("extrapolate mbl outside probe area")));
    writeBlock(gFormat.format(29), "A ;activate mbl");
    forceXYZE();
    writeBlock(gMotionModal.format(1), zOutput.format(toPreciseUnit(10, MM)), feedOutput.format(toPreciseUnit(720, MM)), formatComment(localize("move away in Z")));
    writeBlock(gMotionModal.format(0), xOutput.format(toPreciseUnit(30, MM)), yOutput.format(toPreciseUnit(-8, MM)), feedOutput.format(toPreciseUnit(6000, MM)), formatComment(localize("move next to the sheet")));
    forceXYZE();
  }
  onExtrusionReset(0);
  writeBlock(gAbsIncModal.format(90)); // absolute spatial co-ordinates
  writeBlock(getCode(getProperty("relativeExtrusion") ? commands.extrusionMode.relative : commands.extrusionMode.absolute));
}
 
function onClose() {
  writeBlock("G4", formatComment(localize(" wait")));
  xOutput.reset();
  yOutput.reset();
  if ((model == "i3mk2mk3") || (model == "mini")) {
    var yPosition = (model == "i3mk2mk3") ? toPreciseUnit(200, MM) : toPreciseUnit(150, MM);
    writeBlock(gMotionModal.format(1), xOutput.format(0), yOutput.format(yPosition), formatComment(localize("home X axis")));
  }
  if ((model == "xl") || (model == "mk4")) {
    writeBlock(mFormat.format(900), "K0", formatComment(localize("reset LA")));
    writeBlock(mFormat.format(142), sOutput.format(36), formatComment(localize("reset heatbreak target temp")));
    if (model == "xl") {
      writeBlock(mFormat.format(221), sOutput.format(100), formatComment(localize("reset flow percentage")));
    } else {
      writeBlock(mFormat.format(84), "X Y E", formatComment(localize("disable motors")));
    }
  }
  if (model != "mk4") {
    writeBlock(mFormat.format(84), formatComment(localize("disable motors")));
  }
}
 
// >>>>> INCLUDED FROM ../common/onBedTemp.cpi
function onBedTemp(temp, wait) {
  if (wait) {
    writeBlock(getCode(commands.reportTemperatures));
    writeBlock(getCode(commands.waitBed), sOutput.format(temp));
  } else {
    writeBlock(getCode(commands.setBedTemperature), sOutput.format(temp));
  }
}
// <<<<< INCLUDED FROM ../common/onBedTemp.cpi
// >>>>> INCLUDED FROM ../common/onExtruderTemp.cpi
function onExtruderTemp(temp, wait, id) {
  if (typeof executeTempTowerFeatures == "function" && getProperty("_trigger") != undefined) {
    if (getProperty("_trigger") != "disabled" && (getCurrentPosition().z == 0)) {
      temp = getProperty("tempStart"); // override temperature with the starting temperature for the temp tower feature
    }
  }
  if (wait) {
    writeBlock(getCode(commands.reportTemperatures));
    writeBlock(getCode(commands.waitExtruder), sOutput.format(temp), tFormat.format(id));
  } else {
    writeBlock(getCode(commands.setExtruderTemperature), sOutput.format(temp), tFormat.format(id));
  }
}
// <<<<< INCLUDED FROM ../common/onExtruderTemp.cpi
// >>>>> INCLUDED FROM ../common/onExtruderChange.cpi
function onExtruderChange(id) {
  if (id > machineConfiguration.getNumberExtruders()) {
    error(subst(localize("This printer does not support the extruder '%1'."), integerFormat.format(id)));
    return;
  }
  writeBlock(getCode(commands.extruderChangeCommand), tFormat.format(id));
  activeExtruder = id;
  forceXYZE();
}
// <<<<< INCLUDED FROM ../common/onExtruderChange.cpi
// >>>>> INCLUDED FROM ../common/onExtrusionReset.cpi
function onExtrusionReset(length) {
  if (getProperty("relativeExtrusion")) {
    eOutput.setCurrent(0);
  }
  eOutput.reset();
  writeBlock(gFormat.format(92), eOutput.format(length));
}
// <<<<< INCLUDED FROM ../common/onExtrusionReset.cpi
// >>>>> INCLUDED FROM ../common/onFanSpeed.cpi
function onFanSpeed(speed, id) {
  if (!commands.fan) {
    return;
  }
  if (speed == 0) {
    writeBlock(getCode(commands.fan.off));
  } else {
    writeBlock(getCode(commands.fan.on), sOutput.format(speed));
  }
}
// <<<<< INCLUDED FROM ../common/onFanSpeed.cpi
// >>>>> INCLUDED FROM ../common/onLayer.cpi
function onLayer(num) {
  if (typeof executeTempTowerFeatures == "function") {
    executeTempTowerFeatures(num);
  }
  if (num == 1) {
    writeComment("LAYER_COUNT:" + integerFormat.format(layerCount));
  }
  writeComment("LAYER:" + integerFormat.format(num));
  if (typeof changeFilament == "function" && getProperty("changeLayers") != undefined) {
    changeFilament(num);
  }
  if (typeof pausePrint == "function" && getProperty("pauseLayers") != undefined) {
    pausePrint(num);
  }
}
// <<<<< INCLUDED FROM ../common/onLayer.cpi
// >>>>> INCLUDED FROM ../common/setFormats.cpi
function setFormats(_desiredUnit) {
  if (_desiredUnit != unit) {
    writeComment(subst(localize("This printer does not support programs in %1."), unit == IN ? "inches" : "millimeters"));
    writeComment(localize("The program has been converted to the supported unit."));
    unit = _desiredUnit;
  }
 
  xyzFormat = createFormat({decimals:(unit == MM ? 3 : 4)});
  feedFormat = createFormat({decimals:(unit == MM ? 0 : 1)});
  dimensionFormat = createFormat({decimals:(unit == MM ? 3 : 4), zeropad:false, suffix:(unit == MM ? "mm" : "in")});
 
  xOutput = createOutputVariable({prefix:"X"}, xyzFormat);
  yOutput = createOutputVariable({prefix:"Y"}, xyzFormat);
  zOutput = createOutputVariable({prefix:"Z"}, xyzFormat);
  feedOutput = createOutputVariable({prefix:"F"}, feedFormat);
  eOutput = createOutputVariable({prefix:"E", type:getProperty("relativeExtrusion") ? TYPE_INCREMENTAL : TYPE_ABSOLUTE}, xyzFormat);
  sOutput = createOutputVariable({prefix:"S", control:CONTROL_FORCE}, xyzFormat); // parameter temperature or speed
  iOutput = createOutputVariable({prefix:"I", control:CONTROL_FORCE}, xyzFormat); // circular output
  jOutput = createOutputVariable({prefix:"J", control:CONTROL_FORCE}, xyzFormat); // circular output
  if (typeof parseSpatialProperties == "function") {
    parseSpatialProperties();
  }
}
// <<<<< INCLUDED FROM ../common/setFormats.cpi
// >>>>> INCLUDED FROM ../common/writeProgramHeader.cpi
function writeProgramHeader() {
  if (programName) {
    writeComment(programName);
  }
  if (programComment) {
    writeComment(programComment);
  }
  writeComment(subst(localize("Printer name: %1 %2"), machineConfiguration.getVendor(), machineConfiguration.getModel()));
  writeComment("TIME:" + integerFormat.format(printTime));  // do not localize
  writeComment(subst(localize("Print time: %1"), formatCycleTime(printTime)));
  for (var i = 1; i <= numberOfExtruders; ++i) {
    writeComment(subst(localize("Extruder %1 material used: %2"), i, dimensionFormat.format(toPreciseUnit(getExtruder(i).extrusionLength, MM))));
    writeComment(subst(localize("Extruder %1 material name: %2"), i, getExtruder(i).materialName));
    writeComment(subst(localize("Extruder %1 filament diameter: %2"), i, dimensionFormat.format(toPreciseUnit(getExtruder(i).filamentDiameter, MM))));
    writeComment(subst(localize("Extruder %1 nozzle diameter: %2"), i, dimensionFormat.format(toPreciseUnit(getExtruder(i).nozzleDiameter, MM))));
    writeComment(subst(localize("Extruder %1 offset x: %2"), i, dimensionFormat.format(toPreciseUnit(machineConfiguration.getExtruderOffsetX(i), MM))));
    writeComment(subst(localize("Extruder %1 offset y: %2"), i, dimensionFormat.format(toPreciseUnit(machineConfiguration.getExtruderOffsetY(i), MM))));
    writeComment(subst(localize("Extruder %1 offset z: %2"), i, dimensionFormat.format(toPreciseUnit(machineConfiguration.getExtruderOffsetZ(i), MM))));
    writeComment(subst(localize("Extruder %1 max temp: %2"), i, integerFormat.format(getExtruder(i).temperature)));
  }
  writeComment(subst(localize("Bed temp: %1"), integerFormat.format(bedTemp)));
  writeComment(subst(localize("Layer count: %1"), integerFormat.format(layerCount)));
  writeComment(subst(localize("Width: %1"), dimensionFormat.format(toPreciseUnit(machineConfiguration.getWidth() - machineConfiguration.getCenterPositionX(), MM))));
  writeComment(subst(localize("Depth: %1"), dimensionFormat.format(toPreciseUnit(machineConfiguration.getDepth() - machineConfiguration.getCenterPositionY(), MM))));
  writeComment(subst(localize("Height: %1"), dimensionFormat.format(toPreciseUnit(machineConfiguration.getHeight() + machineConfiguration.getCenterPositionZ(), MM))));
  writeComment(subst(localize("Center x: %1"), dimensionFormat.format(toPreciseUnit((machineConfiguration.getWidth() / 2.0) - machineConfiguration.getCenterPositionX(), MM))));
  writeComment(subst(localize("Center y: %1"), dimensionFormat.format(toPreciseUnit((machineConfiguration.getDepth() / 2.0) - machineConfiguration.getCenterPositionY(), MM))));
  writeComment(subst(localize("Center z: %1"), dimensionFormat.format(toPreciseUnit(machineConfiguration.getCenterPositionZ(), MM))));
  writeComment(subst(localize("Count of bodies: %1"), integerFormat.format(partCount)));
  writeComment(subst(localize("Fusion version: %1"), getGlobalParameter("version")));
}
// <<<<< INCLUDED FROM ../common/writeProgramHeader.cpi
// >>>>> INCLUDED FROM ../common/commonAdditiveFunctions.cpi
function writeBlock() {
  writeWords(arguments);
}
 
validate(settings.comments, "Setting 'comments' is required but not defined.");
function formatComment(text) {
  var prefix = settings.comments.prefix;
  var suffix = settings.comments.suffix;
  var _permittedCommentChars = settings.comments.permittedCommentChars == undefined ? "" : settings.comments.permittedCommentChars;
  switch (settings.comments.outputFormat) {
  case "upperCase":
    text = text.toUpperCase();
    _permittedCommentChars = _permittedCommentChars.toUpperCase();
    break;
  case "lowerCase":
    text = text.toLowerCase();
    _permittedCommentChars = _permittedCommentChars.toLowerCase();
    break;
  case "ignoreCase":
    _permittedCommentChars = _permittedCommentChars.toUpperCase() + _permittedCommentChars.toLowerCase();
    break;
  default:
    error(localize("Unsupported option specified for setting 'comments.outputFormat'."));
  }
  if (_permittedCommentChars != "") {
    text = filterText(String(text), _permittedCommentChars);
  }
  text = String(text).substring(0, settings.comments.maximumLineLength - prefix.length - suffix.length);
  return text != "" ?  prefix + text + suffix : "";
}
 
/**
  Output a comment.
*/
function writeComment(text) {
  if (!text) {
    return;
  }
  var comments = String(text).split(EOL);
  for (comment in comments) {
    var _comment = formatComment(comments[comment]);
    if (_comment) {
      writeln(_comment);
    }
  }
}
 
function onComment(text) {
  writeComment(text);
}
 
function forceXYZE() {
  xOutput.reset();
  yOutput.reset();
  zOutput.reset();
  eOutput.reset();
}
 
function getCode(code) {
  return typeof code == "undefined" ? "" : code;
}
 
function onParameter(name, value) {
  switch (name) {
  case "feedRate":
    rapidFeedrate = toPreciseUnit(value, MM);
    break;
  }
}
 
var nextTriggerValue;
var newTemperature;
function executeTempTowerFeatures(num) {
  if (getProperty("_trigger") != "disabled") {
    var multiplier = getProperty("_trigger") == "height" ? 100 : 1;
    var currentValue = getProperty("_trigger") == "height" ? xyzFormat.format(getCurrentPosition().z * 100) : (num - 1);
    if (num == 1) { // initialize
      nextTriggerValue = getProperty("_triggerValue") * multiplier;
      newTemperature = getProperty("tempStart");
    } else {
      if (currentValue >= nextTriggerValue) {
        newTemperature += getProperty("tempInterval");
        nextTriggerValue += getProperty("_triggerValue") * multiplier;
        if (newTemperature <= maximumExtruderTemp[activeExtruder]) {
          onExtruderTemp(newTemperature, false, activeExtruder);
        } else {
          error(subst(
            localize("Temperature tower - The requested extruder temperature of '%1' exceeds the maximum value of '%2'."), newTemperature, maximumExtruderTemp[activeExtruder])
          );
        }
      }
    }
  }
}
 
function formatCycleTime(cycleTime) {
  var seconds = cycleTime % 60 | 0;
  var minutes = ((cycleTime - seconds) / 60 | 0) % 60;
  var hours = (cycleTime - minutes * 60 - seconds) / (60 * 60) | 0;
  if (hours > 0) {
    return subst(localize("%1h:%2m:%3s"), hours, minutes, seconds);
  } else if (minutes > 0) {
    return subst(localize("%1m:%2s"), minutes, seconds);
  } else {
    return subst(localize("%1s"), seconds);
  }
}
 
function onRapid(_x, _y, _z) {
  var x = xOutput.format(_x);
  var y = yOutput.format(_y);
  var z = zOutput.format(_z);
  var f = feedOutput.format(rapidFeedrate);
 
  if (settings.skipParkPosition) {
    var num =
      (!xyzFormat.areDifferent(_x, currentSection.getFinalPosition().x) ? 1 : 0) +
      (!xyzFormat.areDifferent(_y, currentSection.getFinalPosition().y) ? 1 : 0) +
      (!xyzFormat.areDifferent(_z, currentSection.getFinalPosition().z) ? 1 : 0);
    if (num > 0 && isLastMotionRecord(getNextRecord().getId() + 1)) {
      return; // skip movements to park position
    }
  }
  if (x || y || z || f) {
    writeBlock(gMotionModal.format(settings.useG0 ? 0 : 1), x, y, z, f);
    feedOutput.reset();
  }
}
 
function onLinearExtrude(_x, _y, _z, _f, _e) {
  var x = xOutput.format(_x);
  var y = yOutput.format(_y);
  var z = zOutput.format(_z);
  var f = feedOutput.format(_f);
  var e = eOutput.format(_e);
  if (x || y || z || f || e) {
    writeBlock(gMotionModal.format(1), x, y, z, f, e);
  }
}
 
function onCircularExtrude(_clockwise, _cx, _cy, _cz, _x, _y, _z, _f, _e) {
  var x = xOutput.format(_x);
  var y = yOutput.format(_y);
  var z = zOutput.format(_z);
  var f = feedOutput.format(_f);
  var e = eOutput.format(_e);
  var start = getCurrentPosition();
  var i = iOutput.format(_cx - start.x);
  var j = jOutput.format(_cy - start.y);
 
  switch (getCircularPlane()) {
  case PLANE_XY:
    writeBlock(gMotionModal.format(_clockwise ? 2 : 3), x, y, i, j, f, e);
    break;
  default:
    linearize(tolerance);
  }
}
 
function getLayersFromProperty(_property) {
  var layer = getProperty(_property).toString().split(",");
  for (var i in layer) {
    if (!isNaN(parseFloat(layer[i])) && !isNaN(layer[i] - 0) && (layer[i] - Math.floor(layer[i])) === 0) {
      layer[i] = parseFloat(layer[i], 10);
    } else {
      error(subst(
        localize("The property '%1' contains an invalid value of '%2'. Only integers are allowed."), _property.title, layer[i])
      );
      return undefined;
    }
  }
  return layer; // returns an array of layer numbers as integers
}
 
var pauseLayers;
function pausePrint(num) {
  if (getProperty("pauseLayers") != "") {
    validate(commands.pauseCommand != undefined, "The pause command is not defined.");
    if (num == 1) { // initialize array
      pauseLayers = getLayersFromProperty(properties.pauseLayers);
    }
    if (pauseLayers.indexOf(num) > -1) {
      writeComment(localize("PAUSE PRINT"));
      writeBlock(getCode(commands.displayCommand), getProperty("pauseMessage"));
      forceXYZE();
      writeBlock(gMotionModal.format(1), zOutput.format(machineConfiguration.getParkPositionZ()));
      writeBlock(gMotionModal.format(1), xOutput.format(machineConfiguration.getParkPositionX()), yOutput.format(machineConfiguration.getParkPositionY()));
      writeBlock(getCode(commands.pauseCommand));
    }
  }
}
 
var changeLayers;
function changeFilament(num) {
  if (getProperty("changeLayers") != "") {
    validate(commands.changeFilament.command != undefined, "The filament change command is not defined.");
    if (num == 1) { // initialize array
      changeLayers = getLayersFromProperty(properties.changeLayers);
    }
    if (changeLayers.indexOf(num) > -1) {
      writeComment(localize("FILAMENT CHANGE"));
      if (getProperty("changeMessage") != "") {
        writeBlock(getCode(commands.displayCommand), getProperty("changeMessage"));
      }
      var words = new Array();
      words.push(commands.changeFilament.command);
      /*
      if (!getProperty("useFirmwareConfiguration")) {
        words.push("X" + xyzFormat.format(machineConfiguration.getParkPositionX()));
        words.push("Y" + xyzFormat.format(machineConfiguration.getParkPositionY()));
        words.push("Z" + xyzFormat.format(getProperty("zPosition")));
        words.push(commands.changeFilament.initialRetract + xyzFormat.format(getProperty("initialRetract")));
        words.push(commands.changeFilament.removalRetract + xyzFormat.format(getProperty("removalRetract")));
      }
      */
      writeBlock(words);
      forceXYZE();
      feedOutput.reset();
    }
  }
}
 
function isLastMotionRecord(record) {
  while (!(getRecord(record).isMotion())) {
    if (getRecord(record).getType() == RECORD_OPERATION_END) {
      return true;
    }
    ++record;
  }
  return false;
}
 
var maximumExtruderTemp = [210, 210];
var rapidFeedrate = highFeedrate;
function initializeMachineParameters() {
  var machineData = hasGlobalParameter("machine-v2") ? JSON.parse(getGlobalParameter("machine-v2")) : null;
  if (machineData && typeof machineData == "object") {
    // data in the machine definition is always stored as degree celsius and millimeters
    maximumExtruderTemp[0] = parseFloat(machineData.additive_extruder[0].max_temp); // max temp for extruder 1
    if (machineData.additive_extruder[1]) {
      maximumExtruderTemp[1] = parseFloat(machineData.additive_extruder[1].max_temp); // max temp for extruder 2
    }
    rapidFeedrate = toPreciseUnit(parseFloat(machineData.limits.default.speed_xy_max) * 60, MM); // convert mm/s to mm/min
  } else {
    warning("Failed to read machine data, default values will be used instead.");
  }
  if (highFeedMapping != HIGH_FEED_NO_MAPPING) {
    highFeedMapping = HIGH_FEED_NO_MAPPING;
    warning(localize("The selected High Feedrate mapping method is not supported and has been automatically set to 'Preserve rapid movement' by the postprocessor."));
  }
}
// <<<<< INCLUDED FROM ../common/commonAdditiveFunctions.cpi