from typing import List, Dict, Tuple import numpy from numpy import pi, cos, sin, sqrt from numpy.linalg import norm try: profile except: def profile(f): return f def init_tet(verts: numpy.ndarray): 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 { 'vertices': numpy.empty((0, 3), dtype=float), 'neighbors': numpy.empty((0, 3), dtype=int), } empty_partial_result = ( numpy.empty((0, 3), dtype=int), numpy.empty((0, 1), dtype=int), numpy.empty((0, 3), dtype=float), numpy.empty((0, 1), dtype=int), ) @profile def simple_clip(poly: Dict, plane: Tuple) -> Dict: vertices = poly['vertices'] neighbors = poly['neighbors'] num_vertices = vertices.shape[0] dists = plane[1] + (vertices @ plane[0]) left = dists > 0 right = numpy.logical_not(left) # if the poly lies entirely on one side of the plane, just return the right/left masks if not numpy.any(left): # if all on right or touching plane return (left,) + empty_partial_result if numpy.min(dists) >= 0: # if all on left or touching plane # Can't reuse 'left' because <= vs < return (numpy.ones_like(left),) + empty_partial_result num_left_vertices = numpy.count_nonzero(left) num_right_vertices = num_vertices - num_left_vertices right_inds = numpy.where(right)[0] right_inds3 = numpy.repeat(right_inds, 3) pnbr_inds = numpy.tile(numpy.arange(3), right_inds.size) # array of [[clipped vertex (cv0), connected vertex pv00], [cv0, pv01], [cv0, pv02], [cv1, pv10], ...] # which is effectively a list of all edges which touch the right half-plane right_edges = numpy.column_stack((right_inds3, neighbors[right_inds, :].ravel(), pnbr_inds)) # remove edges which connect two same-side vertices far_vertex_left = left[right_edges[:, 1]] r2l_edges = right_edges[far_vertex_left, :] if r2l_edges.size == 0: # No edges cross, but components on either side return (left,) + empty_partial_result # sort now so we can use searchsorted later r2l_edge_order = _argsort_rows(r2l_edges[:, :2]) r2l_edges = r2l_edges[r2l_edge_order] num_new_vertices = r2l_edges.shape[0] # walk counter-clockwise to next crossing edge edge_walk = r2l_edges[:, :2].copy() edge_walk_inds = numpy.arange(num_new_vertices) edge_walk_inds2 = numpy.arange(num_new_vertices) edge_walk_results = numpy.empty_like(edge_walk) src_pns = None while edge_walk.size > 0: prev_verts = edge_walk[:, 0] cur_verts = edge_walk[:, 1].copy() # Get the list of our current neighbors, find which one points to the # vertex we came from, and choose the next (ccw) one cur_links = neighbors[cur_verts] row, src_pn = numpy.where(cur_links == prev_verts[:, None]) new_pn = (src_pn + 1) % 3 if src_pns is None: src_pns = src_pn next_verts = cur_links[(row, new_pn)] # Save the current vertices as previous, and our chosen neighbors as current # Save edges that cross back to right, and remove them from edge_walk done = right[next_verts] not_done = numpy.logical_not(done) edge_walk_results[edge_walk_inds2[done], 0] = cur_verts[done] edge_walk_results[edge_walk_inds2[done], 1] = next_verts[done] edge_walk = numpy.column_stack((cur_verts[not_done], next_verts[not_done])) edge_walk_inds2 = edge_walk_inds2[not_done] # now edge_walk is list of [[target connected vertex, target clipped adjacent vertex], ...] # figure out the index of each target edge... target_edge_inds = _searchsorted_rows(r2l_edges[:,:2], edge_walk_results[:, ::-1]) v_right = r2l_edges[:, 0] v_left = r2l_edges[:, 1] d_right = dists[v_right][:, None] d_left = dists[v_left][:, None] 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 num_start = poly['vertices'].shape[0] num_left = numpy.count_nonzero(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 ''' ind_map_left = numpy.zeros(num_start, dtype=int) # current side vertices get new (equal or lower) indices from delete operation, remain in same order ind_map_left[left] = numpy.arange(num_left) # Hops across the boundary depend on (origin, destination) pair since that determines final vertex re, le = r2l_edges[:, 0], r2l_edges[:, 1] # use argsort to generate link from target edge to current edge target_order = numpy.argsort(target_edge_inds) new_neighbors_left = numpy.column_stack(( ind_map_left[le], # update left vertices based on new indexing target_order + num_left, # new vertex indices are same as edge indices + offset target_edge_inds + num_left)) old_vertices_left = poly['vertices'][left] 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[(le, src_pn)] = num_left + numpy.arange(num_new) old_neighbors_left = old_neighbors_left[left] left_poly = { 'vertices': numpy.vstack((old_vertices_left, new_vertices)), 'neighbors': numpy.vstack((old_neighbors_left, new_neighbors_left)), } if left_only: return left_poly ind_map_right = numpy.zeros(num_start, dtype=int) ind_map_right[right] = numpy.arange(num_right) new_neighbors_right = numpy.column_stack(( ind_map_right[re], # update right vertices based on new indexing target_edge_inds + num_right, # new vertex indices are same as edge indices + offset target_order + num_right)) old_vertices_right = poly['vertices'][right] old_neighbors_right = poly['neighbors'].copy() 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 = old_neighbors_right[right] right_poly = { 'vertices': numpy.vstack((old_vertices_right, new_vertices)), 'neighbors': numpy.vstack((old_neighbors_right, new_neighbors_right)), } return left_poly, right_poly @profile def reduce(poly, poly_order): vertices = poly['vertices'] neighbors = poly['neighbors'] num_verts = vertices.shape[0] moments = numpy.zeros(NUM_MOMENTS(poly_order), dtype=float) if num_verts == 0: return moments edge_visited= numpy.zeros((num_verts, 3), dtype=bool) #// 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 S = numpy.zeros((3, poly_order + 1, poly_order + 1, 2) , dtype=float) inds = numpy.arange(poly_order + 1) mx, my = numpy.meshgrid(inds, inds, indexing='ij') valid = numpy.zeros((2, poly_order + 1, poly_order + 1), dtype=bool) cropped = numpy.zeros((poly_order + 1, poly_order + 1), dtype=bool) # faces = [] # for vstart in range(num_verts): # for pstart in range(3): # if edge_visited[vstart, pstart]: # continue # # vcur = neighbors[vstart, pstart] # edge_visited[vstart, pstart] = 1 # # prv_edge = numpy.where(neighbors[vcur] == vstart)[0][0] # nxt_edge = (prv_edge + 1) % 3 # edge_visited[vcur, nxt_edge] = 1 # vnext = neighbors[vcur, nxt_edge] # # face = [vstart, vcur] # #// make a triangle fan using edges and first vertex # vecs = numpy.vstack(vertices[[vstart, vcur, vnext]]) # while vnext != vstart: # prv_edge =(neighbors[vnext] == vcur).argmax() # nxt_edge = (prv_edge + 1) % 3 # # vcur = vnext # edge_visited[vcur, nxt_edge] = 1 # vnext = neighbors[vcur, nxt_edge] # # face.append(vcur) # faces.append(face) # # faces_set = faces # 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 = 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 = numpy.logical_and(vcur < vstart, vcur < vnext) 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]) # faces_set = set() # for face in faces: # face = numpy.array(face, dtype=int) # start = face.argmin() # faces_set.add(tuple(numpy.roll(face, -start))) triangle_fans = [] for face in faces_set: triangle_inds = numpy.empty((len(face) - 2, 3), dtype=int) triangle_inds[:, 0] = face[0] triangle_inds[:, 1] = face[1:-1] triangle_inds[:, 2] = face[2:] triverts = vertices[triangle_inds] triangle_fans.append(triverts) triangles = numpy.vstack(triangle_fans) volumes = -numpy.linalg.det(triangles) moments[0] = volumes.sum() / 6 for i, vecs in enumerate(triangles): S[:, 0, 0, prevlayer] = 1 valid[prevlayer, :, :] = False valid[prevlayer, 0, 0] = True m = 1 for c in range(1, poly_order+1): valid[curlayer] = c >= mx + my num_valid = (c + 1) * (c + 2) // 2 # always an int, see NUM_MOMENTS() S[:, 0, :, curlayer] = 0 cropped.fill(0) cropped[1:, :] = valid[curlayer, 1:, :] S[:, cropped, curlayer] = vecs[:, 0][:, None] * S[:, valid[prevlayer], prevlayer] cropped = numpy.moveaxis(cropped, 0, 1) S[:, cropped, curlayer] += vecs[:, 1][:, None] * S[:, valid[prevlayer], prevlayer] S[:, valid[prevlayer], curlayer] += vecs[:, 2][:, None] * S[:, valid[prevlayer], prevlayer] S[1, valid[curlayer], curlayer] += S[0, valid[curlayer], curlayer] S[2, valid[curlayer], curlayer] += S[1, valid[curlayer], curlayer] moments[m:m + num_valid] += volumes[i] * S[2, valid[curlayer], curlayer].ravel() m += num_valid prevlayer, curlayer = curlayer, prevlayer #// reuse S to recursively compute the leading multinomial coefficients S[0, 0, 0, prevlayer] = 1 m = 1 valid[prevlayer, :, :] = False valid[prevlayer, 0, 0] = True for c in range(1, poly_order+1): valid[curlayer] = c >= mx + my num_valid = (c + 1) * (c + 2) // 2 # always an int, see NUM_MOMENTS() S[0, 0, :, curlayer] = 0 cropped.fill(0) cropped[1:, :] = valid[curlayer, 1:, :] S[0, cropped, curlayer] = S[0, valid[prevlayer], prevlayer] cropped = numpy.moveaxis(cropped, 0, 1) S[0, cropped, curlayer] += S[0, valid[prevlayer], prevlayer] S[0, valid[prevlayer], curlayer] += S[0, valid[prevlayer], prevlayer] moments[m:m + num_valid] /= S[0, valid[curlayer], curlayer].ravel() * (c + 1) * (c + 2) * (c + 3) m += num_valid prevlayer, curlayer = curlayer, prevlayer 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. rcur = 1 regions = numpy.zeros(num_vertices, dtype=int) stack = [] for v in range(num_vertices): if regions[v]: continue nums = numpy.array([v], dtype=int) while nums.size > 0: regions[nums] = rcur new_nums = numpy.unique(neighbors[nums]) nums = new_nums[regions[new_nums] == 0] rcur += 1 # 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 init_brep(poly): neighbors = poly['neighbors'] vertices = poly['vertices'] unique_verts, unique_vertex_map = numpy.unique(vertices, axis=0, return_inverse=True) verts_in_component = numpy.empty(unique_verts.shape[0], dtype=bool) component_map = numpy.empty_like(verts_in_component, dtype=int) vert_visited = numpy.zeros(vertices.shape[0], dtype=numpy.int8) edge_visited = numpy.zeros_like(vertices, dtype=bool) vstart = 0 components = [] while True: verts_in_component.fill(0) pedge = 0 faces = [] while True: vcur = vstart uvcur = unique_vertex_map[vcur] face = [] while True: vert_visited[vcur] += 1 edge_visited[vcur, pedge] = True verts_in_component[uvcur] = True vnext = neighbors[vcur, pedge] uvnext = unique_vertex_map[vnext] # don't append duplicates if uvcur != uvnext: face.append(uvcur) if vnext == vstart: break # Figure out index of back-reference # and go ccw to next edge (clockwise face traversal) np = (neighbors[vnext] == vcur).argmax() pedge = (np + 1) % 3 vcur = vnext uvcur = uvnext faces.append(face) # Continue using a vertex touching a connected, unvisited face # Any vertex visited only 1 or 2 times must be touching such a face nv = numpy.where(numpy.logical_and(0 < vert_visited, vert_visited < 3))[0] if len(nv) == 0: # No more connected, unvisited faces! break vstart = nv[0] # Pick an unvisited edge; argmin is equivalent to looking for the first 0 pedge = edge_visited[vstart].argmin() component_map[verts_in_component] = numpy.arange(numpy.count_nonzero(verts_in_component)) component = { 'vertices': unique_verts[verts_in_component], 'faces': [component_map[face] for face in faces], } components.append(component) # Continue from an unvisited vertex np = numpy.where(vert_visited == 0)[0] if len(np) == 0: # Visited all vertices! break vstart = np[0] return components 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