|
|
""" |
|
|
SDF Primitives - Core geometric shape representations as Signed Distance Fields. |
|
|
Following GeoSDF paper methodology. |
|
|
|
|
|
This module contains: |
|
|
- Math utilities for quartic solving (Appendix B) |
|
|
- SDF primitive classes (Circle, Ellipse, Hyperbola, Parabola, Line, etc.) |
|
|
""" |
|
|
|
|
|
import torch |
|
|
import torch.nn as nn |
|
|
from typing import Tuple |
|
|
|
|
|
|
|
|
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def solve_cubic_one_real_batch(a: torch.Tensor, b: torch.Tensor, c: torch.Tensor, |
|
|
d: torch.Tensor) -> torch.Tensor: |
|
|
"""Find one real root of cubic equation using Cardano's formula.""" |
|
|
a_safe = a + 1e-10 * torch.sign(a + 1e-20) |
|
|
p = b / a_safe |
|
|
q = c / a_safe |
|
|
r = d / a_safe |
|
|
|
|
|
alpha = q - p**2 / 3 |
|
|
beta = 2 * p**3 / 27 - p * q / 3 + r |
|
|
discriminant = (beta / 2)**2 + (alpha / 3)**3 |
|
|
sqrt_disc = torch.sqrt(torch.clamp(discriminant, min=0) + 1e-12) |
|
|
|
|
|
term1 = -beta / 2 + sqrt_disc |
|
|
term2 = -beta / 2 - sqrt_disc |
|
|
|
|
|
def safe_cbrt(x): |
|
|
return torch.sign(x) * torch.pow(torch.abs(x) + 1e-12, 1/3) |
|
|
|
|
|
u = safe_cbrt(term1) |
|
|
v = safe_cbrt(term2) |
|
|
|
|
|
return u + v - p / 3 |
|
|
|
|
|
|
|
|
def hyperbola_distance_quartic(px: torch.Tensor, py: torch.Tensor, |
|
|
a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: |
|
|
"""Compute exact distance from point to hyperbola using Newton iteration.""" |
|
|
px_abs = torch.abs(px) |
|
|
py_abs = torch.abs(py) |
|
|
|
|
|
t = torch.asinh(py_abs / (b + 1e-8)) |
|
|
t = torch.clamp(t, 0.01, 10.0) |
|
|
|
|
|
for _ in range(15): |
|
|
cosh_t = torch.cosh(t) |
|
|
sinh_t = torch.sinh(t) |
|
|
hx = a * cosh_t |
|
|
hy = b * sinh_t |
|
|
dx = px_abs - hx |
|
|
dy = py_abs - hy |
|
|
|
|
|
grad = -2 * (dx * a * sinh_t + dy * b * cosh_t) |
|
|
hess = 2 * (a**2 * sinh_t**2 + b**2 * cosh_t**2 - dx * a * cosh_t - dy * b * sinh_t) + 1e-6 |
|
|
|
|
|
step = grad / torch.abs(hess) |
|
|
t = t - torch.clamp(step, -0.3, 0.3) |
|
|
t = torch.clamp(t, 0.001, 20.0) |
|
|
|
|
|
cosh_t = torch.cosh(t) |
|
|
sinh_t = torch.sinh(t) |
|
|
return torch.sqrt((px_abs - a * cosh_t)**2 + (py_abs - b * sinh_t)**2 + 1e-10) |
|
|
|
|
|
|
|
|
def ellipse_distance_quartic(px: torch.Tensor, py: torch.Tensor, |
|
|
a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: |
|
|
"""Compute exact distance from point to ellipse using Newton iteration.""" |
|
|
px_abs = torch.abs(px) |
|
|
py_abs = torch.abs(py) |
|
|
|
|
|
a_use = torch.max(a, b) |
|
|
b_use = torch.min(a, b) |
|
|
|
|
|
needs_swap = a < b |
|
|
if needs_swap: |
|
|
px_use, py_use = py_abs, px_abs |
|
|
else: |
|
|
px_use, py_use = px_abs, py_abs |
|
|
|
|
|
at_origin = (px_use < 1e-10) & (py_use < 1e-10) |
|
|
on_x_axis = py_use < 1e-10 |
|
|
on_y_axis = px_use < 1e-10 |
|
|
|
|
|
theta = torch.atan2(a_use * py_use, b_use * px_use) |
|
|
|
|
|
for _ in range(12): |
|
|
cos_t = torch.cos(theta) |
|
|
sin_t = torch.sin(theta) |
|
|
ex = a_use * cos_t |
|
|
ey = b_use * sin_t |
|
|
dx = px_use - ex |
|
|
dy = py_use - ey |
|
|
|
|
|
grad = 2 * (dx * a_use * sin_t - dy * b_use * cos_t) |
|
|
hess = 2 * (a_use**2 * sin_t**2 + b_use**2 * cos_t**2 + dx * a_use * cos_t + dy * b_use * sin_t) + 1e-6 |
|
|
|
|
|
theta = theta - torch.clamp(grad / torch.abs(hess), -0.3, 0.3) |
|
|
|
|
|
cos_t = torch.cos(theta) |
|
|
sin_t = torch.sin(theta) |
|
|
dist = torch.sqrt((px_use - a_use * cos_t)**2 + (py_use - b_use * sin_t)**2 + 1e-10) |
|
|
|
|
|
dist = torch.where(at_origin, b_use, dist) |
|
|
dist = torch.where(on_x_axis & ~at_origin, torch.where(px_use > a_use, px_use - a_use, torch.sqrt((px_use - a_use)**2 + 1e-10)), dist) |
|
|
dist = torch.where(on_y_axis & ~at_origin, torch.abs(py_use - b_use), dist) |
|
|
|
|
|
return dist |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class SDFPrimitive(nn.Module): |
|
|
"""Base class for SDF primitives - all shapes represented as distance functions.""" |
|
|
|
|
|
def forward(self, p: torch.Tensor) -> torch.Tensor: |
|
|
"""Compute signed distance from points p to the shape boundary.""" |
|
|
raise NotImplementedError |
|
|
|
|
|
|
|
|
class PointSDF(SDFPrimitive): |
|
|
"""SDF for a point: f(p; c) = ||p - c||₂""" |
|
|
|
|
|
def __init__(self, center: torch.Tensor): |
|
|
super().__init__() |
|
|
self.center = nn.Parameter(center.clone()) |
|
|
|
|
|
def forward(self, p: torch.Tensor) -> torch.Tensor: |
|
|
return torch.norm(p - self.center, dim=-1) |
|
|
|
|
|
|
|
|
class CircleSDF(SDFPrimitive): |
|
|
"""SDF for circle: f(p; c, r) = ||p - c||₂ - r""" |
|
|
|
|
|
def __init__(self, center: torch.Tensor, radius: torch.Tensor): |
|
|
super().__init__() |
|
|
self.center = nn.Parameter(center.clone()) |
|
|
self.radius = nn.Parameter(radius.clone()) |
|
|
|
|
|
def forward(self, p: torch.Tensor) -> torch.Tensor: |
|
|
dist_to_center = torch.norm(p - self.center, dim=-1) |
|
|
return dist_to_center - self.radius |
|
|
|
|
|
|
|
|
class EllipseSDF(SDFPrimitive): |
|
|
"""SDF for ellipse: x²/a² + y²/b² = 1""" |
|
|
|
|
|
def __init__(self, center: torch.Tensor, a: torch.Tensor, b: torch.Tensor): |
|
|
super().__init__() |
|
|
self.center = nn.Parameter(center.clone()) |
|
|
self.a = nn.Parameter(a.clone()) |
|
|
self.b = nn.Parameter(b.clone()) |
|
|
|
|
|
def forward(self, p: torch.Tensor) -> torch.Tensor: |
|
|
p_local = p - self.center |
|
|
px = p_local[..., 0] |
|
|
py = p_local[..., 1] |
|
|
|
|
|
a = torch.abs(self.a) + 1e-8 |
|
|
b = torch.abs(self.b) + 1e-8 |
|
|
|
|
|
dist = ellipse_distance_quartic(px, py, a, b) |
|
|
ellipse_val = px**2 / (a**2) + py**2 / (b**2) |
|
|
inside = ellipse_val < 1 |
|
|
|
|
|
return torch.where(inside, -dist, dist) |
|
|
|
|
|
|
|
|
class HyperbolaSDF(SDFPrimitive): |
|
|
"""SDF for hyperbola: x²/a² - y²/b² = 1""" |
|
|
|
|
|
def __init__(self, center: torch.Tensor, a: torch.Tensor, b: torch.Tensor): |
|
|
super().__init__() |
|
|
self.center = nn.Parameter(center.clone()) |
|
|
self.a = nn.Parameter(a.clone()) |
|
|
self.b = nn.Parameter(b.clone()) |
|
|
|
|
|
def forward(self, p: torch.Tensor) -> torch.Tensor: |
|
|
p_local = p - self.center |
|
|
px = p_local[..., 0] |
|
|
py = p_local[..., 1] |
|
|
|
|
|
a = torch.abs(self.a) + 1e-8 |
|
|
b = torch.abs(self.b) + 1e-8 |
|
|
|
|
|
dist = hyperbola_distance_quartic(px, py, a, b) |
|
|
hyperbola_val = px**2 / (a**2) - py**2 / (b**2) |
|
|
is_between_branches = hyperbola_val < 1 |
|
|
|
|
|
return torch.where(is_between_branches, -dist, dist) |
|
|
|
|
|
|
|
|
class ParabolaSDF(SDFPrimitive): |
|
|
"""SDF for parabola: y² = 4px (rightward) or x² = 4py (upward)""" |
|
|
|
|
|
def __init__(self, vertex: torch.Tensor, p: torch.Tensor, direction: str = 'right'): |
|
|
super().__init__() |
|
|
self.vertex = nn.Parameter(vertex.clone()) |
|
|
self.p = nn.Parameter(p.clone()) |
|
|
self.direction = direction |
|
|
|
|
|
def forward(self, pts: torch.Tensor) -> torch.Tensor: |
|
|
p_local = pts - self.vertex |
|
|
px = p_local[..., 0] |
|
|
py = p_local[..., 1] |
|
|
p_param = torch.abs(self.p) + 1e-6 |
|
|
|
|
|
if self.direction == 'right': |
|
|
return self._compute_distance_right(px, py, p_param) |
|
|
elif self.direction == 'left': |
|
|
return self._compute_distance_right(-px, py, p_param) |
|
|
elif self.direction == 'up': |
|
|
return self._compute_distance_right(py, px, p_param) |
|
|
elif self.direction == 'down': |
|
|
return self._compute_distance_right(-py, px, p_param) |
|
|
return self._compute_distance_right(px, py, p_param) |
|
|
|
|
|
def _compute_distance_right(self, px: torch.Tensor, py: torch.Tensor, p: torch.Tensor) -> torch.Tensor: |
|
|
t = py.clone() |
|
|
|
|
|
for _ in range(12): |
|
|
para_x = t**2 / (4 * p) |
|
|
para_y = t |
|
|
dx = px - para_x |
|
|
dy = py - para_y |
|
|
dpara_x = t / (2 * p) |
|
|
dpara_y = torch.ones_like(t) |
|
|
|
|
|
grad = -2 * (dx * dpara_x + dy * dpara_y) |
|
|
ddpara_x = 1 / (2 * p) |
|
|
hess = 2 * (dpara_x**2 + dpara_y**2 - dx * ddpara_x) + 1e-8 |
|
|
|
|
|
t = t - torch.clamp(grad / torch.abs(hess), -1.0, 1.0) |
|
|
|
|
|
para_x = t**2 / (4 * p) |
|
|
para_y = t |
|
|
dist = torch.sqrt((px - para_x)**2 + (py - para_y)**2 + 1e-10) |
|
|
|
|
|
at_vertex = (torch.abs(px) < 1e-6) & (torch.abs(py) < 1e-6) |
|
|
dist = torch.where(at_vertex, torch.zeros_like(dist), dist) |
|
|
|
|
|
on_concave_side = (px >= 0) & (py**2 < 4 * p * px) |
|
|
return torch.where(on_concave_side, -dist, dist) |
|
|
|
|
|
|
|
|
class LineSDF(SDFPrimitive): |
|
|
"""SDF for infinite line passing through point with direction.""" |
|
|
|
|
|
def __init__(self, point: torch.Tensor, direction: torch.Tensor): |
|
|
super().__init__() |
|
|
self.point = nn.Parameter(point.clone()) |
|
|
self.direction = nn.Parameter(direction / (torch.norm(direction) + 1e-8)) |
|
|
|
|
|
def forward(self, p: torch.Tensor) -> torch.Tensor: |
|
|
v = p - self.point |
|
|
normal = torch.tensor([-self.direction[1], self.direction[0]], device=p.device) |
|
|
return (v * normal).sum(dim=-1) |
|
|
|
|
|
|
|
|
class LineSegmentSDF(SDFPrimitive): |
|
|
"""SDF for line segment from point a to point b.""" |
|
|
|
|
|
def __init__(self, a: torch.Tensor, b: torch.Tensor): |
|
|
super().__init__() |
|
|
self.a = nn.Parameter(a.clone()) |
|
|
self.b = nn.Parameter(b.clone()) |
|
|
|
|
|
def forward(self, p: torch.Tensor) -> torch.Tensor: |
|
|
v_ab = self.b - self.a |
|
|
v_ap = p - self.a |
|
|
h = (v_ap * v_ab).sum(dim=-1) / (torch.norm(v_ab)**2 + 1e-8) |
|
|
h_clamped = torch.clamp(h, 0, 1) |
|
|
closest = self.a + h_clamped.unsqueeze(-1) * v_ab |
|
|
return torch.norm(p - closest, dim=-1) |
|
|
|
|
|
|
|
|
class TriangleEdgesSDF(SDFPrimitive): |
|
|
"""SDF for triangle edges (boundary only).""" |
|
|
|
|
|
def __init__(self, v0: torch.Tensor, v1: torch.Tensor, v2: torch.Tensor, |
|
|
line_thickness: float = 0.02): |
|
|
super().__init__() |
|
|
self.edge0 = LineSegmentSDF(v0, v1) |
|
|
self.edge1 = LineSegmentSDF(v1, v2) |
|
|
self.edge2 = LineSegmentSDF(v2, v0) |
|
|
self.thickness = line_thickness |
|
|
|
|
|
def forward(self, p: torch.Tensor) -> torch.Tensor: |
|
|
d0 = self.edge0(p) |
|
|
d1 = self.edge1(p) |
|
|
d2 = self.edge2(p) |
|
|
return torch.min(torch.min(d0, d1), d2) - self.thickness |
|
|
|
|
|
|
|
|
class TriangleFillSDF(SDFPrimitive): |
|
|
"""SDF for filled triangle region.""" |
|
|
|
|
|
def __init__(self, v0: torch.Tensor, v1: torch.Tensor, v2: torch.Tensor): |
|
|
super().__init__() |
|
|
self.v0 = nn.Parameter(v0.clone()) |
|
|
self.v1 = nn.Parameter(v1.clone()) |
|
|
self.v2 = nn.Parameter(v2.clone()) |
|
|
self.edge0 = LineSegmentSDF(v0, v1) |
|
|
self.edge1 = LineSegmentSDF(v1, v2) |
|
|
self.edge2 = LineSegmentSDF(v2, v0) |
|
|
|
|
|
def _sign(self, p: torch.Tensor, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: |
|
|
return (p[..., 0] - a[0]) * (b[1] - a[1]) - (b[0] - a[0]) * (p[..., 1] - a[1]) |
|
|
|
|
|
def forward(self, p: torch.Tensor) -> torch.Tensor: |
|
|
d0 = self.edge0(p) |
|
|
d1 = self.edge1(p) |
|
|
d2 = self.edge2(p) |
|
|
dist = torch.min(torch.min(d0, d1), d2) |
|
|
|
|
|
s0 = self._sign(p, self.v0, self.v1) |
|
|
s1 = self._sign(p, self.v1, self.v2) |
|
|
s2 = self._sign(p, self.v2, self.v0) |
|
|
|
|
|
inside = ((s0 >= 0) & (s1 >= 0) & (s2 >= 0)) | ((s0 <= 0) & (s1 <= 0) & (s2 <= 0)) |
|
|
return torch.where(inside, -dist, dist) |
|
|
|
|
|
|
|
|
class RightAngleSDF(SDFPrimitive): |
|
|
"""SDF for right angle marker.""" |
|
|
|
|
|
def __init__(self, vertex: torch.Tensor, dir1: torch.Tensor, dir2: torch.Tensor, |
|
|
size: float = 0.25, thickness: float = 0.015): |
|
|
super().__init__() |
|
|
dir1_norm = dir1 / (torch.norm(dir1) + 1e-8) |
|
|
dir2_norm = dir2 / (torch.norm(dir2) + 1e-8) |
|
|
|
|
|
p1 = vertex + dir1_norm * size |
|
|
p2 = vertex + dir2_norm * size |
|
|
p3 = vertex + dir1_norm * size + dir2_norm * size |
|
|
|
|
|
self.seg1 = LineSegmentSDF(p1, p3) |
|
|
self.seg2 = LineSegmentSDF(p2, p3) |
|
|
self.thickness = thickness |
|
|
|
|
|
def forward(self, p: torch.Tensor) -> torch.Tensor: |
|
|
return torch.min(self.seg1(p), self.seg2(p)) - self.thickness |
|
|
|