-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPopSvg.js
More file actions
1074 lines (914 loc) · 27.3 KB
/
PopSvg.js
File metadata and controls
1074 lines (914 loc) · 27.3 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
const Debug = console.log;
const Warning = console.warn;
// webspecific api!
function ParseXml(Xml)
{
// web version makes use of the dom parser
// https://stackoverflow.com/a/7951947/355753
if ( typeof window.DOMParser == 'undefined' )
throw "XML parser not supported";
const Parser = new window.DOMParser();
const Dom = Parser.parseFromString(Xml, 'text/xml');
const Object = Dom.documentElement;
return Object;
}
function ParseCss(CssString)
{
// requires PopEngineCommon/Css.js/css.js
const Parser = new cssjs();
const CssJson = Parser.parseCSS(CssString);
return CssJson;
}
function CleanSvg(DomSvg)
{
// the DOMParser turns the svg into a proper svg object, so this func cleans it up
const Svg = {};
Svg.ViewBox = DomSvg.attributes.viewBox.value;
function CreateGroup()
{
const Group = {};
Group.Children = [];
return Group;
}
Svg.Root = CreateGroup();
//
const CssMap = {};
const LinearGradientMap = {};
const RadialGradientMap = {};
function GetStyleFromClass(Class)
{
// temp catch, safari doesn't pre-gen classes
try
{
const Selector = `.${Class}`;
if ( !CssMap.hasOwnProperty(Selector) )
throw `Failed to get css style for ${Class}`;
return CssMap[Selector];
}
catch(e)
{
Debug(`Exception in GetStyleFromClass; ${e}`);
return GetDefaultStyle();
}
}
function PushGroup(Node,Parent)
{
const GroupName = Node.attributes.id;
Debug(`Todo process group ${GroupName}`,Node);
}
function GetShape(Node)
{
const Type = Node.tagName;
const Attribs = Array.from(Node.attributes);
const Shape = {};
function AddAttribute(Attrib)
{
Shape[Attrib.name] = Attrib.value;
}
Attribs.forEach(AddAttribute);
if ( Node.attributes.class )
Shape.Style = GetStyleFromClass(Node.attributes.class.value);
else
Shape.Style = GetDefaultStyle();
Shape.Type = Type;
//const Style = Node.attributes.class;
//const Points = Node.attributes.points;
return Shape;
}
function PushNode(Node,Parent)
{
const TagName = Node.tagName;
if ( TagName == 'g' )
{
const Group = CreateGroup();
if ( Node.attributes.id )
Group.Name = Node.attributes.id.value;
else
Group.Name = null;
Array.from(Node.children).forEach( n => PushNode(n,Group) );
Parent.Children.push(Group);
}
else
{
const Shape = GetShape(Node);
Parent.Children.push(Shape);
}
}
function GetDefaultStyle()
{
// Debug("GetDefaultStyle");
// defaults;
// https://www.w3.org/TR/SVG/painting.html#StrokeWidthProperty
const SvgDefaults = {};
SvgDefaults['stroke-width'] = 1;
SvgDefaults['stroke'] = 'none';
SvgDefaults['fill'] = 'black';
SvgDefaults['stroke-linecap'] = 'butt';
return SvgDefaults;
}
function ParseChromiumStyle(CssRule)
{
// can get multiple selectors for one style!
const SelectorNames = CssRule.selectorText.split(',').map( s => s.trim() );
const Style = {};
// CssRule.style has members like 0:'fill' and an element 'fill':'value'
const Styles = Array.from(CssRule.style);
for ( let Property of Styles )
{
const Key = Property;
const Value = CssRule.style[Key];
Style[Key] = Value;
}
for ( let SelectorName of SelectorNames )
{
// merge style values
let CurrentStyle = CssMap[SelectorName];
if ( CurrentStyle === undefined )
CurrentStyle = GetDefaultStyle();
// overwrite new values
Object.assign( CurrentStyle, Style );
// Debug(`Merged style ${SelectorName};`,CurrentStyle);
CssMap[SelectorName] = CurrentStyle;
}
//Debug('SelectorNames',SelectorNames,"Style",Style);
}
function ParseCssjsStyle(CssRule)
{
const ChromiumRule = {};
ChromiumRule.selectorText = CssRule.selector; // csv names
ChromiumRule.style = {};
// reformat to match the chromium style; [N]=key [Key]=Value
// "rules":[{"directive":"fill","value":"#e3db7a"}]}
function PushStyle(Rule,RuleIndex)
{
const Key = Rule.directive;
const Value = Rule.value;
ChromiumRule.style[RuleIndex] = Key;
ChromiumRule.style[Key] = Value;
}
CssRule.rules.forEach( PushStyle );
// make it iterable for Array.from()
ChromiumRule.style.length = CssRule.rules.length;
ParseChromiumStyle(ChromiumRule);
}
function ProcessStyles(Node)
{
const CssText = Node.textContent;
// Node.sheet not on safari, so use 3rd party
// 3rd party parser
const CssRules = ParseCss(CssText);
// Debug('css',JSON.stringify(CssRules));
CssRules.forEach( ParseCssjsStyle );
/*
if ( Node.sheet )
{
const CssRules = Node.sheet.rules;
Array.from(CssRules).forEach( ParseChromiumStyle );
}
*/
}
function ProcessRadialGradient(Node)
{
/*
<radialGradient id="radial-gradient-5" cx="1156.78" cy="233.61" r="54.68" gradientUnits="userSpaceOnUse">
<stop offset="0.43" stop-color="#904c30"/>
<stop offset="0.55" stop-color="#a81e27"/>
<stop offset="0.7" stop-color="#dd3024"/>
<stop offset="0.72" stop-color="#dc4436"/>
<stop offset="0.79" stop-color="#da7460"/>
<stop offset="0.85" stop-color="#d99a81"/>
<stop offset="0.91" stop-color="#d8b699"/>
<stop offset="0.96" stop-color="#d7c6a7"/>
<stop offset="1" stop-color="#d7ccac"/>
</radialGradient>*/
}
function ProcessLinearGradient(Node)
{
/*
<linearGradient id="linear-gradient-4" x1="1246.44" y1="347.86" x2="1544.83" y2="257.4" gradientUnits="userSpaceOnUse">
<stop offset="0.02" stop-color="#aa8789"/>
<stop offset="0.04" stop-color="#6c445f"/>
<stop offset="0.35" stop-color="#603757"/>
<stop offset="0.37" stop-color="#ad8b8b"/>
<stop offset="0.63" stop-color="#b99793"/>
<stop offset="0.66" stop-color="#9a7d86"/>
</linearGradient>
*/
}
function ProcessDef(Node)
{
switch(Node.tagName)
{
case 'style': return ProcessStyles(Node);
case 'linearGradient': return ProcessLinearGradient(Node);
case 'radialGradient': return ProcessRadialGradient(Node);
default: throw `Unhandled svg tag ${Node.tagName}`;
}
}
function PushRootChild(Child)
{
const TagName = Child.tagName;
if ( TagName == 'defs' )
return Array.from(Child.children).forEach(ProcessDef);
return PushNode(Child,Svg.Root);
}
Array.from(DomSvg.children).forEach(PushRootChild);
// Debug("CSS selectors", Object.keys(CssMap) );
return Svg;
}
// https://github.com/MadLittleMods/svg-curve-lib/blob/master/src/js/svg-curve-lib.js#L84
function GetPointOnArc(p0, rx, ry, xAxisRotation, largeArcFlag, sweepFlag, p1, t)
{
function distance(p0, p1) {
return Math.sqrt(Math.pow(p1.x-p0.x, 2) + Math.pow(p1.y-p0.y, 2));
}
function mod(x, m) {
return (x%m + m)%m;
}
function toRadians(angle) {
return angle * (Math.PI / 180);
}
function angleBetween(v0, v1) {
var p = v0.x*v1.x + v0.y*v1.y;
var n = Math.sqrt((Math.pow(v0.x, 2)+Math.pow(v0.y, 2)) * (Math.pow(v1.x, 2)+Math.pow(v1.y, 2)));
var sign = v0.x*v1.y - v0.y*v1.x < 0 ? -1 : 1;
var angle = sign*Math.acos(p/n);
//var angle = Math.atan2(v0.y, v0.x) - Math.atan2(v1.y, v1.x);
return angle;
}
function clamp(val, min, max) {
return Math.min(Math.max(val, min), max);
}
// In accordance to: http://www.w3.org/TR/SVG/implnote.html#ArcOutOfRangeParameters
rx = Math.abs(rx);
ry = Math.abs(ry);
xAxisRotation = mod(xAxisRotation, 360);
var xAxisRotationRadians = toRadians(xAxisRotation);
// If the endpoints are identical, then this is equivalent to omitting the elliptical arc segment entirely.
if(p0.x === p1.x && p0.y === p1.y) {
return p0;
}
// If rx = 0 or ry = 0 then this arc is treated as a straight line segment joining the endpoints.
if(rx === 0 || ry === 0) {
return this.pointOnLine(p0, p1, t);
}
// Following "Conversion from endpoint to center parameterization"
// http://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
// Step #1: Compute transformedPoint
var dx = (p0.x-p1.x)/2;
var dy = (p0.y-p1.y)/2;
var transformedPoint = {
x: Math.cos(xAxisRotationRadians)*dx + Math.sin(xAxisRotationRadians)*dy,
y: -Math.sin(xAxisRotationRadians)*dx + Math.cos(xAxisRotationRadians)*dy
};
// Ensure radii are large enough
var radiiCheck = Math.pow(transformedPoint.x, 2)/Math.pow(rx, 2) + Math.pow(transformedPoint.y, 2)/Math.pow(ry, 2);
if(radiiCheck > 1) {
rx = Math.sqrt(radiiCheck)*rx;
ry = Math.sqrt(radiiCheck)*ry;
}
// Step #2: Compute transformedCenter
var cSquareNumerator = Math.pow(rx, 2)*Math.pow(ry, 2) - Math.pow(rx, 2)*Math.pow(transformedPoint.y, 2) - Math.pow(ry, 2)*Math.pow(transformedPoint.x, 2);
var cSquareRootDenom = Math.pow(rx, 2)*Math.pow(transformedPoint.y, 2) + Math.pow(ry, 2)*Math.pow(transformedPoint.x, 2);
var cRadicand = cSquareNumerator/cSquareRootDenom;
// Make sure this never drops below zero because of precision
cRadicand = cRadicand < 0 ? 0 : cRadicand;
var cCoef = (largeArcFlag !== sweepFlag ? 1 : -1) * Math.sqrt(cRadicand);
var transformedCenter = {
x: cCoef*((rx*transformedPoint.y)/ry),
y: cCoef*(-(ry*transformedPoint.x)/rx)
};
// Step #3: Compute center
var center = {
x: Math.cos(xAxisRotationRadians)*transformedCenter.x - Math.sin(xAxisRotationRadians)*transformedCenter.y + ((p0.x+p1.x)/2),
y: Math.sin(xAxisRotationRadians)*transformedCenter.x + Math.cos(xAxisRotationRadians)*transformedCenter.y + ((p0.y+p1.y)/2)
};
// Step #4: Compute start/sweep angles
// Start angle of the elliptical arc prior to the stretch and rotate operations.
// Difference between the start and end angles
var startVector = {
x: (transformedPoint.x-transformedCenter.x)/rx,
y: (transformedPoint.y-transformedCenter.y)/ry
};
var startAngle = angleBetween({
x: 1,
y: 0
}, startVector);
var endVector = {
x: (-transformedPoint.x-transformedCenter.x)/rx,
y: (-transformedPoint.y-transformedCenter.y)/ry
};
var sweepAngle = angleBetween(startVector, endVector);
if(!sweepFlag && sweepAngle > 0) {
sweepAngle -= 2*Math.PI;
}
else if(sweepFlag && sweepAngle < 0) {
sweepAngle += 2*Math.PI;
}
// We use % instead of `mod(..)` because we want it to be -360deg to 360deg(but actually in radians)
sweepAngle %= 2*Math.PI;
// From http://www.w3.org/TR/SVG/implnote.html#ArcParameterizationAlternatives
var angle = startAngle+(sweepAngle*t);
var ellipseComponentX = rx*Math.cos(angle);
var ellipseComponentY = ry*Math.sin(angle);
var point = {
x: Math.cos(xAxisRotationRadians)*ellipseComponentX - Math.sin(xAxisRotationRadians)*ellipseComponentY + center.x,
y: Math.sin(xAxisRotationRadians)*ellipseComponentX + Math.cos(xAxisRotationRadians)*ellipseComponentY + center.y
};
// Attach some extra info to use
point.ellipticalArcStartAngle = startAngle;
point.ellipticalArcEndAngle = startAngle+sweepAngle;
point.ellipticalArcAngle = angle;
point.ellipticalArcCenter = center;
point.resultantRx = rx;
point.resultantRy = ry;
return point;
}
function ProcessPathCommands(Commands, TreePath)
{
let Shapes = [];
// walk through
let CurrentPos = null;
let InitialPos = null;
let CurrentLine = [];
let LastBezierControl1Point = null;
function NewShape()
{
// flush old shape
if ( CurrentLine.length )
{
const NewShape = {};
NewShape.Points = CurrentLine.slice();
Shapes.push(NewShape);
}
CurrentLine = [];
LastBezierControl1Point = null;
}
function SetInitialPos(x,y)
{
InitialPos = [x,y];
SetPos(x,y);
}
function SetPos(x,y)
{
if ( [x,y].some( isNaN ) )
throw `Trying to set position as nan; ${x},${y}`;
CurrentPos = [x,y];
CurrentLine.push(CurrentPos.slice());
}
function AddPos(x,y)
{
if ( !InitialPos )
throw "Relative move when InitialPos is null";
x += InitialPos[0];
y += InitialPos[1];
SetPos(x,y);
}
function ClosePath()
{
// re-add first coord
const xy = CurrentLine[0];
SetPos( ...xy );
}
function ProcessArc(RadiusX,RadiusY,Rotation,Arc,Sweep,EndX,EndY)
{
// Debug('ProcessArc');
// for now grab points
const PointCount = 10;
const p0 = {};
p0.x = CurrentPos[0];
p0.y = CurrentPos[1];
const p1 = {};
p1.x = EndX;
p1.y = EndY;
for ( let t=0; t<=1; t+=1/PointCount)
{
// https://github.com/MadLittleMods/svg-curve-lib/blob/master/src/js/svg-curve-lib.js#L79
const Point = GetPointOnArc(p0, RadiusX, RadiusY, Rotation, Arc, Sweep, p1, t);
ProcessLine( Point.x, Point.y );
}
}
function ProcessArcRelative(RadiusX,RadiusY,Rotation,Arc,Sweep,EndX,EndY)
{
EndX += CurrentPos[0];
EndY += CurrentPos[1];
ProcessArc(RadiusX,RadiusY,Rotation,Arc,Sweep,EndX,EndY);
}
function ProcessBezier(ControlX0,ControlY0,ControlX1,ControlY1,EndX,EndY)
{
// for now, turn into points
const Control0 = [ControlX0,ControlY0];
const Control1 = [ControlX1,ControlY1];
const Start = CurrentPos.slice();
const End = [EndX,EndY];
const PointCount = 10;
for ( let t=0; t<=1; t+=1/PointCount)
{
//const Pos = Math.GetCatmullPosition(Prev,Start,End,Next,t);
//const Pos = Math.GetCatmullPosition( Start,Control0,Control1,End,t);
const Pos = Math.GetBezier4Position( Start,Control0,Control1,End,t);
ProcessLine( ...Pos );
}
LastBezierControl1Point = Control1.slice();
}
function ProcessBezierRelative(ControlX0,ControlY0,ControlX1,ControlY1,EndX,EndY)
{
ControlX0 += CurrentPos[0];
ControlY0 += CurrentPos[1];
ControlX1 += CurrentPos[0];
ControlY1 += CurrentPos[1];
EndX += CurrentPos[0];
EndY += CurrentPos[1];
ProcessBezier( ControlX0, ControlY0, ControlX1, ControlY1, EndX, EndY );
}
function ProcessBezierReflection(ControlX1,ControlY1,EndX,EndY)
{
// Basically a C command that assumes the first bezier
// control point is a reflection of the last bezier point
// used in the previous S or C command
// from spec
// The first control point is assumed to be the reflection
// of the second control point on the previous command relative
// to the current point.
// If there is no previous command or if the previous command was not an
// C, c, S or s, assume the first control point is coincident with the
// current point.
if ( !LastBezierControl1Point )
{
// todo: is this coincident?
LastBezierControl1Point = CurrentPos.slice();
}
let LastControlDeltaX = LastBezierControl1Point[0] - CurrentPos[0];
let LastControlDeltaY = LastBezierControl1Point[1] - CurrentPos[1];
let ControlX0 = CurrentPos[0] + -LastControlDeltaX;
let ControlY0 = CurrentPos[1] + -LastControlDeltaY;
ProcessBezier( ControlX0, ControlY0, ControlX1, ControlY1, EndX, EndY );
}
function ProcessBezierReflectionRelative(ControlX1,ControlY1,EndX,EndY)
{
ControlX1 += CurrentPos[0];
ControlY1 += CurrentPos[1];
EndX += CurrentPos[0];
EndY += CurrentPos[1];
ProcessBezierReflection( ControlX1, ControlY1, EndX, EndY );
}
function ProcessQuadratic(ControlX,ControlY,EndX,EndY)
{
Debug("todo: process quadratic");
ProcessLine( EndX, EndY );
}
function ProcessQuadraticRelative(ControlX,ControlY,EndX,EndY)
{
ControlX += CurrentPos[0];
ControlY += CurrentPos[1];
EndX += CurrentPos[0];
EndY += CurrentPos[1];
ProcessQuadratic( ControlX, ControlY, EndX, EndY );
}
function ProcessQuadraticReflection(EndX,EndY)
{
Debug("todo: process quadratic reflection");
ProcessLine( EndX, EndY );
}
function ProcessQuadraticReflectionRelative(EndX,EndY)
{
EndX += CurrentPos[0];
EndY += CurrentPos[1];
ProcessQuadraticReflection( EndX, EndY );
}
function ProcessLine(x,y)
{
if ( x === undefined ) x = CurrentPos[0];
if ( y === undefined ) y = CurrentPos[1];
SetPos( x, y );
}
function ProcessLineRelative(x,y)
{
if ( x !== undefined ) x += CurrentPos[0];
if ( y !== undefined ) y += CurrentPos[1];
ProcessLine( x, y );
}
function ProcessHorzLine(x)
{
ProcessLine(x,undefined);
}
function ProcessHorzLineRelative(x)
{
ProcessLineRelative(x,undefined);
}
function ProcessVertLine(y)
{
ProcessLine(undefined,y);
}
function ProcessVertLineRelative(y)
{
ProcessLineRelative(undefined,y);
}
while ( Commands.length )
{
function CmdHasArguments(Cmd)
{
return (Cmd != 'Z' && Cmd != 'z');
}
const Cmd = Commands.shift();
// gr: close path doesn't take params
let Args = CmdHasArguments(Cmd) ? Commands.shift() : [];
do
{
function Call(Function,NumberOfArgs)
{
Function( ...Args.splice(0,NumberOfArgs) );
}
switch(Cmd)
{
// gr: Move shouldn't draw a line?
case 'M': NewShape(); Call(SetInitialPos,2); break;
case 'm': NewShape(); Call(AddPos,2); break;
case 'L': Call(ProcessLine,2); break;
case 'l': Call(ProcessLineRelative,2); break;
case 'H': Call(ProcessHorzLine,1); break;
case 'h': Call(ProcessHorzLineRelative,1); break;
case 'V': Call(ProcessVertLine,1); break;
case 'v': Call(ProcessVertLineRelative,1); break;
case 'A': Call(ProcessArc,7); break;
case 'a': Call(ProcessArcRelative,7); break;
case 'C': Call(ProcessBezier,6); break;
case 'c': Call(ProcessBezierRelative,6); break;
case 'S': Call(ProcessBezierReflection,4); break;
case 's': Call(ProcessBezierReflectionRelative,4); break;
case 'Z': ClosePath(); break;
case 'z': ClosePath(); break;
case 'Q': Call(ProcessQuadratic,4); break;
case 'q': Call(ProcessQuadraticRelative,4); break;
case 'T': Call(ProcessQuadraticReflection,2); break;
case 't': Call(ProcessQuadraticReflectionRelative,2); break;
default: throw `Unhandled path command ${Cmd}`;
}
// if ( Args.length > 0 ) Warning(`Multiple iteration of path command ${Cmd}`);
}
while(Args.length > 0);
}
// terminate last line
NewShape();
return Shapes;
}
function ParseSvgPathCommandContours(Commands, TreePath)
{
// https://css-tricks.com/svg-path-syntax-illustrated-guide/
// with split(), having (groups) means delim is kept
const IsCommandPattern = new RegExp('([a-zA-Z]{1})','g');
// this regex is careful to split..
// 12.45-67.89
// 12.34.56 (12.34 and 0.56)
///[+-]?([0-9]*[.])?[0-9]+/
const IsNumber = new RegExp('[+-]?([0-9]*[.])?[0-9]+','g');
function StringToFloats(String)
{
// find all floats
const Matches = [...String.matchAll(IsNumber)];
let Floats = Matches.map( m => m[0] );
// Debug(`Floats: ${String}`,Matches);
Floats = Floats.map( parseFloat );
if ( Floats.some( isNaN ) )
throw "String (" + String + ") failed to turn to floats: " + Floats;
return Floats;
}
function ConvertIfNumbers(Command)
{
if ( Command.match(IsCommandPattern) )
return Command;
// assume is array of floats, convert
const Floats = StringToFloats(Command);
return Floats;
}
// split into commands & coords
// Debug(`ParseSvgPathCommands(${Commands})`);
const Matches = Commands.split(IsCommandPattern);
const MatchesNotEmpty = Matches.filter( s => s.length );
const MatchesWithFloats = MatchesNotEmpty.map(ConvertIfNumbers);
//const Matches = [...Commands.matchAll( Pattern )];
// Debug(MatchesWithFloats);
const Contours = ProcessPathCommands(MatchesWithFloats, TreePath);
return Contours;
}
export default async function ParseSvg(Contents,OnShape,FixPosition=null)
{
FixPosition = FixPosition || function(xy,DocumentBounds) { return xy; }
const TranslateRegex = new RegExp("translate\\((.*)\\)");
function ApplyTransform(xy,Transform,Bounds)
{
if ( Transform )
{
//transform="translate(-20.401999,6.3428249)"
let Translate = Transform.match(TranslateRegex);
if ( Translate )
{
Translate = Translate[1].split(',');
Translate = Translate.map( x => Number(x) );
xy[0] += Translate[0];
xy[1] += Translate[1];
}
}
xy = FixPosition( xy, Bounds );
return xy;
}
let Svg = ParseXml(Contents);
// note: the DOMParser in chrome turns this into a proper svg object, not just a structure
Svg = CleanSvg(Svg);
// Debug( JSON.stringify(Svg) );
// name for each shape is group/group/name
const PathSeperator = '/';
const Meta = Svg.svg;
const Bounds = StringToFloats( Svg.ViewBox );
function FixPositionArray(Points,Transform)
{
// Debug(`FixPositionArray`);
// modify array of pairs
for ( let xy of Points )
{
let NewXy = FixPosition(xy,Transform,Bounds);
xy[0] = NewXy[0];
xy[1] = NewXy[1];
}
}
// center bounds so ratio is around height
if ( false )
{
const LeftShift = Bounds[2] - Bounds[3];
Bounds[0] += LeftShift/2;
Bounds[2] -= LeftShift;
}
function Range(Min,Max,Value)
{
return (Value-Min) / (Max-Min);
}
function Lerp(Min,Max,Time)
{
return Min + ((Max-Min) * Time);
}
function StringToFloat(String)
{
let Float = parseFloat(String);
return Float;
}
function StringToFloats(String)
{
let Floats = String.split(' ');
Floats = Floats.map( parseFloat );
if ( Floats.some( isNaN ) )
throw "String (" + String + ") failed to turn to floats: " + Floats;
return Floats;
}
function StringToFloat2s(String,Modifyx)
{
Modifyx = Modifyx || function(x){return x;};
let Floats = String.split(' ');
Floats = Floats.filter( f => f.length > 0 );
Floats = Floats.map( parseFloat );
if ( Floats.some( isNaN ) )
throw "String (" + String + ") failed to turn to floats: " + Floats;
const Float2s = [];
for ( let i=0; i<Floats.length; i+=2 )
{
const x = Modifyx( Floats[i+0] );
const y = Modifyx( Floats[i+1] );
Float2s.push([x,y]);
}
return Float2s;
}
function StringToFloat2Coords(String)
{
const Float2s = StringToFloat2s( String );
return Float2s;
}
function StringToMatrix(String)
{
if ( !String )
return String;
let Floats = StringToFloats(String);
let Matrix =
[
a,c,e,0,
b,d,f,0,
0,0,1,0,
0,0,0,1
];
return Matrix;
}
function StringToCoord(String)
{
if ( String === undefined )
return String;
let x = StringToSize(String);
//x = Lerp( -1, 1, x );
return x;
}
function StringToSize(String)
{
let x = StringToFloat(String);
return x;
}
function ParseCircle(Node,ChildIndex,PathName)
{
const Shape = {};
Shape.NodeType = Node.Type;
Shape.Style = Node.Style;
Shape.Name = Node.id;
Shape.PathName = PathName + PathSeperator;
Shape.PathName += (Node.id!==undefined) ? Node.id : ChildIndex;
Shape.Matrix = StringToMatrix( Node['matrix'] );
let x = StringToCoord( Node['cx'] );
let y = StringToCoord( Node['cy'] );
let r = StringToSize( Node['r'] );
const xy = ApplyTransform([x,y],Node.transform,Bounds);
x = xy[0];
y = xy[1];
Shape.Circle = {};
Shape.Circle.x = x;
Shape.Circle.y = y;
Shape.Circle.Radius = r;
OnShape(Shape);
}
function ParseEllipse(Node,ChildIndex,PathName)
{
const Shape = {};
Shape.NodeType = Node.Type;
Shape.Style = Node.Style;
Shape.Name = Node.id;
Shape.PathName = PathName + PathSeperator;
Shape.PathName += (Node.id!==undefined) ? Node.id : ChildIndex;
Shape.Matrix = StringToMatrix( Node['matrix'] );
let x = StringToCoord( Node['cx'] );
let y = StringToCoord( Node['cy'] );
let rx = StringToSize( Node['rx'] );
let ry = StringToSize( Node['ry'] );
const xy = FixPosition([x,y],Node.transform,Bounds);
x = xy[0];
y = xy[1];
Shape.Ellipse = {};
Shape.Ellipse.x = x;
Shape.Ellipse.y = y;
Shape.Ellipse.RadiusX = rx;
Shape.Ellipse.RadiusY = ry;
OnShape(Shape);
}
function ParsePath(Node,ChildIndex,PathName)
{
// Debug(`ParsePath(${Node.id})`);
const Shape = {};
Shape.NodeType = Node.Type;
Shape.Style = Node.Style;
Shape.Name = Node.id;
Shape.PathName = PathName + PathSeperator;
Shape.PathName += (Node.id!==undefined) ? Node.id : ChildIndex;
Shape.Path = Node['d'];
// get all shapes from the path and output them
const PathContours = ParseSvgPathCommandContours(Node['d'], PathName);
function PushShape(Contour)
{
// is it a line or a poly
let PathShape = {};
// Debug("Countour",Contour);
if ( Shape.Style.fill == "none" )
{
PathShape.Line = {};
PathShape.Line.Points = Contour.Points.slice();
FixPositionArray(PathShape.Line.Points,Node.transform);
}
else
{
PathShape.Polygon = {};
PathShape.Polygon.Points = Contour.Points.slice();
FixPositionArray(PathShape.Polygon.Points,Node.transform);
}
const OutputShape = Object.assign({},Shape);
Object.assign( OutputShape, PathShape );
OnShape( OutputShape );
}
PathContours.forEach( PushShape );
}
function ParsePolygon(Node,ChildIndex,PathName)
{
const Shape = {};
Shape.NodeType = Node.Type;
Shape.Style = Node.Style;
Shape.Name = Node.id;
Shape.PathName = PathName + PathSeperator;
Shape.PathName += (Node.id!==undefined) ? Node.id : ChildIndex;
Shape.Polygon = {};
Shape.Polygon.Points = StringToFloat2Coords(Node['points']);
FixPositionArray(Shape.Polygon.Points,Node.transform);
OnShape(Shape);
}
function ParseLine(Node,ChildIndex,PathName)
{
const Shape = {};
Shape.NodeType = Node.Type;
Shape.Style = Node.Style;
Shape.Name = Node.id;
Shape.PathName = PathName + PathSeperator;
Shape.PathName += (Node.id!==undefined) ? Node.id : ChildIndex;
let x1 = StringToCoord( Node['x1'] );
let y1 = StringToCoord( Node['y1'] );
let x2 = StringToCoord( Node['x2'] );
let y2 = StringToCoord( Node['y2'] );
Shape.Line = {};
Shape.Line.Points = [];
Shape.Line.Points.push( [x1,y1] );
Shape.Line.Points.push( [x2,y2] );
FixPositionArray(Shape.Line.Points,Node.transform);
OnShape( Shape );
}
function ParsePolyLine(Node,ChildIndex,PathName)
{
const Shape = {};
Shape.NodeType = Node.Type;
Shape.Style = Node.Style;
Shape.Name = Node.id;
Shape.PathName = PathName + PathSeperator;
Shape.PathName += (Node.id!==undefined) ? Node.id : ChildIndex;
Shape.Line = {};
Shape.Line.Points = StringToFloat2Coords(Node['points']);
FixPositionArray(Shape.Line.Points,Node.transform);
OnShape( Shape );
}
function ParseRect(Node,ChildIndex,PathName)
{
const Shape = {};
Shape.NodeType = Node.Type;
Shape.Style = Node.Style;
Shape.Name = Node.id;
Shape.PathName = PathName + PathSeperator;
Shape.PathName += (Node.id!==undefined) ? Node.id : ChildIndex;
let x = StringToCoord( Node['x'] ) || 0;
let y = StringToCoord( Node['y'] ) || 0;
let w = StringToSize( Node['width'] );
let h = StringToSize( Node['height'] );
const xy = FixPosition([x,y],Node.transform,Bounds);