This commit is contained in:
jan 2018-03-20 15:10:45 -07:00
commit 3d7cf7b503
9 changed files with 934 additions and 736 deletions

0
__init__.py Normal file
View file

271
boundary.py Normal file
View file

@ -0,0 +1,271 @@
import numpy
from numpy.linalg import norm
from .util import _get_map, find_components, find_faces
try:
profile
except NameError:
def profile(f):
return f
def planes_from_boundary(vertices, faces):
planes = []
for face in faces:
face_verts = vertices[face]
n = numpy.cross(numpy.diff(face_verts, n=1, axis=0),
numpy.diff(face_verts, n=2, axis=0))
n /= norm(n)
centroid = numpy.sum(face_verts, axis=0) / len(face)
d = -n @ centroid
planes.append(n, d)
return planes
@profile
def build_polyhedron(in_vertices, faces):
in_vertices = numpy.array(in_vertices, dtype=float)
faces = [numpy.array(face, dtype=int) for face in faces]
edges_per_vertex = numpy.bincount(numpy.hstack(faces))
if edges_per_vertex.min() < 3:
raise Exception(f'Vertex {edges_per_vertex.argmin()} has < 3 edges')
if edges_per_vertex.max() == 3:
# Don't need to duplicate any vertices to make 3-connected graph
vertices = in_vertices
# Link up the vertices
neighbors = numpy.empty_like(vertices, dtype=int).fill(vertices.size)
for face in faces:
# Check if each vertex in this face is already linked to its next or previous face-neighbor
prev_vert = numpy.roll(face, 1)
next_vert = numpy.roll(face, -1)
neighbor_rows = neighbors[face, :]
has_prev = (neighbor_rows == prev_vert).any(axis=1)
has_next = (neighbor_rows == next_vert).any(axis=1)
# Each vertex touches 3 faces; each vertex triplet (neighbor_row) is a triangle on a face.
# Thus, we will never encounter a situation in which prv == nxt.
# If the vertex hasn't been linked to anything yet, set its first two
# polyhedron-neighbors to its face-neighbors
empty = numpy.logical_not(numpy.logical_or(has_prev, has_next))
neighbors[face[empty], 0] = next_vert[empty]
neighbors[face[empty], 1] = prev_vert[empty]
# If the vertex has already been linked to something (by a different face),
# fill in the third neighbor
# Note that this causes excess writes; it might improve performace to check
# if the third neighbor is already filled
neighbors[face[has_prev], 2] = next_vert[has_prev]
neighbors[face[has_next], 2] = prev_vert[has_next]
return {'vertices': vertices, 'neighbors': neighbors}
'''
Some vertices link more than three edges.
We only allow three edges per vertex in the graph, so we need to make
degenerate copies of those vertices.
For convenience, duplicate each vertex as many times as it has edges.
This creates 2 'excess' duplicates of each vertex (e.g. a vertex with
3 edges will turn into 3 vertices, even though it was fine as-is).
Link the "duplicate" vertices together, as follows:
- Each set of duplicates becomes a doubly-linked ring.
- Each duplicate has an additional, "third" pointer, pointing to one
of the duplicates created for a _different_ original vertex (i.e., this
pointer and its counterpart both correspond to the edge which caused
these two duplicates to be created).
We perform this linkage by creating a list of 3 entries per duplicate, aiming
to eventually fill each row with the indices
[next_row, third_row, prev_row]
corresponding to the linked duplicates.
We begin by filling columns (1, 2) with the (next, prev) _original_ vertex indices
for each face. The subset of the list corresponding to a single original vertex
thus looks like
[???, f0_next, f0_prev] <-- (i.e., the angle fromed by the three points
[???, f3_next, f3_prev] [..., prev, me, next, ...], where 'me' is the
[???, f7_next, f7_prev] (original) vertex index corresponding to this row
... and prev, next are original vertex indices as listed
in face 0's vertex list)
and so on, with a row and f# for each face the original vertex participates in.
The full list is just
[ rows for
original vertex 0
...
rows for
original vertex 1
...
etc
]
(note that each original vertex takes as many rows as it has edges)
Next, note that the newly filled columns will hold the same sets of numbers, just permuted.
Each row specifies two edges (an angle), and each edge is shared by two faces, and appears
once as a "previous" pointer and once as a "next" pointer.
So, we can set column 0 to the (new) index of the row whose f_prev matches our row's f_next.
In other words, pick column 0 to ensure dn[i, 1] == dn[dn[i, 0], 2]. Our columns become
[next_row, f#_next, f#_prev]
Then, replace f#_prev with a back-pointer based on next_row,
[next_row, f#_next, prev_row]
which completes our doubly-linked duplicate vertex rings.
To complete the linkage, we need to link to 'third_row'. We can do this by,
For each set of rows (corresponding to an original vertex V0),
- searching the sets of rows Vi corresponding to the listed f#_next values
for rows whose f#_next == V0
- doubly linking each row (i) in V0 with its 'found' row in Vi
Finally, we can remove the first two ('excess') duplicate vertices in each ring, and update
the links to reflect their removal.
'''
# starting row for each original vertex
vstart = numpy.roll(numpy.cumsum(edges_per_vertex), 1)
vstart[0] = 0
# number of input vertices (v) and duplicates (d)
num_v = in_vertices.shape[0]
num_duplicates = edges_per_vertex.sum()
# Linkage and aux array
neighbors = numpy.empty((num_duplicates, 3), dtype=int)
util = numpy.zeros(num_duplicates, dtype=int)
'''
Fill columns (1, 2) with original vertex inds (f#_next, f#_prev)
'''
for face in faces:
# assume a face can't use the same vertex twice
v_inds = vstart[face] + util[face]
neighbors[v_inds, 1] = numpy.roll(face, -1)
neighbors[v_inds, 2] = numpy.roll(face, 1)
util[face] += 1
'''
Fill columns (0, 2) with new vertex inds (next_row, prev_row)
to complete doubly-linked rings
'''
for v in range(num_v):
v0 = vstart[v]
s = slice(v0, v0 + edges_per_vertex[v])
m, n = _get_map(neighbors[s, 2], neighbors[s, 1])
neighbors[s, 0] = n + v0
neighbors[s, 2] = m + v0
'''
for each pair of original vertices,
find subvertices whose f#_next pointers point to each other's original vertices,
and link them using column 1 (i.e. set their third_row pointers to each other)
'''
# Mapping from row to original vertex index
v0s = numpy.repeat(numpy.arange(len(edges_per_vertex)), edges_per_vertex)
# Copy column 1 to save target info
target_vert = neighbors[:, 1].copy()
# Preallocate mask arrays
src_mask = numpy.empty(num_duplicates, dtype=bool)
dst_mask = numpy.empty(num_duplicates, dtype=bool)
for v in range(num_v):
s = vstart[v]
e = s + edges_per_vertex[v]
src_mask.fill(False)
src_mask[e:] = target_vert[e:] == v # find rows which reference us
src_vert = v0s[src_mask] # figure out their original vertex numbers
if src_vert.size == 0:
continue
dst_mask.fill(False)
dst_mask[s:e] = target_vert[s:e] > v # mask out any references to verts >= current
dst_vert = target_vert[dst_mask]
ma, mb = _get_map(dst_vert, src_vert)
neighbors[dst_mask, 1] = numpy.where(src_mask)[0][mb]
neighbors[src_mask, 1] = numpy.where(dst_mask)[0][ma]
'''
Remove first two duplicates of each vertex (they aren't needed)
'''
nxt, third, prv = neighbors[vstart, :].T
nxt_nxt, nxt_third, _nxt_prv = neighbors[nxt, :].T
# Which vertex to link to
dest_map = numpy.arange(num_duplicates, dtype=int) # default maps to itself
dest_map[vstart] = prv # first maps to previous
dest_map[nxt] = nxt_nxt # second maps to next
# Which backreference to modify
back_map = numpy.full_like(dest_map, 1) # default is 'third'
back_map[vstart] = 0 # if we mapped from a first vertex to its previous, set to 'next'
back_map[nxt] = 2 # if we mapped from a second vertex to its next, set to 'previous'
# Map 'third' to where it should point to
dm_third = dest_map[third]
dm_nxt_third = dest_map[nxt_third]
neighbors[prv, 0] = dm_third # previous's next reference points to third
neighbors[nxt_nxt, 2] = dm_nxt_third # next-next's previous reference points to next-third
neighbors[dm_third, back_map[third]] = prv # third's backreference points to previous
neighbors[dm_nxt_third, back_map[nxt_third]] = nxt_nxt # next-third's backreference points to next-next
# Mark for removal
util.fill(0)
util[vstart] = 1
util[nxt] = 1
neighbors = neighbors[util == 0]
util[util == 0] = numpy.arange(neighbors.shape[0])
neighbors[:] = util[neighbors]
vertices = numpy.repeat(in_vertices, edges_per_vertex - 2, axis=0)
return {'vertices': vertices, 'neighbors': neighbors}
@profile
def boundary_from_poly(poly):
neighbors = poly['neighbors']
vertices = poly['vertices']
owner_components = find_components(neighbors)
faces = find_faces(neighbors)
num_components = owner_components.max() + 1
components = [[] for _ in range(num_components)]
for face in faces:
component_ind = owner_components[face[0]]
components[component_ind].append(face)
unique_verts, unique_vertex_map = numpy.unique(vertices, axis=0, return_inverse=True)
umap = numpy.empty(unique_verts.shape[0], dtype=int)
boundary_map = numpy.empty(vertices.shape[0], dtype=int)
boundaries = []
for i, component in enumerate(components):
mask = owner_components == i
umask = unique_vertex_map[mask]
used_uverts = numpy.unique(umask)
umap[used_uverts] = numpy.arange(used_uverts.size) # map to account for deletion of unique verts not used in this component
boundary_map[mask] = umap[umask] # map from non-unique verts in face to unique, in-use verts
boundary = {
'vertices': unique_verts[used_uverts],
'faces': [boundary_map[face] for face in component],
}
boundaries.append(boundary)
return boundaries

197
pyl Normal file
View file

