diff --git a/adze/boundary.py b/adze/boundary.py index 150030b..e7fbe81 100644 --- a/adze/boundary.py +++ b/adze/boundary.py @@ -24,16 +24,35 @@ def planes_from_boundary( Returns: List of planes, represented by (normal vector, signed distance to origin) tuples. """ - vertices = numpy.asarray(vertices) + vertices = numpy.asarray(vertices, dtype=float) afaces = [numpy.asarray(ff) for ff in faces] planes = [] for face in afaces: 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) + # Newell's method for robust normal calculation + # n_x = sum (y_i - y_{i+1}) * (z_i + z_{i+1}) + # n_y = sum (z_i - z_{i+1}) * (x_i + x_{i+1}) + # n_z = sum (x_i - x_{i+1}) * (y_i + y_{i+1}) + + # Shift vertices to wrap around + v_curr = face_verts + v_next = numpy.roll(face_verts, -1, axis=0) + + # Ensure n is float64 to avoid casting issues with integer inputs + n = numpy.array([ + numpy.sum((v_curr[:, 1] - v_next[:, 1]) * (v_curr[:, 2] + v_next[:, 2])), + numpy.sum((v_curr[:, 2] - v_next[:, 2]) * (v_curr[:, 0] + v_next[:, 0])), + numpy.sum((v_curr[:, 0] - v_next[:, 0]) * (v_curr[:, 1] + v_next[:, 1])) + ], dtype=float) + + n_norm = norm(n) + if n_norm < 1e-15: + # Face is degenerate (zero area) + continue + + n /= n_norm + centroid = numpy.mean(face_verts, axis=0) d = -n @ centroid planes.append((n, d)) return planes @@ -305,4 +324,3 @@ def boundary_from_poly(poly: poly_t) -> list[dict[str, Any]]: boundaries.append(boundary) return boundaries -