adze/chop/voxel.py

74 lines
2.1 KiB
Python
Raw Normal View History

2018-03-20 15:10:45 -07:00
import numpy
2018-03-21 14:54:32 -07:00
from .split import split
from .moments import get_moments, number_of_moments
2018-03-20 15:10:45 -07:00
try:
2018-03-28 10:54:15 -07:00
# Check if running with line_profiler
2018-03-20 15:10:45 -07:00
profile
except NameError:
def profile(f):
return f
@profile
2018-03-21 14:54:32 -07:00
def voxelize(poly, d, box=None, poly_order=0):
box = get_box(poly, d) if box is None else numpy.array(box, dtype=int)
2018-03-20 15:10:45 -07:00
d = numpy.array(d)
2018-03-21 14:54:32 -07:00
grid_shape = box[1] - box[0]
2018-03-20 15:10:45 -07:00
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
2018-03-21 14:54:32 -07:00
stack = [(poly, box)]
2018-03-20 15:10:45 -07:00
while stack:
2018-03-21 14:54:32 -07:00
c_poly, c_box = stack.pop()
2018-03-20 15:10:45 -07:00
# Base case 1: moments are 0 for this region
if c_poly['vertices'].shape[0] == 0:
continue
2018-03-21 14:54:32 -07:00
box_size = c_box[1] - c_box[0]
2018-03-20 15:10:45 -07:00
split_axis = box_size.argmax()
max_dist = box_size[split_axis]
# Base case 2: calculate moments for single voxel
if max_dist == 1:
2018-03-21 14:54:32 -07:00
moments = get_moments(c_poly, poly_order)
offset = (c_box[0] - box[0])
2018-03-20 15:10:45 -07:00
dest_grid[offset[0], offset[1], offset[2], :] += moments
continue
# Recursion case: split along longest side
n = numpy.zeros(3)
n[split_axis] = -1
2018-03-21 14:54:32 -07:00
split_ind = c_box[0][split_axis] + max_dist // 2
2018-03-20 15:10:45 -07:00
plane = (n, d[split_axis] * split_ind)
children = split(c_poly, plane)
2018-03-21 14:54:32 -07:00
split_plane = c_box.copy()
2018-03-20 15:10:45 -07:00
split_plane[:, split_axis] = split_ind
2018-03-21 14:54:32 -07:00
stack.append((children[0], numpy.vstack((c_box[0], split_plane[1])) ))
stack.append((children[1], numpy.vstack((split_plane[0], c_box[1])) ))
2018-03-20 15:10:45 -07:00
return dest_grid
2018-03-21 14:54:32 -07:00
def get_box(poly, d):
2018-03-20 15:10:45 -07:00
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)
2018-03-21 14:54:32 -07:00
def clamp_box(poly, box, clampbox, d):
2018-03-20 15:10:45 -07:00
faces = box_faces_from_verts(clampbox)
for face in faces:
poly = clip(poly, face)
2018-03-21 14:54:32 -07:00
box = get_box(poly, d)
return poly, box
2018-03-20 15:10:45 -07:00