vectorbench 0.0.0-stage → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,556 @@
1
+ """vb3d: draw 3D models as SVG.
2
+
3
+ Build the parts of a solid subject as meshes (trimesh for primitives and
4
+ extrusions, manifold3d for booleans, smoothing and signed-distance shapes),
5
+ set a camera and lights, and render. You get SVG markup in which each part's
6
+ visible surface is shaded from the lights in smooth bands, hidden surfaces
7
+ are removed, parts cast shadows on each other, and every outline is exact.
8
+ Drop the markup into your drawing as it is, or use the pieces (outlines,
9
+ crease lines, projected points) to draw over it in your own style.
10
+
11
+ import numpy as np, trimesh, vb3d
12
+ body = trimesh.creation.capsule(height=60, radius=20)
13
+ cap = trimesh.creation.cylinder(radius=9, height=6).apply_translation((0, 0, 22))
14
+ scene = vb3d.Scene(frame=(0, 0, 1024, 1024)) # where the picture goes, in your SVG's units
15
+ scene.camera(eye=(80, -160, 140), target=(0, 0, 0)) # orthographic; fov=35 for perspective
16
+ scene.light(direction=(-0.4, -0.5, 1), strength=0.95) # points from the surface towards the light
17
+ scene.light(direction=(0.8, 0.3, 0.2), color='#cfe0ff', strength=0.25, shadows=False)
18
+ scene.ambient(0.22)
19
+ scene.add('body', body, color='#ece9e2', gloss=0.35)
20
+ scene.add('cap', cap, color='#55595c', gloss=0.1)
21
+ markup = scene.render() # '<g>...</g>' to put inside your <svg>
22
+ scene.preview('quick.png') # the shaded picture as a PNG, to `view` quickly
23
+ d = scene.outline('cap') # path data of the cap's visible area
24
+ e = scene.edges('body', angle=30) # path data of the visible sharp edges
25
+ pts = scene.project([(0, 0, 25)]) # 3D points to 2D, in the frame's units
26
+
27
+ Units: any. +z is up unless you pass `up`. The camera fits the whole scene
28
+ into the frame unless you give `scale` (frame units per world unit).
29
+ Everything is computed on a raster (`detail`, default 2 pixels per frame
30
+ unit) and traced back into vector paths, so a render takes seconds, and
31
+ the markup is usually 10-60 KB; fewer `levels` or a larger `tolerance`
32
+ makes it smaller.
33
+ """
34
+
35
+ import numpy as np
36
+
37
+ __all__ = ["Scene"]
38
+
39
+
40
+ def _rgb(color):
41
+ """'#rrggbb', '#rgb' or (r, g, b) in 0..1 -> linear-light RGB array."""
42
+ if isinstance(color, str):
43
+ c = color.lstrip("#")
44
+ if len(c) == 3:
45
+ c = "".join(ch * 2 for ch in c)
46
+ srgb = np.array([int(c[i:i + 2], 16) for i in (0, 2, 4)], float) / 255
47
+ else:
48
+ srgb = np.clip(np.asarray(color, float)[:3], 0, 1)
49
+ return np.where(srgb <= 0.04045, srgb / 12.92, ((srgb + 0.055) / 1.055) ** 2.4)
50
+
51
+
52
+ def _hex(linear):
53
+ linear = np.clip(linear, 0, 1)
54
+ srgb = np.where(linear <= 0.0031308, linear * 12.92, 1.055 * linear ** (1 / 2.4) - 0.055)
55
+ return "#%02x%02x%02x" % tuple(int(round(v * 255)) for v in np.clip(srgb, 0, 1))
56
+
57
+
58
+ def _unit(v):
59
+ v = np.asarray(v, float)
60
+ n = np.linalg.norm(v, axis=-1, keepdims=True)
61
+ return v / np.where(n == 0, 1, n)
62
+
63
+
64
+ def _corner_normals(mesh, crease):
65
+ """Per-corner normals, smooth across edges flatter than `crease` degrees and sharp across steeper ones."""
66
+ fn = np.asarray(mesh.face_normals)
67
+ faces = np.asarray(mesh.faces)
68
+ area = np.asarray(mesh.area_faces)
69
+ if crease is None or crease <= 0:
70
+ return np.repeat(fn[:, None, :], 3, axis=1)
71
+ vf = np.asarray(mesh.vertex_faces) # vertices x max valence, -1 padded
72
+ cos = np.cos(np.radians(crease))
73
+ out = np.empty((len(faces), 3, 3))
74
+ for corner in range(3):
75
+ for start in range(0, len(faces), 4096):
76
+ idx = slice(start, start + 4096)
77
+ near = vf[faces[idx, corner]] # chunk x K
78
+ valid = near >= 0
79
+ nb = fn[np.where(valid, near, 0)] # chunk x K x 3
80
+ agree = (np.einsum("ckj,cj->ck", nb, fn[idx]) >= cos) & valid
81
+ w = np.where(agree, area[np.where(valid, near, 0)], 0)[..., None]
82
+ out[idx, corner] = _unit((nb * w).sum(1) + fn[idx] * 1e-9)
83
+ return out
84
+
85
+
86
+ def _contours(mask, pad=1):
87
+ from skimage.measure import find_contours
88
+
89
+ m = np.pad(mask.astype(np.float32), pad)
90
+ return [c - pad for c in find_contours(m, 0.5)]
91
+
92
+
93
+ class Scene:
94
+ def __init__(self, frame=(0, 0, 1024, 1024), detail=2.0, background=None):
95
+ """`frame` is (x, y, width, height) in your SVG's units: where the picture is placed.
96
+ `detail` is raster pixels per frame unit (2 is plenty; 3 for very fine parts)."""
97
+ self.frame = tuple(float(v) for v in frame)
98
+ self.detail = float(detail)
99
+ self.parts = []
100
+ self.lights = []
101
+ self.ambient_color = _rgb("#ffffff")
102
+ self.ambient_strength = 0.25
103
+ self.view = dict(eye=(0, -1, 1), target=(0, 0, 0), up=(0, 0, 1), fov=None, scale=None, fit=0.9, center=None, fit_to=None)
104
+ self._raster = None
105
+ self._fitted = None
106
+
107
+ # ---- set-up -----------------------------------------------------------------
108
+ def camera(self, eye, target=(0, 0, 0), up=(0, 0, 1), fov=None, scale=None, fit=0.9, center=None, fit_to=None):
109
+ """Where the camera is and what it looks at. `fov` (degrees) makes it a perspective
110
+ camera; without it the view is orthographic. The scene is fitted into `fit` of the
111
+ frame unless `scale` (frame units per world unit) is given; `center` is then the frame
112
+ point the target lands on (default: the frame's middle). `fit_to` names the parts to fit
113
+ (say, everything but a floor that runs out of the frame)."""
114
+ self.view = dict(eye=eye, target=target, up=up, fov=fov, scale=scale, fit=fit, center=center, fit_to=fit_to)
115
+ self._raster = None
116
+ self._fitted = None
117
+
118
+ def light(self, direction, color="#ffffff", strength=1.0, shadows=True, softness=1.0):
119
+ """A distant light. `direction` points from the surface towards the light."""
120
+ self.lights.append(dict(direction=_unit(direction), color=_rgb(color), strength=float(strength), shadows=bool(shadows), softness=float(softness)))
121
+ self._raster = None
122
+
123
+ def ambient(self, strength=0.25, color="#ffffff"):
124
+ """Light from everywhere, so nothing is pure black. Accepts (strength) or (color, strength)."""
125
+ if isinstance(strength, str):
126
+ strength, color = (color if not isinstance(color, str) else 0.25), strength
127
+ self.ambient_strength = float(strength)
128
+ self.ambient_color = _rgb(color)
129
+ self._raster = None
130
+
131
+ def add(self, name, mesh, color="#cccccc", gloss=0.3, shininess=40, crease=35, rim=0.0, opacity=1.0):
132
+ """A part. `mesh` is a trimesh.Trimesh (or anything with .vertices and .faces, such as a
133
+ manifold3d Manifold). `gloss` is how strong its highlights are (0 matte to 1 polished),
134
+ `shininess` how tight they are (8 broad to 200 pinpoint). Edges sharper than `crease`
135
+ degrees shade as edges; flatter ones blend smoothly. `rim` adds a light edge glow."""
136
+ import trimesh
137
+
138
+ if not isinstance(mesh, trimesh.Trimesh):
139
+ if hasattr(mesh, "to_mesh"): # manifold3d
140
+ m = mesh.to_mesh()
141
+ mesh = trimesh.Trimesh(np.asarray(m.vert_properties)[:, :3], np.asarray(m.tri_verts), process=True)
142
+ else:
143
+ mesh = trimesh.Trimesh(np.asarray(mesh.vertices), np.asarray(mesh.faces), process=True)
144
+ if any(p["name"] == name for p in self.parts):
145
+ raise ValueError(f"There is already a part called {name!r}.")
146
+ self._fitted = None
147
+ self.parts.append(dict(name=name, mesh=mesh, color=_rgb(color), gloss=float(gloss), shininess=float(shininess), crease=crease, rim=float(rim), opacity=float(opacity)))
148
+ self._raster = None
149
+
150
+ # ---- geometry ---------------------------------------------------------------
151
+ def _basis(self):
152
+ v = self.view
153
+ eye, target = np.asarray(v["eye"], float), np.asarray(v["target"], float)
154
+ f = _unit(target - eye)
155
+ r = _unit(np.cross(f, np.asarray(v["up"], float)))
156
+ if not np.any(r):
157
+ r = _unit(np.cross(f, (0, 1, 0) if abs(f[1]) < 0.9 else (1, 0, 0)))
158
+ u = np.cross(r, f)
159
+ return eye, target, r, u, f
160
+
161
+ def _camera_space(self, points):
162
+ eye, _, r, u, f = self._basis()
163
+ p = np.asarray(points, float) - eye
164
+ return np.stack([p @ r, p @ u, p @ f], axis=-1)
165
+
166
+ def _screen(self, cam):
167
+ """Camera space -> unscaled screen (x right, y down)."""
168
+ if self.view["fov"]:
169
+ z = np.maximum(cam[..., 2], 1e-6)
170
+ return np.stack([cam[..., 0] / z, -cam[..., 1] / z], axis=-1)
171
+ return np.stack([cam[..., 0], -cam[..., 1]], axis=-1)
172
+
173
+ def _fit(self):
174
+ if getattr(self, "_fitted", None) is not None:
175
+ return self._fitted
176
+ if not self.parts:
177
+ raise ValueError("Add a part before rendering.")
178
+ x0, y0, w, h = self.frame
179
+ v = self.view
180
+ chosen = [p for p in self.parts if not v["fit_to"] or p["name"] in v["fit_to"]] or self.parts
181
+ allv = np.concatenate([p["mesh"].vertices for p in chosen])
182
+ scr = self._screen(self._camera_space(allv))
183
+ if v["scale"]:
184
+ s = float(v["scale"])
185
+ if v["fov"]:
186
+ # world units at the target's distance
187
+ _, target, *_ = self._basis()
188
+ s *= float(self._camera_space([target])[0, 2])
189
+ tgt = self._screen(self._camera_space([v["target"]]))[0]
190
+ cx, cy = v["center"] or (x0 + w / 2, y0 + h / 2)
191
+ off = np.array([cx, cy]) - tgt * s
192
+ else:
193
+ lo, hi = scr.min(0), scr.max(0)
194
+ span = np.maximum(hi - lo, 1e-9)
195
+ s = v["fit"] * min(w / span[0], h / span[1])
196
+ off = np.array([x0 + w / 2, y0 + h / 2]) - (lo + hi) / 2 * s
197
+ self._fitted = (s, off)
198
+ return self._fitted
199
+
200
+ def project(self, points):
201
+ """3D points -> 2D points in the frame's units (an N x 2 array)."""
202
+ s, off = self._fit()
203
+ return self._screen(self._camera_space(np.atleast_2d(points))) * s + off
204
+
205
+ # ---- rasterising ------------------------------------------------------------
206
+ @staticmethod
207
+ def _rasterise(xy, depth, tris, shape, persp, zbuf=None, ids=None, bary=None, tag=0):
208
+ """Depth-tested triangle fill. xy: V x 2 raster coords, depth: V camera depth."""
209
+ H, W = shape
210
+ if zbuf is None:
211
+ zbuf = np.full(shape, np.inf, np.float32)
212
+ for t, (a, b, c) in enumerate(tris):
213
+ xa, ya = xy[a]; xb, yb = xy[b]; xc, yc = xy[c]
214
+ area = (xb - xa) * (yc - ya) - (yb - ya) * (xc - xa)
215
+ if abs(area) < 1e-12:
216
+ continue
217
+ ix0 = max(int(np.floor(min(xa, xb, xc))), 0); ix1 = min(int(np.ceil(max(xa, xb, xc))), W - 1)
218
+ iy0 = max(int(np.floor(min(ya, yb, yc))), 0); iy1 = min(int(np.ceil(max(ya, yb, yc))), H - 1)
219
+ if ix0 > ix1 or iy0 > iy1:
220
+ continue
221
+ px = np.arange(ix0, ix1 + 1) + 0.5
222
+ py = (np.arange(iy0, iy1 + 1) + 0.5)[:, None]
223
+ w0 = ((xb - px) * (yc - py) - (yb - py) * (xc - px)) / area
224
+ w1 = ((xc - px) * (ya - py) - (yc - py) * (xa - px)) / area
225
+ w2 = 1 - w0 - w1
226
+ inside = (w0 >= -1e-6) & (w1 >= -1e-6) & (w2 >= -1e-6)
227
+ if not inside.any():
228
+ continue
229
+ da, db, dc = depth[a], depth[b], depth[c]
230
+ if persp:
231
+ iz = w0 / da + w1 / db + w2 / dc
232
+ z = 1 / np.where(iz == 0, 1e-9, iz)
233
+ else:
234
+ z = w0 * da + w1 * db + w2 * dc
235
+ region = zbuf[iy0:iy1 + 1, ix0:ix1 + 1]
236
+ win = inside & (z < region)
237
+ if not win.any():
238
+ continue
239
+ region[win] = z[win]
240
+ if ids is not None:
241
+ ids[0][iy0:iy1 + 1, ix0:ix1 + 1][win] = tag
242
+ ids[1][iy0:iy1 + 1, ix0:ix1 + 1][win] = t
243
+ if persp:
244
+ b0 = w0 / da * z; b1 = w1 / db * z
245
+ else:
246
+ b0, b1 = w0, w1
247
+ bary[0][iy0:iy1 + 1, ix0:ix1 + 1][win] = b0[win]
248
+ bary[1][iy0:iy1 + 1, ix0:ix1 + 1][win] = b1[win]
249
+ return zbuf
250
+
251
+ def _shadow_map(self, light):
252
+ """Depth from the light's side, for all parts, as (lookup function)."""
253
+ L = light["direction"]
254
+ f = -L
255
+ r = _unit(np.cross(f, (0, 0, 1) if abs(f[2]) < 0.95 else (0, 1, 0)))
256
+ u = np.cross(r, f)
257
+ allv = np.concatenate([p["mesh"].vertices for p in self.parts])
258
+ lx, ly = allv @ r, allv @ u
259
+ size = int(min(4096, max(1024, 1.5 * self.detail * max(self.frame[2], self.frame[3]))))
260
+ lo = np.array([lx.min(), ly.min()]); span = max(lx.max() - lx.min(), ly.max() - ly.min(), 1e-9) * 1.04
261
+ lo -= span * 0.02
262
+ k = size / span
263
+ zbuf = np.full((size, size), np.inf, np.float32)
264
+ for p in self.parts:
265
+ v = np.asarray(p["mesh"].vertices)
266
+ xy = np.stack([(v @ r - lo[0]) * k, (v @ u - lo[1]) * k], -1)
267
+ self._rasterise(xy, v @ f, np.asarray(p["mesh"].faces), zbuf.shape, False, zbuf)
268
+ texel = 1 / k
269
+
270
+ def lit(points):
271
+ px = (points @ r - lo[0]) * k - 0.5; py = (points @ u - lo[1]) * k - 0.5
272
+ d = points @ f
273
+ bias = 2.5 * texel
274
+ total = np.zeros(len(points))
275
+ spread = light["softness"]
276
+ offsets = [(i, j) for i in (-1, 0, 1) for j in (-1, 0, 1)]
277
+ for i, j in offsets:
278
+ xi = np.clip(np.round(px + i * spread).astype(int), 0, size - 1)
279
+ yi = np.clip(np.round(py + j * spread).astype(int), 0, size - 1)
280
+ total += d <= zbuf[yi, xi] + bias
281
+ return total / len(offsets)
282
+
283
+ return lit
284
+
285
+ def _render_raster(self):
286
+ if self._raster is not None:
287
+ return self._raster
288
+ self._fitted = None
289
+ s, off = self._fit()
290
+ x0, y0, w, h = self.frame
291
+ H, W = int(round(h * self.detail)), int(round(w * self.detail))
292
+ persp = bool(self.view["fov"])
293
+ zbuf = np.full((H, W), np.inf, np.float32)
294
+ pid = np.full((H, W), -1, np.int16)
295
+ fid = np.full((H, W), -1, np.int32)
296
+ b0 = np.zeros((H, W), np.float32); b1 = np.zeros((H, W), np.float32)
297
+ for k, p in enumerate(self.parts):
298
+ v = np.asarray(p["mesh"].vertices)
299
+ cam = self._camera_space(v)
300
+ xy = (self._screen(cam) * s + off - (x0, y0)) * self.detail
301
+ self._rasterise(xy, cam[:, 2], np.asarray(p["mesh"].faces), (H, W), persp, zbuf, (pid, fid), (b0, b1), tag=k)
302
+ # shading
303
+ eye, _, r, u, f = self._basis()
304
+ colour = np.zeros((H, W, 3)); diffuse_l = np.zeros((H, W)); spec = np.zeros((H, W)); spec_col = np.zeros(3)
305
+ world = np.zeros((H, W, 3))
306
+ normals = np.zeros((H, W, 3))
307
+ for k, p in enumerate(self.parts):
308
+ sel = pid == k
309
+ if not sel.any():
310
+ continue
311
+ mesh = p["mesh"]
312
+ faces = np.asarray(mesh.faces)[fid[sel]]
313
+ wa, wb = b0[sel][:, None], b1[sel][:, None]
314
+ wc = 1 - wa - wb
315
+ V = np.asarray(mesh.vertices)
316
+ P = V[faces[:, 0]] * wa + V[faces[:, 1]] * wb + V[faces[:, 2]] * wc
317
+ cn = _corner_normals(mesh, p["crease"])[fid[sel]]
318
+ N = _unit(cn[:, 0] * wa + cn[:, 1] * wb + cn[:, 2] * wc)
319
+ view_dir = _unit(eye - P) if persp else np.broadcast_to(-f, P.shape)
320
+ flip = (N * view_dir).sum(1) < 0
321
+ N[flip] *= -1
322
+ world[sel] = P; normals[sel] = N
323
+ self._raster = dict(pid=pid, fid=fid, zbuf=zbuf, world=world, normals=normals, shape=(H, W), persp=persp)
324
+ lookups = [self._shadow_map(L) if L["shadows"] else None for L in self.lights]
325
+ for k, p in enumerate(self.parts):
326
+ sel = pid == k
327
+ if not sel.any():
328
+ continue
329
+ P, N = world[sel], normals[sel]
330
+ view_dir = _unit(eye - P) if persp else np.broadcast_to(-f, P.shape)
331
+ light_sum = np.tile(self.ambient_color * self.ambient_strength, (len(P), 1))
332
+ sp = np.zeros(len(P)); spc = np.zeros(3)
333
+ for L, lookup in zip(self.lights, lookups):
334
+ ndl = np.clip(N @ L["direction"], 0, None)
335
+ vis = lookup(P + N * 1e-6) if lookup is not None else 1.0
336
+ light_sum += (ndl * vis)[:, None] * L["color"] * L["strength"]
337
+ hv = _unit(view_dir + L["direction"])
338
+ term = np.clip((N * hv).sum(1), 0, None) ** p["shininess"] * (ndl > 0) * vis * L["strength"] * p["gloss"]
339
+ sp += term; spc += L["color"] * L["strength"]
340
+ if p["rim"]:
341
+ ndv = np.clip((N * view_dir).sum(1), 0, 1)
342
+ light_sum += (p["rim"] * (1 - ndv) ** 3)[:, None] * self.ambient_color
343
+ base = p["color"] * light_sum
344
+ colour[sel] = base
345
+ diffuse_l[sel] = base @ np.array([0.2126, 0.7152, 0.0722])
346
+ spec[sel] = sp
347
+ spec_col = spc
348
+ self._raster.update(colour=colour, lum=diffuse_l, spec=spec, spec_col=spec_col / spec_col.max() if spec_col.any() else np.ones(3))
349
+ return self._raster
350
+
351
+ # ---- outputs ----------------------------------------------------------------
352
+ @staticmethod
353
+ def _fmt(pts, decimals):
354
+ """Closed polygon as compact path data: an absolute start, then relative steps."""
355
+ q = np.round(np.asarray(pts, float), decimals)
356
+ steps = np.round(np.diff(q, axis=0), decimals)
357
+ num = (lambda v: f"{v:.{decimals}f}".rstrip("0").rstrip(".") if decimals else str(int(v)))
358
+ clean = lambda v: num(v).replace("-0.", "-.").lstrip("0") if abs(v) < 1 and v != 0 else (num(v) if v != 0 else "0")
359
+ body = " ".join(f"{clean(a)} {clean(b)}" for a, b in steps if a or b)
360
+ return (f"M{clean(q[0][0])} {clean(q[0][1])}l" + body + "z").replace(" -", "-")
361
+
362
+ def _path(self, mask, tolerance, decimals=1):
363
+ from skimage.measure import approximate_polygon
364
+
365
+ x0, y0, *_ = self.frame
366
+ d = []
367
+ k = 1 / self.detail
368
+ rows, cols = np.any(mask, 1), np.any(mask, 0)
369
+ if not rows.any():
370
+ return ""
371
+ r0, r1 = np.argmax(rows), len(rows) - np.argmax(rows[::-1])
372
+ c0, c1 = np.argmax(cols), len(cols) - np.argmax(cols[::-1])
373
+ for c in _contours(mask[r0:r1, c0:c1]):
374
+ c = c + (r0, c0)
375
+ if len(c) < 4:
376
+ continue
377
+ c = approximate_polygon(c, tolerance * self.detail)
378
+ if len(c) < 4:
379
+ continue
380
+ area = 0.5 * abs(np.dot(c[:, 0], np.roll(c[:, 1], 1)) - np.dot(c[:, 1], np.roll(c[:, 0], 1)))
381
+ if area < (0.8 * self.detail) ** 2:
382
+ continue
383
+ xs = (c[:, 1] + 0.5) * k + x0
384
+ ys = (c[:, 0] + 0.5) * k + y0
385
+ d.append(self._fmt(np.stack([xs, ys], 1)[:-1], decimals))
386
+ return "".join(d)
387
+
388
+ def outline(self, name, tolerance=0.3):
389
+ """Path data (fill-rule evenodd) of the part's visible area."""
390
+ R = self._render_raster()
391
+ return self._path(R["pid"] == self._index(name), tolerance)
392
+
393
+ def _index(self, name):
394
+ for k, p in enumerate(self.parts):
395
+ if p["name"] == name:
396
+ return k
397
+ raise KeyError(f"There is no part called {name!r}; the parts are {[p['name'] for p in self.parts]}.")
398
+
399
+ def edges(self, name, angle=30, tolerance=0.3, boundary=True):
400
+ """Path data (lines, to stroke) of the part's visible edges sharper than `angle` degrees,
401
+ and its open borders if `boundary`."""
402
+ R = self._render_raster()
403
+ k_part = self._index(name)
404
+ mesh = self.parts[k_part]["mesh"]
405
+ pairs = []
406
+ sharp = np.asarray(mesh.face_adjacency_angles) > np.radians(angle)
407
+ if sharp.any():
408
+ pairs.append(np.asarray(mesh.face_adjacency_edges)[sharp])
409
+ if boundary:
410
+ from trimesh.grouping import group_rows
411
+
412
+ e = np.sort(np.asarray(mesh.edges), axis=1)
413
+ single = group_rows(e, require_count=1)
414
+ if len(single):
415
+ pairs.append(e[single])
416
+ if not pairs:
417
+ return ""
418
+ pairs = np.concatenate(pairs)
419
+ V = np.asarray(mesh.vertices)
420
+ s, off = self._fit()
421
+ x0, y0, *_ = self.frame
422
+ H, W = R["shape"]
423
+ zspan = np.ptp(R["zbuf"][np.isfinite(R["zbuf"])]) if np.isfinite(R["zbuf"]).any() else 1
424
+ tol = 0.004 * zspan + 1e-6
425
+ out = []
426
+ for a, b in pairs:
427
+ A, B = V[a], V[b]
428
+ pa, pb = self.project([A, B])
429
+ n = int(max(2, np.hypot(*(pb - pa)) * self.detail))
430
+ t = np.linspace(0, 1, n)[:, None]
431
+ P3 = A + (B - A) * t
432
+ cam = self._camera_space(P3)
433
+ xy = (self._screen(cam) * s + off - (x0, y0)) * self.detail
434
+ xi = np.clip(xy[:, 0].astype(int), 0, W - 1); yi = np.clip(xy[:, 1].astype(int), 0, H - 1)
435
+ # visible if nothing nearer covers the point (look at the pixel and its neighbours)
436
+ best = R["zbuf"][yi, xi]
437
+ for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
438
+ best = np.maximum(best, R["zbuf"][np.clip(yi + dy, 0, H - 1), np.clip(xi + dx, 0, W - 1)])
439
+ vis = cam[:, 2] <= best + tol
440
+ pts = self.project(P3)
441
+ run = []
442
+ for ok, pt in zip(vis, pts):
443
+ if ok:
444
+ run.append(pt)
445
+ elif len(run) > 1:
446
+ out.append(run); run = []
447
+ else:
448
+ run = []
449
+ if len(run) > 1:
450
+ out.append(run)
451
+ d = []
452
+ for run in out:
453
+ run = np.round(np.asarray(run), 1)
454
+ ax, ay = run[-1] - run[0]
455
+ keep = [run[0]] + [q for q in run[1:-1] if abs(ax * (q[1] - run[0][1]) - ay * (q[0] - run[0][0])) > tolerance * np.hypot(ax, ay)] + [run[-1]]
456
+ d.append("M" + " ".join(f"{x:g} {y:g}" for x, y in keep))
457
+ return "".join(d)
458
+
459
+ def render(self, levels=16, soften=3.0, tolerance=0.3, highlights=True, parts=None, prefix="v3d"):
460
+ """SVG markup ('<g>...</g>', with its own <defs>) of the shaded parts in the frame.
461
+ `levels` is the most tone steps a part is traced in (a part with little variation in
462
+ its shading gets fewer; more is smoother and larger);
463
+ `soften` blurs the steps together (in frame units) inside each part's crisp outline;
464
+ `tolerance` is how far outlines may stray from the raster (frame units); the softened
465
+ tone steps inside them are traced more coarsely, since the blur hides it."""
466
+ from scipy import ndimage
467
+
468
+ R = self._render_raster()
469
+ pid, lum, colour, spec = R["pid"], R["lum"], R["colour"], R["spec"]
470
+ names = parts or [p["name"] for p in self.parts]
471
+ grow = max(2, int(np.ceil((soften * 2 + 1) * self.detail)))
472
+ coarse = max(tolerance, 0.5 * soften) if soften > 0 else tolerance
473
+ inner = 0 if soften >= 0.8 else 1 # decimals for the softened steps
474
+ defs = [f'<filter id="{prefix}-soft" x="-10%" y="-10%" width="120%" height="120%" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="{soften:g}"/></filter>'] if soften > 0 else []
475
+ groups = []
476
+ for name in names:
477
+ k = self._index(name)
478
+ p = self.parts[k]
479
+ full = pid == k
480
+ if not full.any():
481
+ continue
482
+ rr, cc = np.nonzero(full)
483
+ H, W = full.shape
484
+ r0, r1 = max(rr.min() - grow - 2, 0), min(rr.max() + grow + 3, H)
485
+ c0, c1 = max(cc.min() - grow - 2, 0), min(cc.max() + grow + 3, W)
486
+ box = (slice(r0, r1), slice(c0, c1))
487
+ mask = full[box]
488
+ lum_b, colour_b, spec_b = lum[box], colour[box], spec[box]
489
+ outline = self._path(full, tolerance * 0.7)
490
+ if not outline:
491
+ continue
492
+ # extend the tone field a little past the outline, so softened steps don't fade at the edge
493
+ dist, (iy, ix) = ndimage.distance_transform_edt(~mask, return_indices=True)
494
+ near = dist <= grow
495
+ L = np.where(mask, lum_b, lum_b[iy, ix])
496
+ Lstar = np.where(L > 0.008856, 116 * np.cbrt(L) - 16, 903.3 * L)
497
+ inside = Lstar[mask]
498
+ lo, hi = np.percentile(inside, 0.5), np.percentile(inside, 99.5)
499
+ # about one step per 2.5 units of lightness (L*), up to `levels`
500
+ count = int(np.clip(np.ceil((hi - lo) / 2.5), 2, max(2, levels)))
501
+ steps = np.linspace(lo, hi, count + 1)
502
+ bins = np.clip(np.digitize(inside, steps[1:-1]), 0, len(steps) - 2)
503
+ cols = colour_b[mask]
504
+ tone = []
505
+ for b in range(len(steps) - 1):
506
+ chosen = bins == b
507
+ tone.append(cols[chosen].mean(0) if chosen.any() else None)
508
+ known = [i for i, t in enumerate(tone) if t is not None]
509
+ for i in range(len(tone)):
510
+ if tone[i] is None:
511
+ j = min(known, key=lambda q: abs(q - i)); tone[i] = tone[j]
512
+ cid = f"{prefix}-{k}-clip"
513
+ defs.append(f'<clipPath id="{cid}"><path fill-rule="evenodd" d="{outline}"/></clipPath>')
514
+ fx, fy, fw, fh = self.frame
515
+ # the darkest tone fills the whole part, unblurred, so the softened steps above it never show a gap
516
+ base = f'<path fill="{_hex(tone[0])}" d="M{fx - 4:g} {fy - 4:g}h{fw + 8:g}v{fh + 8:g}h-{fw + 8:g}z"/>'
517
+ layers = []
518
+ for b in range(1, len(steps) - 1):
519
+ region = np.zeros_like(full)
520
+ region[box] = near & (Lstar >= steps[b])
521
+ d = self._path(region, coarse, inner)
522
+ if d:
523
+ layers.append(f'<path fill="{_hex(tone[b])}" fill-rule="evenodd" d="{d}"/>')
524
+ if highlights and p["gloss"] > 0:
525
+ S = np.where(mask, spec_b, spec_b[iy, ix]) * near
526
+ top = float(np.percentile(spec_b[mask], 99.8)) if mask.any() else 0
527
+ if top > 0.03:
528
+ n = 6
529
+ cover = min(0.92, top)
530
+ alpha = 1 - (1 - cover) ** (1 / n)
531
+ for lev in np.linspace(0.04, top, n + 1)[1:]:
532
+ region = np.zeros_like(full)
533
+ region[box] = S >= lev * 0.999
534
+ d = self._path(region, coarse, inner)
535
+ if d:
536
+ layers.append(f'<path fill="{_hex(R["spec_col"])}" fill-opacity="{alpha:.3f}" fill-rule="evenodd" d="{d}"/>')
537
+ soft = f' filter="url(#{prefix}-soft)"' if soften > 0 else ""
538
+ op = f' opacity="{p["opacity"]:g}"' if p["opacity"] < 1 else ""
539
+ groups.append(f'<g id="{prefix}-{name}"{op}><g clip-path="url(#{cid})">{base}<g{soft}>{"".join(layers)}</g></g></g>')
540
+ return f'<g><defs>{"".join(defs)}</defs>{"".join(groups)}</g>'
541
+
542
+ def preview(self, png, scale=1.0):
543
+ """Saves the shaded raster as a PNG (white where nothing is), to check a set-up quickly."""
544
+ from PIL import Image
545
+
546
+ R = self._render_raster()
547
+ c = R["colour"].copy()
548
+ spec = R["spec"][..., None] * R["spec_col"]
549
+ c = np.clip(c + spec, 0, 1)
550
+ srgb = np.where(c <= 0.0031308, c * 12.92, 1.055 * c ** (1 / 2.4) - 0.055)
551
+ img = np.where((R["pid"] >= 0)[..., None], srgb, 1.0)
552
+ im = Image.fromarray((np.clip(img, 0, 1) * 255).astype(np.uint8))
553
+ if scale != 1:
554
+ im = im.resize((max(1, int(im.width * scale)), max(1, int(im.height * scale))))
555
+ im.save(png)
556
+ return png