-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathgwrite.py
More file actions
365 lines (325 loc) · 11.7 KB
/
gwrite.py
File metadata and controls
365 lines (325 loc) · 11.7 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
from __future__ import annotations
import collections
import copy
import sys
import typing
from pathlib import Path
import click
import vpype as vp
import vpype_cli
# Load the default config
vp.config_manager.load_config_file(str(Path(__file__).parent / "bundled_configs.toml"))
def invert_axis(
document: vp.Document,
invert_x: bool,
invert_y: bool,
whole_page: bool = False,
unit_scale: float = 1.0,
) -> vp.Document:
"""Inverts none, one or both axis of the document.
This applies a relative scale operation with factors of 1 or -1
on the two axis to all layers. The inversion happens relative to
the center of the page, if whole_page is true, otherwise to
the center of the bounds.
"""
if whole_page and document.page_size is None:
raise click.UsageError(
"This profile requires the page size to be set (consider using the `pagesize` or `layout` command)"
)
if whole_page:
# This is called after the document has been scaled, but the page size
# is not adjusted, so we need to adjust it here
(x, y) = document.page_size
bounds = (0.0, 0.0, x / unit_scale, y / unit_scale)
else:
bounds = document.bounds()
if not bounds:
return document
origin = (
0.5 * (bounds[0] + bounds[2]),
0.5 * (bounds[1] + bounds[3]),
)
document.translate(-origin[0], -origin[1])
document.scale(-1 if invert_x else 1, -1 if invert_y else 1)
document.translate(origin[0], origin[1])
return document
@click.command()
@click.argument("output", type=vpype_cli.FileType("w"))
@click.option(
"-p",
"--profile",
type=vpype_cli.TextType(),
help="gcode writer profile from the vpype configuration file subsection 'gwrite'",
)
@click.option(
"-d",
"--default",
nargs=2,
multiple=True,
type=vpype_cli.TextType(),
help="set a default value for a variable in case it is not found as property",
)
@click.option(
"-q", "--quiet", is_flag=True, help="do not print the information string"
)
@vpype_cli.global_processor
def gwrite(
document: vp.Document, output: typing.TextIO, profile: str, default: tuple[tuple[str, str]], quiet: bool
):
"""
Write gcode or other ascii files for the vpype pipeline.
The output format can be customized by the user heavily to an extent that you can also
output most known non-gcode ascii text files.
"""
gwrite_config = vp.config_manager.config["gwrite"]
global_index = 0 # for creating a global line index across layers
# If no profile was provided, try to use a default
if not profile:
# Try to get the default profile from the config
if "default_profile" in gwrite_config:
profile = gwrite_config["default_profile"]
else:
raise click.BadParameter(
"no gwrite profile provided on the commandline and no default gwrite "
+ "profile configured in the vpype configuration. This can be done using "
+ 'the "default_default" key in the "gwrite" section'
)
# Check that the profile is actually there, we can be sure that the `gwrite`
# part exists as there are several default profiles.
if profile not in gwrite_config:
profiles = [p for p in gwrite_config.keys() if p != "default_profile"]
raise click.BadParameter(
"gwrite profile "
+ profile
+ " not found in vpype configuration. Available gwrite profiles: "
+ ", ".join(profiles)
)
# Read the config for the profile from the main vpype
config = gwrite_config[profile]
document_start = config.get("document_start", None)
document_end = config.get("document_end", None)
layer_start = config.get("layer_start", None)
layer_end = config.get("layer_end", None)
layer_join = config.get("layer_join", None)
line_start = config.get("line_start", None)
line_end = config.get("line_end", None)
line_join = config.get("line_join", None)
segment_first = config.get("segment_first", None)
segment = config.get("segment", None)
segment_last = config.get("segment_last", None)
unit = config.get("unit", "mm")
offset_x = config.get("offset_x", 0.0)
offset_y = config.get("offset_y", 0.0)
scale_x = config.get("scale_x", 1.0)
scale_y = config.get("scale_y", 1.0)
# transform the document according to the desired parameters
orig_document = document
document = copy.deepcopy(document) # do NOT affect the pipeline's document
unit_scale = vp.convert_length(unit)
document.scale(scale_x / unit_scale, scale_y / unit_scale)
document.translate(offset_x, offset_y)
invert_x = config.get("invert_x", False)
invert_y = config.get("invert_y", False)
flip_x = config.get("horizontal_flip", False)
flip_y = config.get("vertical_flip", False)
# transform the document according to inversion parameters
if invert_x or invert_y:
document = invert_axis(document, invert_x, invert_y)
if flip_x or flip_y:
document = invert_axis(
document, flip_x, flip_y, whole_page=True, unit_scale=unit_scale
)
# prepare
current_layer: vp.LineCollection | None = None
def write_template(template: str | None, **context_vars: typing.Any):
"""Expend a user-provided template using `format()`-style substitution."""
if template is None:
return
dicts = [context_vars, document.metadata]
if current_layer is not None:
dicts.append(current_layer.metadata)
dicts.append(dict(default))
if "default_values" in config:
dicts.append(config["default_values"])
try:
output.write(template.format_map(collections.ChainMap(*dicts)))
except KeyError as exc:
raise click.BadParameter(
f"key {exc.args[0]!r} not found in context variables or properties"
)
# process file
filename = output.name
write_template(
document_start,
filename=filename,
global_index=global_index,
global_index1=global_index + 1,
)
last_x = 0
last_y = 0
xx = 0
yy = 0
global_index += 1
lastlayer_index = len(document.layers.values()) - 1
for layer_index, (layer_id, layer) in enumerate(sorted(document.layers.items())):
current_layer = layer # used by write_template()
write_template(
layer_start,
x=last_x,
y=last_y,
ix=xx,
iy=yy,
index=layer_index,
index1=layer_index + 1,
layer_index=layer_index,
layer_index1=layer_index + 1,
layer_id=layer_id,
filename=filename,
global_index=global_index,
global_index1=global_index + 1,
)
lastlines_index = len(layer) - 1
for lines_index, line in enumerate(layer):
write_template(
line_start,
x=last_x,
y=last_y,
ix=xx,
iy=yy,
index=lines_index,
index1=lines_index + 1,
lines_index=lines_index,
lines_index1=lines_index + 1,
layer_index=layer_index,
layer_index1=layer_index + 1,
layer_id=layer_id,
filename=filename,
global_index=global_index,
global_index1=global_index + 1,
)
segment_last_index = len(line) - 1
for segment_index, seg in enumerate(line):
x = seg.real
y = seg.imag
dx = x - last_x
dy = y - last_y
idx = int(round(x - xx))
idy = int(round(y - yy))
xx += idx
yy += idy
if segment_first is not None and segment_index == 0:
seg_write = segment_first
elif segment_last is not None and segment_index == segment_last_index:
seg_write = segment_last
else:
seg_write = segment
write_template(
seg_write,
x=x,
y=y,
dx=dx,
dy=dy,
_x=-x,
_y=-y,
_dx=-dx,
_dy=-dy,
ix=xx,
iy=yy,
idx=idx,
idy=idy,
index=segment_index,
index1=segment_index + 1,
segment_index=segment_index,
segment_index1=segment_index + 1,
lines_index=lines_index,
lines_index1=lines_index + 1,
layer_index=layer_index,
layer_index1=layer_index + 1,
layer_id=layer_id,
filename=filename,
global_index=global_index,
global_index1=global_index + 1,
)
last_x = x
last_y = y
global_index += 1
write_template(
line_end,
x=last_x,
y=last_y,
ix=xx,
iy=yy,
index=lines_index,
index1=lines_index + 1,
lines_index=lines_index,
lines_index1=lines_index + 1,
layer_index=layer_index,
layer_index1=layer_index + 1,
layer_id=layer_id,
filename=filename,
global_index=global_index,
global_index1=global_index + 1,
)
if lines_index != lastlines_index:
write_template(
line_join,
x=last_x,
y=last_y,
ix=xx,
iy=yy,
index=lines_index,
index1=lines_index + 1,
lines_index=lines_index,
lines_index1=lines_index + 1,
layer_index=layer_index,
layer_index1=layer_index + 1,
layer_id=layer_id,
filename=filename,
global_index=global_index,
global_index1=global_index + 1,
)
global_index += 1
write_template(
layer_end,
x=last_x,
y=last_y,
ix=xx,
iy=yy,
index=layer_index,
index1=layer_index + 1,
layer_index=layer_index,
layer_index1=layer_index + 1,
layer_id=layer_id,
filename=filename,
global_index=global_index,
global_index1=global_index + 1,
)
if layer_index != lastlayer_index:
write_template(
layer_join,
x=last_x,
y=last_y,
ix=xx,
iy=yy,
index=layer_index,
index1=layer_index + 1,
layer_index=layer_index,
layer_index1=layer_index + 1,
layer_id=layer_id,
filename=filename,
global_index=global_index,
global_index1=global_index + 1,
)
current_layer = None
write_template(
document_end,
filename=filename,
global_index=global_index,
global_index1=global_index + 1,
)
# handle info string
info = config.get("info", None)
if info and not quiet:
print(info, file=sys.stderr)
return orig_document
gwrite.help_group = "Output"