@ -0,0 +1,197 @@
************* Module pyr3d
C: 71, 0: Line too long (106/100) (line-too-long)
C:122, 0: Exactly one space required after comma
target_edge_inds = _searchsorted_rows(r2l_edges[:,:2], edge_walk_results[:, ::-1])
^ (bad-whitespace)
C:176, 0: Line too long (104/100) (line-too-long)
C:178, 0: Line too long (102/100) (line-too-long)
C:186, 0: Line too long (108/100) (line-too-long)
C:192, 0: Line too long (149/100) (line-too-long)
C:209, 0: Line too long (108/100) (line-too-long)
C:295, 0: No space allowed before comma
S = numpy.zeros((3, poly_order + 1, poly_order + 1, 2) , dtype=float)
^ (bad-whitespace)
C:319, 0: Line too long (103/100) (line-too-long)
C:348, 0: Line too long (105/100) (line-too-long)
C:374, 0: Line too long (104/100) (line-too-long)
W:410, 0: Bad indentation. Found 8 spaces, expected 4 (bad-indentation)
W:411, 0: Bad indentation. Found 8 spaces, expected 4 (bad-indentation)
C:436, 0: Unnecessary parens after 'assert' keyword (superfluous-parens)
C:465, 0: Line too long (103/100) (line-too-long)
C:472, 0: Line too long (102/100) (line-too-long)
C:633, 0: Line too long (103/100) (line-too-long)
C:634, 0: Line too long (104/100) (line-too-long)
C:643, 0: Line too long (106/100) (line-too-long)
C:644, 0: Line too long (112/100) (line-too-long)
C:718, 0: Exactly one space required after comma
((0,0,1), -rbounds[0, 2]),
^ (bad-whitespace)
C:718, 0: Exactly one space required after comma
((0,0,1), -rbounds[0, 2]),
^ (bad-whitespace)
C:719, 0: Exactly one space required after comma
((0,0,-1), rbounds[1, 2]),
^ (bad-whitespace)
C:719, 0: Exactly one space required after comma
((0,0,-1), rbounds[1, 2]),
^ (bad-whitespace)
C:720, 0: Exactly one space required after comma
((0,1,0), -rbounds[0, 1]),
^ (bad-whitespace)
C:720, 0: Exactly one space required after comma
((0,1,0), -rbounds[0, 1]),
^ (bad-whitespace)
C:721, 0: Exactly one space required after comma
((0,-1,0), rbounds[1, 1]),
^ (bad-whitespace)
C:721, 0: Exactly one space required after comma
((0,-1,0), rbounds[1, 1]),
^ (bad-whitespace)
C:722, 0: Exactly one space required after comma
((1,0,0), -rbounds[0, 0]),
^ (bad-whitespace)
C:722, 0: Exactly one space required after comma
((1,0,0), -rbounds[0, 0]),
^ (bad-whitespace)
C:723, 0: Exactly one space required after comma
((-1,0,0), rbounds[1, 0]),
^ (bad-whitespace)
C:723, 0: Exactly one space required after comma
((-1,0,0), rbounds[1, 0]),
^ (bad-whitespace)
C:785, 0: Line too long (132/100) (line-too-long)
C:786, 0: Line too long (103/100) (line-too-long)
C:840, 0: No space allowed before bracket
stack.append((children[0], numpy.vstack((c_ibox[0], split_plane[1])) ))
^ (bad-whitespace)
C:841, 0: No space allowed before bracket
stack.append((children[1], numpy.vstack((split_plane[0], c_ibox[1])) ))
^ (bad-whitespace)
C:857, 0: Trailing newlines (trailing-newlines)
C: 1, 0: Missing module docstring (missing-docstring)
W: 10, 0: No exception type(s) specified (bare-except)
C: 11, 4: Argument name "f" doesn't conform to snake_case naming style (invalid-name)
C: 11, 4: Missing function docstring (missing-docstring)
C: 15, 0: Missing function docstring (missing-docstring)
C: 27, 0: Function name "NUM_MOMENTS" doesn't conform to snake_case naming style (invalid-name)
C: 27, 0: Missing function docstring (missing-docstring)
C: 31, 0: Missing function docstring (missing-docstring)
C: 38, 0: Constant name "empty_partial_result" doesn't conform to UPPER_CASE naming style (invalid-name)
C: 46, 0: Missing function docstring (missing-docstring)
R: 46, 0: Too many local variables (38/15) (too-many-locals)
W: 65, 4: Unused variable 'num_right_vertices' (unused-variable)
W: 91, 4: Unused variable 'edge_walk_inds' (unused-variable)
C:132, 0: Argument name "a" doesn't conform to snake_case naming style (invalid-name)
C:138, 0: Argument name "a" doesn't conform to snake_case naming style (invalid-name)
C:138, 0: Argument name "b" doesn't conform to snake_case naming style (invalid-name)
C:145, 0: Missing function docstring (missing-docstring)
C:151, 0: Missing function docstring (missing-docstring)
R:151, 0: Too many local variables (27/15) (too-many-locals)
R:167, 8: Unnecessary "else" after "return" (no-else-return)
W:174,-1: String statement has no effect (pointless-string-statement)
C:180, 4: Variable name "re" doesn't conform to snake_case naming style (invalid-name)
C:180, 8: Variable name "le" doesn't conform to snake_case naming style (invalid-name)
C:227, 0: Missing function docstring (missing-docstring)
R:227, 0: Too many local variables (16/15) (too-many-locals)
C:241,15: Variable name "vn" doesn't conform to snake_case naming style (invalid-name)
C:266, 0: Missing function docstring (missing-docstring)
R:266, 0: Too many local variables (28/15) (too-many-locals)
C:295, 4: Variable name "S" doesn't conform to snake_case naming style (invalid-name)
C:297, 4: Variable name "mx" doesn't conform to snake_case naming style (invalid-name)
C:297, 8: Variable name "my" doesn't conform to snake_case naming style (invalid-name)
C:305, 8: Variable name "m" doesn't conform to snake_case naming style (invalid-name)
C:306,12: Variable name "c" doesn't conform to snake_case naming style (invalid-name)
C:325,12: Variable name "m" doesn't conform to snake_case naming style (invalid-name)
C:330, 4: Variable name "m" doesn't conform to snake_case naming style (invalid-name)
C:333, 8: Variable name "c" doesn't conform to snake_case naming style (invalid-name)
C:349, 8: Variable name "m" doesn't conform to snake_case naming style (invalid-name)
R:266, 0: Too many statements (59/50) (too-many-statements)
C:356, 0: Missing function docstring (missing-docstring)
R:356, 0: Too many local variables (20/15) (too-many-locals)
E:378, 7: Undefined variable 'check_connectivity' (undefined-variable)
C:387,16: Variable name "ia" doesn't conform to snake_case naming style (invalid-name)
C:388,16: Variable name "va" doesn't conform to snake_case naming style (invalid-name)
C:389,20: Variable name "vb" doesn't conform to snake_case naming style (invalid-name)
C:391,20: Variable name "vc" doesn't conform to snake_case naming style (invalid-name)
E:394,16: Undefined variable 'visited' (undefined-variable)
E:395,16: Undefined variable 'visited' (undefined-variable)
W:395,29: Using possibly undefined loop variable 'vb' (undefined-loop-variable)
E:399,20: Undefined variable 'visited' (undefined-variable)
E:401,37: Undefined variable 'visited' (undefined-variable)
E:404,23: Undefined variable 'visited' (undefined-variable)
C:409, 0: Missing function docstring (missing-docstring)
C:410, 8: Variable name "ad" doesn't conform to snake_case naming style (invalid-name)
C:410,12: Variable name "bd" doesn't conform to snake_case naming style (invalid-name)
C:410,16: Variable name "cd" doesn't conform to snake_case naming style (invalid-name)
C:414, 0: Missing function docstring (missing-docstring)
C:422, 4: Variable name "ab" doesn't conform to snake_case naming style (invalid-name)
C:423, 4: Variable name "cd" doesn't conform to snake_case naming style (invalid-name)
C:425, 4: Variable name "n" doesn't conform to snake_case naming style (invalid-name)
C:426, 4: Variable name "n" doesn't conform to snake_case naming style (invalid-name)
C:428, 4: Variable name "d" doesn't conform to snake_case naming style (invalid-name)
E:428, 8: bad operand type for unary -: NoneType (invalid-unary-operand-type)
C:433, 0: Argument name "a" doesn't conform to snake_case naming style (invalid-name)
C:433, 0: Argument name "b" doesn't conform to snake_case naming style (invalid-name)
C:433, 0: Missing function docstring (missing-docstring)
C:439, 4: Variable name "sa" doesn't conform to snake_case naming style (invalid-name)
C:440, 4: Variable name "sb" doesn't conform to snake_case naming style (invalid-name)
C:441, 4: Variable name "ra" doesn't conform to snake_case naming style (invalid-name)
C:442, 4: Variable name "rb" doesn't conform to snake_case naming style (invalid-name)
C:449, 0: Missing function docstring (missing-docstring)
R:449, 0: Too many local variables (41/15) (too-many-locals)
R:458, 4: Unnecessary "else" after "return" (no-else-return)
W:552,-1: String statement has no effect (pointless-string-statement)
W:567,-1: String statement has no effect (pointless-string-statement)
W:578,-1: String statement has no effect (pointless-string-statement)
C:579,12: Variable name "v" doesn't conform to snake_case naming style (invalid-name)
C:580,12: Variable name "v0" doesn't conform to snake_case naming style (invalid-name)
C:581,12: Variable name "s" doesn't conform to snake_case naming style (invalid-name)
C:582,12: Variable name "m" doesn't conform to snake_case naming style (invalid-name)
C:582,15: Variable name "n" doesn't conform to snake_case naming style (invalid-name)
W:590,-1: String statement has no effect (pointless-string-statement)
C:601,12: Variable name "v" doesn't conform to snake_case naming style (invalid-name)
C:602,12: Variable name "s" doesn't conform to snake_case naming style (invalid-name)
C:603,12: Variable name "e" doesn't conform to snake_case naming style (invalid-name)
C:616,12: Variable name "ma" doesn't conform to snake_case naming style (invalid-name)
C:616,16: Variable name "mb" doesn't conform to snake_case naming style (invalid-name)
W:622,-1: String statement has no effect (pointless-string-statement)
R:449, 0: Too many statements (78/50) (too-many-statements)
C:660, 0: Missing function docstring (missing-docstring)
C:661, 4: Variable name "s" doesn't conform to snake_case naming style (invalid-name)
C:661, 7: Variable name "c" doesn't conform to snake_case naming style (invalid-name)
C:662, 4: Variable name "v0" doesn't conform to snake_case naming style (invalid-name)
C:663, 4: Variable name "v1" doesn't conform to snake_case naming style (invalid-name)
C:668, 0: Missing function docstring (missing-docstring)
C:672, 0: Missing function docstring (missing-docstring)
W:672,16: Redefining name 'scale' from outer scope (line 672) (redefined-outer-name)
C:676, 0: Missing function docstring (missing-docstring)
W:676,16: Redefining name 'shear' from outer scope (line 676) (redefined-outer-name)
W:676,16: Unused argument 'shear' (unused-argument)
C:680, 0: Missing function docstring (missing-docstring)
C:683, 4: Variable name "vh" doesn't conform to snake_case naming style (invalid-name)
C:687, 0: Missing function docstring (missing-docstring)
C:716, 0: Missing function docstring (missing-docstring)
C:729, 0: Missing function docstring (missing-docstring)
C:734, 8: Variable name "n" doesn't conform to snake_case naming style (invalid-name)
C:736, 8: Variable name "n" doesn't conform to snake_case naming style (invalid-name)
C:738, 8: Variable name "d" doesn't conform to snake_case naming style (invalid-name)
C:744, 0: Missing function docstring (missing-docstring)
C:763, 0: Missing function docstring (missing-docstring)
R:763, 0: Too many local variables (20/15) (too-many-locals)
C:797, 0: Argument name "d" doesn't conform to snake_case naming style (invalid-name)
C:797, 0: Missing function docstring (missing-docstring)
R:797, 0: Too many local variables (20/15) (too-many-locals)
C:829, 8: Variable name "n" doesn't conform to snake_case naming style (invalid-name)
C:845, 0: Argument name "d" doesn't conform to snake_case naming style (invalid-name)
C:845, 0: Missing function docstring (missing-docstring)
C:851, 0: Argument name "d" doesn't conform to snake_case naming style (invalid-name)
C:851, 0: Missing function docstring (missing-docstring)
E:854,26: Undefined variable 'plane' (undefined-variable)
W:853, 8: Unused variable 'face' (unused-variable)
W: 1, 0: Unused List imported from typing (unused-import)
W: 4, 0: Unused pi imported from numpy (unused-import)
W: 4, 0: Unused sqrt imported from numpy (unused-import)
------------------------------------------------------------------
Your code has been rated at 5.90/10 (previous run: 5.90/10, +0.00)

