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/shapes.py
ADDED
|
@@ -0,0 +1,571 @@
|
|
|
1
|
+
"""World-space glyph geometry.
|
|
2
|
+
|
|
3
|
+
Every function here returns plain world-space points -- an ``(n, 3)`` array, or
|
|
4
|
+
a list of :class:`Face` for solids. Nothing here knows about a camera, a style,
|
|
5
|
+
or SVG. That split is deliberate: geometry stays testable as numbers, and the
|
|
6
|
+
same polygon can be drawn twice with different fills, or reused as a clip path.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Iterable
|
|
12
|
+
from itertools import combinations
|
|
13
|
+
from typing import Literal, NamedTuple
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
import numpy.typing as npt
|
|
17
|
+
|
|
18
|
+
from vecview._types import Array, Point3, Points2, Points3
|
|
19
|
+
from vecview._vec import as_points, basis_for, unit
|
|
20
|
+
|
|
21
|
+
FaceName = Literal["-x", "+x", "-y", "+y", "-z", "+z"]
|
|
22
|
+
|
|
23
|
+
Pivot = Literal["tail", "mid"]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Face(NamedTuple):
|
|
27
|
+
"""One planar polygon of a solid, with the outward normal it was built from.
|
|
28
|
+
|
|
29
|
+
Carrying the normal alongside the points is what lets
|
|
30
|
+
:meth:`~vecview.camera.Camera.visible` decide which walls of a box to draw
|
|
31
|
+
without the caller reasoning about which octant the camera sits in.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
name: str
|
|
35
|
+
points: Array
|
|
36
|
+
normal: Array
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def in_plane_dir(
|
|
40
|
+
angle_deg: float, u: Point3 = (1.0, 0.0, 0.0), v: Point3 = (0.0, 1.0, 0.0)
|
|
41
|
+
) -> Array:
|
|
42
|
+
"""Unit direction at ``angle_deg`` from ``u``, rotating toward ``v``.
|
|
43
|
+
|
|
44
|
+
The common case -- an angle measured in the ``xy`` plane from ``+x``, as
|
|
45
|
+
crystal and polarization angles usually are -- needs no axes passed.
|
|
46
|
+
"""
|
|
47
|
+
a = np.radians(float(angle_deg))
|
|
48
|
+
return unit(np.cos(a) * unit(u) + np.sin(a) * unit(v))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def rect_shape(center: Point3, u: Point3, v: Point3, du: float, dv: float) -> Array:
|
|
52
|
+
"""Rectangle centred on ``center``, in the plane spanned by ``u`` and ``v``."""
|
|
53
|
+
c, uh, vh = np.asarray(center, dtype=np.float64), unit(u), unit(v)
|
|
54
|
+
return np.array(
|
|
55
|
+
[
|
|
56
|
+
c - uh * du / 2 - vh * dv / 2,
|
|
57
|
+
c + uh * du / 2 - vh * dv / 2,
|
|
58
|
+
c + uh * du / 2 + vh * dv / 2,
|
|
59
|
+
c - uh * du / 2 + vh * dv / 2,
|
|
60
|
+
]
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def box_faces(center: Point3, size: Point3) -> list[Face]:
|
|
65
|
+
"""The six faces of an axis-aligned box, each wound CCW about its outward normal.
|
|
66
|
+
|
|
67
|
+
Pair with :meth:`~vecview.camera.Camera.visible` to draw only the walls a
|
|
68
|
+
given camera can see::
|
|
69
|
+
|
|
70
|
+
slab = box_faces(center=(0, 0, -0.45), size=(11, 9, 0.9))
|
|
71
|
+
scene.faces(10, camera.visible(slab), fill="#cfd6e0")
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
center: Centre of the box.
|
|
75
|
+
size: Full extents ``(sx, sy, sz)``, not half-extents.
|
|
76
|
+
"""
|
|
77
|
+
c = np.asarray(center, dtype=np.float64)
|
|
78
|
+
h = np.asarray(size, dtype=np.float64) / 2.0
|
|
79
|
+
if c.shape != (3,) or h.shape != (3,):
|
|
80
|
+
raise ValueError("center and size must each be three numbers")
|
|
81
|
+
|
|
82
|
+
axes = np.eye(3)
|
|
83
|
+
faces: list[Face] = []
|
|
84
|
+
for axis, sign in ((a, s) for a in range(3) for s in (+1, -1)):
|
|
85
|
+
normal = axes[axis] * sign
|
|
86
|
+
# In-plane axes chosen so (u, v, normal) is right-handed, which winds
|
|
87
|
+
# the points counter-clockwise as seen from outside the box.
|
|
88
|
+
u = axes[(axis + 1) % 3] * sign
|
|
89
|
+
v = axes[(axis + 2) % 3]
|
|
90
|
+
du, dv = 2 * h[(axis + 1) % 3], 2 * h[(axis + 2) % 3]
|
|
91
|
+
name = f"{'+' if sign > 0 else '-'}{'xyz'[axis]}"
|
|
92
|
+
faces.append(Face(name, rect_shape(c + normal * h[axis], u, v, du, dv), normal))
|
|
93
|
+
return faces
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _self_intersects(poly: Array) -> bool:
|
|
97
|
+
"""Whether any two non-adjacent edges of a closed polygon cross or touch."""
|
|
98
|
+
n = len(poly)
|
|
99
|
+
a, b = poly, np.roll(poly, -1, axis=0)
|
|
100
|
+
scale = float(np.ptp(poly, axis=0).max()) or 1.0
|
|
101
|
+
eps = 1e-12 * scale * scale
|
|
102
|
+
|
|
103
|
+
def orient(p: Array, q: Array, r: Array) -> Array:
|
|
104
|
+
cross: Array = (q[..., 0] - p[..., 0]) * (r[..., 1] - p[..., 1]) - (
|
|
105
|
+
q[..., 1] - p[..., 1]
|
|
106
|
+
) * (r[..., 0] - p[..., 0])
|
|
107
|
+
return cross
|
|
108
|
+
|
|
109
|
+
def within(p: Array, q: Array, r: Array) -> npt.NDArray[np.bool_]:
|
|
110
|
+
"""Whether r lies in the bounding box of segment pq (for collinear r)."""
|
|
111
|
+
lo, hi = np.minimum(p, q), np.maximum(p, q)
|
|
112
|
+
inside: npt.NDArray[np.bool_] = np.all(
|
|
113
|
+
(r >= lo - 1e-12 * scale) & (r <= hi + 1e-12 * scale), axis=-1
|
|
114
|
+
)
|
|
115
|
+
return inside
|
|
116
|
+
|
|
117
|
+
i, j = np.triu_indices(n, k=2)
|
|
118
|
+
keep = ~((i == 0) & (j == n - 1)) # the closing edge is adjacent to the first
|
|
119
|
+
i, j = i[keep], j[keep]
|
|
120
|
+
ai, bi, aj, bj = a[i], b[i], a[j], b[j]
|
|
121
|
+
d1, d2 = orient(ai, bi, aj), orient(ai, bi, bj)
|
|
122
|
+
d3, d4 = orient(aj, bj, ai), orient(aj, bj, bi)
|
|
123
|
+
proper = (d1 * d2 < -eps * eps) & (d3 * d4 < -eps * eps)
|
|
124
|
+
touching = (
|
|
125
|
+
((np.abs(d1) <= eps) & within(ai, bi, aj))
|
|
126
|
+
| ((np.abs(d2) <= eps) & within(ai, bi, bj))
|
|
127
|
+
| ((np.abs(d3) <= eps) & within(aj, bj, ai))
|
|
128
|
+
| ((np.abs(d4) <= eps) & within(aj, bj, bi))
|
|
129
|
+
)
|
|
130
|
+
return bool(np.any(proper | touching))
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def prism_faces(footprint: Points2, z0: float, z1: float) -> list[Face]:
|
|
134
|
+
"""The faces of a footprint extruded along ``z``, each wound CCW about its normal.
|
|
135
|
+
|
|
136
|
+
The generalization of :func:`box_faces` to any simple cross-section -- a
|
|
137
|
+
tapered electrode, an arc-shaped gate. The cap is named ``"+z"`` and the
|
|
138
|
+
base ``"-z"``, as for a box; wall ``i`` spans footprint vertices ``i`` and
|
|
139
|
+
``i + 1`` and is named ``"side-{i}"``.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
footprint: Simple polygon in the ``xy`` plane, shape ``(n, 2)``, in
|
|
143
|
+
either winding; it may be non-convex. Collinear vertices are
|
|
144
|
+
allowed; repeated ones are not.
|
|
145
|
+
z0: Height of the base.
|
|
146
|
+
z1: Height of the cap; must exceed ``z0``.
|
|
147
|
+
|
|
148
|
+
Raises:
|
|
149
|
+
ValueError: If the footprint is not a simple polygon of at least three
|
|
150
|
+
distinct vertices -- self-intersecting or self-touching outlines
|
|
151
|
+
have no well-defined outside -- or ``z1 <= z0``.
|
|
152
|
+
|
|
153
|
+
Back-face culling selects the walls that face the camera, which for a
|
|
154
|
+
convex footprint is exactly the visible set. For a non-convex one, a
|
|
155
|
+
facing wall can still be hidden behind another wall of the same solid;
|
|
156
|
+
:meth:`~vecview.scene.Scene.prism_walls` draws such a solid correctly.
|
|
157
|
+
"""
|
|
158
|
+
foot = np.asarray(footprint, dtype=np.float64)
|
|
159
|
+
if foot.ndim != 2 or foot.shape[1] != 2 or len(foot) < 3:
|
|
160
|
+
raise ValueError(f"footprint must have shape (n, 2) with n >= 3, got {foot.shape}")
|
|
161
|
+
if not z1 > z0:
|
|
162
|
+
raise ValueError(f"z1 must exceed z0, got z0={z0}, z1={z1}")
|
|
163
|
+
x, y = foot[:, 0], foot[:, 1]
|
|
164
|
+
area = 0.5 * float(np.dot(x, np.roll(y, -1)) - np.dot(np.roll(x, -1), y))
|
|
165
|
+
edges = np.roll(foot, -1, axis=0) - foot
|
|
166
|
+
lengths = np.linalg.norm(edges, axis=1)
|
|
167
|
+
if np.any(lengths <= 1e-12 * float(lengths.max())):
|
|
168
|
+
raise ValueError("footprint has repeated consecutive vertices")
|
|
169
|
+
if abs(area) <= 1e-12 * float(lengths.max()) ** 2:
|
|
170
|
+
raise ValueError("footprint encloses no area")
|
|
171
|
+
if _self_intersects(foot):
|
|
172
|
+
raise ValueError("footprint must be a simple polygon: its edges cross or touch")
|
|
173
|
+
if area < 0:
|
|
174
|
+
foot = foot[::-1] # clockwise: reverse so the cap faces +z
|
|
175
|
+
edges = np.roll(foot, -1, axis=0) - foot
|
|
176
|
+
|
|
177
|
+
n = len(foot)
|
|
178
|
+
base = np.column_stack([foot, np.full(n, float(z0))])
|
|
179
|
+
cap = np.column_stack([foot, np.full(n, float(z1))])
|
|
180
|
+
faces = [
|
|
181
|
+
Face("+z", cap, np.array([0.0, 0.0, 1.0])),
|
|
182
|
+
Face("-z", base[::-1].copy(), np.array([0.0, 0.0, -1.0])),
|
|
183
|
+
]
|
|
184
|
+
for i in range(n):
|
|
185
|
+
j = (i + 1) % n
|
|
186
|
+
# For a CCW footprint the outside is to the right of each edge, and
|
|
187
|
+
# (edge, +z, outward) is right-handed, which winds the wall CCW from outside.
|
|
188
|
+
outward = unit(np.array([edges[i, 1], -edges[i, 0], 0.0]))
|
|
189
|
+
faces.append(Face(f"side-{i}", np.array([base[i], base[j], cap[j], cap[i]]), outward))
|
|
190
|
+
return faces
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def annulus_sector(
|
|
194
|
+
center: tuple[float, float] | Array,
|
|
195
|
+
r_in: float,
|
|
196
|
+
r_out: float,
|
|
197
|
+
theta0_deg: float,
|
|
198
|
+
theta1_deg: float,
|
|
199
|
+
n: int = 32,
|
|
200
|
+
) -> Array:
|
|
201
|
+
"""Footprint of an annular sector, shape ``(m, 2)``, counter-clockwise.
|
|
202
|
+
|
|
203
|
+
The outer arc runs from ``theta0_deg`` to ``theta1_deg`` in ``n`` segments,
|
|
204
|
+
then the inner arc runs back. With ``r_in = 0`` the inner arc collapses to
|
|
205
|
+
the centre and the result is a pie wedge. Angles are measured from ``+x``
|
|
206
|
+
toward ``+y``. Pair with :func:`prism_faces` for an arc-shaped electrode.
|
|
207
|
+
|
|
208
|
+
Raises:
|
|
209
|
+
ValueError: Unless ``0 <= r_in < r_out``, ``n >= 1``, and the span
|
|
210
|
+
``theta1_deg - theta0_deg`` lies in ``(0, 360)``. A full ring is not a
|
|
211
|
+
simple polygon.
|
|
212
|
+
"""
|
|
213
|
+
if not 0.0 <= r_in < r_out:
|
|
214
|
+
raise ValueError(f"need 0 <= r_in < r_out, got r_in={r_in}, r_out={r_out}")
|
|
215
|
+
span = theta1_deg - theta0_deg
|
|
216
|
+
if not 0.0 < span < 360.0:
|
|
217
|
+
raise ValueError(f"theta1_deg - theta0_deg must lie in (0, 360), got {span}")
|
|
218
|
+
if n < 1:
|
|
219
|
+
raise ValueError(f"n must be at least 1, got {n}")
|
|
220
|
+
c = np.asarray(center, dtype=np.float64)
|
|
221
|
+
t = np.radians(np.linspace(theta0_deg, theta1_deg, n + 1))
|
|
222
|
+
ring = np.column_stack([np.cos(t), np.sin(t)])
|
|
223
|
+
outer = c + r_out * ring
|
|
224
|
+
inner = c[None, :] if r_in == 0.0 else c + r_in * ring[::-1]
|
|
225
|
+
footprint: Array = np.vstack([outer, inner])
|
|
226
|
+
return footprint
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def arrow_shape(
|
|
230
|
+
origin: Point3,
|
|
231
|
+
direction: Point3,
|
|
232
|
+
length: float,
|
|
233
|
+
normal: Point3,
|
|
234
|
+
shaft_w: float,
|
|
235
|
+
head_w: float,
|
|
236
|
+
head_len: float,
|
|
237
|
+
pivot: Pivot = "tail",
|
|
238
|
+
) -> Array:
|
|
239
|
+
"""Flat arrow polygon in the plane through ``origin`` with the given normal.
|
|
240
|
+
|
|
241
|
+
Args:
|
|
242
|
+
origin: Tail of the arrow, or its midpoint when ``pivot="mid"``.
|
|
243
|
+
direction: Direction the head points.
|
|
244
|
+
length: Total length, tail to tip.
|
|
245
|
+
normal: Normal of the plane the arrow is drawn flat in.
|
|
246
|
+
shaft_w: Width of the shaft.
|
|
247
|
+
head_w: Width of the head at its widest.
|
|
248
|
+
head_len: Length of the head, measured back from the tip.
|
|
249
|
+
pivot: Whether ``origin`` is the ``"tail"`` or the ``"mid"`` point.
|
|
250
|
+
"""
|
|
251
|
+
d, n = unit(direction), unit(normal)
|
|
252
|
+
s = unit(np.cross(n, d))
|
|
253
|
+
base = np.asarray(origin, dtype=np.float64) - (d * length / 2.0 if pivot == "mid" else 0.0)
|
|
254
|
+
tip = base + d * length
|
|
255
|
+
neck = base + d * max(length - head_len, 0.0)
|
|
256
|
+
return np.array(
|
|
257
|
+
[
|
|
258
|
+
base + s * shaft_w / 2,
|
|
259
|
+
neck + s * shaft_w / 2,
|
|
260
|
+
neck + s * head_w / 2,
|
|
261
|
+
tip,
|
|
262
|
+
neck - s * head_w / 2,
|
|
263
|
+
neck - s * shaft_w / 2,
|
|
264
|
+
base - s * shaft_w / 2,
|
|
265
|
+
]
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def double_arrow_shape(
|
|
270
|
+
center: Point3,
|
|
271
|
+
direction: Point3,
|
|
272
|
+
length: float,
|
|
273
|
+
normal: Point3,
|
|
274
|
+
shaft_w: float,
|
|
275
|
+
head_w: float,
|
|
276
|
+
head_len: float,
|
|
277
|
+
) -> Array:
|
|
278
|
+
"""Double-headed arrow centred on ``center`` -- an axis or polarization marker."""
|
|
279
|
+
d, n = unit(direction), unit(normal)
|
|
280
|
+
s = unit(np.cross(n, d))
|
|
281
|
+
c = np.asarray(center, dtype=np.float64)
|
|
282
|
+
h, neck = length / 2.0, length / 2.0 - head_len
|
|
283
|
+
return np.array(
|
|
284
|
+
[
|
|
285
|
+
c + d * h,
|
|
286
|
+
c + d * neck + s * head_w / 2,
|
|
287
|
+
c + d * neck + s * shaft_w / 2,
|
|
288
|
+
c - d * neck + s * shaft_w / 2,
|
|
289
|
+
c - d * neck + s * head_w / 2,
|
|
290
|
+
c - d * h,
|
|
291
|
+
c - d * neck - s * head_w / 2,
|
|
292
|
+
c - d * neck - s * shaft_w / 2,
|
|
293
|
+
c + d * neck - s * shaft_w / 2,
|
|
294
|
+
c + d * neck - s * head_w / 2,
|
|
295
|
+
]
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def circle_shape(center: Point3, radius: float, normal: Point3, n: int = 64) -> Array:
|
|
300
|
+
"""Circle as an ``n``-gon, in the plane through ``center`` with the given normal."""
|
|
301
|
+
a, b = basis_for(normal)
|
|
302
|
+
t = np.linspace(0.0, 2.0 * np.pi, n, endpoint=False)
|
|
303
|
+
ring: Array = np.asarray(center, dtype=np.float64) + radius * (
|
|
304
|
+
np.outer(np.cos(t), a) + np.outer(np.sin(t), b)
|
|
305
|
+
)
|
|
306
|
+
return ring
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def ellipse_shape(center: Point3, u: Point3, v: Point3, a: float, b: float, n: int = 64) -> Array:
|
|
310
|
+
"""Ellipse as an ``n``-gon, with semi-axis ``a`` along ``u`` and ``b`` along ``v``.
|
|
311
|
+
|
|
312
|
+
The generalization of :func:`circle_shape`. The first vertex lies at
|
|
313
|
+
``center + a * u`` and the points run counter-clockwise about ``u x v``,
|
|
314
|
+
with no duplicated closing point.
|
|
315
|
+
|
|
316
|
+
Raises:
|
|
317
|
+
ValueError: If ``u`` and ``v`` are not perpendicular, since the
|
|
318
|
+
semi-axes would then not be ``a`` and ``b``.
|
|
319
|
+
"""
|
|
320
|
+
uh, vh = unit(u), unit(v)
|
|
321
|
+
if abs(float(np.dot(uh, vh))) > 1e-9:
|
|
322
|
+
raise ValueError("u and v must be perpendicular: they are the ellipse's axes")
|
|
323
|
+
t = np.linspace(0.0, 2.0 * np.pi, n, endpoint=False)
|
|
324
|
+
ring: Array = np.asarray(center, dtype=np.float64) + (
|
|
325
|
+
np.outer(a * np.cos(t), uh) + np.outer(b * np.sin(t), vh)
|
|
326
|
+
)
|
|
327
|
+
return ring
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def arc_shape(
|
|
331
|
+
center: Point3,
|
|
332
|
+
u: Point3,
|
|
333
|
+
v: Point3,
|
|
334
|
+
radius: float,
|
|
335
|
+
theta0_deg: float,
|
|
336
|
+
theta1_deg: float,
|
|
337
|
+
n: int = 32,
|
|
338
|
+
) -> Array:
|
|
339
|
+
"""Circular arc of ``n`` segments in the plane of ``u`` and ``v``.
|
|
340
|
+
|
|
341
|
+
Angles are measured from ``u`` toward ``v``; ``v`` need not be perpendicular
|
|
342
|
+
to ``u``, only not parallel, so the arc marking the angle between two
|
|
343
|
+
vectors is ``arc_shape(origin, a, b, r, 0, angle_between)``.
|
|
344
|
+
|
|
345
|
+
Raises:
|
|
346
|
+
ValueError: If ``u`` and ``v`` are parallel, which leaves no plane.
|
|
347
|
+
"""
|
|
348
|
+
uh = unit(u)
|
|
349
|
+
w = np.asarray(v, dtype=np.float64) - float(np.dot(v, uh)) * uh
|
|
350
|
+
if float(np.linalg.norm(w)) < 1e-12 * max(float(np.linalg.norm(v)), 1.0):
|
|
351
|
+
raise ValueError("u and v are parallel, so they span no plane for the arc")
|
|
352
|
+
vh = unit(w)
|
|
353
|
+
t = np.radians(np.linspace(theta0_deg, theta1_deg, n + 1))
|
|
354
|
+
arc: Array = np.asarray(center, dtype=np.float64) + radius * (
|
|
355
|
+
np.outer(np.cos(t), uh) + np.outer(np.sin(t), vh)
|
|
356
|
+
)
|
|
357
|
+
return arc
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def helix(
|
|
361
|
+
start: Point3,
|
|
362
|
+
axis: Point3,
|
|
363
|
+
radius: float,
|
|
364
|
+
pitch: float,
|
|
365
|
+
turns: float,
|
|
366
|
+
n_per_turn: int = 48,
|
|
367
|
+
phase_deg: float = 0.0,
|
|
368
|
+
) -> Array:
|
|
369
|
+
"""Helix winding about ``axis`` from ``start``, for a coil or a spin spiral.
|
|
370
|
+
|
|
371
|
+
``start`` is on the axis. The curve begins ``radius`` from it at angle
|
|
372
|
+
``phase_deg`` (measured in the frame of :func:`circle_shape`), turns
|
|
373
|
+
counter-clockwise about ``axis`` and advances ``pitch`` along it per turn,
|
|
374
|
+
so a positive ``pitch`` is right-handed and a negative one left-handed.
|
|
375
|
+
|
|
376
|
+
Raises:
|
|
377
|
+
ValueError: Unless ``turns`` and ``n_per_turn`` are positive.
|
|
378
|
+
"""
|
|
379
|
+
if turns <= 0 or n_per_turn < 1:
|
|
380
|
+
raise ValueError(f"need turns > 0 and n_per_turn >= 1, got {turns}, {n_per_turn}")
|
|
381
|
+
a = unit(axis)
|
|
382
|
+
e1, e2 = basis_for(a)
|
|
383
|
+
count = max(round(turns * n_per_turn), 1)
|
|
384
|
+
s = np.linspace(0.0, turns, count + 1)
|
|
385
|
+
t = 2.0 * np.pi * s + np.radians(phase_deg)
|
|
386
|
+
curve: Array = (
|
|
387
|
+
np.asarray(start, dtype=np.float64)
|
|
388
|
+
+ radius * (np.outer(np.cos(t), e1) + np.outer(np.sin(t), e2))
|
|
389
|
+
+ np.outer(s * pitch, a)
|
|
390
|
+
)
|
|
391
|
+
return curve
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def surface_faces(x: Array, y: Array, z: Array) -> list[Face]:
|
|
395
|
+
"""Quads of a parametric surface sampled on a grid, for band surfaces and cones.
|
|
396
|
+
|
|
397
|
+
``x``, ``y`` and ``z`` are 2D arrays of one shape ``(m, n)`` -- the output
|
|
398
|
+
of :func:`numpy.meshgrid` for a height field ``z = f(x, y)``, or any
|
|
399
|
+
parametrization ``(x(s, t), y(s, t), z(s, t))``. Quad ``(i, j)`` spans
|
|
400
|
+
samples ``i..i+1`` and ``j..j+1``, is named ``"q-{i}-{j}"``, and is wound
|
|
401
|
+
counter-clockwise about its normal, which points along ``d/di x d/dj``. For
|
|
402
|
+
a height field from ``np.meshgrid(xs, ys, indexing="ij")`` that is upward;
|
|
403
|
+
the default ``indexing="xy"`` swaps the axes and points it downward.
|
|
404
|
+
|
|
405
|
+
A surface is two-sided, so do not cull it; draw the quads in a layer passed
|
|
406
|
+
to :meth:`~vecview.scene.Scene.sort_by_depth`, and use the normal to pick a
|
|
407
|
+
front or back colour if the surface folds toward the camera.
|
|
408
|
+
|
|
409
|
+
Raises:
|
|
410
|
+
ValueError: If the arrays differ in shape or have fewer than two
|
|
411
|
+
samples along either axis.
|
|
412
|
+
"""
|
|
413
|
+
gx, gy, gz = (np.asarray(a, dtype=np.float64) for a in (x, y, z))
|
|
414
|
+
if not gx.shape == gy.shape == gz.shape or gx.ndim != 2:
|
|
415
|
+
raise ValueError(
|
|
416
|
+
f"x, y and z must be 2D arrays of one shape, got {gx.shape}, {gy.shape}, {gz.shape}"
|
|
417
|
+
)
|
|
418
|
+
m, n = gx.shape
|
|
419
|
+
if m < 2 or n < 2:
|
|
420
|
+
raise ValueError(f"a surface needs at least 2 x 2 samples, got {m} x {n}")
|
|
421
|
+
p = np.stack([gx, gy, gz], axis=-1)
|
|
422
|
+
faces: list[Face] = []
|
|
423
|
+
for i in range(m - 1):
|
|
424
|
+
for j in range(n - 1):
|
|
425
|
+
quad = np.array([p[i, j], p[i + 1, j], p[i + 1, j + 1], p[i, j + 1]])
|
|
426
|
+
# Twice the cross product of the two partial derivatives, from the
|
|
427
|
+
# diagonals, which stays defined when one edge collapses to a point.
|
|
428
|
+
normal = unit(np.cross(quad[2] - quad[0], quad[3] - quad[1]))
|
|
429
|
+
faces.append(Face(f"q-{i}-{j}", quad, normal))
|
|
430
|
+
return faces
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def convex_polyhedron(vertices: Points3, *, tol: float = 1e-9) -> list[Face]:
|
|
434
|
+
"""Faces of the convex hull of ``vertices``, each wound CCW about its outward normal.
|
|
435
|
+
|
|
436
|
+
For a Brillouin zone, a coordination octahedron, or any small convex solid
|
|
437
|
+
known by its corners. Faces are named ``"face-{k}"`` in a deterministic
|
|
438
|
+
order, and coplanar vertices merge into one polygonal face, so a truncated
|
|
439
|
+
octahedron gives eight hexagons and six squares rather than triangles.
|
|
440
|
+
Vertices strictly inside the hull are ignored.
|
|
441
|
+
|
|
442
|
+
The search tests every vertex triple against every vertex, which is
|
|
443
|
+
``O(n^4)``: instant for the tens of vertices this is meant for, and the
|
|
444
|
+
wrong tool for a mesh of thousands.
|
|
445
|
+
|
|
446
|
+
Args:
|
|
447
|
+
vertices: World points, shape ``(n, 3)``.
|
|
448
|
+
tol: Coplanarity tolerance, relative to the size of the solid.
|
|
449
|
+
|
|
450
|
+
Raises:
|
|
451
|
+
ValueError: For fewer than four vertices, or vertices that are all
|
|
452
|
+
coplanar, since neither encloses a volume.
|
|
453
|
+
"""
|
|
454
|
+
pts = as_points(vertices)
|
|
455
|
+
n = len(pts)
|
|
456
|
+
if n < 4:
|
|
457
|
+
raise ValueError(f"a polyhedron needs at least 4 vertices, got {n}")
|
|
458
|
+
size = float(np.ptp(pts, axis=0).max()) or 1.0
|
|
459
|
+
eps = tol * size
|
|
460
|
+
|
|
461
|
+
i, j, k = (np.asarray(c) for c in zip(*combinations(range(n), 3), strict=True))
|
|
462
|
+
found: dict[frozenset[int], Array] = {}
|
|
463
|
+
chunk = 4096
|
|
464
|
+
for lo in range(0, len(i), chunk):
|
|
465
|
+
a, b, c = pts[i[lo : lo + chunk]], pts[j[lo : lo + chunk]], pts[k[lo : lo + chunk]]
|
|
466
|
+
normals = np.cross(b - a, c - a)
|
|
467
|
+
lengths = np.linalg.norm(normals, axis=1)
|
|
468
|
+
ok = lengths > eps * size
|
|
469
|
+
normals = normals[ok] / lengths[ok, None]
|
|
470
|
+
side = pts @ normals.T - np.einsum("ij,ij->i", a[ok], normals)
|
|
471
|
+
below, above = np.all(side <= eps, axis=0), np.all(side >= -eps, axis=0)
|
|
472
|
+
for col in np.flatnonzero(below | above):
|
|
473
|
+
normal = normals[col] if below[col] else -normals[col]
|
|
474
|
+
on = frozenset(int(v) for v in np.flatnonzero(np.abs(side[:, col]) <= eps))
|
|
475
|
+
found.setdefault(on, normal)
|
|
476
|
+
if not found or all(len(on) == n for on in found):
|
|
477
|
+
raise ValueError("vertices are coplanar, so they enclose no volume")
|
|
478
|
+
|
|
479
|
+
faces: list[Face] = []
|
|
480
|
+
for on, normal in found.items():
|
|
481
|
+
idx = sorted(on)
|
|
482
|
+
ring = pts[idx]
|
|
483
|
+
centre = ring.mean(axis=0)
|
|
484
|
+
e1, e2 = basis_for(normal)
|
|
485
|
+
rel = ring - centre
|
|
486
|
+
order = np.argsort(np.arctan2(rel @ e2, rel @ e1), kind="stable")
|
|
487
|
+
faces.append(Face(f"face-{len(faces)}", ring[order], np.asarray(normal)))
|
|
488
|
+
return faces
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def trim_corners(faces: Iterable[Face], radius: float, n: int = 8) -> list[Face]:
|
|
492
|
+
"""Faces with a disk of ``radius`` cut out at every corner.
|
|
493
|
+
|
|
494
|
+
For a polyhedron with an atom or marker on each vertex. A face that runs
|
|
495
|
+
into the centre of a sphere cannot be depth-sorted against it, since part
|
|
496
|
+
of the face is inside the ball; cut back to the sphere's surface, it can.
|
|
497
|
+
The ball meets each face plane in a disk about the vertex, so the corner is
|
|
498
|
+
replaced by an inward arc of ``n`` segments, centred on the vertex, from
|
|
499
|
+
one edge to the other. Name and normal are kept.
|
|
500
|
+
|
|
501
|
+
Pair with :meth:`~vecview.scene.Scene.edges` ``trim=radius`` for the edges.
|
|
502
|
+
|
|
503
|
+
Raises:
|
|
504
|
+
ValueError: If ``radius`` is not smaller than half of every edge, which
|
|
505
|
+
would make neighbouring cuts overlap.
|
|
506
|
+
"""
|
|
507
|
+
trimmed: list[Face] = []
|
|
508
|
+
for face in faces:
|
|
509
|
+
ring = np.asarray(face.points, dtype=np.float64)
|
|
510
|
+
edges = np.linalg.norm(np.roll(ring, -1, axis=0) - ring, axis=1)
|
|
511
|
+
if radius <= 0:
|
|
512
|
+
trimmed.append(face)
|
|
513
|
+
continue
|
|
514
|
+
if radius >= 0.5 * float(edges.min()):
|
|
515
|
+
raise ValueError(
|
|
516
|
+
f"radius {radius:g} must be under half the shortest edge, "
|
|
517
|
+
f"{0.5 * float(edges.min()):g}, of face {face.name!r}"
|
|
518
|
+
)
|
|
519
|
+
out: list[Array] = []
|
|
520
|
+
for i, v in enumerate(ring):
|
|
521
|
+
a = unit(ring[i - 1] - v)
|
|
522
|
+
b = unit(ring[(i + 1) % len(ring)] - v)
|
|
523
|
+
angle = float(np.arccos(np.clip(np.dot(a, b), -1.0, 1.0)))
|
|
524
|
+
w = unit(b - np.dot(b, a) * a)
|
|
525
|
+
t = np.linspace(0.0, angle, n + 1)
|
|
526
|
+
out.extend(v + radius * (np.outer(np.cos(t), a) + np.outer(np.sin(t), w)))
|
|
527
|
+
trimmed.append(Face(face.name, np.array(out), face.normal))
|
|
528
|
+
return trimmed
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def sine_ribbon(
|
|
532
|
+
start: Point3,
|
|
533
|
+
axis: Point3,
|
|
534
|
+
length: float,
|
|
535
|
+
transverse: Point3,
|
|
536
|
+
amplitude: float | Array,
|
|
537
|
+
wavelength: float,
|
|
538
|
+
n: int = 400,
|
|
539
|
+
phase: float = 0.0,
|
|
540
|
+
) -> Array:
|
|
541
|
+
"""Transverse wave along ``axis``, displaced along ``transverse``.
|
|
542
|
+
|
|
543
|
+
``amplitude`` may be a scalar or an array of length ``n``, so a component
|
|
544
|
+
that decays inside a medium can be drawn by passing its envelope.
|
|
545
|
+
"""
|
|
546
|
+
a, e = unit(axis), unit(transverse)
|
|
547
|
+
t = np.linspace(0.0, length, n)
|
|
548
|
+
disp = np.asarray(amplitude, dtype=np.float64) * np.sin(2.0 * np.pi * t / wavelength + phase)
|
|
549
|
+
ribbon: Array = np.asarray(start, dtype=np.float64) + np.outer(t, a) + np.outer(disp, e)
|
|
550
|
+
return ribbon
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
__all__ = [
|
|
554
|
+
"Face",
|
|
555
|
+
"FaceName",
|
|
556
|
+
"annulus_sector",
|
|
557
|
+
"arc_shape",
|
|
558
|
+
"arrow_shape",
|
|
559
|
+
"box_faces",
|
|
560
|
+
"circle_shape",
|
|
561
|
+
"convex_polyhedron",
|
|
562
|
+
"double_arrow_shape",
|
|
563
|
+
"ellipse_shape",
|
|
564
|
+
"helix",
|
|
565
|
+
"in_plane_dir",
|
|
566
|
+
"prism_faces",
|
|
567
|
+
"rect_shape",
|
|
568
|
+
"sine_ribbon",
|
|
569
|
+
"surface_faces",
|
|
570
|
+
"trim_corners",
|
|
571
|
+
]
|