Skip to content

The most powerful and modular diffusion model GUI, api and backend with a graph/nodes interface. The fastest local inference engine in the world.

Refactor 3D model remeshing (CORE-560) (#16805)

Jukka Seppänen719ee29cfc89
diff --git a/comfy/ldm/trellis2/model.py b/comfy/ldm/trellis2/model.py
index 352c9c91c..22eaf146c 100644
--- a/comfy/ldm/trellis2/model.py
+++ b/comfy/ldm/trellis2/model.py
@@ -125,16 +125,13 @@ class SparseRotaryPositionEmbedder(nn.Module):
freqs_cis = self._get_freqs_cis(coords)
q.register_spatial_cache(cache_name, freqs_cis)
- if q.feats.ndim == 3:
- f_cis = freqs_cis.unsqueeze(1)
- else:
- f_cis = freqs_cis
-
+ f_cis = freqs_cis.unsqueeze(1) if q.feats.ndim == 3 else freqs_cis
+ # a leading batch dim gives the (B, L, H, D) layout the kitchen kernel takes; without it RoPE runs in float32 torch
if k is None:
- return q.replace(apply_rope1(q.feats, f_cis))
+ return q.replace(apply_rope1(q.feats[None], f_cis[None])[0])
- q_feats, k_feats = apply_rope(q.feats, k.feats, f_cis)
- return q.replace(q_feats), k.replace(k_feats)
+ q_feats, k_feats = apply_rope(q.feats[None], k.feats[None], f_cis[None])
+ return q.replace(q_feats[0]), k.replace(k_feats[0])
class RotaryPositionEmbedder(SparseRotaryPositionEmbedder):
diff --git a/comfy_extras/mesh3d/postprocess/qem_decimate.py b/comfy_extras/mesh3d/postprocess/qem_decimate.py
index 157364aaa..136630d93 100644
--- a/comfy_extras/mesh3d/postprocess/qem_decimate.py
+++ b/comfy_extras/mesh3d/postprocess/qem_decimate.py
@@ -1,11 +1,8 @@
"""
-Pure-PyTorch GPU-parallel QEM mesh simplification.
+Pure-PyTorch GPU QEM mesh simplification.
- - Parallel greedy edge-matching collapse loop
- - Plane/line/feature-edge/boundary quadrics, memoryless accumulation
- - Normal-flip prevention, link-condition, skinny penalties
- - Non-manifold/sliver handling without dropping faces
- - Pre/post-clean pipeline (weld, degenerates, small components)
+Parallel rounds of independent edge collapses, gated by normal-flip, link-condition and
+skinny-triangle checks, with mesh cleanup before and after.
"""
from __future__ import annotations
@@ -14,95 +11,63 @@ from typing import Optional, Tuple
import math
-import numpy as _np
import torch
-from scipy.sparse import coo_matrix
-from scipy.sparse.csgraph import connected_components
from tqdm import tqdm as _tqdm
+import comfy.quant_ops
import comfy.utils as _comfy_utils
@dataclass
class QEMConfig:
- # Precision
- dtype: torch.dtype = torch.float32 # float64 much slower on consumer GPUs
-
- # Numerical conditioning
- stabilizer_scale: float = 1e-3 # Tikhonov reg: stabilizer = mesh_scale^2 * this
- wander_threshold: float = 2.0 # fall back to midpoint if v* lands > N×edge_length from an endpoint
+ stabilizer_scale: float = 1e-3 # Tikhonov term = mesh_scale² * this
+ wander_threshold: float = 2.0 # midpoint fallback when v* is > this × edge length from an endpoint
clamp_v_to_edge: bool = True # project v* onto the edge segment (qem mode only)
- # Placement mode (also selects collapse driver):
- # "midpoint" = threshold-schedule driver, most stable (defaults below match it);
- # "qem" = sharpest, QEM-optimum placement + ratio driver.
+ # "midpoint": cost-threshold driver, most stable, defaults tuned for it; "qem": optimal placement, ratio driver
placement_mode: str = "midpoint"
- flip_reject_hard: bool = True # hard-reject (err=+inf) top-K collapses that flip any 1-ring normal
-
- # Per-iteration batch sizing
- sampling_cap: int = 10_000_000 # max edges processed per outer iter
+ sampling_cap: int = 10_000_000 # about this many edges evaluated per round
max_collapses_fraction: float = 0.25 # of remaining faces-to-remove
max_collapses_floor: int = 10_000
max_collapses_ceiling: int = 1_000_000
- max_collapses_relative_cap: float = 0.10 # cap per-iter collapses as fraction of current faces; 0 disables
+ max_collapses_relative_cap: float = 0.10 # of current faces
- # Loop control
max_iterations: int = 5_000
- compaction_period: int = 5
- compaction_threshold: float = 0.85 # compact when alive_frac < this
- # Quality knobs
- boundary_quadrics: bool = True
- boundary_weight: float = 1000.0
- recompute_normals_post: bool = True
- line_quadric_weight: float = 0.0 # penalise deviation ⟂ to edge dir → more uniform verts; 0 disables
- line_quadric_skip_opposite_normals_cos: float = 0.0 # skip line quadrics on edges with endpoint cos < this
+ boundary_weight: float = 1000.0 # line quadrics pinning boundary edges
+ line_quadric_weight: float = 0.0 # more uniform verts; 0 disables
+ line_quadric_skip_opposite_normals_cos: float = 0.0 # skip edges with endpoint normal cos below this
- # Feature-edge quadrics on sharp interior edges (dihedral > min); 0 disables.
+ # line quadrics on interior edges sharper than the min dihedral; 0 disables
feature_edge_quadric_weight: float = 0.0
feature_edge_min_dihedral_deg: float = 30.0
- # Flip check (FA-QEM §3.3)
- quality_topk_multiplier: int = 4 # quality-check band size = this * max_collapses_per_iter
- flip_cos_threshold: float = 0.0 # 0 = count any sign reversal (dihedral > 90°)
- flip_check_max_degree: int = 16 # cap on vertex degree for the flip-check table
+ # FA-QEM §3.3: reject collapses that flip a 1-ring normal
+ flip_cos_threshold: float = 0.0 # 0 = any sign reversal (dihedral > 90°)
+ flip_check_max_degree: int = 16 # torch fallback only; the kitchen op is exact
- # Triangle shape penalty
- skinny_weight: float = 1e-3 # penalise top-K collapses producing needle/sliver tris; 0 disables
+ skinny_weight: float = 1e-3 # needle/sliver penalty
- # Topology preservation
- enforce_link_condition: bool = True # reject collapses that violate the link condition
+ enforce_link_condition: bool = True # keep topology, until that alone blocks the target
- # Quadric area weighting
- area_weighted_quadrics: bool = False # True: Garland-Heckbert area-weighted; False: un-weighted
+ area_weighted_quadrics: bool = False # Garland-Heckbert area weighting
- # edge-length cost regularizer
- lambda_edge_length: float = 1e-2 # add λ*len² to bias toward short edges; 0 disables
- lambda_edge_length_absolute: bool = True # apply λ absolutely vs relative-to-QEM-median
+ lambda_edge_length: float = 1e-2 # cost += λ·len², favours short edges
- # Threshold-schedule driver (placement_mode == "midpoint"):
- # each round collapses a disjoint set with cost <= thresh, ×10 when < 1% removed.
- threshold_start: float = 1e-8
- memoryless_qem: bool = True # rebuild quadrics each round vs accumulate
- repair_nonmanifold: bool = True # final repair_non_manifold_edges pass
+ threshold_start: float = 1e-8 # midpoint driver, × mesh_scale²; ×10 when a round removes < 1%
+ repair_nonmanifold: bool = True # split sheets fused at non-manifold edges after decimation
- # Pre-clean (input mesh)
- preclean: bool = True # weld coincident verts, drop degenerate/duplicate/unused
-
- # Post-clean (output mesh)
postclean: bool = True # remove slivers, tiny components, unused verts left by collapse
postclean_min_angle_deg: float = 0.5
postclean_max_aspect_ratio: float = 100.0
- postclean_min_component_faces: int = 8 # drop components with fewer faces than this
+ postclean_min_component_faces: int = 8
- # Preclean tuning
- preclean_weld_epsilon_rel: float = 1e-5 # weld tolerance as fraction of bbox diagonal
- preclean_min_component_faces: int = 0 # 0 = keep all components
+ preclean_weld_epsilon_rel: float = 1e-5 # fraction of bbox diagonal
@property
def threshold_driver(self) -> bool:
- """The cost-threshold collapse driver is used by the midpoint placement mode."""
+ """True when the cost-threshold driver is used (midpoint placement)."""
return self.placement_mode == "midpoint"
@@ -122,37 +87,10 @@ def _sorted_edge_halfedges(
return key[sort_idx], face_per_he[sort_idx], slot_per_he[sort_idx]
-def _vert_is_boundary_mask(faces: torch.Tensor, num_verts: int) -> torch.Tensor:
- """(V,) bool mask: True for verts incident to any boundary edge."""
- device = faces.device
- out = torch.zeros(num_verts, dtype=torch.bool, device=device)
- bedges = _detect_boundary_edges(faces, num_verts)
- if bedges.numel() == 0:
- return out
- out[bedges[:, 0]] = True
- out[bedges[:, 1]] = True
- return out
-
-
-def _detect_boundary_edges(faces: torch.Tensor, num_verts: int) -> torch.Tensor:
- """Boundary edges as [N, 2] of vertex indices (each appearing in exactly one face)."""
- if faces.numel() == 0:
- return torch.empty((0, 2), dtype=torch.int64, device=faces.device)
- sorted_keys, _, _ = _sorted_edge_halfedges(faces, num_verts)
- unique_key, counts = torch.unique(sorted_keys, return_counts=True)
- boundary_key = unique_key[counts == 1]
- if boundary_key.numel() == 0:
- return torch.empty((0, 2), dtype=torch.int64, device=faces.device)
- P = num_verts + 1
- bv0 = boundary_key // P
- bv1 = boundary_key % P
- return torch.stack([bv0, bv1], dim=1)
-
-
def _manifold_edge_pairs(
sorted_keys: torch.Tensor, sorted_faces: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
- """Edges shared by exactly 2 faces (filters >2-incident groups); returns (pair_keys, fa, fb)."""
+ """Edges shared by exactly 2 faces; returns (pair_keys, fa, fb)."""
if sorted_keys.shape[0] < 2:
empty = sorted_keys.new_empty(0)
return empty, empty, empty
@@ -172,15 +110,20 @@ def _manifold_edge_pairs(
sorted_faces[pair_starts + 1])
+_FACE_CHUNK = 1 << 22 # faces per pass of the quadric build
+_EDGE_CHUNK = 1 << 21 # edges per pass of the collapse errors
+
+
def _line_quadric_planes(
pa: torch.Tensor, pb: torch.Tensor
-) -> Tuple[torch.Tensor, torch.Tensor]:
- """Two plane equations (E,4) per edge whose squared-dist sum = squared ⟂ distance to the edge line."""
- e = pb - pa # (E, 3)
+) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Two planes (E, 4) per edge whose squared distances sum to the squared distance from the edge line.
+ Returns (p_u, p_w, edge_len)."""
+ e = pb - pa
elen = torch.norm(e, dim=-1, keepdim=True).clamp_min(1e-12)
- e_unit = e / elen # (E, 3)
- m = 0.5 * (pa + pb) # (E, 3)
- # helper axis not parallel to e_unit, then Gram-Schmidt against e_unit
+ e_unit = e / elen
+ m = 0.5 * (pa + pb)
+ # least-aligned axis, orthogonalised against e_unit
helper = torch.zeros_like(e_unit)
helper.scatter_(-1, e_unit.abs().argmin(dim=-1, keepdim=True), 1.0)
u = helper - (helper * e_unit).sum(-1, keepdim=True) * e_unit
@@ -188,7 +131,7 @@ def _line_quadric_planes(
w = torch.cross(e_unit, u, dim=-1)
d_u = -(u * m).sum(-1, keepdim=True)
d_w = -(w * m).sum(-1, keepdim=True)
- p_u = torch.cat([u, d_u], dim=-1) # (E, 4)
+ p_u = torch.cat([u, d_u], dim=-1)
p_w = torch.cat([w, d_w], dim=-1)
return p_u, p_w, elen.squeeze(-1)
@@ -201,7 +144,7 @@ def _add_line_quadrics(
weight: float,
skip_he_mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
- """Add line quadrics for all 3F half-edges, weighted by face_area*weight; skip_he_mask zeroes True positions."""
+ """Add line quadrics of all 3F half-edges to Q_flat, weighted by face area * weight; skip_he_mask drops edges."""
a_all = torch.cat([faces[:, 0], faces[:, 1], faces[:, 2]], dim=0).long()
b_all = torch.cat([faces[:, 1], faces[:, 2], faces[:, 0]], dim=0).long()
pa = verts[a_all]
@@ -217,7 +160,7 @@ def _add_line_quadrics(
+ p_w.unsqueeze(-1) * p_w.unsqueeze(-2)
) * w_per_edge
K_flat = K_line.reshape(-1, 16)
- Q_flat.scatter_add_(0, a_all.unsqueeze(1).expand(-1, 16), K_flat) # scatter to both endpoints
+ Q_flat.scatter_add_(0, a_all.unsqueeze(1).expand(-1, 16), K_flat)
Q_flat.scatter_add_(0, b_all.unsqueeze(1).expand(-1, 16), K_flat)
return Q_flat
@@ -226,8 +169,9 @@ def _build_quadrics(
verts: torch.Tensor,
faces: torch.Tensor,
cfg: QEMConfig,
+ b_edges: torch.Tensor, # (B, 2) boundary edges of `faces`
) -> torch.Tensor:
- """Per-vertex area-weighted quadric (V, 4, 4)."""
+ """Per-vertex quadrics (V, 4, 4): face planes plus the line, boundary and feature-edge terms enabled in cfg."""
V = verts.shape[0]
dtype = verts.dtype
device = verts.device
@@ -235,66 +179,58 @@ def _build_quadrics(
Q_flat = torch.zeros((V, 16), dtype=dtype, device=device)
if faces.numel() > 0:
- v0 = verts[faces[:, 0]]
- v1 = verts[faces[:, 1]]
- v2 = verts[faces[:, 2]]
- e1 = v1 - v0
- e2 = v2 - v0
- n = torch.cross(e1, e2, dim=-1)
- area = torch.norm(n, dim=-1)
- mask = area > 1e-12
- # where() avoids boolean-index gather+scatter (fewer index kernels)
- n_norm = torch.where(mask.unsqueeze(-1),
- n / area.unsqueeze(-1).clamp_min(1e-12),
- n.new_zeros(()))
- d = -(n_norm * v0).sum(dim=-1, keepdim=True)
- p = torch.cat([n_norm, d], dim=-1) # (F, 4)
- K = torch.einsum("fi,fj->fij", p, p) # (F, 4, 4)
-
- if cfg.area_weighted_quadrics:
- K.mul_(area[:, None, None])
- K_flat = K.reshape(-1, 16)
- for corner in range(3):
- idx = faces[:, corner].unsqueeze(1).expand(-1, 16)
- Q_flat.scatter_add_(0, idx, K_flat)
+ F = faces.shape[0]
+ area = torch.empty(F, dtype=dtype, device=device)
+ n_norm = torch.empty((F, 3), dtype=dtype, device=device) if cfg.line_quadric_weight > 0 else None
+ # a chunk at a time: the per-face quadrics are the decimation's largest transient
+ for s in range(0, F, _FACE_CHUNK):
+ f = faces[s:s + _FACE_CHUNK]
+ v0 = verts[f[:, 0]]
+ n = torch.cross(verts[f[:, 1]] - v0, verts[f[:, 2]] - v0, dim=-1)
+ a = torch.norm(n, dim=-1)
+ # degenerate faces get a zero plane
+ nn = torch.where((a > 1e-12).unsqueeze(-1), n / a.unsqueeze(-1).clamp_min(1e-12), n.new_zeros(()))
+ p = torch.cat([nn, -(nn * v0).sum(dim=-1, keepdim=True)], dim=-1) # (n, 4)
+ K = torch.einsum("fi,fj->fij", p, p)
+ if cfg.area_weighted_quadrics:
+ K.mul_(a[:, None, None])
+ K_flat = K.reshape(-1, 16)
+ for corner in range(3):
+ Q_flat.scatter_add_(0, f[:, corner].unsqueeze(1).expand(-1, 16), K_flat)
+ area[s:s + f.shape[0]] = a
+ if n_norm is not None:
+ n_norm[s:s + f.shape[0]] = nn
- # Line quadrics: squared ⟂ distance from v to the edge-midpoint line, all 3F half-edges in one pass.
+ # line quadrics on all half-edges, skipping thin-shell rim edges whose endpoint normals oppose
if cfg.line_quadric_weight > 0 and faces.numel() > 0:
- # skip thin-shell rim edges (endpoint normals oppose)
- skip_he_sharp = None
- if cfg.line_quadric_skip_opposite_normals_cos < 1.0:
- v_norm = torch.zeros((V, 3), dtype=dtype, device=device)
- n_weighted = n_norm * area.unsqueeze(-1) # normal * 2× area
- for corner in range(3):
- v_norm.scatter_add_(0, faces[:, corner].unsqueeze(-1).expand(-1, 3),
- n_weighted)
- v_norm = torch.nn.functional.normalize(v_norm, p=2, dim=-1, eps=1e-12)
- a_he = torch.cat([faces[:, 0], faces[:, 1], faces[:, 2]], dim=0).long()
- b_he = torch.cat([faces[:, 1], faces[:, 2], faces[:, 0]], dim=0).long()
- cos_endpoints = (v_norm[a_he] * v_norm[b_he]).sum(dim=-1)
- skip_he_sharp = cos_endpoints < cfg.line_quadric_skip_opposite_normals_cos
- if not skip_he_sharp.any():
- skip_he_sharp = None
+ v_norm = torch.zeros((V, 3), dtype=dtype, device=device)
+ n_weighted = n_norm * area.unsqueeze(-1)
+ for corner in range(3):
+ v_norm.scatter_add_(0, faces[:, corner].unsqueeze(-1).expand(-1, 3),
+ n_weighted)
+ v_norm = torch.nn.functional.normalize(v_norm, p=2, dim=-1, eps=1e-12)
+ a_he = torch.cat([faces[:, 0], faces[:, 1], faces[:, 2]], dim=0).long()
+ b_he = torch.cat([faces[:, 1], faces[:, 2], faces[:, 0]], dim=0).long()
+ cos_endpoints = (v_norm[a_he] * v_norm[b_he]).sum(dim=-1)
+ skip_he_sharp = cos_endpoints < cfg.line_quadric_skip_opposite_normals_cos
Q_flat = _add_line_quadrics(verts, faces, area, Q_flat,
cfg.line_quadric_weight,
skip_he_mask=skip_he_sharp)
- # Boundary line quadrics: pin boundary-edge endpoints to the boundary line.
- if cfg.boundary_quadrics and faces.numel() > 0:
- b_edges = _detect_boundary_edges(faces, V)
- if b_edges.shape[0] > 0:
- ba = b_edges[:, 0]
- bb = b_edges[:, 1]
- pa = verts[ba]
- pb = verts[bb]
- p_u, p_w, _ = _line_quadric_planes(pa, pb)
- K_b = (torch.einsum("ei,ej->eij", p_u, p_u)
- + torch.einsum("ei,ej->eij", p_w, p_w)) * cfg.boundary_weight
- K_b_flat = K_b.reshape(-1, 16)
- Q_flat.scatter_add_(0, ba.unsqueeze(1).expand(-1, 16), K_b_flat)
- Q_flat.scatter_add_(0, bb.unsqueeze(1).expand(-1, 16), K_b_flat)
-
- # Feature-edge quadrics: line quadric on sharp interior edges weighted by (1 - cos(dihedral)).
+ # pin boundary verts to their boundary edge lines
+ if b_edges.shape[0] > 0:
+ ba = b_edges[:, 0]
+ bb = b_edges[:, 1]
+ pa = verts[ba]
+ pb = verts[bb]
+ p_u, p_w, _ = _line_quadric_planes(pa, pb)
+ K_b = (torch.einsum("ei,ej->eij", p_u, p_u)
+ + torch.einsum("ei,ej->eij", p_w, p_w)) * cfg.boundary_weight
+ K_b_flat = K_b.reshape(-1, 16)
+ Q_flat.scatter_add_(0, ba.unsqueeze(1).expand(-1, 16), K_b_flat)
+ Q_flat.scatter_add_(0, bb.unsqueeze(1).expand(-1, 16), K_b_flat)
+
+ # feature-edge line quadrics, weighted by 1 - cos(dihedral)
if cfg.feature_edge_quadric_weight > 0 and faces.numel() > 0:
v0 = verts[faces[:, 0]]
v1 = verts[faces[:, 1]]
@@ -333,31 +269,24 @@ def _edge_errors(
verts: torch.Tensor,
Q: torch.Tensor,
edges: torch.Tensor,
- stabilizer: float,
- max_edge_length_sq: float,
- mesh_scale_sq: float,
+ stabilizer: torch.Tensor, # 0-d, like max_err and mesh_scale_sq
+ max_err: torch.Tensor,
+ mesh_scale_sq: torch.Tensor,
cfg: QEMConfig,
vert_is_boundary: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
- """Returns (optimal_pos, error, valid_mask); vert_is_boundary enables boundary-aware midpoint."""
+ """Per-edge collapse position, cost and valid mask; vert_is_boundary snaps midpoints to boundary endpoints."""
n_edges = edges.shape[0]
dtype = verts.dtype
device = verts.device
- if n_edges == 0:
- return (
- torch.empty((0, 3), dtype=dtype, device=device),
- torch.empty((0,), dtype=dtype, device=device),
- torch.zeros((0,), dtype=torch.bool, device=device),
- )
-
verts_pair = verts[edges] # (E, 2, 3)
pa = verts_pair[:, 0]
pb = verts_pair[:, 1]
edge_vec = pb - pa
el = torch.norm(edge_vec, dim=-1)
- # boundary-aware midpoint: snap to the boundary endpoint when exactly one is boundary
+ # snap to the boundary endpoint when exactly one endpoint is on the boundary
if vert_is_boundary is not None:
ba = vert_is_boundary[edges[:, 0]]
bb = vert_is_boundary[edges[:, 1]]
@@ -368,7 +297,7 @@ def _edge_errors(
else:
midpoint = torch.lerp(pa, pb, 0.5)
- Qe = Q[edges].sum(dim=1) # (E, 4, 4) — sum of Q[va] and Q[vb]
+ Qe = Q[edges].sum(dim=1) # (E, 4, 4)
if cfg.placement_mode == "midpoint":
opt = midpoint
@@ -376,20 +305,19 @@ def _edge_errors(
A = Qe[:, :3, :3] + torch.eye(3, device=device, dtype=dtype) * stabilizer
b = -Qe[:, :3, 3].unsqueeze(-1)
- # stabilizer keeps A invertible; full-batch solve, midpoint fallback via where (no sync)
+ # stabilizer keeps A invertible; where() fallback avoids a host sync
sol = torch.linalg.solve(A, b)
dets = torch.det(A)
good = (dets.abs() > 1e-12).unsqueeze(-1)
opt = torch.where(good, sol.squeeze(-1), midpoint)
if cfg.clamp_v_to_edge:
- # project v* onto the edge segment (subsumes the wander check)
+ # subsumes the wander check
edge_len_sq = (edge_vec * edge_vec).sum(dim=-1) + 1e-20
t = ((opt - pa) * edge_vec).sum(dim=-1) / edge_len_sq
t = t.clamp(0.0, 1.0).unsqueeze(-1)
opt = torch.lerp(pa, pb, t)
else:
- # fall back to midpoint when v* wanders from both endpoints
dist_a = torch.norm(opt - pa, dim=-1)
dist_b = torch.norm(opt - pb, dim=-1)
wander_bad = ((dist_a > cfg.wander_threshold * el) |
@@ -399,25 +327,12 @@ def _edge_errors(
v4 = torch.cat([opt, torch.ones((n_edges, 1), device=device, dtype=dtype)], dim=1)
err = torch.abs(torch.einsum("ei,eij,ej->e", v4, Qe, v4))
- # mesh_scale_sq: Python float or 0-d tensor
- if torch.is_tensor(mesh_scale_sq):
- length_ok = el * el > mesh_scale_sq * 1e-10
- else:
- length_ok = el > math.sqrt(mesh_scale_sq) * 1e-5
- error_ok = err < max_edge_length_sq
+ length_ok = el * el > mesh_scale_sq * 1e-10
+ error_ok = err < max_err
nan_ok = ~torch.isnan(opt).any(dim=-1) & ~torch.isnan(err)
valid = length_ok & error_ok & nan_ok
- # edge-length regularizer: bias collapse order toward short edges (uniform sizing)
- if cfg.lambda_edge_length > 0.0 and valid.any():
- el2 = el * el
- if cfg.lambda_edge_length_absolute:
- err = err + cfg.lambda_edge_length * el2
- else:
- qem_med = err[valid].median()
- len_med = el2[valid].median().clamp_min(1e-30)
- err = err + cfg.lambda_edge_length * el2 * (qem_med / len_med)
- return opt, err, valid
+ return opt, err + cfg.lambda_edge_length * el * el, valid
def _greedy_matching(
@@ -426,7 +341,7 @@ def _greedy_matching(
v_alive: torch.Tensor,
max_select: int,
) -> torch.Tensor:
- """Vectorised independent edge-set selection: an edge wins iff it is the min-key edge at both endpoints."""
+ """Independent edge set: an edge wins iff its (err, index) key is lowest at both endpoints; at most max_select."""
device = edges.device
n_edges = edges.shape[0]
if n_edges == 0:
@@ -461,7 +376,7 @@ def _build_vert_to_faces_pad(
num_verts: int,
max_deg: int,
) -> torch.Tensor:
- """Pad-CSR vertex-to-incident-faces table (V, max_deg) of face indices, -1 padded, degree truncated."""
+ """(V, max_deg) incident-face table, -1 padded; faces beyond max_deg are dropped."""
device = faces.device
F = faces.shape[0]
if F == 0:
@@ -481,166 +396,26 @@ def _build_vert_to_faces_pad(
return table
-def _normal_flip_mask(
- verts: torch.Tensor, # (V, 3)
- faces: torch.Tensor, # (F, 3) — must be alive faces only
- edges: torch.Tensor, # (E, 2) candidate collapse edges
- opt: torch.Tensor, # (E, 3) proposed collapse positions
- vert_to_faces: torch.Tensor, # (V, max_deg) face indices or -1
+def _quality_checks_fused(
+ verts: torch.Tensor,
+ faces: torch.Tensor,
+ edges: torch.Tensor,
+ opt: torch.Tensor,
+ vert_to_faces: torch.Tensor,
cos_threshold: float = 0.0,
+ want_link: bool = False,
chunk_size: int = 100_000,
- return_count: bool = False,
-) -> torch.Tensor:
- """(E,) bool mask (no adjacent-face flip), or int count of would-flip faces per edge if return_count."""
+) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
+ """Torch fallback for the 1-ring collapse checks; returns (flip_count, skinny, link_ok or None)."""
E = edges.shape[0]
device = verts.device
- if return_count:
- out = torch.zeros(E, dtype=torch.int32, device=device)
- else:
- out = torch.ones(E, dtype=torch.bool, device=device)
- if E == 0:
- return out
-
- max_deg = vert_to_faces.shape[1]
- a_all = edges[:, 0]
- b_all = edges[:, 1]
-
- for start in range(0, E, chunk_size):
- stop = min(start + chunk_size, E)
- Ec = stop - start
- a = a_all[start:stop]
- b = b_all[start:stop]
- oc = opt[start:stop]
-
- fa = vert_to_faces[a] # (Ec, max_deg)
- fb = vert_to_faces[b]
- all_f = torch.cat([fa, fb], dim=1) # (Ec, 2*max_deg)
- valid_f = all_f >= 0
- all_f_safe = all_f.clamp(min=0)
- fv = faces[all_f_safe] # (Ec, 2*max_deg, 3)
-
- a_b = a.view(Ec, 1)
- b_b = b.view(Ec, 1)
- s0_a = fv[..., 0] == a_b
- s0_b = fv[..., 0] == b_b
- s1_a = fv[..., 1] == a_b
- s1_b = fv[..., 1] == b_b
- s2_a = fv[..., 2] == a_b
- s2_b = fv[..., 2] == b_b
- contains_a = s0_a | s1_a | s2_a
- contains_b = s0_b | s1_b | s2_b
- # affected: face contains exactly one of {a, b} and slot is non-pad
- affected = (contains_a ^ contains_b) & valid_f
- if not affected.any():
- continue
-
- p0 = verts[fv[..., 0]] # (Ec, 2*max_deg, 3)
- p1 = verts[fv[..., 1]]
- p2 = verts[fv[..., 2]]
- n_old = torch.cross(p1 - p0, p2 - p0, dim=-1)
-
- opt_b = oc.view(Ec, 1, 3).expand(-1, 2 * max_deg, -1)
- rep0 = (s0_a | s0_b).unsqueeze(-1)
- rep1 = (s1_a | s1_b).unsqueeze(-1)
- rep2 = (s2_a | s2_b).unsqueeze(-1)
- p0n = torch.where(rep0, opt_b, p0)
- p1n = torch.where(rep1, opt_b, p1)
- p2n = torch.where(rep2, opt_b, p2)
- n_new = torch.cross(p1n - p0n, p2n - p0n, dim=-1)
-
- nlen_old = torch.norm(n_old, dim=-1)
- nlen_new = torch.norm(n_new, dim=-1)
- # degenerate-before faces can't flip; treat as OK
- denom = nlen_old * nlen_new
- safe = denom > 1e-20
- cos = torch.where(safe, (n_old * n_new).sum(dim=-1) / denom.clamp_min(1e-20),
- torch.ones_like(denom))
- flip = (cos < cos_threshold) & affected & safe
- if return_count:
- out[start:stop] = flip.sum(dim=-1).to(torch.int32)
- else:
- out[start:stop] = ~flip.any(dim=-1)
-
- return out
-
+ flip_out = torch.zeros(E, dtype=torch.int32, device=device)
+ skinny_out = torch.zeros(E, dtype=verts.dtype, device=device)
+ link_out = torch.ones(E, dtype=torch.bool, device=device) if want_link else None
-def _link_condition_mask(
- faces: torch.Tensor, # (F, 3) alive faces only
- edges: torch.Tensor, # (E, 2) candidate collapse edges
- vert_to_faces: torch.Tensor, # (V, max_deg) face idx or -1
- chunk_size: int = 100_000,
-) -> torch.Tensor:
- """(E,) bool mask — True where the collapse is topology-safe (link condition: common neighbours <= edge faces)."""
- E = edges.shape[0]
- device = faces.device
- out = torch.ones(E, dtype=torch.bool, device=device)
- if E == 0:
- return out
D = vert_to_faces.shape[1]
a_all = edges[:, 0]
b_all = edges[:, 1]
-
- for s in range(0, E, chunk_size):
- e = min(s + chunk_size, E)
- a = a_all[s:e]
- b = b_all[s:e]
- Ec = a.shape[0]
-
- fa = vert_to_faces[a] # (Ec, D)
- fb = vert_to_faces[b]
- fa_ok = fa >= 0
- fb_ok = fb >= 0
- fav = faces[fa.clamp(min=0)] # (Ec, D, 3)
- fbv = faces[fb.clamp(min=0)]
-
- # neighbour verts of a/b: take the 2 non-anchor verts per incident face → (Ec, 2D)
- a_b = a[:, None]
- b_b = b[:, None]
- an1 = torch.where(fav[..., 0] == a_b, fav[..., 1], fav[..., 0])
- an2 = torch.where(fav[..., 2] == a_b, fav[..., 1], fav[..., 2])
- bn1 = torch.where(fbv[..., 0] == b_b, fbv[..., 1], fbv[..., 0])
- bn2 = torch.where(fbv[..., 2] == b_b, fbv[..., 1], fbv[..., 2])
- na = torch.stack([an1, an2], dim=-1).reshape(Ec, 2 * D)
- nb = torch.stack([bn1, bn2], dim=-1).reshape(Ec, 2 * D)
- fa_okx = fa_ok.repeat_interleave(2, dim=1)
- fb_okx = fb_ok.repeat_interleave(2, dim=1)
- na[(na == a_b) | (na == b_b) | ~fa_okx] = -1
- nb[(nb == a_b) | (nb == b_b) | ~fb_okx] = -1
-
- # common neighbours: na entries also appearing in nb
- in_b = (na[:, :, None] == nb[:, None, :]) & (na[:, :, None] >= 0)
- na_common = torch.where(in_b.any(dim=2), na, torch.full_like(na, -1))
- # distinct count of common neighbours per edge (sort + count transitions)
- cs, _ = na_common.sort(dim=1)
- count_common = ((cs[:, 1:] != cs[:, :-1]) & (cs[:, 1:] >= 0)).sum(dim=1) \
- + (cs[:, :1] >= 0).sum(dim=1)
-
- # faces on the edge = a's faces also containing b
- count_faces = ((fav == b[:, None, None]).any(dim=2) & fa_ok).sum(dim=1)
-
- out[s:e] = count_common <= count_faces
-
- return out
-
-
-def _skinny_penalty(
- verts: torch.Tensor, # (V, 3)
- faces: torch.Tensor, # (F, 3) — alive faces only
- edges: torch.Tensor, # (E, 2) candidate collapse edges
- opt: torch.Tensor, # (E, 3) proposed collapse positions
- vert_to_faces: torch.Tensor, # (V, max_deg)
- chunk_size: int = 100_000,
-) -> torch.Tensor:
- """Per-edge post-collapse triangle-shape penalty (lambda_skinny); mean of 1 - clamp(shape,0,1) over the 1-ring."""
- E = edges.shape[0]
- device = verts.device
- out = torch.zeros(E, dtype=verts.dtype, device=device)
- if E == 0:
- return out
-
- max_deg = vert_to_faces.shape[1]
- a_all = edges[:, 0]
- b_all = edges[:, 1]
sqrt3_4 = 4.0 * math.sqrt(3.0)
for start in range(0, E, chunk_size):
@@ -648,17 +423,16 @@ def _skinny_penalty(
Ec = stop - start
a = a_all[start:stop]
b = b_all[start:stop]
- oc = opt[start:stop]
fa = vert_to_faces[a]
fb = vert_to_faces[b]
- all_f = torch.cat([fa, fb], dim=1)
+ all_f = torch.cat([fa, fb], dim=1) # (Ec, 2D)
valid_f = all_f >= 0
- all_f_safe = all_f.clamp(min=0)
- fv = faces[all_f_safe]
-
+ fv = faces[all_f.clamp(min=0)] # (Ec, 2D, 3)
a_b = a.view(Ec, 1)
b_b = b.view(Ec, 1)
+
+ oc = opt[start:stop]
s0_a = fv[..., 0] == a_b
s0_b = fv[..., 0] == b_b
s1_a = fv[..., 1] == a_b
@@ -667,131 +441,38 @@ def _skinny_penalty(
s2_b = fv[..., 2] == b_b
contains_a = s0_a | s1_a | s2_a
contains_b = s0_b | s1_b | s2_b
- # affected: face contains exactly one of {a, b} and slot is non-pad
affected = (contains_a ^ contains_b) & valid_f
- if not affected.any():
- continue
-
p0 = verts[fv[..., 0]]
p1 = verts[fv[..., 1]]
p2 = verts[fv[..., 2]]
- opt_b = oc.view(Ec, 1, 3).expand(-1, 2 * max_deg, -1)
- rep0 = (s0_a | s0_b).unsqueeze(-1)
- rep1 = (s1_a | s1_b).unsqueeze(-1)
- rep2 = (s2_a | s2_b).unsqueeze(-1)
- p0n = torch.where(rep0, opt_b, p0)
- p1n = torch.where(rep1, opt_b, p1)
- p2n = torch.where(rep2, opt_b, p2)
+ opt_b = oc.view(Ec, 1, 3).expand(-1, 2 * D, -1)
+ p0n = torch.where((s0_a | s0_b).unsqueeze(-1), opt_b, p0)
+ p1n = torch.where((s1_a | s1_b).unsqueeze(-1), opt_b, p1)
+ p2n = torch.where((s2_a | s2_b).unsqueeze(-1), opt_b, p2)
+ # ‖n_new‖ is also twice the new area for the skinny term
e01 = p1n - p0n
e02 = p2n - p0n
e12 = p2n - p1n
- two_area = torch.cross(e01, e02, dim=-1).norm(dim=-1)
- edge_sum_sq = ((e01 * e01).sum(-1)
- + (e02 * e02).sum(-1)
- + (e12 * e12).sum(-1))
- shape = (sqrt3_4 * 0.5 * two_area) / edge_sum_sq.clamp_min(1e-20)
- term = 1.0 - shape.clamp(0.0, 1.0)
- term = torch.where(affected, term, torch.zeros_like(term))
- n_affected = affected.sum(dim=-1).clamp_min(1).to(term.dtype)
- out[start:stop] = term.sum(dim=-1) / n_affected
-
- return out
-
-
-def _quality_checks_fused(
- verts: torch.Tensor,
- faces: torch.Tensor,
- edges: torch.Tensor,
- opt: torch.Tensor,
- vert_to_faces: torch.Tensor,
- cos_threshold: float = 0.0,
- want_flip: bool = True,
- want_skinny: bool = True,
- want_link: bool = False,
- chunk_size: int = 100_000,
-) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]:
- """Fused 1-ring checks (flip count / skinny / link) sharing one faces gather.
- Returns (flip_count|None, skinny|None, link_safe|None)."""
- E = edges.shape[0]
- device = verts.device
- flip_out = torch.zeros(E, dtype=torch.int32, device=device) if want_flip else None
- skinny_out = torch.zeros(E, dtype=verts.dtype, device=device) if want_skinny else None
- link_out = torch.ones(E, dtype=torch.bool, device=device) if want_link else None
- if E == 0:
- return flip_out, skinny_out, link_out
-
- D = vert_to_faces.shape[1]
- a_all = edges[:, 0]
- b_all = edges[:, 1]
- sqrt3_4 = 4.0 * math.sqrt(3.0)
- need_geom = want_flip or want_skinny
-
- for start in range(0, E, chunk_size):
- stop = min(start + chunk_size, E)
- Ec = stop - start
- a = a_all[start:stop]
- b = b_all[start:stop]
+ n_new = torch.cross(e01, e02, dim=-1)
+ nlen_new = torch.norm(n_new, dim=-1)
+ edge_sum_sq = (e01 * e01).sum(-1) + (e02 * e02).sum(-1) + (e12 * e12).sum(-1)
- # shared gather of a's and b's incident faces (the expensive part)
- fa = vert_to_faces[a]
- fb = vert_to_faces[b]
- all_f = torch.cat([fa, fb], dim=1) # (Ec, 2D)
- valid_f = all_f >= 0
- fv = faces[all_f.clamp(min=0)] # (Ec, 2D, 3)
- a_b = a.view(Ec, 1)
- b_b = b.view(Ec, 1)
+ d01, d02, d12 = p1 - p0, p2 - p0, p2 - p1
+ n_old = torch.cross(d01, d02, dim=-1)
+ nlen_old = torch.norm(n_old, dim=-1)
+ old_sum_sq = (d01 * d01).sum(-1) + (d02 * d02).sum(-1) + (d12 * d12).sum(-1)
+ # faces too thin to have a normal never count as flipped (scale-relative test)
+ usable = (nlen_old > 1e-6 * old_sum_sq) & (nlen_new > 1e-6 * edge_sum_sq)
+ flip = ((n_old * n_new).sum(dim=-1) < cos_threshold * nlen_old * nlen_new) & affected & usable
+ flip_out[start:stop] = flip.sum(dim=-1).to(torch.int32)
- if need_geom:
- oc = opt[start:stop]
- s0_a = fv[..., 0] == a_b
- s0_b = fv[..., 0] == b_b
- s1_a = fv[..., 1] == a_b
- s1_b = fv[..., 1] == b_b
- s2_a = fv[..., 2] == a_b
- s2_b = fv[..., 2] == b_b
- contains_a = s0_a | s1_a | s2_a
- contains_b = s0_b | s1_b | s2_b
- affected = (contains_a ^ contains_b) & valid_f
- if affected.any():
- p0 = verts[fv[..., 0]]
- p1 = verts[fv[..., 1]]
- p2 = verts[fv[..., 2]]
- opt_b = oc.view(Ec, 1, 3).expand(-1, 2 * D, -1)
- rep0 = (s0_a | s0_b).unsqueeze(-1)
- rep1 = (s1_a | s1_b).unsqueeze(-1)
- rep2 = (s2_a | s2_b).unsqueeze(-1)
- p0n = torch.where(rep0, opt_b, p0)
- p1n = torch.where(rep1, opt_b, p1)
- p2n = torch.where(rep2, opt_b, p2)
-
- # post-collapse normal (skinny's two_area == flip's ‖n_new‖)
- e01 = p1n - p0n
- e02 = p2n - p0n
- n_new = torch.cross(e01, e02, dim=-1)
- nlen_new = torch.norm(n_new, dim=-1)
-
- if want_flip:
- n_old = torch.cross(p1 - p0, p2 - p0, dim=-1)
- nlen_old = torch.norm(n_old, dim=-1)
- denom = nlen_old * nlen_new
- safe = denom > 1e-20
- cos = torch.where(safe, (n_old * n_new).sum(dim=-1) / denom.clamp_min(1e-20),
- torch.ones_like(denom))
- flip = (cos < cos_threshold) & affected & safe
- flip_out[start:stop] = flip.sum(dim=-1).to(torch.int32)
-
- if want_skinny:
- e12 = p2n - p1n
- edge_sum_sq = ((e01 * e01).sum(-1) + (e02 * e02).sum(-1) + (e12 * e12).sum(-1))
- shape = (sqrt3_4 * 0.5 * nlen_new) / edge_sum_sq.clamp_min(1e-20)
- term = 1.0 - shape.clamp(0.0, 1.0)
- term = torch.where(affected, term, torch.zeros_like(term))
- n_affected = affected.sum(dim=-1).clamp_min(1).to(term.dtype)
- skinny_out[start:stop] = term.sum(dim=-1) / n_affected
+ shape = (sqrt3_4 * 0.5 * nlen_new) / edge_sum_sq.clamp_min(1e-20)
+ term = torch.where(affected, 1.0 - shape.clamp(0.0, 1.0), torch.zeros_like(shape))
+ skinny_out[start:stop] = term.sum(dim=-1) / affected.sum(dim=-1).clamp_min(1).to(term.dtype)
if want_link:
- # reuses fv / valid_f; matches _link_condition_mask
+ # link condition: common neighbours of a and b must not outnumber the faces on edge ab
fa_ok = valid_f[:, :D]
fb_ok = valid_f[:, D:]
fav = fv[:, :D]
@@ -817,10 +498,34 @@ def _quality_checks_fused(
return flip_out, skinny_out, link_out
+def _gated_errors(
+ verts: torch.Tensor,
+ faces: torch.Tensor, # (F, 3) alive faces only
+ edges: torch.Tensor,
+ opt: torch.Tensor,
+ err: torch.Tensor,
+ cfg: QEMConfig,
+ link: bool,
+) -> torch.Tensor:
+ """Collapse costs with +inf on normal flips and (if `link`) link violations, plus the skinny penalty.
+ The comfy-kitchen kernel is exact; the torch fallback caps vertex degree at cfg.flip_check_max_degree."""
+ collapse_checks = _kitchen_op("edge_collapse_checks", verts)
+ if collapse_checks is not None:
+ flips, skinny, link_ok = collapse_checks(verts, faces, edges, opt, cfg.flip_cos_threshold)
+ else:
+ v_to_f = _build_vert_to_faces_pad(faces, verts.shape[0], cfg.flip_check_max_degree)
+ flips, skinny, link_ok = _quality_checks_fused(
+ verts, faces, edges, opt, v_to_f, cos_threshold=cfg.flip_cos_threshold, want_link=link)
+ if link:
+ err = err.masked_fill(~link_ok, float("inf"))
+ err = err.masked_fill(flips > 0, float("inf"))
+ # × len² to match the QEM cost scale
+ el_sq = (verts[edges[:, 1]] - verts[edges[:, 0]]).pow(2).sum(dim=-1)
+ return err + cfg.skinny_weight * skinny * el_sq
+
+
def _compute_vertex_normals(verts: torch.Tensor, faces: torch.Tensor, weld: bool = True) -> torch.Tensor:
- """Area-weighted smooth vertex normals. `weld` averages face normals across vertices that
- share a position (UV-seam duplicates from unwrapping) so both sides of a seam get one
- identical normal — otherwise a visible shading seam appears in the exported GLB."""
+ """Area-weighted vertex normals; `weld` gives coincident vertices (UV-seam duplicates) one shared normal."""
if faces.numel() == 0:
return torch.zeros_like(verts)
faces_long = faces.to(torch.int64)
@@ -828,7 +533,7 @@ def _compute_vertex_normals(verts: torch.Tensor, faces: torch.Tensor, weld: bool
v0, v1, v2 = verts[i0], verts[i1], verts[i2]
fn = torch.cross(v1 - v0, v2 - v0, dim=-1)
if weld and verts.shape[0]:
- # Group coincident positions (quantized to ~1e-5 of the bbox) into one shared normal.
+ # coincident = same position quantized to 1e-5 of the largest bbox extent
lo = verts.min(0).values
inv_tol = 1.0 / (float((verts.max(0).values - lo).max().clamp_min(1e-9)) * 1e-5)
q = ((verts - lo) * inv_tol).round().to(torch.int64)
@@ -846,47 +551,24 @@ def _compute_vertex_normals(verts: torch.Tensor, faces: torch.Tensor, weld: bool
return torch.nn.functional.normalize(vn, p=2, dim=-1, eps=1e-6)
-# Public API
-
-@dataclass
-class CleanStats:
- in_verts: int = 0
- in_faces: int = 0
- out_verts: int = 0
- out_faces: int = 0
- welded_verts: int = 0 # how many vertex IDs collapsed during welding
- degenerate_faces: int = 0 # zero-area or repeated-index faces removed
- duplicate_faces: int = 0 # same vertex-set removed
- unused_verts: int = 0 # verts not in any face removed
- components_dropped: int = 0 # disconnected components below threshold
-
- def __str__(self):
- return (f"clean: in={self.in_verts}v/{self.in_faces}f -> "
- f"out={self.out_verts}v/{self.out_faces}f "
- f"(welded {self.welded_verts}v, degen {self.degenerate_faces}f, "
- f"dup {self.duplicate_faces}f, unused {self.unused_verts}v, "
- f"comps {self.components_dropped})")
-
-
def _weld_vertices(
verts: torch.Tensor, faces: torch.Tensor, epsilon,
colors: Optional[torch.Tensor] = None,
- normals: Optional[torch.Tensor] = None,
-) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor], int]:
- """Merge vertices closer than epsilon (L_inf grid), cluster-averaging attributes; returns (v, f, colors, normals, n_welded)."""
+) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
+ """Merge vertices that round to the same epsilon grid cell, averaging positions and colors; returns (v, f, colors)."""
if verts.shape[0] == 0:
- return verts, faces, colors, normals, 0
+ return verts, faces, colors
device = verts.device
scale = 1.0 / epsilon
bbox_min = verts.min(dim=0)[0]
q = ((verts - bbox_min) * scale).round().to(torch.int64)
bbox = (verts.max(dim=0)[0] - bbox_min)
extent = (bbox * scale).round().to(torch.int64) + 2
- key = (q[:, 0] * extent[1] + q[:, 1]) * extent[2] + q[:, 2] # pack 3D quantized pos to 1D key
+ key = (q[:, 0] * extent[1] + q[:, 1]) * extent[2] + q[:, 2]
unique_key, inv = torch.unique(key, return_inverse=True)
n_unique = unique_key.shape[0]
if n_unique == verts.shape[0]:
- return verts, faces, colors, normals, 0
+ return verts, faces, colors
counts = torch.zeros(n_unique, dtype=verts.dtype, device=device)
counts.scatter_add_(0, inv, torch.ones(verts.shape[0], dtype=verts.dtype, device=device))
counts_div = counts.unsqueeze(-1).clamp_min(1.0)
@@ -901,23 +583,17 @@ def _weld_vertices(
new_colors.scatter_add_(0, inv.unsqueeze(-1).expand_as(colors), colors)
new_colors = new_colors / counts_div.to(colors.dtype)
- new_normals = None
- if normals is not None:
- new_normals = torch.zeros((n_unique, normals.shape[1]), dtype=normals.dtype, device=device)
- new_normals.scatter_add_(0, inv.unsqueeze(-1).expand_as(normals), normals)
- new_normals = torch.nn.functional.normalize(new_normals, p=2, dim=-1, eps=1e-6)
-
new_faces = inv[faces.long()] if faces.numel() > 0 else faces
- return new_verts, new_faces, new_colors, new_normals, int(verts.shape[0] - n_unique)
+ return new_verts, new_faces, new_colors
def _drop_degenerate_faces(
verts: torch.Tensor, faces: torch.Tensor,
min_area: float = 1e-14,
-) -> Tuple[torch.Tensor, int]:
- """Drop degenerate-by-construction faces (repeated indices or zero-area); slivers go to _collapse_slivers."""
+) -> torch.Tensor:
+ """Drop faces with repeated indices or area below min_area."""
if faces.numel() == 0:
- return faces, 0
+ return faces
idx_bad = (faces[:, 0] == faces[:, 1]) | (faces[:, 1] == faces[:, 2]) | (faces[:, 0] == faces[:, 2])
f_good = faces[~idx_bad]
v0 = verts[f_good[:, 0]]
@@ -926,20 +602,17 @@ def _drop_degenerate_faces(
e0 = v1 - v0
e2 = v0 - v2
area = 0.5 * torch.norm(torch.cross(e0, -e2, dim=-1), dim=-1)
- bad = area < min_area
- kept = f_good[~bad]
- n_dropped = idx_bad.sum() + bad.sum() # tensor-scalar; caller .item()s once
- return kept, n_dropped
+ return f_good[area >= min_area]
def _collapse_slivers(
verts: torch.Tensor, faces: torch.Tensor,
min_angle_deg: float = 0.0,
max_aspect_ratio: float = 0.0,
-) -> Tuple[torch.Tensor, int]:
- """Resolve sliver triangles by collapsing each sliver's shortest edge (no holes); returns (faces, n_collapsed)."""
+) -> torch.Tensor:
+ """Resolve sliver triangles by collapsing each sliver's shortest edge (no holes)."""
if faces.numel() == 0 or (min_angle_deg <= 0 and max_aspect_ratio <= 0):
- return faces, 0
+ return faces
fl = faces.long()
v0 = verts[fl[:, 0]]
@@ -967,245 +640,259 @@ def _collapse_slivers(
bad = bad | (angles_deg.min(dim=-1).values < min_angle_deg)
if not bad.any():
- return faces, 0
-
- # per sliver pick its shortest edge to collapse
- edge_lens = torch.stack([l0, l1, l2], dim=-1) # (F, 3)
- shortest_slot = edge_lens.argmin(dim=-1) # (F,) ∈ {0,1,2}
+ return faces
- V = verts.shape[0]
- # collapse higher-index endpoint into lower (min/max ordering avoids cycles)
- merge_map = torch.arange(V, device=verts.device, dtype=torch.int64)
+ # chained collapses all merge into the lowest vertex
bad_idx = torch.nonzero(bad, as_tuple=True)[0]
- for slot in range(3):
- sel = bad_idx[shortest_slot[bad_idx] == slot]
- if sel.numel() == 0:
- continue
- a = fl[sel, slot]
- b = fl[sel, (slot + 1) % 3]
- lo = torch.minimum(a, b)
- hi = torch.maximum(a, b)
- merge_map[hi] = lo # last-write-wins on conflict
-
- # path-compress until stable
- for _ in range(10):
- new_map = merge_map[merge_map]
- if torch.equal(new_map, merge_map):
- break
- merge_map = new_map
-
- new_faces = merge_map[fl]
+ slot = torch.stack([l0, l1, l2], dim=-1)[bad_idx].argmin(dim=-1)
+ merge = torch.stack([fl[bad_idx, slot], fl[bad_idx, (slot + 1) % 3]], dim=1)
+ new_faces = _connected_labels(merge, verts.shape[0])[fl]
nondeg = ((new_faces[:, 0] != new_faces[:, 1]) &
(new_faces[:, 1] != new_faces[:, 2]) &
(new_faces[:, 0] != new_faces[:, 2]))
- new_faces = new_faces[nondeg].to(dtype=faces.dtype)
- return new_faces, bad.sum()
+ return new_faces[nondeg].to(dtype=faces.dtype)
-def _drop_duplicate_faces(faces: torch.Tensor, num_verts: int) -> Tuple[torch.Tensor, int]:
+def _drop_duplicate_faces(faces: torch.Tensor) -> torch.Tensor:
"""Remove duplicate faces (same vertex set), keeping the first occurrence (winding-preserving)."""
if faces.shape[0] <= 1:
- return faces, 0
- key_sorted = torch.sort(faces, dim=1)[0]
- P = num_verts + 1
- packed = (key_sorted[:, 0].long() * P + key_sorted[:, 1].long()) * P + key_sorted[:, 2].long()
- unique_packed, inv = torch.unique(packed, return_inverse=True)
- if unique_packed.shape[0] == faces.shape[0]:
- return faces, 0
- # first-occurrence index per unique key
- arange = torch.arange(packed.shape[0], device=packed.device)
- first = torch.full((unique_packed.shape[0],), packed.shape[0],
- dtype=torch.int64, device=packed.device)
+ return faces
+ groups, inv = torch.unique(torch.sort(faces, dim=1)[0], dim=0, return_inverse=True)
+ if groups.shape[0] == faces.shape[0]:
+ return faces
+ arange = torch.arange(faces.shape[0], dtype=torch.int32, device=faces.device)
+ first = torch.full((groups.shape[0],), faces.shape[0], dtype=torch.int32, device=faces.device)
first.scatter_reduce_(0, inv, arange, reduce="amin", include_self=True)
- kept = faces[first]
- return kept, int(faces.shape[0] - kept.shape[0])
+ return faces[first]
+
+
+def _folded_faces(faces: torch.Tensor) -> torch.Tensor:
+ """(F,) bool: faces sharing their vertex set with another face.
+ Marks every face of a group with mixed winding (fins) and all but the first of same-wound repeats."""
+ key_sorted, order = torch.sort(faces, dim=1)
+ groups, inv = torch.unique(key_sorted, dim=0, return_inverse=True)
+ n_groups = groups.shape[0]
+ # winding = parity of the sorting permutation
+ odd = ((order[:, 0] > order[:, 1]).long() + (order[:, 0] > order[:, 2]).long()
+ + (order[:, 1] > order[:, 2]).long()) % 2
+ n_odd = torch.zeros(n_groups, dtype=torch.long, device=faces.device).scatter_add_(0, inv, odd)
+ mixed = (n_odd > 0) & (n_odd < torch.bincount(inv, minlength=n_groups))
+ arange = torch.arange(faces.shape[0], dtype=torch.int32, device=faces.device)
+ first = torch.full((n_groups,), faces.shape[0], dtype=torch.int32, device=faces.device)
+ first.scatter_reduce_(0, inv, arange, reduce="amin")
+ return mixed[inv] | (first[inv] != arange)
def _drop_unused_verts(
verts: torch.Tensor, faces: torch.Tensor,
colors: Optional[torch.Tensor] = None,
- normals: Optional[torch.Tensor] = None,
-) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor], int]:
- """Remove vertices not referenced by any face; remap faces and filter attributes."""
+) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
+ """Remove vertices not referenced by any face; remap faces and filter colors."""
if verts.shape[0] == 0 or faces.numel() == 0:
- return verts, faces, colors, normals, 0
+ return verts, faces, colors
used = torch.zeros(verts.shape[0], dtype=torch.bool, device=verts.device)
used[faces[:, 0]] = True
used[faces[:, 1]] = True
used[faces[:, 2]] = True
- # cumsum compact remap: 0..N-1 to used verts in order
remap = used.long().cumsum(0) - 1
new_verts = verts[used]
new_faces = remap[faces.long()]
new_colors = colors[used] if colors is not None else None
- new_normals = normals[used] if normals is not None else None
- n_dropped = verts.shape[0] - used.sum()
- return new_verts, new_faces, new_colors, new_normals, n_dropped
+ return new_verts, new_faces, new_colors
+
+
+def _split_touching_sheets(v, f, max_passes=4):
+ """Split sheets touching along an edge or at a vertex; returns (faces, src), src = original vertex per new vertex.
+ On 3+-face edges, forward faces pair with backward ones by normal agreement; where pairings around a vertex
+ conflict, the least sure pairing of each conflicting group is flipped, up to `max_passes` times.
+ A closed, consistently oriented mesh stays closed."""
+ dev = f.device
+ m = f.shape[0]
+ n = int(f.max()) + 1
+ fv = f.reshape(-1)
+ nxt = lambda c: c - c % 3 + (c + 1) % 3 # the corner after c in its face: c -> nxt(c) is the half-edge
+ fe = f.roll(-1, 1).reshape(-1)
+ key = torch.minimum(fv, fe) * n + torch.maximum(fv, fe)
+ del fe
+ order = torch.argsort(key)
+ ks = key[order]
+ edge_cnt = torch.unique_consecutive(ks, return_counts=True)[1]
+ cnt = torch.repeat_interleave(edge_cnt, edge_cnt)
+ pair = torch.nonzero(ks[1:] == ks[:-1], as_tuple=True)[0]
+ pair = pair[cnt[pair] == 2]
+ h1, h2 = order[pair], order[pair + 1]
+ del pair
+
+ fans = bool((cnt > 2).any())
+ if fans:
+ h = order[cnt > 2]
+ size = edge_cnt[edge_cnt > 2]
+ fan_key = ks[torch.cumsum(edge_cnt, 0) - edge_cnt][edge_cnt > 2]
+ g = torch.repeat_interleave(torch.arange(size.numel(), device=dev), size)
+ d = (fv[h] > fv[nxt(h)]).long()
+ o = torch.argsort((g * 2 + d) * (3 * m) + h)
+ h, g, d = h[o], g[o], d[o]
+ per_dir = torch.bincount(g * 2 + d, minlength=2 * size.numel()).view(-1, 2)
+ g_start = torch.cumsum(size, 0) - size
+ rank = torch.arange(h.numel(), device=dev) - g_start[g] - d * per_dir[g, 0]
+ # dot[g, i, j]: normal agreement of the i-th forward and j-th backward face
+ first2 = rank < 2
+ tri = v[f[h[first2] // 3]]
+ fn = torch.nn.functional.normalize(torch.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0], dim=-1), dim=-1)
+ nrm = torch.zeros((size.numel(), 2, 2, 3), dtype=v.dtype, device=dev)
+ nrm[g[first2], d[first2], rank[first2]] = fn
+ dot = torch.einsum("gic,gjc->gij", nrm[:, 0], nrm[:, 1])
+ nf, nb = per_dir[:, 0], per_dir[:, 1]
+ swap = ((dot[:, 0, 1] + dot[:, 1, 0]) > (dot[:, 0, 0] + dot[:, 1, 1])).long()
+ pick_f = (dot[:, 1, 0] > dot[:, 0, 0]).long()
+ pick_b = (dot[:, 0, 1] > dot[:, 0, 0]).long()
+ # how sure each choice is; larger fans pair by order and gain nothing from a flip
+ margin = torch.full_like(dot[:, 0, 0], float("inf"))
+ margin = torch.where((nf == 2) & (nb == 2), (dot[:, 0, 1] + dot[:, 1, 0] - dot[:, 0, 0] - dot[:, 1, 1]).abs(), margin)
+ margin = torch.where((nf == 2) & (nb == 1), (dot[:, 1, 0] - dot[:, 0, 0]).abs(), margin)
+ margin = torch.where((nf == 1) & (nb == 2), (dot[:, 0, 1] - dot[:, 0, 0]).abs(), margin)
+ hf, gf, rf = h[d == 0], g[d == 0], rank[d == 0]
+ del key, order, ks, edge_cnt, cnt
+
+ def join(flip):
+ a1, a2 = h1, h2
+ if fans:
+ sw, pf, pb = swap ^ flip, pick_f ^ flip, pick_b ^ flip
+ partner = torch.where(rf < nb[gf], rf, -1) # larger fans pair by order
+ partner = torch.where((nf[gf] == 2) & (nb[gf] == 2), rf ^ sw[gf], partner)
+ partner = torch.where((nf[gf] == 2) & (nb[gf] == 1), torch.where(rf == pf[gf], 0, -1), partner)
+ partner = torch.where((nf[gf] == 1) & (nb[gf] == 2), pb[gf], partner)
+ ok = partner >= 0
+ a1 = torch.cat([a1, hf[ok]])
+ a2 = torch.cat([a2, h[g_start[gf[ok]] + nf[gf[ok]] + partner[ok]]])
+ same_dir = fv[a1] == fv[a2]
+ a = torch.cat([a1, nxt(a1)])
+ b = torch.cat([torch.where(same_dir, a2, nxt(a2)), torch.where(same_dir, nxt(a2), a2)])
+ return _connected_labels(torch.stack([a, b], 1), 3 * m)
+
+ flip = 0
+ for _ in range(max_passes):
+ label = join(flip)
+ if not fans:
+ break
+ # fan edges still shared after the split: corners only merge within one vertex, so a label pair can repeat
+ # only among the half-edges of one edge, and the fans' own half-edges suffice
+ lk = torch.minimum(label[h], label[nxt(h)]) * (3 * m) + torch.maximum(label[h], label[nxt(h)])
+ _, inv, c = torch.unique(lk, return_inverse=True, return_counts=True)
+ stuck = torch.zeros(size.numel(), dtype=torch.bool, device=dev)
+ stuck[g[c[inv] > 2]] = True
+ stuck &= torch.isfinite(margin)
+ if not bool(stuck.any()):
+ break
+ # flipping all of them keeps a ring of conflicting fans inconsistent: flip the least sure one per group
+ idx = stuck.nonzero().squeeze(1)
+ va, vb = fan_key[idx] // n, fan_key[idx] % n
+ grp = _connected_labels(torch.stack([va, vb], 1), n)[va]
+ least = torch.full((n,), float("inf"), dtype=margin.dtype, device=dev).scatter_reduce(0, grp, margin[idx], "amin")
+ flip = flip ^ torch.zeros_like(fan_key).index_fill(0, idx[margin[idx] == least[grp]], 1)
+ # labels are the smallest corner of their component, so the roots in order are the new vertices
+ root = label == torch.arange(3 * m, device=dev)
+ return (root.cumsum(0) - 1)[label].view(m, 3), fv[root]
def _repair_nonmanifold_edges(
verts: torch.Tensor, faces: torch.Tensor,
-) -> Tuple[torch.Tensor, torch.Tensor]:
- """repair_non_manifold_edges: explode corners, re-merge only across manifold edges; returns (verts, faces, src)."""
+) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """cumesh's repair_non_manifold_edges: explode corners, re-merge only across manifold edges; returns (verts, faces, src)."""
if faces.numel() == 0:
- return verts, faces
- dev, vdt, fdt = verts.device, verts.dtype, faces.dtype
- F = faces.detach().cpu().numpy().astype(_np.int64)
- V = verts.detach().cpu().numpy()
- nf = F.shape[0]
- nv = V.shape[0]
- corner_vert = F.reshape(-1) # (3F,) original vertex per corner
-
- # per-face edges keyed by (vmin,vmax)
- keys_l, ca_l, cb_l = [], [], []
- for (i, j) in ((0, 1), (1, 2), (2, 0)):
- va, vb = F[:, i], F[:, j]
- ci = 3 * _np.arange(nf) + i
- cj = 3 * _np.arange(nf) + j
- amin = _np.where(va <= vb, ci, cj) # corner of the smaller-id endpoint
- amax = _np.where(va <= vb, cj, ci)
- vmin = _np.minimum(va, vb).astype(_np.int64)
- vmax = _np.maximum(va, vb).astype(_np.int64)
- keys_l.append(vmin * (nv + 1) + vmax)
- ca_l.append(amin)
- cb_l.append(amax)
- keys = _np.concatenate(keys_l)
- ca = _np.concatenate(ca_l)
- cb = _np.concatenate(cb_l)
- order = _np.argsort(keys, kind="stable")
- keys = keys[order]
- ca = ca[order]
- cb = cb[order]
- uniq, start, cnt = _np.unique(keys, return_index=True, return_counts=True)
- man = start[cnt == 2] # manifold edges (exactly 2 incident faces)
- # union both endpoints' corners across each manifold edge
- rows = _np.concatenate([ca[man], cb[man]])
- cols = _np.concatenate([ca[man + 1], cb[man + 1]])
-
- n = 3 * nf
- g = coo_matrix((_np.ones(rows.shape[0], dtype=_np.int8), (rows, cols)), shape=(n, n))
- _ncomp, labels = connected_components(g, directed=False)
-
- new_faces = labels[3 * _np.arange(nf)[:, None] + _np.array([0, 1, 2])[None, :]]
- nnv = int(labels.max()) + 1
- # source original-vertex index per new vertex
- src = _np.zeros(nnv, dtype=_np.int64)
- src[labels] = corner_vert
- new_verts = V[src]
- src_t = torch.from_numpy(src).to(device=dev)
- return (torch.from_numpy(new_verts).to(device=dev, dtype=vdt),
- torch.from_numpy(new_faces.astype(_np.int64)).to(device=dev, dtype=fdt),
- src_t)
+ return verts, faces, torch.arange(verts.shape[0], device=verts.device)
+ nf = faces.shape[0]
+ corner_vert = faces.long().reshape(-1) # (3F,) original vertex per corner
+ corner = torch.arange(3 * nf, device=faces.device).view(nf, 3)
+
+ # half-edges keyed by (vmin, vmax), with the corners at each endpoint
+ va = corner_vert
+ vb = faces.long()[:, [1, 2, 0]].reshape(-1)
+ ca = corner.reshape(-1)
+ cb = corner[:, [1, 2, 0]].reshape(-1)
+ swap = va > vb
+ keys = torch.minimum(va, vb) * (verts.shape[0] + 1) + torch.maximum(va, vb)
+ keys, order = torch.sort(keys)
+ cmin = torch.where(swap, cb, ca)[order]
+ cmax = torch.where(swap, ca, cb)[order]
+ _, cnt = torch.unique_consecutive(keys, return_counts=True)
+ man = (torch.cumsum(cnt, 0) - cnt)[cnt == 2] # manifold edges (exactly 2 incident faces)
+ pairs = torch.cat([torch.stack([cmin[man], cmin[man + 1]], 1), torch.stack([cmax[man], cmax[man + 1]], 1)])
+ roots, labels = torch.unique(_connected_labels(pairs, 3 * nf), return_inverse=True)
+ src = corner_vert[roots]
+ return verts[src], labels.view(nf, 3).to(faces.dtype), src
+
+
+def _kitchen_op(name: str, tensor: torch.Tensor):
+ """comfy-kitchen's op `name` when its CUDA backend can run it on `tensor`, else None."""
+ ck = getattr(comfy.quant_ops, "ck", None)
+ if ck is None or not hasattr(ck, name) or not tensor.is_cuda:
+ return None
+ cuda = ck.list_backends().get("cuda", {})
+ if not (cuda.get("available", False) and not cuda.get("disabled", True) and name in cuda.get("capabilities", ())):
+ return None
+ floor = ck.registry.get_constraints("cuda", name).min_compute_capability
+ if floor is not None and torch.cuda.get_device_capability(tensor.device) < floor:
+ return None
+ return getattr(ck, name)
+
+
+def _connected_labels(edges: torch.Tensor, n: int) -> torch.Tensor:
+ """Smallest node index of each node's connected component, for nodes 0..n-1 and edges (E, 2)."""
+ connected_components = _kitchen_op("connected_components", edges)
+ if connected_components is not None:
+ return connected_components(edges, n)
+ # min-label propagation with pointer jumping; stopping before convergence splits long components
+ label = torch.arange(n, dtype=torch.int32, device=edges.device)
+ a, b = edges[:, 0], edges[:, 1]
+ while True:
+ low = torch.minimum(label[a], label[b])
+ new = label.clone()
+ new.scatter_reduce_(0, a, low, "amin")
+ new.scatter_reduce_(0, b, low, "amin")
+ new = new[new]
+ if torch.equal(new, label):
+ return label.long()
+ label = new
def _drop_small_components(
verts: torch.Tensor, faces: torch.Tensor, min_faces: int,
- max_propagation_iters: int = 200,
-) -> Tuple[torch.Tensor, torch.Tensor, int]:
- """Label-propagation connected components; drop components below min_faces."""
+) -> torch.Tensor:
+ """Faces of the connected components with at least min_faces faces."""
if faces.numel() == 0 or min_faces <= 1:
- return verts, faces, 0
- device = verts.device
- V = verts.shape[0]
- labels = torch.arange(V, device=device, dtype=torch.int64)
- for _ in range(max_propagation_iters):
- v0, v1, v2 = faces[:, 0], faces[:, 1], faces[:, 2]
- face_min = torch.minimum(torch.minimum(labels[v0], labels[v1]), labels[v2])
- new_labels = labels.clone()
- new_labels.scatter_reduce_(0, v0, face_min, reduce="amin", include_self=True)
- new_labels.scatter_reduce_(0, v1, face_min, reduce="amin", include_self=True)
- new_labels.scatter_reduce_(0, v2, face_min, reduce="amin", include_self=True)
- new_labels = new_labels[new_labels] # path-compress
- if torch.equal(new_labels, labels):
- break
- labels = new_labels
+ return faces
+ labels = _connected_labels(torch.cat([faces[:, :2], faces[:, 1:]]), verts.shape[0])
face_label = labels[faces[:, 0]]
unique_labels, counts = torch.unique(face_label, return_counts=True)
big_labels = unique_labels[counts >= min_faces]
- if big_labels.shape[0] == unique_labels.shape[0]:
- return verts, faces, 0
- # safety: never drop every component (return the small mesh, not an empty one)
- if big_labels.shape[0] == 0:
- return verts, faces, 0
- keep_face = torch.isin(face_label, big_labels)
- kept_faces = faces[keep_face]
- n_dropped = int(unique_labels.shape[0] - big_labels.shape[0])
- return verts, kept_faces, n_dropped
+ # never drop every component
+ if big_labels.shape[0] in (0, unique_labels.shape[0]):
+ return faces
+ return faces[torch.isin(face_label, big_labels)]
def clean_mesh(
verts: torch.Tensor, faces: torch.Tensor,
colors: Optional[torch.Tensor] = None,
- normals: Optional[torch.Tensor] = None,
- weld_epsilon: float = 0.0,
- weld_epsilon_rel: float = 1e-6,
- drop_degenerate: bool = True,
+ weld_epsilon_rel: float = 0.0,
drop_duplicates: bool = True,
- drop_unused: bool = True,
min_component_faces: int = 0,
min_angle_deg: float = 0.0,
max_aspect_ratio: float = 0.0,
-) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor], CleanStats]:
- """Mesh hygiene pipeline; preserves per-vertex attributes through welding. Returns (v, f, colors, normals, stats)."""
- stats = CleanStats(in_verts=verts.shape[0], in_faces=faces.shape[0])
- v = verts
+) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
+ """Weld, drop degenerate faces, collapse slivers, drop duplicates, small components and unused verts.
+ Returns (v, f, colors)."""
f = faces.long() if faces.numel() > 0 else faces
- c = colors
- n = normals
-
- if weld_epsilon != 0.0 or weld_epsilon_rel > 0:
- # eps stays a 0-d tensor (no sync)
- if weld_epsilon > 0:
- eps = torch.as_tensor(weld_epsilon, dtype=v.dtype, device=v.device)
- else:
- eps = torch.norm(v.max(dim=0)[0] - v.min(dim=0)[0]) * weld_epsilon_rel
- v, f, c, n, n_welded = _weld_vertices(v, f, eps, c, n)
- stats.welded_verts = n_welded
-
- if drop_degenerate:
- f_new, n_drop = _drop_degenerate_faces(v, f)
- stats.degenerate_faces = n_drop
- f = f_new
- # slivers get collapse-merged instead of dropped (preserves topology)
- if min_angle_deg > 0 or max_aspect_ratio > 0:
- f_new, n_sliv = _collapse_slivers(
- v, f, min_angle_deg=min_angle_deg, max_aspect_ratio=max_aspect_ratio,
- )
- stats.degenerate_faces += n_sliv
- f = f_new
-
+ if weld_epsilon_rel > 0:
+ eps = torch.norm(verts.max(dim=0)[0] - verts.min(dim=0)[0]) * weld_epsilon_rel # 0-d, no sync
+ verts, f, colors = _weld_vertices(verts, f, eps, colors)
+ f = _drop_degenerate_faces(verts, f)
+ f = _collapse_slivers(verts, f, min_angle_deg=min_angle_deg, max_aspect_ratio=max_aspect_ratio)
if drop_duplicates:
- f_new, n_dup = _drop_duplicate_faces(f, v.shape[0])
- stats.duplicate_faces = n_dup
- f = f_new
-
- if min_component_faces > 1:
- v, f, n_comp = _drop_small_components(v, f, min_component_faces)
- stats.components_dropped = n_comp
-
- if drop_unused:
- v, f, c, n, n_unused = _drop_unused_verts(v, f, c, n)
- stats.unused_verts = n_unused
-
- stats.out_verts = v.shape[0]
- stats.out_faces = f.shape[0]
- # materialize tensor-scalar counts to plain ints once at exit
- for field in ("welded_verts", "degenerate_faces", "duplicate_faces",
- "unused_verts", "components_dropped"):
- val = getattr(stats, field)
- if torch.is_tensor(val):
- setattr(stats, field, int(val.item()))
- return v, f, c, n, stats
-
-
-@dataclass
-class SimplifyStats:
- input_verts: int = 0
- input_faces: int = 0
- output_verts: int = 0
- output_faces: int = 0
- iterations: int = 0
- total_collapses: int = 0
+ f = _drop_duplicate_faces(f)
+ f = _drop_small_components(verts, f, min_component_faces)
+ return _drop_unused_verts(verts, f, colors)
def qem_simplify(
@@ -1213,80 +900,54 @@ def qem_simplify(
faces: torch.Tensor,
target_faces: int,
colors: Optional[torch.Tensor] = None,
- normals: Optional[torch.Tensor] = None,
- max_edge_length: Optional[float] = None,
config: Optional[QEMConfig] = None,
-) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor], SimplifyStats]:
- """Single-mesh QEM simplification. Returns (v, f, colors, normals, stats)."""
+) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
+ """QEM-simplify a mesh to about target_faces faces; returns (v, f, colors)."""
cfg = config or QEMConfig()
device = vertices.device
in_v_dtype = vertices.dtype
in_f_dtype = faces.dtype
in_c_dtype = colors.dtype if colors is not None else None
- in_n_dtype = normals.dtype if normals is not None else None
-
- verts = vertices.to(device=device, dtype=cfg.dtype, copy=True)
- faces = faces.to(device=device, dtype=torch.int64).clone()
- colors_w = colors.to(device=device, dtype=cfg.dtype, copy=True) if colors is not None else None
- normals_w = normals.to(device=device, dtype=cfg.dtype, copy=True) if normals is not None else None
-
- # preclean: weld + drop degenerate/duplicate, attributes cluster-averaged
- if cfg.preclean:
- verts, faces, colors_w, normals_w, _cs = clean_mesh(
- verts, faces, colors_w, normals_w,
- weld_epsilon_rel=cfg.preclean_weld_epsilon_rel,
- min_component_faces=cfg.preclean_min_component_faces,
- )
+
+ # preclean on copies, since collapses edit verts and colors in place
+ verts, faces, colors_w = clean_mesh(
+ vertices.to(dtype=torch.float32, copy=True), faces.to(dtype=torch.int64),
+ colors.to(dtype=torch.float32, copy=True) if colors is not None else None,
+ weld_epsilon_rel=cfg.preclean_weld_epsilon_rel,
+ )
num_verts = verts.shape[0]
num_faces = faces.shape[0]
- stats = SimplifyStats(input_verts=num_verts, input_faces=num_faces)
-
if num_faces <= target_faces or num_verts < 4:
- stats.output_verts = num_verts
- stats.output_faces = num_faces
return verts.to(in_v_dtype), faces.to(in_f_dtype), \
- (colors_w.to(in_c_dtype) if colors_w is not None else None), \
- (normals_w.to(in_n_dtype) if normals_w is not None else None), \
- stats
+ (colors_w.to(in_c_dtype) if colors_w is not None else None)
v_alive = torch.ones(num_verts, dtype=torch.bool, device=device)
f_alive = torch.ones(num_faces, dtype=torch.bool, device=device)
- Q = _build_quadrics(verts, faces, cfg)
-
bbox = verts.max(dim=0)[0] - verts.min(dim=0)[0]
mesh_scale = torch.norm(bbox) # 0-d tensor; never .item()'d
- if max_edge_length is None or max_edge_length <= 0:
- max_edge_length = mesh_scale * 2.0
- else:
- max_edge_length = torch.as_tensor(max_edge_length, dtype=cfg.dtype, device=device)
- # tiny-bbox guard (tensor-side, no sync)
- max_edge_length = torch.where(
- max_edge_length < 1e-6,
- torch.ones((), dtype=max_edge_length.dtype, device=device),
- max_edge_length,
- )
-
- stabilizer = mesh_scale * mesh_scale * cfg.stabilizer_scale
- max_edge_length_sq = max_edge_length * max_edge_length
mesh_scale_sq = mesh_scale * mesh_scale
+ stabilizer = mesh_scale_sq * cfg.stabilizer_scale
+ # reject costs >= (2 × bbox diagonal)², or >= 1 on a tiny bbox
+ max_err = torch.where(mesh_scale < 5e-7, torch.ones_like(mesh_scale), 4.0 * mesh_scale_sq)
+ Q = None
- # threshold scaled by mesh_scale² so the 1e-8 start is scale-robust
thresh = float(cfg.threshold_start) * float(mesh_scale_sq) if cfg.threshold_driver else 0.0
- # pre-allocated merge_map, reused each iter
merge_map = torch.arange(num_verts, device=device)
+ gen = torch.Generator(device=device).manual_seed(0) # the edge sample must not depend on the global RNG state
+
+ # dropped once only the link condition keeps the threshold driver from the target
+ link = cfg.enforce_link_condition
- # py_n_faces: Python-int face count (no host sync in hot loop), re-synced at compaction
+ # Python-int face estimate to avoid host syncs in the loop, re-synced at compaction
py_n_faces = num_faces
iteration = 0
- total_collapses = 0
- # progress bars (tqdm + comfy ProgressBar)
_start_faces = num_faces
_prog_total = max(1, _start_faces - int(target_faces))
_qtq = _tqdm(total=100, desc="QEM simplify", leave=False)
@@ -1303,47 +964,36 @@ def qem_simplify(
break
_qreport()
- alive_f = torch.nonzero(f_alive, as_tuple=True)[0]
- if alive_f.numel() == 0:
+ if faces.shape[0] == 0:
break
- active_faces = faces[alive_f]
-
- # memoryless QEM: rebuild Q from current geometry each iter
- if cfg.threshold_driver and cfg.memoryless_qem and iteration > 0:
- Q = _build_quadrics(verts, active_faces, cfg)
-
- Q_for_iter = Q
- # edge extraction: pack (min*V + max) so unique dedups in one pass
- af_roll = torch.roll(active_faces, shifts=-1, dims=1)
- mn = torch.minimum(active_faces, af_roll)
- mx = torch.maximum(active_faces, af_roll)
- packed = torch.add(mx, mn, alpha=num_verts).flatten()
- packed = torch.unique(packed)
+ # unique edges; those used by one face are boundary
+ packed = torch.cat([torch.add(torch.maximum(faces[:, i], faces[:, j]), torch.minimum(faces[:, i], faces[:, j]), alpha=num_verts)
+ for i, j in ((0, 1), (1, 2), (2, 0))])
+ packed, counts = torch.unique(packed, return_counts=True)
edges_orig = torch.stack([packed // num_verts, packed % num_verts], dim=1)
+ b_edges = edges_orig[counts == 1]
+ del packed, counts
- # filter by edge length
- pab = verts[edges_orig] # (E, 2, 3)
- el = torch.norm(pab[:, 1] - pab[:, 0], dim=-1)
- edges_orig = edges_orig[el < max_edge_length]
- if edges_orig.shape[0] == 0:
- break
+ # threshold driver rebuilds quadrics from the current geometry each round; qem driver accumulates them
+ if Q is None:
+ Q = _build_quadrics(verts, faces, cfg, b_edges)
- # sampling cap
- n_edges_total = edges_orig.shape[0]
- if n_edges_total > cfg.sampling_cap:
- perm = torch.randperm(n_edges_total, device=device)[: cfg.sampling_cap]
- edges_orig = edges_orig[perm]
+ if edges_orig.shape[0] > cfg.sampling_cap:
+ # a Bernoulli sample: randperm would sort every edge
+ edges_orig = edges_orig[torch.rand(edges_orig.shape[0], device=device, generator=gen) < cfg.sampling_cap / edges_orig.shape[0]]
- # boundary mask only needed for non-qem placement
if cfg.placement_mode != "qem":
- vib = _vert_is_boundary_mask(active_faces, num_verts)
+ vib = torch.zeros(num_verts, dtype=torch.bool, device=device)
+ vib[b_edges.flatten()] = True
else:
vib = None
- optimal, err, valid = _edge_errors(
- verts, Q_for_iter, edges_orig, stabilizer, max_edge_length_sq,
- mesh_scale_sq, cfg, vert_is_boundary=vib,
- )
+ parts = [_edge_errors(verts, Q, edges_orig[s:s + _EDGE_CHUNK], stabilizer, max_err, mesh_scale_sq, cfg, vert_is_boundary=vib)
+ for s in range(0, edges_orig.shape[0], _EDGE_CHUNK)]
+ optimal, err, valid = (torch.cat(p) for p in zip(*parts))
+ del parts
+ if cfg.threshold_driver:
+ Q = None # rebuilt next round; the collapse and the next edge extraction run without it
valid_idx = torch.nonzero(valid, as_tuple=True)[0]
edges_orig = edges_orig[valid_idx]
optimal = optimal[valid_idx]
@@ -1351,40 +1001,24 @@ def qem_simplify(
faces_to_remove = py_n_faces - target_faces
n_faces_round_start = py_n_faces
- # ~2 faces removed per collapse, so cap the round at faces_to_remove//2
+ # ~2 faces removed per collapse
cap_to_target = max(1, faces_to_remove // 2)
if cfg.threshold_driver:
- # band = cost <= thresh (×10 until non-empty), quality-check, then collapse a disjoint set
cand = err <= thresh
esc = 0
while not bool(cand.any()) and esc < 50:
thresh *= 10.0
cand = err <= thresh
esc += 1
+ full_band = bool(cand.all())
cand_idx = torch.nonzero(cand, as_tuple=True)[0]
ce = edges_orig[cand_idx]
copt = optimal[cand_idx]
cerr = err[cand_idx].clone()
- need_flip = cfg.flip_reject_hard
- if ((need_flip or cfg.skinny_weight > 0 or cfg.enforce_link_condition)
- and ce.shape[0] > 0):
- afq = faces[alive_f]
- v_to_f = _build_vert_to_faces_pad(afq, num_verts, cfg.flip_check_max_degree)
- # link + flip + skinny share one fused 1-ring pass
- fc, sk, link_safe = _quality_checks_fused(
- verts, afq, ce, copt, v_to_f, cos_threshold=cfg.flip_cos_threshold,
- want_flip=need_flip, want_skinny=(cfg.skinny_weight > 0),
- want_link=cfg.enforce_link_condition)
- if link_safe is not None:
- cerr[~link_safe] = float("inf")
- if fc is not None:
- cerr = torch.where(fc > 0, torch.full_like(cerr, float("inf")), cerr)
- if sk is not None:
- el_sq = (verts[ce[:, 1]] - verts[ce[:, 0]]).pow(2).sum(dim=-1)
- cerr = cerr + cfg.skinny_weight * sk * el_sq
- del v_to_f, afq
- # penalties may push edges above thresh — re-gate the band
+ if ce.shape[0] > 0:
+ cerr = _gated_errors(verts, faces, ce, copt, cerr, cfg, link)
+ # penalties can push edges out of the band
keep = cerr <= thresh
ce = ce[keep]
copt = copt[keep]
@@ -1392,8 +1026,11 @@ def qem_simplify(
edges_orig = ce
optimal = copt
sel = _greedy_matching(ce, cerr, v_alive, cap_to_target)
+ if link and full_band and 2 * sel.numel() < min(0.01 * py_n_faces, 2 * cap_to_target):
+ # whole band gated yet < 1% removed: the link condition protects topology the target
+ # can't afford (e.g. tiny handles of a damaged mesh)
+ link = False
if sel.numel() == 0:
- # band fully rejected → raise thresh and retry
thresh *= 10.0
iteration += 1
if iteration >= cfg.max_iterations:
@@ -1404,61 +1041,17 @@ def qem_simplify(
cfg.max_collapses_ceiling,
max(cfg.max_collapses_floor, int(faces_to_remove * cfg.max_collapses_fraction)),
)
- if cfg.max_collapses_relative_cap > 0:
- # cap to a fraction of current mesh size (anti cascade-overshoot)
- rel_cap = max(1, int(py_n_faces * cfg.max_collapses_relative_cap))
- max_collapses = min(max_collapses, rel_cap)
- max_collapses = min(max_collapses, cap_to_target)
-
- # soft quality penalties on top-K: flip + skinny, sharing one v_to_f build
- need_flip = cfg.flip_reject_hard
- need_quality = ((need_flip or cfg.skinny_weight > 0 or cfg.enforce_link_condition)
- and edges_orig.shape[0] > 0)
- if need_quality:
- n_check = min(edges_orig.shape[0],
- max(1, cfg.quality_topk_multiplier * max_collapses))
- if n_check < edges_orig.shape[0]:
- topk = torch.topk(err, n_check, largest=False).indices
- else:
- topk = torch.arange(edges_orig.shape[0], device=device)
- active_for_quality = faces[alive_f]
- v_to_f = _build_vert_to_faces_pad(active_for_quality, num_verts,
- cfg.flip_check_max_degree)
- err = err.clone()
- if cfg.enforce_link_condition:
- # reject link-condition violations on ALL candidate edges, not just top-K
- link_safe = _link_condition_mask(active_for_quality, edges_orig, v_to_f)
- err[~link_safe] = float("inf")
- e_tk = edges_orig[topk]
- o_tk = optimal[topk]
- _do_flip = need_flip
- _do_skinny = cfg.skinny_weight > 0
- if _do_flip and _do_skinny:
- flip_count, skinny, _ = _quality_checks_fused(
- verts, active_for_quality, e_tk, o_tk, v_to_f,
- cos_threshold=cfg.flip_cos_threshold, want_link=False)
- elif _do_flip:
- flip_count = _normal_flip_mask(
- verts, active_for_quality, e_tk, o_tk, v_to_f,
- cos_threshold=cfg.flip_cos_threshold, return_count=True)
- skinny = None
- else:
- skinny = _skinny_penalty(verts, active_for_quality, e_tk, o_tk, v_to_f)
- flip_count = None
- if _do_flip:
- # hard reject: any flipping top-K edge → +inf
- flips = flip_count > 0
- if flips.any():
- err[topk] = torch.where(
- flips, torch.full_like(err[topk], float("inf")),
- err[topk],
- )
- if _do_skinny:
- # skinny_cost * len² (match QEM's length² scaling)
- elen_sq = (verts[e_tk[:, 1]] - verts[e_tk[:, 0]]).pow(2).sum(dim=-1)
- err[topk] = torch.add(err[topk], skinny * elen_sq,
- alpha=cfg.skinny_weight)
- del v_to_f, active_for_quality
+ # relative cap avoids overshooting the target in one round
+ rel_cap = max(1, int(py_n_faces * cfg.max_collapses_relative_cap))
+ max_collapses = min(max_collapses, rel_cap, cap_to_target)
+
+ if edges_orig.shape[0] > 0:
+ err = _gated_errors(verts, faces, edges_orig, optimal, err, cfg, link)
+ # +inf edges must not win the matching where all their neighbours are rejected too
+ keep = torch.isfinite(err)
+ edges_orig = edges_orig[keep]
+ optimal = optimal[keep]
+ err = err[keep]
sel = _greedy_matching(edges_orig, err, v_alive, max_collapses)
@@ -1469,51 +1062,49 @@ def qem_simplify(
v_a = ed_sel[:, 0]
v_b = ed_sel[:, 1]
new_pos = optimal[sel]
+ # the round's arrays would otherwise stay alive while the collapse and the next round allocate
+ del b_edges, edges_orig, optimal, err, valid, sel, ed_sel
- # interpolate attributes by new_pos's position along [pa, pb]
- if colors_w is not None or normals_w is not None:
+ if colors_w is not None:
pa_sel = verts[v_a]
pb_sel = verts[v_b]
edge_vec = pb_sel - pa_sel
edge_len_sq = (edge_vec * edge_vec).sum(dim=-1) + 1e-20
t = ((new_pos - pa_sel) * edge_vec).sum(dim=-1) / edge_len_sq
- t = t.clamp(0.0, 1.0).unsqueeze(-1)
- if colors_w is not None:
- colors_w[v_a] = torch.lerp(colors_w[v_a], colors_w[v_b], t)
- if normals_w is not None:
- normals_w[v_a] = torch.lerp(normals_w[v_a], normals_w[v_b], t)
+ colors_w[v_a] = torch.lerp(colors_w[v_a], colors_w[v_b], t.clamp(0.0, 1.0).unsqueeze(-1))
- # apply collapse
verts[v_a] = new_pos
v_alive[v_b] = False
- if not (cfg.threshold_driver and cfg.memoryless_qem):
+ if not cfg.threshold_driver:
Q[v_a] += Q[v_b]
merge_map[v_b] = v_a
- faces = merge_map[faces]
- merge_map[v_b] = v_b # restore identity for next iter
+ for s in range(0, faces.shape[0], _FACE_CHUNK): # in place, a chunk at a time
+ faces[s:s + _FACE_CHUNK] = merge_map[faces[s:s + _FACE_CHUNK]]
+ merge_map[v_b] = v_b # back to identity
bad = (faces[:, 0] == faces[:, 1]) | (faces[:, 1] == faces[:, 2]) | (faces[:, 2] == faces[:, 0])
f_alive.masked_fill_(bad, False)
- py_n_faces -= 2 * v_a.numel() # ~2 faces/collapse estimate; re-synced at compaction
+ py_n_faces -= 2 * v_a.numel()
+ del v_a, v_b, new_pos, bad
+ if cfg.enforce_link_condition and not link:
+ # collapses through handles fold faces onto each other; drop the folds so counts see the real surface
+ alive_idx = torch.nonzero(f_alive, as_tuple=True)[0]
+ f_alive[alive_idx[_folded_faces(faces[alive_idx])]] = False
+ py_n_faces = int(f_alive.sum())
- # schedule: round removed < 1% → raise thresh ×10
if cfg.threshold_driver:
removed = n_faces_round_start - py_n_faces
if removed < 0.01 * n_faces_round_start:
thresh *= 10.0
- total_collapses += int(v_a.numel())
iteration += 1
- # periodic compaction (resyncs py_n_faces exactly)
- if iteration % cfg.compaction_period == 0:
- alive_frac = py_n_faces / max(1, num_faces)
- if alive_frac < cfg.compaction_threshold:
- faces = faces[f_alive]
- num_faces = faces.shape[0]
- f_alive = torch.ones(num_faces, dtype=torch.bool, device=device)
- py_n_faces = num_faces
+ # drop the dead faces now rather than carry them: the next round would copy the alive ones anyway
+ faces = faces[f_alive]
+ num_faces = faces.shape[0]
+ f_alive = torch.ones(num_faces, dtype=torch.bool, device=device)
+ py_n_faces = num_faces
if iteration >= cfg.max_iterations:
break
@@ -1521,116 +1112,31 @@ def qem_simplify(
_qreport()
_qtq.close()
- # finalize: compact verts and faces
+ # alive faces are non-degenerate and only use alive verts
final_v = verts[v_alive]
final_c = colors_w[v_alive] if colors_w is not None else None
- final_n = normals_w[v_alive] if normals_w is not None else None
-
- remap = torch.full((num_verts,), -1, dtype=torch.int64, device=device)
- remap[v_alive] = v_alive.long().cumsum(0)[v_alive] - 1 # compact remap, no sync
-
- final_f_raw = faces[f_alive]
- alive_mask = v_alive[final_f_raw].all(dim=1)
- final_f_raw = final_f_raw[alive_mask]
- final_f = remap[final_f_raw]
- valid_faces = (final_f >= 0).all(dim=1)
- final_f = final_f[valid_faces]
-
- # drop degenerate faces (two indices equal)
- if final_f.numel() > 0:
- nondeg = (final_f[:, 0] != final_f[:, 1]) & (final_f[:, 1] != final_f[:, 2]) & (final_f[:, 0] != final_f[:, 2])
- final_f = final_f[nondeg]
-
- # dedup duplicate faces, winding-preserving
- if final_f.numel() > 0:
- key = torch.sort(final_f, dim=1)[0]
- packed = (key[:, 0].long() * (final_v.shape[0] + 1) + key[:, 1].long()) \
- * (final_v.shape[0] + 1) + key[:, 2].long()
- unique_packed, inv = torch.unique(packed, return_inverse=True)
- arange = torch.arange(packed.shape[0], device=packed.device)
- first = torch.full((unique_packed.shape[0],), packed.shape[0],
- dtype=torch.int64, device=packed.device)
- first.scatter_reduce_(0, inv, arange, reduce="amin", include_self=True)
- final_f = final_f[first]
-
- # split back fused surface sheets (after dedup, before pruning)
+ remap = v_alive.long().cumsum(0) - 1
+ final_f = _drop_duplicate_faces(remap[faces[f_alive]])
+
+ # split fused sheets after dedup and before postclean pruning
if cfg.repair_nonmanifold and final_f.numel() > 0:
- final_v, final_f, _src = _repair_nonmanifold_edges(final_v, final_f)
+ final_f, _src = _split_touching_sheets(final_v, final_f)
+ final_v, final_f, _src2 = _repair_nonmanifold_edges(final_v[_src], final_f)
if final_c is not None:
- final_c = final_c[_src]
- if final_n is not None:
- final_n = final_n[_src]
+ final_c = final_c[_src[_src2]]
- # post-clean: drop slivers, tiny components, unused verts
+ # postclean; already welded and deduplicated
if cfg.postclean and final_f.numel() > 0:
- comp_threshold = cfg.postclean_min_component_faces
- final_v, final_f, final_c, final_n, _ps = clean_mesh(
- final_v, final_f, final_c, final_n,
- weld_epsilon=0.0, weld_epsilon_rel=0.0, # already welded
- drop_degenerate=True,
- drop_duplicates=False, # already done above
- drop_unused=True,
- min_component_faces=comp_threshold,
+ final_v, final_f, final_c = clean_mesh(
+ final_v, final_f, final_c,
+ drop_duplicates=False,
+ min_component_faces=cfg.postclean_min_component_faces,
min_angle_deg=cfg.postclean_min_angle_deg,
max_aspect_ratio=cfg.postclean_max_aspect_ratio,
)
- # post-simplify normals
- if cfg.recompute_normals_post and final_f.numel() > 0:
- final_n = _compute_vertex_normals(final_v, final_f)
- elif final_n is not None and final_f.numel() > 0:
- # keep supplied normals; flip face winding where it disagrees
- v0 = final_v[final_f[:, 0]]
- v1 = final_v[final_f[:, 1]]
- v2 = final_v[final_f[:, 2]]
- fn = torch.cross(v1 - v0, v2 - v0, dim=-1)
- ref = (final_n[final_f[:, 0]] + final_n[final_f[:, 1]]
- + final_n[final_f[:, 2]]) / 3.0
- wrong = (fn * ref).sum(dim=-1) < 0
- final_f[wrong] = final_f[wrong][:, [0, 2, 1]]
-
- stats.iterations = iteration
- stats.total_collapses = total_collapses
- stats.output_verts = final_v.shape[0]
- stats.output_faces = final_f.shape[0]
-
- return (
- final_v.to(in_v_dtype),
- final_f.to(in_f_dtype),
- final_c.to(in_c_dtype) if final_c is not None else None,
- final_n.to(in_n_dtype) if (final_n is not None and in_n_dtype is not None) else final_n,
- stats,
- )
-
-
-def qem_decimate_simplify(
- vertices: torch.Tensor,
- faces: torch.Tensor,
- target: int,
- colors: Optional[torch.Tensor] = None,
- normals: Optional[torch.Tensor] = None,
- max_edge_length: Optional[float] = None,
- config: Optional[QEMConfig] = None,
-):
- """Batched wrapper. Accepts (V,3)/(F,3) or (B,V,3)/(B,F,3)."""
- if vertices.ndim == 3:
- out_v, out_f, out_c, out_n, out_s = [], [], [], [], []
- for i in range(vertices.shape[0]):
- c_in = colors[i] if colors is not None else None
- n_in = normals[i] if normals is not None else None
- v, f, c, n, s = qem_simplify(vertices[i], faces[i], target, c_in, n_in, max_edge_length, config)
- out_v.append(v)
- out_f.append(f)
- out_s.append(s)
- if c is not None:
- out_c.append(c)
- if n is not None:
- out_n.append(n)
- return (out_v, out_f,
- out_c if out_c else None,
- out_n if out_n else None,
- out_s)
- return qem_simplify(vertices, faces, target, colors, normals, max_edge_length, config)
+ return (final_v.to(in_v_dtype), final_f.to(in_f_dtype),
+ final_c.to(in_c_dtype) if final_c is not None else None)
def qem_cluster_decimate(
@@ -1639,8 +1145,8 @@ def qem_cluster_decimate(
colors: Optional[torch.Tensor] = None,
face_chunk: int = 4_000_000,
) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
- """Vertex-cluster decimation (Rossignac-Borrel): grid-bin/average verts, remap faces,
- drop degenerate/duplicate. Fast O(V+F) prepass for huge meshes. Returns (verts, faces, colors)."""
+ """Rossignac-Borrel vertex clustering to about target_verts, an O(V+F) prepass for huge meshes.
+ Returns (verts, faces, colors)."""
if vertices.shape[0] == 0 or faces.shape[0] == 0:
return vertices, faces, colors
@@ -1676,7 +1182,7 @@ def qem_cluster_decimate(
new_colors.scatter_add_(0, inv.unsqueeze(-1).expand_as(colors), colors)
new_colors = new_colors / counts_div.to(colors.dtype)
- # remap faces in chunks (face tensor can be huge), drop degenerates per chunk
+ # chunked to bound peak memory on huge face tensors
out_chunks = []
F = faces.shape[0]
for fs in range(0, F, face_chunk):
@@ -1690,16 +1196,4 @@ def qem_cluster_decimate(
else:
new_faces = torch.empty((0, 3), dtype=faces.dtype, device=device)
- # drop duplicate faces (same vertex set after clustering)
- if new_faces.numel() > 0:
- key_sorted = torch.sort(new_faces, dim=1)[0]
- P = n_unique + 1
- packed = (key_sorted[:, 0].long() * P + key_sorted[:, 1].long()) * P + key_sorted[:, 2].long()
- _, first = torch.unique(packed, return_inverse=True)
- arange = torch.arange(packed.shape[0], device=device, dtype=torch.int64)
- first_idx = torch.full((int(first.max().item()) + 1,), packed.shape[0],
- dtype=torch.int64, device=device)
- first_idx.scatter_reduce_(0, first, arange, reduce="amin", include_self=True)
- new_faces = new_faces[first_idx]
-
- return new_verts.to(vertices.dtype), new_faces.to(faces.dtype), new_colors
+ return new_verts, _drop_duplicate_faces(new_faces).to(faces.dtype), new_colors
diff --git a/comfy_extras/mesh3d/postprocess/remesh.py b/comfy_extras/mesh3d/postprocess/remesh.py
index 5e2a07778..364977e5e 100644
--- a/comfy_extras/mesh3d/postprocess/remesh.py
+++ b/comfy_extras/mesh3d/postprocess/remesh.py
@@ -1,11 +1,4 @@
-"""Narrow-band Dual Contouring remeshing.
-
-Re-extracts a mesh from a sparse narrow-band voxel grid around the input
-surface (pure-PyTorch approximation of CuMesh's remesh_narrow_band_dc).
-Coarse-to-fine voxelise the band, sample SDF/UDF at voxel corners, dual
-contour (optionally QEF / Manifold DC), then optionally project back,
-filter components, fix poles, smooth, and interpolate vertex colors.
-"""
+"""Narrow-band dual contouring remesher, a PyTorch approximation of CuMesh's remesh_narrow_band_dc."""
from __future__ import annotations
import functools
@@ -15,17 +8,16 @@ from typing import Optional, Tuple
import numpy as np
import torch
import scipy.spatial
+import comfy.quant_ops
import comfy.utils
from tqdm import tqdm as _tqdm
from comfy.model_management import throw_exception_if_processing_interrupted
-from .qem_decimate import _sorted_edge_halfedges
+from .qem_decimate import _connected_labels, _kitchen_op, _sorted_edge_halfedges, _split_touching_sheets
-# Point-to-triangle distance (exact, vectorised)
-
def _point_tri_closest(points: torch.Tensor, tris: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
- """Exact closest point + squared distance per (point, triangle) pair; points (N,3), tris (N,3,3)."""
+ """Closest point and squared distance per (point, triangle) pair (Ericson's region test); points (N, 3), tris (N, 3, 3)."""
a = tris[:, 0]
b = tris[:, 1]
c = tris[:, 2]
@@ -48,32 +40,28 @@ def _point_tri_closest(points: torch.Tensor, tris: torch.Tensor) -> Tuple[torch.
d6 = (ac * cp).sum(-1)
region_C = (d6 >= 0) & (d5 <= d6)
- # Edge AB
vc = d1 * d4 - d3 * d2
region_AB = (vc <= 0) & (d1 >= 0) & (d3 <= 0)
v_ab = d1 / (d1 - d3 + 1e-20)
closest_AB = a + v_ab.unsqueeze(-1) * ab
- # Edge AC
vb = d5 * d2 - d1 * d6
region_AC = (vb <= 0) & (d2 >= 0) & (d6 <= 0)
v_ac = d2 / (d2 - d6 + 1e-20)
closest_AC = a + v_ac.unsqueeze(-1) * ac
- # Edge BC
va = d3 * d6 - d5 * d4
region_BC = (va <= 0) & ((d4 - d3) >= 0) & ((d5 - d6) >= 0)
v_bc = (d4 - d3) / ((d4 - d3) + (d5 - d6) + 1e-20)
closest_BC = b + v_bc.unsqueeze(-1) * (c - b)
- # Face interior (barycentric)
denom = va + vb + vc + 1e-20
v_face = vb / denom
w_face = vc / denom
closest_face = a + v_face.unsqueeze(-1) * ab + w_face.unsqueeze(-1) * ac
- # Combine by mask via in-place where (out= aliases input, no per-step alloc)
- closest = closest_face # fresh; safe to mutate
+ # in-place where into the fresh closest_face; later regions take precedence
+ closest = closest_face
torch.where(region_BC.unsqueeze(-1), closest_BC, closest, out=closest)
torch.where(region_AC.unsqueeze(-1), closest_AC, closest, out=closest)
torch.where(region_AB.unsqueeze(-1), closest_AB, closest, out=closest)
@@ -85,26 +73,45 @@ def _point_tri_closest(points: torch.Tensor, tris: torch.Tensor) -> Tuple[torch.
return closest, (diff * diff).sum(-1)
-def _build_centroid_tree(tri_verts: torch.Tensor):
- """scipy cKDTree over triangle centroids; build once and reuse across _udf_exact calls.
- balanced_tree/compact_nodes off: ~2.4x faster build (and faster queries on near-uniform
- centroid clouds) with identical exact-kNN results."""
+def _split_long_triangles(tri_verts: torch.Tensor, max_edge: float):
+ """Bisect triangles on their longest edge until no edge exceeds `max_edge`; returns (pieces (M, 3, 3), source index (M,)).
+
+ Keeps the centroid kNN in _udf_exact from missing the closest triangle on low-poly inputs; pieces keep their source's winding."""
+ src = torch.arange(tri_verts.shape[0], device=tri_verts.device)
+ while True:
+ e = (tri_verts.roll(-1, 1) - tri_verts).norm(dim=-1) # edge k runs from vertex k to k + 1
+ split = e.max(1).values > max_edge
+ if not bool(split.any()):
+ return tri_verts, src
+ k = e[split].argmax(1)
+ rot = (torch.arange(3, device=k.device)[None] + k[:, None]) % 3 # longest edge first
+ t = torch.gather(tri_verts[split], 1, rot[..., None].expand(-1, -1, 3))
+ m = 0.5 * (t[:, 0] + t[:, 1])
+ tri_verts = torch.cat([tri_verts[~split], torch.stack([t[:, 0], m, t[:, 2]], 1), torch.stack([m, t[:, 1], t[:, 2]], 1)])
+ src = torch.cat([src[~split], src[split], src[split]])
+
+
+def _build_udf_tree(tri_verts: torch.Tensor):
+ """Closest-triangle index for _udf_exact: comfy-kitchen's mesh BVH when available, else a cKDTree over triangle centroids."""
+ mesh_bvh = _kitchen_op("mesh_bvh", tri_verts)
+ if mesh_bvh is not None and tri_verts.dtype == torch.float32:
+ return mesh_bvh(tri_verts)
return scipy.spatial.cKDTree(tri_verts.mean(dim=1).detach().cpu().numpy(),
balanced_tree=False, compact_nodes=False)
def _udf_exact(query_points: torch.Tensor, tri_verts: torch.Tensor,
k: int = 8, chunk: int = 262144, tree=None):
- """Exact UDF (no max_dist cap) via centroid kNN; returns (dist [N], closest [N,3], tri_idx [N]). Pass prebuilt `tree` to skip rebuild.
+ """Unsigned distance to the triangles; returns (dist (N,), closest point (N, 3), triangle index (N,)).
- k=8 nearest centroids before the exact point-triangle test: on dense meshes the true
- closest triangle is essentially always within the first few neighbours. Measured vs k=16:
- bit-identical topology, ~0.003-voxel RMS sub-voxel drift, ~15% faster overall."""
+ The cKDTree path only tests the `k` nearest centroids, so long triangles must be split first (_split_long_triangles)."""
+ if tree is None:
+ tree = _build_udf_tree(tri_verts)
+ if not isinstance(tree, scipy.spatial.cKDTree):
+ return comfy.quant_ops.ck.closest_point_on_mesh(tree, query_points)
device = query_points.device
F = tri_verts.shape[0]
kq = int(min(k, F))
- if tree is None:
- tree = _build_centroid_tree(tri_verts)
_, cand = tree.query(query_points.detach().cpu().numpy(), k=kq, workers=-1)
if cand.ndim == 1:
cand = cand[:, None]
@@ -131,154 +138,13 @@ def _udf_exact(query_points: torch.Tensor, tri_verts: torch.Tensor,
return out_d, out_c, out_t
-# UDF query via spatial hash on triangle AABBs
-
-def _build_tri_spatial_hash(centroids: torch.Tensor, tri_radii: torch.Tensor,
- cell_size: torch.Tensor):
- """Bucket triangles into `cell_size` cells (each tri into every cell its AABB touches); returns hash tuple."""
- device = centroids.device
- aabb_lo = (centroids - tri_radii.unsqueeze(-1))
- aabb_hi = (centroids + tri_radii.unsqueeze(-1))
- origin = aabb_lo.min(0)[0]
- extent = aabb_hi.max(0)[0] - origin
- dims = (extent / cell_size).long() + 2
-
- cell_lo = ((aabb_lo - origin) / cell_size).long().clamp(min=0)
- cell_hi = ((aabb_hi - origin) / cell_size).long()
- cell_hi = torch.minimum(cell_hi, dims - 1)
-
- # Cap span at 3 cells/axis to bound memory
- spans = (cell_hi - cell_lo + 1).clamp(max=3)
- n_per_tri = spans.prod(dim=-1)
- total = int(n_per_tri.sum().item())
-
- # Per-insertion local offset within each tri's cell box
- rep = torch.repeat_interleave(torch.arange(centroids.shape[0], device=device), n_per_tri)
- cum = torch.cat([torch.zeros(1, device=device, dtype=n_per_tri.dtype),
- n_per_tri.cumsum(0)[:-1]])
- local = torch.arange(total, device=device) - cum[rep]
- sx = spans[rep, 0]
- sy = spans[rep, 1]
-
- lx = local % sx
- ly = (local // sx) % sy
- lz = local // (sx * sy)
- cx = cell_lo[rep, 0] + lx
- cy = cell_lo[rep, 1] + ly
- cz = cell_lo[rep, 2] + lz
- keys = (cx * dims[1] + cy) * dims[2] + cz
-
- sort_idx = keys.argsort()
- sorted_keys = keys[sort_idx]
- tri_per_cell = rep[sort_idx]
-
- unique_keys, counts = torch.unique_consecutive(sorted_keys, return_counts=True)
- cell_starts = torch.cat([torch.zeros(1, dtype=counts.dtype, device=device),
- counts.cumsum(0)])
- return origin, dims, unique_keys, tri_per_cell, cell_starts, centroids, tri_radii
-
-
-def _udf_query(query_points: torch.Tensor,
- tri_verts: torch.Tensor,
- hash_data,
- cell_size: torch.Tensor,
- max_dist: float,
- chunk_max: int = 4096,
- return_closest: bool = False,
- return_tri_idx: bool = False):
- """Capped UDF to nearest triangle (<= max_dist), optionally with closest point and/or tri index; chunk size is adaptive to hash density."""
- origin, dims, unique_keys, tri_per_cell, cell_starts, tri_centroids, tri_radii = hash_data
- device = query_points.device
- Q = query_points.shape[0]
- # Adaptive chunk: bound per-chunk candidate-gather memory by hash density
- avg_per_cell = tri_per_cell.numel() / max(1, unique_keys.numel())
- est_cands_per_query = max(1.0, avg_per_cell * 27)
- chunk = max(256, min(chunk_max, int(50_000_000 / est_cands_per_query)))
- out_d2 = torch.full((Q,), float(max_dist) ** 2, dtype=query_points.dtype, device=device)
- # Default closest_pt = query_pt itself, so a missed query's lerp is a no-op
- out_closest = (query_points.clone() if return_closest else None)
- out_tri = (torch.full((Q,), -1, dtype=torch.long, device=device)
- if return_tri_idx else None)
-
- rng = torch.tensor([-1, 0, 1], device=device, dtype=torch.long)
- offs = torch.stack(torch.meshgrid(rng, rng, rng, indexing="ij"), dim=-1).reshape(-1, 3) # (27, 3)
-
- for cs in range(0, Q, chunk):
- ce = min(cs + chunk, Q)
- qp = query_points[cs:ce]
- q_cell = ((qp - origin) / cell_size).long()
- # Look up 27 neighbour cells per query
- n_cell = q_cell.unsqueeze(1) + offs.unsqueeze(0) # (q, 27, 3)
- n_valid = ((n_cell >= 0) & (n_cell < dims)).all(-1)
- n_key = (n_cell[..., 0] * dims[1] + n_cell[..., 1]) * dims[2] + n_cell[..., 2]
- flat_key = n_key.reshape(-1).contiguous()
- ins = torch.searchsorted(unique_keys, flat_key)
- ins_c = ins.clamp(max=unique_keys.numel() - 1)
- found = (ins < unique_keys.numel()) & (unique_keys[ins_c] == flat_key) & n_valid.reshape(-1)
- cell_idx = torch.where(found, ins_c, torch.zeros_like(ins_c))
- c_starts = cell_starts[cell_idx]
- c_ends = cell_starts[cell_idx + 1]
- c_counts = (c_ends - c_starts) * found.long()
- rep_q = torch.repeat_interleave(
- torch.arange(qp.shape[0] * 27, device=device) // 27, c_counts)
- if rep_q.numel() == 0:
- continue
- total = rep_q.numel()
- slot_starts_per_pair = torch.cumsum(c_counts, dim=0) - c_counts
- per_pair_start = torch.repeat_interleave(c_starts, c_counts)
- slot_within = torch.arange(total, device=device) - torch.repeat_interleave(slot_starts_per_pair, c_counts)
- tri_indices = tri_per_cell[per_pair_start + slot_within]
-
- pts = qp[rep_q]
- # Centroid pre-cull (squared): drop where ||pts-centroid||-radius > max_dist
- diff = pts - tri_centroids[tri_indices]
- d2_cand = (diff * diff).sum(-1)
- thresh = max_dist + tri_radii[tri_indices]
- cull_keep = d2_cand < thresh * thresh
- rep_q = rep_q[cull_keep]
- pts = pts[cull_keep]
- tri_indices = tri_indices[cull_keep]
- if rep_q.numel() == 0:
- continue
- tri = tri_verts[tri_indices]
- closest, d2 = _point_tri_closest(pts, tri)
-
- # Min per query for this chunk.
- local_min = torch.full((qp.shape[0],), float(max_dist) ** 2,
- dtype=query_points.dtype, device=device)
- local_min.scatter_reduce_(0, rep_q, d2, reduce="amin", include_self=True)
- # Only update where this chunk improved; ties may overwrite (any is valid)
- better = local_min < out_d2[cs:ce]
- out_d2[cs:ce] = torch.where(better, local_min, out_d2[cs:ce])
- if return_closest or return_tri_idx:
- ties = (d2 == local_min[rep_q]) & better[rep_q]
- if return_closest:
- out_closest[cs + rep_q[ties]] = closest[ties]
- if return_tri_idx:
- out_tri[cs + rep_q[ties]] = tri_indices[ties]
-
- out_d = out_d2.sqrt()
- extras = []
- if return_closest:
- extras.append(out_closest)
- if return_tri_idx:
- extras.append(out_tri)
- if extras:
- return (out_d, *extras)
- return out_d
-
-
-# Sparse coarse-to-fine voxel grid in narrow band
-
-def _build_narrow_band_voxels(verts: torch.Tensor, faces: torch.Tensor,
+def _build_narrow_band_voxels(tri_verts: torch.Tensor,
center: torch.Tensor, scale: float,
resolution: int, eps: float,
progress_callback=None) -> torch.Tensor:
- """Voxel coords (Nv,3) in 0..resolution-1 whose centre is within ~0.87 cell_size of the surface; also returns the kept cKDTree."""
- device = verts.device
- tri_verts = verts[faces.long()]
- # Exact UDF; build the centroid cKDTree once and reuse across refinement levels
- tree = _build_centroid_tree(tri_verts)
+ """Returns voxel coords (Nv, 3) in [0, resolution) whose centre is within half a cell diagonal + eps of the surface, and the distance tree."""
+ device = tri_verts.device
+ tree = _build_udf_tree(tri_verts)
base_resolution = resolution
while base_resolution > 32 and base_resolution % 2 == 0:
@@ -311,168 +177,166 @@ def _build_narrow_band_voxels(verts: torch.Tensor, faces: torch.Tensor,
return coords, tree
-# Dual Contouring
+# _CUBE_EDGES: the 12 voxel edges as corner pairs, x-, y-, then z-aligned. _EDGE_VOXELS: per axis, the 4 voxels
+# around a grid edge; the y order is reversed vs x/z so quads wind consistently around every edge.
+_VOXEL_CHUNK = 1 << 21 # voxels per pass of the per-corner lookups, the remesh's largest transient
+_POINT_CHUNK = 1 << 21 # points per field evaluation, tet walk and sorted-merge pass; each walk step gathers 4 float64 planes per point
+_CUBE_CORNERS = ((0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 0, 1), (1, 0, 1), (0, 1, 1), (1, 1, 1))
+_CUBE_EDGES = ((0, 1), (2, 3), (4, 5), (6, 7), (0, 2), (1, 3), (4, 6), (5, 7), (0, 4), (1, 5), (2, 6), (3, 7))
+_EDGE_VOXELS = (((0, 0, 0), (0, -1, 0), (0, -1, -1), (0, 0, -1)),
+ ((0, 0, 0), (0, 0, -1), (-1, 0, -1), (-1, 0, 0)),
+ ((0, 0, 0), (-1, 0, 0), (-1, -1, 0), (0, -1, 0)))
+
+
+def _voxel_key(coords, resolution):
+ """Row-major key of voxel or corner coords on the (resolution + 1)³ corner grid; a band is its sorted voxel keys."""
+ r1 = resolution + 1
+ return (coords[..., 0] * r1 + coords[..., 1]) * r1 + coords[..., 2]
-def _dual_contour(voxel_coords: torch.Tensor, corner_udf: torch.Tensor,
+
+def _decode_key(keys, resolution):
+ r1 = resolution + 1
+ return torch.stack([keys // (r1 * r1), keys // r1 % r1, keys % r1], dim=1)
+
+
+def _dual_contour(vox_keys: torch.Tensor, corner_udf: torch.Tensor,
corner_keys: torch.Tensor,
resolution: int, scale: float, center: torch.Tensor,
tri_face_normals: Optional[torch.Tensor] = None,
qef_query=None,
corner_valid: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
- """Dual contour active voxels; returns (Nv,3) dual verts and (M,3) faces into them. QEF placement when tri_face_normals+qef_query given, else centroid of crossings."""
- device = voxel_coords.device
- Nv = voxel_coords.shape[0]
- # 8 corners per voxel, packed into a 1d key
- CORNER_OFFS = torch.tensor([
- [0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0],
- [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1],
- ], dtype=torch.long, device=device)
-
- corner_pos_per_voxel = voxel_coords.unsqueeze(1) + CORNER_OFFS.unsqueeze(0) # (Nv, 8, 3)
- R1 = resolution + 1
- keys_per_voxel = (corner_pos_per_voxel[..., 0] * R1
- + corner_pos_per_voxel[..., 1]) * R1 + corner_pos_per_voxel[..., 2]
- # Look up SDF index per corner; missing corners default to +1 (outside)
- idx_per_voxel = torch.searchsorted(corner_keys, keys_per_voxel.reshape(-1))
- idx_clamped = idx_per_voxel.clamp(max=corner_keys.numel() - 1)
- found = (idx_per_voxel < corner_keys.numel()) & (corner_keys[idx_clamped] == keys_per_voxel.reshape(-1))
- sd = torch.where(found, corner_udf[idx_clamped], torch.full_like(corner_udf[idx_clamped], 1.0))
- sd = sd.reshape(Nv, 8) # surface at sign = 0
-
- # 12 voxel edges as (corner_a, corner_b) pairs (indices into the 8 corners above)
- EDGES = torch.tensor([
- [0, 1], [2, 3], [4, 5], [6, 7], # x-axis edges
- [0, 2], [1, 3], [4, 6], [5, 7], # y-axis
- [0, 4], [1, 5], [2, 6], [3, 7], # z-axis
- ], dtype=torch.long, device=device)
-
- a_sd = sd[:, EDGES[:, 0]] # (Nv, 12)
- b_sd = sd[:, EDGES[:, 1]]
- crosses = (a_sd * b_sd) < 0 # (Nv, 12) bool
- # Skip crossings touching an invalid corner (avoids fake faces at band edge)
- if corner_valid is not None:
- cv_per_voxel = torch.where(found, corner_valid[idx_clamped],
- torch.zeros_like(found)).reshape(Nv, 8)
- edge_valid = cv_per_voxel[:, EDGES[:, 0]] & cv_per_voxel[:, EDGES[:, 1]]
- crosses = crosses & edge_valid
- del cv_per_voxel, edge_valid
- del keys_per_voxel, idx_per_voxel, idx_clamped, found
- # Zero-crossing interp factor per edge
- t = a_sd / (a_sd - b_sd + 1e-20)
- t = t.clamp(0.0, 1.0).unsqueeze(-1)
-
- corner_world = (corner_pos_per_voxel.float() / resolution - 0.5) * scale + center.unsqueeze(0).unsqueeze(0) # (Nv, 8, 3)
- a_pos = corner_world[:, EDGES[:, 0]] # (Nv, 12, 3)
- b_pos = corner_world[:, EDGES[:, 1]]
- crossing_pts = torch.lerp(a_pos, b_pos, t) # (Nv, 12, 3)
- del corner_pos_per_voxel, a_pos, b_pos, t
-
- # Default dual vert: centroid of crossings (also QEF/no-crossing fallback)
- crosses_f = crosses.float().unsqueeze(-1)
- crossing_sum = (crossing_pts * crosses_f).sum(dim=1)
- n_cross = crosses.float().sum(dim=1, keepdim=True).clamp_min(1.0)
- centroid_verts = crossing_sum / n_cross
- centre_world = ((voxel_coords.float() + 0.5) / resolution - 0.5) * scale + center.unsqueeze(0)
- has_cross = crosses.any(dim=1, keepdim=True)
- dual_verts = torch.where(has_cross, centroid_verts, centre_world)
-
- # QEF placement: minimise sum_i (n_i·(x-p_i))² via Tikhonov-regularised
- # normal equations (A+reg I)x=b; clamp to voxel bbox, else fall back to centroid.
- if tri_face_normals is not None and qef_query is not None:
- Nv = voxel_coords.shape[0]
- flat_pts = crossing_pts.reshape(-1, 3)
- flat_mask = crosses.reshape(-1)
- if flat_mask.any():
- query_pts = flat_pts[flat_mask]
- _, _, qef_tri_idx = qef_query(query_pts)
- # Missed queries get a zero normal (null constraint, ignored by solver)
- valid_q = qef_tri_idx >= 0
- normals_at_q = torch.zeros_like(query_pts)
- normals_at_q[valid_q] = tri_face_normals[qef_tri_idx[valid_q]]
- full_normals = torch.zeros((Nv * 12, 3), dtype=query_pts.dtype, device=device)
- full_normals[flat_mask] = normals_at_q
- n_per_edge = full_normals.reshape(Nv, 12, 3)
-
- # einsum sums into the 3x3 directly, skipping a big intermediate
- A = torch.einsum('vec,ved->vcd', n_per_edge, n_per_edge) # (Nv, 3, 3)
- n_dot_p = (n_per_edge * crossing_pts).sum(dim=-1) # (Nv, 12)
- b = torch.einsum('ve,vec->vc', n_dot_p, n_per_edge) # (Nv, 3)
-
- # Tikhonov regularisation in-place (A, b are fresh einsum outputs)
- reg = 1e-2
- A.diagonal(dim1=-2, dim2=-1).add_(reg)
- b.add_(centroid_verts, alpha=reg)
- try:
+ """Dual contour the active voxels, given as sorted keys; returns dual verts (Nv, 3) and faces (M, 3), surface where
+ corner values change sign.
+
+ Verts go to the QEF minimiser when tri_face_normals and qef_query are given, else to the centroid of the edge crossings."""
+ device = vox_keys.device
+ CORNER_OFFS = torch.tensor(_CUBE_CORNERS, dtype=torch.long, device=device)
+ EDGES = torch.tensor(_CUBE_EDGES, dtype=torch.long, device=device)
+ corner_key_offs = _voxel_key(CORNER_OFFS, resolution)
+
+ def edge_values(vk):
+ """Per voxel: crossing position along each of the 12 edges, whether corner a of the edges the voxel owns
+ (slots 0/4/8) is outside, and which edges cross."""
+ keys = vk[:, None] + corner_key_offs
+ idx = torch.searchsorted(corner_keys, keys.reshape(-1))
+ idx_c = idx.clamp(max=corner_keys.numel() - 1)
+ found = (idx < corner_keys.numel()) & (corner_keys[idx_c] == keys.reshape(-1))
+ # corners missing from corner_keys count as outside (+1)
+ sd = torch.where(found, corner_udf[idx_c], 1.0).reshape(-1, 8)
+ a_sd, b_sd = sd[:, EDGES[:, 0]], sd[:, EDGES[:, 1]] # (n, 12)
+ crosses = (a_sd * b_sd) < 0
+ # crossings at an invalid corner would emit fake faces at the band edge
+ if corner_valid is not None:
+ cv = torch.where(found, corner_valid[idx_c], False).reshape(-1, 8)
+ crosses &= cv[:, EDGES[:, 0]] & cv[:, EDGES[:, 1]]
+ return (a_sd / (a_sd - b_sd + 1e-20)).clamp(0.0, 1.0), a_sd[:, 0::4] > 0, crosses
+
+ # only voxels with a crossing emit anything, and all 4 voxels around a crossing edge share it; the per-corner
+ # lookups run in chunks, since over the whole band at once they would be the remesh's largest allocation
+ keep = torch.empty(vox_keys.numel(), dtype=torch.bool, device=device)
+ for s in range(0, vox_keys.numel(), _VOXEL_CHUNK):
+ keep[s:s + _VOXEL_CHUNK] = edge_values(vox_keys[s:s + _VOXEL_CHUNK])[2].any(dim=1)
+ vox_keys = vox_keys[keep]
+ Nv = vox_keys.numel()
+ if Nv == 0:
+ return torch.empty((0, 3), device=device), torch.empty((0, 3), dtype=torch.long, device=device)
+ EDGE_OF_AXIS = torch.tensor([0, 4, 8], dtype=torch.long, device=device) # a voxel owns the +axis edges at its min corner
+
+ def corner_world(vc, c):
+ return ((vc + CORNER_OFFS[c]).float() / resolution - 0.5) * scale + center # (n, 3)
+
+ # per voxel, a chunk at a time: the crossing points of all 12 edges, and the QEF normals, would otherwise be the
+ # largest arrays of the pass. What survives is the dual vertex and the crossing edges the voxel owns, for the quads.
+ dual_verts = torch.empty((Nv, 3), dtype=torch.float32, device=device)
+ own_voxel, own_axis, own_flip = [], [], []
+ for s in range(0, Nv, _VOXEL_CHUNK):
+ vk = vox_keys[s:s + _VOXEL_CHUNK]
+ vc = _decode_key(vk, resolution)
+ t, a_outside, crosses = edge_values(vk)
+ t = t.unsqueeze(-1)
+ crossing_pts = torch.empty((vc.shape[0], 12, 3), dtype=torch.float32, device=device)
+ for e in range(12):
+ crossing_pts[:, e] = torch.lerp(corner_world(vc, EDGES[e, 0]), corner_world(vc, EDGES[e, 1]), t[:, e])
+ del t
+
+ # centroid of the crossings, also the QEF fallback; the entries of edges without a crossing are zeroed, nothing reads them
+ crosses_f = crosses.float().unsqueeze(-1)
+ crossing_pts.mul_(crosses_f)
+ verts = centroid = crossing_pts.sum(dim=1) / crosses_f.sum(dim=1)
+
+ # QEF: minimise sum_i (n_i·(x - p_i))², regularised towards the centroid; solutions outside the voxel fall back to it
+ if tri_face_normals is not None and qef_query is not None:
+ flat_mask = crosses.reshape(-1)
+ if flat_mask.any():
+ query_pts = crossing_pts.reshape(-1, 3)[flat_mask]
+ _, _, qef_tri_idx = qef_query(query_pts)
+ # missed queries (tri -1) get a zero normal, i.e. no constraint
+ valid_q = qef_tri_idx >= 0
+ normals_at_q = torch.zeros_like(query_pts)
+ normals_at_q[valid_q] = tri_face_normals[qef_tri_idx[valid_q]]
+ n_per_edge = torch.zeros((vc.shape[0] * 12, 3), dtype=query_pts.dtype, device=device)
+ n_per_edge[flat_mask] = normals_at_q
+ n_per_edge = n_per_edge.reshape(-1, 12, 3)
+
+ A = torch.einsum('vec,ved->vcd', n_per_edge, n_per_edge) # (n, 3, 3)
+ n_dot_p = (n_per_edge * crossing_pts).sum(dim=-1)
+ b = torch.einsum('ve,vec->vc', n_dot_p, n_per_edge) # (n, 3)
+
+ # Tikhonov regularisation, in place on the fresh einsum outputs
+ reg = 1e-2
+ A.diagonal(dim1=-2, dim2=-1).add_(reg)
+ b.add_(centroid, alpha=reg)
qef_solution = torch.linalg.solve(A, b.unsqueeze(-1)).squeeze(-1)
- except torch.linalg.LinAlgError:
- qef_solution = centroid_verts
-
- # Clamp QEF output to the voxel bbox
- lo = corner_world[:, 0] # (Nv, 3) min corner
- hi = corner_world[:, 7] # (Nv, 3) max corner
- in_box = (qef_solution >= lo).all(dim=-1) & (qef_solution <= hi).all(dim=-1)
- qef_solution = torch.where(in_box.unsqueeze(-1), qef_solution, centroid_verts)
-
- dual_verts = torch.where(has_cross, qef_solution, centre_world)
- del query_pts, qef_tri_idx, valid_q, normals_at_q, full_normals, n_per_edge
- del A, n_dot_p, b, qef_solution, lo, hi, in_box
- del flat_pts, flat_mask
-
- del crossing_pts, corner_world, crosses_f, crossing_sum, n_cross
- del centroid_verts, centre_world, has_cross
-
- # Topology: each crossing grid edge is shared by 4 voxels -> quad -> 2 tris.
- # NEIGHBOUR_OFFS lays out the 4 sharing voxels per axis; y-axis order is
- # reversed vs x/z to keep manifold winding around each shared edge.
- NEIGHBOUR_OFFS = torch.tensor([
- [[0, 0, 0], [0, -1, 0], [0, -1, -1], [0, 0, -1]],
- [[0, 0, 0], [0, 0, -1], [-1, 0, -1], [-1, 0, 0]],
- [[0, 0, 0], [-1, 0, 0], [-1, -1, 0], [0, -1, 0]],
- ], dtype=torch.long, device=device)
-
- # Min-corner +axis edge index per axis (slots 0/4/8 in EDGES)
- EDGE_OF_AXIS = torch.tensor([0, 4, 8], dtype=torch.long, device=device)
- # Sorted voxel-coord keys for neighbour lookup
- vox_dims = voxel_coords.max(dim=0)[0] + 2
- vox_key = (voxel_coords[:, 0] * vox_dims[1] + voxel_coords[:, 1]) * vox_dims[2] + voxel_coords[:, 2]
- sort_v = vox_key.argsort()
- sorted_vox_key = vox_key[sort_v]
+ in_box = (qef_solution >= corner_world(vc, 0)).all(dim=-1) & (qef_solution <= corner_world(vc, 7)).all(dim=-1)
+ verts = torch.where(in_box.unsqueeze(-1), qef_solution, centroid)
+ del query_pts, qef_tri_idx, valid_q, normals_at_q, n_per_edge, A, n_dot_p, b, qef_solution, in_box
+ dual_verts[s:s + vc.shape[0]] = verts
+ v, axis = crosses[:, EDGE_OF_AXIS].nonzero(as_tuple=True)
+ own_voxel.append(v + s)
+ own_axis.append(axis.to(torch.int8))
+ own_flip.append(a_outside[v, axis])
+ del vk, vc, a_outside, crosses, crossing_pts, crosses_f, verts, centroid
+ own_voxel, own_axis, own_flip = torch.cat(own_voxel), torch.cat(own_axis), torch.cat(own_flip)
+
+ # each crossing grid edge gives a quad over the 4 voxels around it, split into 2 triangles; the keys are sorted,
+ # so a neighbour's position is its dual vertex
+ neighbour_key_offs = _voxel_key(torch.tensor(_EDGE_VOXELS, dtype=torch.long, device=device), resolution) # (3, 4)
tris = []
for axis in range(3):
- edge_idx = EDGE_OF_AXIS[axis]
- owner_mask = crosses[:, edge_idx] # (Nv,) bool
- if not owner_mask.any():
- continue
- owner_voxels = voxel_coords[owner_mask] # (No, 3)
- a_sign = a_sd[owner_mask, edge_idx] # (No,) sign at corner a
- nbrs = owner_voxels.unsqueeze(1) + NEIGHBOUR_OFFS[axis].unsqueeze(0) # (No, 4, 3)
- nbr_keys = (nbrs[..., 0] * vox_dims[1] + nbrs[..., 1]) * vox_dims[2] + nbrs[..., 2]
- flat = nbr_keys.reshape(-1).contiguous()
- ins = torch.searchsorted(sorted_vox_key, flat)
- ins_c = ins.clamp(max=sorted_vox_key.numel() - 1)
- valid = (ins < sorted_vox_key.numel()) & (sorted_vox_key[ins_c] == flat)
- valid = valid.reshape(-1, 4).all(dim=1)
- if not valid.any():
- continue
- dual_indices = sort_v[ins_c].reshape(-1, 4)[valid] # (Mv, 4)
- sign_a = a_sign[valid]
- # Winding: flip when corner a is outside (sign_a > 0) so normal points out
- d0 = dual_indices[:, 0]
- d1 = dual_indices[:, 1]
- d2 = dual_indices[:, 2]
- d3 = dual_indices[:, 3]
- flip = sign_a > 0
- t1a = torch.stack([d0, d1, d2], dim=1)
- t2a = torch.stack([d0, d2, d3], dim=1)
- t1b = torch.stack([d0, d2, d1], dim=1)
- t2b = torch.stack([d0, d3, d2], dim=1)
- t1 = torch.where(flip.unsqueeze(-1), t1b, t1a)
- t2 = torch.where(flip.unsqueeze(-1), t2b, t2a)
- tris.append(t1)
- tris.append(t2)
+ on_axis = own_axis == axis
+ owners, flips = own_voxel[on_axis], own_flip[on_axis]
+ t1s, t2s = [], []
+ for s in range(0, owners.shape[0], _VOXEL_CHUNK):
+ flat = (vox_keys[owners[s:s + _VOXEL_CHUNK], None] + neighbour_key_offs[axis]).reshape(-1)
+ ins = torch.searchsorted(vox_keys, flat)
+ ins_c = ins.clamp(max=Nv - 1)
+ valid = ((ins < Nv) & (vox_keys[ins_c] == flat)).reshape(-1, 4).all(dim=1)
+ if not valid.any():
+ continue
+ dual_indices = ins_c.reshape(-1, 4)[valid] # (Mv, 4)
+ # split along the shorter diagonal; a fixed one folds curved surfaces into grid-aligned terraces
+ p = dual_verts[dual_indices]
+ rot = (p[:, 1] - p[:, 3]).norm(dim=-1) < (p[:, 0] - p[:, 2]).norm(dim=-1)
+ dual_indices = torch.where(rot.unsqueeze(-1), dual_indices.roll(-1, dims=1), dual_indices)
+ del p, rot
+ # flip when corner a is outside so the normal points out
+ d0 = dual_indices[:, 0]
+ d1 = dual_indices[:, 1]
+ d2 = dual_indices[:, 2]
+ d3 = dual_indices[:, 3]
+ flip = flips[s:s + _VOXEL_CHUNK][valid]
+ t1a = torch.stack([d0, d1, d2], dim=1)
+ t2a = torch.stack([d0, d2, d3], dim=1)
+ t1b = torch.stack([d0, d2, d1], dim=1)
+ t2b = torch.stack([d0, d3, d2], dim=1)
+ t1s.append(torch.where(flip.unsqueeze(-1), t1b, t1a))
+ t2s.append(torch.where(flip.unsqueeze(-1), t2b, t2a))
+ if t1s:
+ tris.append(torch.cat(t1s))
+ tris.append(torch.cat(t2s))
if not tris:
return dual_verts, torch.empty((0, 3), dtype=torch.long, device=device)
@@ -484,12 +348,7 @@ def _dual_contour(voxel_coords: torch.Tensor, corner_udf: torch.Tensor,
@functools.lru_cache(maxsize=None)
def _build_mdc_lut() -> Tuple[torch.Tensor, torch.Tensor]:
- """Per 8-corner sign pattern: K (256,) patch count and group (256,12) patch id per edge (-1 if non-crossing)."""
- EDGE_PAIRS = [
- (0, 1), (2, 3), (4, 5), (6, 7), # x-axis edges
- (0, 2), (1, 3), (4, 6), (5, 7), # y-axis edges
- (0, 4), (1, 5), (2, 6), (3, 7), # z-axis edges
- ]
+ """Per 8-corner sign pattern: patch count K (256,) and per-edge patch id `group` (256, 12), -1 if not crossing."""
K = torch.zeros(256, dtype=torch.int64)
group = torch.full((256, 12), -1, dtype=torch.int64)
@@ -508,16 +367,16 @@ def _build_mdc_lut() -> Tuple[torch.Tensor, torch.Tensor]:
x = nxt
return r
- # Union same-sign corners (not separated by the surface)
- for a, b in EDGE_PAIRS:
+ # corners joined by a same-sign edge are on the same side of one patch
+ for a, b in _CUBE_EDGES:
if signs[a] == signs[b]:
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
- # Distinct (interior_root, exterior_root) pairs are distinct patches
+ # each distinct (interior root, exterior root) pair is one patch
group_map: dict[tuple[int, int], int] = {}
- for ei, (a, b) in enumerate(EDGE_PAIRS):
+ for ei, (a, b) in enumerate(_CUBE_EDGES):
if signs[a] == signs[b]:
continue
in_c = a if signs[a] == 0 else b
@@ -541,14 +400,11 @@ def _dual_contour_manifold(voxel_coords: torch.Tensor, corner_udf: torch.Tensor,
resolution: int, scale: float, center: torch.Tensor,
corner_valid: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
- """Manifold DC: like _dual_contour but emits 1-4 dual verts per voxel via the patch LUT (centroid placement only)."""
+ """Manifold DC: like _dual_contour but with one dual vert per patch (1-4 per voxel), centroid placement only."""
device = voxel_coords.device
Nv = voxel_coords.shape[0]
- CORNER_OFFS = torch.tensor([
- [0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0],
- [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1],
- ], dtype=torch.long, device=device)
+ CORNER_OFFS = torch.tensor(_CUBE_CORNERS, dtype=torch.long, device=device)
corner_pos = voxel_coords.unsqueeze(1) + CORNER_OFFS.unsqueeze(0) # (Nv, 8, 3)
R1 = resolution + 1
keys = (corner_pos[..., 0] * R1 + corner_pos[..., 1]) * R1 + corner_pos[..., 2]
@@ -559,30 +415,26 @@ def _dual_contour_manifold(voxel_coords: torch.Tensor, corner_udf: torch.Tensor,
sd = torch.where(found, corner_udf[idx_c],
torch.full_like(corner_udf[idx_c], 1.0)).reshape(Nv, 8)
- # Sign pattern: bit i = (sd[i] > 0), matching the LUT convention
- sign_bits = (sd > 0).to(torch.int64) # (Nv, 8)
+ # bit i set when corner i is outside, as in the LUT
+ sign_bits = (sd > 0).to(torch.int64)
weights = (1 << torch.arange(8, device=device, dtype=torch.int64))
pat_per_voxel = (sign_bits * weights).sum(dim=-1) # (Nv,) in 0..255
K_lut, group_lut = _mdc_lut(device)
- K_per_voxel = K_lut[pat_per_voxel] # (Nv,)
+ K_per_voxel = K_lut[pat_per_voxel]
total_verts = int(K_per_voxel.sum().item())
if total_verts == 0:
return (torch.empty((0, 3), dtype=voxel_coords.dtype, device=device),
torch.empty((0, 3), dtype=torch.long, device=device))
- vert_offset = (torch.cumsum(K_per_voxel, dim=0) - K_per_voxel) # (Nv,)
+ vert_offset = (torch.cumsum(K_per_voxel, dim=0) - K_per_voxel)
voxel_per_subvol = torch.repeat_interleave(
- torch.arange(Nv, device=device), K_per_voxel) # (total_verts,)
+ torch.arange(Nv, device=device), K_per_voxel)
- EDGES = torch.tensor([
- [0, 1], [2, 3], [4, 5], [6, 7],
- [0, 2], [1, 3], [4, 6], [5, 7],
- [0, 4], [1, 5], [2, 6], [3, 7],
- ], dtype=torch.long, device=device)
- sb_a = sign_bits[:, EDGES[:, 0]] # (Nv, 12)
+ EDGES = torch.tensor(_CUBE_EDGES, dtype=torch.long, device=device)
+ sb_a = sign_bits[:, EDGES[:, 0]]
sb_b = sign_bits[:, EDGES[:, 1]]
- crosses = sb_a != sb_b # (Nv, 12)
+ crosses = sb_a != sb_b
if corner_valid is not None:
cv = torch.where(found, corner_valid[idx_c],
@@ -590,13 +442,13 @@ def _dual_contour_manifold(voxel_coords: torch.Tensor, corner_udf: torch.Tensor,
edge_valid = cv[:, EDGES[:, 0]] & cv[:, EDGES[:, 1]]
crosses = crosses & edge_valid
- edge_group_per_voxel = group_lut[pat_per_voxel] # (Nv, 12), -1 if not crossing
- # LUT already gives -1 for non-crossing edges; only re-mask for corner_valid
+ edge_group_per_voxel = group_lut[pat_per_voxel] # (Nv, 12)
+ # the LUT already marks non-crossing edges -1; mask the ones at invalid corners too
if corner_valid is not None:
edge_group_per_voxel = torch.where(crosses, edge_group_per_voxel,
torch.full_like(edge_group_per_voxel, -1))
- a_sd = sd[:, EDGES[:, 0]] # (Nv, 12)
+ a_sd = sd[:, EDGES[:, 0]]
b_sd = sd[:, EDGES[:, 1]]
denom = a_sd - b_sd
t = torch.where(denom.abs() > 1e-20, a_sd / denom, torch.zeros_like(a_sd))
@@ -606,7 +458,7 @@ def _dual_contour_manifold(voxel_coords: torch.Tensor, corner_udf: torch.Tensor,
b_pos = corner_world[:, EDGES[:, 1]]
crossing_pts = torch.lerp(a_pos, b_pos, t) # (Nv, 12, 3)
- # Aggregate crossing positions per (voxel, subvolume) into global dual verts
+ # each dual vert is the centroid of its patch's crossings
flat_group = edge_group_per_voxel.reshape(-1)
valid_mask = flat_group >= 0
flat_voxel = torch.arange(Nv, device=device).unsqueeze(-1).expand(Nv, 12).reshape(-1)
@@ -614,14 +466,14 @@ def _dual_contour_manifold(voxel_coords: torch.Tensor, corner_udf: torch.Tensor,
v_idx = flat_voxel[valid_mask]
g_idx = flat_group[valid_mask]
pos = flat_pos[valid_mask]
- global_idx = vert_offset[v_idx] + g_idx # (Nvalid,)
+ global_idx = vert_offset[v_idx] + g_idx
pos_dtype = crossing_pts.dtype
sums = torch.zeros((total_verts, 3), dtype=pos_dtype, device=device)
counts = torch.zeros(total_verts, dtype=pos_dtype, device=device)
sums.scatter_add_(0, global_idx.unsqueeze(-1).expand(-1, 3), pos)
counts.scatter_add_(0, global_idx, torch.ones_like(g_idx, dtype=pos_dtype))
- # Fully-masked subvolumes default to the voxel centre (unreferenced)
+ # fully masked patches get the voxel centre; no face uses them
voxel_centre = ((voxel_coords.float() + 0.5) / resolution - 0.5) * scale + center.unsqueeze(0)
dual_verts = torch.where(
counts.unsqueeze(-1) > 0,
@@ -629,17 +481,12 @@ def _dual_contour_manifold(voxel_coords: torch.Tensor, corner_udf: torch.Tensor,
voxel_centre[voxel_per_subvol].to(pos_dtype),
)
- # Face emission. SHARED_LOCAL_EDGE[axis,k] = the k-th neighbour's local edge
- # slot corresponding to the shared grid edge (owner's slot = EDGE_OF_AXIS[axis]).
- NEIGHBOUR_OFFS = torch.tensor([
- [[0, 0, 0], [0, -1, 0], [0, -1, -1], [0, 0, -1]],
- [[0, 0, 0], [0, 0, -1], [-1, 0, -1], [-1, 0, 0]],
- [[0, 0, 0], [-1, 0, 0], [-1, -1, 0], [0, -1, 0]],
- ], dtype=torch.long, device=device)
+ # SHARED_LOCAL_EDGE[axis, k]: the slot of the shared grid edge in the k-th neighbour around it
+ NEIGHBOUR_OFFS = torch.tensor(_EDGE_VOXELS, dtype=torch.long, device=device)
SHARED_LOCAL_EDGE = torch.tensor([
- [0, 1, 3, 2], # x-axis
- [4, 6, 7, 5], # y-axis
- [8, 9, 11, 10], # z-axis
+ [0, 1, 3, 2],
+ [4, 6, 7, 5],
+ [8, 9, 11, 10],
], dtype=torch.long, device=device)
EDGE_OF_AXIS = torch.tensor([0, 4, 8], dtype=torch.long, device=device)
@@ -655,7 +502,7 @@ def _dual_contour_manifold(voxel_coords: torch.Tensor, corner_udf: torch.Tensor,
if not owner_mask.any():
continue
owner_voxels = voxel_coords[owner_mask]
- sign_a_at_owner = sb_a[owner_mask, edge_idx] # (No,) — 0 inside, 1 outside
+ sign_a_at_owner = sb_a[owner_mask, edge_idx] # 0 inside, 1 outside
nbrs = owner_voxels.unsqueeze(1) + NEIGHBOUR_OFFS[axis].unsqueeze(0) # (No, 4, 3)
nbr_keys = (nbrs[..., 0] * vox_dims[1] + nbrs[..., 1]) * vox_dims[2] + nbrs[..., 2]
@@ -667,20 +514,24 @@ def _dual_contour_manifold(voxel_coords: torch.Tensor, corner_udf: torch.Tensor,
if not valid_quad.any():
continue
- nbr_orig = sort_v[ins_c].reshape(-1, 4)[valid_quad] # (Mv, 4) voxel idx
- nbr_pat = pat_per_voxel[nbr_orig] # (Mv, 4)
+ nbr_orig = sort_v[ins_c].reshape(-1, 4)[valid_quad] # (Mv, 4)
+ nbr_pat = pat_per_voxel[nbr_orig]
local_e = SHARED_LOCAL_EDGE[axis].unsqueeze(0).expand_as(nbr_pat)
- nbr_subvol = group_lut[nbr_pat, local_e] # (Mv, 4)
- # Every neighbour must agree the shared edge is crossing
+ nbr_subvol = group_lut[nbr_pat, local_e]
+ # every neighbour must agree the shared edge is crossing
ok = (nbr_subvol >= 0).all(dim=1)
if not ok.any():
continue
nbr_subvol = nbr_subvol[ok]
nbr_orig = nbr_orig[ok]
- dual_indices = vert_offset[nbr_orig] + nbr_subvol # (Mv', 4)
- sign_a = sign_a_at_owner[valid_quad][ok] # 0 = inside, 1 = outside
-
- # Winding: flip when corner a is outside (same as _dual_contour)
+ dual_indices = vert_offset[nbr_orig] + nbr_subvol
+ sign_a = sign_a_at_owner[valid_quad][ok]
+ p = dual_verts[dual_indices]
+ rot = (p[:, 1] - p[:, 3]).norm(dim=-1) < (p[:, 0] - p[:, 2]).norm(dim=-1)
+ dual_indices = torch.where(rot.unsqueeze(-1), dual_indices.roll(-1, dims=1), dual_indices)
+ del p, rot
+
+ # same split and winding as _dual_contour
flip = sign_a > 0
d0, d1, d2, d3 = dual_indices.unbind(dim=1)
t1a = torch.stack([d0, d1, d2], dim=1)
@@ -695,31 +546,16 @@ def _dual_contour_manifold(voxel_coords: torch.Tensor, corner_udf: torch.Tensor,
return dual_verts, torch.cat(tris_out, dim=0)
-# Main entry
-
def _filter_components(verts: torch.Tensor, faces: torch.Tensor,
min_fraction: float = 0.01,
drop_inverted: bool = True,
drop_enclosed: bool = True) -> torch.Tensor:
- """Drop tiny / inverted-volume / bbox-enclosed connected components; returns filtered faces."""
+ """Drop tiny, inside-out and enclosed connected components; returns the kept faces."""
device = faces.device
V = verts.shape[0]
- # Connected components via min-label propagation across faces (200-iter max)
- label = torch.arange(V, dtype=torch.long, device=device)
- for _ in range(200):
- f_min = torch.minimum(torch.minimum(label[faces[:, 0]], label[faces[:, 1]]),
- label[faces[:, 2]])
- new_label = label.clone()
- new_label.scatter_reduce_(0, faces[:, 0], f_min, reduce="amin", include_self=True)
- new_label.scatter_reduce_(0, faces[:, 1], f_min, reduce="amin", include_self=True)
- new_label.scatter_reduce_(0, faces[:, 2], f_min, reduce="amin", include_self=True)
- new_label = new_label[new_label] # path compression
- if torch.equal(new_label, label):
- break
- label = new_label
-
- face_label = label[faces[:, 0]] # (F,)
+ label = _connected_labels(torch.cat([faces[:, :2], faces[:, 1:]]), V)
+ face_label = label[faces[:, 0]]
unique_labels, inv = torch.unique(face_label, return_inverse=True)
C = unique_labels.shape[0]
counts = torch.bincount(inv, minlength=C)
@@ -731,11 +567,11 @@ def _filter_components(verts: torch.Tensor, faces: torch.Tensor,
keep = keep & (counts >= threshold)
if drop_inverted:
- # Drop components with negative signed volume, but always keep the largest
+ # negative signed volume means inside out; the largest component is always kept
v0 = verts[faces[:, 0]]
v1 = verts[faces[:, 1]]
v2 = verts[faces[:, 2]]
- face_vol = (v0 * torch.cross(v1, v2, dim=-1)).sum(dim=-1) # (F,)
+ face_vol = (v0 * torch.cross(v1, v2, dim=-1)).sum(dim=-1)
comp_vol = torch.zeros(C, dtype=face_vol.dtype, device=device)
comp_vol.scatter_add_(0, inv, face_vol)
if C > 1:
@@ -745,7 +581,7 @@ def _filter_components(verts: torch.Tensor, faces: torch.Tensor,
keep = keep & vol_ok
if drop_enclosed and C > 1:
- # Two-pass: (1) bbox-inside-largest test, then (2) +X raycast point-in-mesh
+ # enclosed: bbox inside the largest's bbox, or centroid inside the largest by +X ray parity
large = counts.argmax()
face_v = verts[faces]
face_min = face_v.min(dim=1).values
@@ -762,13 +598,11 @@ def _filter_components(verts: torch.Tensor, faces: torch.Tensor,
& (comp_max <= big_max).all(dim=-1))
enclosed[large] = False
- # Per-component centroid for the raycast test
- face_centroid = face_v.mean(dim=1) # (F, 3)
+ face_centroid = face_v.mean(dim=1)
comp_centroid = torch.zeros((C, 3), dtype=verts.dtype, device=device)
comp_centroid.scatter_add_(0, inv[:, None].expand(-1, 3), face_centroid)
comp_centroid = comp_centroid / counts.to(verts.dtype).unsqueeze(-1).clamp_min(1.0)
- # Raycast surviving non-largest candidates (small loop)
big_faces = faces[inv == large]
bv0 = verts[big_faces[:, 0]]
bv1 = verts[big_faces[:, 1]]
@@ -778,7 +612,7 @@ def _filter_components(verts: torch.Tensor, faces: torch.Tensor,
as_tuple=True)[0]
for ci in candidates.tolist():
origin = comp_centroid[ci]
- # 2D point-in-triangle in YZ for the ray origin's (y, z)
+ # the +X ray hits the triangles whose YZ projection contains the origin
oy, oz = origin[1], origin[2]
s12 = (bv1[:, 1] - oy) * (bv2[:, 2] - oz) - (bv1[:, 2] - oz) * (bv2[:, 1] - oy)
s20 = (bv2[:, 1] - oy) * (bv0[:, 2] - oz) - (bv2[:, 2] - oz) * (bv0[:, 1] - oy)
@@ -803,7 +637,7 @@ def _filter_components(verts: torch.Tensor, faces: torch.Tensor,
def _taubin_smooth(verts: torch.Tensor, faces: torch.Tensor,
iters: int, lam: float = 0.5, mu: float = -0.53,
progress_callback=None) -> torch.Tensor:
- """Taubin lambda|mu low-pass smoothing (volume-preserving); boundary verts are no-ops."""
+ """Taubin lambda/mu smoothing with uniform weights, a low-pass filter that limits shrinkage."""
if iters <= 0 or verts.numel() == 0 or faces.numel() == 0:
return verts
device = verts.device
@@ -839,7 +673,7 @@ def _taubin_smooth(verts: torch.Tensor, faces: torch.Tensor,
def _fix_poles(verts: torch.Tensor, faces: torch.Tensor,
colors: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
- """Midpoint-collapse edge-sharing valence-3 vertex pairs (DC T-junction poles); boundary verts excluded."""
+ """Collapse adjacent interior valence-3 vertex pairs (DC pole artifacts) to their midpoint; returns (verts, faces, colors)."""
device = verts.device
V = verts.shape[0]
if V == 0 or faces.numel() == 0:
@@ -850,7 +684,6 @@ def _fix_poles(verts: torch.Tensor, faces: torch.Tensor,
P = V + 1
a = uniq_keys // P
b = uniq_keys % P
- # Boundary verts (endpoints of single-face edges) are excluded from poles
boundary_v = torch.zeros(V, dtype=torch.bool, device=device)
bnd_mask = key_counts == 1
if bnd_mask.any():
@@ -870,7 +703,7 @@ def _fix_poles(verts: torch.Tensor, faces: torch.Tensor,
cand_a = a[pp_edge]
cand_b = b[pp_edge]
- # Greedy maximal matching: accept candidates whose endpoints are still free
+ # greedy matching, so each vertex collapses at most once
used = torch.zeros(V, dtype=torch.bool, device="cpu")
cand_a_cpu = cand_a.cpu().tolist()
cand_b_cpu = cand_b.cpu().tolist()
@@ -883,7 +716,7 @@ def _fix_poles(verts: torch.Tensor, faces: torch.Tensor,
if not pairs:
return verts, faces, colors
- pairs_t = torch.tensor(pairs, dtype=torch.long, device=device) # (P, 2)
+ pairs_t = torch.tensor(pairs, dtype=torch.long, device=device)
keep_i = torch.minimum(pairs_t[:, 0], pairs_t[:, 1])
drop_i = torch.maximum(pairs_t[:, 0], pairs_t[:, 1])
@@ -913,6 +746,268 @@ def _fix_poles(verts: torch.Tensor, faces: torch.Tensor,
return new_verts, new_faces.to(faces.dtype), new_colors
+def _merge_sorted(keys: torch.Tensor, new_keys: torch.Tensor, *columns):
+ """Merge sorted, disjoint `new_keys` into sorted `keys` without re-sorting; each (old, new) column in `columns`
+ follows its keys. A key's slot is its own index plus the count of the other array's keys below it."""
+ device = keys.device
+ columns = ((keys, new_keys),) + columns
+ merged = [torch.empty((keys.numel() + new_keys.numel(),) + old.shape[1:], dtype=old.dtype, device=device) for old, _ in columns]
+ at_new = torch.searchsorted(keys, new_keys) + torch.arange(new_keys.numel(), device=device)
+ for out, (_, new) in zip(merged, columns):
+ out[at_new] = new
+ for s in range(0, keys.numel(), _POINT_CHUNK):
+ at_old = torch.searchsorted(new_keys, keys[s:s + _POINT_CHUNK]) + torch.arange(s, min(s + _POINT_CHUNK, keys.numel()), device=device)
+ for out, (old, _) in zip(merged, columns):
+ out[at_old] = old[s:s + _POINT_CHUNK]
+ return merged
+
+
+def _close_band(vox_keys: torch.Tensor, corner_keys: torch.Tensor, corner_sdf: torch.Tensor,
+ field, resolution: int, scale: float, center: torch.Tensor):
+ """Add the missing voxels around every sign-changing grid edge, so each one emits a quad and the surface closes.
+
+ `vox_keys` are the band's sorted voxel keys and `field(points)` gives the SDF at new corners. Returns the grown,
+ still sorted (vox_keys, corner_keys, corner_sdf)."""
+ device = vox_keys.device
+ corner_offs = torch.tensor(_CUBE_CORNERS, dtype=torch.long, device=device)
+ edges = torch.tensor(_CUBE_EDGES, dtype=torch.long, device=device)
+ axis_of_edge = torch.tensor([0] * 4 + [1] * 4 + [2] * 4, device=device)
+ around = torch.tensor(_EDGE_VOXELS, dtype=torch.long, device=device)
+ corner_key_offs = _voxel_key(corner_offs, resolution)
+ while True:
+ new = []
+ for s in range(0, vox_keys.numel(), _VOXEL_CHUNK):
+ vk = vox_keys[s:s + _VOXEL_CHUNK]
+ val = corner_sdf[torch.searchsorted(corner_keys, vk[:, None] + corner_key_offs)] # (n, 8)
+ v, e = ((val[:, edges[:, 0]] < 0) != (val[:, edges[:, 1]] < 0)).nonzero(as_tuple=True)
+ # the 4 voxels around the crossing edge, from its min corner; nearly all are in the band already
+ vox = ((_decode_key(vk, resolution)[v] + corner_offs[edges[e, 0]])[:, None, :] + around[axis_of_edge[e]]).reshape(-1, 3)
+ need = torch.unique(_voxel_key(vox[((vox >= 0) & (vox < resolution)).all(1)], resolution))
+ pos = torch.searchsorted(vox_keys, need).clamp(max=vox_keys.numel() - 1)
+ new.append(need[vox_keys[pos] != need])
+ new = torch.unique(torch.cat(new))
+ if new.numel() == 0:
+ return vox_keys, corner_keys, corner_sdf
+ vox_keys = _merge_sorted(vox_keys, new)[0]
+ new_corners = torch.unique(new[:, None] + corner_key_offs)
+ pos = torch.searchsorted(corner_keys, new_corners).clamp(max=corner_keys.numel() - 1)
+ new_corners = new_corners[corner_keys[pos] != new_corners]
+ if new_corners.numel():
+ new_sdf = torch.empty(new_corners.numel(), dtype=corner_sdf.dtype, device=device)
+ for s in range(0, new_corners.numel(), _POINT_CHUNK):
+ new_sdf[s:s + _POINT_CHUNK] = field((_decode_key(new_corners[s:s + _POINT_CHUNK], resolution).to(corner_sdf.dtype) / resolution - 0.5) * scale + center)
+ corner_keys, corner_sdf = _merge_sorted(corner_keys, new_corners, (corner_sdf, new_sdf))
+
+
+# Solid sign mode (CelloCut, arXiv 2605.17853): inside/outside from a graph cut over a tetrahedralization of the UDF shell.
+
+_TET_FACES = ((1, 2, 3), (0, 2, 3), (0, 1, 3), (0, 1, 2)) # face k is opposite vertex k
+
+
+def _min_cut(nbr: torch.Tensor, cap: torch.Tensor, s_cap: torch.Tensor, t_cap: torch.Tensor,
+ relabel_every: int = 64) -> torch.Tensor:
+ """Data-parallel push-relabel min s-t cut; returns the source side as a bool mask (N,).
+
+ nbr (N, 4) holds neighbour ids (-1 = none) with symmetric capacities `cap` (N, 4); s_cap / t_cap are per-node terminal capacities."""
+ min_cut = _kitchen_op("min_cut", nbr)
+ if min_cut is not None:
+ return min_cut(nbr, cap.float(), s_cap.float(), t_cap.float())
+ n = nbr.shape[0]
+ device = nbr.device
+ big = n + 2
+ valid = nbr >= 0
+ j = nbr.clamp(min=0)
+ rev = (nbr[j] == torch.arange(n, device=device)[:, None, None]).int().argmax(-1) # nbr[j, rev] == i
+ tol = 1e-12 * float(cap.max()) if cap.numel() else 0.0
+ r = torch.where(valid, cap, torch.zeros_like(cap))
+ rt = t_cap.clone()
+ e = s_cap.clone()
+
+ def global_relabel():
+ h = torch.full((n,), big, dtype=torch.long, device=device)
+ frontier = rt > tol
+ h[frontier] = 1
+ d = 1
+ while bool(frontier.any()):
+ d += 1
+ frontier = ((r > tol) & frontier[j]).any(1) & (h == big)
+ h[frontier] = d
+ return h
+
+ h = global_relabel()
+ it = 0
+ while True:
+ throw_exception_if_processing_interrupted()
+ if not bool(((e > tol) & (h < big)).any()):
+ break
+ amt = torch.where((e > tol) & (h == 1) & (rt > tol), torch.minimum(e, rt), torch.zeros_like(e))
+ e = e - amt
+ rt = rt - amt
+ for k in range(4): # one slot at a time, so a node never pushes more than its excess
+ jk = j[:, k]
+ adm = (e > tol) & (h < big) & (r[:, k] > tol) & (h == h[jk] + 1)
+ idx = adm.nonzero().squeeze(1)
+ amt = torch.minimum(e[idx], r[idx, k])
+ e[idx] -= amt
+ r[idx, k] -= amt
+ r[jk[idx], rev[idx, k]] += amt
+ e.index_add_(0, jk[idx], amt)
+ stuck = (e > tol) & (h < big)
+ if bool(stuck.any()):
+ hmin = torch.where(r > tol, h[j], big).amin(1)
+ hmin = torch.where(rt > tol, torch.zeros_like(hmin), hmin)
+ h = torch.where(stuck, torch.maximum(h, (hmin + 1).clamp(max=big)), h)
+ it += 1
+ if it % relabel_every == 0:
+ h = global_relabel()
+ return global_relabel() >= big
+
+
+def _tet_locator(tet_pts: torch.Tensor, tets: torch.Tensor, nbr: torch.Tensor, max_steps: int = 1024):
+ """Returns locate(points) -> containing tet per point (-1 outside the hull, or a walk not done in max_steps), by
+ stochastic visibility walks from the nearest triangulated vertex. The per-tet setup is done once here, the points
+ come in batches.
+
+ Tests run in the float64 of `tet_pts`, on its device: in float32 the faces of near-flat hull tets enclose points far
+ outside them. The tet ids come back on the points' device."""
+ device = tet_pts.device
+ N = tets.shape[0]
+ tet_faces = torch.tensor(_TET_FACES, device=device)
+ # planes from sorted vertex ids, oriented by the better-conditioned tet, so both tets of a face agree on sides;
+ # built a chunk of tets at a time, since the gathered face vertices are several times the planes' size
+ n = torch.empty((N, 4, 3), dtype=tet_pts.dtype, device=device)
+ d = torch.empty((N, 4), dtype=tet_pts.dtype, device=device)
+ opp = torch.empty((N, 4), dtype=tet_pts.dtype, device=device)
+ for s in range(0, N, _VOXEL_CHUNK):
+ chunk = tets[s:s + _VOXEL_CHUNK]
+ fv = chunk[:, tet_faces].sort(-1).values
+ a = tet_pts[fv[..., 0]]
+ nc = torch.cross(tet_pts[fv[..., 1]] - a, tet_pts[fv[..., 2]] - a, dim=-1)
+ n[s:s + _VOXEL_CHUNK] = nc
+ d[s:s + _VOXEL_CHUNK] = (nc * a).sum(-1)
+ opp[s:s + _VOXEL_CHUNK] = (nc * tet_pts[chunk]).sum(-1) - d[s:s + _VOXEL_CHUNK] # opposite vertex goes on the inner side
+ del chunk, fv, a, nc
+ for s in range(0, N, _VOXEL_CHUNK):
+ nb = nbr[s:s + _VOXEL_CHUNK]
+ j = nb.clamp(min=0)
+ rev = (nbr[j] == torch.arange(s, s + nb.shape[0], device=device)[:, None, None]).int().argmax(-1)
+ opp_j = opp[j, rev]
+ o = opp[s:s + _VOXEL_CHUNK]
+ side = torch.where((nb >= 0) & (opp_j.abs() > o.abs()), torch.where(opp_j > 0, -1.0, 1.0), torch.where(o >= 0, 1.0, -1.0))
+ n[s:s + _VOXEL_CHUNK] *= side[..., None]
+ d[s:s + _VOXEL_CHUNK] *= side
+ del nb, j, rev, opp_j, o, side
+ del opp
+ vert_tet = torch.full((tet_pts.shape[0],), -1, dtype=torch.long, device=device)
+ vert_tet[tets.reshape(-1)] = torch.arange(tets.shape[0], device=device).repeat_interleave(4)
+ used = torch.nonzero(vert_tet >= 0).squeeze(1) # qhull leaves out near-duplicate points
+ # nearest triangulated vertex, as the closest of zero-area triangles
+ start = tet_pts[used].float()[:, None].expand(-1, 3, -1)
+ tree = _build_udf_tree(start)
+ gen = torch.Generator(device=device).manual_seed(0)
+
+ def locate(points):
+ out = torch.full((points.shape[0],), -1, dtype=torch.long, device=points.device)
+ for s in range(0, points.shape[0], _POINT_CHUNK):
+ q = points[s:s + _POINT_CHUNK].to(device).to(tet_pts.dtype)
+ cur = vert_tet[used[_udf_exact(q.float(), start, k=1, tree=tree)[2]]]
+ found = torch.full((q.shape[0],), -1, dtype=torch.long, device=device)
+ todo = torch.arange(q.shape[0], device=device)
+ for _ in range(max_steps):
+ if todo.numel() == 0:
+ break
+ t = cur[todo]
+ outside = (n[t] * q[todo][:, None, :]).sum(-1) < d[t]
+ inside = ~outside.any(1)
+ found[todo[inside]] = t[inside]
+ # leave through a random face the point is outside of: no cycles under rounding
+ k = torch.where(outside, torch.rand(outside.shape, device=device, generator=gen), -1.0).argmax(1)
+ step = nbr[t, k]
+ moving = ~inside & (step >= 0)
+ cur[todo[moving]] = step[moving]
+ todo = todo[moving]
+ out[s:s + q.shape[0]] = found
+ return out
+
+ return locate
+
+
+def _solid_partition(shell_v: torch.Tensor, tri_verts: torch.Tensor, tree, eps: float, fill: float):
+ """Label the tets of a Delaunay tetrahedralization of shell sites solid or outside by a min cut.
+
+ Returns (tet points, tets, neighbours, solid per tet, outward boundary triangles (M, 3, 3)); the last two on the
+ device of shell_v, the tetrahedralization on the CPU when that device has no float64."""
+ device = shell_v.device
+ # sites: one shell vertex per block of 4 cells and offset direction, so both sides of a thin sheet keep theirs and
+ # a corner gets one per facing; about the 5% a decimation kept, without its edges and quadrics
+ away = shell_v - _udf_exact(shell_v, tri_verts, tree=tree)[1]
+ axis = away.abs().argmax(1)
+ facing = axis * 2 + (away.gather(1, axis[:, None])[:, 0] < 0).long()
+ block = torch.floor(shell_v / (4 * eps)).long()
+ block -= block.amin(0)
+ span = block.amax(0) + 1
+ cluster = torch.unique(((block[:, 0] * span[1] + block[:, 1]) * span[2] + block[:, 2]) * 6 + facing, return_inverse=True)[1]
+ first = torch.full((int(cluster.max()) + 1,), shell_v.shape[0], dtype=torch.int32, device=device)
+ dv = shell_v[first.scatter_reduce(0, cluster, torch.arange(shell_v.shape[0], dtype=torch.int32, device=device), "amin")]
+ del away, axis, facing, block, cluster, first
+ # jitter: grid-aligned flat regions give cocircular points that qhull is very slow to merge
+ gen = torch.Generator(device=device).manual_seed(0)
+ dv = dv + (torch.rand(dv.shape, generator=gen, device=device, dtype=dv.dtype) * 2 - 1) * (1e-3 * eps)
+ delaunay3d = _kitchen_op("delaunay3d", dv)
+ if delaunay3d is not None:
+ # tets on the kitchen's bounding-tet corners cover the space outside the points' hull
+ tet_pts, tets, nbr = delaunay3d(dv)
+ tets, nbr = tets.long(), nbr.long()
+ outside = (tets >= dv.shape[0]).any(1)
+ else:
+ dt = scipy.spatial.Delaunay(dv.cpu().double().numpy(), qhull_options="Qbb Qc Qz Q12 Qt Q5") # Q5: skip the final outer-plane check
+ # the float64 tets stay on the CPU unless the device is CUDA: MPS has no float64, other backends vary
+ tet_device = device if device.type == "cuda" else torch.device("cpu")
+ tet_pts = torch.from_numpy(dt.points).to(tet_device)
+ tets = torch.from_numpy(dt.simplices).to(tet_device).long()
+ nbr = torch.from_numpy(dt.neighbors).to(tet_device).long()
+ outside = (nbr < 0).any(1)
+
+ # per chunk: the four face areas and whether the centroid lies in the shell layer; all faces of all tets at
+ # once would be the partition's largest array
+ tet_faces = torch.tensor(_TET_FACES, device=tets.device)
+ area = torch.empty((tets.shape[0], 4), dtype=tet_pts.dtype, device=tets.device)
+ shell = torch.empty(tets.shape[0], dtype=torch.bool, device=tets.device)
+ for s in range(0, tets.shape[0], _VOXEL_CHUNK):
+ chunk = tets[s:s + _VOXEL_CHUNK]
+ fv = tet_pts[chunk[:, tet_faces]] # (n, 4, 3, 3)
+ area[s:s + _VOXEL_CHUNK] = 0.5 * torch.cross(fv[:, :, 1] - fv[:, :, 0], fv[:, :, 2] - fv[:, :, 0], dim=-1).norm(dim=-1)
+ shell[s:s + _VOXEL_CHUNK] = _udf_exact(tet_pts[chunk].mean(1).to(tri_verts.dtype).to(device), tri_verts, tree=tree)[0] < 0.95 * eps
+ del chunk, fv
+ hull = outside & ~shell
+
+ # shell tets are solid, hull tets outside; the cut runs over face areas, (1 + fill)x higher between
+ # two shell or two non-shell tets, so it follows the shell and only crosses open space to close small openings
+ j = nbr.clamp(min=0)
+ cap = torch.where(nbr >= 0, area * torch.where(shell[:, None] == shell[j], 1.0 + fill, 1.0), 0.0)
+ free = ~shell & ~hull
+ free_idx = torch.full((tets.shape[0],), -1, dtype=torch.long, device=tets.device)
+ free_idx[free] = torch.arange(int(free.sum()), device=tets.device)
+ fn, fcap = nbr[free], cap[free]
+ fj = fn.clamp(min=0)
+ to_free = (fn >= 0) & free[fj]
+ solid = shell.clone()
+ # the cut needs no float64: it runs on the compute device in float32, as the kitchen op does
+ solid[free] = _min_cut(torch.where(to_free, free_idx[fj], -1).to(device),
+ torch.where(to_free, fcap, 0.0).float().to(device),
+ torch.where((fn >= 0) & shell[fj], fcap, 0.0).sum(1).float().to(device),
+ torch.where((fn >= 0) & hull[fj], fcap, 0.0).sum(1).float().to(device)).to(tets.device)
+
+ # boundary faces of solid tets, wound to face away from their tet
+ bnd = solid[:, None] & ((nbr < 0) | ~solid[j])
+ t, k = bnd.nonzero(as_tuple=True)
+ tri = tet_pts[tets[t].gather(1, tet_faces[k])]
+ opp = tet_pts[tets[t, k]]
+ inward = (torch.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0], dim=-1) * (opp - tri[:, 0])).sum(-1) > 0
+ tri = torch.where(inward[:, None, None], tri[:, [0, 2, 1]], tri)
+ return tet_pts, tets, nbr, solid.to(device), tri.to(tri_verts.dtype).to(device)
+
+
def remesh_narrow_band_dc(
vertices: torch.Tensor,
faces: torch.Tensor,
@@ -921,24 +1016,26 @@ def remesh_narrow_band_dc(
band: float = 1.0,
project_back: float = 0.0,
qef: bool = True,
- sign_mode: str = "udf", # "sdf" | "udf"
- drop_small_components: float = 0.01, # drop components below this fraction of max
- drop_inverted_components: bool = True, # drop closed components with negative signed volume
- drop_enclosed_components: bool = True, # drop components whose bbox is inside the largest's bbox
- fix_poles: bool = False, # collapse 3-3 valence vertex pairs (DC T-junction artifact)
- smooth_iters: int = 0, # Taubin smoothing iterations (low-pass, volume-preserving)
+ sign_mode: str = "udf", # "sdf" | "udf" | "solid"
+ drop_small_components: float = 0.01, # drop components below this fraction of the largest
+ drop_inverted_components: bool = True, # drop inside-out components
+ drop_enclosed_components: bool = True, # drop components inside the largest one
+ fix_poles: bool = False, # collapse adjacent valence-3 vertex pairs
+ smooth_iters: int = 0, # Taubin smoothing iterations
smooth_lambda: float = 0.5,
smooth_mu: float = -0.53,
- manifold: bool = False, # Manifold DC: emit 1-4 dual verts per voxel for multi-sheet cases
+ manifold: bool = False, # Manifold DC, sdf mode only
+ fill: float = 20.0, # solid: cost factor for closing openings through open space
colors: Optional[torch.Tensor] = None,
scale: Optional[float] = None,
center: Optional[torch.Tensor] = None,
):
- """Narrow-band Dual Contouring re-extraction; returns (new_vertices, new_faces, new_colors), new_colors None unless `colors` given.
+ """Narrow-band dual contouring remesh; returns (vertices, faces, colors), colors None unless `colors` is given.
- Key params: target_faces>0 auto-derives resolution; sign_mode sdf/udf
- (UDF disables qef and may need component filters); project_back lerps verts
- toward the closest surface point; scale/center default to bbox.
+ sign_mode "sdf" signs corners by the nearest face normal, "udf" contours the unsigned distance at eps (closed inputs
+ also give an inner shell for the component filters to drop), "solid" signs them by a graph cut that closes small openings
+ and erodes the eps offset back to half a cell: a closing, so creases are filleted and gaps bridged at eps while the
+ surface sits half a cell outside the input.
"""
assert vertices.ndim == 2 and vertices.shape[1] == 3
assert faces.ndim == 2 and faces.shape[1] == 3
@@ -952,28 +1049,28 @@ def remesh_narrow_band_dc(
bbox = vertices.max(dim=0)[0] - vertices.min(dim=0)[0]
scale = float(bbox.max().item()) * 1.1
- # Auto-derive resolution from target_faces (~3 tris/crossing-voxel; +-30%)
+ # resolution from target_faces, at ~3 triangles per surface voxel
if target_faces > 0:
tv = vertices[faces.long()]
cross_v = torch.cross(tv[:, 1] - tv[:, 0], tv[:, 2] - tv[:, 0], dim=-1)
surface_area = 0.5 * cross_v.norm(dim=-1).sum().item()
relative_area = max(surface_area / (scale * scale), 1e-6)
derived = int(math.sqrt(target_faces / (3.0 * relative_area)))
- # Round to a multiple of 32 (builder doubles from a <=32 base)
+ # multiple of 32: the band builder doubles up from a base <= 32
derived = ((derived + 31) // 32) * 32
derived = max(32, min(1024, derived))
resolution = derived
eps = band * scale / resolution
- # progress: one tick per narrow-band level + 3 stages (SDF/DC/post) + each smoothing iter
+ # ticks: one per narrow-band level, SDF, DC, post-process, each smoothing iter, and 2 more in solid mode
n_levels, _b = 1, resolution
while _b > 32 and _b % 2 == 0:
_b //= 2
while _b < resolution:
_b *= 2
n_levels += 1
- _total_ticks = n_levels + 3 + int(smooth_iters)
+ _total_ticks = n_levels + 3 + int(smooth_iters) + (2 if sign_mode == "solid" else 0)
_pbar = comfy.utils.ProgressBar(_total_ticks)
_tq = _tqdm(total=_total_ticks, desc="Remesh DC", leave=False)
@@ -981,9 +1078,12 @@ def remesh_narrow_band_dc(
_pbar.update(1)
_tq.update(1)
- # Step 1: sparse narrow-band voxel grid (coarse-to-fine)
+ # Distance queries run on triangles no longer than a few cells; tri_src maps back to `faces`
+ tri_verts_g, tri_src = _split_long_triangles(vertices[faces.long()], 4.0 * scale / resolution)
+
+ # Step 1: narrow-band voxels
voxel_coords, _band_tree = _build_narrow_band_voxels(
- vertices, faces, center, scale, resolution, eps,
+ tri_verts_g, center, scale, resolution, eps,
progress_callback=tick)
if voxel_coords.numel() == 0:
return (torch.empty((0, 3), dtype=vertices.dtype, device=device),
@@ -991,38 +1091,32 @@ def remesh_narrow_band_dc(
None if colors is None else torch.empty((0, colors.shape[1]),
dtype=colors.dtype, device=device))
- # Step 2: collect unique corner positions of all active voxels
- CORNER_OFFS = torch.tensor([
- [0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0],
- [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1],
- ], dtype=torch.long, device=device)
- corners = (voxel_coords.unsqueeze(1) + CORNER_OFFS.unsqueeze(0)).reshape(-1, 3)
- R1 = resolution + 1
- corner_keys = (corners[:, 0] * R1 + corners[:, 1]) * R1 + corners[:, 2]
- unique_corner_keys, corner_inv = torch.unique(corner_keys, return_inverse=True)
- unique_corners = torch.zeros((unique_corner_keys.shape[0], 3), dtype=torch.long, device=device)
- unique_corners[corner_inv] = corners
- del corners, corner_keys, corner_inv
-
- if sign_mode == "sdf":
- use_sdf = True
- elif sign_mode == "udf":
- use_sdf = False
- else:
- raise ValueError(f"sign_mode must be 'sdf'|'udf', got {sign_mode!r}")
+ if sign_mode not in ("sdf", "udf", "solid"):
+ raise ValueError(f"sign_mode must be 'sdf'|'udf'|'solid', got {sign_mode!r}")
+ use_sdf = sign_mode == "sdf"
+
+ # Step 2: the band as sorted voxel keys, and its unique corners
+ CORNER_OFFS = torch.tensor(_CUBE_CORNERS, dtype=torch.long, device=device)
+ corner_key_offs = _voxel_key(CORNER_OFFS, resolution)
+ vox_keys = _voxel_key(voxel_coords, resolution).sort().values
+ del voxel_coords
+
+ def corner_world_of(keys):
+ return (_decode_key(keys, resolution).float() / resolution - 0.5) * scale + center
+
+ # a voxel's 8 corner keys are mostly its neighbours' too: dedupe per chunk before the unique over all of them
+ unique_corner_keys = torch.unique(torch.cat([torch.unique(vox_keys[s:s + _VOXEL_CHUNK, None] + corner_key_offs)
+ for s in range(0, vox_keys.numel(), _VOXEL_CHUNK)]))
+ corner_world = corner_world_of(unique_corner_keys)
- # Step 3: distance field at every unique corner.
- tri_verts_g = vertices[faces.long()]
- # face normals: needed for the SDF sign AND for QEF placement (QEF is sign-agnostic,
- # so it works in UDF mode too — (n·(x-p))² is unchanged by normal orientation)
+ # Step 3: signed field at the corners
+ # normals feed the SDF sign and QEF; QEF ignores their orientation, so it works in every sign mode
if use_sdf or qef:
tri_face_normals_all = torch.nn.functional.normalize(
torch.cross(tri_verts_g[:, 1] - tri_verts_g[:, 0],
tri_verts_g[:, 2] - tri_verts_g[:, 0], dim=-1),
p=2, dim=-1, eps=1e-12)
cell_size = scale / resolution
- corner_world = (unique_corners.float() / resolution - 0.5) * scale + center.unsqueeze(0)
- # Exact corner UDF (no max_dist cap) so DC crossings keep fine detail
udf, corner_closest, corner_tri = _udf_exact(corner_world, tri_verts_g, tree=_band_tree)
corner_valid = corner_tri >= 0
if use_sdf:
@@ -1032,73 +1126,127 @@ def remesh_narrow_band_dc(
sign_dot = (offset * n_for_corner).sum(-1)
sign = torch.where(corner_valid & (sign_dot < 0), -sign, sign)
sdf = sign * udf
- else:
- # UDF mode: iso at UDF=eps; double surface on closed meshes, weld after
+ del sign, n_for_corner, offset, sign_dot, corner_world, udf, corner_closest, corner_tri
+ elif sign_mode == "udf":
sdf = udf - eps
- del unique_corners, corner_world, udf, corner_closest, corner_tri
- if use_sdf:
- del sign, n_for_corner, offset, sign_dot
+ del corner_world, udf, corner_closest, corner_tri
+ else:
+ del corner_world, corner_closest, corner_tri # the sign pass re-queries distances per chunk; the shell needs udf
+ # graph-cut a tetrahedralization of the UDF shell into one solid and sign the corners by it
+ shell_v = _dual_contour(vox_keys, udf - eps, unique_corner_keys, resolution, scale, center)[0]
+ del udf
+ tet_pts, tets, nbr, solid, cut_tri = _solid_partition(shell_v, tri_verts_g, _band_tree, eps, fill)
+ locate = _tet_locator(tet_pts, tets, nbr)
+ del shell_v, tet_pts, tets, nbr
+ tick()
+ # where the solid closes an opening its boundary crosses open space: widen the band to it
+ cut_tri = _split_long_triangles(cut_tri, 4.0 * cell_size)[0]
+ cut_coords, cut_tree = _build_narrow_band_voxels(cut_tri, center, scale, resolution, eps)
+ cut_keys = torch.unique(_voxel_key(cut_coords, resolution))
+ del cut_coords
+ pos = torch.searchsorted(vox_keys, cut_keys).clamp(max=vox_keys.numel() - 1)
+ cut_keys = cut_keys[vox_keys[pos] != cut_keys]
+ vox_keys = _merge_sorted(vox_keys, cut_keys)[0]
+
+ def solid_field(points, d, closest):
+ # inside the shell is solid, elsewhere the cut tets decide; they only approximate the shell, so probe one eps further out
+ inside = d < eps
+ out = ~inside
+ p, dd = points[out], d[out]
+ probe = torch.where((dd < 2 * eps)[:, None], p + eps * torch.nn.functional.normalize(p - closest[out], dim=-1), p)
+ tet = locate(probe)
+ inside[out] = (tet >= 0) & solid[tet.clamp(min=0)]
+ # no voxels exist past the grid edge, so the solid has to close before it
+ g = ((points - center) / scale + 0.5) * resolution
+ inside &= ((g > 0.5) & (g < resolution - 0.5)).all(1)
+ # magnitude: offset distance near the input, distance to the cut across closed openings
+ mag = (d - eps).abs()
+ far = d >= 2 * eps
+ mag[far] = _udf_exact(points[far], cut_tri, tree=cut_tree)[0]
+ return torch.where(inside, -1.0, 1.0) * mag.clamp(min=1e-6 * cell_size)
+
+ # the corners of the cut voxels join the band's; the field is evaluated a chunk at a time, distances included
+ new = torch.unique(cut_keys[:, None] + corner_key_offs)
+ del cut_keys
+ pos = torch.searchsorted(unique_corner_keys, new).clamp(max=unique_corner_keys.numel() - 1)
+ unique_corner_keys = _merge_sorted(unique_corner_keys, new[unique_corner_keys[pos] != new])[0]
+ del pos, new
+ field = lambda p: solid_field(p, *_udf_exact(p, tri_verts_g, tree=_band_tree)[:2])
+ sdf = torch.cat([field(corner_world_of(unique_corner_keys[s:s + _POINT_CHUNK]))
+ for s in range(0, unique_corner_keys.numel(), _POINT_CHUNK)])
+ vox_keys, unique_corner_keys, sdf = _close_band(vox_keys, unique_corner_keys, sdf, field, resolution, scale, center)
+ # that surface is the input dilated by eps, which fills creases and gaps; erode it back to half a cell (a closing)
+ erode = eps - 0.5 * cell_size
+ if erode > 0:
+ offset_v, offset_f = _dual_contour(vox_keys, sdf, unique_corner_keys, resolution, scale, center)
+ offset_tri = offset_v[offset_f]
+ offset_tree = _build_udf_tree(offset_tri)
+
+ def eroded(points, sign):
+ val = torch.where(sign < 0, -1.0, 1.0) * _udf_exact(points, offset_tri, tree=offset_tree)[0] + erode
+ return val.masked_fill(val == 0, 1e-6 * cell_size) # a zero crosses for _close_band but not for _dual_contour
+
+ # _close_band left every corner of every voxel in it
+ corner_sdf = torch.cat([eroded(corner_world_of(unique_corner_keys[s:s + _POINT_CHUNK]), sdf[s:s + _POINT_CHUNK])
+ for s in range(0, unique_corner_keys.numel(), _POINT_CHUNK)])
+ vox_keys, unique_corner_keys, sdf = _close_band(
+ vox_keys, unique_corner_keys, corner_sdf,
+ lambda p: eroded(p, solid_field(p, *_udf_exact(p, tri_verts_g, tree=_band_tree)[:2])), resolution, scale, center)
+ del offset_v, offset_f, offset_tri, offset_tree, corner_sdf
+ del locate, solid, cut_tri, cut_tree
+ tick()
tick() # SDF done
- # Step 4 + 5: dual contouring + topology. QEF works in both modes (sign-agnostic);
- # in UDF it pulls the ±eps crossing back onto the triangle planes → sharper edges.
+ # Step 4: dual contouring; QEF fits planes through the offset crossings with the input's normals, keeping creases sharp
if qef:
tri_face_normals = tri_face_normals_all
- # QEF needs the nearest triangle per crossing point. The centroid cKDTree
- # (_band_tree) is already built, and its exact k-NN query is markedly faster
- # here than a spatial-hash gather (which builds ~100-triangle candidate lists
- # per query on a dense input) — and it's exact. So reuse it directly.
def _qef_query(pts):
- return _udf_exact(pts, tri_verts_g, tree=_band_tree)
+ d, closest, tri = _udf_exact(pts, tri_verts_g, tree=_band_tree)
+ if sign_mode == "solid": # crossings on closed openings have no input plane to snap to
+ tri = torch.where(d < 2 * eps, tri, -1)
+ return d, closest, tri
else:
tri_face_normals = None
_qef_query = None
if manifold and use_sdf:
- # MDC ignores qef / tri_face_normals — centroid placement only.
+ # MDC places verts at centroids, no QEF
dual_verts, new_faces = _dual_contour_manifold(
- voxel_coords, sdf, unique_corner_keys,
+ _decode_key(vox_keys, resolution), sdf, unique_corner_keys,
resolution, scale, center,
corner_valid=corner_valid)
else:
dual_verts, new_faces = _dual_contour(
- voxel_coords, sdf, unique_corner_keys,
+ vox_keys, sdf, unique_corner_keys,
resolution, scale, center,
tri_face_normals=tri_face_normals, qef_query=_qef_query,
- # corner_valid filter only matters in SDF mode
+ # corner_valid only matters for sdf
corner_valid=corner_valid if use_sdf else None)
- del voxel_coords, sdf, unique_corner_keys, corner_valid
+ if sign_mode == "solid" and new_faces.numel() > 0:
+ # the closed contour is two-manifold only where one dual vertex carries one sheet
+ new_faces, src_vert = _split_touching_sheets(dual_verts, new_faces)
+ dual_verts = dual_verts[src_vert]
+ del vox_keys, sdf, unique_corner_keys, corner_valid
del tri_face_normals, _qef_query
if use_sdf or qef:
del tri_face_normals_all
tick() # DC done
- # Step 6: project_back and / or color sampling share one closest-point query
+ # Step 5: project_back and color sampling share one closest-point query
need_query = (project_back > 0 or colors is not None) and dual_verts.numel() > 0
out_colors = None
if need_query:
- centroids = tri_verts_g.mean(dim=1)
- tri_radii = (tri_verts_g - centroids.unsqueeze(1)).norm(dim=-1).max(dim=-1).values
- short_hash_cell_t = torch.tensor(2.0 * cell_size, dtype=vertices.dtype, device=device)
- short_hash = _build_tri_spatial_hash(centroids, tri_radii, short_hash_cell_t)
- result = _udf_query(
- dual_verts, tri_verts_g, short_hash, short_hash_cell_t,
- max_dist=4.0 * cell_size,
- return_closest=True,
- return_tri_idx=(colors is not None))
- if colors is not None:
- _, closest_pts, closest_tri = result
- else:
- _, closest_pts = result
+ d, closest_pts, closest_tri = _udf_exact(dual_verts, tri_verts_g, tree=_band_tree)
if project_back > 0:
- dual_verts = torch.lerp(dual_verts, closest_pts, float(project_back))
+ # only verts near the input, not lids over openings closed in solid mode
+ back = (d <= 4.0 * cell_size)[:, None]
+ dual_verts = torch.where(back, torch.lerp(dual_verts, closest_pts, float(project_back)), dual_verts)
if colors is not None:
- # Barycentric-interpolate input colors at the closest point
- safe_tri = closest_tri.clamp(min=0)
- tri_v_idx = faces[safe_tri].long() # (N, 3)
- tri_v = vertices[tri_v_idx] # (N, 3, 3)
+ # barycentric-interpolate the input colors at the closest point
+ tri_v_idx = faces[tri_src[closest_tri]].long()
+ tri_v = vertices[tri_v_idx]
v0 = tri_v[:, 0]
v1 = tri_v[:, 1]
v2 = tri_v[:, 2]
@@ -1118,12 +1266,8 @@ def remesh_narrow_band_dc(
out_colors = (bu.unsqueeze(-1) * tri_c[:, 0]
+ bv.unsqueeze(-1) * tri_c[:, 1]
+ bw.unsqueeze(-1) * tri_c[:, 2])
- # Zero out failed-query rows (their barycentric used bogus triangle 0)
- invalid = closest_tri < 0
- if invalid.any():
- out_colors[invalid] = 0
- # Filter spurious components (tiny pieces, inverted inner shells)
+ # Step 6: post-process
if (new_faces.numel() > 0
and (drop_small_components > 0 or drop_inverted_components
or drop_enclosed_components)):
@@ -1145,7 +1289,7 @@ def remesh_narrow_band_dc(
mu=float(smooth_mu),
progress_callback=tick)
- # Drop unused verts (non-crossing voxels' dual verts) and compact faces
+ # drop dual verts no face uses (voxels without crossings)
if dual_verts.numel() > 0 and new_faces.numel() > 0:
used = torch.zeros(dual_verts.shape[0], dtype=torch.bool, device=device)
used[new_faces[:, 0]] = True
diff --git a/comfy_extras/nodes_mesh_postprocess.py b/comfy_extras/nodes_mesh_postprocess.py
index d730cbff9..e0d59b4cd 100644
--- a/comfy_extras/nodes_mesh_postprocess.py
+++ b/comfy_extras/nodes_mesh_postprocess.py
@@ -7,7 +7,7 @@ import copy
import comfy.utils
import comfy.model_management
from server import PromptServer
-from comfy_extras.mesh3d.postprocess.qem_decimate import QEMConfig, qem_decimate_simplify, qem_cluster_decimate, _compute_vertex_normals
+from comfy_extras.mesh3d.postprocess.qem_decimate import QEMConfig, qem_simplify, qem_cluster_decimate, _compute_vertex_normals, _connected_labels
from comfy_extras.mesh3d.postprocess.remesh import remesh_narrow_band_dc, _point_tri_closest
from comfy_extras.nodes_save_3d import get_mesh_batch_item, pack_variable_mesh_batch
from comfy_extras.mesh3d.uv_unwrap import mesh as _uv_mesh
@@ -1940,19 +1940,8 @@ def _fill_holes_v2_gpu(verts, faces, max_perimeter, colors=None, fill_chains=Fal
src = b_directed[:, 0].long()
tgt = b_directed[:, 1].long()
- # Undirected bidirectional min-prop with path compression.
- labels = torch.arange(V, dtype=torch.long, device=device)
- for _ in range(64):
- edge_min = torch.minimum(labels[src], labels[tgt])
- new_labels = labels.clone()
- new_labels.scatter_reduce_(0, src, edge_min, reduce="amin", include_self=True)
- new_labels.scatter_reduce_(0, tgt, edge_min, reduce="amin", include_self=True)
- new_labels = new_labels[new_labels] # path compression
- if torch.equal(new_labels, labels):
- break
- labels = new_labels
-
- # After bidir-prop, labels[src] == labels[tgt], so labels[src] is the edge's component.
+ labels = _connected_labels(torch.stack([src, tgt], 1), V)
+ # labels[src] == labels[tgt], so labels[src] is the edge's component
edge_component = labels[src]
unique_components, component_idx = torch.unique(edge_component, return_inverse=True)
L = unique_components.shape[0]
@@ -2349,7 +2338,7 @@ class DecimateMesh(IO.ComfyNode):
counts["in"] += int(f.shape[0])
if target_face_count > 0 and f.shape[0] > target_face_count:
src_device = v.device
- rv, rf, rc, _rn, _rs = qem_decimate_simplify(
+ rv, rf, rc = qem_simplify(
v.to(compute_device), f.to(compute_device), int(target_face_count),
colors=(c.to(compute_device) if c is not None else None),
config=cfg)
@@ -2377,7 +2366,8 @@ class RemeshMesh(IO.ComfyNode):
sign_mode_options = [
IO.DynamicCombo.Option(key="udf", inputs=[
IO.Boolean.Input("qef", default=False, advanced=True,
- tooltip="QEF (Quadratic Error Function) dual-vertex placement for sharper edges."),
+ tooltip="QEF (Quadratic Error Function) vertex placement: sharp edges on hard-surface input, "
+ "jagged creases on organic input."),
IO.Boolean.Input("drop_inverted_components", default=False, advanced=True,
tooltip="Drop inward-normal (negative-volume) closed components — the UDF inner shell."),
IO.Boolean.Input("drop_enclosed_components", default=False, advanced=True,
@@ -2389,6 +2379,14 @@ class RemeshMesh(IO.ComfyNode):
IO.Boolean.Input("manifold", default=False,
tooltip="Manifold Dual Contouring: 1-4 dual verts/voxel for multi-sheet cases. Slower."),
]),
+ IO.DynamicCombo.Option(key="solid", inputs=[
+ IO.Float.Input("fill", default=20.0, min=0.0, max=1000.0, step=1.0,
+ tooltip="Cost of closing an opening relative to following the surface. Lower closes "
+ "larger openings (0 puts a lid on a cup); higher only closes small holes and cracks."),
+ IO.Boolean.Input("qef", default=False, advanced=True,
+ tooltip="QEF (Quadratic Error Function) vertex placement: sharp edges on hard-surface input, "
+ "jagged creases on organic input."),
+ ]),
]
return IO.Schema(
node_id="RemeshMesh",
@@ -2407,9 +2405,12 @@ class RemeshMesh(IO.ComfyNode):
"For an exact face count, follow with Decimate Mesh."),
IO.DynamicCombo.Input("sign_mode", options=sign_mode_options, display_name="sign_mode",
tooltip="udf: robust to messy/non-manifold input. sdf: clean single "
- "surface with QEF (Quadratic Error Function) sharp-feature recovery, but needs consistent winding."),
+ "surface with QEF (Quadratic Error Function) sharp-feature recovery, but needs consistent winding. "
+ "solid: one watertight solid from messy input: a global inside/outside graph cut "
+ "(CelloCut) removes double shells and closes small holes. Slower."),
IO.Float.Input("band", default=1.0, min=0.5, max=4.0, step=0.1, advanced=True,
- tooltip="Narrow-band width in voxel units. In UDF mode also offsets the surface."),
+ tooltip="Narrow-band width in voxel units. In udf mode also offsets the surface; in solid mode it is the "
+ "closing radius: creases are filleted and gaps bridged at this size, the surface sits half a voxel out."),
IO.Float.Input("project_back", default=0.0, min=0.0, max=1.0, step=0.05, advanced=True,
tooltip="Linearly interpolate vertices toward the original surface (0 = pure DC, 1 = snapped)."),
IO.Boolean.Input("fix_poles", default=False, advanced=True,
@@ -2431,10 +2432,11 @@ class RemeshMesh(IO.ComfyNode):
drop_small_components, precluster_max_verts):
mode = sign_mode.get("sign_mode", "udf")
# mode-specific sub-widgets (absent → defaults)
- qef = bool(sign_mode.get("qef", True))
+ qef = bool(sign_mode.get("qef", mode == "sdf"))
manifold = bool(sign_mode.get("manifold", False))
drop_inverted_components = bool(sign_mode.get("drop_inverted_components", False))
drop_enclosed_components = bool(sign_mode.get("drop_enclosed_components", False))
+ fill = float(sign_mode.get("fill", 20.0))
# ComfyUI passes meshes on CPU (remesh far faster on GPU); compute on device, return on original.
compute_device = comfy.model_management.get_torch_device()
@@ -2463,7 +2465,7 @@ class RemeshMesh(IO.ComfyNode):
resolution=int(resolution),
band=float(band), project_back=float(project_back),
qef=qef, sign_mode=mode,
- manifold=manifold, fix_poles=bool(fix_poles),
+ manifold=manifold, fill=fill, fix_poles=bool(fix_poles),
smooth_iters=int(smooth_iters),
drop_small_components=float(drop_small_components),
drop_inverted_components=drop_inverted_components,