671
pyr3d.py
View file

@ -1,68 +1,47 @@
from typing import List, Dict, Tuple from typing import Dict, Tuple
import numpy import numpy
from numpy import pi, cos, sin, sqrt
from numpy.linalg import norm
from .util import _searchsorted_rows, _argsort_rows, find_faces, number_of_moments
try: try:
profile profile
except: except NameError:
def profile(f): def profile(f):
return f return f
def init_tet(verts: numpy.ndarray): def build_empty_poly() -> Dict:
poly = {
'vertices': numpy.array(verts, dtype=float),
'neighbors': numpy.array((
(1, 3, 2),
(2, 3, 0),
(0, 3, 1),
(1, 2, 0)), dtype=int),
}
return poly
def NUM_MOMENTS(order):
return ((order + 1) * (order + 2) * (order + 3)) // 6
def empty_poly() -> Dict:
return { return {
'vertices': numpy.empty((0, 3), dtype=float), 'vertices': numpy.empty((0, 3), dtype=float),
'neighbors': numpy.empty((0, 3), dtype=int), 'neighbors': numpy.empty((0, 3), dtype=int),
} }
empty_partial_result = ( def clip(poly, plane):
numpy.empty((0, 3), dtype=int), left_poly = split(poly, plane, left_only=True)
numpy.empty((0, 1), dtype=int), return left_poly
numpy.empty((0, 3), dtype=float),
numpy.empty((0, 1), dtype=int),
)
@profile @profile
def simple_clip(poly: Dict, plane: Tuple) -> Dict: def split(poly, plane, left_only: bool = False):
vertices = poly['vertices'] vertices = poly['vertices']
neighbors = poly['neighbors'] neighbors = poly['neighbors']
num_vertices = vertices.shape[0]
dists = plane[1] + (vertices @ plane[0]) dists = plane[1] + (vertices @ plane[0])
left = dists > 0 left = dists > 0
right = numpy.logical_not(left) right = numpy.logical_not(left)
# if the poly lies entirely on one side of the plane, just return the right/left masks # if the poly lies entirely on one side of the plane, just return it
ret = None
if not numpy.any(left): if not numpy.any(left):
# if all on right or touching plane # if all on right or touching plane
return (left,) + empty_partial_result ret = build_empty_poly(), poly
if numpy.min(dists) >= 0: elif numpy.min(dists) >= 0:
# if all on left or touching plane # if all on left or touching plane
# Can't reuse 'left' because <= vs < # Can't reuse 'left' because <= vs <
return (numpy.ones_like(left),) + empty_partial_result ret = poly, build_empty_poly()
if ret is not None:
num_left_vertices = numpy.count_nonzero(left) return ret[0] if left_only else ret
num_right_vertices = num_vertices - num_left_vertices
right_inds = numpy.where(right)[0] right_inds = numpy.where(right)[0]
right_inds3 = numpy.repeat(right_inds, 3) right_inds3 = numpy.repeat(right_inds, 3)
@ -78,8 +57,12 @@ def simple_clip(poly: Dict, plane: Tuple) -> Dict:
if r2l_edges.size == 0: if r2l_edges.size == 0:
# No edges cross, but components on either side # No edges cross, but components on either side
return (left,) + empty_partial_result r2l_edges = numpy.empty((0, 3), dtype=int)
target_edge_inds = numpy.empty((0, 1), dtype=int)
new_vertices = numpy.empty((0, 3), dtype=float)
src_pns = numpy.empty((0, 1), dtype=int)
num_new_vertices = 0
else:
# sort now so we can use searchsorted later # sort now so we can use searchsorted later
r2l_edge_order = _argsort_rows(r2l_edges[:, :2]) r2l_edge_order = _argsort_rows(r2l_edges[:, :2])
r2l_edges = r2l_edges[r2l_edge_order] r2l_edges = r2l_edges[r2l_edge_order]
@ -89,7 +72,6 @@ def simple_clip(poly: Dict, plane: Tuple) -> Dict:
# walk counter-clockwise to next crossing edge # walk counter-clockwise to next crossing edge
edge_walk = r2l_edges[:, :2].copy() edge_walk = r2l_edges[:, :2].copy()
edge_walk_inds = numpy.arange(num_new_vertices) edge_walk_inds = numpy.arange(num_new_vertices)
edge_walk_inds2 = numpy.arange(num_new_vertices)
edge_walk_results = numpy.empty_like(edge_walk) edge_walk_results = numpy.empty_like(edge_walk)
src_pns = None src_pns = None
while edge_walk.size > 0: while edge_walk.size > 0:
@ -111,63 +93,26 @@ def simple_clip(poly: Dict, plane: Tuple) -> Dict:
# Save edges that cross back to right, and remove them from edge_walk # Save edges that cross back to right, and remove them from edge_walk
done = right[next_verts] done = right[next_verts]
not_done = numpy.logical_not(done) not_done = numpy.logical_not(done)
edge_walk_results[edge_walk_inds2[done], 0] = cur_verts[done] edge_walk_results[edge_walk_inds[done], 0] = cur_verts[done]
edge_walk_results[edge_walk_inds2[done], 1] = next_verts[done] edge_walk_results[edge_walk_inds[done], 1] = next_verts[done]
edge_walk = numpy.column_stack((cur_verts[not_done], next_verts[not_done])) edge_walk = numpy.column_stack((cur_verts[not_done], next_verts[not_done]))
edge_walk_inds2 = edge_walk_inds2[not_done] edge_walk_inds = edge_walk_inds[not_done]
# now edge_walk is list of [[target connected vertex, target clipped adjacent vertex], ...] # now edge_walk is list of [[target connected vertex, target clipped adjacent vertex], ...]
# figure out the index of each target edge... # figure out the index of each target edge...
target_edge_inds = _searchsorted_rows(r2l_edges[:,:2], edge_walk_results[:, ::-1]) target_edge_inds = _searchsorted_rows(r2l_edges[:, :2], edge_walk_results[:, ::-1])
v_right = r2l_edges[:, 0] v_right = r2l_edges[:, 0]
v_left = r2l_edges[:, 1] v_left = r2l_edges[:, 1]
d_right = dists[v_right][:, None] d_right = dists[v_right][:, None]
d_left = dists[v_left][:, None] d_left = dists[v_left][:, None]
new_vertices = (d_right * vertices[v_left] - d_left * vertices[v_right]) / (d_right - d_left) new_vertices = (d_right * vertices[v_left] - d_left * vertices[v_right]) / (d_right - d_left)
return left, r2l_edges, target_edge_inds, new_vertices, src_pns
def _argsort_rows(a):
dims = a.max(0) + 1
a1d = numpy.ravel_multi_index(a.T, dims)
return numpy.argsort(a1d)
def _searchsorted_rows(a, b):
dims = numpy.maximum(a.max(0), b.max(0)) + 1
a1d = numpy.ravel_multi_index(a.T, dims)
b1d = numpy.ravel_multi_index(b.T, dims)
return numpy.searchsorted(a1d, b1d)
def clip(poly, plane):
left_poly = split(poly, plane, left_only=True)
return left_poly
@profile
def split(poly, plane, left_only: bool = False):
left, r2l_edges, target_edge_inds, new_vertices, src_pn = simple_clip(poly, plane)
right = numpy.logical_not(left)
# vertex counts # vertex counts
num_start = poly['vertices'].shape[0] num_start = poly['vertices'].shape[0]
num_left = numpy.count_nonzero(left) num_left = numpy.count_nonzero(left)
num_right = num_start - num_left num_right = num_start - num_left
num_new = r2l_edges.shape[0]
if num_left == 0 or num_right == 0:
if num_left == 0:
ret = empty_poly(), poly
else:
ret = poly, empty_poly()
if left_only:
return ret[0]
else:
return ret
''' '''
map from old vertex ind to new map from old vertex ind to new
@ -190,7 +135,7 @@ def split(poly, plane, left_only: bool = False):
old_neighbors_left = poly['neighbors'].copy() old_neighbors_left = poly['neighbors'].copy()
old_neighbors_left[left] = ind_map_left[old_neighbors_left[left]] # map vertices on left side, wrongly mapping any right-side vertices to 0 old_neighbors_left[left] = ind_map_left[old_neighbors_left[left]] # map vertices on left side, wrongly mapping any right-side vertices to 0
old_neighbors_left[(le, src_pn)] = num_left + numpy.arange(num_new) old_neighbors_left[(le, src_pns)] = num_left + numpy.arange(num_new_vertices)
old_neighbors_left = old_neighbors_left[left] old_neighbors_left = old_neighbors_left[left]
left_poly = { left_poly = {
@ -213,7 +158,7 @@ def split(poly, plane, left_only: bool = False):
old_neighbors_right = poly['neighbors'].copy() old_neighbors_right = poly['neighbors'].copy()
old_neighbors_right[right] = ind_map_right[old_neighbors_right[right]] old_neighbors_right[right] = ind_map_right[old_neighbors_right[right]]
old_neighbors_right[(re, r2l_edges[:, 2])] = num_right + numpy.arange(num_new) old_neighbors_right[(re, r2l_edges[:, 2])] = num_right + numpy.arange(num_new_vertices)
old_neighbors_right = old_neighbors_right[right] old_neighbors_right = old_neighbors_right[right]
right_poly = { right_poly = {
@ -223,44 +168,6 @@ def split(poly, plane, left_only: bool = False):
return left_poly, right_poly return left_poly, right_poly
@profile
def find_faces(neighbors):
num_verts = neighbors.shape[0]
edge_id = numpy.arange(3 * num_verts)
nxt_edge = numpy.tile(numpy.arange(3), num_verts)
vstart = edge_id // 3
vcur = vstart.copy()
vnext = neighbors[vcur, nxt_edge]
faces = [[v] for v in vcur]
mask = vstart # dummy for loop init, could use numpy.array([True])
remove = numpy.zeros_like(edge_id, dtype=bool)
while mask.any():
for i, vn in zip(edge_id, vnext):
faces[i].append(vn)
prv_edge = (neighbors[vnext, :] == vcur[:, None]).argmax(axis=1)
nxt_edge = (prv_edge + 1) % 3
vcur, vnext = vnext, neighbors[vnext, nxt_edge]
remove_mask = vcur < vstart
remove[edge_id[remove_mask]] = True
mask = numpy.logical_and(vnext != vstart, ~remove_mask)
edge_id = edge_id[mask]
vcur = vcur[mask]
vnext = vnext[mask]
vstart = vstart[mask]
faces_set = []
for i, do_remove in enumerate(remove):
if not do_remove:
faces_set.append(faces[i])
return faces_set
@profile @profile
def reduce(poly, poly_order): def reduce(poly, poly_order):
@ -268,7 +175,7 @@ def reduce(poly, poly_order):
neighbors = poly['neighbors'] neighbors = poly['neighbors']
num_verts = vertices.shape[0] num_verts = vertices.shape[0]
moments = numpy.zeros(NUM_MOMENTS(poly_order), dtype=float) moments = numpy.zeros(number_of_moments(poly_order), dtype=float)
if num_verts == 0: if num_verts == 0:
return moments return moments
@ -291,10 +198,8 @@ def reduce(poly, poly_order):
volumes = -numpy.linalg.det(triangles) volumes = -numpy.linalg.det(triangles)
moments[0] = volumes.sum() / 6 moments[0] = volumes.sum() / 6
#// Storage for coefficients keep two layers of the pyramid of coefficients
#// Note: Uses twice as much space as needed, but indexing is faster this way
prevlayer, curlayer = 0, 1 prevlayer, curlayer = 0, 1
S = numpy.zeros((3, poly_order + 1, poly_order + 1, 2) , dtype=float) S = numpy.zeros((3, poly_order + 1, poly_order + 1, 2), dtype=float)
inds = numpy.arange(poly_order + 1) inds = numpy.arange(poly_order + 1)
mx, my = numpy.meshgrid(inds, inds, indexing='ij') mx, my = numpy.meshgrid(inds, inds, indexing='ij')
valid = numpy.zeros((2, poly_order + 1, poly_order + 1), dtype=bool) valid = numpy.zeros((2, poly_order + 1, poly_order + 1), dtype=bool)
@ -307,7 +212,7 @@ def reduce(poly, poly_order):
m = 1 m = 1
for c in range(1, poly_order+1): for c in range(1, poly_order+1):
valid[curlayer] = c >= mx + my valid[curlayer] = c >= mx + my
num_valid = (c + 1) * (c + 2) // 2 # always an int, see NUM_MOMENTS() num_valid = (c + 1) * (c + 2) // 2 # always an int, see number_of_moments()
S[:, 0, :, curlayer] = 0 S[:, 0, :, curlayer] = 0
@ -327,14 +232,14 @@ def reduce(poly, poly_order):
m += num_valid m += num_valid
prevlayer, curlayer = curlayer, prevlayer prevlayer, curlayer = curlayer, prevlayer
#// reuse S to recursively compute the leading multinomial coefficients # reuse S[0] to compute the moments' coefficients
S[0, 0, 0, prevlayer] = 1 S[0, 0, 0, prevlayer] = 1
m = 1 m = 1
valid[prevlayer, :, :] = False valid[prevlayer, :, :] = False
valid[prevlayer, 0, 0] = True valid[prevlayer, 0, 0] = True
for c in range(1, poly_order+1): for c in range(1, poly_order+1):
valid[curlayer] = c >= mx + my valid[curlayer] = c >= mx + my
num_valid = (c + 1) * (c + 2) // 2 # always an int, see NUM_MOMENTS() num_valid = (c + 1) * (c + 2) // 2 # always an int, see number_of_moments()
S[0, 0, :, curlayer] = 0 S[0, 0, :, curlayer] = 0
@ -354,513 +259,3 @@ def reduce(poly, poly_order):
return moments return moments
@profile
def is_good(poly) -> bool:
neighbors = poly['neighbors']
vertices = poly['vertices']
num_vertices = vertices.shape[0]
out_of_bounds = numpy.logical_or(neighbors >= vertices.shape[0], neighbors < 0)
if numpy.any(out_of_bounds):
which_vertices = numpy.where(out_of_bounds)[0]
raise Exception(f'Vertices {which_vertices} have out-of-bounds neighbors')
repeated_neighbors = neighbors == numpy.roll(neighbors, 1, axis=1)
if numpy.any(repeated_neighbors):
which_vertices = numpy.where(repeated_neighbors)[0]
raise Exception(f'Vertices {which_vertices} have duplicate neighbors')
vertex_uses = numpy.bincount(neighbors.ravel())
if numpy.any(vertex_uses != 3):
which_vertices = numpy.where(vertex_uses != 3)[0]
raise Exception(f'Vertices {which_vertices} are referenced {vertex_uses[which_vertices]} times,'
' should be exactly 3')
# check for 3-vertex-connectedness (slow, n^2)
#// handle multiply-connected polyhedra by testing each component separately
#// Flood-fill starting from each vertex to give each connected region a unique ID.
regions = find_components(neighbors)
# loop over unique pairs of verts
vct = numpy.empty_like(regions, dtype=bool)
for va in range(num_vertices):
rcur = regions[va]
vbs = numpy.arange(va + 1, num_vertices)
vbs_in_rcur = vbs[regions[vbs] == rcur]
for vb in vbs:
# pick vc != va && vc != vb and in the same connected component as va and vb
for vc in numpy.where(regions == rcur)[0]:
if vc != va and vc != vb:
break
# use vct to mark visited verts mask out va and vb
vct.fill(False)
vct[va] = True
vct[vb] = True
# flood-fill from vc to make sure the graph is still connected when va and vb are masked
if not vct[vc]:
nums = numpy.array([vc], dtype=int)
while nums.size > 0:
vct[nums] = True
new_nums = numpy.unique(neighbors[nums])
nums = new_nums[~vct[new_nums]]
# if any verts in the region rcur were untouched, the graph is only
# 2-vertex-connected and hence an invalid polyhedron
if not vct[regions == rcur].all():
raise Exception('Not 3-vertex connected')
return True
def orient(tet_verts):
ad, bd, cd = tet_verts[0:3] - tet_verts[3]
return -ad @ numpy.cross(bd, cd) / 6
def tet_faces_from_verts(tet_verts):
verts = numpy.array(tet_verts, dtype=float)
vset_inds = numpy.array((
[3, 1, 2, 1],
[2, 0, 3, 2],
[1, 3, 0, 3],
[0, 2, 1, 0]))
vertsets = numpy.moveaxis(numpy.dstack(verts[v] for v in vset_inds), 2, 0)
ab = vertsets[:, 0, :] - vertsets[:, 1, :]
cd = vertsets[:, 2, :] - vertsets[:, 3, :]
n = numpy.cross(ab, cd)
n /= norm(n, axis=1)[:, None]
centers = numpy.sum(vertsets[:, :3, :], axis=1) / 3
d = -numpy.sum(n * centers, axis=1)
return [plane for plane in zip(n, d)]
def get_map(a, b):
# Assume all elements appear exactly once in each array
# Returns m, n such that a[m] == b, b[n] == a
assert(a.size == b.size)
if a.size == 0:
return numpy.array(()), numpy.array(())
sa = a.argsort()
sb = b.argsort()
ra = numpy.empty_like(sa)
rb = numpy.empty_like(sa)
ra[sa] = numpy.arange(sa.size)
rb[sb] = numpy.arange(sa.size)
return sa[rb], sb[ra]
@profile
def init_poly(in_vertices, faces):
in_vertices = numpy.array(in_vertices, dtype=float)
faces = [numpy.array(face, dtype=int) for face in faces]
edges_per_vertex = numpy.bincount(numpy.hstack(faces))
if edges_per_vertex.min() < 3:
raise Exception(f'Vertex {edges_per_vertex.argmin()} has < 3 edges')
if edges_per_vertex.max() == 3:
# Don't need to duplicate any vertices to make 3-connected graph
vertices = in_vertices
# Link up the vertices
neighbors = numpy.empty_like(vertices, dtype=int).fill(vertices.size)
for face in faces:
# Check if each vertex in this face is already linked to its next or previous face-neighbor
prev_vert = numpy.roll(face, 1)
next_vert = numpy.roll(face, -1)
neighbor_rows = neighbors[face, :]
has_prev = (neighbor_rows == prev_vert).any(axis=1)
has_next = (neighbor_rows == next_vert).any(axis=1)
# Each vertex touches 3 faces; each vertex triplet (neighbor_row) is a triangle on a face.
# Thus, we will never encounter a situation in which prv == nxt.
# If the vertex hasn't been linked to anything yet, set its first two
# polyhedron-neighbors to its face-neighbors
empty = numpy.logical_not(numpy.logical_or(has_prev, has_next))
neighbors[face[empty], 0] = next_vert[empty]
neighbors[face[empty], 1] = prev_vert[empty]
# If the vertex has already been linked to something (by a different face),
# fill in the third neighbor
# Note that this causes excess writes; it might improve performace to check
# if the third neighbor is already filled
neighbors[face[has_prev], 2] = next_vert[has_prev]
neighbors[face[has_next], 2] = prev_vert[has_next]
return {'vertices': vertices, 'neighbors': neighbors}
else:
'''
Some vertices link more than three edges.
We only allow three edges per vertex in the graph, so we need to make
degenerate copies of those vertices.
For convenience, duplicate each vertex as many times as it has edges.
This creates 2 'excess' duplicates of each vertex (e.g. a vertex with
3 edges will turn into 3 vertices, even though it was fine as-is).
Link the "duplicate" vertices together, as follows:
- Each set of duplicates becomes a doubly-linked ring.
- Each duplicate has an additional, "third" pointer, pointing to one
of the duplicates created for a _different_ original vertex (i.e., this
pointer and its counterpart both correspond to the edge which caused
these two duplicates to be created).
We perform this linkage by creating a list of 3 entries per duplicate, aiming
to eventually fill each row with the indices
[next_row, third_row, prev_row]
corresponding to the linked duplicates.
We begin by filling columns (1, 2) with the (next, prev) _original_ vertex indices
for each face. The subset of the list corresponding to a single original vertex
thus looks like
[???, f0_next, f0_prev] <-- (i.e., the angle fromed by the three points
[???, f3_next, f3_prev] [..., prev, me, next, ...], where 'me' is the
[???, f7_next, f7_prev] (original) vertex index corresponding to this row
... and prev, next are original vertex indices as listed
in face 0's vertex list)
and so on, with a row and f# for each face the original vertex participates in.
The full list is just
[ rows for
original vertex 0
...
rows for
original vertex 1
...
etc
]
(note that each original vertex takes as many rows as it has edges)
Next, note that the newly filled columns will hold the same sets of numbers, just permuted.
Each row specifies two edges (an angle), and each edge is shared by two faces, and appears
once as a "previous" pointer and once as a "next" pointer.
So, we can set column 0 to the (new) index of the row whose f_prev matches our row's f_next.
In other words, pick column 0 to ensure dn[i, 1] == dn[dn[i, 0], 2]. Our columns become
[next_row, f#_next, f#_prev]
Then, replace f#_prev with a back-pointer based on next_row,
[next_row, f#_next, prev_row]
which completes our doubly-linked duplicate vertex rings.
To complete the linkage, we need to link to 'third_row'. We can do this by,
For each set of rows (corresponding to an original vertex V0),
- searching the sets of rows Vi corresponding to the listed f#_next values
for rows whose f#_next == V0
- doubly linking each row (i) in V0 with its 'found' row in Vi
Finally, we can remove the first two ('excess') duplicate vertices in each ring, and update
the links to reflect their removal.
'''
# starting row for each original vertex
vstart = numpy.roll(numpy.cumsum(edges_per_vertex), 1)
vstart[0] = 0
# number of input vertices (v) and duplicates (d)
num_v = in_vertices.shape[0]
num_duplicates = edges_per_vertex.sum()
# Linkage and aux array
neighbors = numpy.empty((num_duplicates, 3), dtype=int)
util = numpy.zeros(num_duplicates, dtype=int)
'''
Fill columns (1, 2) with original vertex inds (f#_next, f#_prev)
'''
for face in faces:
# assume a face can't use the same vertex twice
v_inds = vstart[face] + util[face]
neighbors[v_inds, 1] = numpy.roll(face, -1)
neighbors[v_inds, 2] = numpy.roll(face, 1)
util[face] += 1
'''
Fill columns (0, 2) with new vertex inds (next_row, prev_row)
to complete doubly-linked rings
'''
for v in range(num_v):
v0 = vstart[v]
s = slice(v0, v0 + edges_per_vertex[v])
m, n = get_map(neighbors[s, 2], neighbors[s, 1])
neighbors[s, 0] = n + v0
neighbors[s, 2] = m + v0
'''
for each pair of original vertices,
find subvertices whose f#_next pointers point to each other's original vertices,
and link them using column 1 (i.e. set their third_row pointers to each other)
'''
# Mapping from row to original vertex index
v0s = numpy.repeat(numpy.arange(len(edges_per_vertex)), edges_per_vertex)
# Copy column 1 to save target info
target_vert = neighbors[:, 1].copy()
# Preallocate mask arrays
src_mask = numpy.empty(num_duplicates, dtype=bool)
dst_mask = numpy.empty(num_duplicates, dtype=bool)
for v in range(num_v):
s = vstart[v]
e = s + edges_per_vertex[v]
src_mask.fill(False)
src_mask[e:] = target_vert[e:] == v # find rows which reference us
src_vert = v0s[src_mask] # figure out their original vertex numbers
if src_vert.size == 0:
continue
dst_mask.fill(False)
dst_mask[s:e] = target_vert[s:e] > v # mask out any references to verts >= current
dst_vert = target_vert[dst_mask]
ma, mb = get_map(dst_vert, src_vert)
neighbors[dst_mask, 1] = numpy.where(src_mask)[0][mb]
neighbors[src_mask, 1] = numpy.where(dst_mask)[0][ma]
'''
Remove first two duplicates of each vertex (they aren't needed)
'''
nxt, third, prv = neighbors[vstart, :].T
nxt_nxt, nxt_third, _nxt_prv = neighbors[nxt, :].T
# Which vertex to link to
dest_map = numpy.arange(num_duplicates, dtype=int) # default maps to itself
dest_map[vstart] = prv # first maps to previous
dest_map[nxt] = nxt_nxt # second maps to next
# Which backreference to modify
back_map = numpy.full_like(dest_map, 1) # default is 'third'
back_map[vstart] = 0 # if we mapped from a first vertex to its previous, set to 'next'
back_map[nxt] = 2 # if we mapped from a second vertex to its next, set to 'previous'
# Map 'third' to where it should point to
dm_third = dest_map[third]
dm_nxt_third = dest_map[nxt_third]
neighbors[prv, 0] = dm_third # previous's next reference points to third
neighbors[nxt_nxt, 2] = dm_nxt_third # next-next's previous reference points to next-third
neighbors[dm_third, back_map[third]] = prv # third's backreference points to previous
neighbors[dm_nxt_third, back_map[nxt_third]] = nxt_nxt # next-third's backreference points to next-next
# Mark for removal
util.fill(0)
util[vstart] = 1
util[nxt] = 1
neighbors = neighbors[util == 0]
util[util == 0] = numpy.arange(neighbors.shape[0])
neighbors[:] = util[neighbors]
vertices = numpy.repeat(in_vertices, edges_per_vertex - 2, axis=0)
return {'vertices': vertices, 'neighbors': neighbors}
def rotate(poly, theta: float, axis: int):
s, c = sin(theta), cos(theta)
v0 = poly['vertices'][:, axis - 2].copy()
v1 = poly['vertices'][:, axis - 1].copy()
poly['vertices'][:, axis - 2] = c * v0 - s * v1
poly['vertices'][:, axis - 1] = s * v1 + c * v0
def translate(poly, shift):
poly['vertices'] += shift
def scale(poly, scale):
poly['vertices'] *= scale
def shear(poly, shear: float, axb: int, axs: int):
poly['vertices'][:, axb] += poly['vertices'][:, axs]
def affine(poly, mat):
mat4x3 = mat[:, :3]
mat4x1 = mat[:, 3]
vh = mat4x3 @ poly['vertices'].T + mat4x1
poly['vertices'] = vh[:3, :] / vh[3, :]
def init_box(rbounds):
neighbors = [
[1, 4, 3],
[2, 5, 0],
[3, 6, 1],
[0, 7, 2],
[7, 0, 5],
[4, 1, 6],
[5, 2, 7],
[6, 3, 4],
]
vertices = [
[rbounds[0, 0], rbounds[0, 1], rbounds[0, 2]],
[rbounds[1, 0], rbounds[0, 1], rbounds[0, 2]],
[rbounds[1, 0], rbounds[1, 1], rbounds[0, 2]],
[rbounds[0, 0], rbounds[1, 1], rbounds[0, 2]],
[rbounds[0, 0], rbounds[0, 1], rbounds[1, 2]],
[rbounds[1, 0], rbounds[0, 1], rbounds[1, 2]],
[rbounds[1, 0], rbounds[1, 1], rbounds[1, 2]],
[rbounds[0, 0], rbounds[1, 1], rbounds[1, 2]],
]
return {
'neighbors': numpy.array(neighbors, dtype=int),
'vertices': numpy.array(vertices, dtype=float),
}
def box_faces_from_verts(rbounds):
faces = [
((0,0,1), -rbounds[0, 2]),
((0,0,-1), rbounds[1, 2]),
((0,1,0), -rbounds[0, 1]),
((0,-1,0), rbounds[1, 1]),
((1,0,0), -rbounds[0, 0]),
((-1,0,0), rbounds[1, 0]),
]
return [(numpy.array(n), d) for n, d in faces]
def poly_faces_from_verts(vertices, faces):
planes = []
for face in faces:
face_verts = vertices[face]
n = numpy.cross(numpy.diff(face_verts, n=1, axis=0),
numpy.diff(face_verts, n=2, axis=0))
n /= norm(n)
centroid = numpy.sum(face_verts, axis=0) / len(face)
d = -n @ centroid
planes.append(n, d)
return planes
@profile
def find_components(neighbors):
num_vertices = neighbors.shape[0]
current_component = 1
component = numpy.zeros(num_vertices, dtype=int)
for v_start in range(num_vertices):
if component[v_start] != 0:
continue
verts = numpy.array([v_start], dtype=int)
while verts.size > 0:
component[verts] = current_component
next_verts = numpy.unique(neighbors[verts])
verts = next_verts[component[next_verts] == 0]
current_component += 1
return component - 1
@profile
def into_boundary(poly):
neighbors = poly['neighbors']
vertices = poly['vertices']
owner_components = find_components(neighbors)
faces = find_faces(neighbors)
num_components = owner_components.max() + 1
components = [[] for _ in range(num_components)]
for face in faces:
component_ind = owner_components[face[0]]
components[component_ind].append(face)
unique_verts, unique_vertex_map = numpy.unique(vertices, axis=0, return_inverse=True)
umap = numpy.empty(unique_verts.shape[0], dtype=int)
boundary_map = numpy.empty(vertices.shape[0], dtype=int)
boundaries = []
for i, component in enumerate(components):
mask = owner_components == i
umask = unique_vertex_map[mask]
used_uverts = numpy.unique(umask)
umap[used_uverts] = numpy.arange(used_uverts.size) # map to account for deletion of unique verts not used in this component
boundary_map[mask] = umap[umask] # map from non-unique verts in face to unique, in-use verts
boundary = {
'vertices': unique_verts[used_uverts],
'faces': [boundary_map[face] for face in component],
}
boundaries.append(boundary)
return boundaries
def voxelize(poly, ibox, d, poly_order=0):
ibox = numpy.array(ibox, dtype=int)
d = numpy.array(d)
grid_shape = ibox[1] - ibox[0]
num_moments = NUM_MOMENTS(poly_order)
dest_grid = numpy.zeros((*grid_shape, num_moments), dtype=float)
if poly is None or poly['vertices'].shape[0] == 0 or (grid_shape <= 0).any():
return dest_grid
# Stack-based recursive split
stack = [(poly, ibox)]
while stack:
c_poly, c_ibox = stack.pop()
# Base case 1: moments are 0 for this region
if c_poly['vertices'].shape[0] == 0:
continue
box_size = c_ibox[1] - c_ibox[0]
split_axis = box_size.argmax()
max_dist = box_size[split_axis]
# Base case 2: calculate moments for single voxel
if max_dist == 1:
moments = reduce(c_poly, poly_order)
offset = (c_ibox[0] - ibox[0])
dest_grid[offset[0], offset[1], offset[2], :] += moments
continue
# Recursion case: split along longest side
n = numpy.zeros(3)
n[split_axis] = -1
split_ind = c_ibox[0][split_axis] + max_dist // 2
plane = (n, d[split_axis] * split_ind)
children = split(c_poly, plane)
split_plane = c_ibox.copy()
split_plane[:, split_axis] = split_ind
stack.append((children[0], numpy.vstack((c_ibox[0], split_plane[1])) ))
stack.append((children[1], numpy.vstack((split_plane[0], c_ibox[1])) ))
return dest_grid
def get_ibox(poly, d):
min_box = numpy.floor(numpy.min(poly['vertices'], axis=0) / d)
max_box = numpy.ceil(numpy.max(poly['vertices'], axis=0) / d)
return numpy.array((min_box, max_box), dtype=int)
def clamp_ibox(poly, ibox, clampbox, d):
faces = box_faces_from_verts(clampbox)
for face in faces:
poly = clip(poly, plane)
ibox = get_ibox(poly, d)
return poly, ibox

82
shapes.py Normal file
View file

@ -0,0 +1,82 @@
import numpy
from numpy.linalg import norm
def build_tetrahedron(vertices: numpy.ndarray):
poly = {
'vertices': numpy.array(vertices, dtype=float),
'neighbors': numpy.array((
(1, 3, 2),
(2, 3, 0),
(0, 3, 1),
(1, 2, 0)), dtype=int),
}
return poly
def build_box(rbounds):
neighbors = [
[1, 4, 3],
[2, 5, 0],
[3, 6, 1],
[0, 7, 2],
[7, 0, 5],
[4, 1, 6],
[5, 2, 7],
[6, 3, 4],
]
vertices = [
[rbounds[0, 0], rbounds[0, 1], rbounds[0, 2]],
[rbounds[1, 0], rbounds[0, 1], rbounds[0, 2]],
[rbounds[1, 0], rbounds[1, 1], rbounds[0, 2]],
[rbounds[0, 0], rbounds[1, 1], rbounds[0, 2]],
[rbounds[0, 0], rbounds[0, 1], rbounds[1, 2]],
[rbounds[1, 0], rbounds[0, 1], rbounds[1, 2]],
[rbounds[1, 0], rbounds[1, 1], rbounds[1, 2]],
[rbounds[0, 0], rbounds[1, 1], rbounds[1, 2]],
]
return {
'neighbors': numpy.array(neighbors, dtype=int),
'vertices': numpy.array(vertices, dtype=float),
}
def planes_from_box(rbounds):
faces = [
(( 0, 0, 1), -rbounds[0, 2]),
(( 0, 0, -1), rbounds[1, 2]),
(( 0, 1, 0), -rbounds[0, 1]),
(( 0, -1, 0), rbounds[1, 1]),
(( 1, 0, 0), -rbounds[0, 0]),
((-1, 0, 0), rbounds[1, 0]),
]
return [(numpy.array(n), d) for n, d in faces]
def planes_from_tetrahedron(vertices: numpy.ndarray):
verts = numpy.array(vertices, dtype=float)
vset_inds = numpy.array((
[3, 1, 2, 1],
[2, 0, 3, 2],
[1, 3, 0, 3],
[0, 2, 1, 0]))
vertsets = numpy.moveaxis(numpy.dstack(verts[v] for v in vset_inds), 2, 0)
ab = vertsets[:, 0, :] - vertsets[:, 1, :]
cd = vertsets[:, 2, :] - vertsets[:, 3, :]
n = numpy.cross(ab, cd)
n /= norm(n, axis=1)[:, None]
centers = numpy.sum(vertsets[:, :3, :], axis=1) / 3
d = -numpy.sum(n * centers, axis=1)
return [plane for plane in zip(n, d)]
def volume_of_tetrahedron(vertices):
ad, bd, cd = vertices[0:3] - vertices[3]
return -ad @ numpy.cross(bd, cd) / 6

View file

@ -1,6 +1,5 @@
import warnings import warnings
from time import perf_counter from time import perf_counter
import copy
import random import random
import logging import logging
@ -8,14 +7,17 @@ import numpy
from numpy import sin, cos, pi from numpy import sin, cos, pi
from numpy.linalg import norm from numpy.linalg import norm
import pyr3d from . import pyr3d
from .shapes import build_tetrahedron, build_box, planes_from_tetrahedron, volume_of_tetrahedron
from .boundary import build_polyhedron, boundary_from_poly
from .util import check_poly, number_of_moments
from .voxel import voxelize
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
try: try:
profile profile
except: except NameError:
def profile(f): def profile(f):
return f return f
@ -27,10 +29,8 @@ TOL_FAIL = 1e-4
# minimum volume allowed for test polyhedra # minimum volume allowed for test polyhedra
MIN_VOL = 1e-8 MIN_VOL = 1e-8
# for recursive tests, the stack capacity and # maximum recursion depth allowed for recursive tests
# maximum recursion depth allowed MAX_DEPTH = 8
STACK_SIZE = 64
MAX_DEPTH = 6 #10
# order of polynomial integration for all tests # order of polynomial integration for all tests
POLY_ORDER = 0 POLY_ORDER = 0
@ -58,7 +58,7 @@ def check(om, m1, m2):
def thru_cent_3d(poly): def thru_cent_3d(poly):
# make a randomly-oriented plane passing through the centroid # make a randomly-oriented plane passing through the centroid
centroid = get_centroid_3d(poly) centroid = get_centroid_3d(poly)
n = rand_uvec_3d(); n = rand_uvec_3d()
d = -n @ centroid d = -n @ centroid
return n, d return n, d
@ -128,7 +128,7 @@ def rand_tet_3d(minvol: float):
tetvol = 0.0 tetvol = 0.0
while tetvol < minvol: while tetvol < minvol:
verts = [rand_uvec_3d() for _ in range(4)] verts = [rand_uvec_3d() for _ in range(4)]
tetvol = pyr3d.orient(verts) tetvol = volume_of_tetrahedron(verts)
if tetvol < 0.0: if tetvol < 0.0:
verts[2], verts[3] = verts[3], verts[2] verts[2], verts[3] = verts[3], verts[2]
tetvol = -tetvol tetvol = -tetvol
@ -142,14 +142,14 @@ def get_centroid_3d(poly):
def test_split_tet_manual(): def test_split_tet_manual():
tet = pyr3d.init_tet([ tet = build_tetrahedron([
[0,0,0], [0,0,0],
[2,0,0], [2,0,0],
[0,2,0], [0,2,0],
[0,0,2]]) [0,0,2]])
logger.debug(f'Splitting manual tet {tet}') logger.debug(f'Splitting manual tetrahedron {tet}')
logger.debug(f'orient volume {pyr3d.orient(tet["vertices"])}') logger.debug(f'orient volume {volume_of_tetrahedron(tet["vertices"])}')
plane = numpy.array((-1,0,0)), 1 plane = numpy.array((-1,0,0)), 1
p_left, p_right = pyr3d.split(tet, plane) p_left, p_right = pyr3d.split(tet, plane)
@ -157,9 +157,9 @@ def test_split_tet_manual():
logger.debug(f'left {p_left}') logger.debug(f'left {p_left}')
logger.debug(f'right {p_right}') logger.debug(f'right {p_right}')
pyr3d.is_good(tet) check_poly(tet)
pyr3d.is_good(p_left) check_poly(p_left)
pyr3d.is_good(p_right) check_poly(p_right)
om = pyr3d.reduce(tet, 0) om = pyr3d.reduce(tet, 0)
m1 = pyr3d.reduce(p_left, 0) m1 = pyr3d.reduce(p_left, 0)
@ -182,7 +182,7 @@ def test_split_tets_thru_centroid():
# generate a random tet and clip plane # generate a random tet and clip plane
ntets = 1 ntets = 1
opoly = [pyr3d.init_tet(rand_tet_3d(MIN_VOL)) for _ in range(ntets)] opoly = [build_tetrahedron(rand_tet_3d(MIN_VOL)) for _ in range(ntets)]
plane = thru_cent_3d(opoly[ntets//7]) plane = thru_cent_3d(opoly[ntets//7])
# split them all about the same plane # split them all about the same plane
@ -190,9 +190,9 @@ def test_split_tets_thru_centroid():
poly1, poly2 = zip(*poly12) poly1, poly2 = zip(*poly12)
for orig, p1, p2 in zip(opoly, poly1, poly2): for orig, p1, p2 in zip(opoly, poly1, poly2):
pyr3d.is_good(orig) check_poly(orig)
pyr3d.is_good(p1) check_poly(p1)
pyr3d.is_good(p2) check_poly(p2)
# reduce the original and its two parts # reduce the original and its two parts
om = pyr3d.reduce(orig, POLY_ORDER) om = pyr3d.reduce(orig, POLY_ORDER)
@ -205,8 +205,8 @@ def test_split_tets_thru_centroid():
def time_split(): def time_split():
NUM_TRIALS = int(10e3) NUM_TRIALS = int(10e3)
logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.') logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.')
polys = [pyr3d.init_tet(rand_tet_3d(MIN_VOL)) for _ in range(NUM_TRIALS)] polys = [build_tetrahedron(rand_tet_3d(MIN_VOL)) for _ in range(NUM_TRIALS)]
facesets = [pyr3d.tet_faces_from_verts(rand_tet_3d(MIN_VOL)) for _ in range(NUM_TRIALS)] facesets = [planes_from_tetrahedron(rand_tet_3d(MIN_VOL)) for _ in range(NUM_TRIALS)]
t0 = perf_counter() t0 = perf_counter()
for t in range(NUM_TRIALS): for t in range(NUM_TRIALS):
# clip the first tet against the faces of the second # clip the first tet against the faces of the second
@ -237,17 +237,17 @@ def test_tet_tet_timing():
logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.') logger.info(f'Intersecting {NUM_TRIALS} pairs of tetrahedra.')
for t in range(NUM_TRIALS): for t in range(NUM_TRIALS):
# generate the first random tet # generate the first random tet
poly = pyr3d.init_tet(rand_tet_3d(MIN_VOL)) poly = build_tetrahedron(rand_tet_3d(MIN_VOL))
# generate the second random tet # generate the second random tet
faces = pyr3d.tet_faces_from_verts(rand_tet_3d(MIN_VOL)) faces = planes_from_tetrahedron(rand_tet_3d(MIN_VOL))
# clip the first tet against the faces of the second # clip the first tet against the faces of the second
for face in faces: for face in faces:
poly = pyr3d.clip(poly, face) poly = pyr3d.clip(poly, face)
# find the moments (up to quadratic order) of the clipped poly # find the moments (up to quadratic order) of the clipped poly
om = pyr3d.reduce(poly, POLY_ORDER) _om = pyr3d.reduce(poly, POLY_ORDER)
if (t+1) % 1000 == 0: if (t+1) % 1000 == 0:
t_each = (perf_counter() - t0) / (t + 1) t_each = (perf_counter() - t0) / (t + 1)
@ -286,7 +286,7 @@ def test_split_nonconvex():
'neighbors': neighbors, 'neighbors': neighbors,
} }
logger.debug('good:', pyr3d.is_good(opoly)) logger.debug('good: {}'.format(check_poly(opoly)))
# split along the x-axis (two single connected components this direction) # split along the x-axis (two single connected components this direction)
plane = [numpy.array((1, 0, 0)), plane = [numpy.array((1, 0, 0)),
@ -334,12 +334,12 @@ def test_recursive_splitting_nondegenerate():
# recursively splits a polyhedron (starting from a tet) through the centroid, # recursively splits a polyhedron (starting from a tet) through the centroid,
# checking to see that the resulting volumes add up properly. # checking to see that the resulting volumes add up properly.
NUM_TRIALS=10 NUM_TRIALS = 10
logger.info(f'Recursively splitting {NUM_TRIALS} tetrahedra, maximum splits per tet is {MAX_DEPTH}.') logger.info(f'Recursively splitting {NUM_TRIALS} tetrahedra, maximum splits per tet is {MAX_DEPTH}.')
for _ in range(NUM_TRIALS): for _ in range(NUM_TRIALS):
# generate a random tet # generate a random tet
opoly = pyr3d.init_tet(rand_tet_3d(MIN_VOL)) opoly = build_tetrahedron(rand_tet_3d(MIN_VOL))
stack_split(opoly, plane_fun=lambda p: thru_cent_3d(p)) stack_split(opoly, plane_fun=thru_cent_3d)
def test_recursive_splitting_degenerate(): def test_recursive_splitting_degenerate():
@ -347,11 +347,11 @@ def test_recursive_splitting_degenerate():
# that is always degenerate with the tet in some way, # that is always degenerate with the tet in some way,
# checking to see that the resulting volumes add up properly. # checking to see that the resulting volumes add up properly.
NUM_TRIALS=10 NUM_TRIALS = 10
logger.info(f'Recursively splitting {NUM_TRIALS} tetrahedra, maximum splits per tet is {MAX_DEPTH}.') logger.info(f'Recursively splitting {NUM_TRIALS} tetrahedra, maximum splits per tet is {MAX_DEPTH}.')
for _ in range(NUM_TRIALS): for _ in range(NUM_TRIALS):
# generate a random tet # generate a random tet
opoly = pyr3d.init_tet(rand_tet_3d(MIN_VOL)) opoly = build_tetrahedron(rand_tet_3d(MIN_VOL))
stack_split(opoly) stack_split(opoly)
@ -363,18 +363,18 @@ def test_recursive_splitting_degenerate_perturbed():
MIN_PERTURB_ORDER = -17 MIN_PERTURB_ORDER = -17
MAX_PERTURB_ORDER = -1 MAX_PERTURB_ORDER = -1
NUM_TRIALS=10 NUM_TRIALS = 10
logger.info(f'Recursively splitting {NUM_TRIALS} tetrahedra, maximum splits per tet is {MAX_DEPTH}.') logger.info(f'Recursively splitting {NUM_TRIALS} tetrahedra, maximum splits per tet is {MAX_DEPTH}.')
for t in range(NUM_TRIALS): for t in range(NUM_TRIALS):
# generate a random tet # generate a random tet
opoly = pyr3d.init_tet(rand_tet_3d(MIN_VOL)) opoly = build_tetrahedron(rand_tet_3d(MIN_VOL))
# compute the order of magnitude by which to perturb the clip plane, # compute the order of magnitude by which to perturb the clip plane,
# determined by the trial number # determined by the trial number
perturb = pow(10, MIN_PERTURB_ORDER + t%(MAX_PERTURB_ORDER - MIN_PERTURB_ORDER)) perturb = pow(10, MIN_PERTURB_ORDER + t%(MAX_PERTURB_ORDER - MIN_PERTURB_ORDER))
# generate a random tet # generate a random tet
opoly = pyr3d.init_tet(rand_tet_3d(MIN_VOL)) opoly = build_tetrahedron(rand_tet_3d(MIN_VOL))
stack_split(opoly, perturb=perturb) stack_split(opoly, perturb=perturb)
@ -387,18 +387,17 @@ def test_voxelization():
# create a random tet in the unit box # create a random tet in the unit box
verts = (numpy.array(rand_tet_3d(MIN_VOL)) + 1) / 2 verts = (numpy.array(rand_tet_3d(MIN_VOL)) + 1) / 2
poly = pyr3d.init_tet(verts) poly = build_tetrahedron(verts)
# get its original moments for reference # get its original moments for reference
moments = pyr3d.reduce(poly, POLY_ORDER) moments = pyr3d.reduce(poly, POLY_ORDER)
# voxelize it # voxelize it
dx = numpy.ones((3,)) / NGRID dx = numpy.ones((3,)) / NGRID
ibox = pyr3d.get_ibox(poly, dx)
logger.info(f'Voxelizing a tetrahedron to a grid with dx = {dx} and moments of order {POLY_ORDER}') logger.info(f'Voxelizing a tetrahedron to a grid with dx = {dx} and moments of order {POLY_ORDER}')
logger.info(f'Minimum index box = {ibox}') # logger.info(f'Minimum index box = {ibox}')
grid = pyr3d.voxelize(poly, ibox, dx, POLY_ORDER) grid = voxelize(poly, dx, poly_order=POLY_ORDER)
# visualize_voxels(grid) # visualize_voxels(grid)
@ -412,7 +411,7 @@ def test_voxelization():
def visualize_voxels(grid): def visualize_voxels(grid):
import gridlock import gridlock
g = gridlock.Grid([numpy.arange(n+1) for n in grid.shape], shifts=[[0,0,0]]) g = gridlock.Grid([numpy.arange(n+1) for n in grid.shape], shifts=[[0, 0, 0]])
g.grids[0][:] = grid[:, :, :, 0] g.grids[0][:] = grid[:, :, :, 0]
g.visualize_isosurface() g.visualize_isosurface()
@ -421,10 +420,10 @@ def visualize_voxels(grid):
def stack_split(opoly, plane_fun=None, perturb=0): def stack_split(opoly, plane_fun=None, perturb=0):
stack = [(opoly, 0)] stack = [(opoly, 0)]
i=0 i = 0
# recursively split the poly # recursively split the poly
while stack: while stack:
i+=1 i += 1
opoly, depth = stack.pop() opoly, depth = stack.pop()
# generate a random plane from one of a few # generate a random plane from one of a few
@ -471,7 +470,7 @@ def stack_split(opoly, plane_fun=None, perturb=0):
stack.append((poly1, depth + 1)) stack.append((poly1, depth + 1))
if m2[0] > MIN_VOL: if m2[0] > MIN_VOL:
stack.append((poly2, depth + 1)) stack.append((poly2, depth + 1))
if i % 100 == 0: if i % 300 == 0:
logger.info(f'Stack split iter {i} length {len(stack)} depth {depth}') logger.info(f'Stack split iter {i} length {len(stack)} depth {depth}')
@ -493,12 +492,11 @@ def test_poly_pyramid():
] ]
# initialize a general polyhedron # initialize a general polyhedron
opoly = pyr3d.init_poly(vertices, faces) opoly = build_polyhedron(vertices, faces)
print(opoly) check_poly(opoly)
pyr3d.is_good(opoly)
stack_split(opoly) stack_split(opoly)
brep = pyr3d.into_boundary(opoly) brep = boundary_from_poly(opoly)
logger.debug(f'Round-trip converted pyramid: {brep}') logger.debug(f'Round-trip converted pyramid: {brep}')
#plot_brep(brep) #plot_brep(brep)
@ -543,7 +541,7 @@ def test_torus_load_and_chop():
# Recursively splits a polyhedron (starting from a torus) with a cut plane # Recursively splits a polyhedron (starting from a torus) with a cut plane
# that is always degenerate with the poly in some way, # that is always degenerate with the poly in some way,
# checking to see that the resulting volumes add up properly. # checking to see that the resulting volumes add up properly.
# This checks non-convex geometry, and also r3d_init_poly() when more than # This checks non-convex geometry, and also build_polyhedron() when more than
# three edges per vertex are needed. # three edges per vertex are needed.
n_th = 20 n_th = 20
@ -582,11 +580,11 @@ def test_torus_load_and_chop():
# initialize a general polyhedron # initialize a general polyhedron
opoly = pyr3d.init_poly(vertices, faces) opoly = build_polyhedron(vertices, faces)
# pyr3d.is_good(opoly) # check_poly(opoly)
stack_split(opoly) stack_split(opoly)
brep = pyr3d.into_boundary(opoly) brep = boundary_from_poly(opoly)
logger.debug(f'Round-trip converted torus: {brep}') logger.debug(f'Round-trip converted torus: {brep}')
#plot_brep(brep) #plot_brep(brep)

31
transform.py Normal file
View file

@ -0,0 +1,31 @@
import numpy
from numpy import sin, cos
def rotate(poly, theta: float, axis: int):
s, c = sin(theta), cos(theta)
v0 = poly['vertices'][:, axis - 2].copy()
v1 = poly['vertices'][:, axis - 1].copy()
poly['vertices'][:, axis - 2] = c * v0 - s * v1
poly['vertices'][:, axis - 1] = s * v1 + c * v0
def translate(poly, shift):
poly['vertices'] += shift
def scale(poly, factor):
poly['vertices'] *= factor
def shear(poly, factor: float, axb: int, axs: int):
poly['vertices'][:, axb] += factor * poly['vertices'][:, axs]
def affine(poly, mat):
mat4x3 = mat[:, :3]
mat4x1 = mat[:, 3]
vh = mat4x3 @ poly['vertices'].T + mat4x1
poly['vertices'] = vh[:3, :] / vh[3, :]

151
util.py Normal file
View file

@ -0,0 +1,151 @@
import numpy
try:
profile
except NameError:
def profile(f):
return f
def number_of_moments(order):
return ((order + 1) * (order + 2) * (order + 3)) // 6
@profile
def find_components(neighbors):
num_vertices = neighbors.shape[0]
current_component = 1
component = numpy.zeros(num_vertices, dtype=int)
for v_start in range(num_vertices):
if component[v_start] != 0:
continue
verts = numpy.array([v_start], dtype=int)
while verts.size > 0:
component[verts] = current_component
next_verts = numpy.unique(neighbors[verts])
verts = next_verts[component[next_verts] == 0]
current_component += 1
return component - 1
@profile
def find_faces(neighbors):
num_verts = neighbors.shape[0]
edge_id = numpy.arange(3 * num_verts)
nxt_edge = numpy.tile(numpy.arange(3), num_verts)
vstart = edge_id // 3
vcur = vstart.copy()
vnext = neighbors[vcur, nxt_edge]
faces = [[v] for v in vcur]
mask = vstart # dummy for loop init, could use numpy.array([True]) instead
remove = numpy.zeros_like(edge_id, dtype=bool)
while mask.any():
for i, vn in zip(edge_id, vnext):
faces[i].append(vn)
prv_edge = (neighbors[vnext, :] == vcur[:, None]).argmax(axis=1)
nxt_edge = (prv_edge + 1) % 3
vcur, vnext = vnext, neighbors[vnext, nxt_edge]
remove_mask = vcur < vstart
remove[edge_id[remove_mask]] = True
mask = numpy.logical_and(vnext != vstart, ~remove_mask)
edge_id = edge_id[mask]
vcur = vcur[mask]
vnext = vnext[mask]
vstart = vstart[mask]
faces_set = []
for i, do_remove in enumerate(remove):
if not do_remove:
faces_set.append(faces[i])
return faces_set
def _get_map(a, b):
# Assume all elements appear exactly once in each array
# Returns m, n such that a[m] == b, b[n] == a
assert(a.size == b.size)
if a.size == 0:
return numpy.array(()), numpy.array(())
sa = a.argsort()
sb = b.argsort()
ra = numpy.empty_like(sa)
rb = numpy.empty_like(sa)
ra[sa] = numpy.arange(sa.size)
rb[sb] = numpy.arange(sa.size)
return sa[rb], sb[ra]
def _argsort_rows(a):
dims = a.max(0) + 1
a1d = numpy.ravel_multi_index(a.T, dims)
return numpy.argsort(a1d)
def _searchsorted_rows(a, b):
dims = numpy.maximum(a.max(0), b.max(0)) + 1
a1d = numpy.ravel_multi_index(a.T, dims)
b1d = numpy.ravel_multi_index(b.T, dims)
return numpy.searchsorted(a1d, b1d)
def check_poly(poly, check_connectivity=True) -> bool:
neighbors = poly['neighbors']
vertices = poly['vertices']
num_vertices = vertices.shape[0]
out_of_bounds = numpy.logical_or(neighbors >= vertices.shape[0], neighbors < 0)
if numpy.any(out_of_bounds):
which_vertices = numpy.where(out_of_bounds)[0]
raise Exception(f'Vertices {which_vertices} have out-of-bounds neighbors')
repeated_neighbors = neighbors == numpy.roll(neighbors, 1, axis=1)
if numpy.any(repeated_neighbors):
which_vertices = numpy.where(repeated_neighbors)[0]
raise Exception(f'Vertices {which_vertices} have duplicate neighbors')
vertex_uses = numpy.bincount(neighbors.ravel())
if numpy.any(vertex_uses != 3):
which_vertices = numpy.where(vertex_uses != 3)[0]
raise Exception(f'Vertices {which_vertices} are referenced {vertex_uses[which_vertices]} times,'
' should be exactly 3')
# check for 3-vertex-connectedness (~n^3 because need bfs for each removed vertex pair)
if check_connectivity:
components = find_components(neighbors)
vert_ids = numpy.arange(num_vertices, dtype=int)
visited = numpy.empty(num_vertices, dtype=bool)
for part_id in numpy.unique(components):
part_mask = components == part_id
part_verts = vert_ids[part_mask]
vcs = set(part_verts[:3])
for ia in range(part_verts.size):
va = part_verts[ia]
for vb in part_verts[ia + 1:]:
# pick vc != {va, vb}
vc = (vcs - set((va, vb))).pop()
# flood-fill from vc without passing through va, vb
visited.fill(False)
visited[[va, vb]] = True
nums = numpy.array([vc], dtype=int)
while nums.size > 0:
visited[nums] = True
new_nums = numpy.unique(neighbors[nums])
nums = new_nums[~visited[new_nums]]
# Make sure we touched all vertices in the component
if not visited[components == part_id].all():
raise Exception('Vertex graph is not 3-vertex-connected')
return True

73
voxel.py Normal file
View file

@ -0,0 +1,73 @@
import numpy
from .pyr3d import split, reduce
from .util import number_of_moments
try:
profile
except NameError:
def profile(f):
return f
@profile
def voxelize(poly, d, ibox=None, poly_order=0):
ibox = get_ibox(poly, d) if ibox is None else numpy.array(ibox, dtype=int)
d = numpy.array(d)
grid_shape = ibox[1] - ibox[0]
dest_grid = numpy.zeros((*grid_shape, number_of_moments(poly_order)), dtype=float)
if poly is None or poly['vertices'].shape[0] == 0 or (grid_shape <= 0).any():
return dest_grid
# Stack-based recursive split
stack = [(poly, ibox)]
while stack:
c_poly, c_ibox = stack.pop()
# Base case 1: moments are 0 for this region
if c_poly['vertices'].shape[0] == 0:
continue
box_size = c_ibox[1] - c_ibox[0]
split_axis = box_size.argmax()
max_dist = box_size[split_axis]
# Base case 2: calculate moments for single voxel
if max_dist == 1:
moments = reduce(c_poly, poly_order)
offset = (c_ibox[0] - ibox[0])
dest_grid[offset[0], offset[1], offset[2], :] += moments
continue
# Recursion case: split along longest side
n = numpy.zeros(3)
n[split_axis] = -1
split_ind = c_ibox[0][split_axis] + max_dist // 2
plane = (n, d[split_axis] * split_ind)
children = split(c_poly, plane)
split_plane = c_ibox.copy()
split_plane[:, split_axis] = split_ind
stack.append((children[0], numpy.vstack((c_ibox[0], split_plane[1])) ))
stack.append((children[1], numpy.vstack((split_plane[0], c_ibox[1])) ))
return dest_grid
def get_ibox(poly, d):
min_box = numpy.floor(numpy.min(poly['vertices'], axis=0) / d)
max_box = numpy.ceil(numpy.max(poly['vertices'], axis=0) / d)
return numpy.array((min_box, max_box), dtype=int)
def clamp_ibox(poly, ibox, clampbox, d):
faces = box_faces_from_verts(clampbox)
for face in faces:
poly = clip(poly, face)
ibox = get_ibox(poly, d)
return poly, ibox