-
Notifications
You must be signed in to change notification settings - Fork 2
/
svg2fcsketch.py
1983 lines (1685 loc) · 78.7 KB
/
svg2fcsketch.py
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
#! /usr/bin/python
#
# (C) 2018 juergen@fabmail.org
# Distribute under GPL-2.0 or ask.
#
# References:
# https://github.com/FreeCAD/FreeCAD/blob/master/src/Mod/Sketcher/TestSketcherApp.py
# /usr/lib/freecad-daily/Mod/Sketcher/SketcherExample.py
# https://en.wikipedia.org/wiki/Rytz%27s_construction#Computer_aided_solution
# http://wiki.inkscape.org/wiki/index.php/Python_modules_for_extensions
# https://en.wikipedia.org/wiki/Composite_B%C3%A9zier_curve
# https://en.wikipedia.org/wiki/B-spline#Relationship_to_piecewise/composite_B%C3%A9zier
#
# v0.1 jw, initial draft refactoring inksvg to make it fit here.
# v0.2 jw, Introducing class SketchPathGen to seperate the sketch generator from the svg parser.
# v0.3 jw, correct _coord_from_svg() size and offset handling. Suppress
# silly version printing, that would ruin an inkscape extension.
# V0.4 jw, Added GuiDocument.xml for visibility and camera defaults.
# Using BoundBox() to compute camera placement.
# V0.5 jw, objEllipse() done correctly with _ellipse_vertices2d()
# V0.6 jw, objArc() done. ArcOfCircle() is a strange beast with rotation and mirroring.
# V0.7 jw, pathString() done.
# V0.8 jw, imported class SubPathTracker() from src/examples/sketch_spline.py
#
from optparse import OptionParser
import os, sys, math, re
sys_platform = sys.platform.lower()
if sys_platform.startswith('win'):
sys.path.append('C:\Program Files\Inkscape\share\extensions')
elif sys_platform.startswith('darwin'):
sys.path.append('~/.config/inkscape/extensions')
else: # Linux
sys.path.append('/usr/share/inkscape/extensions/')
import cubicsuperpath
sys.path.append('/usr/lib/freecad-daily/lib/') # prefer daily over normal.
sys.path.append('/usr/lib/freecad/lib/')
verbose=-1 # -1=quiet, 0=normal, 1=babble
epsilon = 0.00001
if verbose <= 0:
os.dup2(1,99) # hack to avoid silly version string printing.
f = open("/dev/null", "w")
os.dup2(f.fileno(), 1)
# The version printing code has
# src/App/Application.cpp: if (!(mConfig["Verbose"] == "Strict"))
# but we cannot call SetConfig('Verbose', 'Strict') early enough.
from FreeCAD import Base, BoundBox
sys.stdout.flush() # push silly version string into /dev/null
if verbose <= 0:
f.close()
os.dup2(99,1) # back in cansas.
import Part, Sketcher # causes SEGV if Base is not yet imported from FreeCAD
import ProfileLib.RegularPolygon as Poly
# CAUTION: Keep in sync with with svg2fcsketch.inx ca. line 3 and line 24
__version__ = '0.8'
#! /usr/bin/python
#
# inksvg.py - parse an svg file into a plain list of paths.
#
# (C) 2017 juergen@fabmail.org, authors of eggbot and others.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#################
# 2017-12-04 jw, v1.0 Refactored class InkSvg from cookiecutter extension
# 2017-12-07 jw, v1.1 Added roundedRectBezier()
# 2017-12-10 jw, v1.3 Added styleDasharray() with stroke-dashoffset
# 2017-12-14 jw, v1.4 Added matchStrokeColor()
# 2017-12-21 jw, v1.5 Changed getPathVertices() to construct a to self.paths list, instead of
# a dictionary. (Preserving native ordering)
# 2017-12-22 jw, v1.6 fixed "use" to avoid errors with unknown global symbal 'composeTransform'
# 2017-12-25 jw, v1.7 Added getNodeStyle(), cssDictAdd(), expanded matchStrokeColor() to use
# inline style defs. Added a warning message for not-implemented CSS styles.
# v1.7a Added getNodeStyleOne() made getNodeStyle() recurse through parents.
# 2018-03-10 jw, v1.7b Added search paths to find inkex.
# v1.7c Refactoring for simpler interface without subclassing.
# Added load(), getElementsByIds() methods.
# 2018-03-21 jw, v1.7d Added handleViewBox() to load().
# Added traverse().
import gettext
import re
import sys
sys_platform = sys.platform.lower()
if sys_platform.startswith('win'):
sys.path.append('C:\Program Files\Inkscape\share\extensions')
elif sys_platform.startswith('darwin'):
sys.path.append('~/.config/inkscape/extensions')
else: # Linux
sys.path.append('/usr/share/inkscape/extensions/')
import inkex
import simplepath
import simplestyle
import simpletransform
import cubicsuperpath
import cspsubdiv
import bezmisc
from lxml import etree
class PathGenerator():
"""
A PathGenerator has methods for different svg objects. It compiles an
internal representation of them all, handling transformations and linear
interpolation of curved path segments.
The base class PathGenerator is dummy (abstract) class that raises an
NotImplementedError() on each method entry point. It serves as documentation for
the generator interface.
"""
def __init__(self):
self._svg = None
def registerSvg(self, svg):
self._svg = svg
svg.stats = self.stats
def pathString(self, d, node, mat):
"""
d is expected formatted as an svg path string here.
"""
raise NotImplementedError("See example inksvg.LinearPathGen.pathString()")
def pathList(self, d, node, mat):
"""
d is expected as an [[cmd, [args]], ...] arrray
"""
raise NotImplementedError("See example inksvg.LinearPathGen.pathList()")
def objRect(x, y, w, h, node, mat):
raise NotImplementedError("See example inksvg.LinearPathGen.objRect()")
def objRoundedRect(self, x, y, w, h, rx, ry, node, mat):
raise NotImplementedError("See example inksvg.LinearPathGen.objRoundedRect()")
def objEllipse(self, cx, xy, rx, ry, node, mat):
raise NotImplementedError("See example inksvg.LinearPathGen.objEllipse()")
def objArc(self, d, cx, cy, rx, ry, st, en, cl, node, mat):
"""
SVG does not have an arc element. Inkscape creates officially a path element,
but also (redundantly) provides the original arc values.
Implementations can choose to work with the path d and ignore the rest,
or work with the cx, cy, rx, ry, ... parameters and ignore d.
Note: the parameter closed=True/False is actually derived from looking at the last
command of path d. Hackish, but there is no 'sodipodi:closed' element, or similar.
"""
raise NotImplementedError("See example inksvg.LinearPathGen.objArc()")
class LinearPathGen(PathGenerator):
def __init__(self, smoothness=0.2):
self.smoothness = max(0.0001, smoothness)
def pathString(self, d, node, mat):
"""
d is expected formatted as an svg path string here.
"""
print("calling getPathVertices", self.smoothness)
self._svg.getPathVertices(d, node, mat, self.smoothness)
def pathList(self, d, node, mat):
"""
d is expected as an [[cmd, [args]], ...] arrray
"""
return self.pathString(simplepath.formatPath(d), node, mat)
def objRect(x, y, w, h, node, mat):
"""
Manually transform
<rect x="X" y="Y" width="W" height="H"/>
into
<path d="MX,Y lW,0 l0,H l-W,0 z"/>
I.e., explicitly draw three sides of the rectangle and the
fourth side implicitly
"""
a = []
a.append(['M ', [x, y]])
a.append([' l ', [w, 0]])
a.append([' l ', [0, h]])
a.append([' l ', [-w, 0]])
a.append([' Z', []])
self.pathList(a, node, matNew)
def objRoundedRect(self, x, y, w, h, rx, ry, node, mat):
print("calling roundedRectBezier")
d = self._svg.roundedRectBezier(x, y, w, h, rx, ry)
self._svg.getPathVertices(d, node, mat, self.smoothness)
def objEllipse(self, cx, xy, rx, ry, node, mat):
"""
Convert circles and ellipses to a path with two 180 degree
arcs. In general (an ellipse), we convert
<ellipse rx="RX" ry="RY" cx="X" cy="Y"/>
to
<path d="MX1,CY A RX,RY 0 1 0 X2,CY A RX,RY 0 1 0 X1,CY"/>
where
X1 = CX - RX
X2 = CX + RX
Note: ellipses or circles with a radius attribute of value 0
are ignored
"""
x1 = cx - rx
x2 = cx + rx
d = 'M %f,%f ' % (x1, cy) + \
'A %f,%f ' % (rx, ry) + \
'0 1 0 %f,%f ' % (x2, cy) + \
'A %f,%f ' % (rx, ry) + \
'0 1 0 %f,%f' % (x1, cy)
self.pathString(d, node, matNew)
def objArc(self, d, cx, cy, rx, ry, st, en, cl, node, mat):
"""
We ignore the cx, cy, rx, ry data, and are happy that inkscape
also provides the same information as a path.
"""
self.pathString(d, node, matNew)
class InkSvg():
"""
Usage example with subclassing:
#
# class ThunderLaser(inkex.Effect):
# def __init__(self):
# inkex.localize()
# inkex.Effect.__init__(self)
# def effect(self):
# svg = InkSvg(document=self.document, pathgen=LinearPathGen(smoothness=0.2))
# svg.handleViewBox()
# svg.recursivelyTraverseSvg(self.document.getroot(), svg.docTransform)
# for tup in svg.paths:
# node = tup[0]
# ...
# e = ThunderLaser()
# e.affect()
#
Simple usage example with method invocation:
# svg = InkSvg(pathgen=LinearPathGen(smoothness=0.01))
# svg.load(svgfile)
# svg.traverse([ids...])
# print(svg.pathgen.path)
"""
__version__ = "1.7c"
DEFAULT_WIDTH = 100
DEFAULT_HEIGHT = 100
# imports from inkex
NSS = inkex.NSS
def getElementsByIds(self, ids):
"""
ids be a string of a comma seperated values, or a list of strings.
Returns a list of xml nodes.
"""
if not self.document:
raise ValueError("no document loaded.")
if isinstance(ids, (bytes, str)): ids = [ ids ] # handle some scalars
ids = ','.join(ids).split(',') # merge into a string and re-split
## OO-Fail:
# cannot use inkex.getElementById() -- it returns only the first element of each hit.
# cannot use inkex.getselected() -- it returns the last element of each hit only.
"""Collect selected nodes"""
nodes = []
for id in ids:
if id != '': # empty strings happen after splitting...
path = '//*[@id="%s"]' % id
el_list = self.document.xpath(path, namespaces=InkSvg.NSS)
if el_list:
for node in el_list:
nodes.append(node)
else:
raise ValueError("id "+id+" not found in the svg document.")
return nodes
def load(self, filename):
inkex.localize()
# OO-Fail: cannot call inkex.Effect.parse(), Effect constructor has so many side-effects.
stream = open(filename, 'r')
p = etree.XMLParser(huge_tree=True)
self.document = etree.parse(stream, parser=p)
stream.close()
# initialize a coordinate system that can be picked up by pathgen.
self.handleViewBox()
def traverse(self, ids=None):
"""
Recursively traverse the SVG document. If ids are given, all matching nodes
are taken as start positions for traversal. Otherwise traveral starts at
the root node of the document.
"""
selected = []
if ids is not None:
selected = self.getElementsByIds(ids)
if len(selected):
# Traverse the selected objects
for node in selected:
transform = self.recursivelyGetEnclosingTransform(node)
self.recursivelyTraverseSvg([node], transform)
else:
# Traverse the entire document building new, transformed paths
self.recursivelyTraverseSvg(self.document.getroot(), self.docTransform)
def getNodeStyleOne(self, node):
"""
Finds style declarations by .class, #id or by tag.class syntax,
and of course by a direct style='...' attribute.
"""
sheet = ''
selectors = []
classes = node.get('class', '') # classes == None can happen here.
if classes is not None and classes != '':
selectors = ["."+cls for cls in re.split('[\s,]+', classes)]
selectors += [node.tag+sel for sel in selectors]
node_id = node.get('id', '')
if node_id is not None and node_id != '':
selectors += [ "#"+node_id ]
for sel in selectors:
if sel in self.css_dict:
sheet += '; '+self.css_dict[sel]
style = node.get('style', '')
if style is not None and style != '':
sheet += '; '+style
return simplestyle.parseStyle(sheet)
def getNodeStyle(self, node):
"""
Recurse into parent group nodes, like simpletransform.ComposeParents
Calling getNodeStyleOne() for each.
"""
combined_style = {}
parent = node.getparent()
if parent.tag == inkex.addNS('g','svg') or parent.tag == 'g':
combined_style = self.getNodeStyle(parent)
style = self.getNodeStyleOne(node)
for s in style:
combined_style[s] = style[s] # overwrite or add
return combined_style
def styleDasharray(self, path_d, node):
"""
Check the style of node for a stroke-dasharray, and apply it to the
path d returning the result. d is returned unchanged, if no
stroke-dasharray was found.
## Extracted from inkscape extension convert2dashes; original
## comments below.
## Added stroke-dashoffset handling, made it a universal operator
## on nodes and 'd' paths.
This extension converts a path into a dashed line using 'stroke-dasharray'
It is a modification of the file addnodes.py
Copyright (C) 2005,2007 Aaron Spike, aaron@ekips.org
Copyright (C) 2009 Alvin Penner, penner@vaxxine.com
"""
def tpoint((x1,y1), (x2,y2), t = 0.5):
return [x1+t*(x2-x1),y1+t*(y2-y1)]
def cspbezsplit(sp1, sp2, t = 0.5):
m1=tpoint(sp1[1],sp1[2],t)
m2=tpoint(sp1[2],sp2[0],t)
m3=tpoint(sp2[0],sp2[1],t)
m4=tpoint(m1,m2,t)
m5=tpoint(m2,m3,t)
m=tpoint(m4,m5,t)
return [[sp1[0][:],sp1[1][:],m1], [m4,m,m5], [m3,sp2[1][:],sp2[2][:]]]
def cspbezsplitatlength(sp1, sp2, l = 0.5, tolerance = 0.001):
bez = (sp1[1][:],sp1[2][:],sp2[0][:],sp2[1][:])
t = bezmisc.beziertatlength(bez, l, tolerance)
return cspbezsplit(sp1, sp2, t)
def cspseglength(sp1,sp2, tolerance = 0.001):
bez = (sp1[1][:],sp1[2][:],sp2[0][:],sp2[1][:])
return bezmisc.bezierlength(bez, tolerance)
style = self.getNodeStyle(node)
if not style.has_key('stroke-dasharray'):
return path_d
dashes = []
if style['stroke-dasharray'].find(',') > 0:
dashes = [float (dash) for dash in style['stroke-dasharray'].split(',') if dash]
if not dashes:
return path_d
dashoffset = 0.0
if style.has_key('stroke-dashoffset'):
dashoffset = float(style['stroke-dashoffset'])
if dashoffset < 0.0: dashoffset = 0.0
if dashoffset > dashes[0]: dashoffset = dashes[0] # avoids a busy-loop below!
p = cubicsuperpath.parsePath(path_d)
new = []
for sub in p:
idash = 0
dash = dashes[0]
# print("initial dash length: ", dash, dashoffset)
dash = dash - dashoffset
length = 0
new.append([sub[0][:]])
i = 1
while i < len(sub):
dash = dash - length
length = cspseglength(new[-1][-1], sub[i])
while dash < length:
new[-1][-1], next, sub[i] = cspbezsplitatlength(new[-1][-1], sub[i], dash/length)
if idash % 2: # create a gap
new.append([next[:]])
else: # splice the curve
new[-1].append(next[:])
length = length - dash
idash = (idash + 1) % len(dashes)
dash = dashes[idash]
if idash % 2:
new.append([sub[i]])
else:
new[-1].append(sub[i])
i+=1
return cubicsuperpath.formatPath(new)
def matchStrokeColor(self, node, rgb, eps=None, avg=True):
"""
Return True if the line color found in the style attribute of elem
does not differ from rgb in any of the components more than eps.
The default eps with avg=True is 64.
With avg=False the default is eps=85 (33% on a 0..255 scale).
In avg mode, the average of all three color channel differences is
compared against eps. Otherwise each color channel difference is
compared individually.
The special cases None, False, True for rgb are interpreted logically.
Otherwise rgb is expected as a list of three integers in 0..255 range.
Missing style attribute or no stroke element is interpreted as False.
Unparseable stroke elements are interpreted as 'black' (0,0,0).
Hexadecimal stroke formats of '#RRGGBB' or '#RGB' are understood
as well as 'rgb(100%, 0%, 0%) or 'red' relying on simplestyle.
"""
if eps is None:
eps = 64 if avg == True else 85
if rgb is None or rgb is False: return False
if rgb is True: return True
style = self.getNodeStyle(node)
s = style.get('stroke', '')
if s == '': return False
c = simplestyle.parseColor(s)
if sum:
s = abs(rgb[0]-c[0]) + abs(rgb[1]-c[1]) + abs(rgb[2]-c[2])
if s < 3*eps:
return True
return False
if abs(rgb[0]-c[0]) > eps: return False
if abs(rgb[1]-c[1]) > eps: return False
if abs(rgb[2]-c[2]) > eps: return False
return True
def cssDictAdd(self, text):
"""
Represent css cdata as a hash in css_dict.
Implements what is seen on: http://www.blooberry.com/indexdot/css/examples/cssembedded.htm
"""
text=re.sub('^\s*(<!--)?\s*', '', text)
while True:
try:
(keys, rest) = text.split('{', 1)
except:
break
keys = re.sub('/\*.*?\*/', ' ', keys) # replace comments with whitespace
keys = re.split('[\s,]+', keys) # convert to list
while '' in keys:
keys.remove('') # remove empty elements (at start or end)
(val,text) = rest.split('}', 1)
val = re.sub('/\*.*?\*/', '', val) # replace comments nothing in values
val = re.sub('\s+', ' ', val).strip() # normalize whitespace
for k in keys:
if not k in self.css_dict:
self.css_dict[k] = val
else:
self.css_dict[k] += '; '+val
def roundedRectBezier(self, x, y, w, h, rx, ry=0):
"""
Draw a rectangle of size w x h, at start point x, y with the corners rounded by radius
rx and ry. Each corner is a quarter of an ellipsis, where rx and ry are the horizontal
and vertical dimenstion.
A pathspec according to https://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands
is returned. Very similar to what inkscape would do when converting object to path.
Inkscape seems to use a kappa value of 0.553, higher precision is used here.
x=0, y=0, w=200, h=100, rx=50, ry=30 produces in inkscape
d="m 50,0 h 100 c 27.7,0 50,13.38 50,30 v 40 c 0,16.62 -22.3,30 -50,30
H 50 C 22.3,100 0,86.62 0,70 V 30 C 0,13.38 22.3,0 50,0 Z"
It is unclear, why there is a Z, the last point is identical with the first already.
It is unclear, why half of the commands use relative and half use absolute coordinates.
We do it all in relative coords, except for the initial M, and we ommit the Z.
"""
if rx < 0: rx = 0
if rx > 0.5*w: rx = 0.5*w
if ry < 0: ry = 0
if ry > 0.5*h: ry = 0.5*h
if ry < 0.0000001: ry = rx
k = 0.5522847498307933984022516322796 # kappa, handle length for a 4-point-circle.
d = "M %f,%f h %f " % (x+rx, y, w-rx-rx) # top horizontal to right
d += "c %f,%f %f,%f %f,%f " % (rx*k,0, rx,ry*(1-k), rx,ry) # top right ellipse
d += "v %f " % (h-ry-ry) # right vertical down
d += "c %f,%f %f,%f %f,%f " % (0,ry*k, rx*(k-1),ry, -rx,ry) # bottom right ellipse
d += "h %f " % (-w+rx+rx) # bottom horizontal to left
d += "c %f,%f %f,%f %f,%f " % (-rx*k,0, -rx,ry*(k-1), -rx,-ry) # bottom left ellipse
d += "v %f " % (-h+ry+ry) # left vertical up
d += "c %f,%f %f,%f %f,%f" % (0,-ry*k, rx*(1-k),-ry, rx,-ry) # top left ellipse
return d
def subdivideCubicPath(self, sp, flat, i=1):
'''
[ Lifted from eggbot.py with impunity ]
Break up a bezier curve into smaller curves, each of which
is approximately a straight line within a given tolerance
(the "smoothness" defined by [flat]).
This is a modified version of cspsubdiv.cspsubdiv(): rewritten
because recursion-depth errors on complicated line segments
could occur with cspsubdiv.cspsubdiv().
'''
while True:
while True:
if i >= len(sp):
return
p0 = sp[i - 1][1]
p1 = sp[i - 1][2]
p2 = sp[i][0]
p3 = sp[i][1]
b = (p0, p1, p2, p3)
if cspsubdiv.maxdist(b) > flat:
break
i += 1
one, two = bezmisc.beziersplitatt(b, 0.5)
sp[i - 1][2] = one[1]
sp[i][0] = two[2]
p = [one[2], one[3], two[1]]
sp[i:1] = [p]
def parseLengthWithUnits(self, str, default_unit='px'):
'''
Parse an SVG value which may or may not have units attached
This version is greatly simplified in that it only allows: no units,
units of px, and units of %. Everything else, it returns None for.
There is a more general routine to consider in scour.py if more
generality is ever needed.
With inkscape 0.91 we need other units too: e.g. svg:width="400mm"
'''
u = default_unit
s = str.strip()
if s[-2:] in ('px', 'pt', 'pc', 'mm', 'cm', 'in', 'ft'):
u = s[-2:]
s = s[:-2]
elif s[-1:] in ('m', '%'):
u = s[-1:]
s = s[:-1]
try:
v = float(s)
except:
return None, None
return v, u
def __init__(self, document=None, svgfile=None, smoothness=0.2, pathgen=LinearPathGen(smoothness=0.2)):
"""
Usage: ...
"""
self.dpi = 90.0 # factored out for inkscape-0.92
self.px_used = False # raw px unit depends on correct dpi.
self.xmin, self.xmax = (1.0E70, -1.0E70)
self.ymin, self.ymax = (1.0E70, -1.0E70)
# CAUTION: smoothness here is deprecated. it belongs into pathgen, if.
# CAUTION: smoothness == 0.0 leads to a busy-loop.
self.smoothness = max(0.0001, smoothness) # 0.0001 .. 5.0
self.pathgen = pathgen
pathgen.registerSvg(self)
# List of paths we will construct. Path lists are paired with the SVG node
# they came from. Such pairing can be useful when you actually want
# to go back and update the SVG document, or retrieve e.g. style information.
self.paths = []
# cssDictAdd collects style definitions here:
self.css_dict = {}
# For handling an SVG viewbox attribute, we will need to know the
# values of the document's <svg> width and height attributes as well
# as establishing a transform from the viewbox to the display.
self.docWidth = float(self.DEFAULT_WIDTH)
self.docHeight = float(self.DEFAULT_HEIGHT)
self.docTransform = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
# Dictionary of warnings issued. This to prevent from warning
# multiple times about the same problem
self.warnings = {}
if document:
self.document = document
if svgfile:
inkex.errormsg('Warning: ignoring svgfile. document given too.')
elif svgfile:
self.document = self.load(svgfile)
def getLength(self, name, default):
'''
Get the <svg> attribute with name "name" and default value "default"
Parse the attribute into a value and associated units. Then, accept
units of cm, ft, in, m, mm, pc, or pt. Convert to pixels.
Note that SVG defines 90 px = 1 in = 25.4 mm.
Note: Since inkscape 0.92 we use the CSS standard of 96 px = 1 in.
'''
str = self.document.getroot().get(name)
if str:
return self.lengthWithUnit(str)
else:
# No width specified; assume the default value
return float(default)
def lengthWithUnit(self, strn, default_unit='px'):
v, u = self.parseLengthWithUnits(strn, default_unit)
if v is None:
# Couldn't parse the value
return None
elif (u == 'mm'):
return float(v) * (self.dpi / 25.4)
elif (u == 'cm'):
return float(v) * (self.dpi * 10.0 / 25.4)
elif (u == 'm'):
return float(v) * (self.dpi * 1000.0 / 25.4)
elif (u == 'in'):
return float(v) * self.dpi
elif (u == 'ft'):
return float(v) * 12.0 * self.dpi
elif (u == 'pt'):
# Use modern "Postscript" points of 72 pt = 1 in instead
# of the traditional 72.27 pt = 1 in
return float(v) * (self.dpi / 72.0)
elif (u == 'pc'):
return float(v) * (self.dpi / 6.0)
elif (u == 'px'):
self.px_used = True
return float(v)
else:
# Unsupported units
return None
def getDocProps(self):
'''
Get the document's height and width attributes from the <svg> tag.
Use a default value in case the property is not present or is
expressed in units of percentages.
This initializes:
* self.basename
* self.docWidth
* self.docHeight
* self.dpi
'''
inkscape_version = self.document.getroot().get(
"{http://www.inkscape.org/namespaces/inkscape}version")
sodipodi_docname = self.document.getroot().get(
"{http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd}docname")
if sodipodi_docname is None:
sodipodi_docname = "inkscape"
self.basename = re.sub(r"\.SVG", "", sodipodi_docname, flags=re.I)
# a simple 'inkscape:version' does not work here. sigh....
#
# BUG:
# inkscape 0.92 uses 96 dpi, inkscape 0.91 uses 90 dpi.
# From inkscape 0.92 we receive an svg document that has
# both inkscape:version and sodipodi:docname if the document
# was ever saved before. If not, both elements are missing.
#
import lxml.etree
# inkex.errormsg(lxml.etree.tostring(self.document.getroot()))
if inkscape_version:
'''
inkscape:version="0.91 r"
inkscape:version="0.92.0 ..."
See also https://github.com/fablabnbg/paths2openscad/issues/1
'''
# inkex.errormsg("inkscape:version="+inkscape_version)
m = re.match(r"(\d+)\.(\d+)", inkscape_version)
if m:
if int(m.group(1)) > 0 or int(m.group(2)) > 91:
self.dpi = 96 # 96dpi since inkscape 0.92
# inkex.errormsg("switching to 96 dpi")
# BUGFIX https://github.com/fablabnbg/inkscape-paths2openscad/issues/1
# get height and width after dpi. This is needed for e.g. mm units.
self.docHeight = self.getLength('height', self.DEFAULT_HEIGHT)
self.docWidth = self.getLength('width', self.DEFAULT_WIDTH)
if (self.docHeight is None) or (self.docWidth is None):
return False
else:
return True
def handleViewBox(self):
'''
Set up the document-wide transform in the event that the document has
an SVG viewbox
This initializes:
* self.basename
* self.docWidth
* self.docHeight
* self.dpi
* self.docTransform
'''
if self.getDocProps():
viewbox = self.document.getroot().get('viewBox')
if viewbox:
vinfo = viewbox.strip().replace(',', ' ').split(' ')
if (vinfo[2] != 0) and (vinfo[3] != 0):
sx = self.docWidth / float(vinfo[2])
sy = self.docHeight / float(vinfo[3])
self.docTransform = simpletransform.parseTransform('scale(%f,%f)' % (sx, sy))
def getPathVertices(self, path, node=None, transform=None, smoothness=None):
'''
Decompose the path data from an SVG element into individual
subpaths, each subpath consisting of absolute move to and line
to coordinates. Place these coordinates into a list of polygon
vertices.
The result is appended to self.paths as a two-element tuple of the
form (node, path_list). This preserves the native ordering of
the SVG file as much as possible, while still making all attributes
if the node available when processing the path list.
'''
if not smoothness:
smoothness = self.smoothness # self.smoothness is deprecated.
if (not path) or (len(path) == 0):
# Nothing to do
return None
if node is not None:
path = self.styleDasharray(path, node)
# parsePath() may raise an exception. This is okay
sp = simplepath.parsePath(path)
if (not sp) or (len(sp) == 0):
# Path must have been devoid of any real content
return None
# Get a cubic super path
p = cubicsuperpath.CubicSuperPath(sp)
if (not p) or (len(p) == 0):
# Probably never happens, but...
return None
if transform:
simpletransform.applyTransformToPath(transform, p)
# Now traverse the cubic super path
subpath_list = []
subpath_vertices = []
for sp in p:
# We've started a new subpath
# See if there is a prior subpath and whether we should keep it
if len(subpath_vertices):
subpath_list.append([subpath_vertices, [sp_xmin, sp_xmax, sp_ymin, sp_ymax]])
subpath_vertices = []
self.subdivideCubicPath(sp, float(smoothness))
# Note the first point of the subpath
first_point = sp[0][1]
subpath_vertices.append(first_point)
sp_xmin = first_point[0]
sp_xmax = first_point[0]
sp_ymin = first_point[1]
sp_ymax = first_point[1]
n = len(sp)
# Traverse each point of the subpath
for csp in sp[1:n]:
# Append the vertex to our list of vertices
pt = csp[1]
subpath_vertices.append(pt)
# Track the bounding box of this subpath
if pt[0] < sp_xmin:
sp_xmin = pt[0]
elif pt[0] > sp_xmax:
sp_xmax = pt[0]
if pt[1] < sp_ymin:
sp_ymin = pt[1]
elif pt[1] > sp_ymax:
sp_ymax = pt[1]
# Track the bounding box of the overall drawing
# This is used for centering the polygons in OpenSCAD around the
# (x,y) origin
if sp_xmin < self.xmin:
self.xmin = sp_xmin
if sp_xmax > self.xmax:
self.xmax = sp_xmax
if sp_ymin < self.ymin:
self.ymin = sp_ymin
if sp_ymax > self.ymax:
self.ymax = sp_ymax
# Handle the final subpath
if len(subpath_vertices):
subpath_list.append([subpath_vertices, [sp_xmin, sp_xmax, sp_ymin, sp_ymax]])
if len(subpath_list) > 0:
self.paths.append( (node, subpath_list) )
def recursivelyTraverseSvg(self, aNodeList, matCurrent=[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
parent_visibility='visible'):
'''
[ This too is largely lifted from eggbot.py ]
Recursively walk the SVG document aNodeList, building polygon vertex lists
for each graphical element we support. The list is generated in self.paths
as a list of tuples [ (node, path_list), (node, path_list), ...] ordered
natively by their order of appearance in the SVG document.
Rendered SVG elements:
<circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, <rect>
Supported SVG elements:
<group>, <use>
Ignored SVG elements:
<defs>, <eggbot>, <metadata>, <namedview>, <pattern>,
processing directives
All other SVG elements trigger an error (including <text>)
'''
for node in aNodeList:
# Ignore invisible nodes
visibility = node.get('visibility', parent_visibility)
if visibility == 'inherit':
visibility = parent_visibility
if visibility == 'hidden' or visibility == 'collapse':
continue
# FIXME: should we inherit styles from parents?
s = self.getNodeStyle(node)
if s.get('display', '') == 'none': continue
# First apply the current matrix transform to this node's tranform
matNew = simpletransform.composeTransform(
matCurrent, simpletransform.parseTransform(node.get("transform")))
if node.tag == inkex.addNS('g', 'svg') or node.tag == 'g':
self.recursivelyTraverseSvg(node, matNew, visibility)
elif node.tag == inkex.addNS('use', 'svg') or node.tag == 'use':
# A <use> element refers to another SVG element via an
# xlink:href="#blah" attribute. We will handle the element by
# doing an XPath search through the document, looking for the
# element with the matching id="blah" attribute. We then
# recursively process that element after applying any necessary
# (x,y) translation.
#
# Notes:
# 1. We ignore the height and width attributes as they do not
# apply to path-like elements, and
# 2. Even if the use element has visibility="hidden", SVG
# still calls for processing the referenced element. The
# referenced element is hidden only if its visibility is
# "inherit" or "hidden".
refid = node.get(inkex.addNS('href', 'xlink'))
if not refid:
continue
# [1:] to ignore leading '#' in reference
path = '//*[@id="%s"]' % refid[1:]
refnode = node.xpath(path)
if refnode:
x = float(node.get('x', '0'))
y = float(node.get('y', '0'))
# Note: the transform has already been applied
if (x != 0) or (y != 0):
matNew2 = simpletransform.composeTransform(matNew, simpletransform.parseTransform('translate(%f,%f)' % (x, y)))
else:
matNew2 = matNew
visibility = node.get('visibility', visibility)
self.recursivelyTraverseSvg(refnode, matNew2, visibility)
elif node.tag == inkex.addNS('path', 'svg'):
path_data = node.get('d', '')
if node.get(inkex.addNS('type', 'sodipodi'), '') == 'arc':
cx = float(node.get(inkex.addNS('cx', 'sodipodi'), '0'))
cy = float(node.get(inkex.addNS('cy', 'sodipodi'), '0'))
rx = float(node.get(inkex.addNS('rx', 'sodipodi'), '0'))
ry = float(node.get(inkex.addNS('ry', 'sodipodi'), '0'))
st = float(node.get(inkex.addNS('start', 'sodipodi'), '0'))
en = float(node.get(inkex.addNS('end', 'sodipodi'), '0'))
cl = path_data.strip()[-1] in ('z', 'Z')
self.pathgen.objArc(path_data, cx, cy, rx, ry, st, en, cl, node, matNew)
else:
### sodipodi:type="star" also comes here. TBD later, if need be.
self.pathgen.pathString(path_data, node, matNew)
elif node.tag == inkex.addNS('rect', 'svg') or node.tag == 'rect':
# Create a path with the outline of the rectangle
# Adobe Illustrator leaves out 'x'='0'.
x = float(node.get('x', '0'))
y = float(node.get('y', '0'))
w = float(node.get('width', '0'))
h = float(node.get('height', '0'))
rx = float(node.get('rx', '0'))
ry = float(node.get('ry', '0'))
if rx > 0.0 or ry > 0.0:
if ry < 0.0000001: ry = rx
elif rx < 0.0000001: rx = ry
self.pathgen.objRoundedRect(x, y, w, h, rx, ry, node, matNew)
else:
self.pathgen.objRect(x, y, w, h, node, matNew)
elif node.tag == inkex.addNS('line', 'svg') or node.tag == 'line':