-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathp5.plotSvg.js
More file actions
3855 lines (3431 loc) · 141 KB
/
p5.plotSvg.js
File metadata and controls
3855 lines (3431 loc) · 141 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
// p5.plotSvg: a Plotter-Oriented SVG Exporter for p5.js
// https://github.com/golanlevin/p5.plotSvg
// Initiated by Golan Levin (@golanlevin)
// v.0.1.8, January 22, 2026
// Known to work with p5.js versions 1.4.2–1.11.11
(function(global) {
// Create a namespace for the library
const p5plotSvg = {};
// Attach constants to the p5plotSvg namespace
p5plotSvg.VERSION = "0.1.8";
p5plotSvg.SVG_INDENT_NONE = 0;
p5plotSvg.SVG_INDENT_SPACES = 1;
p5plotSvg.SVG_INDENT_TABS = 2;
p5plotSvg.SVG_UNITS_IN = 0;
p5plotSvg.SVG_UNITS_CM = 1;
// Internal properties set using setter functions
let _bFlattenTransforms = false; // false is default
let _bTransformsExist = false;
let _bSvgExportPolylinesAsPaths = false;
let _svgFilename = "output.svg";
let _svgCurveTightness = 0.0;
let _svgCoordPrecision = 4;
let _svgTransformPrecision = 6;
let _svgIndentType = p5plotSvg.SVG_INDENT_SPACES;
let _svgIndentAmount = 2;
let _svgPointRadius = 0.25; // Default radius for point representation
let _svgDPI = 96; // Default DPI value. Set from DPCM if needed.
let _svgUnitMode = p5plotSvg.SVG_UNITS_IN; // Default to inches
let _svgWidth = 816; // Default width for SVG output (8.5" at 96 DPI)
let _svgHeight = 1056; // Default height for SVG output (11" at 96 DPI)
let _svgDefaultStrokeColor = 'black';
let _svgCurrentStrokeColor = _svgDefaultStrokeColor;
let _svgBackgroundColor = null;
let _svgDefaultStrokeWeight = 1;
let _svgMergeNamedGroups = true;
let _svgGroupByStrokeColor = false;
let _svgInkscapeCompatibility = true; // Default: enabled
let _inkscapeLayerMap = {}; // Maps group names to layer numbers
let _inkscapeUsedLabels = {}; // Tracks all used label values (for collision detection)
let _inkscapeNextLayerNumber = 1; // Counter for auto-incrementing
// Internal variables, not to be accessed directly
let _p5Instance;
let _recordingSessionId = 0;
let _p5PixelDensity = 1;
let _svgGroupLevel = 0;
let _commands = [];
let _vertexStack = []; // Temp stack for polyline/polygon vertices
let _groupStack = []; // Stack for tracking open groups (for unclosed group detection)
let _hasNonDefaultStrokeColor = false; // True if user has used any non-default stroke color
let _injectedHeaderAttributes = []; // Attributes to inject into the SVG header
let _injectedDefs = [];
let _shapeMode = "simple"; // Track mode: "simple" or "complex"
let _shapeKind = "poly";
let _bRecordingSvg = false;
let _bRecordingSvgBegun = false;
let _bCustomSizeSet = false;
let _bP5v2WarningShown = false;
let _bCurveV2WarningShown = false;
let _bCurveTightnessV2WarningShown = false;
let _bClipWarningShown = false;
let _p5MajorVersion = 1; // Will be set when beginRecordSvg is called
let _pointsSetCount = 0;
let _linesSetCount = 0;
let _trianglesSetCount = 0;
let _triangleFanSetCount = 0;
let _triangleStripSetCount = 0;
let _quadsSetCount = 0;
let _quadStripSetCount = 0;
let _originalArcFunc;
let _originalBezierFunc;
let _originalCircleFunc;
let _originalCurveFunc;
let _originalEllipseFunc;
let _originalLineFunc;
let _originalPointFunc;
let _originalQuadFunc;
let _originalRectFunc;
let _originalSquareFunc;
let _originalTriangleFunc;
let _originalBezierDetailFunc;
let _originalCurveTightnessFunc;
let _originalBeginShapeFunc;
let _originalVertexFunc;
let _originalBezierVertexFunc;
let _originalQuadraticVertexFunc;
let _originalCurveVertexFunc;
let _originalBeginContourFunc;
let _originalEndContourFunc;
let _originalEndShapeFunc;
let _originalDescribeFunc;
let _originalPushFunc;
let _originalPopFunc;
let _originalScaleFunc;
let _originalTranslateFunc;
let _originalRotateFunc;
let _originalShearXFunc;
let _originalShearYFunc;
let _originalTextFunc;
let _originalStrokeFunc;
let _originalColorModeFunc;
let _originalClipFunc;
/**
* @private
* Overrides a function on a target object, handling p5.js v2's non-writable properties.
* In p5.js v2, global functions are defined with writable:false, so simple assignment fails.
* This helper uses Object.defineProperty when needed to ensure the override takes effect.
* @param {object} target - The object to override the function on (e.g., window or _p5Instance)
* @param {string} funcName - The name of the function to override
* @param {function} newFunc - The new function to use
*/
function overrideFunction(target, funcName, newFunc) {
if (_p5MajorVersion >= 2) {
// p5.js v2: properties are non-writable, must use defineProperty
Object.defineProperty(target, funcName, {
value: newFunc,
writable: true,
configurable: true,
enumerable: true
});
} else {
// p5.js v1: simple assignment works
target[funcName] = newFunc;
}
}
/**
* @private
* Restores a function on a target object to its original implementation.
* Uses Object.defineProperty for p5.js v2 compatibility.
* @param {object} target - The object to restore the function on
* @param {string} funcName - The name of the function to restore
* @param {function} originalFunc - The original function to restore
*/
function restoreFunction(target, funcName, originalFunc) {
if (_p5MajorVersion >= 2) {
// p5.js v2: use defineProperty but keep writable for compatibility
Object.defineProperty(target, funcName, {
value: originalFunc,
writable: true, // keep writable to avoid issues
configurable: true,
enumerable: true
});
} else {
// p5.js v1: simple assignment works
target[funcName] = originalFunc;
}
}
/**
* Begins recording SVG output for a p5.js sketch.
* Initializes recording state, validates and sets the output filename,
* and overrides p5.js drawing functions to capture drawing commands for SVG export.
* Behavior is as follows:
* beginRecordSvg(this); // saves to output.svg (default)
* beginRecordSvg(this, "file.svg"); // saves to file.svg
* beginRecordSvg(this, null); // DOES NOT save any file!
* @param {object} p5Instance - A reference to the current p5.js sketch (e.g. `this`).
* @param {string} [fn] - Optional filename for the output SVG file.
*/
p5plotSvg.beginRecordSvg = function(p5Instance, fn) {
// Validate the p5 instance
if (!p5Instance) {
throw new Error("Invalid p5 instance provided to beginRecordSvg().");
}
if (typeof p5Instance === 'string') {
throw new Error("beginRecordSvg() requires a p5 instance as the first argument. Use: beginRecordSvg(this, \"" + p5Instance + "\")");
}
// Detect p5.js version for compatibility handling
const p5Version = p5.VERSION || '1.0.0';
_p5MajorVersion = parseInt(p5Version.split('.')[0]);
// Store a reference to the p5 instance for use in other functions
// In p5.js v2 global mode, 'this' in draw() is window, not the p5 instance
// Use p5.instance instead when available and p5Instance appears to be window
if (_p5MajorVersion >= 2 && p5Instance === window && typeof p5.instance !== 'undefined') {
_p5Instance = p5.instance;
} else {
_p5Instance = p5Instance;
}
_p5PixelDensity = _p5Instance.pixelDensity();
// Warn if using v2 (only once per session)
if (!_bP5v2WarningShown && _p5MajorVersion >= 2) {
console.warn(
`p5.plotSvg: Detected p5.js version ${p5Version}. ` +
`This library is currently only designed for p5.js v1.x. Your mileage may vary with v2. ` +
`Basic geometry export should work, but curve commands and other programs using ` +
`beginShape/endShape may behave unexpectedly. v2 compatibility is planned for mid-2026. ` +
`If you experience issues with curves, consider using the p5.js v1.x compatibility add-on: ` +
`https://github.com/processing/p5.js-compatibility`
);
_bP5v2WarningShown = true;
}
// Check if filename is provided and valid
if (fn === null) {
// if fn is null, explicit opt-out: do NOT save a file
_svgFilename = null;
} else if (typeof fn === 'string' && fn.length > 0) {
// Ensure ".svg" extension is present
if (!fn.endsWith(".svg")) {
fn += ".svg";
}
// Strip out illegal filename characters (keep alphanumeric, hyphen, underscore, dot)
fn = fn.replace(/[^a-zA-Z0-9-_\.]/g, '');
// Get the base name (without .svg extension)
let base = fn.slice(0, -4);
// Check if base has any real content (not just dots)
let hasContent = base.replace(/\./g, '').length > 0;
// If base is empty or only dots, fall back to default
if (!hasContent) {
_svgFilename = "output.svg";
} else {
_svgFilename = fn;
}
} else {
// Default behavior: undefined or invalid fn → output.svg
_svgFilename = "output.svg";
}
// Initialize SVG settings and override functions
_bRecordingSvg = true;
_bRecordingSvgBegun = true;
_bTransformsExist = false;
_commands = [];
// This is critically important, do not move;
// Needed for addon libraries like e.g. p5PowerStroke to access _commands:
p5plotSvg._commands = _commands;
_vertexStack = [];
_groupStack = [];
_hasNonDefaultStrokeColor = false;
_injectedHeaderAttributes = [];
_injectedDefs = [];
_svgGroupLevel = 0;
_pointsSetCount = 0;
_linesSetCount = 0;
_trianglesSetCount = 0;
_triangleFanSetCount = 0;
_triangleStripSetCount = 0;
_quadsSetCount = 0;
_quadStripSetCount = 0;
_svgCurrentStrokeColor = _svgDefaultStrokeColor;
_inkscapeLayerMap = {};
_inkscapeUsedLabels = {};
_inkscapeNextLayerNumber = 1;
overrideP5Functions();
}
/**
* Pauses or unpauses recording of SVG output for a p5.js sketch,
* depending on whether the bPause argument is true or false.
*/
p5plotSvg.pauseRecordSvg = function(bPause) {
if (!_bRecordingSvgBegun){
console.warn("You must beginRecordSvg() before you can pauseRecordSvg().");
return;
} else {
if (bPause === true){
_bRecordingSvg = false;
} else if (bPause === false){
_bRecordingSvg = true;
}
}
}
/**
* Ends recording of SVG output for a p5.js sketch.
* Calls the export function to generate the SVG output
* and restores the original p5.js functions.
* Returns the text of the SVG file as a string.
*/
p5plotSvg.endRecordSvg = function() {
let svgStr = exportSVG();
restoreP5Functions();
_bRecordingSvg = false;
_bRecordingSvgBegun = false;
_recordingSessionId++;
p5plotSvg._recordingSessionId = _recordingSessionId;
return svgStr;
}
// Old names: wrappers for backward compatibility
p5plotSvg.beginRecordSVG = function() {
console.warn("beginRecordSVG() is deprecated. The new name is beginRecordSvg().");
return p5plotSvg.beginRecordSvg.apply(p5plotSvg, arguments);
};
p5plotSvg.pauseRecordSVG = function() {
console.warn("pauseRecordSVG() is deprecated. The new name is pauseRecordSvg().");
return p5plotSvg.pauseRecordSvg.apply(p5plotSvg, arguments);
};
p5plotSvg.endRecordSVG = function() {
console.warn("endRecordSVG() is deprecated. The new name is endRecordSvg().");
return p5plotSvg.endRecordSvg.apply(p5plotSvg, arguments);
};
/**
* @private
* Overrides p5.js drawing functions to capture commands for SVG export.
* Includes support for shapes, vertices, transformations, and text functions.
*/
function overrideP5Functions() {
overrideArcFunction();
overrideBezierFunction();
overrideCircleFunction();
overrideCurveFunction();
overrideEllipseFunction();
overrideLineFunction();
overridePointFunction();
overrideQuadFunction();
overrideRectFunction();
overrideSquareFunction();
overrideTriangleFunction();
overrideBezierDetailFunction();
overrideCurveTightnessFunction();
overrideBeginShapeFunction();
overrideVertexFunction();
overrideBezierVertexFunction();
overrideQuadraticVertexFunction();
overrideCurveVertexFunction();
overrideBeginContourFunction();
overrideEndContourFunction();
overrideEndShapeFunction();
overrideDescribeFunction();
overridePushFunction();
overridePopFunction();
overrideScaleFunction();
overrideTranslateFunction();
overrideRotateFunction();
overrideShearXFunction();
overrideShearYFunction();
overrideTextFunction();
overrideStrokeFunction();
overrideColorModeFunction();
overrideClipFunction();
}
/**
* @private
* Restores the original p5.js drawing functions that were overridden for SVG export.
* Reverts all overrides, returning p5.js functions to their standard behavior.
*/
function restoreP5Functions(){
restoreFunction(_p5Instance, 'arc', _originalArcFunc);
restoreFunction(window, 'arc', _originalArcFunc);
restoreFunction(_p5Instance, 'bezier', _originalBezierFunc);
restoreFunction(window, 'bezier', _originalBezierFunc);
restoreFunction(_p5Instance, 'circle', _originalCircleFunc);
restoreFunction(window, 'circle', _originalCircleFunc);
// curve() was removed in p5.js v2 - only restore in v1
if (_p5MajorVersion < 2) {
restoreFunction(_p5Instance, 'curve', _originalCurveFunc);
restoreFunction(window, 'curve', _originalCurveFunc);
}
restoreFunction(_p5Instance, 'ellipse', _originalEllipseFunc);
restoreFunction(window, 'ellipse', _originalEllipseFunc);
restoreFunction(_p5Instance, 'line', _originalLineFunc);
restoreFunction(window, 'line', _originalLineFunc);
restoreFunction(_p5Instance, 'point', _originalPointFunc);
restoreFunction(window, 'point', _originalPointFunc);
restoreFunction(_p5Instance, 'quad', _originalQuadFunc);
restoreFunction(window, 'quad', _originalQuadFunc);
restoreFunction(_p5Instance, 'rect', _originalRectFunc);
restoreFunction(window, 'rect', _originalRectFunc);
restoreFunction(_p5Instance, 'square', _originalSquareFunc);
restoreFunction(window, 'square', _originalSquareFunc);
restoreFunction(_p5Instance, 'triangle', _originalTriangleFunc);
restoreFunction(window, 'triangle', _originalTriangleFunc);
_p5Instance.bezierDetail = _originalBezierDetailFunc;
// curveTightness() was removed in p5.js v2 - only restore in v1
if (_p5MajorVersion < 2) {
_p5Instance.curveTightness = _originalCurveTightnessFunc;
}
_p5Instance.beginShape = _originalBeginShapeFunc;
_p5Instance.vertex = _originalVertexFunc;
_p5Instance.bezierVertex = _originalBezierVertexFunc;
_p5Instance.quadraticVertex = _originalQuadraticVertexFunc;
_p5Instance.curveVertex = _originalCurveVertexFunc;
_p5Instance.beginContour = _originalBeginContourFunc;
_p5Instance.endContour = _originalEndContourFunc;
_p5Instance.endShape = _originalEndShapeFunc;
_p5Instance.describe = _originalDescribeFunc;
_p5Instance.push = _originalPushFunc;
_p5Instance.pop = _originalPopFunc;
_p5Instance.scale = _originalScaleFunc;
_p5Instance.translate = _originalTranslateFunc;
_p5Instance.rotate = _originalRotateFunc;
_p5Instance.shearX = _originalShearXFunc;
_p5Instance.shearY = _originalShearYFunc;
_p5Instance.text = _originalTextFunc;
_p5Instance.stroke = _originalStrokeFunc;
_p5Instance.colorMode = _originalColorModeFunc;
_p5Instance.clip = _originalClipFunc;
}
/**
* @private
* Overrides the p5.js arc function to capture SVG arc commands for export.
* Supports different arc modes. Warns about optional detail parameter in WEBGL context.
* Stores arc parameters in the `_commands` array when recording SVG output.
* @see {@link https://p5js.org/reference/p5/arc/}
*/
function overrideArcFunction() {
// Save the original window.arc for proper restoration in v2
_originalArcFunc = window.arc;
const newArcFunc = function(x, y, w, h, start, stop, mode = OPEN, detail = 0) {
if (_bRecordingSvg) {
if (detail !== undefined && _p5Instance._renderer?.drawingContext instanceof WebGLRenderingContext) {
console.warn("arc() detail is currently unsupported in SVG output.");
}
// Get ellipseMode: v2 stores in states.ellipseMode, v1 in _ellipseMode
const ellipseMode = _p5Instance._renderer?.states?.ellipseMode ||
_p5Instance._renderer?._ellipseMode ||
'center';
// Adjust x, y, w, h based on ellipseMode (arc follows ellipse mode)
if (ellipseMode === 'center') {
// No adjustment needed for 'center'
} else if (ellipseMode === 'corner') {
x += w / 2;
y += h / 2;
} else if (ellipseMode === 'radius') {
w *= 2;
h *= 2;
} else if (ellipseMode === 'corners') {
let px = Math.min(x, w);
let qx = Math.max(x, w);
let py = Math.min(y, h);
let qy = Math.max(y, h);
x = px + (qx - px) / 2;
y = py + (qy - py) / 2;
w = qx - px;
h = qy - py;
}
let transformMatrix = captureCurrentTransformMatrix();
_commands.push({ type: 'arc', x, y, w, h, start, stop, mode, transformMatrix });
}
_originalArcFunc.apply(_p5Instance, arguments);
};
overrideFunction(_p5Instance, 'arc', newArcFunc);
overrideFunction(window, 'arc', newArcFunc);
}
/**
* @private
* Overrides the p5.js bezier function to capture SVG bezier curve commands for export.
* Stores bezier curve control points in the `_commands` array when recording SVG output.
* @see {@link https://p5js.org/reference/p5/bezier/}
*/
function overrideBezierFunction(){
// Save the original window.bezier for proper restoration in v2
_originalBezierFunc = window.bezier;
const newBezierFunc = function(x1, y1, x2, y2, x3, y3, x4, y4) {
if (_bRecordingSvg) {
let transformMatrix = captureCurrentTransformMatrix();
_commands.push({ type: 'bezier', x1, y1, x2, y2, x3, y3, x4, y4, transformMatrix });
}
_originalBezierFunc.apply(_p5Instance, arguments);
};
overrideFunction(_p5Instance, 'bezier', newBezierFunc);
overrideFunction(window, 'bezier', newBezierFunc);
}
/**
* @private
* Overrides the p5.js circle function to capture SVG circle commands for export.
* Handles different ellipse modes (center, corner, radius, corners)
* to convert circle parameters appropriately.
* Stores circle or ellipse parameters in the `_commands` array when recording SVG output.
* @see {@link https://p5js.org/reference/p5/circle/}
*/
function overrideCircleFunction(){
// Save the original window.circle for proper restoration in v2
_originalCircleFunc = window.circle;
const newCircleFunc = function(x, y, d) {
let argumentsCopy = [...arguments]; // safe snapshot
if (_bRecordingSvg) {
let transformMatrix = captureCurrentTransformMatrix();
// Get ellipseMode: v2 stores in states.ellipseMode, v1 in _ellipseMode
const ellipseMode = _p5Instance._renderer?.states?.ellipseMode ||
_p5Instance._renderer?._ellipseMode ||
'center';
if (ellipseMode === 'center'){
_commands.push({ type: 'circle', x, y, d, transformMatrix });
} else if (ellipseMode === 'corner'){
x += d/2;
y += d/2;
_commands.push({ type: 'circle', x, y, d, transformMatrix });
} else if (ellipseMode === 'radius'){
d *= 2;
_commands.push({ type: 'circle', x, y, d, transformMatrix });
} else if (ellipseMode === 'corners'){
let w = d - x;
let h = d - y;
x += w/2;
y += h/2;
_commands.push({ type: 'ellipse', x, y, w, h, transformMatrix });
}
}
_originalCircleFunc.apply(_p5Instance, argumentsCopy);
};
overrideFunction(_p5Instance, 'circle', newCircleFunc);
overrideFunction(window, 'circle', newCircleFunc);
}
/**
* @private
* Overrides the p5.js curve function to capture SVG curve commands for export.
* Stores curve parameters and current tightness in the `_commands` array.
* @see {@link https://p5js.org/reference/#/p5/curve}
*/
function overrideCurveFunction() {
// curve() was removed in p5.js v2 - skip override and warn if used
if (_p5MajorVersion >= 2) {
// Define a stub that warns the user
const curveWarningFunc = function() {
if (!_bCurveV2WarningShown) {
console.warn("curve() is no longer defined in p5.js v.2.x. This function will not be recorded.");
_bCurveV2WarningShown = true;
}
};
overrideFunction(_p5Instance, 'curve', curveWarningFunc);
overrideFunction(window, 'curve', curveWarningFunc);
return;
}
// p5.js v1 - normal override
_originalCurveFunc = window.curve;
const newCurveFunc = function(x1, y1, x2, y2, x3, y3, x4, y4) {
let argumentsCopy = [...arguments]; // safe snapshot
if (_bRecordingSvg) {
let transformMatrix = captureCurrentTransformMatrix();
let tightness = _svgCurveTightness; // Capture current tightness (set via curveTightness override)
_commands.push({ type: 'curve', x1, y1, x2, y2, x3, y3, x4, y4, tightness, transformMatrix });
}
_originalCurveFunc.apply(_p5Instance, argumentsCopy);
};
overrideFunction(_p5Instance, 'curve', newCurveFunc);
overrideFunction(window, 'curve', newCurveFunc);
}
/**
* @private
* Overrides the p5.js ellipse function to capture SVG ellipse commands for export.
* Handles different ellipse modes (center, corner, radius, corners) and warns
* when detail is used in WEBGL context as it is unsupported for SVG output.
* Stores ellipse parameters in the `_commands` array when recording SVG output.
* @see {@link https://p5js.org/reference/p5/ellipse/}
*/
function overrideEllipseFunction(){
// Save the original window.ellipse for proper restoration in v2
_originalEllipseFunc = window.ellipse;
const newEllipseFunc = function(x, y, w, h, detail = 0) {
let argumentsCopy = [...arguments]; // safe snapshot
if (_bRecordingSvg) {
if (detail !== undefined && _p5Instance._renderer?.drawingContext instanceof WebGLRenderingContext) {
console.warn("ellipse() detail is currently unsupported in SVG output.");
}
// Get ellipseMode: v2 stores in states.ellipseMode, v1 in _ellipseMode
const ellipseMode = _p5Instance._renderer?.states?.ellipseMode ||
_p5Instance._renderer?._ellipseMode ||
'center';
if (ellipseMode === 'center'){
;
} else if (ellipseMode === 'corner'){
x += w/2;
y += h/2;
} else if (ellipseMode === 'radius'){
w *= 2;
h *= 2;
} else if (ellipseMode === 'corners'){
let px = Math.min(x, w);
let qx = Math.max(x, w);
let py = Math.min(y, h);
let qy = Math.max(y, h);
x = px;
y = py;
w = qx - px;
h = qy - py;
x += w/2;
y += h/2;
}
let transformMatrix = captureCurrentTransformMatrix();
_commands.push({ type: 'ellipse', x, y, w, h, transformMatrix });
}
_originalEllipseFunc.apply(_p5Instance, argumentsCopy);
};
overrideFunction(_p5Instance, 'ellipse', newEllipseFunc);
overrideFunction(window, 'ellipse', newEllipseFunc);
}
/**
* @private
* Overrides the p5.js line function to capture SVG line commands for export.
* Stores line parameters in the `_commands` array when recording SVG output.
* @see {@link https://p5js.org/reference/p5/line/}
*/
function overrideLineFunction() {
// Save the original window.line for proper restoration in v2
_originalLineFunc = window.line;
const newLineFunc = function(x1, y1, x2, y2) {
if (_bRecordingSvg) {
let transformMatrix = captureCurrentTransformMatrix();
_commands.push({ type: 'line', x1, y1, x2, y2, transformMatrix });
}
_originalLineFunc.apply(_p5Instance, arguments);
};
overrideFunction(_p5Instance, 'line', newLineFunc);
overrideFunction(window, 'line', newLineFunc);
}
/**
* @private
* Overrides the p5.js point function to capture SVG point commands for export.
* Stores point parameters as small circles in the `_commands` array when recording SVG output.
* @see {@link https://p5js.org/reference/p5/point/}
*/
function overridePointFunction() {
// Save the original window.point for proper restoration in v2
_originalPointFunc = window.point;
const newPointFunc = function(x, y) {
if (_bRecordingSvg) {
let transformMatrix = captureCurrentTransformMatrix();
_commands.push({ type: 'point', x, y, radius: _svgPointRadius, transformMatrix });
}
_originalPointFunc.apply(_p5Instance, arguments);
};
overrideFunction(_p5Instance, 'point', newPointFunc);
overrideFunction(window, 'point', newPointFunc);
}
/**
* @private
* Overrides the p5.js quad function to capture SVG quad commands for export.
* Stores quad parameters in the `_commands` array when recording SVG output.
* @see {@link https://p5js.org/reference/p5/quad/}
*/
function overrideQuadFunction(){
// Save the original window.quad for proper restoration in v2
_originalQuadFunc = window.quad;
const newQuadFunc = function(x1, y1, x2, y2, x3, y3, x4, y4) {
if (_bRecordingSvg) {
let transformMatrix = captureCurrentTransformMatrix();
_commands.push({ type: 'quad', x1, y1, x2, y2, x3, y3, x4, y4, transformMatrix });
}
_originalQuadFunc.apply(_p5Instance, arguments);
};
overrideFunction(_p5Instance, 'quad', newQuadFunc);
overrideFunction(window, 'quad', newQuadFunc);
}
/**
* @private
* Overrides the p5.js rect function to capture SVG rect commands for export.
* Handles different rect modes (corner, center, radius, corners) and supports
* rectangles with optional uniform or individual corner radii.
* Stores rect parameters in the `_commands` array when recording SVG output.
* @see {@link https://p5js.org/reference/p5/rect/}
*/
function overrideRectFunction() {
// Save the original window.rect for proper restoration in v2
_originalRectFunc = window.rect;
const newRectFunc = function(x, y, w, h, tl, tr, br, bl) {
let argumentsCopy = [...arguments]; // safe snapshot
if (_bRecordingSvg) {
if (arguments.length === 3) { h = w; }
// Get rectMode: v2 stores in states.rectMode, v1 in _rectMode
const rectMode = _p5Instance._renderer?.states?.rectMode ||
_p5Instance._renderer?._rectMode ||
'corner';
// Handle different rect modes
if (rectMode === 'corner') {
// No adjustment needed for 'corner'
} else if (rectMode === 'center') {
x = x - w / 2;
y = y - h / 2;
} else if (rectMode === 'radius') {
x = x - w;
y = y - h;
w = 2 * w;
h = 2 * h;
} else if (rectMode === 'corners') {
let px = Math.min(x, w);
let qx = Math.max(x, w);
let py = Math.min(y, h);
let qy = Math.max(y, h);
x = px;
y = py;
w = qx - px;
h = qy - py;
}
let transformMatrix = captureCurrentTransformMatrix();
// Check for corner radii
if (arguments.length === 5) { // Single corner radius
_commands.push({ type: 'rect', x, y, w, h, tl, transformMatrix });
} else if (arguments.length === 8) { // Individual corner radii
_commands.push({ type: 'rect', x, y, w, h, tl,tr,br,bl, transformMatrix });
} else { // Standard rectangle
_commands.push({ type: 'rect', x, y, w, h, transformMatrix });
}
}
_originalRectFunc.apply(_p5Instance, argumentsCopy);
};
overrideFunction(_p5Instance, 'rect', newRectFunc);
overrideFunction(window, 'rect', newRectFunc);
}
/**
* @private
* Overrides the p5.js square function to capture SVG square commands for export.
* Handles different rect modes (corner, center, radius, corners) and supports
* squares with optional uniform or individual corner radii.
* Converts square parameters to equivalent rectangle parameters and stores them
* in the `_commands` array when recording SVG output.
* @see {@link https://p5js.org/reference/p5/square/}
*/
function overrideSquareFunction(){
// Save the original window.square for proper restoration in v2
_originalSquareFunc = window.square;
const newSquareFunc = function(x, y, s, tl, tr, br, bl) {
let argumentsCopy = [...arguments]; // safe snapshot
if (_bRecordingSvg) {
let w = s;
let h = s;
// Get rectMode: v2 stores in states.rectMode, v1 in _rectMode
const rectMode = _p5Instance._renderer?.states?.rectMode ||
_p5Instance._renderer?._rectMode ||
'corner';
if (rectMode === 'corner'){
;
} else if (rectMode === 'center'){
x = x - w/2;
y = y - h/2;
} else if (rectMode === 'radius'){
x = x - w;
y = y - h;
w = 2*w;
h = 2*h;
} else if (rectMode === 'corners'){
let px = Math.min(x, s);
let qx = Math.max(x, s);
let py = Math.min(y, s);
let qy = Math.max(y, s);
x = px;
y = py;
w = qx - px;
h = qy - py;
}
let transformMatrix = captureCurrentTransformMatrix();
if (arguments.length === 3) { // standard square
_commands.push({ type: 'rect', x, y, w, h, transformMatrix });
} else if (arguments.length === 4) { // rounded square
_commands.push({ type: 'rect', x, y, w, h, tl, transformMatrix });
} else if (arguments.length === 7) {
_commands.push({ type: 'rect', x, y, w, h, tl, tr, br, bl, transformMatrix });
}
}
_originalSquareFunc.apply(_p5Instance, argumentsCopy);
};
overrideFunction(_p5Instance, 'square', newSquareFunc);
overrideFunction(window, 'square', newSquareFunc);
}
/**
* @private
* Overrides the p5.js triangle function to capture SVG triangle commands for export.
* Stores triangle vertex coordinates in the `_commands` array when recording SVG output.
* @see {@link https://p5js.org/reference/p5/triangle/}
*/
function overrideTriangleFunction(){
// Save the original window.triangle for proper restoration in v2
_originalTriangleFunc = window.triangle;
const newTriangleFunc = function(x1, y1, x2, y2, x3, y3) {
if (_bRecordingSvg) {
let transformMatrix = captureCurrentTransformMatrix();
_commands.push({ type: 'triangle', x1, y1, x2, y2, x3, y3, transformMatrix });
}
_originalTriangleFunc.apply(_p5Instance, arguments);
};
overrideFunction(_p5Instance, 'triangle', newTriangleFunc);
overrideFunction(window, 'triangle', newTriangleFunc);
}
/**
* @private
* Overrides the p5.js bezierDetail function to provide a warning when used in WEBGL context.
* Warns users that bezierDetail is currently unsupported in SVG output.
* https://p5js.org/reference/p5/bezierDetail/
*/
function overrideBezierDetailFunction() {
_originalBezierDetailFunc = _p5Instance.bezierDetail;
_p5Instance.bezierDetail = function(detailLevel) { // Check if the renderer is WEBGL
if (p5.instance._renderer.drawingContext instanceof WebGLRenderingContext) {
console.warn("bezierDetail() is currently unsupported in SVG output.");
}
_originalBezierDetailFunc.apply(this, arguments);
};
}
/**
* @private
* Overrides the p5.js curveTightness function to capture curve tightness settings for SVG export.
* Updates the `_svgCurveTightness` variable to reflect the specified tightness value.
* @see {@link https://p5js.org/reference/p5/curveTightness/}
*/
function overrideCurveTightnessFunction() {
// curveTightness() was removed in p5.js v2 - skip override and warn if used
if (_p5MajorVersion >= 2) {
const curveTightnessWarningFunc = function() {
if (!_bCurveTightnessV2WarningShown) {
console.warn("curveTightness() is no longer defined in p5.js v.2.x.");
_bCurveTightnessV2WarningShown = true;
}
};
overrideFunction(_p5Instance, 'curveTightness', curveTightnessWarningFunc);
overrideFunction(window, 'curveTightness', curveTightnessWarningFunc);
return;
}
// p5.js v1 - normal override
_originalCurveTightnessFunc = _p5Instance.curveTightness;
_p5Instance.curveTightness = function(tightness) {
if (_bRecordingSvg) {
_svgCurveTightness = tightness;
}
_originalCurveTightnessFunc.apply(this, arguments);
};
}
/**
* @private
* Overrides the p5.js beginShape function to initiate shape recording for SVG export.
* Initializes the vertex stack and sets the shape kind based on the provided kind parameter.
* @see {@link https://p5js.org/reference/p5/beginShape/}
*/
function overrideBeginShapeFunction() {
_originalBeginShapeFunc = _p5Instance.beginShape;
_p5Instance.beginShape = function(kind) {
if (_bRecordingSvg) {
_vertexStack = []; // Start with an empty vertex stack
_shapeMode = "simple"; // Assume simple mode initially
if ((kind !== null) && (kind === 0)) {
_shapeKind = 'points';
} else if (kind === null){
_shapeKind = 'poly'; // default to "poly" for polyline/polygon
} else {
_shapeKind = kind;
}
}
_originalBeginShapeFunc.apply(this, arguments);
};
}
/**
* @private
* Overrides the p5.js vertex function to capture vertex coordinates for SVG export.
* Pushes simple vertex data to the `_vertexStack` when recording is active.
* @see {@link https://p5js.org/reference/p5/vertex/}
*/
function overrideVertexFunction() {
_originalVertexFunc = _p5Instance.vertex;
_p5Instance.vertex = function(x, y) {
if (_bRecordingSvg) {
_vertexStack.push({ type: 'vertex', x, y });
}
_originalVertexFunc.apply(this, arguments);
};
}
/**
* @private
* Overrides the p5.js bezierVertex function to capture Bézier control points for SVG export.
* Marks the current shape as complex and stores Bézier vertex data in the `_vertexStack`.
* @see {@link https://p5js.org/reference/p5/bezierVertex/}
*/
function overrideBezierVertexFunction() {
// Override `bezierVertex()` and mark shape as complex
_originalBezierVertexFunc = _p5Instance.bezierVertex;
_p5Instance.bezierVertex = function(x2, y2, x3, y3, x4, y4) {
if (_bRecordingSvg) {
_shapeMode = 'complex'; // Switch to complex mode
_vertexStack.push({ type: 'bezier', x2, y2, x3, y3, x4, y4 });
}
_originalBezierVertexFunc.apply(this, arguments);
};
}
/**
* @private
* Overrides the p5.js quadraticVertex function to capture quadratic Bézier control points for SVG export.
* Marks the current shape as complex and stores quadratic vertex data in the `_vertexStack`.
* @see {@link https://p5js.org/reference/p5/quadraticVertex/}
*/
function overrideQuadraticVertexFunction() {
// Override `quadraticVertex()` and mark shape as complex
_originalQuadraticVertexFunc = _p5Instance.quadraticVertex;
_p5Instance.quadraticVertex = function(cx, cy, x, y) {
if (_bRecordingSvg) {
_shapeMode = 'complex'; // Switch to complex mode
_vertexStack.push({ type: 'quadratic', cx, cy, x, y });
}
_originalQuadraticVertexFunc.apply(this, arguments);
};
}
/**
* @private
* Overrides the p5.js curveVertex function to capture Catmull-Rom curve control points for SVG export.
* Marks the current shape as complex and handles specific kludge logic for initial vertices.
* @see {@link https://p5js.org/reference/p5/curveVertex/}
*/
function overrideCurveVertexFunction() {
// Override `curveVertex()` and mark shape as complex
_originalCurveVertexFunc = _p5Instance.curveVertex;
_p5Instance.curveVertex = function(x, y) {
if (_bRecordingSvg) {
_shapeMode = 'complex'; // Switch to complex mode
let tightness = _svgCurveTightness; // Capture current tightness
let bDoKludge = true; // TODO: Revisit
if (bDoKludge){
if (_vertexStack.length === 1){
if(_vertexStack[0].type === 'curve'){
let x0 = _vertexStack[0].x;
let y0 = _vertexStack[0].y;
let dist01 = Math.hypot(x-x0, y-y0);
if (dist01 > 0){
_vertexStack.shift();
_vertexStack.push({ type: 'curve', x, y, tightness });
}
}
}
}
_vertexStack.push({ type: 'curve', x, y, tightness });
}
_originalCurveVertexFunc.apply(this, arguments);
};
}
/**
* @private
* Overrides the p5.js beginContour function to mark the start of an inner contour.