vecview 0.2.0__py3-none-any.whl
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.
- vecview/__init__.py +85 -0
- vecview/_occlusion.py +532 -0
- vecview/_types.py +31 -0
- vecview/_vec.py +69 -0
- vecview/camera.py +299 -0
- vecview/projections.py +232 -0
- vecview/py.typed +0 -0
- vecview/scene.py +2427 -0
- vecview/shapes.py +571 -0
- vecview-0.2.0.dist-info/METADATA +290 -0
- vecview-0.2.0.dist-info/RECORD +13 -0
- vecview-0.2.0.dist-info/WHEEL +4 -0
- vecview-0.2.0.dist-info/licenses/LICENSE +21 -0
vecview/scene.py
ADDED
|
@@ -0,0 +1,2427 @@
|
|
|
1
|
+
"""Scenes: world-space objects in, one SVG document per camera out.
|
|
2
|
+
|
|
3
|
+
A :class:`Scene` only records what was drawn, the way a 3D application keeps
|
|
4
|
+
objects separate from the camera that views them. Rendering replays the record
|
|
5
|
+
against a camera on a private canvas, which is where every projection happens.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import dataclasses
|
|
11
|
+
import functools
|
|
12
|
+
import itertools
|
|
13
|
+
import math
|
|
14
|
+
import re
|
|
15
|
+
from collections.abc import Callable, Iterable, Mapping, Sequence
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Literal, cast
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
import svg
|
|
21
|
+
|
|
22
|
+
from vecview._occlusion import (
|
|
23
|
+
Line,
|
|
24
|
+
Piece,
|
|
25
|
+
Plane,
|
|
26
|
+
Shape,
|
|
27
|
+
Surface,
|
|
28
|
+
Visibility,
|
|
29
|
+
capsule_depth,
|
|
30
|
+
planar_depth,
|
|
31
|
+
plane_through,
|
|
32
|
+
planes_through,
|
|
33
|
+
)
|
|
34
|
+
from vecview._types import Array, Point3, Points2, Points3, Style
|
|
35
|
+
from vecview._vec import as_points, basis_for, convex_hull, unit
|
|
36
|
+
from vecview.camera import Camera, ParallelCamera
|
|
37
|
+
from vecview.shapes import Face, Pivot, arrow_shape, ellipse_shape, prism_faces
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _points(projected: Array, ndigits: int = 2) -> list[svg.Point]:
|
|
41
|
+
"""Projected coordinates as the ``x,y`` pairs ``svg.py`` wants for ``points``."""
|
|
42
|
+
# Adding 0.0 turns the -0.0 that rounding can produce into 0.0.
|
|
43
|
+
return [
|
|
44
|
+
svg.Point(round(float(x), ndigits) + 0.0, round(float(y), ndigits) + 0.0)
|
|
45
|
+
for x, y in projected
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _face_id(base: str, name: str) -> str:
|
|
50
|
+
"""Per-face id derived from a base and a face name.
|
|
51
|
+
|
|
52
|
+
``+`` is not a legal XML name character, so the sign is spelled out:
|
|
53
|
+
``"slab"`` and ``"+z"`` give ``"slab-pz"``.
|
|
54
|
+
"""
|
|
55
|
+
return f"{base}-{name.replace('+', 'p').replace('-', 'm')}"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
type Align = Literal[
|
|
59
|
+
"center",
|
|
60
|
+
"north",
|
|
61
|
+
"south",
|
|
62
|
+
"east",
|
|
63
|
+
"west",
|
|
64
|
+
"northeast",
|
|
65
|
+
"northwest",
|
|
66
|
+
"southeast",
|
|
67
|
+
"southwest",
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
# Which point of a slot's box sits on its anchor, as fractions of (width, height).
|
|
71
|
+
_ALIGN: dict[str, tuple[float, float]] = {
|
|
72
|
+
"center": (0.5, 0.5),
|
|
73
|
+
"north": (0.5, 0.0),
|
|
74
|
+
"south": (0.5, 1.0),
|
|
75
|
+
"east": (1.0, 0.5),
|
|
76
|
+
"west": (0.0, 0.5),
|
|
77
|
+
"northeast": (1.0, 0.0),
|
|
78
|
+
"northwest": (0.0, 0.0),
|
|
79
|
+
"southeast": (1.0, 1.0),
|
|
80
|
+
"southwest": (0.0, 1.0),
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _runs(visible: list[bool]) -> list[tuple[int, int]]:
|
|
85
|
+
"""Maximal runs of consecutive ``True`` entries in a cyclic sequence.
|
|
86
|
+
|
|
87
|
+
Each run is ``(start, count)``; a run may wrap past the end. A sequence
|
|
88
|
+
that is ``True`` throughout is one run starting at ``0``.
|
|
89
|
+
"""
|
|
90
|
+
n = len(visible)
|
|
91
|
+
if all(visible):
|
|
92
|
+
return [(0, n)] if n else []
|
|
93
|
+
# Start scanning just after a False entry, so no run is split by the wrap.
|
|
94
|
+
first = next(i for i in range(n) if not visible[i]) + 1
|
|
95
|
+
runs: list[tuple[int, int]] = []
|
|
96
|
+
count = 0
|
|
97
|
+
for k in range(n):
|
|
98
|
+
i = (first + k) % n
|
|
99
|
+
if visible[i]:
|
|
100
|
+
count += 1
|
|
101
|
+
elif count:
|
|
102
|
+
runs.append(((i - count) % n, count))
|
|
103
|
+
count = 0
|
|
104
|
+
if count:
|
|
105
|
+
runs.append(((first + n - count) % n, count))
|
|
106
|
+
return runs
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _parallel(cam: Camera, what: str) -> ParallelCamera:
|
|
110
|
+
"""``cam`` as a :class:`ParallelCamera`, or a clear error naming ``what`` needs it."""
|
|
111
|
+
if not isinstance(cam, ParallelCamera):
|
|
112
|
+
raise TypeError(
|
|
113
|
+
f"{type(cam).__name__} cannot {what}: it needs the affine map only a "
|
|
114
|
+
"parallel projection has"
|
|
115
|
+
)
|
|
116
|
+
return cam
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _num(x: float, ndigits: int = 2) -> float:
|
|
120
|
+
"""``x`` rounded for emission, with the ``-0.0`` rounding can produce made ``0.0``."""
|
|
121
|
+
return round(float(x), ndigits) + 0.0
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _path(runs: Iterable[Array], *, closed: bool = False) -> list[svg.PathData]:
|
|
125
|
+
"""Path commands tracing each run of screen points as its own subpath."""
|
|
126
|
+
commands: list[svg.PathData] = []
|
|
127
|
+
for run in runs:
|
|
128
|
+
first, *rest = _points(run)
|
|
129
|
+
commands.append(svg.M(first.x, first.y))
|
|
130
|
+
commands += [svg.L(p.x, p.y) for p in rest]
|
|
131
|
+
if closed:
|
|
132
|
+
commands.append(svg.Z())
|
|
133
|
+
return commands
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _ellipse_axes(axes: Array) -> tuple[float, float, float, Array]:
|
|
137
|
+
"""Semi-axes, rotation in degrees, and major direction of ``axes @ (cos t, sin t)``.
|
|
138
|
+
|
|
139
|
+
The rotation is folded into ``(-90, 90]``, so the same ellipse always
|
|
140
|
+
gets the same attributes.
|
|
141
|
+
"""
|
|
142
|
+
u, s, _ = np.linalg.svd(axes)
|
|
143
|
+
major: Array = u[:, 0]
|
|
144
|
+
angle = math.degrees(math.atan2(float(major[1]), float(major[0])))
|
|
145
|
+
if angle > 90.0:
|
|
146
|
+
angle, major = angle - 180.0, -major
|
|
147
|
+
elif angle <= -90.0:
|
|
148
|
+
angle, major = angle + 180.0, -major
|
|
149
|
+
return float(s[0]), float(s[1]), angle, major
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _ellipse_element(center: Array, axes: Array, **style: Style) -> svg.Element:
|
|
153
|
+
"""The ellipse ``center + axes @ (cos t, sin t)`` as a native SVG shape.
|
|
154
|
+
|
|
155
|
+
A ``<circle>`` when the semi-axes agree -- a sphere, or a face-on disk,
|
|
156
|
+
under an orthographic camera -- and a rotated ``<ellipse>`` otherwise, so
|
|
157
|
+
the result stays a shape Inkscape edits as one rather than a path.
|
|
158
|
+
"""
|
|
159
|
+
rx, ry, angle, _ = _ellipse_axes(axes)
|
|
160
|
+
cx, cy = _num(center[0]), _num(center[1])
|
|
161
|
+
if abs(rx - ry) <= 1e-9 * max(rx, 1.0):
|
|
162
|
+
return svg.Circle(cx=cx, cy=cy, r=_num(rx, 3), **style)
|
|
163
|
+
rotation = _num(angle, 3)
|
|
164
|
+
transform: list[svg.Transform] | None = [svg.Rotate(rotation, cx, cy)] if rotation else None
|
|
165
|
+
return svg.Ellipse(cx=cx, cy=cy, rx=_num(rx, 3), ry=_num(ry, 3), transform=transform, **style)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _ball_axes(cam: ParallelCamera, radius: float) -> Array:
|
|
169
|
+
"""Axes of the ellipse a ball of ``radius`` projects to: ``radius * sqrt(S S^T)``.
|
|
170
|
+
|
|
171
|
+
``S`` is the camera's linear map, so this is exact for any parallel
|
|
172
|
+
projection. The square root is the symmetric one, so the result is a
|
|
173
|
+
valid ``axes`` for :func:`_ellipse_element`.
|
|
174
|
+
"""
|
|
175
|
+
u, s, _ = np.linalg.svd(cam.matrix * cam.scale)
|
|
176
|
+
axes: Array = radius * (u * s) @ u.T
|
|
177
|
+
return axes
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _frustum_outline(
|
|
181
|
+
c0: Array,
|
|
182
|
+
c1: Array,
|
|
183
|
+
axes: Array,
|
|
184
|
+
r0: float,
|
|
185
|
+
r1: float,
|
|
186
|
+
*,
|
|
187
|
+
closed: bool = True,
|
|
188
|
+
arcs: tuple[bool, bool] = (True, True),
|
|
189
|
+
) -> list[svg.PathData]:
|
|
190
|
+
"""Exact outline of a projected frustum: two tangent lines and two elliptical arcs.
|
|
191
|
+
|
|
192
|
+
Under a parallel projection the two end circles become the homothetic
|
|
193
|
+
ellipses ``c_k + r_k * axes @ (cos t, sin t)``, and the solid's outline is
|
|
194
|
+
their convex hull. Mapping the screen back through ``axes`` turns both
|
|
195
|
+
ellipses into circles, where the outer common tangents have a closed form;
|
|
196
|
+
mapping the tangent points forward again gives the outline, with each
|
|
197
|
+
curved side as one SVG arc rather than a polyline. ``r1 = 0`` is a cone.
|
|
198
|
+
|
|
199
|
+
With ``closed=False`` the result is for stroking only: the two sides, and
|
|
200
|
+
the end arcs that ``arcs`` asks for. That is how a sliced cylinder strokes
|
|
201
|
+
its silhouette without a line across every joint. The degenerate views
|
|
202
|
+
fall back to the closed outline.
|
|
203
|
+
"""
|
|
204
|
+
rx, ry, angle, major = _ellipse_axes(axes)
|
|
205
|
+
det = float(np.linalg.det(axes))
|
|
206
|
+
if abs(det) <= 1e-9 * rx * rx:
|
|
207
|
+
# The end circles are seen edge-on and project to segments.
|
|
208
|
+
ends = np.array(
|
|
209
|
+
[c0 + r0 * rx * major, c0 - r0 * rx * major, c1 + r1 * rx * major, c1 - r1 * rx * major]
|
|
210
|
+
)
|
|
211
|
+
return _path([ends[convex_hull(ends)]], closed=True)
|
|
212
|
+
|
|
213
|
+
def at(c: Array, r: float, phi: float) -> svg.Point:
|
|
214
|
+
x, y = c + r * (axes @ np.array([math.cos(phi), math.sin(phi)]))
|
|
215
|
+
return svg.Point(_num(x), _num(y))
|
|
216
|
+
|
|
217
|
+
def arc(r: float, large: bool, sweep: bool, end: svg.Point) -> svg.Arc:
|
|
218
|
+
return svg.Arc(_num(rx * r, 3), _num(ry * r, 3), _num(angle, 3), large, sweep, end.x, end.y)
|
|
219
|
+
|
|
220
|
+
d = np.linalg.solve(axes, c1 - c0)
|
|
221
|
+
dist = float(np.linalg.norm(d))
|
|
222
|
+
if dist <= abs(r0 - r1) * (1.0 + 1e-12):
|
|
223
|
+
# Seen down the axis: the larger end covers everything else.
|
|
224
|
+
c, r = (c0, r0) if r0 >= r1 else (c1, r1)
|
|
225
|
+
p, q = at(c, r, 0.0), at(c, r, math.pi)
|
|
226
|
+
return [svg.M(p.x, p.y), arc(r, False, True, q), arc(r, False, True, p), svg.Z()]
|
|
227
|
+
theta = math.atan2(float(d[1]), float(d[0]))
|
|
228
|
+
alpha = math.acos(min(max((r0 - r1) / dist, -1.0), 1.0))
|
|
229
|
+
# Both arcs run toward decreasing parameter angle, which is SVG's positive
|
|
230
|
+
# sweep exactly when `axes` reverses orientation.
|
|
231
|
+
sweep = det < 0
|
|
232
|
+
start, back = at(c0, r0, theta + alpha), at(c0, r0, theta - alpha)
|
|
233
|
+
if r1 > 0:
|
|
234
|
+
near, far = at(c1, r1, theta + alpha), at(c1, r1, theta - alpha)
|
|
235
|
+
else:
|
|
236
|
+
near = far = svg.Point(_num(c1[0]), _num(c1[1]))
|
|
237
|
+
far_arc = arc(r1, 2 * alpha > math.pi, sweep, far)
|
|
238
|
+
near_arc = arc(r0, 2 * alpha < math.pi, sweep, start)
|
|
239
|
+
commands: list[svg.PathData] = [svg.M(start.x, start.y), svg.L(near.x, near.y)]
|
|
240
|
+
if closed:
|
|
241
|
+
if r1 > 0:
|
|
242
|
+
commands.append(far_arc)
|
|
243
|
+
return [*commands, svg.L(back.x, back.y), near_arc, svg.Z()]
|
|
244
|
+
commands.append(far_arc if arcs[1] and r1 > 0 else svg.M(far.x, far.y))
|
|
245
|
+
commands.append(svg.L(back.x, back.y))
|
|
246
|
+
if arcs[0]:
|
|
247
|
+
commands.append(near_arc)
|
|
248
|
+
return commands
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
type TextContent = str | Sequence[svg.TSpan]
|
|
252
|
+
"""A label: plain text, or ``svg.TSpan`` runs for subscripts and mixed styles."""
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _text_length(s: TextContent) -> int:
|
|
256
|
+
"""Characters in a label, for the nominal-width bounding-box estimate."""
|
|
257
|
+
return len(s) if isinstance(s, str) else sum(len(run.text or "") for run in s)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _frustum_faces(a: Array, b: Array, r0: float, r1: float, n: int = 32) -> list[Face]:
|
|
261
|
+
"""A frustum as a convex polyhedron circumscribing it, for occlusion only.
|
|
262
|
+
|
|
263
|
+
Circumscribed rather than inscribed, so the facets cover the exact outline
|
|
264
|
+
that is drawn rather than falling a sliver short of it.
|
|
265
|
+
"""
|
|
266
|
+
axis = b - a
|
|
267
|
+
along = unit(axis)
|
|
268
|
+
e1, e2 = basis_for(axis)
|
|
269
|
+
t = np.linspace(0.0, 2.0 * np.pi, n, endpoint=False)
|
|
270
|
+
grow = 1.0 / math.cos(math.pi / n)
|
|
271
|
+
ring = grow * (np.outer(np.cos(t), e1) + np.outer(np.sin(t), e2))
|
|
272
|
+
bottom, top = a + r0 * ring, b + r1 * ring
|
|
273
|
+
length = float(np.linalg.norm(axis))
|
|
274
|
+
faces: list[Face] = []
|
|
275
|
+
for i in range(n):
|
|
276
|
+
j = (i + 1) % n
|
|
277
|
+
radial = unit(ring[i] + ring[j])
|
|
278
|
+
normal = unit(radial * length + along * (r0 - r1))
|
|
279
|
+
faces.append(Face(f"side-{i}", np.array([bottom[i], bottom[j], top[j], top[i]]), normal))
|
|
280
|
+
faces.append(Face("-axis", bottom[::-1].copy(), -along))
|
|
281
|
+
if r1 > 0:
|
|
282
|
+
faces.append(Face("+axis", top.copy(), along))
|
|
283
|
+
return faces
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _spanning(points: Array) -> Array:
|
|
287
|
+
"""Three corners of a planar polygon that span it as widely as its first edge allows."""
|
|
288
|
+
first, second = points[0], points[1]
|
|
289
|
+
if not np.any(second != first):
|
|
290
|
+
second = points[2]
|
|
291
|
+
away = np.linalg.norm(np.cross(second - first, points - first), axis=1)
|
|
292
|
+
return np.array([first, second, points[int(np.argmax(away))]])
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _coverage(style: Mapping[str, Style]) -> tuple[bool, float]:
|
|
296
|
+
"""Whether a style hides what is behind it, and half its stroke width."""
|
|
297
|
+
|
|
298
|
+
def amount(key: str) -> float:
|
|
299
|
+
value = style.get(key, 1.0)
|
|
300
|
+
return float(value) if isinstance(value, int | float) else 1.0
|
|
301
|
+
|
|
302
|
+
opaque = style.get("fill") != "none" and amount("opacity") >= 1 and amount("fill_opacity") >= 1
|
|
303
|
+
stroked = style.get("stroke") not in (None, "none")
|
|
304
|
+
return opaque, 0.5 * amount("stroke_width") if stroked else 0.0
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _named(base: str | None, suffix: str) -> dict[str, Style]:
|
|
308
|
+
"""``{"id": "{base}-{suffix}"}``, or nothing when there is no base id."""
|
|
309
|
+
return {} if base is None else {"id": f"{base}-{suffix}"}
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _slug(color: str) -> str:
|
|
313
|
+
"""A colour reduced to characters that are safe in an XML id."""
|
|
314
|
+
return re.sub(r"[^0-9A-Za-z]+", "", color).lower() or "c"
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
DEFAULT_FONT = "DejaVu Sans, Verdana, sans-serif"
|
|
318
|
+
DEFAULT_TEXT_FILL = "#222222"
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _check_highlight(style: Mapping[str, Style], highlight: str | None, *, needs_id: bool) -> None:
|
|
322
|
+
"""Reject a ``highlight`` that has no fill to shade toward, or no id to name it by."""
|
|
323
|
+
if highlight is None:
|
|
324
|
+
return
|
|
325
|
+
if not isinstance(style.get("fill"), str):
|
|
326
|
+
raise ValueError("highlight needs a fill colour to shade toward")
|
|
327
|
+
if needs_id and style.get("id") is None:
|
|
328
|
+
raise ValueError("highlight needs an id to name the gradient")
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _check_axis(p0: Point3, p1: Point3, r0: float, r1: float) -> None:
|
|
332
|
+
"""Reject a solid of revolution with no axis or a negative radius."""
|
|
333
|
+
if r0 <= 0 or r1 < 0:
|
|
334
|
+
raise ValueError(f"need r0 > 0 and r1 >= 0, got r0={r0}, r1={r1}")
|
|
335
|
+
if np.array_equal(np.asarray(p0, dtype=np.float64), np.asarray(p1, dtype=np.float64)):
|
|
336
|
+
raise ValueError("the two ends coincide, so the solid has no axis")
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
class _Canvas:
|
|
340
|
+
"""One projection of a scene: its recorded calls replayed against a camera.
|
|
341
|
+
|
|
342
|
+
Every method with a public name implements the :class:`Scene` method of the
|
|
343
|
+
same name, which documents it. A canvas is built, filled, and turned into a
|
|
344
|
+
document by :meth:`Scene.render`, and never escapes it.
|
|
345
|
+
"""
|
|
346
|
+
|
|
347
|
+
def __init__(self, cam: Camera) -> None:
|
|
348
|
+
self.cam = cam
|
|
349
|
+
self.items: list[tuple[int, int, svg.Element]] = []
|
|
350
|
+
self.defs: list[svg.Element] = []
|
|
351
|
+
self._seq = 0
|
|
352
|
+
self._lo: Array = np.array([np.inf, np.inf])
|
|
353
|
+
self._hi: Array = np.array([-np.inf, -np.inf])
|
|
354
|
+
self._depths: dict[int, float] = {}
|
|
355
|
+
self._sorted: set[int] = set()
|
|
356
|
+
self._exact: set[int] = set()
|
|
357
|
+
self._shapes: dict[int, Callable[[], Shape | None]] = {}
|
|
358
|
+
self._opaque: set[int] = set()
|
|
359
|
+
self._rank: dict[int, int] = {}
|
|
360
|
+
self._shared: set[str] = set()
|
|
361
|
+
|
|
362
|
+
@property
|
|
363
|
+
def is_empty(self) -> bool:
|
|
364
|
+
return not bool(np.all(np.isfinite(self._lo)))
|
|
365
|
+
|
|
366
|
+
def bbox(self) -> tuple[Array, Array]:
|
|
367
|
+
return self._lo.copy(), self._hi.copy()
|
|
368
|
+
|
|
369
|
+
def document(self, pad: float, background: str | None) -> svg.SVG:
|
|
370
|
+
"""Assemble the document, fitting the viewBox to the content plus ``pad``."""
|
|
371
|
+
if self.is_empty:
|
|
372
|
+
raise ValueError("cannot render an empty scene: no geometry to fit a viewBox to")
|
|
373
|
+
if self._exact:
|
|
374
|
+
self._occlude()
|
|
375
|
+
lo, hi = self._lo - pad, self._hi + pad
|
|
376
|
+
w, h = hi - lo
|
|
377
|
+
elements: list[svg.Element] = []
|
|
378
|
+
if self.defs:
|
|
379
|
+
elements.append(svg.Defs(elements=list(self.defs)))
|
|
380
|
+
if background:
|
|
381
|
+
elements.append(svg.Rect(x=lo[0], y=lo[1], width=w, height=h, fill=background))
|
|
382
|
+
elements += [el for _, _, el in sorted(self.items, key=self._order)]
|
|
383
|
+
return svg.SVG(
|
|
384
|
+
width=round(w, 1),
|
|
385
|
+
height=round(h, 1),
|
|
386
|
+
viewBox=svg.ViewBoxSpec(round(lo[0], 1), round(lo[1], 1), round(w, 1), round(h, 1)),
|
|
387
|
+
elements=elements,
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
def _grow(self, pts2: np.ndarray) -> None:
|
|
391
|
+
p = np.atleast_2d(pts2)
|
|
392
|
+
self._lo = np.minimum(self._lo, p.min(axis=0))
|
|
393
|
+
self._hi = np.maximum(self._hi, p.max(axis=0))
|
|
394
|
+
|
|
395
|
+
def _emit(self, layer: int, element: svg.Element, depth: float | None = None) -> None:
|
|
396
|
+
"""Queue an element at ``layer`` without logging it.
|
|
397
|
+
|
|
398
|
+
``depth`` is what a layer passed to :meth:`sort_by_depth` orders by. It
|
|
399
|
+
is rounded so that equal depths tie exactly and fall back to insertion
|
|
400
|
+
order, rather than to the last bits of a floating-point sum.
|
|
401
|
+
"""
|
|
402
|
+
if depth is not None:
|
|
403
|
+
self._depths[self._seq] = _num(depth, 6)
|
|
404
|
+
self.items.append((int(layer), self._seq, element))
|
|
405
|
+
self._seq += 1
|
|
406
|
+
|
|
407
|
+
def _depth(self, pts3: Points3) -> float:
|
|
408
|
+
"""Mean depth of world points: the key one element sorts by."""
|
|
409
|
+
return float(np.mean(self.cam.depth(pts3)))
|
|
410
|
+
|
|
411
|
+
def sort_by_depth(self, layer: int, *, exact: bool = False) -> None:
|
|
412
|
+
"""Order ``layer`` back to front by depth instead of by insertion."""
|
|
413
|
+
self._sorted.add(int(layer))
|
|
414
|
+
if exact:
|
|
415
|
+
self._exact.add(int(layer))
|
|
416
|
+
|
|
417
|
+
# --- occlusion --------------------------------------------------------
|
|
418
|
+
def _shape(self, build: Callable[[], Shape | None]) -> None:
|
|
419
|
+
"""Describe the element just emitted, for an exact layer to resolve.
|
|
420
|
+
|
|
421
|
+
Kept as a thunk: only the layers that ask for exact visibility pay for
|
|
422
|
+
building the shapes.
|
|
423
|
+
"""
|
|
424
|
+
self._shapes[self._seq - 1] = build
|
|
425
|
+
|
|
426
|
+
def _planar_piece(self, pts3: Points3) -> Piece | None:
|
|
427
|
+
pts = as_points(pts3)
|
|
428
|
+
screen = self.cam.project(pts)
|
|
429
|
+
plane = plane_through(screen, self.cam.depth(pts))
|
|
430
|
+
return None if plane is None else Piece(screen, planar_depth(plane), plane)
|
|
431
|
+
|
|
432
|
+
def _convex_piece(self, faces: Sequence[Face]) -> Piece | None:
|
|
433
|
+
"""A convex solid: depth is the nearest of its front faces' planes."""
|
|
434
|
+
cam = _parallel(self.cam, "resolve occlusion")
|
|
435
|
+
screen = cam.project(np.vstack([face.points for face in faces]))
|
|
436
|
+
# A plane per face, from three corners that span it -- which survives a
|
|
437
|
+
# quad collapsed to a triangle at a cone's apex.
|
|
438
|
+
corners = np.array([_spanning(face.points) for face in faces])
|
|
439
|
+
flat = corners.reshape(-1, 3)
|
|
440
|
+
planes = planes_through(cam.project(flat).reshape(-1, 3, 2), cam.depth(flat).reshape(-1, 3))
|
|
441
|
+
front: list[Plane] = []
|
|
442
|
+
rear: list[Plane] = []
|
|
443
|
+
for face, plane in zip(faces, planes, strict=True):
|
|
444
|
+
if plane is not None:
|
|
445
|
+
(front if cam.faces_camera(face.normal) else rear).append(plane)
|
|
446
|
+
if not front:
|
|
447
|
+
return None
|
|
448
|
+
near, far = np.array(front), np.array(rear) if rear else np.zeros((0, 3))
|
|
449
|
+
size = float(np.ptp(screen, axis=0).max()) or 1.0
|
|
450
|
+
|
|
451
|
+
def depth(xy: Array) -> Array:
|
|
452
|
+
# A ray enters a convex solid through the last front plane it
|
|
453
|
+
# crosses; past the solid's edge that plane goes on smoothly.
|
|
454
|
+
out: Array = (xy @ near[:, :2].T + near[:, 2]).min(axis=1)
|
|
455
|
+
return out
|
|
456
|
+
|
|
457
|
+
def covers(xy: Array) -> Any:
|
|
458
|
+
# ... and leaves through the first back plane: a miss if that comes first.
|
|
459
|
+
exit_ = (xy @ far[:, :2].T + far[:, 2]).max(axis=1)
|
|
460
|
+
return depth(xy) >= exit_ - 1e-9 * size
|
|
461
|
+
|
|
462
|
+
outline = screen[convex_hull(screen)]
|
|
463
|
+
return Piece(outline, depth, None, covers if len(far) else None)
|
|
464
|
+
|
|
465
|
+
def _grown(self, pad: float) -> float:
|
|
466
|
+
"""A stroke's half-width in world units, by which a solid's depth is grown.
|
|
467
|
+
|
|
468
|
+
Depth is then defined, and the solid in front, over the whole of its
|
|
469
|
+
drawn outline; otherwise whatever is behind would claim the stroke.
|
|
470
|
+
"""
|
|
471
|
+
return pad / self.cam.scale
|
|
472
|
+
|
|
473
|
+
def _sphere_piece(self, center: Point3, radius: float, pad: float = 0.0) -> Piece:
|
|
474
|
+
"""A sphere: the exact depth of its front surface along each ray."""
|
|
475
|
+
cam = _parallel(self.cam, "resolve occlusion")
|
|
476
|
+
c = np.asarray(center, dtype=np.float64)
|
|
477
|
+
radius += self._grown(pad)
|
|
478
|
+
n = 96
|
|
479
|
+
t = np.linspace(0.0, 2.0 * np.pi, n, endpoint=False)
|
|
480
|
+
ring = np.column_stack([np.cos(t), np.sin(t)]) / math.cos(math.pi / n)
|
|
481
|
+
outline = np.asarray(cam.at(c)) + ring @ _ball_axes(cam, radius).T
|
|
482
|
+
back = np.linalg.pinv(cam.matrix * cam.scale)
|
|
483
|
+
view = cam.view
|
|
484
|
+
|
|
485
|
+
def reach(xy: Array) -> tuple[Array, Array]:
|
|
486
|
+
base = cam.origin + xy @ back.T # on each ray
|
|
487
|
+
w = base - c
|
|
488
|
+
along = w @ view
|
|
489
|
+
return base @ view - along, along**2 - np.einsum("ij,ij->i", w, w) + radius**2
|
|
490
|
+
|
|
491
|
+
def depth(xy: Array) -> Array:
|
|
492
|
+
# Past the rim, the depth of the rim: the ray's closest approach.
|
|
493
|
+
mid, disc = reach(xy)
|
|
494
|
+
out: Array = mid + np.sqrt(np.maximum(disc, 0.0))
|
|
495
|
+
return out
|
|
496
|
+
|
|
497
|
+
def covers(xy: Array) -> Any:
|
|
498
|
+
return reach(xy)[1] >= 0
|
|
499
|
+
|
|
500
|
+
return Piece(outline, depth, covers=covers)
|
|
501
|
+
|
|
502
|
+
def _line(
|
|
503
|
+
self,
|
|
504
|
+
runs3: Sequence[Array],
|
|
505
|
+
style: Mapping[str, Style],
|
|
506
|
+
back: Mapping[str, Style] | None,
|
|
507
|
+
) -> Line:
|
|
508
|
+
"""A stroked shape: its runs with depths, and how to redraw it once split."""
|
|
509
|
+
runs = [(self.cam.project(run), self.cam.depth(run)) for run in runs3]
|
|
510
|
+
base = style.get("id")
|
|
511
|
+
|
|
512
|
+
def rebuild(visible: list[Array], hidden: list[Array]) -> list[svg.Element]:
|
|
513
|
+
out: list[svg.Element] = []
|
|
514
|
+
if visible:
|
|
515
|
+
out.append(svg.Path(d=_path(visible), **style))
|
|
516
|
+
if hidden and back is not None:
|
|
517
|
+
attrs: dict[str, Style] = {**style, **back}
|
|
518
|
+
if base is not None:
|
|
519
|
+
attrs["id"] = f"{base}-hidden"
|
|
520
|
+
out.append(svg.Path(d=_path(hidden), **attrs))
|
|
521
|
+
return out
|
|
522
|
+
|
|
523
|
+
return Line(runs, rebuild)
|
|
524
|
+
|
|
525
|
+
def _paint_order(
|
|
526
|
+
self, members: Sequence[tuple[int, Shape]], seen: Sequence[Visibility]
|
|
527
|
+
) -> None:
|
|
528
|
+
"""Order an exact layer's opaque surfaces so whatever hides another comes after it.
|
|
529
|
+
|
|
530
|
+
Clipped, opaque surfaces overlap only along their edges, and there the
|
|
531
|
+
one in front must be painted last. A topological sort of "hides part
|
|
532
|
+
of" gives that order; depth breaks ties, and a cycle -- planes that
|
|
533
|
+
cross -- falls back to depth for the surfaces caught in it.
|
|
534
|
+
"""
|
|
535
|
+
seqs = [seq for seq, _ in members]
|
|
536
|
+
after: dict[int, set[int]] = {seq: set() for seq in seqs}
|
|
537
|
+
for (seq, _), visibility in zip(members, seen, strict=True):
|
|
538
|
+
for other in visibility.hidden_by:
|
|
539
|
+
after[seq].add(seqs[other])
|
|
540
|
+
waiting = {seq: 0 for seq in seqs}
|
|
541
|
+
for seq in seqs:
|
|
542
|
+
for later in after[seq]:
|
|
543
|
+
waiting[later] += 1
|
|
544
|
+
|
|
545
|
+
def key(seq: int) -> tuple[float, int]:
|
|
546
|
+
return (self._depths.get(seq, 0.0), seq)
|
|
547
|
+
|
|
548
|
+
ready = sorted((seq for seq in seqs if waiting[seq] == 0), key=key)
|
|
549
|
+
left = set(seqs)
|
|
550
|
+
rank = len(self._rank)
|
|
551
|
+
while left:
|
|
552
|
+
if not ready:
|
|
553
|
+
ready = [min(left, key=key)] # a cycle: take the farthest
|
|
554
|
+
seq = ready.pop(0)
|
|
555
|
+
if seq not in left:
|
|
556
|
+
continue
|
|
557
|
+
left.discard(seq)
|
|
558
|
+
self._rank[seq] = rank
|
|
559
|
+
rank += 1
|
|
560
|
+
for later in sorted(after[seq], key=key):
|
|
561
|
+
waiting[later] -= 1
|
|
562
|
+
if waiting[later] == 0 and later in left:
|
|
563
|
+
ready.append(later)
|
|
564
|
+
ready.sort(key=key)
|
|
565
|
+
|
|
566
|
+
def _occlude(self) -> None:
|
|
567
|
+
"""Resolve every exact layer: clip surfaces to what shows, split lines."""
|
|
568
|
+
from vecview._occlusion import resolve
|
|
569
|
+
|
|
570
|
+
outcome: dict[int, tuple[Shape, Visibility]] = {}
|
|
571
|
+
for layer in sorted(self._exact):
|
|
572
|
+
seqs = [seq for at, seq, _ in self.items if at == layer and seq in self._shapes]
|
|
573
|
+
built = [(seq, self._shapes[seq]()) for seq in seqs]
|
|
574
|
+
members = [(seq, shape) for seq, shape in built if shape is not None]
|
|
575
|
+
seen_all = resolve([shape for _, shape in members])
|
|
576
|
+
for (seq, shape), seen in zip(members, seen_all, strict=True):
|
|
577
|
+
outcome[seq] = (shape, seen)
|
|
578
|
+
self._paint_order(members, seen_all)
|
|
579
|
+
items: list[tuple[int, int, svg.Element]] = []
|
|
580
|
+
for layer, seq, element in self.items:
|
|
581
|
+
if seq not in outcome:
|
|
582
|
+
items.append((layer, seq, element))
|
|
583
|
+
continue
|
|
584
|
+
shape, seen = outcome[seq]
|
|
585
|
+
if isinstance(shape, Surface):
|
|
586
|
+
if shape.opaque:
|
|
587
|
+
self._opaque.add(seq)
|
|
588
|
+
rings = seen.rings
|
|
589
|
+
if rings is None:
|
|
590
|
+
items.append((layer, seq, element))
|
|
591
|
+
elif rings:
|
|
592
|
+
name = getattr(element, "id", None)
|
|
593
|
+
clip = f"{name}-visible" if name else f"visible-{seq}"
|
|
594
|
+
region = svg.Path(d=_path(rings, closed=True), clip_rule="evenodd")
|
|
595
|
+
self.defs.append(svg.ClipPath(id=clip, elements=[region]))
|
|
596
|
+
element.clip_path = f"url(#{clip})" # ty: ignore[unresolved-attribute]
|
|
597
|
+
items.append((layer, seq, element))
|
|
598
|
+
elif seen.hidden:
|
|
599
|
+
rebuilt = shape.rebuild(seen.visible, seen.hidden)
|
|
600
|
+
items += [(layer, seq, part) for part in rebuilt]
|
|
601
|
+
else:
|
|
602
|
+
items.append((layer, seq, element))
|
|
603
|
+
self.items = items
|
|
604
|
+
|
|
605
|
+
def add(self, layer: int, element: svg.Element) -> None:
|
|
606
|
+
"""Add a ready-made ``svg.py`` element at ``layer``, bypassing projection."""
|
|
607
|
+
self._emit(layer, element)
|
|
608
|
+
|
|
609
|
+
def add_def(self, element: svg.Element) -> None:
|
|
610
|
+
"""Add an element to ``<defs>`` -- a gradient, marker, or clip path."""
|
|
611
|
+
self.defs.append(element)
|
|
612
|
+
|
|
613
|
+
def polygon(self, layer: int, pts3: Points3, **style: Style) -> None:
|
|
614
|
+
"""Filled polygon through projected world points."""
|
|
615
|
+
p = self.cam.project(pts3)
|
|
616
|
+
self._grow(p)
|
|
617
|
+
self._emit(layer, svg.Polygon(points=_points(p), **style), self._depth(pts3))
|
|
618
|
+
pts = as_points(pts3)
|
|
619
|
+
if style.get("fill") == "none":
|
|
620
|
+
self._shape(lambda: self._line([np.vstack([pts, pts[:1]])], style, None))
|
|
621
|
+
else:
|
|
622
|
+
opaque, pad = _coverage(style)
|
|
623
|
+
|
|
624
|
+
def surface() -> Surface | None:
|
|
625
|
+
piece = self._planar_piece(pts)
|
|
626
|
+
return None if piece is None else Surface([piece], opaque, pad)
|
|
627
|
+
|
|
628
|
+
self._shape(surface)
|
|
629
|
+
|
|
630
|
+
def polyline(
|
|
631
|
+
self, layer: int, pts3: Points3, *, back: Mapping[str, Style] | None = None, **style: Style
|
|
632
|
+
) -> None:
|
|
633
|
+
"""Open path through projected world points; unfilled unless asked."""
|
|
634
|
+
style.setdefault("fill", "none")
|
|
635
|
+
p = self.cam.project(pts3)
|
|
636
|
+
self._grow(p)
|
|
637
|
+
self._emit(layer, svg.Polyline(points=_points(p), **style), self._depth(pts3))
|
|
638
|
+
pts = as_points(pts3)
|
|
639
|
+
self._shape(lambda: self._line([pts], style, back))
|
|
640
|
+
|
|
641
|
+
def faces(
|
|
642
|
+
self, layer: int, faces: Iterable[Face], *, cull: bool = False, **style: Style
|
|
643
|
+
) -> None:
|
|
644
|
+
"""Draw each face as a polygon, all with the same style."""
|
|
645
|
+
base = style.pop("id", None)
|
|
646
|
+
given = list(faces)
|
|
647
|
+
drawn = self.cam.visible(given) if cull else given
|
|
648
|
+
for face in drawn:
|
|
649
|
+
if base is None:
|
|
650
|
+
self.polygon(layer, face.points, **style)
|
|
651
|
+
else:
|
|
652
|
+
self.polygon(layer, face.points, id=_face_id(str(base), face.name), **style)
|
|
653
|
+
|
|
654
|
+
def plane(
|
|
655
|
+
self,
|
|
656
|
+
layer: int,
|
|
657
|
+
origin: Point3,
|
|
658
|
+
u_edge: Point3,
|
|
659
|
+
v_edge: Point3,
|
|
660
|
+
*,
|
|
661
|
+
id: str,
|
|
662
|
+
**style: Style,
|
|
663
|
+
) -> None:
|
|
664
|
+
"""Reserve an empty group occupying a rectangle of a world plane."""
|
|
665
|
+
cam = _parallel(self.cam, "embed content in a plane")
|
|
666
|
+
matrix = cam.plane_matrix(origin, u_edge, v_edge)
|
|
667
|
+
o = np.asarray(origin, dtype=np.float64)
|
|
668
|
+
u = np.asarray(u_edge, dtype=np.float64)
|
|
669
|
+
v = np.asarray(v_edge, dtype=np.float64)
|
|
670
|
+
self._grow(self.cam.project([o, o + u, o + u + v, o + v]))
|
|
671
|
+
self._emit(
|
|
672
|
+
layer,
|
|
673
|
+
svg.G(
|
|
674
|
+
id=id,
|
|
675
|
+
transform=[svg.Matrix(*(round(value, 4) for value in matrix))],
|
|
676
|
+
**style,
|
|
677
|
+
),
|
|
678
|
+
self._depth([o + (u + v) / 2.0]),
|
|
679
|
+
)
|
|
680
|
+
|
|
681
|
+
def slot(
|
|
682
|
+
self,
|
|
683
|
+
layer: int,
|
|
684
|
+
pt3: Point3,
|
|
685
|
+
w: float,
|
|
686
|
+
h: float,
|
|
687
|
+
*,
|
|
688
|
+
id: str,
|
|
689
|
+
align: Align = "center",
|
|
690
|
+
dx: float = 0.0,
|
|
691
|
+
dy: float = 0.0,
|
|
692
|
+
**style: Style,
|
|
693
|
+
) -> None:
|
|
694
|
+
"""Reserve an empty, screen-aligned group anchored at a projected world point."""
|
|
695
|
+
if align not in _ALIGN:
|
|
696
|
+
raise ValueError(f"unknown align {align!r}; expected one of {sorted(_ALIGN)}")
|
|
697
|
+
x, y = self.cam.at(pt3)
|
|
698
|
+
x, y = x + dx, y + dy
|
|
699
|
+
fx, fy = _ALIGN[align]
|
|
700
|
+
x0, y0 = x - fx * w, y - fy * h
|
|
701
|
+
self._grow(np.array([[x0, y0], [x0 + w, y0 + h]]))
|
|
702
|
+
self._emit(
|
|
703
|
+
layer,
|
|
704
|
+
svg.G(
|
|
705
|
+
id=id,
|
|
706
|
+
transform=[svg.Translate(round(x, 2), round(y, 2))],
|
|
707
|
+
data={"align": align},
|
|
708
|
+
**style,
|
|
709
|
+
),
|
|
710
|
+
self._depth([pt3]),
|
|
711
|
+
)
|
|
712
|
+
|
|
713
|
+
def silhouette(self, layer: int, solid: Iterable[Face] | Points3, **style: Style) -> None:
|
|
714
|
+
"""Fill the projected outline of a convex solid as one polygon."""
|
|
715
|
+
given = list(solid)
|
|
716
|
+
if given and isinstance(given[0], Face):
|
|
717
|
+
pts = np.vstack([face.points for face in given if isinstance(face, Face)])
|
|
718
|
+
else:
|
|
719
|
+
pts = as_points(cast(Points3, given))
|
|
720
|
+
p = self.cam.project(pts)
|
|
721
|
+
outline = p[convex_hull(p)]
|
|
722
|
+
self._grow(outline)
|
|
723
|
+
self._emit(layer, svg.Polygon(points=_points(outline), **style), self._depth(pts))
|
|
724
|
+
solid = [face for face in given if isinstance(face, Face)]
|
|
725
|
+
if solid:
|
|
726
|
+
opaque, pad = _coverage(style)
|
|
727
|
+
|
|
728
|
+
def surface() -> Surface | None:
|
|
729
|
+
piece = self._convex_piece(solid)
|
|
730
|
+
return None if piece is None else Surface([piece], opaque, pad)
|
|
731
|
+
|
|
732
|
+
self._shape(surface)
|
|
733
|
+
|
|
734
|
+
def prism_walls(
|
|
735
|
+
self, layer: int, footprint: Points2, z0: float, z1: float, **style: Style
|
|
736
|
+
) -> None:
|
|
737
|
+
"""Draw the camera-facing walls of an extruded footprint as one seamless shape."""
|
|
738
|
+
walls = prism_faces(footprint, z0, z1)[2:]
|
|
739
|
+
facing = {id(face) for face in self.cam.visible(walls)}
|
|
740
|
+
runs = _runs([id(face) in facing for face in walls])
|
|
741
|
+
if not runs:
|
|
742
|
+
return
|
|
743
|
+
n = len(walls)
|
|
744
|
+
outlines: list[Array] = []
|
|
745
|
+
for start, count in runs:
|
|
746
|
+
indices = [(start + k) % n for k in range(count)]
|
|
747
|
+
bottom = [walls[i].points[0] for i in indices] + [walls[indices[-1]].points[1]]
|
|
748
|
+
top = [walls[indices[-1]].points[2]] + [walls[i].points[3] for i in reversed(indices)]
|
|
749
|
+
outlines.append(self.cam.project(np.array(bottom + top)))
|
|
750
|
+
self._grow(outlines[-1])
|
|
751
|
+
depth = self._depth(np.vstack([wall.points for wall in walls]))
|
|
752
|
+
self._emit(layer, svg.Path(d=_path(outlines, closed=True), **style), depth)
|
|
753
|
+
shown = [wall for wall in walls if id(wall) in facing]
|
|
754
|
+
opaque, pad = _coverage(style)
|
|
755
|
+
|
|
756
|
+
def surface() -> Surface | None:
|
|
757
|
+
pieces = [piece for wall in shown if (piece := self._planar_piece(wall.points))]
|
|
758
|
+
return Surface(pieces, opaque, pad) if pieces else None
|
|
759
|
+
|
|
760
|
+
self._shape(surface)
|
|
761
|
+
|
|
762
|
+
def arrow(
|
|
763
|
+
self,
|
|
764
|
+
layer: int,
|
|
765
|
+
origin: Point3,
|
|
766
|
+
direction: Point3,
|
|
767
|
+
length: float,
|
|
768
|
+
*,
|
|
769
|
+
normal: Point3 | Literal["camera"],
|
|
770
|
+
shaft_w: float,
|
|
771
|
+
head_w: float,
|
|
772
|
+
head_len: float,
|
|
773
|
+
pivot: Pivot = "tail",
|
|
774
|
+
**style: Style,
|
|
775
|
+
) -> None:
|
|
776
|
+
"""Flat arrow, as :func:`~vecview.shapes.arrow_shape`, drawn as a polygon."""
|
|
777
|
+
if isinstance(normal, str):
|
|
778
|
+
if normal != "camera":
|
|
779
|
+
raise ValueError(f"normal must be a vector or 'camera', got {normal!r}")
|
|
780
|
+
normal = self._facing_normal(direction)
|
|
781
|
+
shape = arrow_shape(origin, direction, length, normal, shaft_w, head_w, head_len, pivot)
|
|
782
|
+
self.polygon(layer, shape, **style)
|
|
783
|
+
|
|
784
|
+
def _facing_normal(self, direction: Point3) -> Array:
|
|
785
|
+
"""Normal of the plane through ``direction`` that shows the widest arrow.
|
|
786
|
+
|
|
787
|
+
The arrow's width runs along some ``s`` perpendicular to its axis; this
|
|
788
|
+
picks the ``s`` whose screen projection is longest -- the top singular
|
|
789
|
+
vector of the camera matrix restricted to that perpendicular plane. For
|
|
790
|
+
an orthographic camera that is the plane facing the viewer; for an
|
|
791
|
+
oblique one, ``view`` would give a narrower arrow, so it is not used.
|
|
792
|
+
"""
|
|
793
|
+
cam = _parallel(self.cam, "face an arrow toward the camera")
|
|
794
|
+
d = unit(direction)
|
|
795
|
+
if float(np.linalg.norm(cam.matrix @ d)) < 1e-9:
|
|
796
|
+
raise ValueError(
|
|
797
|
+
"arrow points along the projection ray, so no plane through it faces the camera"
|
|
798
|
+
)
|
|
799
|
+
e1, e2 = basis_for(d)
|
|
800
|
+
_, _, vt = np.linalg.svd(cam.matrix @ np.column_stack([e1, e2]))
|
|
801
|
+
width = vt[0, 0] * e1 + vt[0, 1] * e2
|
|
802
|
+
n = unit(np.cross(d, width))
|
|
803
|
+
return n if float(np.dot(n, cam.view)) >= 0 else -n
|
|
804
|
+
|
|
805
|
+
def gaussian(
|
|
806
|
+
self,
|
|
807
|
+
layer: int,
|
|
808
|
+
center: Point3,
|
|
809
|
+
u: Point3,
|
|
810
|
+
v: Point3,
|
|
811
|
+
a: float,
|
|
812
|
+
b: float,
|
|
813
|
+
*,
|
|
814
|
+
id: str,
|
|
815
|
+
color: str,
|
|
816
|
+
opacity: float = 1.0,
|
|
817
|
+
extent: float = 2.0,
|
|
818
|
+
stops: int = 9,
|
|
819
|
+
**style: Style,
|
|
820
|
+
) -> None:
|
|
821
|
+
"""A soft Gaussian spot lying in a world plane, as one gradient-filled polygon."""
|
|
822
|
+
cam = _parallel(self.cam, "map a gradient through a plane")
|
|
823
|
+
if stops < 2:
|
|
824
|
+
raise ValueError("a gradient needs at least two stops")
|
|
825
|
+
# Gradient coordinates (s, t) in units of the half-widths, mapped onto the plane.
|
|
826
|
+
matrix = cam.plane_matrix(center, a * unit(u), b * unit(v))
|
|
827
|
+
floor = np.exp(-(extent**2))
|
|
828
|
+
profile: list[svg.Element] = [
|
|
829
|
+
svg.Stop(
|
|
830
|
+
offset=round(k / (stops - 1), 4),
|
|
831
|
+
stop_color=color,
|
|
832
|
+
stop_opacity=round(
|
|
833
|
+
opacity * (np.exp(-((extent * k / (stops - 1)) ** 2)) - floor) / (1 - floor), 4
|
|
834
|
+
),
|
|
835
|
+
)
|
|
836
|
+
for k in range(stops)
|
|
837
|
+
]
|
|
838
|
+
self.defs.append(
|
|
839
|
+
svg.RadialGradient(
|
|
840
|
+
id=f"{id}-profile",
|
|
841
|
+
gradientUnits="userSpaceOnUse",
|
|
842
|
+
gradientTransform=[svg.Matrix(*(round(value, 4) for value in matrix))],
|
|
843
|
+
cx=0,
|
|
844
|
+
cy=0,
|
|
845
|
+
r=extent,
|
|
846
|
+
elements=profile,
|
|
847
|
+
)
|
|
848
|
+
)
|
|
849
|
+
outline = ellipse_shape(center, u, v, a * extent, b * extent)
|
|
850
|
+
self.polygon(layer, outline, fill=f"url(#{id}-profile)", id=id, **style)
|
|
851
|
+
# A soft spot fades to nothing, so it hides nothing behind it.
|
|
852
|
+
build = self._shapes[self._seq - 1]
|
|
853
|
+
|
|
854
|
+
def translucent() -> Shape | None:
|
|
855
|
+
shape = build()
|
|
856
|
+
return dataclasses.replace(shape, opaque=False) if isinstance(shape, Surface) else shape
|
|
857
|
+
|
|
858
|
+
self._shape(translucent)
|
|
859
|
+
|
|
860
|
+
def sphere(
|
|
861
|
+
self,
|
|
862
|
+
layer: int,
|
|
863
|
+
center: Point3,
|
|
864
|
+
radius: float,
|
|
865
|
+
*,
|
|
866
|
+
highlight: str | None = None,
|
|
867
|
+
**style: Style,
|
|
868
|
+
) -> None:
|
|
869
|
+
"""A sphere, drawn as its exact outline: one ``<circle>`` or ``<ellipse>``."""
|
|
870
|
+
cam = _parallel(self.cam, "outline a sphere")
|
|
871
|
+
c = np.asarray(self.cam.at(center))
|
|
872
|
+
axes = _ball_axes(cam, radius)
|
|
873
|
+
if highlight is not None:
|
|
874
|
+
style["fill"] = self._ball_gradient(style, highlight)
|
|
875
|
+
reach = np.linalg.norm(axes, axis=1)
|
|
876
|
+
self._grow(np.array([c - reach, c + reach]))
|
|
877
|
+
self._emit(layer, _ellipse_element(c, axes, **style), self._depth([center]))
|
|
878
|
+
opaque, pad = _coverage(style)
|
|
879
|
+
self._shape(lambda: Surface([self._sphere_piece(center, radius, pad)], opaque, pad))
|
|
880
|
+
|
|
881
|
+
def _ball_gradient(self, style: Mapping[str, Style], highlight: str) -> str:
|
|
882
|
+
"""Add (once) the radial gradient shared by spheres of one colour pair."""
|
|
883
|
+
fill = style.get("fill")
|
|
884
|
+
if not isinstance(fill, str):
|
|
885
|
+
raise ValueError("highlight needs a fill colour to shade toward")
|
|
886
|
+
gid = f"ball-{_slug(fill)}-{_slug(highlight)}"
|
|
887
|
+
if gid not in self._shared:
|
|
888
|
+
self._shared.add(gid)
|
|
889
|
+
self.defs.append(
|
|
890
|
+
svg.RadialGradient(
|
|
891
|
+
id=gid,
|
|
892
|
+
cx=0.5,
|
|
893
|
+
cy=0.5,
|
|
894
|
+
r=0.5,
|
|
895
|
+
fx=0.36,
|
|
896
|
+
fy=0.32,
|
|
897
|
+
elements=[
|
|
898
|
+
svg.Stop(offset=0, stop_color=highlight),
|
|
899
|
+
svg.Stop(offset=1, stop_color=fill),
|
|
900
|
+
],
|
|
901
|
+
)
|
|
902
|
+
)
|
|
903
|
+
return f"url(#{gid})"
|
|
904
|
+
|
|
905
|
+
def _frustum(
|
|
906
|
+
self,
|
|
907
|
+
p0: Point3,
|
|
908
|
+
p1: Point3,
|
|
909
|
+
r0: float,
|
|
910
|
+
r1: float,
|
|
911
|
+
*,
|
|
912
|
+
ends: tuple[bool, bool],
|
|
913
|
+
end_style: Mapping[str, Style] | None,
|
|
914
|
+
highlight: str | None,
|
|
915
|
+
name: str | None,
|
|
916
|
+
style: Mapping[str, Style],
|
|
917
|
+
) -> list[svg.Element]:
|
|
918
|
+
"""Body outline plus whichever end disks face the camera, as elements.
|
|
919
|
+
|
|
920
|
+
``ends`` says which of the two end disks may be drawn at all; each is
|
|
921
|
+
then drawn only if it faces the camera, after the body, which is exact
|
|
922
|
+
for a convex solid.
|
|
923
|
+
"""
|
|
924
|
+
cam = _parallel(self.cam, "outline a solid of revolution")
|
|
925
|
+
if r0 <= 0 or r1 < 0:
|
|
926
|
+
raise ValueError(f"need r0 > 0 and r1 >= 0, got r0={r0}, r1={r1}")
|
|
927
|
+
a, b = np.asarray(p0, dtype=np.float64), np.asarray(p1, dtype=np.float64)
|
|
928
|
+
axis = b - a
|
|
929
|
+
if float(np.linalg.norm(axis)) == 0.0:
|
|
930
|
+
raise ValueError("the two ends coincide, so the solid has no axis")
|
|
931
|
+
axes = cam.scale * cam.matrix @ np.column_stack(basis_for(axis))
|
|
932
|
+
c0, c1 = cam.project([a, b])
|
|
933
|
+
reach = np.linalg.norm(axes, axis=1)
|
|
934
|
+
self._grow(np.array([c0 - r0 * reach, c0 + r0 * reach, c1 - r1 * reach, c1 + r1 * reach]))
|
|
935
|
+
|
|
936
|
+
body: dict[str, Style] = dict(style)
|
|
937
|
+
if highlight is not None:
|
|
938
|
+
fill = body.get("fill")
|
|
939
|
+
if not isinstance(fill, str) or name is None:
|
|
940
|
+
raise ValueError("highlight needs a fill colour and an id to name the gradient")
|
|
941
|
+
body["fill"] = f"url(#{name}-shade)"
|
|
942
|
+
self.defs.append(self._shade_across(f"{name}-shade", c0, c1, axes, r0, fill, highlight))
|
|
943
|
+
label: dict[str, Style] = {} if name is None else {"id": name}
|
|
944
|
+
elements: list[svg.Element] = [
|
|
945
|
+
svg.Path(d=_frustum_outline(c0, c1, axes, r0, r1), **label, **body)
|
|
946
|
+
]
|
|
947
|
+
disk: dict[str, Style] = {**style, **(end_style or {})}
|
|
948
|
+
toward = float(np.dot(unit(axis), cam.view))
|
|
949
|
+
for k, (c, r, faces) in enumerate(((c0, r0, toward < 0), (c1, r1, toward > 0))):
|
|
950
|
+
if ends[k] and faces and r > 0:
|
|
951
|
+
end: dict[str, Style] = {} if name is None else {"id": f"{name}-end{k}"}
|
|
952
|
+
elements.append(_ellipse_element(c, r * axes, **end, **disk))
|
|
953
|
+
return elements
|
|
954
|
+
|
|
955
|
+
def _sliced_cylinder(
|
|
956
|
+
self,
|
|
957
|
+
layer: int,
|
|
958
|
+
p0: Point3,
|
|
959
|
+
p1: Point3,
|
|
960
|
+
r0: float,
|
|
961
|
+
r1: float,
|
|
962
|
+
*,
|
|
963
|
+
slices: int,
|
|
964
|
+
ends: bool,
|
|
965
|
+
end_style: Mapping[str, Style] | None,
|
|
966
|
+
highlight: str | None,
|
|
967
|
+
base: str | None,
|
|
968
|
+
style: Mapping[str, Style],
|
|
969
|
+
) -> None:
|
|
970
|
+
""":meth:`cylinder` cut into ``slices`` separately sorted lengths."""
|
|
971
|
+
cam = _parallel(self.cam, "outline a solid of revolution")
|
|
972
|
+
if r0 <= 0 or r1 < 0:
|
|
973
|
+
raise ValueError(f"need r0 > 0 and r1 >= 0, got r0={r0}, r1={r1}")
|
|
974
|
+
a, b = np.asarray(p0, dtype=np.float64), np.asarray(p1, dtype=np.float64)
|
|
975
|
+
axis = b - a
|
|
976
|
+
if float(np.linalg.norm(axis)) == 0.0:
|
|
977
|
+
raise ValueError("the two ends coincide, so the solid has no axis")
|
|
978
|
+
axes = cam.scale * cam.matrix @ np.column_stack(basis_for(axis))
|
|
979
|
+
reach = np.linalg.norm(axes, axis=1)
|
|
980
|
+
c0, c1 = cam.project([a, b])
|
|
981
|
+
self._grow(np.array([c0 - r0 * reach, c0 + r0 * reach, c1 - r1 * reach, c1 + r1 * reach]))
|
|
982
|
+
|
|
983
|
+
fill: dict[str, Style] = {k: v for k, v in style.items() if not k.startswith("stroke")}
|
|
984
|
+
edge: dict[str, Style] = {k: v for k, v in style.items() if k.startswith("stroke")}
|
|
985
|
+
if highlight is not None:
|
|
986
|
+
colour = fill.get("fill")
|
|
987
|
+
if not isinstance(colour, str) or base is None:
|
|
988
|
+
raise ValueError("highlight needs a fill colour and an id to name the gradient")
|
|
989
|
+
fill["fill"] = f"url(#{base}-shade)"
|
|
990
|
+
self.defs.append(
|
|
991
|
+
self._shade_across(f"{base}-shade", c0, c1, axes, max(r0, r1), colour, highlight)
|
|
992
|
+
)
|
|
993
|
+
disk: dict[str, Style] = {**style, **(end_style or {})}
|
|
994
|
+
toward = float(np.dot(unit(axis), cam.view))
|
|
995
|
+
# Each slice's body overruns into its neighbours, so no seam shows at a
|
|
996
|
+
# joint whichever of the two is drawn on top.
|
|
997
|
+
overrun = 0.15 / slices
|
|
998
|
+
cuts = np.linspace(0.0, 1.0, slices + 1)
|
|
999
|
+
|
|
1000
|
+
def at(t: float) -> tuple[Array, float]:
|
|
1001
|
+
return a + t * axis, r0 + t * (r1 - r0)
|
|
1002
|
+
|
|
1003
|
+
for k in range(slices):
|
|
1004
|
+
lo, hi = max(cuts[k] - overrun, 0.0), min(cuts[k + 1] + overrun, 1.0)
|
|
1005
|
+
(pa, ra), (pb, rb) = at(lo), at(hi)
|
|
1006
|
+
qa, qb = cam.project([pa, pb])
|
|
1007
|
+
first, last = k == 0, k == slices - 1
|
|
1008
|
+
parts: list[svg.Element] = [
|
|
1009
|
+
svg.Path(
|
|
1010
|
+
d=_frustum_outline(qa, qb, axes, ra, rb),
|
|
1011
|
+
**_named(base, f"{k}-body"),
|
|
1012
|
+
**fill,
|
|
1013
|
+
)
|
|
1014
|
+
]
|
|
1015
|
+
if edge.get("stroke"):
|
|
1016
|
+
parts.append(
|
|
1017
|
+
svg.Path(
|
|
1018
|
+
d=_frustum_outline(qa, qb, axes, ra, rb, closed=False, arcs=(first, last)),
|
|
1019
|
+
fill="none",
|
|
1020
|
+
**_named(base, f"{k}-edge"),
|
|
1021
|
+
**edge,
|
|
1022
|
+
)
|
|
1023
|
+
)
|
|
1024
|
+
for cap, centre, r, faces in ((first, qa, ra, toward < 0), (last, qb, rb, toward > 0)):
|
|
1025
|
+
if ends and cap and faces and r > 0:
|
|
1026
|
+
end = "0" if centre is qa else "1"
|
|
1027
|
+
label = _named(base, f"end{end}")
|
|
1028
|
+
parts.append(_ellipse_element(centre, r * axes, **label, **disk))
|
|
1029
|
+
group = svg.G(elements=parts, **_named(base, str(k)))
|
|
1030
|
+
self._emit(layer, group, self._depth([at(cuts[k])[0], at(cuts[k + 1])[0]]))
|
|
1031
|
+
self._solid_shape([(pa, pb, ra, rb)], style)
|
|
1032
|
+
|
|
1033
|
+
@staticmethod
|
|
1034
|
+
def _shade_across(
|
|
1035
|
+
gid: str, c0: Array, c1: Array, axes: Array, r: float, fill: str, highlight: str
|
|
1036
|
+
) -> svg.Element:
|
|
1037
|
+
"""A linear gradient across a projected solid, lightest toward the upper left."""
|
|
1038
|
+
along = c1 - c0
|
|
1039
|
+
length = float(np.linalg.norm(along))
|
|
1040
|
+
side = np.array([-along[1], along[0]]) / length if length > 1e-9 else np.array([-1.0, -1.0])
|
|
1041
|
+
side = side / float(np.linalg.norm(side))
|
|
1042
|
+
if side[0] + side[1] > 0:
|
|
1043
|
+
side = -side
|
|
1044
|
+
half = r * float(np.linalg.norm(axes.T @ side))
|
|
1045
|
+
mid = (c0 + c1) / 2.0
|
|
1046
|
+
(x1, y1), (x2, y2) = mid + half * side, mid - half * side
|
|
1047
|
+
return svg.LinearGradient(
|
|
1048
|
+
id=gid,
|
|
1049
|
+
gradientUnits="userSpaceOnUse",
|
|
1050
|
+
x1=_num(x1),
|
|
1051
|
+
y1=_num(y1),
|
|
1052
|
+
x2=_num(x2),
|
|
1053
|
+
y2=_num(y2),
|
|
1054
|
+
elements=[
|
|
1055
|
+
svg.Stop(offset=0, stop_color=fill),
|
|
1056
|
+
svg.Stop(offset=0.3, stop_color=highlight),
|
|
1057
|
+
svg.Stop(offset=1, stop_color=fill),
|
|
1058
|
+
],
|
|
1059
|
+
)
|
|
1060
|
+
|
|
1061
|
+
def cylinder(
|
|
1062
|
+
self,
|
|
1063
|
+
layer: int,
|
|
1064
|
+
p0: Point3,
|
|
1065
|
+
p1: Point3,
|
|
1066
|
+
radius: float,
|
|
1067
|
+
*,
|
|
1068
|
+
r1: float | None = None,
|
|
1069
|
+
ends: bool = True,
|
|
1070
|
+
end_style: Mapping[str, Style] | None = None,
|
|
1071
|
+
highlight: str | None = None,
|
|
1072
|
+
slices: int = 1,
|
|
1073
|
+
**style: Style,
|
|
1074
|
+
) -> None:
|
|
1075
|
+
"""A cylinder from ``p0`` to ``p1``, or a frustum when ``r1`` differs."""
|
|
1076
|
+
base = style.pop("id", None)
|
|
1077
|
+
if slices < 1:
|
|
1078
|
+
raise ValueError(f"slices must be at least 1, got {slices}")
|
|
1079
|
+
if slices > 1:
|
|
1080
|
+
self._sliced_cylinder(
|
|
1081
|
+
layer,
|
|
1082
|
+
p0,
|
|
1083
|
+
p1,
|
|
1084
|
+
radius,
|
|
1085
|
+
radius if r1 is None else r1,
|
|
1086
|
+
slices=slices,
|
|
1087
|
+
ends=ends,
|
|
1088
|
+
end_style=end_style,
|
|
1089
|
+
highlight=highlight,
|
|
1090
|
+
base=base,
|
|
1091
|
+
style=style,
|
|
1092
|
+
)
|
|
1093
|
+
return
|
|
1094
|
+
elements = self._frustum(
|
|
1095
|
+
p0,
|
|
1096
|
+
p1,
|
|
1097
|
+
radius,
|
|
1098
|
+
radius if r1 is None else r1,
|
|
1099
|
+
ends=(ends, ends),
|
|
1100
|
+
end_style=end_style,
|
|
1101
|
+
highlight=highlight,
|
|
1102
|
+
name=None if base is None else f"{base}-body",
|
|
1103
|
+
style=style,
|
|
1104
|
+
)
|
|
1105
|
+
group = svg.G(elements=elements, **({} if base is None else {"id": base}))
|
|
1106
|
+
self._emit(layer, group, self._depth([p0, p1]))
|
|
1107
|
+
a, b = np.asarray(p0, dtype=np.float64), np.asarray(p1, dtype=np.float64)
|
|
1108
|
+
self._solid_shape([(a, b, radius, radius if r1 is None else r1)], style)
|
|
1109
|
+
|
|
1110
|
+
def _solid_shape(
|
|
1111
|
+
self, parts: Sequence[tuple[Array, Array, float, float]], style: Mapping[str, Style]
|
|
1112
|
+
) -> None:
|
|
1113
|
+
"""Describe the solids of revolution just emitted as one surface."""
|
|
1114
|
+
opaque, pad = _coverage(style)
|
|
1115
|
+
|
|
1116
|
+
def surface() -> Surface | None:
|
|
1117
|
+
grow = self._grown(pad)
|
|
1118
|
+
pieces = []
|
|
1119
|
+
for a, b, r0, r1 in parts:
|
|
1120
|
+
along = unit(b - a) * grow
|
|
1121
|
+
faces = _frustum_faces(a - along, b + along, r0 + grow, r1 + grow)
|
|
1122
|
+
if piece := self._convex_piece(faces):
|
|
1123
|
+
pieces.append(piece)
|
|
1124
|
+
return Surface(pieces, opaque, pad) if pieces else None
|
|
1125
|
+
|
|
1126
|
+
self._shape(surface)
|
|
1127
|
+
|
|
1128
|
+
def cone(
|
|
1129
|
+
self,
|
|
1130
|
+
layer: int,
|
|
1131
|
+
base: Point3,
|
|
1132
|
+
apex: Point3,
|
|
1133
|
+
radius: float,
|
|
1134
|
+
*,
|
|
1135
|
+
end: bool = True,
|
|
1136
|
+
end_style: Mapping[str, Style] | None = None,
|
|
1137
|
+
highlight: str | None = None,
|
|
1138
|
+
**style: Style,
|
|
1139
|
+
) -> None:
|
|
1140
|
+
"""A cone from a disk of ``radius`` at ``base`` to a point at ``apex``."""
|
|
1141
|
+
self.cylinder(
|
|
1142
|
+
layer,
|
|
1143
|
+
base,
|
|
1144
|
+
apex,
|
|
1145
|
+
radius,
|
|
1146
|
+
r1=0.0,
|
|
1147
|
+
ends=end,
|
|
1148
|
+
end_style=end_style,
|
|
1149
|
+
highlight=highlight,
|
|
1150
|
+
**style,
|
|
1151
|
+
)
|
|
1152
|
+
|
|
1153
|
+
def arrow3d(
|
|
1154
|
+
self,
|
|
1155
|
+
layer: int,
|
|
1156
|
+
origin: Point3,
|
|
1157
|
+
direction: Point3,
|
|
1158
|
+
length: float,
|
|
1159
|
+
*,
|
|
1160
|
+
shaft_r: float,
|
|
1161
|
+
head_r: float,
|
|
1162
|
+
head_len: float,
|
|
1163
|
+
pivot: Pivot = "tail",
|
|
1164
|
+
end_style: Mapping[str, Style] | None = None,
|
|
1165
|
+
highlight: str | None = None,
|
|
1166
|
+
**style: Style,
|
|
1167
|
+
) -> None:
|
|
1168
|
+
"""A solid arrow: a cylindrical shaft and a conical head, in one ``<g>``."""
|
|
1169
|
+
d = unit(direction)
|
|
1170
|
+
if not d.any():
|
|
1171
|
+
raise ValueError("an arrow needs a non-zero direction")
|
|
1172
|
+
base = style.pop("id", None)
|
|
1173
|
+
tail = np.asarray(origin, dtype=np.float64) - (d * length / 2.0 if pivot == "mid" else 0.0)
|
|
1174
|
+
tip = tail + d * length
|
|
1175
|
+
neck = tail + d * max(length - head_len, 0.0)
|
|
1176
|
+
|
|
1177
|
+
def piece(a: Array, b: Array, r0: float, r1: float, part: str) -> list[svg.Element]:
|
|
1178
|
+
return self._frustum(
|
|
1179
|
+
a,
|
|
1180
|
+
b,
|
|
1181
|
+
r0,
|
|
1182
|
+
r1,
|
|
1183
|
+
ends=(True, False),
|
|
1184
|
+
end_style=end_style,
|
|
1185
|
+
highlight=highlight,
|
|
1186
|
+
name=None if base is None else f"{base}-{part}",
|
|
1187
|
+
style=style,
|
|
1188
|
+
)
|
|
1189
|
+
|
|
1190
|
+
head = piece(neck, tip, head_r, 0.0, "head")
|
|
1191
|
+
shaft = piece(tail, neck, shaft_r, shaft_r, "shaft") if length > head_len else []
|
|
1192
|
+
toward = float(np.dot(d, _parallel(self.cam, "draw a solid arrow").view)) >= 0
|
|
1193
|
+
elements = shaft + head if toward else head + shaft
|
|
1194
|
+
group = svg.G(elements=elements, **({} if base is None else {"id": base}))
|
|
1195
|
+
self._emit(layer, group, self._depth([tail, tip]))
|
|
1196
|
+
parts = [(neck, tip, head_r, 0.0)]
|
|
1197
|
+
if length > head_len:
|
|
1198
|
+
parts.append((tail, neck, shaft_r, shaft_r))
|
|
1199
|
+
self._solid_shape(parts, style)
|
|
1200
|
+
|
|
1201
|
+
def tube(
|
|
1202
|
+
self,
|
|
1203
|
+
layer: int,
|
|
1204
|
+
pts3: Points3,
|
|
1205
|
+
radius: float,
|
|
1206
|
+
*,
|
|
1207
|
+
chunk: int = 4,
|
|
1208
|
+
**style: Style,
|
|
1209
|
+
) -> None:
|
|
1210
|
+
"""A tube of ``radius`` along a world-space curve -- a coil, a field line, a bond path."""
|
|
1211
|
+
cam = _parallel(self.cam, "draw a tube")
|
|
1212
|
+
if chunk < 1:
|
|
1213
|
+
raise ValueError(f"chunk must be at least 1, got {chunk}")
|
|
1214
|
+
pts = as_points(pts3)
|
|
1215
|
+
if len(pts) < 2:
|
|
1216
|
+
raise ValueError("a tube needs at least two points")
|
|
1217
|
+
body = style.pop("fill", "#000000")
|
|
1218
|
+
edge = style.pop("stroke", None)
|
|
1219
|
+
edge_w = float(style.pop("stroke_width", 1.0))
|
|
1220
|
+
base = style.pop("id", None)
|
|
1221
|
+
s = np.linalg.svd(cam.matrix, compute_uv=False) * cam.scale
|
|
1222
|
+
width = 2.0 * radius * math.sqrt(float(s[0] * s[1]))
|
|
1223
|
+
p = cam.project(pts)
|
|
1224
|
+
margin = width / 2.0 + (edge_w if edge else 0.0)
|
|
1225
|
+
self._grow(np.vstack([p - margin, p + margin]))
|
|
1226
|
+
last = len(pts) - 1
|
|
1227
|
+
line: dict[str, Style] = dict(fill="none", stroke_linecap="butt", stroke_linejoin="round")
|
|
1228
|
+
for k, start in enumerate(range(0, last, chunk)):
|
|
1229
|
+
# Outlines of neighbouring pieces overlap by a segment, so their
|
|
1230
|
+
# square ends leave no notch on the outside of a bend, and each body
|
|
1231
|
+
# overruns its own outline by a segment at either inner end, so an
|
|
1232
|
+
# outline's square end lies under body colour rather than leaving an
|
|
1233
|
+
# anti-aliased seam across the tube.
|
|
1234
|
+
stop = min(start + chunk + 3, last)
|
|
1235
|
+
strokes: list[svg.Element] = []
|
|
1236
|
+
if edge:
|
|
1237
|
+
inner = p[(start + 1 if start else 0) : min(start + chunk + 2, last) + 1]
|
|
1238
|
+
strokes.append(
|
|
1239
|
+
svg.Polyline(
|
|
1240
|
+
points=_points(inner),
|
|
1241
|
+
stroke=edge,
|
|
1242
|
+
stroke_width=_num(width + 2 * edge_w, 3),
|
|
1243
|
+
**line,
|
|
1244
|
+
)
|
|
1245
|
+
)
|
|
1246
|
+
strokes.append(
|
|
1247
|
+
svg.Polyline(
|
|
1248
|
+
points=_points(p[start : stop + 1]),
|
|
1249
|
+
stroke=body,
|
|
1250
|
+
stroke_width=_num(width, 3),
|
|
1251
|
+
**line,
|
|
1252
|
+
)
|
|
1253
|
+
)
|
|
1254
|
+
label: dict[str, Style] = {} if base is None else {"id": f"{base}-{k}"}
|
|
1255
|
+
self._emit(
|
|
1256
|
+
layer,
|
|
1257
|
+
svg.G(elements=strokes, **label, **style),
|
|
1258
|
+
self._depth(pts[start : stop + 1]),
|
|
1259
|
+
)
|
|
1260
|
+
self._tube_shape(
|
|
1261
|
+
pts[start : stop + 1],
|
|
1262
|
+
width,
|
|
1263
|
+
radius,
|
|
1264
|
+
{**style, "fill": body},
|
|
1265
|
+
edge_w if edge else 0.0,
|
|
1266
|
+
(id(pts), k),
|
|
1267
|
+
)
|
|
1268
|
+
|
|
1269
|
+
def _tube_shape(
|
|
1270
|
+
self,
|
|
1271
|
+
run: Array,
|
|
1272
|
+
width: float,
|
|
1273
|
+
radius: float,
|
|
1274
|
+
style: Mapping[str, Style],
|
|
1275
|
+
edge: float,
|
|
1276
|
+
chain: tuple[int, int],
|
|
1277
|
+
) -> None:
|
|
1278
|
+
"""A tube piece: the chain of capsules along its centre line, exactly."""
|
|
1279
|
+
opaque, _ = _coverage(style)
|
|
1280
|
+
|
|
1281
|
+
def surface() -> Surface | None:
|
|
1282
|
+
cam = _parallel(self.cam, "resolve occlusion")
|
|
1283
|
+
segments = np.array([(a, b) for a, b in itertools.pairwise(run) if np.any(a != b)])
|
|
1284
|
+
if not len(segments):
|
|
1285
|
+
return None
|
|
1286
|
+
back = np.linalg.pinv(cam.matrix * cam.scale)
|
|
1287
|
+
grown = radius + self._grown(edge)
|
|
1288
|
+
depth, covers = capsule_depth(segments, grown, back, cam.origin, cam.view)
|
|
1289
|
+
piece = Piece(cam.project(run), depth, covers=covers, width=width / 2.0)
|
|
1290
|
+
return Surface([piece], opaque, edge, chain)
|
|
1291
|
+
|
|
1292
|
+
self._shape(surface)
|
|
1293
|
+
|
|
1294
|
+
def edges(
|
|
1295
|
+
self,
|
|
1296
|
+
layer: int,
|
|
1297
|
+
faces: Iterable[Face],
|
|
1298
|
+
*,
|
|
1299
|
+
back: Mapping[str, Style] | None = None,
|
|
1300
|
+
back_layer: int | None = None,
|
|
1301
|
+
separate: bool = False,
|
|
1302
|
+
trim: float = 0.0,
|
|
1303
|
+
**style: Style,
|
|
1304
|
+
) -> None:
|
|
1305
|
+
"""The edges of a convex solid, split into visible and hidden."""
|
|
1306
|
+
given = list(faces)
|
|
1307
|
+
base = style.pop("id", None)
|
|
1308
|
+
style.setdefault("fill", "none")
|
|
1309
|
+
facing = {id(face) for face in self.cam.visible(given)}
|
|
1310
|
+
ends: dict[tuple[tuple[float, ...], ...], Array] = {}
|
|
1311
|
+
shown: dict[tuple[tuple[float, ...], ...], bool] = {}
|
|
1312
|
+
for face in given:
|
|
1313
|
+
ring: Array = np.asarray(face.points, dtype=np.float64)
|
|
1314
|
+
for start, end in zip(ring, np.roll(ring, -1, axis=0), strict=True):
|
|
1315
|
+
a, b = cast(Array, start), cast(Array, end)
|
|
1316
|
+
key = tuple(sorted((tuple(np.round(a, 9)), tuple(np.round(b, 9)))))
|
|
1317
|
+
if key not in ends:
|
|
1318
|
+
along = unit(b - a) * trim
|
|
1319
|
+
ends[key] = np.array([a + along, b - along])
|
|
1320
|
+
shown[key] = shown.get(key, False) or id(face) in facing
|
|
1321
|
+
for visible, at, extra, suffix in (
|
|
1322
|
+
(True, layer, {}, "front"),
|
|
1323
|
+
(False, layer if back_layer is None else back_layer, back, "back"),
|
|
1324
|
+
):
|
|
1325
|
+
if extra is None:
|
|
1326
|
+
continue
|
|
1327
|
+
segments = [ends[key] for key in ends if shown[key] is visible]
|
|
1328
|
+
groups = [[seg] for seg in segments] if separate else [segments]
|
|
1329
|
+
for k, group in enumerate(groups):
|
|
1330
|
+
if not group:
|
|
1331
|
+
continue
|
|
1332
|
+
projected = [self.cam.project(seg) for seg in group]
|
|
1333
|
+
for seg in projected:
|
|
1334
|
+
self._grow(seg)
|
|
1335
|
+
attrs: dict[str, Style] = {**style, **extra}
|
|
1336
|
+
if base is not None:
|
|
1337
|
+
attrs["id"] = f"{base}-{suffix}-{k}" if separate else f"{base}-{suffix}"
|
|
1338
|
+
self._emit(at, svg.Path(d=_path(projected), **attrs), self._depth(np.vstack(group)))
|
|
1339
|
+
# Behind another object, a visible edge takes the hidden style and
|
|
1340
|
+
# a hidden one disappears.
|
|
1341
|
+
hide = back if visible else None
|
|
1342
|
+
self._shape(functools.partial(self._line, group, attrs, hide))
|
|
1343
|
+
|
|
1344
|
+
def sphere_curve(
|
|
1345
|
+
self,
|
|
1346
|
+
layer: int,
|
|
1347
|
+
center: Point3,
|
|
1348
|
+
pts3: Points3,
|
|
1349
|
+
*,
|
|
1350
|
+
closed: bool = False,
|
|
1351
|
+
back: Mapping[str, Style] | None = None,
|
|
1352
|
+
back_layer: int | None = None,
|
|
1353
|
+
**style: Style,
|
|
1354
|
+
) -> None:
|
|
1355
|
+
"""A curve on a sphere's surface, split where it passes behind the sphere."""
|
|
1356
|
+
cam = _parallel(self.cam, "split a curve at a sphere's outline")
|
|
1357
|
+
style.setdefault("fill", "none")
|
|
1358
|
+
base = style.pop("id", None)
|
|
1359
|
+
pts = as_points(pts3)
|
|
1360
|
+
if closed:
|
|
1361
|
+
pts = np.vstack([pts, pts[:1]])
|
|
1362
|
+
side = (pts - np.asarray(center, dtype=np.float64)) @ cam.view
|
|
1363
|
+
front = side >= 0
|
|
1364
|
+
runs: list[tuple[bool, list[Array]]] = []
|
|
1365
|
+
current, state = [pts[0]], bool(front[0])
|
|
1366
|
+
for i in range(len(pts) - 1):
|
|
1367
|
+
if bool(front[i + 1]) != state:
|
|
1368
|
+
t = side[i] / (side[i] - side[i + 1])
|
|
1369
|
+
cut = pts[i] + t * (pts[i + 1] - pts[i])
|
|
1370
|
+
current.append(cut)
|
|
1371
|
+
runs.append((state, current))
|
|
1372
|
+
current, state = [cut], bool(front[i + 1])
|
|
1373
|
+
current.append(pts[i + 1])
|
|
1374
|
+
runs.append((state, current))
|
|
1375
|
+
if closed and len(runs) > 1 and runs[0][0] == runs[-1][0]:
|
|
1376
|
+
runs = [(runs[0][0], runs[-1][1] + runs[0][1][1:]), *runs[1:-1]]
|
|
1377
|
+
for visible, at, extra, suffix in (
|
|
1378
|
+
(True, layer, {}, "front"),
|
|
1379
|
+
(False, layer if back_layer is None else back_layer, back, "back"),
|
|
1380
|
+
):
|
|
1381
|
+
if extra is None:
|
|
1382
|
+
continue
|
|
1383
|
+
chosen = [np.array(run) for state, run in runs if state is visible]
|
|
1384
|
+
if not chosen:
|
|
1385
|
+
continue
|
|
1386
|
+
projected = [self.cam.project(run) for run in chosen]
|
|
1387
|
+
for run in projected:
|
|
1388
|
+
self._grow(run)
|
|
1389
|
+
attrs: dict[str, Style] = {**style, **extra}
|
|
1390
|
+
if base is not None:
|
|
1391
|
+
attrs["id"] = f"{base}-{suffix}"
|
|
1392
|
+
self._emit(
|
|
1393
|
+
at,
|
|
1394
|
+
svg.Path(d=_path(projected), **attrs),
|
|
1395
|
+
self._depth(np.vstack(chosen)),
|
|
1396
|
+
)
|
|
1397
|
+
hide = back if visible else None
|
|
1398
|
+
self._shape(functools.partial(self._line, chosen, attrs, hide))
|
|
1399
|
+
|
|
1400
|
+
def text(
|
|
1401
|
+
self,
|
|
1402
|
+
layer: int,
|
|
1403
|
+
pt3: Point3,
|
|
1404
|
+
s: TextContent,
|
|
1405
|
+
dx: float = 0.0,
|
|
1406
|
+
dy: float = 0.0,
|
|
1407
|
+
size: float = 22.0,
|
|
1408
|
+
**style: Style,
|
|
1409
|
+
) -> None:
|
|
1410
|
+
"""Text anchored at a projected world point, offset by ``(dx, dy)`` on screen."""
|
|
1411
|
+
x, y = self.cam.at(pt3)
|
|
1412
|
+
self._place_text(layer, x + dx, y + dy, s, size, True, self._depth([pt3]), **style)
|
|
1413
|
+
|
|
1414
|
+
def rect2d(
|
|
1415
|
+
self,
|
|
1416
|
+
layer: int,
|
|
1417
|
+
x: float,
|
|
1418
|
+
y: float,
|
|
1419
|
+
w: float,
|
|
1420
|
+
h: float,
|
|
1421
|
+
grow: bool = False,
|
|
1422
|
+
**style: Style,
|
|
1423
|
+
) -> None:
|
|
1424
|
+
"""Rectangle in screen coordinates -- a backdrop, glow, or gradient wash."""
|
|
1425
|
+
if grow:
|
|
1426
|
+
self._grow(np.array([[x, y], [x + w, y + h]]))
|
|
1427
|
+
self._emit(
|
|
1428
|
+
layer,
|
|
1429
|
+
svg.Rect(x=round(x, 1), y=round(y, 1), width=round(w, 1), height=round(h, 1), **style),
|
|
1430
|
+
)
|
|
1431
|
+
|
|
1432
|
+
def text2d(
|
|
1433
|
+
self,
|
|
1434
|
+
layer: int,
|
|
1435
|
+
x: float,
|
|
1436
|
+
y: float,
|
|
1437
|
+
s: TextContent,
|
|
1438
|
+
size: float = 22.0,
|
|
1439
|
+
grow: bool = True,
|
|
1440
|
+
**style: Style,
|
|
1441
|
+
) -> None:
|
|
1442
|
+
"""Text in screen coordinates; ``s`` as for :meth:`text`."""
|
|
1443
|
+
style.setdefault("font_family", DEFAULT_FONT)
|
|
1444
|
+
style.setdefault("fill", DEFAULT_TEXT_FILL)
|
|
1445
|
+
self._place_text(layer, x, y, s, size, grow, None, **style)
|
|
1446
|
+
|
|
1447
|
+
def _place_text(
|
|
1448
|
+
self,
|
|
1449
|
+
layer: int,
|
|
1450
|
+
x: float,
|
|
1451
|
+
y: float,
|
|
1452
|
+
s: TextContent,
|
|
1453
|
+
size: float,
|
|
1454
|
+
grow: bool,
|
|
1455
|
+
depth: float | None,
|
|
1456
|
+
**style: Style,
|
|
1457
|
+
) -> None:
|
|
1458
|
+
"""Emit a text element; shared by :meth:`text` and :meth:`text2d`."""
|
|
1459
|
+
style.setdefault("font_family", DEFAULT_FONT)
|
|
1460
|
+
style.setdefault("fill", DEFAULT_TEXT_FILL)
|
|
1461
|
+
if grow:
|
|
1462
|
+
# Crude metrics, but enough to keep the fitted viewBox from clipping
|
|
1463
|
+
# labels. Real advance widths would need the font loaded.
|
|
1464
|
+
w = 0.56 * size * _text_length(s)
|
|
1465
|
+
anchor = style.get("text_anchor", "start")
|
|
1466
|
+
x0 = x if anchor == "start" else (x - w if anchor == "end" else x - w / 2)
|
|
1467
|
+
self._grow(np.array([[x0, y - 0.82 * size], [x0 + w, y + 0.25 * size]]))
|
|
1468
|
+
content: dict[str, Style] = {"text": s} if isinstance(s, str) else {"elements": list(s)}
|
|
1469
|
+
self._emit(
|
|
1470
|
+
layer,
|
|
1471
|
+
svg.Text(
|
|
1472
|
+
x=round(x, 2),
|
|
1473
|
+
y=round(y, 2),
|
|
1474
|
+
font_size=size,
|
|
1475
|
+
**content,
|
|
1476
|
+
**style,
|
|
1477
|
+
),
|
|
1478
|
+
depth,
|
|
1479
|
+
)
|
|
1480
|
+
|
|
1481
|
+
def _order(self, item: tuple[int, int, svg.Element]) -> tuple[int, int, float, int]:
|
|
1482
|
+
"""Sort key: layer, then depth within a depth-sorted layer, then insertion.
|
|
1483
|
+
|
|
1484
|
+
In an exact layer the opaque surfaces come first, in the order
|
|
1485
|
+
:meth:`_paint_order` found, and everything translucent or stroked is
|
|
1486
|
+
then painted back to front over them.
|
|
1487
|
+
"""
|
|
1488
|
+
layer, seq, _ = item
|
|
1489
|
+
if layer not in self._sorted:
|
|
1490
|
+
return (layer, 0, 0.0, seq)
|
|
1491
|
+
depth = self._depths.get(seq)
|
|
1492
|
+
if depth is None:
|
|
1493
|
+
return (layer, 2, 0.0, seq)
|
|
1494
|
+
if seq in self._opaque:
|
|
1495
|
+
return (layer, 0, float(self._rank.get(seq, 0)), seq)
|
|
1496
|
+
return (layer, 1, depth, seq)
|
|
1497
|
+
|
|
1498
|
+
|
|
1499
|
+
type CameraRef = Camera | str
|
|
1500
|
+
"""A camera, or the name of one in :attr:`Scene.cameras`."""
|
|
1501
|
+
|
|
1502
|
+
|
|
1503
|
+
class Scene:
|
|
1504
|
+
"""A 3D scene: objects in world space, and the cameras that view them.
|
|
1505
|
+
|
|
1506
|
+
Drawing calls record objects and nothing more; nothing is projected until
|
|
1507
|
+
the scene is rendered. As in a 3D application, a scene can hold any number
|
|
1508
|
+
of named cameras, one of them active, and a render uses the active camera
|
|
1509
|
+
unless told which other to use::
|
|
1510
|
+
|
|
1511
|
+
scene = Scene(pad=28, background="#ffffff")
|
|
1512
|
+
scene.sphere(10, (0, 0, 0), 1.0, fill="#c33")
|
|
1513
|
+
scene.cameras["main"] = OrthographicCamera(35, 24, 62)
|
|
1514
|
+
scene.cameras["cabinet"] = ObliqueCamera.cabinet(62)
|
|
1515
|
+
scene.camera = "main" # the active camera
|
|
1516
|
+
scene.save("main.svg")
|
|
1517
|
+
scene.save("cabinet.svg", "cabinet")
|
|
1518
|
+
scene.render(OrthographicCamera.isometric(62)) # any camera, named or not
|
|
1519
|
+
|
|
1520
|
+
:attr:`camera` is the active camera, which :meth:`render`, :meth:`save`,
|
|
1521
|
+
and :meth:`bbox` use unless given another, and which
|
|
1522
|
+
:meth:`to_svg_document` -- the zero-argument embedding contract -- always
|
|
1523
|
+
uses. Set it to the name of a camera in :attr:`cameras`, which keeps
|
|
1524
|
+
following that entry if it is replaced, or to a camera directly. It may be
|
|
1525
|
+
``None`` while the scene is built.
|
|
1526
|
+
|
|
1527
|
+
Draw order is an explicit integer ``layer`` per call, resolved stably by
|
|
1528
|
+
insertion order within a layer. There is no z-buffer, and no layer is
|
|
1529
|
+
depth-sorted unless it asks to be with :meth:`sort_by_depth`: for a schematic
|
|
1530
|
+
with a beam passing through a translucent slab, deciding what occludes what
|
|
1531
|
+
by hand is worth more than getting it automatically and almost right, while
|
|
1532
|
+
for a lattice of hundreds of atoms the painter's algorithm is the only
|
|
1533
|
+
practical answer. :meth:`Camera.visible` handles the one case where the
|
|
1534
|
+
answer is unambiguous -- the back faces of a convex solid.
|
|
1535
|
+
|
|
1536
|
+
Args:
|
|
1537
|
+
camera: The active camera, or the name of one in ``cameras``, or ``None``
|
|
1538
|
+
to choose one later.
|
|
1539
|
+
cameras: Named cameras the scene holds.
|
|
1540
|
+
pad: Default margin added around the fitted content.
|
|
1541
|
+
background: Default background fill, or ``None`` for a transparent document.
|
|
1542
|
+
"""
|
|
1543
|
+
|
|
1544
|
+
def __init__(
|
|
1545
|
+
self,
|
|
1546
|
+
camera: CameraRef | None = None,
|
|
1547
|
+
*,
|
|
1548
|
+
cameras: Mapping[str, Camera] | None = None,
|
|
1549
|
+
pad: float = 26.0,
|
|
1550
|
+
background: str | None = None,
|
|
1551
|
+
) -> None:
|
|
1552
|
+
self.cameras: dict[str, Camera] = dict(cameras or {})
|
|
1553
|
+
self._active: CameraRef | None = None
|
|
1554
|
+
self.camera = camera
|
|
1555
|
+
self.pad = float(pad)
|
|
1556
|
+
self.background = background
|
|
1557
|
+
self._log: list[tuple[str, tuple[object, ...], dict[str, Style]]] = []
|
|
1558
|
+
|
|
1559
|
+
def __repr__(self) -> str:
|
|
1560
|
+
names = ", ".join(self.cameras)
|
|
1561
|
+
return f"Scene({self._active!r}, cameras=[{names}], {len(self._log)} calls)"
|
|
1562
|
+
|
|
1563
|
+
def _add(self, method: str, *args: object, **kwargs: Style) -> None:
|
|
1564
|
+
"""Record one drawing call, to be replayed against a camera when rendering."""
|
|
1565
|
+
self._log.append((method, args, kwargs))
|
|
1566
|
+
|
|
1567
|
+
# --- cameras ----------------------------------------------------------
|
|
1568
|
+
@property
|
|
1569
|
+
def camera(self) -> Camera | None:
|
|
1570
|
+
"""The active camera, looked up by name if it was set by name."""
|
|
1571
|
+
return None if self._active is None else self._lookup(self._active)
|
|
1572
|
+
|
|
1573
|
+
@camera.setter
|
|
1574
|
+
def camera(self, value: CameraRef | None) -> None:
|
|
1575
|
+
if isinstance(value, str):
|
|
1576
|
+
self._lookup(value)
|
|
1577
|
+
self._active = value
|
|
1578
|
+
|
|
1579
|
+
def _lookup(self, ref: CameraRef) -> Camera:
|
|
1580
|
+
if not isinstance(ref, str):
|
|
1581
|
+
return ref
|
|
1582
|
+
if ref not in self.cameras:
|
|
1583
|
+
raise KeyError(f"no camera named {ref!r}; the scene has {sorted(self.cameras)}")
|
|
1584
|
+
return self.cameras[ref]
|
|
1585
|
+
|
|
1586
|
+
def _view(self, camera: CameraRef | None) -> Camera:
|
|
1587
|
+
if camera is not None:
|
|
1588
|
+
return self._lookup(camera)
|
|
1589
|
+
active = self.camera
|
|
1590
|
+
if active is None:
|
|
1591
|
+
raise ValueError("no camera to render with: pass one, or set scene.camera")
|
|
1592
|
+
return active
|
|
1593
|
+
|
|
1594
|
+
# --- rendering --------------------------------------------------------
|
|
1595
|
+
def _project(self, camera: CameraRef | None) -> _Canvas:
|
|
1596
|
+
"""Replay every recorded call against a camera, on a fresh canvas."""
|
|
1597
|
+
canvas = _Canvas(self._view(camera))
|
|
1598
|
+
for method, args, kwargs in self._log:
|
|
1599
|
+
getattr(canvas, method)(*args, **kwargs)
|
|
1600
|
+
return canvas
|
|
1601
|
+
|
|
1602
|
+
@property
|
|
1603
|
+
def is_empty(self) -> bool:
|
|
1604
|
+
"""Whether nothing has been drawn yet: settings and definitions do not count."""
|
|
1605
|
+
return all(method in ("sort_by_depth", "add_def") for method, _, _ in self._log)
|
|
1606
|
+
|
|
1607
|
+
def bbox(self, camera: CameraRef | None = None) -> tuple[Array, Array]:
|
|
1608
|
+
"""Screen-space bounds of the content under ``camera`` (default: the active one).
|
|
1609
|
+
|
|
1610
|
+
Text extents are estimated from a nominal glyph width, which is enough
|
|
1611
|
+
to keep the fitted viewBox from clipping a label but is not exact.
|
|
1612
|
+
"""
|
|
1613
|
+
return self._project(camera).bbox()
|
|
1614
|
+
|
|
1615
|
+
def render(
|
|
1616
|
+
self,
|
|
1617
|
+
camera: CameraRef | None = None,
|
|
1618
|
+
*,
|
|
1619
|
+
pad: float | None = None,
|
|
1620
|
+
background: str | None = None,
|
|
1621
|
+
) -> svg.SVG:
|
|
1622
|
+
"""Project the scene and assemble the document, fitting the viewBox to the content.
|
|
1623
|
+
|
|
1624
|
+
Nothing has to be centred by hand: the viewBox follows the geometry.
|
|
1625
|
+
Rendering is a pure function of the recorded calls and the camera, so
|
|
1626
|
+
it can be called any number of times, with any cameras.
|
|
1627
|
+
|
|
1628
|
+
Args:
|
|
1629
|
+
camera: A camera, or the name of one in :attr:`cameras`; defaults
|
|
1630
|
+
to the active :attr:`camera`.
|
|
1631
|
+
pad: Margin around the content; defaults to the scene's ``pad``.
|
|
1632
|
+
background: Background fill; defaults to the scene's ``background``.
|
|
1633
|
+
|
|
1634
|
+
Raises:
|
|
1635
|
+
ValueError: If there is no camera, or nothing to fit a viewBox to.
|
|
1636
|
+
KeyError: For a camera name the scene does not hold.
|
|
1637
|
+
"""
|
|
1638
|
+
canvas = self._project(camera)
|
|
1639
|
+
return canvas.document(
|
|
1640
|
+
self.pad if pad is None else float(pad),
|
|
1641
|
+
self.background if background is None else background,
|
|
1642
|
+
)
|
|
1643
|
+
|
|
1644
|
+
def with_camera(self, camera: CameraRef) -> Scene:
|
|
1645
|
+
"""A copy of this scene whose active camera is ``camera``.
|
|
1646
|
+
|
|
1647
|
+
The recorded calls and the named cameras are copied, so later changes to
|
|
1648
|
+
either scene do not affect the other. Useful for handing the same
|
|
1649
|
+
scene, seen two ways, to a tool that only calls :meth:`to_svg_document`.
|
|
1650
|
+
|
|
1651
|
+
Two things behave as their names promise rather than as a new camera
|
|
1652
|
+
might suggest. Screen-space calls -- :meth:`rect2d`, :meth:`text2d`,
|
|
1653
|
+
and anything handed to :meth:`add` -- stay at the same screen
|
|
1654
|
+
coordinates, because that is what "screen space" means. And geometry
|
|
1655
|
+
computed by the *caller* from a camera (a point placed via
|
|
1656
|
+
:meth:`Camera.at`, say) is baked in already.
|
|
1657
|
+
|
|
1658
|
+
The world-space arrays handed to :meth:`polygon` and friends are held by
|
|
1659
|
+
reference, not copied, so do not mutate them after adding.
|
|
1660
|
+
"""
|
|
1661
|
+
clone = Scene(camera, cameras=self.cameras, pad=self.pad, background=self.background)
|
|
1662
|
+
clone._log = list(self._log)
|
|
1663
|
+
return clone
|
|
1664
|
+
|
|
1665
|
+
def _repr_svg_(self) -> str | None:
|
|
1666
|
+
"""Show the scene inline in Jupyter; ``None`` (plain repr) without a camera or content."""
|
|
1667
|
+
if self.camera is None or self.is_empty:
|
|
1668
|
+
return None
|
|
1669
|
+
return self.to_svg_document()
|
|
1670
|
+
|
|
1671
|
+
def to_svg_document(self) -> str:
|
|
1672
|
+
"""Return the scene, seen by its active :attr:`camera`, as a complete SVG document.
|
|
1673
|
+
|
|
1674
|
+
This is the whole surface a consumer needs. A tool that assembles a
|
|
1675
|
+
larger document can accept any object exposing this method and place a
|
|
1676
|
+
scene without importing this package, or being imported by it.
|
|
1677
|
+
"""
|
|
1678
|
+
return str(self.render())
|
|
1679
|
+
|
|
1680
|
+
def save(self, path: str | Path, camera: CameraRef | None = None) -> Path:
|
|
1681
|
+
"""Write the document rendered by ``camera`` (default: the active one); return the path.
|
|
1682
|
+
|
|
1683
|
+
Only SVG is written. Rasterizing and PDF are left to the consumer,
|
|
1684
|
+
which is what keeps them out of this package's dependencies -- run
|
|
1685
|
+
``cairosvg`` over the file, or hand :meth:`to_svg_document` to whatever
|
|
1686
|
+
assembles the final page.
|
|
1687
|
+
"""
|
|
1688
|
+
out = Path(path)
|
|
1689
|
+
out.write_text(str(self.render(camera)), encoding="utf-8")
|
|
1690
|
+
return out
|
|
1691
|
+
|
|
1692
|
+
# --- drawing ----------------------------------------------------------
|
|
1693
|
+
def sort_by_depth(self, layer: int, *, exact: bool = False) -> None:
|
|
1694
|
+
"""Order ``layer`` back to front by depth instead of by insertion.
|
|
1695
|
+
|
|
1696
|
+
The painter's algorithm, opted into one layer at a time. Every
|
|
1697
|
+
world-space element drawn at ``layer`` is keyed by the mean depth of
|
|
1698
|
+
the points that produced it -- a sphere by its centre, a cylinder by its
|
|
1699
|
+
axis midpoint, a polygon by its vertices -- and drawn farthest first.
|
|
1700
|
+
Equal depths keep insertion order, and screen-space elements, which have
|
|
1701
|
+
no depth, go on top in insertion order. Other layers are untouched.
|
|
1702
|
+
|
|
1703
|
+
This is for many separate objects that do not interpenetrate: the atoms
|
|
1704
|
+
and bonds of a lattice, the arrows of a spin texture, the quads of a
|
|
1705
|
+
surface. It is a heuristic, exact for non-overlapping spheres of one
|
|
1706
|
+
radius and good for small, similar pieces, and it cannot order two long
|
|
1707
|
+
objects that each cover part of the other.
|
|
1708
|
+
|
|
1709
|
+
``exact=True`` lifts that limit by deciding visibility point by point
|
|
1710
|
+
instead. Each surface keeps its native element, clipped to the part of
|
|
1711
|
+
it that no opaque surface hides -- found exactly between two planar
|
|
1712
|
+
surfaces, and to a quarter of a screen unit elsewhere -- so a bond can
|
|
1713
|
+
run into an atom's centre, two planes can cross, and a coil can wrap an
|
|
1714
|
+
unsliced core. Each line is cut where an opaque surface hides it; the
|
|
1715
|
+
hidden part is dropped, or drawn in the ``back`` style of
|
|
1716
|
+
:meth:`polyline`, :meth:`edges`, or :meth:`sphere_curve`. Translucent
|
|
1717
|
+
surfaces hide nothing but are clipped by what is in front of them. It
|
|
1718
|
+
needs the ``occlusion`` extra (``shapely`` and ``contourpy``), is
|
|
1719
|
+
slower, and adds one ``<clipPath>`` per partly hidden element.
|
|
1720
|
+
|
|
1721
|
+
A beam inside a translucent slab still belongs on separate layers: a
|
|
1722
|
+
translucent face hides nothing, so no rule of visibility orders it.
|
|
1723
|
+
|
|
1724
|
+
The setting is recorded, so rendering with another camera re-sorts.
|
|
1725
|
+
"""
|
|
1726
|
+
self._add("sort_by_depth", layer, exact=exact)
|
|
1727
|
+
|
|
1728
|
+
def add(self, layer: int, element: svg.Element) -> None:
|
|
1729
|
+
"""Add a ready-made ``svg.py`` element at ``layer``, bypassing projection."""
|
|
1730
|
+
self._add("add", layer, element)
|
|
1731
|
+
|
|
1732
|
+
def add_def(self, element: svg.Element) -> None:
|
|
1733
|
+
"""Add an element to ``<defs>`` -- a gradient, marker, or clip path."""
|
|
1734
|
+
self._add("add_def", element)
|
|
1735
|
+
|
|
1736
|
+
def polygon(self, layer: int, pts3: Points3, **style: Style) -> None:
|
|
1737
|
+
"""Filled polygon through projected world points."""
|
|
1738
|
+
self._add("polygon", layer, pts3, **style)
|
|
1739
|
+
|
|
1740
|
+
def polyline(
|
|
1741
|
+
self, layer: int, pts3: Points3, *, back: Mapping[str, Style] | None = None, **style: Style
|
|
1742
|
+
) -> None:
|
|
1743
|
+
"""Open path through projected world points; unfilled unless asked.
|
|
1744
|
+
|
|
1745
|
+
In a layer sorted with ``exact=True``, the parts an opaque surface hides
|
|
1746
|
+
are dropped, or drawn with ``{**style, **back}`` when ``back`` is given
|
|
1747
|
+
-- a ray dashed where it passes behind an atom. Elsewhere ``back`` has
|
|
1748
|
+
no effect.
|
|
1749
|
+
"""
|
|
1750
|
+
style.setdefault("fill", "none")
|
|
1751
|
+
self._add("polyline", layer, pts3, back=back, **style)
|
|
1752
|
+
|
|
1753
|
+
def faces(
|
|
1754
|
+
self, layer: int, faces: Iterable[Face], *, cull: bool = False, **style: Style
|
|
1755
|
+
) -> None:
|
|
1756
|
+
"""Draw each face as a polygon, all with the same style.
|
|
1757
|
+
|
|
1758
|
+
Args:
|
|
1759
|
+
layer: Draw order.
|
|
1760
|
+
faces: Faces to draw, typically from :func:`~vecview.shapes.box_faces`.
|
|
1761
|
+
cull: Drop back faces when rendering, using the camera that renders.
|
|
1762
|
+
Prefer this over filtering with :meth:`Camera.visible` yourself:
|
|
1763
|
+
culling done by the caller bakes in *that* camera's answer, so
|
|
1764
|
+
any other camera would keep the original walls and quietly draw
|
|
1765
|
+
the wrong ones. With ``cull=True`` the full set is recorded and
|
|
1766
|
+
each camera decides.
|
|
1767
|
+
**style: SVG presentation attributes, shared by every face.
|
|
1768
|
+
|
|
1769
|
+
An ``id`` is suffixed per face rather than repeated, since duplicate ids
|
|
1770
|
+
are invalid SVG and break selection downstream: ``id="slab"`` over a
|
|
1771
|
+
box's visible walls yields ``slab-pz``, ``slab-px``, ``slab-py``.
|
|
1772
|
+
"""
|
|
1773
|
+
base = style.pop("id", None)
|
|
1774
|
+
given = list(faces)
|
|
1775
|
+
self._add(
|
|
1776
|
+
"faces",
|
|
1777
|
+
layer,
|
|
1778
|
+
given,
|
|
1779
|
+
cull=cull,
|
|
1780
|
+
**({} if base is None else {"id": base}),
|
|
1781
|
+
**style,
|
|
1782
|
+
)
|
|
1783
|
+
|
|
1784
|
+
def plane(
|
|
1785
|
+
self,
|
|
1786
|
+
layer: int,
|
|
1787
|
+
origin: Point3,
|
|
1788
|
+
u_edge: Point3,
|
|
1789
|
+
v_edge: Point3,
|
|
1790
|
+
*,
|
|
1791
|
+
id: str,
|
|
1792
|
+
**style: Style,
|
|
1793
|
+
) -> None:
|
|
1794
|
+
"""Reserve an empty group occupying a rectangle of a world plane.
|
|
1795
|
+
|
|
1796
|
+
The group carries the affine transform that maps content coordinates in
|
|
1797
|
+
:math:`[0,1]^2` onto the projected rectangle, so flat SVG content sits
|
|
1798
|
+
*in* the plane -- correctly foreshortened and sheared -- rather than on
|
|
1799
|
+
top of the picture. Nothing is drawn: this package does not parse or
|
|
1800
|
+
embed foreign SVG. A consumer fills the group by ``id``, normalizing
|
|
1801
|
+
its content to the unit square.
|
|
1802
|
+
|
|
1803
|
+
Because the group participates in the layer stack like anything else,
|
|
1804
|
+
content placed in it can be drawn over the slab it lies on and under the
|
|
1805
|
+
beam that crosses it. The rectangle also grows the fitted viewBox, so
|
|
1806
|
+
the embedded content is never clipped.
|
|
1807
|
+
|
|
1808
|
+
Args:
|
|
1809
|
+
layer: Draw order, as for every other primitive.
|
|
1810
|
+
origin: World point for content ``(0, 0)`` -- the top-left corner,
|
|
1811
|
+
since SVG ``y`` grows downward.
|
|
1812
|
+
u_edge: World vector along content ``+x``; its length is the width.
|
|
1813
|
+
v_edge: World vector along content ``+y`` (downward); its length is
|
|
1814
|
+
the height.
|
|
1815
|
+
id: Handle a consumer uses to find and fill the group. Required.
|
|
1816
|
+
|
|
1817
|
+
See :meth:`Camera.plane_matrix` for the geometry, including why this is
|
|
1818
|
+
exact for an orthographic camera and would not be for a perspective one.
|
|
1819
|
+
"""
|
|
1820
|
+
self._add("plane", layer, origin, u_edge, v_edge, id=id, **style)
|
|
1821
|
+
|
|
1822
|
+
def slot(
|
|
1823
|
+
self,
|
|
1824
|
+
layer: int,
|
|
1825
|
+
pt3: Point3,
|
|
1826
|
+
w: float,
|
|
1827
|
+
h: float,
|
|
1828
|
+
*,
|
|
1829
|
+
id: str,
|
|
1830
|
+
align: Align = "center",
|
|
1831
|
+
dx: float = 0.0,
|
|
1832
|
+
dy: float = 0.0,
|
|
1833
|
+
**style: Style,
|
|
1834
|
+
) -> None:
|
|
1835
|
+
"""Reserve an empty, screen-aligned group anchored at a projected world point.
|
|
1836
|
+
|
|
1837
|
+
The screen-space sibling of :meth:`plane`: where a plane makes content
|
|
1838
|
+
lie *in* the scene, a slot keeps it upright and unforeshortened -- a
|
|
1839
|
+
label, an equation, an inset -- while pinning it to a point of the
|
|
1840
|
+
geometry. Nothing is drawn, and this package does not embed foreign
|
|
1841
|
+
SVG; a consumer fills the group by ``id``.
|
|
1842
|
+
|
|
1843
|
+
The group is translated to the anchor, ``cam.at(pt3)`` offset by
|
|
1844
|
+
``(dx, dy)``, and records ``align`` as ``data-align``, so a consumer can
|
|
1845
|
+
line its content up against the anchor at whatever size it ends up. A
|
|
1846
|
+
``w`` by ``h`` box aligned the same way grows the fitted viewBox, so
|
|
1847
|
+
content of that size is not clipped. Each camera projects the anchor
|
|
1848
|
+
afresh, so the slot follows the geometry.
|
|
1849
|
+
|
|
1850
|
+
Args:
|
|
1851
|
+
layer: Draw order, so geometry on a higher layer can cover the content.
|
|
1852
|
+
pt3: World point the slot is pinned to.
|
|
1853
|
+
w: Width of the box to reserve, in scene units.
|
|
1854
|
+
h: Height of the box to reserve, in scene units.
|
|
1855
|
+
id: Handle a consumer uses to find and fill the group. Required.
|
|
1856
|
+
align: Which point of the box sits on the anchor: ``"west"`` puts
|
|
1857
|
+
the anchor at the middle of the box's left edge, so the content
|
|
1858
|
+
extends to the right.
|
|
1859
|
+
dx: Screen offset of the anchor, in scene units.
|
|
1860
|
+
dy: Screen offset of the anchor, in scene units, downward.
|
|
1861
|
+
"""
|
|
1862
|
+
if align not in _ALIGN:
|
|
1863
|
+
raise ValueError(f"unknown align {align!r}; expected one of {sorted(_ALIGN)}")
|
|
1864
|
+
self._add("slot", layer, pt3, w, h, id=id, align=align, dx=dx, dy=dy, **style)
|
|
1865
|
+
|
|
1866
|
+
def silhouette(self, layer: int, solid: Iterable[Face] | Points3, **style: Style) -> None:
|
|
1867
|
+
"""Fill the projected outline of a convex solid as one polygon.
|
|
1868
|
+
|
|
1869
|
+
Drawing a convex solid's visible walls one polygon each leaves hairline
|
|
1870
|
+
seams where neighbouring walls meet, because each edge is anti-aliased
|
|
1871
|
+
against the background separately. Every visible wall lies inside the
|
|
1872
|
+
silhouette, so filling the silhouette in the wall colour and drawing the
|
|
1873
|
+
cap over it gives the same picture with no seams::
|
|
1874
|
+
|
|
1875
|
+
fin = prism_faces(footprint, 0.0, 0.3)
|
|
1876
|
+
scene.silhouette(30, fin, fill="#b98a40", id="lead-walls")
|
|
1877
|
+
scene.faces(30, [f for f in fin if f.name == "+z"], fill="#e2b56a")
|
|
1878
|
+
|
|
1879
|
+
The outline is the convex hull of the projected vertices, so it is only
|
|
1880
|
+
the silhouette of a convex solid. Each camera recomputes it.
|
|
1881
|
+
|
|
1882
|
+
Args:
|
|
1883
|
+
layer: Draw order.
|
|
1884
|
+
solid: Faces of the solid, or its world-space vertices.
|
|
1885
|
+
**style: SVG presentation attributes of the polygon.
|
|
1886
|
+
"""
|
|
1887
|
+
given = list(solid)
|
|
1888
|
+
self._add("silhouette", layer, given, **style)
|
|
1889
|
+
|
|
1890
|
+
def prism_walls(
|
|
1891
|
+
self, layer: int, footprint: Points2, z0: float, z1: float, **style: Style
|
|
1892
|
+
) -> None:
|
|
1893
|
+
"""Draw the camera-facing walls of an extruded footprint as one seamless shape.
|
|
1894
|
+
|
|
1895
|
+
Each maximal run of consecutive facing walls becomes one strip -- along
|
|
1896
|
+
the base, then back along the top -- so no seam shows between
|
|
1897
|
+
neighbouring walls, however finely a curved footprint is faceted. All
|
|
1898
|
+
strips go into a single ``<path>``. Draw the cap over it::
|
|
1899
|
+
|
|
1900
|
+
gate = annulus_sector((0, 0), 2.6, 3.0, 20, 160)
|
|
1901
|
+
scene.prism_walls(30, gate, 0.0, 0.26, fill="#4a5059", id="gate-walls")
|
|
1902
|
+
scene.faces(30, prism_faces(gate, 0.0, 0.26)[:1], fill="#737a84", id="gate")
|
|
1903
|
+
|
|
1904
|
+
Works for non-convex footprints, which :meth:`silhouette` does not. With
|
|
1905
|
+
an unstroked wall style and a cap facing the camera, walls-then-cap is
|
|
1906
|
+
exact at any height: along any view ray the cap is never behind a wall,
|
|
1907
|
+
and walls hiding other walls of the same solid are indistinguishable
|
|
1908
|
+
when they share one fill. Only a stroke can show an edge of a wall that
|
|
1909
|
+
another wall of the same solid hides -- negligible for a low extrusion,
|
|
1910
|
+
visible for a tall non-convex one. There is no depth sort to fix that,
|
|
1911
|
+
by design.
|
|
1912
|
+
|
|
1913
|
+
Args:
|
|
1914
|
+
layer: Draw order.
|
|
1915
|
+
footprint: Simple polygon, as for :func:`~vecview.shapes.prism_faces`.
|
|
1916
|
+
z0: Height of the base.
|
|
1917
|
+
z1: Height of the top.
|
|
1918
|
+
**style: SVG presentation attributes of the path.
|
|
1919
|
+
|
|
1920
|
+
Culling uses the camera that renders, so each camera draws the walls it
|
|
1921
|
+
faces.
|
|
1922
|
+
"""
|
|
1923
|
+
prism_faces(footprint, z0, z1) # rejects a footprint that is not a simple polygon
|
|
1924
|
+
self._add("prism_walls", layer, footprint, z0, z1, **style)
|
|
1925
|
+
|
|
1926
|
+
def arrow(
|
|
1927
|
+
self,
|
|
1928
|
+
layer: int,
|
|
1929
|
+
origin: Point3,
|
|
1930
|
+
direction: Point3,
|
|
1931
|
+
length: float,
|
|
1932
|
+
*,
|
|
1933
|
+
normal: Point3 | Literal["camera"],
|
|
1934
|
+
shaft_w: float,
|
|
1935
|
+
head_w: float,
|
|
1936
|
+
head_len: float,
|
|
1937
|
+
pivot: Pivot = "tail",
|
|
1938
|
+
**style: Style,
|
|
1939
|
+
) -> None:
|
|
1940
|
+
"""Flat arrow, as :func:`~vecview.shapes.arrow_shape`, drawn as a polygon.
|
|
1941
|
+
|
|
1942
|
+
``normal="camera"`` turns the arrow about its own axis to show the
|
|
1943
|
+
widest face it can, so it reads from any viewpoint -- a spin along
|
|
1944
|
+
``z``, say. The normal is resolved from the camera that renders, so
|
|
1945
|
+
every camera sees the arrow turned toward it. Computing that normal
|
|
1946
|
+
yourself from ``cam.view`` would bake in one camera's answer.
|
|
1947
|
+
|
|
1948
|
+
Args:
|
|
1949
|
+
normal: Normal of the plane the arrow lies flat in, or ``"camera"``.
|
|
1950
|
+
The latter needs a :class:`ParallelCamera`.
|
|
1951
|
+
|
|
1952
|
+
Raises:
|
|
1953
|
+
ValueError: If ``normal="camera"`` and the arrow points along the
|
|
1954
|
+
projection ray, where it has no face to show.
|
|
1955
|
+
|
|
1956
|
+
The remaining arguments are those of :func:`~vecview.shapes.arrow_shape`.
|
|
1957
|
+
"""
|
|
1958
|
+
if isinstance(normal, str) and normal != "camera":
|
|
1959
|
+
raise ValueError(f"normal must be a vector or 'camera', got {normal!r}")
|
|
1960
|
+
self._add(
|
|
1961
|
+
"arrow",
|
|
1962
|
+
layer,
|
|
1963
|
+
origin,
|
|
1964
|
+
direction,
|
|
1965
|
+
length,
|
|
1966
|
+
normal=normal,
|
|
1967
|
+
shaft_w=shaft_w,
|
|
1968
|
+
head_w=head_w,
|
|
1969
|
+
head_len=head_len,
|
|
1970
|
+
pivot=pivot,
|
|
1971
|
+
**style,
|
|
1972
|
+
)
|
|
1973
|
+
|
|
1974
|
+
def gaussian(
|
|
1975
|
+
self,
|
|
1976
|
+
layer: int,
|
|
1977
|
+
center: Point3,
|
|
1978
|
+
u: Point3,
|
|
1979
|
+
v: Point3,
|
|
1980
|
+
a: float,
|
|
1981
|
+
b: float,
|
|
1982
|
+
*,
|
|
1983
|
+
id: str,
|
|
1984
|
+
color: str,
|
|
1985
|
+
opacity: float = 1.0,
|
|
1986
|
+
extent: float = 2.0,
|
|
1987
|
+
stops: int = 9,
|
|
1988
|
+
**style: Style,
|
|
1989
|
+
) -> None:
|
|
1990
|
+
"""A soft Gaussian spot lying in a world plane, as one gradient-filled polygon.
|
|
1991
|
+
|
|
1992
|
+
The opacity follows ``exp(-(s/a)**2 - (t/b)**2)`` along the in-plane
|
|
1993
|
+
axes ``u`` and ``v``, so ``a`` and ``b`` are the ``1/e`` half-widths. A
|
|
1994
|
+
radial gradient mapped through the plane's affine transform does this in
|
|
1995
|
+
one element, foreshortened with the plane, where nested translucent
|
|
1996
|
+
ellipses would take many and show their steps.
|
|
1997
|
+
|
|
1998
|
+
The profile is shifted to reach exactly zero at ``extent`` half-widths,
|
|
1999
|
+
where the polygon ends, so there is no visible rim. The gradient goes
|
|
2000
|
+
into ``<defs>`` as ``{id}-profile``.
|
|
2001
|
+
|
|
2002
|
+
Args:
|
|
2003
|
+
layer: Draw order.
|
|
2004
|
+
center: Centre of the spot.
|
|
2005
|
+
u: Direction of the ``a`` axis.
|
|
2006
|
+
v: Direction of the ``b`` axis; perpendicular to ``u``.
|
|
2007
|
+
a: ``1/e`` half-width along ``u``.
|
|
2008
|
+
b: ``1/e`` half-width along ``v``.
|
|
2009
|
+
id: Id of the polygon. Required, since the gradient id derives from it.
|
|
2010
|
+
color: Fill colour.
|
|
2011
|
+
opacity: Opacity at the centre.
|
|
2012
|
+
extent: Radius drawn, in half-widths.
|
|
2013
|
+
stops: Gradient stops sampling the profile; more is smoother.
|
|
2014
|
+
|
|
2015
|
+
Raises:
|
|
2016
|
+
TypeError: For a camera that is not a :class:`ParallelCamera`; only
|
|
2017
|
+
an affine projection maps a gradient through a plane exactly.
|
|
2018
|
+
|
|
2019
|
+
Note that ``cairosvg`` renders a gradient *fill* correctly; it is a
|
|
2020
|
+
gradient *mask* that it silently drops.
|
|
2021
|
+
"""
|
|
2022
|
+
if stops < 2:
|
|
2023
|
+
raise ValueError("a gradient needs at least two stops")
|
|
2024
|
+
self._add(
|
|
2025
|
+
"gaussian",
|
|
2026
|
+
layer,
|
|
2027
|
+
center,
|
|
2028
|
+
u,
|
|
2029
|
+
v,
|
|
2030
|
+
a,
|
|
2031
|
+
b,
|
|
2032
|
+
id=id,
|
|
2033
|
+
color=color,
|
|
2034
|
+
opacity=opacity,
|
|
2035
|
+
extent=extent,
|
|
2036
|
+
stops=stops,
|
|
2037
|
+
**style,
|
|
2038
|
+
)
|
|
2039
|
+
|
|
2040
|
+
def sphere(
|
|
2041
|
+
self,
|
|
2042
|
+
layer: int,
|
|
2043
|
+
center: Point3,
|
|
2044
|
+
radius: float,
|
|
2045
|
+
*,
|
|
2046
|
+
highlight: str | None = None,
|
|
2047
|
+
**style: Style,
|
|
2048
|
+
) -> None:
|
|
2049
|
+
"""A sphere, drawn as its exact outline: one ``<circle>`` or ``<ellipse>``.
|
|
2050
|
+
|
|
2051
|
+
A parallel projection maps a sphere onto an ellipse -- a circle for an
|
|
2052
|
+
orthographic camera, an ellipse for an oblique one -- so the outline is
|
|
2053
|
+
exact and a single native shape, not a polygon.
|
|
2054
|
+
|
|
2055
|
+
Args:
|
|
2056
|
+
layer: Draw order.
|
|
2057
|
+
center: Centre of the sphere.
|
|
2058
|
+
radius: Radius, in world units.
|
|
2059
|
+
highlight: A lighter colour for a glossy ball: the ``fill`` becomes
|
|
2060
|
+
a radial gradient from ``highlight`` near the upper left to
|
|
2061
|
+
``fill`` at the rim. This is a fill style, not a lighting model
|
|
2062
|
+
-- the highlight sits in the same place on screen whatever the
|
|
2063
|
+
camera. One gradient per colour pair is shared by every sphere
|
|
2064
|
+
that uses it, under the id ``ball-{fill}-{highlight}``.
|
|
2065
|
+
**style: SVG presentation attributes; ``fill`` is required with
|
|
2066
|
+
``highlight``.
|
|
2067
|
+
"""
|
|
2068
|
+
_check_highlight(style, highlight, needs_id=False)
|
|
2069
|
+
self._add("sphere", layer, center, radius, highlight=highlight, **style)
|
|
2070
|
+
|
|
2071
|
+
def cylinder(
|
|
2072
|
+
self,
|
|
2073
|
+
layer: int,
|
|
2074
|
+
p0: Point3,
|
|
2075
|
+
p1: Point3,
|
|
2076
|
+
radius: float,
|
|
2077
|
+
*,
|
|
2078
|
+
r1: float | None = None,
|
|
2079
|
+
ends: bool = True,
|
|
2080
|
+
end_style: Mapping[str, Style] | None = None,
|
|
2081
|
+
highlight: str | None = None,
|
|
2082
|
+
slices: int = 1,
|
|
2083
|
+
**style: Style,
|
|
2084
|
+
) -> None:
|
|
2085
|
+
"""A cylinder from ``p0`` to ``p1``, or a frustum when ``r1`` differs.
|
|
2086
|
+
|
|
2087
|
+
The outline is exact and compact: two straight sides and two elliptical
|
|
2088
|
+
arcs in one ``<path>``, since a parallel projection maps the end circles
|
|
2089
|
+
to ellipses whose common tangents have a closed form. The end disk that
|
|
2090
|
+
faces the camera, if any, is drawn over the body as a native
|
|
2091
|
+
``<ellipse>`` (or ``<circle>``). Everything goes into one ``<g>``, so
|
|
2092
|
+
the solid is one object in Inkscape and one element for
|
|
2093
|
+
:meth:`sort_by_depth`, keyed by its axis midpoint.
|
|
2094
|
+
|
|
2095
|
+
Args:
|
|
2096
|
+
layer: Draw order.
|
|
2097
|
+
p0: Centre of the first end.
|
|
2098
|
+
p1: Centre of the second end.
|
|
2099
|
+
radius: Radius at ``p0``.
|
|
2100
|
+
r1: Radius at ``p1``; defaults to ``radius``. ``0`` is a cone, for
|
|
2101
|
+
which :meth:`cone` reads better.
|
|
2102
|
+
ends: Whether to draw the end disks. ``False`` leaves an open tube,
|
|
2103
|
+
which is what a bond hidden inside two atoms wants.
|
|
2104
|
+
end_style: Presentation attributes for the end disks, over
|
|
2105
|
+
``style`` -- a lighter ``fill`` for a flat-shaded cap, say.
|
|
2106
|
+
highlight: A lighter colour shading the body across its width,
|
|
2107
|
+
lightest toward the upper left: a fill style, not a lighting
|
|
2108
|
+
model. Needs ``fill`` and ``id``; the gradient is ``{id}-shade``.
|
|
2109
|
+
slices: Cut the solid into this many lengths along its axis, each
|
|
2110
|
+
its own ``<g>`` keyed by its own midpoint, for a long cylinder
|
|
2111
|
+
in a layer passed to :meth:`sort_by_depth`. Keyed by its
|
|
2112
|
+
centre alone, a core with a coil wound round it sorts wholly in
|
|
2113
|
+
front of the far turns and wholly behind the near ones; sliced,
|
|
2114
|
+
each turn meets the slice it wraps. The slices overlap a little
|
|
2115
|
+
and the outline is stroked along the sides only, so the result
|
|
2116
|
+
looks like one solid -- except with a translucent fill, where
|
|
2117
|
+
the overlaps show.
|
|
2118
|
+
**style: SVG presentation attributes. An ``id`` goes on the group;
|
|
2119
|
+
the body takes ``{id}-body`` and the end disks ``{id}-body-end0``
|
|
2120
|
+
and ``{id}-body-end1``. Sliced, the groups are ``{id}-0``,
|
|
2121
|
+
``{id}-1``, ... with ``{id}-{k}-body`` and ``{id}-{k}-edge``.
|
|
2122
|
+
|
|
2123
|
+
Raises:
|
|
2124
|
+
ValueError: If ``p0 == p1``, or for a negative radius.
|
|
2125
|
+
"""
|
|
2126
|
+
_check_axis(p0, p1, radius, radius if r1 is None else r1)
|
|
2127
|
+
_check_highlight(style, highlight, needs_id=True)
|
|
2128
|
+
if slices < 1:
|
|
2129
|
+
raise ValueError(f"slices must be at least 1, got {slices}")
|
|
2130
|
+
self._add(
|
|
2131
|
+
"cylinder",
|
|
2132
|
+
layer,
|
|
2133
|
+
p0,
|
|
2134
|
+
p1,
|
|
2135
|
+
radius,
|
|
2136
|
+
r1=r1,
|
|
2137
|
+
ends=ends,
|
|
2138
|
+
end_style=end_style,
|
|
2139
|
+
highlight=highlight,
|
|
2140
|
+
slices=slices,
|
|
2141
|
+
**style,
|
|
2142
|
+
)
|
|
2143
|
+
|
|
2144
|
+
def cone(
|
|
2145
|
+
self,
|
|
2146
|
+
layer: int,
|
|
2147
|
+
base: Point3,
|
|
2148
|
+
apex: Point3,
|
|
2149
|
+
radius: float,
|
|
2150
|
+
*,
|
|
2151
|
+
end: bool = True,
|
|
2152
|
+
end_style: Mapping[str, Style] | None = None,
|
|
2153
|
+
highlight: str | None = None,
|
|
2154
|
+
**style: Style,
|
|
2155
|
+
) -> None:
|
|
2156
|
+
"""A cone from a disk of ``radius`` at ``base`` to a point at ``apex``.
|
|
2157
|
+
|
|
2158
|
+
:meth:`cylinder` with ``r1=0``, and the same exact outline: the two
|
|
2159
|
+
tangents from the apex and one elliptical arc. ``end`` draws the base
|
|
2160
|
+
disk when it faces the camera.
|
|
2161
|
+
"""
|
|
2162
|
+
_check_axis(base, apex, radius, 0.0)
|
|
2163
|
+
_check_highlight(style, highlight, needs_id=True)
|
|
2164
|
+
self._add(
|
|
2165
|
+
"cone",
|
|
2166
|
+
layer,
|
|
2167
|
+
base,
|
|
2168
|
+
apex,
|
|
2169
|
+
radius,
|
|
2170
|
+
end=end,
|
|
2171
|
+
end_style=end_style,
|
|
2172
|
+
highlight=highlight,
|
|
2173
|
+
**style,
|
|
2174
|
+
)
|
|
2175
|
+
|
|
2176
|
+
def arrow3d(
|
|
2177
|
+
self,
|
|
2178
|
+
layer: int,
|
|
2179
|
+
origin: Point3,
|
|
2180
|
+
direction: Point3,
|
|
2181
|
+
length: float,
|
|
2182
|
+
*,
|
|
2183
|
+
shaft_r: float,
|
|
2184
|
+
head_r: float,
|
|
2185
|
+
head_len: float,
|
|
2186
|
+
pivot: Pivot = "tail",
|
|
2187
|
+
end_style: Mapping[str, Style] | None = None,
|
|
2188
|
+
highlight: str | None = None,
|
|
2189
|
+
**style: Style,
|
|
2190
|
+
) -> None:
|
|
2191
|
+
"""A solid arrow: a cylindrical shaft and a conical head, in one ``<g>``.
|
|
2192
|
+
|
|
2193
|
+
Unlike the flat :meth:`arrow` it reads as a solid from every side, so it
|
|
2194
|
+
suits a field of spins seen at an angle. The shaft and head are ordered
|
|
2195
|
+
within the group by which end is nearer the camera, and the disks that
|
|
2196
|
+
face it -- the back of the head, the tail of the shaft -- are drawn.
|
|
2197
|
+
|
|
2198
|
+
Args:
|
|
2199
|
+
origin: Tail of the arrow, or its midpoint when ``pivot="mid"``.
|
|
2200
|
+
direction: Direction the head points.
|
|
2201
|
+
length: Total length, tail to tip.
|
|
2202
|
+
shaft_r: Radius of the shaft.
|
|
2203
|
+
head_r: Radius of the head at its base.
|
|
2204
|
+
head_len: Length of the head, measured back from the tip.
|
|
2205
|
+
end_style: Presentation attributes for the visible disks.
|
|
2206
|
+
highlight: Shade both parts as :meth:`cylinder` does. Needs an
|
|
2207
|
+
``id``; the parts are ``{id}-shaft`` and ``{id}-head``.
|
|
2208
|
+
**style: SVG presentation attributes.
|
|
2209
|
+
|
|
2210
|
+
Raises:
|
|
2211
|
+
ValueError: For a zero ``direction``.
|
|
2212
|
+
"""
|
|
2213
|
+
if not unit(direction).any():
|
|
2214
|
+
raise ValueError("an arrow needs a non-zero direction")
|
|
2215
|
+
_check_highlight(style, highlight, needs_id=True)
|
|
2216
|
+
self._add(
|
|
2217
|
+
"arrow3d",
|
|
2218
|
+
layer,
|
|
2219
|
+
origin,
|
|
2220
|
+
direction,
|
|
2221
|
+
length,
|
|
2222
|
+
shaft_r=shaft_r,
|
|
2223
|
+
head_r=head_r,
|
|
2224
|
+
head_len=head_len,
|
|
2225
|
+
pivot=pivot,
|
|
2226
|
+
end_style=end_style,
|
|
2227
|
+
highlight=highlight,
|
|
2228
|
+
**style,
|
|
2229
|
+
)
|
|
2230
|
+
|
|
2231
|
+
def tube(
|
|
2232
|
+
self,
|
|
2233
|
+
layer: int,
|
|
2234
|
+
pts3: Points3,
|
|
2235
|
+
radius: float,
|
|
2236
|
+
*,
|
|
2237
|
+
chunk: int = 4,
|
|
2238
|
+
**style: Style,
|
|
2239
|
+
) -> None:
|
|
2240
|
+
"""A tube of ``radius`` along a world-space curve -- a coil, a field line, a bond path.
|
|
2241
|
+
|
|
2242
|
+
Drawn as wide strokes rather than as a mesh: for an orthographic
|
|
2243
|
+
camera, a tube projects to the curve thickened by the projected radius,
|
|
2244
|
+
which a round-joined stroke is exactly. ``fill`` is the colour of the
|
|
2245
|
+
tube and ``stroke`` its outline, drawn as a wider stroke underneath, so
|
|
2246
|
+
the call reads like any filled shape. For an oblique camera the width
|
|
2247
|
+
is the mean of the projected radius over directions, an approximation.
|
|
2248
|
+
|
|
2249
|
+
The curve is cut into pieces of ``chunk`` segments, one ``<g>`` each, so
|
|
2250
|
+
in a layer passed to :meth:`sort_by_depth` a tube can pass over and
|
|
2251
|
+
under itself and others, as a coil does. Neighbouring pieces overlap,
|
|
2252
|
+
and the outline of each stops a segment short of its body, so no seam
|
|
2253
|
+
shows where they meet. The tube's own two ends are
|
|
2254
|
+
square.
|
|
2255
|
+
|
|
2256
|
+
Args:
|
|
2257
|
+
layer: Draw order.
|
|
2258
|
+
pts3: The centre line, shape ``(n, 3)``, with ``n >= 2``.
|
|
2259
|
+
radius: Tube radius, in world units.
|
|
2260
|
+
chunk: Segments per piece; shorter sorts more finely.
|
|
2261
|
+
**style: ``fill`` (default black) and ``stroke`` (default none)
|
|
2262
|
+
colour the tube and its outline, ``stroke_width`` (default
|
|
2263
|
+
``1``) is the outline width, and anything else -- ``opacity``,
|
|
2264
|
+
say -- goes on each piece. An ``id`` is suffixed per piece:
|
|
2265
|
+
``coil-0``, ``coil-1``, ...
|
|
2266
|
+
"""
|
|
2267
|
+
if chunk < 1:
|
|
2268
|
+
raise ValueError(f"chunk must be at least 1, got {chunk}")
|
|
2269
|
+
if len(as_points(pts3)) < 2:
|
|
2270
|
+
raise ValueError("a tube needs at least two points")
|
|
2271
|
+
self._add("tube", layer, pts3, radius, chunk=chunk, **style)
|
|
2272
|
+
|
|
2273
|
+
def edges(
|
|
2274
|
+
self,
|
|
2275
|
+
layer: int,
|
|
2276
|
+
faces: Iterable[Face],
|
|
2277
|
+
*,
|
|
2278
|
+
back: Mapping[str, Style] | None = None,
|
|
2279
|
+
back_layer: int | None = None,
|
|
2280
|
+
separate: bool = False,
|
|
2281
|
+
trim: float = 0.0,
|
|
2282
|
+
**style: Style,
|
|
2283
|
+
) -> None:
|
|
2284
|
+
"""The edges of a convex solid, split into visible and hidden.
|
|
2285
|
+
|
|
2286
|
+
An edge is visible when either face it bounds faces the camera, which is
|
|
2287
|
+
exact for a convex solid: a unit cell, a Brillouin zone, a coordination
|
|
2288
|
+
polyhedron. Visible edges go into one ``<path>`` with ``style``.
|
|
2289
|
+
Hidden ones are dropped unless ``back`` is given, in which case they
|
|
2290
|
+
form a second path styled ``{**style, **back}`` -- the crystallographer's
|
|
2291
|
+
dashed back edges::
|
|
2292
|
+
|
|
2293
|
+
cell = vecview.box_faces((0, 0, 0), (1, 1, 1))
|
|
2294
|
+
scene.edges(40, cell, back={"stroke_dasharray": "4 3"}, stroke="#333")
|
|
2295
|
+
|
|
2296
|
+
Args:
|
|
2297
|
+
layer: Draw order of the visible edges.
|
|
2298
|
+
faces: Faces of the solid, sharing vertices exactly where they meet.
|
|
2299
|
+
back: Style overrides for the hidden edges, or ``None`` to omit them.
|
|
2300
|
+
back_layer: Draw order of the hidden edges; defaults to ``layer``.
|
|
2301
|
+
Put it below a translucent solid's faces so they veil it.
|
|
2302
|
+
separate: Emit one ``<path>`` per edge, each keyed by its own
|
|
2303
|
+
midpoint, so that in a layer passed to :meth:`sort_by_depth`
|
|
2304
|
+
the edges interleave with other objects -- the cell edges of a
|
|
2305
|
+
crystal among its atoms.
|
|
2306
|
+
trim: Shorten every edge by this much, in world units, at both
|
|
2307
|
+
ends, so it stops at the surface of an atom or marker sitting
|
|
2308
|
+
on each vertex. A line through the centre of a sphere cannot
|
|
2309
|
+
be depth-sorted against it, since part of it is inside; one
|
|
2310
|
+
that starts on the surface can.
|
|
2311
|
+
**style: SVG presentation attributes; ``fill`` defaults to none.
|
|
2312
|
+
An ``id`` becomes ``{id}-front`` and ``{id}-back``, suffixed
|
|
2313
|
+
``-0``, ``-1``, ... per edge when ``separate``.
|
|
2314
|
+
|
|
2315
|
+
Culling uses the camera that renders, so each camera splits afresh.
|
|
2316
|
+
"""
|
|
2317
|
+
given = list(faces)
|
|
2318
|
+
base = style.pop("id", None)
|
|
2319
|
+
style.setdefault("fill", "none")
|
|
2320
|
+
self._add(
|
|
2321
|
+
"edges",
|
|
2322
|
+
layer,
|
|
2323
|
+
given,
|
|
2324
|
+
back=back,
|
|
2325
|
+
back_layer=back_layer,
|
|
2326
|
+
separate=separate,
|
|
2327
|
+
trim=trim,
|
|
2328
|
+
**({} if base is None else {"id": base}),
|
|
2329
|
+
**style,
|
|
2330
|
+
)
|
|
2331
|
+
|
|
2332
|
+
def sphere_curve(
|
|
2333
|
+
self,
|
|
2334
|
+
layer: int,
|
|
2335
|
+
center: Point3,
|
|
2336
|
+
pts3: Points3,
|
|
2337
|
+
*,
|
|
2338
|
+
closed: bool = False,
|
|
2339
|
+
back: Mapping[str, Style] | None = None,
|
|
2340
|
+
back_layer: int | None = None,
|
|
2341
|
+
**style: Style,
|
|
2342
|
+
) -> None:
|
|
2343
|
+
"""A curve on a sphere's surface, split where it passes behind the sphere.
|
|
2344
|
+
|
|
2345
|
+
For the equator and meridians of a Bloch sphere or a globe. A point
|
|
2346
|
+
``p`` on the sphere about ``center`` faces the camera when
|
|
2347
|
+
``(p - center) . view >= 0``; the curve is cut exactly where that
|
|
2348
|
+
changes sign. The visible runs form one ``<path>`` with ``style``;
|
|
2349
|
+
the hidden ones are dropped unless ``back`` is given, as for
|
|
2350
|
+
:meth:`edges`.
|
|
2351
|
+
|
|
2352
|
+
Args:
|
|
2353
|
+
layer: Draw order of the visible part.
|
|
2354
|
+
center: Centre of the sphere the curve lies on.
|
|
2355
|
+
pts3: The curve, shape ``(n, 3)``; :func:`~vecview.shapes.circle_shape`
|
|
2356
|
+
and :func:`~vecview.shapes.arc_shape` give the usual ones.
|
|
2357
|
+
closed: Join the last point back to the first, as for a circle.
|
|
2358
|
+
back: Style overrides for the hidden part, or ``None`` to omit it.
|
|
2359
|
+
back_layer: Draw order of the hidden part; defaults to ``layer``.
|
|
2360
|
+
**style: SVG presentation attributes; ``fill`` defaults to none.
|
|
2361
|
+
An ``id`` becomes ``{id}-front`` and ``{id}-back``.
|
|
2362
|
+
"""
|
|
2363
|
+
style.setdefault("fill", "none")
|
|
2364
|
+
self._add(
|
|
2365
|
+
"sphere_curve",
|
|
2366
|
+
layer,
|
|
2367
|
+
center,
|
|
2368
|
+
pts3,
|
|
2369
|
+
closed=closed,
|
|
2370
|
+
back=back,
|
|
2371
|
+
back_layer=back_layer,
|
|
2372
|
+
**style,
|
|
2373
|
+
)
|
|
2374
|
+
|
|
2375
|
+
def text(
|
|
2376
|
+
self,
|
|
2377
|
+
layer: int,
|
|
2378
|
+
pt3: Point3,
|
|
2379
|
+
s: TextContent,
|
|
2380
|
+
dx: float = 0.0,
|
|
2381
|
+
dy: float = 0.0,
|
|
2382
|
+
size: float = 22.0,
|
|
2383
|
+
**style: Style,
|
|
2384
|
+
) -> None:
|
|
2385
|
+
"""Text anchored at a projected world point, offset by ``(dx, dy)`` on screen.
|
|
2386
|
+
|
|
2387
|
+
``s`` is a string, or a sequence of ``svg.TSpan`` runs for mixed styling
|
|
2388
|
+
such as a subscript::
|
|
2389
|
+
|
|
2390
|
+
scene.text(30, tip, [svg.TSpan(text="k"), svg.TSpan(text="x", baseline_shift="sub")])
|
|
2391
|
+
"""
|
|
2392
|
+
self._add("text", layer, pt3, s, dx, dy, size, **style)
|
|
2393
|
+
|
|
2394
|
+
def rect2d(
|
|
2395
|
+
self,
|
|
2396
|
+
layer: int,
|
|
2397
|
+
x: float,
|
|
2398
|
+
y: float,
|
|
2399
|
+
w: float,
|
|
2400
|
+
h: float,
|
|
2401
|
+
grow: bool = False,
|
|
2402
|
+
**style: Style,
|
|
2403
|
+
) -> None:
|
|
2404
|
+
"""Rectangle in screen coordinates -- a backdrop, glow, or gradient wash.
|
|
2405
|
+
|
|
2406
|
+
Excluded from the bounding box by default, so a soft glow extending past
|
|
2407
|
+
the geometry does not inflate the fitted viewBox.
|
|
2408
|
+
"""
|
|
2409
|
+
self._add("rect2d", layer, x, y, w, h, grow, **style)
|
|
2410
|
+
|
|
2411
|
+
def text2d(
|
|
2412
|
+
self,
|
|
2413
|
+
layer: int,
|
|
2414
|
+
x: float,
|
|
2415
|
+
y: float,
|
|
2416
|
+
s: TextContent,
|
|
2417
|
+
size: float = 22.0,
|
|
2418
|
+
grow: bool = True,
|
|
2419
|
+
**style: Style,
|
|
2420
|
+
) -> None:
|
|
2421
|
+
"""Text in screen coordinates; ``s`` as for :meth:`text`."""
|
|
2422
|
+
style.setdefault("font_family", DEFAULT_FONT)
|
|
2423
|
+
style.setdefault("fill", DEFAULT_TEXT_FILL)
|
|
2424
|
+
self._add("text2d", layer, x, y, s, size, grow, **style)
|
|
2425
|
+
|
|
2426
|
+
|
|
2427
|
+
__all__ = ["DEFAULT_FONT", "DEFAULT_TEXT_FILL", "Align", "CameraRef", "Scene", "TextContent"]
|