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/__init__.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Layered 3D scenes that render to SVG.
|
|
2
|
+
|
|
3
|
+
A small projection layer on top of `svg.py <https://pypi.org/project/svg.py/>`_.
|
|
4
|
+
``svg.py`` builds the elements; this package supplies what it has no notion of --
|
|
5
|
+
a camera, world-space glyph geometry, and an explicit layer stack.
|
|
6
|
+
|
|
7
|
+
World coordinates are right-handed ``(x, y, z)`` with ``z`` up. Every camera is
|
|
8
|
+
a parallel projection, so parallel edges stay parallel and no perspective
|
|
9
|
+
distortion creeps into a lattice. :class:`OrthographicCamera` covers the
|
|
10
|
+
axonometric views (isometric, dimetric, trimetric) and :class:`ObliqueCamera` the
|
|
11
|
+
cavalier and cabinet ones::
|
|
12
|
+
|
|
13
|
+
import vecview
|
|
14
|
+
|
|
15
|
+
cam = vecview.OrthographicCamera(azim_deg=35, elev_deg=24, scale=62)
|
|
16
|
+
scene = vecview.Scene(cam, pad=28, background="#ffffff")
|
|
17
|
+
|
|
18
|
+
slab = vecview.box_faces(center=(0, 0, -0.45), size=(11, 9, 0.9))
|
|
19
|
+
scene.faces(10, cam.visible(slab), fill="#cfd6e0", stroke="#8b96a6")
|
|
20
|
+
scene.save("slab.svg")
|
|
21
|
+
|
|
22
|
+
The rendered document is also available as a string from
|
|
23
|
+
:meth:`Scene.to_svg_document`, for handing to a tool that assembles a larger
|
|
24
|
+
document.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
from vecview._vec import unit
|
|
30
|
+
from vecview.camera import Camera, ParallelCamera
|
|
31
|
+
from vecview.projections import (
|
|
32
|
+
ISOMETRIC_ELEV_DEG,
|
|
33
|
+
ISOMETRIC_RATIO,
|
|
34
|
+
ObliqueCamera,
|
|
35
|
+
OrthographicCamera,
|
|
36
|
+
)
|
|
37
|
+
from vecview.scene import Scene
|
|
38
|
+
from vecview.shapes import (
|
|
39
|
+
Face,
|
|
40
|
+
annulus_sector,
|
|
41
|
+
arc_shape,
|
|
42
|
+
arrow_shape,
|
|
43
|
+
box_faces,
|
|
44
|
+
circle_shape,
|
|
45
|
+
convex_polyhedron,
|
|
46
|
+
double_arrow_shape,
|
|
47
|
+
ellipse_shape,
|
|
48
|
+
helix,
|
|
49
|
+
in_plane_dir,
|
|
50
|
+
prism_faces,
|
|
51
|
+
rect_shape,
|
|
52
|
+
sine_ribbon,
|
|
53
|
+
surface_faces,
|
|
54
|
+
trim_corners,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
__version__ = "0.2.0"
|
|
58
|
+
|
|
59
|
+
__all__ = [
|
|
60
|
+
"ISOMETRIC_ELEV_DEG",
|
|
61
|
+
"ISOMETRIC_RATIO",
|
|
62
|
+
"Camera",
|
|
63
|
+
"Face",
|
|
64
|
+
"ObliqueCamera",
|
|
65
|
+
"OrthographicCamera",
|
|
66
|
+
"ParallelCamera",
|
|
67
|
+
"Scene",
|
|
68
|
+
"__version__",
|
|
69
|
+
"annulus_sector",
|
|
70
|
+
"arc_shape",
|
|
71
|
+
"arrow_shape",
|
|
72
|
+
"box_faces",
|
|
73
|
+
"circle_shape",
|
|
74
|
+
"convex_polyhedron",
|
|
75
|
+
"double_arrow_shape",
|
|
76
|
+
"ellipse_shape",
|
|
77
|
+
"helix",
|
|
78
|
+
"in_plane_dir",
|
|
79
|
+
"prism_faces",
|
|
80
|
+
"rect_shape",
|
|
81
|
+
"sine_ribbon",
|
|
82
|
+
"surface_faces",
|
|
83
|
+
"trim_corners",
|
|
84
|
+
"unit",
|
|
85
|
+
]
|
vecview/_occlusion.py
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
"""Exact visibility for a layer passed to ``Scene.sort_by_depth(layer, exact=True)``.
|
|
2
|
+
|
|
3
|
+
The painter's algorithm orders whole elements, so it fails wherever two
|
|
4
|
+
elements each hide part of the other. Here every element of the layer is
|
|
5
|
+
described by where it covers the screen and how deep its nearest surface is at
|
|
6
|
+
each screen point, and visibility is decided point by point:
|
|
7
|
+
|
|
8
|
+
* a **surface** keeps its native SVG element, clipped to the region where no
|
|
9
|
+
opaque surface is nearer. Between two planar surfaces that region is bounded
|
|
10
|
+
by a straight line, found exactly; anywhere else it is the zero contour of
|
|
11
|
+
the depth difference, traced at sub-pixel resolution;
|
|
12
|
+
* a **line** is cut where it passes behind an opaque surface, into visible
|
|
13
|
+
runs and hidden runs, which the caller can draw in another style.
|
|
14
|
+
|
|
15
|
+
Translucent surfaces hide nothing, but are themselves clipped by opaque ones in
|
|
16
|
+
front of them. ``shapely`` and ``contourpy`` are imported only when such a
|
|
17
|
+
layer is rendered; they come with the ``occlusion`` extra.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from collections.abc import Callable, Sequence
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
from typing import TYPE_CHECKING, Any
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
|
|
28
|
+
from vecview._types import Array
|
|
29
|
+
|
|
30
|
+
if TYPE_CHECKING:
|
|
31
|
+
import svg
|
|
32
|
+
|
|
33
|
+
type DepthFn = Callable[[Array], Array]
|
|
34
|
+
"""Screen points ``(n, 2)`` to the depth of the nearest surface; ``-inf`` where it misses."""
|
|
35
|
+
|
|
36
|
+
type Plane = tuple[float, float, float]
|
|
37
|
+
"""Depth as ``a * x + b * y + c`` over the screen, for a planar piece."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class Piece:
|
|
42
|
+
"""One planar or convex part of a surface.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
outline: Screen polygon the piece covers, shape ``(n, 2)``.
|
|
46
|
+
depth: Depth of the piece's front surface at screen points. Past its
|
|
47
|
+
edge it should go on smoothly -- the rim's depth, say -- rather than
|
|
48
|
+
stop: an element's stroke reaches past the surface, and is hidden
|
|
49
|
+
or not as the surface beside it would be.
|
|
50
|
+
plane: The depth as an affine function of screen position, for a
|
|
51
|
+
planar piece, which makes comparisons with other planes exact.
|
|
52
|
+
covers: Where the piece truly covers, for telling the parts of one
|
|
53
|
+
surface apart; ``None`` to go by ``outline``.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
outline: Array
|
|
57
|
+
depth: DepthFn
|
|
58
|
+
plane: Plane | None = None
|
|
59
|
+
covers: Callable[[Array], Any] | None = None
|
|
60
|
+
width: float = 0.0
|
|
61
|
+
"""When positive, ``outline`` is a centre line and the piece covers the band
|
|
62
|
+
this far either side of it -- a tube, drawn as a wide stroke."""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass
|
|
66
|
+
class Surface:
|
|
67
|
+
"""Something that fills area and may hide what is behind it."""
|
|
68
|
+
|
|
69
|
+
pieces: list[Piece]
|
|
70
|
+
opaque: bool
|
|
71
|
+
pad: float = 0.0
|
|
72
|
+
"""Half the stroke width: the element covers its outline grown by this much."""
|
|
73
|
+
chain: tuple[int, int] | None = None
|
|
74
|
+
"""``(chain id, position)`` for consecutive pieces of one tube, which overlap
|
|
75
|
+
by construction and are one surface: neighbours in a chain never hide each
|
|
76
|
+
other."""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class Line:
|
|
81
|
+
"""Something drawn as strokes, which hides nothing but can be hidden.
|
|
82
|
+
|
|
83
|
+
``runs`` are screen polylines with the depth at each vertex; depth varies
|
|
84
|
+
linearly along each straight segment, which holds for any parallel
|
|
85
|
+
projection.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
runs: list[tuple[Array, Array]]
|
|
89
|
+
rebuild: Callable[[list[Array], list[Array]], list[svg.Element]]
|
|
90
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
type Shape = Surface | Line
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@dataclass
|
|
97
|
+
class Visibility:
|
|
98
|
+
"""What :func:`resolve` decided for one shape.
|
|
99
|
+
|
|
100
|
+
For a surface, ``rings`` is ``None`` when nothing hides it, empty when it is
|
|
101
|
+
hidden entirely, and otherwise the rings of its visible region -- outer
|
|
102
|
+
boundaries counter-clockwise and holes clockwise, in screen coordinates.
|
|
103
|
+
For a line, ``visible`` and ``hidden`` are its runs on either side.
|
|
104
|
+
"""
|
|
105
|
+
|
|
106
|
+
rings: list[Array] | None = None
|
|
107
|
+
visible: list[Array] = field(default_factory=list)
|
|
108
|
+
hidden: list[Array] = field(default_factory=list)
|
|
109
|
+
hidden_by: list[int] = field(default_factory=list)
|
|
110
|
+
"""The shapes, by index, that hide some of this one, and so must be
|
|
111
|
+
painted after it: where two edges meet, the one in front belongs on top."""
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def plane_through(screen: Array, depth: Array) -> Plane | None:
|
|
115
|
+
"""The plane ``depth = a x + b y + c`` through projected vertices, or ``None`` edge-on.
|
|
116
|
+
|
|
117
|
+
Exact for the vertices of any planar polygon under a parallel projection,
|
|
118
|
+
where both screen position and depth are affine in the polygon's plane.
|
|
119
|
+
"""
|
|
120
|
+
if len(screen) < 3:
|
|
121
|
+
return None
|
|
122
|
+
centred = screen - screen.mean(axis=0)
|
|
123
|
+
if np.linalg.matrix_rank(centred, tol=1e-9 * max(float(np.abs(centred).max()), 1.0)) < 2:
|
|
124
|
+
return None
|
|
125
|
+
a = np.column_stack([screen, np.ones(len(screen))])
|
|
126
|
+
coef, *_ = np.linalg.lstsq(a, depth, rcond=None)
|
|
127
|
+
return float(coef[0]), float(coef[1]), float(coef[2])
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def planar_depth(plane: Plane) -> DepthFn:
|
|
131
|
+
a, b, c = plane
|
|
132
|
+
|
|
133
|
+
def depth(xy: Array) -> Array:
|
|
134
|
+
out: Array = a * xy[:, 0] + b * xy[:, 1] + c
|
|
135
|
+
return out
|
|
136
|
+
|
|
137
|
+
return depth
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _import() -> tuple[Any, Any]:
|
|
141
|
+
try:
|
|
142
|
+
import contourpy
|
|
143
|
+
import shapely
|
|
144
|
+
except ImportError as exc:
|
|
145
|
+
raise ImportError(
|
|
146
|
+
"sort_by_depth(..., exact=True) needs shapely and contourpy: "
|
|
147
|
+
"pip install 'vecview[occlusion]'"
|
|
148
|
+
) from exc
|
|
149
|
+
return shapely, contourpy
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def resolve(
|
|
153
|
+
shapes: Sequence[Shape], *, resolution: float = 0.5, tuck: float = 0.4
|
|
154
|
+
) -> list[Visibility]:
|
|
155
|
+
"""Decide what of each shape is visible.
|
|
156
|
+
|
|
157
|
+
Args:
|
|
158
|
+
shapes: Every shape of one layer.
|
|
159
|
+
resolution: Grid step, in screen units, of the depth contours traced
|
|
160
|
+
where two surfaces are not both planar.
|
|
161
|
+
tuck: How far, in screen units, a hidden surface is kept on under the
|
|
162
|
+
edge of what hides it.
|
|
163
|
+
"""
|
|
164
|
+
shapely, contourpy = _import()
|
|
165
|
+
_COVER.clear()
|
|
166
|
+
surfaces: list[tuple[int, Surface]] = [
|
|
167
|
+
(k, s) for k, s in enumerate(shapes) if isinstance(s, Surface)
|
|
168
|
+
]
|
|
169
|
+
regions = {k: _region(shapely, s) for k, s in surfaces}
|
|
170
|
+
occluders = [k for k, s in surfaces if s.opaque and not regions[k].is_empty]
|
|
171
|
+
solid = dict(surfaces)
|
|
172
|
+
# What a surface hides stops a little inside its own outline, so whatever is
|
|
173
|
+
# behind runs on under its anti-aliased edge instead of both edges fading
|
|
174
|
+
# out over the same pixels and letting the background through.
|
|
175
|
+
tucked = {k: regions[k].buffer(-tuck, quad_segs=2) for k in occluders}
|
|
176
|
+
tree = shapely.STRtree([regions[k] for k in occluders])
|
|
177
|
+
span = _depth_span(shapes)
|
|
178
|
+
eps_surface, eps_line = 1e-9 * span, 1e-4 * span
|
|
179
|
+
|
|
180
|
+
result = [Visibility() for _ in shapes]
|
|
181
|
+
for k, surface in surfaces:
|
|
182
|
+
region = regions[k]
|
|
183
|
+
if region.is_empty:
|
|
184
|
+
continue
|
|
185
|
+
hidden = []
|
|
186
|
+
for j in tree.query(region):
|
|
187
|
+
other = occluders[int(j)]
|
|
188
|
+
if other == k or _neighbours(surface, solid[other]):
|
|
189
|
+
continue
|
|
190
|
+
overlap = region.intersection(tucked[other])
|
|
191
|
+
if overlap.is_empty or overlap.area <= 1e-9:
|
|
192
|
+
continue
|
|
193
|
+
front = _in_front(
|
|
194
|
+
shapely, contourpy, surface, solid[other], overlap, eps_surface, resolution, tuck
|
|
195
|
+
)
|
|
196
|
+
if front is not None and not front.is_empty:
|
|
197
|
+
hidden.append(front)
|
|
198
|
+
result[k].hidden_by.append(other)
|
|
199
|
+
if not hidden:
|
|
200
|
+
continue
|
|
201
|
+
visible = region.difference(shapely.union_all(hidden))
|
|
202
|
+
if visible.area <= 1e-3:
|
|
203
|
+
result[k].rings = [] # hidden entirely
|
|
204
|
+
continue
|
|
205
|
+
# A clip path a twentieth of a screen unit off is invisible, and far smaller.
|
|
206
|
+
result[k].rings = _rings(shapely, visible.simplify(0.05)) or None
|
|
207
|
+
|
|
208
|
+
for k, shape in enumerate(shapes):
|
|
209
|
+
if isinstance(shape, Line):
|
|
210
|
+
result[k].visible, result[k].hidden = _split_line(
|
|
211
|
+
shapely,
|
|
212
|
+
shape,
|
|
213
|
+
[solid[o] for o in occluders],
|
|
214
|
+
[regions[o] for o in occluders],
|
|
215
|
+
tree,
|
|
216
|
+
eps_line,
|
|
217
|
+
)
|
|
218
|
+
return result
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _cover(shapely: Any, piece: Piece) -> Any:
|
|
222
|
+
"""The screen region a piece covers, as a shapely geometry."""
|
|
223
|
+
if piece.width > 0:
|
|
224
|
+
return shapely.LineString(piece.outline).buffer(piece.width, quad_segs=8, cap_style="flat")
|
|
225
|
+
return shapely.make_valid(shapely.Polygon(piece.outline))
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _region(shapely: Any, surface: Surface) -> Any:
|
|
229
|
+
polygons = [_cover(shapely, piece) for piece in surface.pieces]
|
|
230
|
+
region = shapely.union_all(polygons)
|
|
231
|
+
if surface.pad > 0:
|
|
232
|
+
region = region.buffer(surface.pad, quad_segs=4)
|
|
233
|
+
return region
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _depth_span(shapes: Sequence[Shape]) -> float:
|
|
237
|
+
"""A depth scale for the tolerances: the spread of the line depths, or 1."""
|
|
238
|
+
values = [d for s in shapes if isinstance(s, Line) for _, d in s.runs]
|
|
239
|
+
if not values:
|
|
240
|
+
return 1.0
|
|
241
|
+
joined = np.concatenate(values)
|
|
242
|
+
return max(float(np.ptp(joined)), 1.0)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _neighbours(a: Surface, b: Surface) -> bool:
|
|
246
|
+
if a.chain is None or b.chain is None or a.chain[0] != b.chain[0]:
|
|
247
|
+
return False
|
|
248
|
+
return abs(a.chain[1] - b.chain[1]) <= 1
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def planes_through(screen: Array, depth: Array) -> list[Plane | None]:
|
|
252
|
+
""":func:`plane_through` for many triangles at once: ``(k, 3, 2)`` and ``(k, 3)``."""
|
|
253
|
+
a = np.concatenate([screen, np.ones((*screen.shape[:2], 1))], axis=2)
|
|
254
|
+
det = np.linalg.det(a)
|
|
255
|
+
scale = np.abs(screen).max() if screen.size else 1.0
|
|
256
|
+
ok = np.abs(det) > 1e-9 * max(float(scale), 1.0) ** 2
|
|
257
|
+
out: list[Plane | None] = [None] * len(screen)
|
|
258
|
+
if ok.any():
|
|
259
|
+
coef = np.linalg.solve(a[ok], depth[ok][..., None])[..., 0]
|
|
260
|
+
for i, row in zip(np.flatnonzero(ok), coef, strict=True):
|
|
261
|
+
out[int(i)] = (float(row[0]), float(row[1]), float(row[2]))
|
|
262
|
+
return out
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def capsule_depth(
|
|
266
|
+
segments: Array, radius: float, back: Array, origin: Array, view: Array
|
|
267
|
+
) -> tuple[DepthFn, Callable[[Array], Any]]:
|
|
268
|
+
"""Exact depth of a chain of capsules -- a tube of ``radius`` along ``segments``.
|
|
269
|
+
|
|
270
|
+
``segments`` is ``(m, 2, 3)`` in world space; ``back`` maps screen points to
|
|
271
|
+
a world point on each ray (``origin + xy @ back.T``) and ``view`` is the
|
|
272
|
+
unit direction toward the camera, so depth is ``x @ view``. Each ray is
|
|
273
|
+
cast from beyond the nearest point of the chain toward the scene, and the
|
|
274
|
+
first capsule it meets gives the depth. A ray that meets none takes the
|
|
275
|
+
depth of its closest approach to the nearest one, so the depth goes on
|
|
276
|
+
smoothly past the tube's edge. Returns the depth and where the tube covers.
|
|
277
|
+
"""
|
|
278
|
+
pa, pb = segments[:, 0], segments[:, 1]
|
|
279
|
+
top = float(np.max(segments.reshape(-1, 3) @ view)) + radius + 1.0
|
|
280
|
+
ba = pb - pa
|
|
281
|
+
baba = np.einsum("ij,ij->i", ba, ba)
|
|
282
|
+
rd = -view
|
|
283
|
+
bard = ba @ rd
|
|
284
|
+
|
|
285
|
+
def cast(xy: Array) -> tuple[Array, Array]:
|
|
286
|
+
"""Distance along each ray to each capsule (``inf`` on a miss), and the
|
|
287
|
+
distance to each capsule's closest approach, for the extension."""
|
|
288
|
+
base = origin + xy @ back.T
|
|
289
|
+
ro = base + (top - base @ view)[:, None] * view # depth `top`, past everything
|
|
290
|
+
oa = ro[:, None, :] - pa[None, :, :]
|
|
291
|
+
baoa = np.einsum("nmj,mj->nm", oa, ba)
|
|
292
|
+
rdoa = oa @ rd
|
|
293
|
+
oaoa = np.einsum("nmj,nmj->nm", oa, oa)
|
|
294
|
+
a = baba - bard**2
|
|
295
|
+
b = baba * rdoa - baoa * bard
|
|
296
|
+
c = baba * oaoa - baoa**2 - radius**2 * baba
|
|
297
|
+
h = b * b - a * c
|
|
298
|
+
with np.errstate(invalid="ignore", divide="ignore"):
|
|
299
|
+
t = (-b - np.sqrt(np.maximum(h, 0.0))) / a
|
|
300
|
+
y = baoa + t * bard
|
|
301
|
+
body = (h >= 0) & (a > 1e-12) & (y > 0) & (y < baba)
|
|
302
|
+
hit = np.where(body, t, np.inf)
|
|
303
|
+
# The rounded ends: the sphere at whichever end the axis point fell past.
|
|
304
|
+
oc = np.where((y <= 0)[..., None], oa, ro[:, None, :] - pb[None, :, :])
|
|
305
|
+
bc = oc @ rd
|
|
306
|
+
hc = bc * bc - (np.einsum("nmj,nmj->nm", oc, oc) - radius**2)
|
|
307
|
+
hit = np.where(~body & (hc >= 0), -bc - np.sqrt(np.maximum(hc, 0.0)), hit)
|
|
308
|
+
closest = np.take_along_axis(-bc, hc.argmax(axis=1)[:, None], axis=1)[:, 0]
|
|
309
|
+
return hit.min(axis=1), closest
|
|
310
|
+
|
|
311
|
+
def depth(xy: Array) -> Array:
|
|
312
|
+
first, closest = cast(xy)
|
|
313
|
+
out: Array = top - np.where(np.isfinite(first), first, closest)
|
|
314
|
+
return out
|
|
315
|
+
|
|
316
|
+
def covers(xy: Array) -> Any:
|
|
317
|
+
return np.isfinite(cast(xy)[0])
|
|
318
|
+
|
|
319
|
+
return depth, covers
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
_COVER: dict[int, Any] = {}
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _depth_of(shapely: Any, surface: Surface, xy: Array) -> Array:
|
|
326
|
+
"""Nearest depth of a surface at screen points: the front-most of its pieces."""
|
|
327
|
+
if len(surface.pieces) == 1:
|
|
328
|
+
return surface.pieces[0].depth(xy)
|
|
329
|
+
best = np.full(len(xy), -np.inf)
|
|
330
|
+
for piece in surface.pieces:
|
|
331
|
+
if piece.covers is not None:
|
|
332
|
+
inside = piece.covers(xy)
|
|
333
|
+
best[inside] = np.maximum(best[inside], piece.depth(xy[inside]))
|
|
334
|
+
continue
|
|
335
|
+
cover = _COVER.get(id(piece))
|
|
336
|
+
if cover is None:
|
|
337
|
+
cover = _cover(shapely, piece).buffer(surface.pad + 1e-6, quad_segs=2)
|
|
338
|
+
shapely.prepare(cover)
|
|
339
|
+
_COVER[id(piece)] = cover
|
|
340
|
+
inside = shapely.contains_xy(cover, xy[:, 0], xy[:, 1])
|
|
341
|
+
if inside.any():
|
|
342
|
+
best[inside] = np.maximum(best[inside], piece.depth(xy[inside]))
|
|
343
|
+
return best
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _in_front(
|
|
347
|
+
shapely: Any,
|
|
348
|
+
contourpy: Any,
|
|
349
|
+
back: Surface,
|
|
350
|
+
front: Surface,
|
|
351
|
+
overlap: Any,
|
|
352
|
+
eps: float,
|
|
353
|
+
resolution: float,
|
|
354
|
+
tuck: float,
|
|
355
|
+
) -> Any:
|
|
356
|
+
"""The part of ``overlap`` where ``front`` is nearer than ``back``."""
|
|
357
|
+
pa = back.pieces[0].plane if len(back.pieces) == 1 else None
|
|
358
|
+
pb = front.pieces[0].plane if len(front.pieces) == 1 else None
|
|
359
|
+
if pa is not None and pb is not None:
|
|
360
|
+
a, b, c = (pb[i] - pa[i] for i in range(3))
|
|
361
|
+
# Where two planes cross, the tuck moves the boundary into the hidden side.
|
|
362
|
+
shift = eps + tuck * float(np.hypot(a, b))
|
|
363
|
+
return overlap.intersection(_half_plane(shapely, overlap.bounds, a, b, c - shift))
|
|
364
|
+
|
|
365
|
+
probe = _probe_points(shapely, overlap)
|
|
366
|
+
diff = _difference(shapely, front, back, probe)
|
|
367
|
+
if np.all(diff > eps):
|
|
368
|
+
return overlap
|
|
369
|
+
if np.all(diff <= eps):
|
|
370
|
+
return None
|
|
371
|
+
|
|
372
|
+
x0, y0, x1, y1 = overlap.bounds
|
|
373
|
+
nx = int(np.clip(np.ceil((x1 - x0) / resolution), 8, 160)) + 1
|
|
374
|
+
ny = int(np.clip(np.ceil((y1 - y0) / resolution), 8, 160)) + 1
|
|
375
|
+
xs, ys = np.linspace(x0, x1, nx), np.linspace(y0, y1, ny)
|
|
376
|
+
gx, gy = np.meshgrid(xs, ys)
|
|
377
|
+
grid = np.column_stack([gx.ravel(), gy.ravel()])
|
|
378
|
+
z = _difference(shapely, front, back, grid)
|
|
379
|
+
top = max(float(z.max()), eps) + 1.0
|
|
380
|
+
generator = contourpy.contour_generator(
|
|
381
|
+
xs, ys, z.reshape(ny, nx), fill_type=contourpy.FillType.OuterOffset
|
|
382
|
+
)
|
|
383
|
+
points, offsets = generator.filled(eps, top)
|
|
384
|
+
polygons = []
|
|
385
|
+
for pts, offs in zip(points, offsets, strict=True):
|
|
386
|
+
rings = [pts[offs[i] : offs[i + 1]] for i in range(len(offs) - 1)]
|
|
387
|
+
rings = [r for r in rings if len(r) >= 4]
|
|
388
|
+
if rings:
|
|
389
|
+
polygons.append(shapely.make_valid(shapely.Polygon(rings[0], rings[1:])))
|
|
390
|
+
if not polygons:
|
|
391
|
+
return None
|
|
392
|
+
return overlap.intersection(shapely.union_all(polygons))
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _difference(shapely: Any, front: Surface, back: Surface, xy: Array) -> Array:
|
|
396
|
+
"""How much nearer ``front`` is than ``back``, or ``-1`` where either misses.
|
|
397
|
+
|
|
398
|
+
A surface is hidden only where both are present and the other is nearer.
|
|
399
|
+
Where only one is -- the edge of a stroke, say -- the order of painting,
|
|
400
|
+
which puts whatever hides something after it, already gives the answer.
|
|
401
|
+
"""
|
|
402
|
+
a, b = _depth_of(shapely, front, xy), _depth_of(shapely, back, xy)
|
|
403
|
+
with np.errstate(invalid="ignore"):
|
|
404
|
+
z = a - b
|
|
405
|
+
z[~(np.isfinite(a) & np.isfinite(b))] = -1.0
|
|
406
|
+
return z
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _half_plane(shapely: Any, bounds: tuple[float, ...], a: float, b: float, c: float) -> Any:
|
|
410
|
+
"""The part of a box, grown a little, where ``a x + b y + c > 0`` (Sutherland-Hodgman)."""
|
|
411
|
+
x0, y0, x1, y1 = bounds
|
|
412
|
+
m = 1.0 + 0.01 * max(x1 - x0, y1 - y0)
|
|
413
|
+
box = [(x0 - m, y0 - m), (x1 + m, y0 - m), (x1 + m, y1 + m), (x0 - m, y1 + m)]
|
|
414
|
+
out: list[tuple[float, float]] = []
|
|
415
|
+
for i, p in enumerate(box):
|
|
416
|
+
q = box[(i + 1) % 4]
|
|
417
|
+
fp, fq = a * p[0] + b * p[1] + c, a * q[0] + b * q[1] + c
|
|
418
|
+
if fp > 0:
|
|
419
|
+
out.append(p)
|
|
420
|
+
if (fp > 0) != (fq > 0):
|
|
421
|
+
t = fp / (fp - fq)
|
|
422
|
+
out.append((p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])))
|
|
423
|
+
return shapely.Polygon(out) if len(out) >= 3 else shapely.Polygon()
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _probe_points(shapely: Any, region: Any) -> Array:
|
|
427
|
+
"""A few points spread over a region, for a quick test of which surface is in front."""
|
|
428
|
+
x0, y0, x1, y1 = region.bounds
|
|
429
|
+
gx, gy = np.meshgrid(np.linspace(x0, x1, 9)[1:-1], np.linspace(y0, y1, 9)[1:-1])
|
|
430
|
+
inside = shapely.contains_xy(region, gx.ravel(), gy.ravel())
|
|
431
|
+
pts = np.column_stack([gx.ravel()[inside], gy.ravel()[inside]])
|
|
432
|
+
rep = region.representative_point()
|
|
433
|
+
return np.vstack([pts, [[rep.x, rep.y]]])
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _rings(shapely: Any, geometry: Any) -> list[Array]:
|
|
437
|
+
"""The rings of a region, valid at the precision they are written in.
|
|
438
|
+
|
|
439
|
+
Snapped to the 0.01 grid that coordinates are rounded to on output, so the
|
|
440
|
+
written polygon is the valid one shapely computed rather than a rounding of
|
|
441
|
+
it, which can fold a thin spike over itself. Slivers and pinholes too
|
|
442
|
+
small to see are dropped.
|
|
443
|
+
"""
|
|
444
|
+
snapped = shapely.set_precision(geometry, 0.01)
|
|
445
|
+
rings: list[Array] = []
|
|
446
|
+
for poly in getattr(snapped, "geoms", [snapped]):
|
|
447
|
+
if poly.is_empty or poly.geom_type != "Polygon" or poly.area <= 0.01:
|
|
448
|
+
continue
|
|
449
|
+
poly = shapely.geometry.polygon.orient(poly, 1.0)
|
|
450
|
+
rings.append(np.asarray(poly.exterior.coords)[:-1])
|
|
451
|
+
rings += [
|
|
452
|
+
np.asarray(hole.coords)[:-1]
|
|
453
|
+
for hole in poly.interiors
|
|
454
|
+
if shapely.Polygon(hole).area > 0.01
|
|
455
|
+
]
|
|
456
|
+
return rings
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _split_line(
|
|
460
|
+
shapely: Any,
|
|
461
|
+
line: Line,
|
|
462
|
+
occluders: list[Surface],
|
|
463
|
+
regions: list[Any],
|
|
464
|
+
tree: Any,
|
|
465
|
+
eps: float,
|
|
466
|
+
) -> tuple[list[Array], list[Array]]:
|
|
467
|
+
"""Cut a line's runs where they pass behind an opaque surface."""
|
|
468
|
+
visible: list[Array] = []
|
|
469
|
+
hidden: list[Array] = []
|
|
470
|
+
for pts, depths in line.runs:
|
|
471
|
+
if len(pts) < 2:
|
|
472
|
+
continue
|
|
473
|
+
candidates = [int(j) for j in tree.query(shapely.LineString(pts))] if occluders else []
|
|
474
|
+
if not candidates:
|
|
475
|
+
visible.append(pts)
|
|
476
|
+
continue
|
|
477
|
+
|
|
478
|
+
def behind(xy: Array, d: Array, candidates: list[int] = candidates) -> Array:
|
|
479
|
+
flag = np.zeros(len(xy), dtype=bool)
|
|
480
|
+
for j in candidates:
|
|
481
|
+
inside = shapely.contains_xy(regions[j], xy[:, 0], xy[:, 1])
|
|
482
|
+
if inside.any():
|
|
483
|
+
front = _depth_of(shapely, occluders[j], xy[inside])
|
|
484
|
+
flag[inside] |= front > d[inside] + eps
|
|
485
|
+
return flag
|
|
486
|
+
|
|
487
|
+
# Sample every segment densely, then refine each change by bisection.
|
|
488
|
+
xy_parts, d_parts = [pts[:1]], [depths[:1]]
|
|
489
|
+
for i in range(len(pts) - 1):
|
|
490
|
+
n = max(int(np.ceil(np.linalg.norm(pts[i + 1] - pts[i]) / 0.5)), 1)
|
|
491
|
+
t = np.linspace(0.0, 1.0, n + 1)[1:, None]
|
|
492
|
+
xy_parts.append(pts[i] + t * (pts[i + 1] - pts[i]))
|
|
493
|
+
d_parts.append(depths[i] + t[:, 0] * (depths[i + 1] - depths[i]))
|
|
494
|
+
xy, d = np.vstack(xy_parts), np.concatenate(d_parts)
|
|
495
|
+
flags = behind(xy, d)
|
|
496
|
+
|
|
497
|
+
current = [xy[0]]
|
|
498
|
+
state = bool(flags[0])
|
|
499
|
+
for i in range(1, len(xy)):
|
|
500
|
+
if bool(flags[i]) != state:
|
|
501
|
+
lo, hi = 0.0, 1.0
|
|
502
|
+
for _ in range(12):
|
|
503
|
+
mid = 0.5 * (lo + hi)
|
|
504
|
+
p = xy[i - 1] + mid * (xy[i] - xy[i - 1])
|
|
505
|
+
dm = d[i - 1] + mid * (d[i] - d[i - 1])
|
|
506
|
+
if bool(behind(p[None, :], np.array([dm]))[0]) == state:
|
|
507
|
+
lo = mid
|
|
508
|
+
else:
|
|
509
|
+
hi = mid
|
|
510
|
+
cut = xy[i - 1] + 0.5 * (lo + hi) * (xy[i] - xy[i - 1])
|
|
511
|
+
current.append(cut)
|
|
512
|
+
(hidden if state else visible).append(np.array(current))
|
|
513
|
+
current, state = [cut], bool(flags[i])
|
|
514
|
+
current.append(xy[i])
|
|
515
|
+
(hidden if state else visible).append(np.array(current))
|
|
516
|
+
return [_simplify(r) for r in visible if len(r) >= 2], [
|
|
517
|
+
_simplify(r) for r in hidden if len(r) >= 2
|
|
518
|
+
]
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def _simplify(run: Array) -> Array:
|
|
522
|
+
"""Drop sample points that lie on a straight stretch, keeping the corners."""
|
|
523
|
+
if len(run) <= 2:
|
|
524
|
+
return run
|
|
525
|
+
keep = [0]
|
|
526
|
+
for i in range(1, len(run) - 1):
|
|
527
|
+
a, b, c = run[keep[-1]], run[i], run[i + 1]
|
|
528
|
+
cross = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
|
|
529
|
+
if abs(cross) > 1e-6 * max(float(np.linalg.norm(c - a)), 1.0) ** 2:
|
|
530
|
+
keep.append(i)
|
|
531
|
+
keep.append(len(run) - 1)
|
|
532
|
+
return run[keep]
|
vecview/_types.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Shared array type aliases.
|
|
2
|
+
|
|
3
|
+
``numpy`` accepts a wide range of array-likes. These aliases name the shapes
|
|
4
|
+
the public API actually cares about -- a single 3D point, and a sequence of them
|
|
5
|
+
-- so signatures stay readable when type checking.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Sequence
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
import numpy.typing as npt
|
|
15
|
+
|
|
16
|
+
type Array = npt.NDArray[np.float64]
|
|
17
|
+
"""A ``float64`` array of any shape."""
|
|
18
|
+
|
|
19
|
+
type Point3 = Sequence[float] | Array
|
|
20
|
+
"""One world-space point or direction, ``(x, y, z)``."""
|
|
21
|
+
|
|
22
|
+
type Points3 = Sequence[Point3] | Array
|
|
23
|
+
"""A sequence of world-space points, shape ``(n, 3)``."""
|
|
24
|
+
|
|
25
|
+
type Points2 = Sequence[Sequence[float]] | Array
|
|
26
|
+
"""A sequence of 2D points, shape ``(n, 2)`` -- a footprint in a plane."""
|
|
27
|
+
|
|
28
|
+
type Style = Any
|
|
29
|
+
"""An SVG presentation attribute value, passed through to ``svg.py``."""
|
|
30
|
+
|
|
31
|
+
__all__ = ["Array", "Point3", "Points2", "Points3", "Style"]
|