[offset] add offset_anisotropic

This commit is contained in:
jan 2026-03-07 23:53:59 -08:00
commit f0e30f1f6c
3 changed files with 74 additions and 10 deletions

View file

@ -99,6 +99,7 @@ from .boolean import (
) )
from .offset import ( from .offset import (
offset as offset, offset as offset,
offset_anisotropic as offset_anisotropic,
smooth as smooth, smooth as smooth,
opening as opening, opening as opening,
closing as closing, closing as closing,

View file

@ -1,8 +1,12 @@
import numpy import numpy
from numpy.typing import NDArray
from collections.abc import Callable
from . import poly_t from . import poly_t
from .util import find_faces from .util import find_faces
from .boundary import planes_from_boundary from .boundary import planes_from_boundary
RateFunction = Callable[[NDArray[numpy.floating]], float]
def offset(poly: poly_t, delta: float, miter_limit: float = 10.0) -> poly_t: def offset(poly: poly_t, delta: float, miter_limit: float = 10.0) -> poly_t:
""" """
Offset a polyhedron by a distance delta. Offset a polyhedron by a distance delta.
@ -40,7 +44,21 @@ def offset(poly: poly_t, delta: float, miter_limit: float = 10.0) -> poly_t:
"Closing" operation: an expansion followed by a shrinking of the same "Closing" operation: an expansion followed by a shrinking of the same
magnitude (or vice versa for small protrusions). magnitude (or vice versa for small protrusions).
""" """
def constant_rate(_n: NDArray) -> float:
return delta
return offset_anisotropic(poly, constant_rate, miter_limit)
def offset_anisotropic(poly: poly_t, rate_func: RateFunction, miter_limit: float = 10.0) -> poly_t:
"""
Offset a polyhedron with a direction-dependent rate.
Args:
poly: Input polyhedron.
rate_func: Function taking a unit normal (inward facing) and returning
the scalar offset for that face. Positive values expand against the normal.
miter_limit: Maximum allowed multiplier for displacement.
"""
if poly['vertices'].shape[0] == 0: if poly['vertices'].shape[0] == 0:
return poly return poly
@ -54,13 +72,17 @@ def offset(poly: poly_t, delta: float, miter_limit: float = 10.0) -> poly_t:
# Map vertex to which faces it belongs to # Map vertex to which faces it belongs to
vertex_to_faces: list[list[int]] = [[] for _ in range(num_verts)] vertex_to_faces: list[list[int]] = [[] for _ in range(num_verts)]
face_normals = [] face_normals = []
face_deltas = []
for face_idx, face in enumerate(faces): for face_idx, face in enumerate(faces):
# planes_from_boundary handles robust normal calculation via Newell's method. # planes_from_boundary handles robust normal calculation via Newell's method.
# Note: adze convention for boundary representation usually has # Note: adze convention for boundary representation usually has
# INWARD facing normals for clipping. # INWARD facing normals for clipping.
plane = planes_from_boundary(vertices, [face])[0] plane = planes_from_boundary(vertices, [face])[0]
face_normals.append(plane[0]) # plane[0] is unit normal normal = plane[0]
face_normals.append(normal)
face_deltas.append(rate_func(normal))
for v_idx in face: for v_idx in face:
vertex_to_faces[v_idx].append(face_idx) vertex_to_faces[v_idx].append(face_idx)
@ -77,36 +99,46 @@ def offset(poly: poly_t, delta: float, miter_limit: float = 10.0) -> poly_t:
# Normal matrix A # Normal matrix A
A = numpy.array([face_normals[fi] for fi in f_indices]) A = numpy.array([face_normals[fi] for fi in f_indices])
# Target deltas for the 3 faces
deltas = numpy.array([face_deltas[fi] for fi in f_indices])
# If n is INWARD normal, then to EXPAND (positive delta) we want to move # If n is INWARD normal, then to EXPAND (positive delta) we want to move
# AGAINST the normal. # AGAINST the normal.
# n . (V' - V) = -delta # n . (V' - V) = -delta
# Let d = V' - V # A d = -deltas
# A d = -delta * [1, 1, 1]^T
# Max delta magnitude for miter limit check
max_delta = numpy.max(numpy.abs(deltas))
try: try:
# solve A d = -delta # solve A d = -deltas
rhs = numpy.full(3, -delta) rhs = -deltas
d = numpy.linalg.solve(A, rhs) d = numpy.linalg.solve(A, rhs)
# Check miter limit # Check miter limit
d_norm = numpy.linalg.norm(d) d_norm = numpy.linalg.norm(d)
if abs(delta) > 1e-15 and d_norm > miter_limit * abs(delta): if max_delta > 1e-15 and d_norm > miter_limit * max_delta:
# Clamp displacement # Clamp displacement
avg_n = numpy.mean(A, axis=0) avg_n = numpy.mean(A, axis=0)
avg_n_norm = numpy.linalg.norm(avg_n) avg_n_norm = numpy.linalg.norm(avg_n)
# Fallback direction is average normal
# Fallback magnitude is limited
if avg_n_norm > 1e-12: if avg_n_norm > 1e-12:
# Move along average inward normal (negative for expansion) # Move along average inward normal (negative for expansion)
new_vertices[i] = vertices[i] - (avg_n / avg_n_norm) * delta # Use the average requested delta
avg_delta = numpy.mean(deltas)
new_vertices[i] = vertices[i] - (avg_n / avg_n_norm) * avg_delta
else: else:
new_vertices[i] = vertices[i] + d * (miter_limit * abs(delta) / d_norm) new_vertices[i] = vertices[i] + d * (miter_limit * max_delta / d_norm)
else: else:
new_vertices[i] = vertices[i] + d new_vertices[i] = vertices[i] + d
except numpy.linalg.LinAlgError: except numpy.linalg.LinAlgError:
# Singular matrix # Singular matrix
avg_n = numpy.mean(A, axis=0) avg_n = numpy.mean(A, axis=0)
avg_n_norm = numpy.linalg.norm(avg_n) avg_n_norm = numpy.linalg.norm(avg_n)
avg_delta = numpy.mean(deltas)
if avg_n_norm > 1e-12: if avg_n_norm > 1e-12:
new_vertices[i] = vertices[i] - (avg_n / avg_n_norm) * delta new_vertices[i] = vertices[i] - (avg_n / avg_n_norm) * avg_delta
else: else:
new_vertices[i] = vertices[i] new_vertices[i] = vertices[i]

View file

@ -1,7 +1,7 @@
import numpy import numpy
import adze import adze
from adze.shapes import build_box from adze.shapes import build_box
from adze.offset import offset, smooth, closing from adze.offset import offset, smooth, closing, offset_anisotropic
def test_offset_cube_expand() -> None: def test_offset_cube_expand() -> None:
# Unit cube: [0,1]x[0,1]x[0,1], vol=1 # Unit cube: [0,1]x[0,1]x[0,1], vol=1
@ -58,3 +58,34 @@ def test_closing_cube() -> None:
# For a perfect cube, offset(0.1) then offset(-0.1) should return to original # For a perfect cube, offset(0.1) then offset(-0.1) should return to original
assert numpy.isclose(adze.get_volume(closed), 1.0, atol=1e-7) assert numpy.isclose(adze.get_volume(closed), 1.0, atol=1e-7)
def test_anisotropic_etch() -> None:
# Unit cube [0,1]^3
cube = build_box([[0, 0, 0], [1, 1, 1]])
# Define an etch rate function:
# Fast vertical etch (-0.2), slow horizontal etch (-0.05)
# Note: Normals are inward facing for adze clipping convention?
# Wait, planes_from_box in shapes.py returns normals like (0,0,1) for z=0 face.
# Let's verify normal direction with a quick check if needed, but standard logic:
# offset uses inward normals. A negative return value from rate_func shrinks.
def vertical_etch_rate(normal: numpy.ndarray) -> float:
# Check if normal is primarily vertical (z-axis)
if abs(normal[2]) > 0.9:
return -0.2
return -0.05
etched = offset_anisotropic(cube, vertical_etch_rate)
# Expected bounds:
# Z: [0,1] -> [0.2, 0.8] (shrunk by 0.2 on both top and bottom) -> height 0.6
# X, Y: [0,1] -> [0.05, 0.95] (shrunk by 0.05 on sides) -> width 0.9
vmin, vmax = adze.util.get_aabb(etched)
assert numpy.allclose(vmin, [0.05, 0.05, 0.2])
assert numpy.allclose(vmax, [0.95, 0.95, 0.8])
# Volume = 0.9 * 0.9 * 0.6 = 0.486
assert numpy.isclose(adze.get_volume(etched), 0.486)