import numpy from .split import split from .moments import get_moments, number_of_moments try: profile except NameError: def profile(f): return f @profile def voxelize(poly, d, box=None, poly_order=0): box = get_box(poly, d) if box is None else numpy.array(box, dtype=int) d = numpy.array(d) grid_shape = box[1] - box[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, box)] while stack: c_poly, c_box = stack.pop() # Base case 1: moments are 0 for this region if c_poly['vertices'].shape[0] == 0: continue box_size = c_box[1] - c_box[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 = get_moments(c_poly, poly_order) offset = (c_box[0] - box[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_box[0][split_axis] + max_dist // 2 plane = (n, d[split_axis] * split_ind) children = split(c_poly, plane) split_plane = c_box.copy() split_plane[:, split_axis] = split_ind stack.append((children[0], numpy.vstack((c_box[0], split_plane[1])) )) stack.append((children[1], numpy.vstack((split_plane[0], c_box[1])) )) return dest_grid def get_box(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_box(poly, box, clampbox, d): faces = box_faces_from_verts(clampbox) for face in faces: poly = clip(poly, face) box = get_box(poly, d) return poly, box