-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathstl2ps.py
265 lines (252 loc) · 8.62 KB
/
stl2ps.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
#! /usr/bin/env python
# file: stl2ps.py
# vim:fileencoding=utf-8:fdm=marker:ft=python
#
# Copyright © 2011-2020 R.F. Smith <[email protected]>.
# SPDX-License-Identifier: MIT
# Created: 2011-04-11T01:41:59+02:00
# Last modified: 2022-12-20T00:01:23+0100
"""
Program for converting a view of an STL file into a PostScript file.
Using the -x, -y and -z options you can rotate the object around these axis.
Subsequent rotations will be applied in the order they are given on the command
line.
Note that the object will be automatically centered and scaled to fit in the
picture.
"""
import argparse
import logging
import sys
import time
from stltools import stl, bbox, utils, vecops, matrix, __version__
def main(argv):
"""
Entry point of stl2ps.
Arguments:
argv: Command line arguments (without program name!)
"""
args = setup(argv)
f_red, f_green, f_blue = utils.num2rgb(args.fg)
if "rotations" not in args:
logging.info("no rotations specified")
tr = matrix.I()
else:
tl = []
which = {"x": matrix.rotx, "y": matrix.roty, "z": matrix.rotz}
for axis, rot in args.rotations:
tl.append(which[axis](rot))
tr = matrix.concat(*tl)
logging.info("rotation matrix:\n{}".format(tr))
if not args.outfile:
args.outfile = utils.outname(args.file, ".eps")
ofs = "no output filename given, using '{}'"
logging.info(ofs.format(args.outfile))
logging.info("reading STL file '{}'".format(args.file))
try:
start = time.monotonic()
vertices, _ = stl.readstl(args.file, args.encoding)
dt = time.monotonic() - start
logging.info(f"reading the STL file took {dt:.3f} s")
except ValueError as e:
logging.error(f"{args.file}: {e}")
sys.exit(1)
start = time.monotonic()
indices, uvertices = vecops.indexate(vertices)
dt = time.monotonic() - start
logging.info(f"indexing the vertices took {dt:.3f} s")
del vertices
origbb = bbox.makebb(uvertices)
logging.info("calculating normal vectors")
start = time.monotonic()
ifacets = list(utils.chunked(indices, 3))
normals = [
vecops.normal(uvertices[a], uvertices[b], uvertices[c]) for a, b, c in ifacets
]
dt = time.monotonic() - start
logging.info(f"calculating the normal vectors took {dt:.3f} s")
cscale = args.canvas_size / 10
csys = [(0, 0, 0), (cscale, 0, 0), (0, cscale, 0), (0, 0, cscale)]
start = time.monotonic()
uvertices = vecops.xform(tr, uvertices)
normals = vecops.xform(tr, normals)
csys = vecops.xform(tr, csys)
dt = time.monotonic() - start
logging.info(f"applying transformations to world coordinates took {dt:.3f} s")
minx, maxx, miny, maxy, _, maxz = bbox.makebb(uvertices)
width = maxx - minx
height = maxy - miny
dx = -(minx + maxx) / 2
dy = -(miny + maxy) / 2
dz = -maxz
m = matrix.trans([dx, dy, dz])
sf = min(args.canvas_size / width, args.canvas_size / height)
v = matrix.scale(sf, sf)
v[0][3], v[1][3] = args.canvas_size / 2, args.canvas_size / 2
mv = matrix.concat(m, v)
start = time.monotonic()
uvertices = vecops.xform(mv, uvertices)
csys = vecops.xform(mv, csys)
dt = time.monotonic() - start
logging.info(f"transforming to view space took {dt:.3f} s")
# In the ortho projection on the z=0 plane, z+ is _towards_ the viewer
start = time.monotonic()
vf = [(f, n, 0.4 * n[2] + 0.5) for f, n in zip(ifacets, normals) if n[2] > 0]
dt = time.monotonic() - start
fvs = "{:.2f}% of facets is visible"
logging.info(fvs.format(100 * len(vf) / len(ifacets)))
logging.info(f"determining visible facets took {dt:.3f} s")
# Next, depth-sort the facets using the largest z-value of the
# three vertices.
def fkey(t):
(a, b, c), _, _ = t
return max(uvertices[a][2], uvertices[b][2], uvertices[c][2])
start = time.monotonic()
vf.sort(key=fkey)
dt = time.monotonic() - start
logging.info(f"depth-sorting visible facets took {dt:.3f} s")
minx, maxx, miny, maxy, _, maxz = bbox.makebb(uvertices)
start = time.monotonic()
# logging.info("creating PostScript header")
s1 = "% The scale factor used is: {:.2f} PostScript points/STL-unit"
s2 = (
"% This becomes a picture of {:.0f}×{:.0f} PostScript points;"
" {:.0f}×{:.0f} mm."
)
cs = "% {:.2f} ≤ {} ≤ {:.2f}"
lines = [
"%!PS-Adobe-3.0 EPSF-3.0",
"%%BoundingBox: 0 0 {:.0f} {:.0f}".format(maxx, maxy),
"%%EndComments",
"% Generated by stl2ps {}".format(__version__),
"% on {}.".format(time.asctime()),
"% Bounding box (STL units)",
cs.format(origbb[0], "x", origbb[1]),
cs.format(origbb[2], "y", origbb[3]),
cs.format(origbb[4], "z", origbb[5]),
s1.format(sf),
s2.format(maxx, maxy, maxx / 72 * 25.4, maxy / 72 * 25.4),
"% {} of {} facets are visible.".format(len(vf), len(ifacets)),
]
# PostScript settings and macros.
lines += [
"% Settings",
".5 setlinewidth",
"1 setlinejoin",
"% Defining drawing commands",
"/c {setrgbcolor} def",
"/f {moveto} def",
"/s {lineto} def",
"/t {lineto closepath gsave fill grestore stroke} def",
"% Start drawing",
]
# Draw triangles.
lines += ["% Rendering triangles"]
s3 = "{:4.2f} {:4.2f} {:4.2f} c {:.3f} {:.3f} f {:.3f} {:.3f} s {:.3f} {:.3f} t"
lines += [
s3.format(
f_red * i,
f_green * i,
f_blue * i,
uvertices[a][0],
uvertices[a][1],
uvertices[b][0],
uvertices[b][1],
uvertices[c][0],
uvertices[c][1],
)
for (a, b, c), z, i in vf
]
if args.axes:
lines += [
"1 0 0 c",
f"{csys[0][0]} {csys[0][1]} f",
f"{csys[1][0]} {csys[1][1]} lineto closepath stroke",
"0 1 0 c",
f"{csys[0][0]} {csys[0][1]} f",
f"{csys[2][0]} {csys[2][1]} lineto closepath stroke",
"0 0 1 c",
f"{csys[0][0]} {csys[0][1]} f",
f"{csys[3][0]} {csys[3][1]} lineto closepath stroke",
]
pass
lines += ["showpage", "%%EOF"]
outs = "\n".join(lines)
try:
with open(args.outfile, "w+") as outf:
logging.info('writing output file "{}"'.format(args.outfile))
outf.write(outs)
logging.info("done")
except Exception:
logging.error('cannot write output file "{}"'.format(args.outfile))
dt = time.monotonic() - start
logging.info(f"generating PostScript file took {dt:.3f} s")
def setup(argv):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--log",
default="warning",
choices=["debug", "info", "warning", "error"],
help="logging level (defaults to 'warning')",
)
parser.add_argument(
"-a",
"--axes",
action="store_true",
help="Add coordinate system (x,y,z = red, green, blue)",
)
parser.add_argument(
"-c",
"--canvas",
dest="canvas_size",
type=int,
help="canvas size, defaults to 200 PostScript points",
default=200,
)
parser.add_argument(
"-f",
"--foreground",
dest="fg",
type=str,
help="foreground color in 6-digit hexdecimal RGB (default E6E6E6)",
default="E6E6E6",
)
parser.add_argument(
"-e",
"--encoding",
type=str,
help="encoding for the name of the STL object (default utf-8)",
default="utf-8",
)
parser.add_argument(
"-o", "--output", dest="outfile", type=str, help="output file name", default=""
)
parser.add_argument(
"-x",
type=float,
action=utils.RotateAction,
help="rotation around X axis in degrees",
)
parser.add_argument(
"-y",
type=float,
action=utils.RotateAction,
help="rotation around Y axis in degrees",
)
parser.add_argument(
"-z",
type=float,
action=utils.RotateAction,
help="rotation around Z axis in degrees",
)
parser.add_argument("-v", "--version", action="version", version=__version__)
parser.add_argument("file", nargs=1, type=str, help="name of the file to process")
args = parser.parse_args(argv)
logging.basicConfig(
level=getattr(logging, args.log.upper(), None),
format="%(levelname)s: %(message)s",
)
args.file = args.file[0]
args.fg = int(args.fg, 16)
return args
if __name__ == "__main__":
main(sys.argv[1:])