Debian Codegraph @

texmf-dist/source/latex/wargame/utils/wgsvg2tikz.py

raw
1 #!/usr/bin/env python3
2
3 from sys import stderr, stdout
4
5 def monkey_patch():
6 from svgelements import SVGElement
7
8 def SVGElement__imatmul__(self,other):
9 print('Dummy SVGElement.__imatmul__')
10 return self
11
12 SVGElement.__imatmul__ = SVGElement__imatmul__
13
14 monkey_patch()
15
16 # --------------------------------------------------------------------
17 def open_svg(input):
18 from svgelements import SVG
19
20 svg = SVG.parse(input,reify=False)
21 print(type(svg[0]),file=stderr)
22 return svg
23
24 # --------------------------------------------------------------------
25 def get_bb(svg):
26 llx,lly,urx,ury = svg.bbox()
27 # print(llx,lly,urx,ury)
28 return llx,lly,urx,ury
29
30 # --------------------------------------------------------------------
31 def flush_left(svg):
32 from svgelements import Matrix
33
34 llx,lly,urx,ury = get_bb(svg)
35 svg *= Matrix.translate(-llx,-lly)
36 return svg
37
38 # --------------------------------------------------------------------
39 def scale_unit(svg):
40 from svgelements import Matrix
41
42 llx,lly,urx,ury = get_bb(svg)
43 scale = 1 / max(urx,ury)
44 svg *= Matrix.scale(scale)
45
46 return svg
47
48 # --------------------------------------------------------------------
49 def scale_to_cm(svg,px_per_cm = 37.79531157367762334497):
50 from svgelements import Matrix
51
52 scale = 1 / px_per_cm
53 svg *= Matrix.scale(scale)
54
55 return svg
56
57 # --------------------------------------------------------------------
58 def shift_to_centre(svg):
59 from svgelements import Matrix
60
61 llx,lly,urx,ury = get_bb(svg)
62 svg *= Matrix.translate(-urx/2,-ury/2)
63 svg *= Matrix.scale(1,-1)
64 svg.reify()
65 svg.render()
66 return svg
67
68 # --------------------------------------------------------------------
69 def flipy(svg):
70 from svgelements import Matrix
71
72 llx,lly,urx,ury = get_bb(svg)
73 svg *= Matrix.translate(-llx,-lly)
74 svg *= Matrix.scale(1,-1)
75 svg.reify()
76 svg.render()
77 llx,lly,urx,ury = get_bb(svg)
78 svg *= Matrix.translate(0,-lly)
79 return svg
80
81 # ====================================================================
82 def get_paths(svg):
83 '''Read in paths from the SVG image
84
85 This will recurse down groups for path operations
86
87 Returns
88 -------
89 paths : list
90 List of svg.path.Path objects
91 '''
92 from svgelements import Path, Group
93 from svg.path import parse_path
94
95 paths = []
96
97 for e in svg:
98 if isinstance(e,Path):
99 print('Parse path',file=stderr)
100 p = parse_path(e.d())
101 paths.append(p)
102 if isinstance(e,Group):
103 print('Parse group',file=stderr)
104 paths.append(get_paths(e))
105
106 return paths
107
108 # ====================================================================
109 def tikz_point(e,f):
110 '''Ouput a point
111
112 Parameters
113 ----------
114 e : complex
115 The point
116 f : str
117 Floating point format
118
119 Return
120 ------
121 coord : str
122 The point formatted for Tikz
123 '''
124 return f'({e.real:{f}},{e.imag:{f}})'
125
126 # --------------------------------------------------------------------
127 def tikz_move(e,f):
128 '''Output a move-to operation
129
130 Parameters
131 ----------
132 e : complex
133 The point to move to
134 f : str
135 Floating point format
136
137 Return
138 ------
139 coord : str
140 The point formatted for Tikz
141 '''
142 return tikz_point(e.start,f)
143
144 # --------------------------------------------------------------------
145 def tikz_line(e,f):
146 '''Output a line-to operation
147
148 Parameters
149 ----------
150 e : complex
151 The point to draw line to
152 f : str
153 Floating point format
154
155 Return
156 ------
157 line : str
158 The line-to operation to point
159 '''
160 return '-- '+tikz_point(e.end,f)
161
162 # --------------------------------------------------------------------
163 def tikz_curve(e,f):
164 '''Output a curve-to operation
165
166 Parameters
167 ----------
168 e : curve operation (3 complex numbers)
169 The control points (2 of them) and the point to draw curve to
170 f : str
171 Floating point format
172
173 Return
174 ------
175 curve : str
176 The curve-to operation to point
177 '''
178 return \
179 '.. controls '+tikz_point(e.control1,f) + \
180 ' and ' +tikz_point(e.control2,f) + \
181 ' ..' +tikz_point(e.end,f)
182
183 # --------------------------------------------------------------------
184 def tikz_close(e,f):
185 '''Ouput a close (or cycle) operation
186 '''
187 return '-- cycle'
188
189 # ====================================================================
190 def path_to_tikz(path,f='8.5f'):
191 '''Convert a svt.path.Path to a TikZ path
192
193 Parameters
194 ----------
195 path : svg.path.Path
196 Path to convert
197 f : str
198 floating point format to use
199
200 Returns
201 -------
202 code : list
203 List of Tikz path operations as strings
204 '''
205 from svg.path import Line, Move, Close, CubicBezier, Path
206
207 code = [f'% ']
208 for e in path:
209 if isinstance(e, Move): code.append(tikz_move(e, f))
210 elif isinstance(e, Line): code.append(tikz_line(e, f))
211 elif isinstance(e, Close): code.append(tikz_close(e,f))
212 elif isinstance(e, CubicBezier): code.append(tikz_curve(e,f))
213 elif isinstance(e, Path): code.extend(path_to_tikz(e,f))
214 else:
215 print(f'Unknown type: {type(e)}',file=stderr)
216
217 return code
218
219 # ====================================================================
220 def doc_header(output=stdout):
221 '''Prinout put standalone document header
222 '''
223 print(r'''%
224 \documentclass{standalone}
225 \usepackage{tikz}
226 \begin{document}%''',file=output)
227
228 # --------------------------------------------------------------------
229 def doc_footer(output=stdout):
230 '''Prinout put standalone document footer
231 '''
232 print(r'''%
233 \end{document}''',file=output)
234
235 # --------------------------------------------------------------------
236 def path_to_pic(path,name,output,format):
237 '''Output a Tikz pic definition from the path
238
239 Parameters
240 ----------
241 path : Path
242 The path to convert
243 name : str
244 The name of the pic
245 output : File
246 Output file
247 format : str
248 Floating point format
249 '''
250 print(fr'''\tikzset{{%
251 {name}/.pic={{%
252 \path[pic actions]''',file=output,end='\n ')
253
254 code = path_to_tikz(path,format)
255 print('\n '.join(code),file=output)
256 print(' ;\n }',file=output)
257 print('}%',file=output)
258
259 # ====================================================================
260
261 # ====================================================================
262 def doit(input='soldier_side.svg',
263 centre=True,
264 unit=True,
265 output=stdout,
266 standalone=False,
267 format='8.5f'):
268 svg = open_svg(input)
269 orig_bb = get_bb(svg)
270
271 if centre or unit:
272 svg = flush_left(svg)
273 if unit:
274 svg = scale_unit(svg)
275 else:
276 svg = scale_to_cm(svg)
277 if centre:
278 svg = shift_to_centre(svg)
279 else:
280 svg = flipy(svg)
281 new_bb = get_bb(svg)
282
283 paths = get_paths(svg)
284
285 if standalone:
286 doc_header(output)
287 print(f'% Original bounding box: ({orig_bb[0]},{orig_bb[1]}) ({orig_bb[2]},{orig_bb[3]})',
288 file=output)
289 print(f'% New bounding box: ({new_bb[0]},{new_bb[1]}) ({new_bb[2]},{new_bb[3]})',
290 file=output)
291 pics = []
292 for i, path in enumerate(paths):
293 name = f'pic_{i:03d}'
294 path_to_pic(path,name,output,format)
295 pics.append(name)
296
297 if standalone:
298 print(r'\begin{tikzpicture}%',file=output)
299 x = 0
300 y = 0
301 for i, name in enumerate(pics):
302 if x > 10:
303 x = 0
304 y += 2
305
306 print(fr' \pic[draw,fill=red] at ({x},{y}) {{{name}}};%',
307 file=output)
308 x += 2
309
310 print(r'\end{tikzpicture}%',file=output)
311 doc_footer(output)
312
313 # ====================================================================
314 def test(svgfile='soldier_side.svg',tikzfile=stdout,standalone=True):
315 with open(svgfile,'r') as input:
316 with open(tikzfile,'w') if isinstance(tikzfile,str) else tikzfile as output:
317 doit(input=input,output=output,standalone=standalone)
318
319
320 # ====================================================================
321 if __name__ == '__main__':
322 from argparse import ArgumentParser, FileType
323
324 ap = ArgumentParser(description='Convert SVG to unit Tikz picture')
325 ap.add_argument('input',type=FileType('r'),nargs='?',default='soldier_side.svg',
326 help='Input SVG file')
327 ap.add_argument('-o','--output',type=FileType('w'),default=None,
328 help='Output Tikz file')
329 ap.add_argument('-s','--standalone',action='store_true',default=True,
330 help='Write standalone document')
331 ap.add_argument('-p','--picture',action='store_false',dest='standalone',
332 help='Only write picture')
333 ap.add_argument('-f','--format',type=str,default='8.5f',
334 help='Format for coordinates')
335 ap.add_argument('-O','--original-size',dest='unit',action='store_false',
336 help='Do no scale paths to unit size')
337 ap.add_argument('-S','--unit-size',dest='unit',action='store_true',
338 help='Scale paths to unit size')
339 ap.add_argument('-Z','--no-centre',dest='centre',action='store_false',
340 help='Do not centre paths')
341 ap.add_argument('-C','--centre',dest='centre',action='store_true',
342 help='Centre paths')
343
344 args = ap.parse_args()
345
346 if args.output is None:
347 from pathlib import Path
348 inname = Path(args.input.name)
349 outname = inname.with_suffix('.tex')
350 args.output = open(outname,'w')
351
352
353 doit(input = args.input,
354 unit = args.unit,
355 centre = args.centre,
356 output = args.output,
357 standalone = args.standalone,
358 format = args.format)
359
360
361
362
363
364
365