Spike boolean-weld round 4: spade CDT, slide onto the seam, no loop snapping, facet CDT, add mode, UV0 carry-through
- Driver: `cdt` subcommand over spade 2.15.1 (MIT OR Apache-2.0), interior Steiner points only, constraint edges never split; union op for add mode. - round4.py replaces round3.py and its Triangle (Shewchuk) dependency. - owner_weld.py: the 'snap' merge kind and its knobs are cut (weld-path-fixed). - Slide: a hull vertex within the bevel width of the loop slides inside its own surface onto it and the loop vertices its edges made merge into it, joint on both pieces; guards judge the compound end state. - Brush facets trimmed by the hull are re-triangulated in their plane; a variant splits long brush edges. - Flips never cross a UV0 seam; every output face is matched to its operand face and takes UVs by interpolation. - Blender script reads UVs, renders a UV grid and measures bevel strip UVs with bmesh.ops.bevel. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
db2c162a79
commit
50993e4ed3
13 changed files with 7180 additions and 337 deletions
69
spikes/boolean-weld/Cargo.lock
generated
69
spikes/boolean-weld/Cargo.lock
generated
|
|
@ -2,6 +2,18 @@
|
|||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "allocator-api2"
|
||||
version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "boolmesh"
|
||||
version = "0.2.1"
|
||||
|
|
@ -30,18 +42,41 @@ dependencies = [
|
|||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "glam"
|
||||
version = "0.32.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f70749695b063ecbf6b62949ccccde2e733ec3ecbbd71d467dca4e5c6c97cca0"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.16.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
|
||||
dependencies = [
|
||||
"allocator-api2",
|
||||
"equivalent",
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.34"
|
||||
|
|
@ -68,6 +103,15 @@ dependencies = [
|
|||
"cmake",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
|
|
@ -86,18 +130,43 @@ dependencies = [
|
|||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "robust"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e27ee8bb91ca0adcf0ecb116293afa12d393f9c2b9b9cd54d33e8078fe19839"
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.16.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b"
|
||||
|
||||
[[package]]
|
||||
name = "spade"
|
||||
version = "2.15.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9699399fd9349b00b184f5635b074f9ec93afffef30c853f8c875b32c0f8c7fa"
|
||||
dependencies = [
|
||||
"hashbrown",
|
||||
"num-traits",
|
||||
"robust",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spike-boolean-weld"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"boolmesh",
|
||||
"manifold-csg",
|
||||
"spade",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ manifold = ["dep:manifold-csg"]
|
|||
[dependencies]
|
||||
manifold-csg = { version = "=0.4.1", optional = true }
|
||||
boolmesh = "=0.2.1"
|
||||
# Round 4: constrained Delaunay for created faces (MIT OR Apache-2.0), replacing Shewchuk's Triangle.
|
||||
spade = "=2.15.1"
|
||||
|
||||
[profile.release]
|
||||
debug = false
|
||||
|
|
|
|||
20
spikes/boolean-weld/cutters/add_box_flank.obj
Normal file
20
spikes/boolean-weld/cutters/add_box_flank.obj
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
v 0.201069627 -0.000045536 0.078752425
|
||||
v 0.207746278 0.008569293 0.117238877
|
||||
v 0.172253320 -0.038568992 0.092374606
|
||||
v 0.178929972 -0.029954163 0.130861059
|
||||
v 0.161070028 0.029954163 0.078976428
|
||||
v 0.167746680 0.038568992 0.117462880
|
||||
v 0.132253722 -0.008569293 0.092598609
|
||||
v 0.138930373 0.000045536 0.131085062
|
||||
f 1 2 4
|
||||
f 5 7 8
|
||||
f 1 5 6
|
||||
f 3 4 8
|
||||
f 1 3 7
|
||||
f 2 6 8
|
||||
f 1 4 3
|
||||
f 5 8 6
|
||||
f 1 6 2
|
||||
f 3 8 7
|
||||
f 1 7 5
|
||||
f 2 8 4
|
||||
6146
spikes/boolean-weld/cutters/add_cyl_flank_ref.obj
Normal file
6146
spikes/boolean-weld/cutters/add_cyl_flank_ref.obj
Normal file
File diff suppressed because it is too large
Load diff
98
spikes/boolean-weld/cutters/add_cyl_flank_s16.obj
Normal file
98
spikes/boolean-weld/cutters/add_cyl_flank_s16.obj
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
v 0.166661674 0.010330357 0.082398990
|
||||
v 0.161001952 0.009425415 0.083583404
|
||||
v 0.156203872 0.006429774 0.085086324
|
||||
v 0.152997897 0.001799493 0.086678943
|
||||
v 0.151872108 -0.003760509 0.088118800
|
||||
v 0.152997897 -0.009403773 0.089186688
|
||||
v 0.156203872 -0.014271162 0.089720033
|
||||
v 0.161001952 -0.017621661 0.089637637
|
||||
v 0.166661674 -0.018945187 0.088952044
|
||||
v 0.172321396 -0.018040245 0.087767630
|
||||
v 0.177119477 -0.015044603 0.086264710
|
||||
v 0.180325452 -0.010414323 0.084672091
|
||||
v 0.181451240 -0.004854321 0.083232234
|
||||
v 0.180325452 0.000788943 0.082164346
|
||||
v 0.177119477 0.005656332 0.081631001
|
||||
v 0.172321396 0.009006831 0.081713397
|
||||
v 0.173338326 0.018945187 0.120885442
|
||||
v 0.167678604 0.018040245 0.122069857
|
||||
v 0.162880523 0.015044603 0.123572777
|
||||
v 0.159674548 0.010414323 0.125165396
|
||||
v 0.158548760 0.004854321 0.126605252
|
||||
v 0.159674548 -0.000788943 0.127673141
|
||||
v 0.162880523 -0.005656332 0.128206486
|
||||
v 0.167678604 -0.009006831 0.128124090
|
||||
v 0.173338326 -0.010330357 0.127438497
|
||||
v 0.178998048 -0.009425415 0.126254082
|
||||
v 0.183796128 -0.006429774 0.124751163
|
||||
v 0.187002103 -0.001799493 0.123158544
|
||||
v 0.188127892 0.003760509 0.121718687
|
||||
v 0.187002103 0.009403773 0.120650798
|
||||
v 0.183796128 0.014271162 0.120117453
|
||||
v 0.178998048 0.017621661 0.120199849
|
||||
v 0.166661674 -0.004307415 0.085675517
|
||||
v 0.173338326 0.004307415 0.124161970
|
||||
f 1 2 18
|
||||
f 1 18 17
|
||||
f 33 2 1
|
||||
f 34 17 18
|
||||
f 2 3 19
|
||||
f 2 19 18
|
||||
f 33 3 2
|
||||
f 34 18 19
|
||||
f 3 4 20
|
||||
f 3 20 19
|
||||
f 33 4 3
|
||||
f 34 19 20
|
||||
f 4 5 21
|
||||
f 4 21 20
|
||||
f 33 5 4
|
||||
f 34 20 21
|
||||
f 5 6 22
|
||||
f 5 22 21
|
||||
f 33 6 5
|
||||
f 34 21 22
|
||||
f 6 7 23
|
||||
f 6 23 22
|
||||
f 33 7 6
|
||||
f 34 22 23
|
||||
f 7 8 24
|
||||
f 7 24 23
|
||||
f 33 8 7
|
||||
f 34 23 24
|
||||
f 8 9 25
|
||||
f 8 25 24
|
||||
f 33 9 8
|
||||
f 34 24 25
|
||||
f 9 10 26
|
||||
f 9 26 25
|
||||
f 33 10 9
|
||||
f 34 25 26
|
||||
f 10 11 27
|
||||
f 10 27 26
|
||||
f 33 11 10
|
||||
f 34 26 27
|
||||
f 11 12 28
|
||||
f 11 28 27
|
||||
f 33 12 11
|
||||
f 34 27 28
|
||||
f 12 13 29
|
||||
f 12 29 28
|
||||
f 33 13 12
|
||||
f 34 28 29
|
||||
f 13 14 30
|
||||
f 13 30 29
|
||||
f 33 14 13
|
||||
f 34 29 30
|
||||
f 14 15 31
|
||||
f 14 31 30
|
||||
f 33 15 14
|
||||
f 34 30 31
|
||||
f 15 16 32
|
||||
f 15 32 31
|
||||
f 33 16 15
|
||||
f 34 31 32
|
||||
f 16 1 17
|
||||
f 16 17 32
|
||||
f 33 1 16
|
||||
f 34 32 17
|
||||
|
|
@ -341,5 +341,69 @@
|
|||
0.03
|
||||
],
|
||||
"note": "oriented box half-width 0.06"
|
||||
},
|
||||
{
|
||||
"name": "add_box_flank",
|
||||
"kind": "obox",
|
||||
"op": "add",
|
||||
"cutter": "cutters/add_box_flank.obj",
|
||||
"p": [
|
||||
0.17,
|
||||
0.0,
|
||||
0.10491874328928341
|
||||
],
|
||||
"n": [
|
||||
0.16691628816232545,
|
||||
0.2153707407240696,
|
||||
0.9621613153656081
|
||||
],
|
||||
"R": [
|
||||
[
|
||||
-0.7999919715756821,
|
||||
-0.5763261213588748,
|
||||
0.16691628816232545
|
||||
],
|
||||
[
|
||||
0.5999939786817615,
|
||||
-0.770469123057891,
|
||||
0.2153707407240696
|
||||
],
|
||||
[
|
||||
0.004480062508814215,
|
||||
0.27244363133286853,
|
||||
0.9621613153656081
|
||||
]
|
||||
],
|
||||
"lo": [
|
||||
-0.025,
|
||||
-0.025,
|
||||
-0.02
|
||||
],
|
||||
"hi": [
|
||||
0.025,
|
||||
0.025,
|
||||
0.02
|
||||
],
|
||||
"note": "add: oriented box raised panel, half-width 0.025, 0.02 proud"
|
||||
},
|
||||
{
|
||||
"name": "add_cyl_flank_s16",
|
||||
"kind": "cyl",
|
||||
"op": "add",
|
||||
"cutter": "cutters/add_cyl_flank_s16.obj",
|
||||
"p": [
|
||||
0.17,
|
||||
0.0,
|
||||
0.10491874328928341
|
||||
],
|
||||
"n": [
|
||||
0.16691628816232545,
|
||||
0.2153707407240696,
|
||||
0.9621613153656081
|
||||
],
|
||||
"r": 0.015,
|
||||
"seg": 16,
|
||||
"depth": 0.02,
|
||||
"note": "add: 16-segment cylinder boss r 0.015, 0.02 proud, at the gun port"
|
||||
}
|
||||
]
|
||||
31
spikes/boolean-weld/py/case_add.py
Normal file
31
spikes/boolean-weld/py/case_add.py
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
"""Round 4 cases: add mode (union). An oriented box raised panel at the flank box's placement and a 16-segment cylinder
|
||||
boss at the gun port's placement, each half sunk into the hull. Appends to cases.json; writes the cylinder's 1024-segment
|
||||
reference. Usage: case_add.py <cases.json> <cutters-dir>"""
|
||||
import sys, os, json, numpy as np
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from geo import save_obj
|
||||
cf, outd = sys.argv[1:3]
|
||||
cases = [c for c in json.load(open(cf)) if c['op'] != 'add']
|
||||
fl = next(c for c in cases if c['name'] == 'probe_box_flank'); port = next(c for c in cases if c['name'] == 'port_flank_s16')
|
||||
p, R = np.array(fl['p']), np.array(fl['R']); lo, hi = np.array([-0.025, -0.025, -0.02]), np.array([0.025, 0.025, 0.02])
|
||||
Vb = p + np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])]) @ R.T
|
||||
Q = [[0, 1, 3, 2], [4, 6, 7, 5], [0, 4, 5, 1], [2, 3, 7, 6], [0, 2, 6, 4], [1, 5, 7, 3]]
|
||||
Tb = np.array([[q[0], q[1], q[2]] for q in Q] + [[q[0], q[2], q[3]] for q in Q])
|
||||
if np.einsum('ij,ij->i', Vb[Tb[:, 0]], np.cross(Vb[Tb[:, 1]], Vb[Tb[:, 2]])).sum() < 0: Tb = Tb[:, ::-1]
|
||||
save_obj(f'{outd}/add_box_flank.obj', Vb, Tb)
|
||||
cases.append(dict(name='add_box_flank', kind='obox', op='add', cutter=f'{outd}/add_box_flank.obj', p=p.tolist(), n=fl['n'], R=R.tolist(),
|
||||
lo=lo.tolist(), hi=hi.tolist(), note='add: oriented box raised panel, half-width 0.025, 0.02 proud'))
|
||||
pc, n = np.array(port['p']), np.array(port['n']) / np.linalg.norm(port['n'])
|
||||
e1 = np.cross(n, [1, 0, 0] if abs(n[0]) < .9 else [0, 1, 0]); e1 /= np.linalg.norm(e1); e2 = np.cross(n, e1)
|
||||
for seg in (16, 1024):
|
||||
ang = np.arange(seg) * 2 * np.pi / seg; ring = np.cos(ang)[:, None] * e1 + np.sin(ang)[:, None] * e2
|
||||
Vc = np.vstack([pc - 0.02 * n + 0.015 * ring, pc + 0.02 * n + 0.015 * ring, [pc - 0.02 * n], [pc + 0.02 * n]]); cb, ct = 2 * seg, 2 * seg + 1
|
||||
Tc = []
|
||||
for i in range(seg):
|
||||
j = (i + 1) % seg; Tc += [[i, j, seg + j], [i, seg + j, seg + i], [cb, j, i], [ct, seg + i, seg + j]]
|
||||
Tc = np.array(Tc)
|
||||
if np.einsum('ij,ij->i', Vc[Tc[:, 0]], np.cross(Vc[Tc[:, 1]], Vc[Tc[:, 2]])).sum() < 0: Tc = Tc[:, ::-1]
|
||||
tag = 's16' if seg == 16 else 'ref'; save_obj(f'{outd}/add_cyl_flank_{tag}.obj', Vc, Tc)
|
||||
cases.append(dict(name='add_cyl_flank_s16', kind='cyl', op='add', cutter=f'{outd}/add_cyl_flank_s16.obj', p=pc.tolist(), n=n.tolist(), r=0.015, seg=16,
|
||||
depth=0.02, note='add: 16-segment cylinder boss r 0.015, 0.02 proud, at the gun port'))
|
||||
json.dump(cases, open(cf, 'w'), indent=1); print('ok', len(cases))
|
||||
|
|
@ -1,26 +1,20 @@
|
|||
"""Round 2 weld: ruling weld-owner-defines-silhouette. The surface whose own vertices shape the loop owns it
|
||||
(measured as curvature along the loop); its vertices survive, the other surface's spare vertices near the loop
|
||||
merge onto them:
|
||||
"""Owner weld: rulings weld-owner-local-corners-kept and brush-modes-add-subtract-split, target r4. Ownership is local
|
||||
along the loop (curvature along the loop); the owner's vertices survive and the other surface's spare vertices near
|
||||
that stretch merge onto them:
|
||||
- 'loop': a loop vertex made only by the yielding side's edges merges into the nearest owner-made loop vertex.
|
||||
- 'ring' (cutter owns): a hull vertex one ring off the loop merges onto that loop vertex.
|
||||
- 'snap' (hull owns): a loop vertex the boolean inserted on a hull edge, within SNAP local edge lengths of an
|
||||
existing hull vertex, merges INTO that hull vertex (the hull vertex survives where it is).
|
||||
Round 4 cut the 'snap' kind (loop vertex merged into a nearby hull vertex on hull-owned stretches) and its knobs
|
||||
(SNAP, SNAPDIR, NOSNAP_FLAT): target r4's weld-path-fixed forbids snapping the loop on any stretch. Rounds 2 and 3 ran
|
||||
with it; that code is at db2c162.
|
||||
A split is welded jointly: every operation is checked on both pieces and applied only if both accept, so the two
|
||||
pieces' loops stay identical. In the piece that lacks the surviving hull vertex, the loop vertex moves to it.
|
||||
Guards (both pieces): no face flip, worst angle not driven below MIN_ANGLE, edge exists, link condition."""
|
||||
pieces' loops stay identical. Guards (both pieces): no face flip, worst angle not driven below MIN_ANGLE, edge exists,
|
||||
link condition. Corners (sharp cutter edge or hull crease on the loop) are never a merge source and never moved."""
|
||||
import os, numpy as np
|
||||
from collections import defaultdict
|
||||
from scipy.spatial import cKDTree
|
||||
from weld import analyse_loops, loops_of, angles
|
||||
|
||||
MIN_ANGLE = float(os.environ.get('MIN_ANGLE', '10'))
|
||||
SNAP = float(os.environ.get('SNAP', '0.25'))
|
||||
# SNAPDIR=reverse: the hull vertex slides onto the loop vertex instead (the loop stays on the cutter; spike variant)
|
||||
SNAPDIR = os.environ.get('SNAPDIR', 'loop-to-hull')
|
||||
# Round 3 (ruling weld-owner-local-corners-kept + Self's calls): no snapping where the cutter is planar (the seam stays on
|
||||
# the cutter's plane), and feature corners on the loop always survive: loop vertices on a sharp cutter edge (dihedral
|
||||
# > CORNER_DEG) or on a hull crease edge are never a merge source and never moved.
|
||||
NOSNAP_FLAT = os.environ.get('NOSNAP_FLAT', '0') == '1'
|
||||
CORNER_DEG = 30.0
|
||||
|
||||
|
||||
|
|
@ -114,7 +108,7 @@ class Piece:
|
|||
return s.V, np.array([s.faces[i] for i in keep]), np.array([s.prov[i] for i in keep])
|
||||
|
||||
|
||||
def candidates(P, info, loops, hull, tol, scope_ring=True, cut_is_flat=False):
|
||||
def candidates(P, info, loops, hull, tol, scope_ring=True):
|
||||
"""Operations as (dist, v_pos, w_pos, kind): v merges into w."""
|
||||
cand = []; loopset = set(info)
|
||||
for L in loops:
|
||||
|
|
@ -139,12 +133,6 @@ def candidates(P, info, loops, hull, tol, scope_ring=True, cut_is_flat=False):
|
|||
d = np.linalg.norm(P.V[x] - P.V[v])
|
||||
if own == 1 and scope_ring:
|
||||
cand.append((d, P.V[x].copy(), P.V[v].copy(), 'ring'))
|
||||
elif own == 0 and not (NOSNAP_FLAT and cut_is_flat) and inf['origin'] == 'H' and hull.kd.query(P.V[v])[0] > tol and hull.kd.query(P.V[x])[0] < tol:
|
||||
if d < SNAP * hull.vlen[hull.kd.query(P.V[x])[1]]:
|
||||
if SNAPDIR == 'reverse':
|
||||
cand.append((d, P.V[x].copy(), P.V[v].copy(), 'snap'))
|
||||
else:
|
||||
cand.append((d, P.V[v].copy(), P.V[x].copy(), 'snap'))
|
||||
return cand
|
||||
|
||||
|
||||
|
|
@ -155,7 +143,7 @@ def owner_weld(pieces, hull, cut, tol):
|
|||
cand = []; corners = []
|
||||
for P in Ps:
|
||||
loops, le, info = analyse_loops(P.V, np.array([f for f in P.faces]), np.array(P.prov), hull, cut, 'along', tol)
|
||||
infos.append((loops, info)); cand += candidates(P, info, loops, hull, tol, cut_is_flat=cut.kind in ('box', 'obox'))
|
||||
infos.append((loops, info)); cand += candidates(P, info, loops, hull, tol)
|
||||
corners.extend(corners_of(P, info, hull, cut, tol))
|
||||
cand.sort(key=lambda z: z[0])
|
||||
stats = defaultdict(int); done = []; seen = set()
|
||||
|
|
@ -172,7 +160,7 @@ def owner_weld(pieces, hull, cut, tol):
|
|||
if v is None:
|
||||
if w is None:
|
||||
continue
|
||||
if kind == 'loop' or (kind == 'snap' and SNAPDIR != 'reverse'):
|
||||
if kind == 'loop':
|
||||
reason = 'gone'; break # the loop vertex is already gone in this piece
|
||||
continue
|
||||
if w is not None:
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
"""Headless Blender: apply the shipped stack (Bevel 1 segment weight-limited 0.001 + Weighted Normal, settings copied
|
||||
from the cage's own modifiers) to naive and welded boolean results and render them. Run on a COPY of Ships.blend:
|
||||
blender -b Ships_copy.blend --python render_blender.py -- <weld-dir> <out-dir> <jobs.txt>
|
||||
jobs.txt lines: <png-name> <ortho-scale> <dx> <dy> <dz> <mesh-stem>[,<mesh-stem>...] [tubes]"""
|
||||
import bpy, bmesh, sys, os
|
||||
jobs.txt lines: <png-name> <ortho-scale> <dx> <dy> <dz> <mesh-stem>[,<mesh-stem>...] [tubes] [uvgrid]
|
||||
Round 4: reads per-corner UVs (vt); 'uvgrid' renders a UV-grid texture view; for every mesh built it measures the bevel
|
||||
strips' UVs with bmesh.ops.bevel (the BM bevel the modifier runs) with the modifier's settings on the weighted edges,
|
||||
whose new faces are the strips; written to <out-dir>/bevel_uv.json."""
|
||||
import bpy, bmesh, sys, os, json, math
|
||||
from mathutils import Vector, kdtree
|
||||
from mathutils.geometry import intersect_point_line
|
||||
|
||||
|
|
@ -14,26 +17,11 @@ wn_src = next(m for m in cage.modifiers if m.type == 'WEIGHTED_NORMAL')
|
|||
for m in cage.modifiers:
|
||||
if m.type in ('BEVEL', 'WEIGHTED_NORMAL'):
|
||||
m.show_viewport = False
|
||||
dg = bpy.context.evaluated_depsgraph_get()
|
||||
me = cage.evaluated_get(dg).to_mesh()
|
||||
att = me.attributes.get('bevel_weight_edge')
|
||||
segs = []
|
||||
for e in me.edges:
|
||||
w = att.data[e.index].value if att else 0.0
|
||||
if w > 0:
|
||||
segs.append((cage.matrix_world @ me.vertices[e.vertices[0]].co, cage.matrix_world @ me.vertices[e.vertices[1]].co, w))
|
||||
print('CAGE clamp_overlap', bev_src.use_clamp_overlap, 'harden', bev_src.harden_normals, 'WN', wn_src.mode, wn_src.keep_sharp, 'weighted edges', len(segs), 'smooth', [p.use_smooth for p in me.polygons][:1])
|
||||
# Diagnostic: compare the cage's bevel-weight edges with the crease edges exported with the hull fixture.
|
||||
print('CAGE clamp_overlap', bev_src.use_clamp_overlap, 'width', bev_src.width, 'offset_type', bev_src.offset_type, 'WN', wn_src.mode, wn_src.keep_sharp)
|
||||
# Hull crease edges, exported with the hull fixture, carry bevel weight 1 (they equal the cage's bevel-weight edges, round 1).
|
||||
fx = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'fixtures')
|
||||
HV = [Vector(tuple(map(float, l.split()[1:4]))) for l in open(fx + '/hull_nobevel.obj') if l.startswith('v ')]
|
||||
csegs = [(HV[int(a)], HV[int(b)]) for a, b in (l.split() for l in open(fx + '/hull_creases.txt') if l.strip())]
|
||||
ck = kdtree.KDTree(len(csegs))
|
||||
for i, (a, b) in enumerate(csegs):
|
||||
ck.insert((a + b) / 2, i)
|
||||
ck.balance()
|
||||
dmax = max((ck.find((a + b) / 2)[2] for a, b, w in segs), default=0)
|
||||
print('BEVEL-vs-CREASE max midpoint distance', dmax, 'weights', sorted({round(w, 3) for a, b, w in segs}))
|
||||
segs = [(a, b, 1.0) for a, b in csegs]
|
||||
segs = [(HV[int(a)], HV[int(b)], 1.0) for a, b in (l.split() for l in open(fx + '/hull_creases.txt') if l.strip())]
|
||||
kd = kdtree.KDTree(len(segs))
|
||||
for i, (a, b, w) in enumerate(segs):
|
||||
kd.insert((a + b) / 2, i)
|
||||
|
|
@ -44,7 +32,6 @@ scene = bpy.data.scenes.new('spike')
|
|||
bpy.context.window.scene = scene
|
||||
scene.render.engine = 'BLENDER_WORKBENCH'
|
||||
scene.display.shading.light = 'STUDIO'
|
||||
scene.display.shading.color_type = 'MATERIAL'
|
||||
scene.display.shading.show_specular_highlight = True
|
||||
scene.render.resolution_x = scene.render.resolution_y = 700
|
||||
scene.world = bpy.data.worlds.new('w')
|
||||
|
|
@ -53,29 +40,88 @@ cam.data.type = 'ORTHO'
|
|||
scene.collection.objects.link(cam)
|
||||
scene.camera = cam
|
||||
grey = bpy.data.materials.new('grey'); grey.diffuse_color = (0.75, 0.75, 0.78, 1)
|
||||
cmat = bpy.data.materials.new('cut'); cmat.diffuse_color = (0.62, 0.66, 0.75, 1)
|
||||
own = [bpy.data.materials.new('own_hull'), bpy.data.materials.new('own_cutter'), bpy.data.materials.new('own_none')]
|
||||
own[0].diffuse_color = (0.1, 0.35, 1.0, 1); own[1].diffuse_color = (1.0, 0.45, 0.05, 1); own[2].diffuse_color = (0.2, 0.2, 0.2, 1)
|
||||
grid = bpy.data.images.new('grid', 1024, 1024); grid.generated_type = 'UV_GRID'
|
||||
gmat = bpy.data.materials.new('uvgrid'); gmat.use_nodes = True
|
||||
tex = gmat.node_tree.nodes.new('ShaderNodeTexImage'); tex.image = grid; gmat.node_tree.nodes.active = tex
|
||||
bsdf = gmat.node_tree.nodes.get('Principled BSDF')
|
||||
if bsdf:
|
||||
gmat.node_tree.links.new(tex.outputs['Color'], bsdf.inputs['Base Color'])
|
||||
MEAS = {}
|
||||
|
||||
|
||||
def load(stem):
|
||||
V, F = [], []
|
||||
V, F, VT, FT = [], [], [], []
|
||||
for line in open(f'{wd}/{stem}.obj'):
|
||||
s = line.split()
|
||||
if s and s[0] == 'v':
|
||||
V.append(tuple(map(float, s[1:4])))
|
||||
elif s and s[0] == 'vt':
|
||||
VT.append(tuple(map(float, s[1:3])))
|
||||
elif s and s[0] == 'f':
|
||||
F.append(tuple(int(x) - 1 for x in s[1:]))
|
||||
F.append(tuple(int(x.split('/')[0]) - 1 for x in s[1:]))
|
||||
FT.append(tuple(int(x.split('/')[1]) - 1 for x in s[1:]) if '/' in s[1] else None)
|
||||
loop = [tuple(map(int, l.split())) for l in open(f'{wd}/{stem}.loop') if l.strip()]
|
||||
return V, F, loop
|
||||
return V, F, loop, VT, FT
|
||||
|
||||
|
||||
def build(stem, tubes):
|
||||
V, F, loop = load(stem)
|
||||
def bevel_uv(m, bev):
|
||||
"""Strip faces from bmesh.ops.bevel on the weighted edges (all weights are 1 here), with the modifier's settings.
|
||||
Per strip: singular values of its 3D-to-UV map in units of the mesh's median hull density, and which charts its
|
||||
corners lie in (hull UVs at u < 2.5, brush UVs at u >= 3)."""
|
||||
bm = bmesh.new(); bm.from_mesh(m)
|
||||
bw = bm.edges.layers.float.get('bevel_weight_edge'); uvl = bm.loops.layers.uv.active
|
||||
if uvl is None:
|
||||
bm.free(); return None
|
||||
|
||||
def tri_sig(P, Q):
|
||||
e1, e2 = P[1] - P[0], P[2] - P[0]; n = e1.cross(e2)
|
||||
if e1.length < 1e-15 or n.length < 1e-18:
|
||||
return 0.0, 0.0
|
||||
x = e1.normalized(); y = n.normalized().cross(x)
|
||||
a11, a12, a21, a22 = e1.dot(x), e2.dot(x), e1.dot(y), e2.dot(y); det = a11 * a22 - a12 * a21
|
||||
b1, b2 = Q[1] - Q[0], Q[2] - Q[0]
|
||||
j11 = (b1.x * a22 - b2.x * a21) / det; j12 = (-b1.x * a12 + b2.x * a11) / det
|
||||
j21 = (b1.y * a22 - b2.y * a21) / det; j22 = (-b1.y * a12 + b2.y * a11) / det
|
||||
t = j11 * j11 + j12 * j12 + j21 * j21 + j22 * j22; dd = abs(j11 * j22 - j12 * j21)
|
||||
r = math.sqrt(max(t * t / 4 - dd * dd, 0))
|
||||
return math.sqrt(max(t / 2 - r, 0)), math.sqrt(max(t / 2 + r, 0))
|
||||
|
||||
def sig(f):
|
||||
ls = f.loops
|
||||
out = [tri_sig([ls[0].vert.co, ls[i].vert.co, ls[i + 1].vert.co], [ls[0][uvl].uv, ls[i][uvl].uv, ls[i + 1][uvl].uv]) for i in range(1, len(ls) - 1)]
|
||||
return min(o[0] for o in out), max(o[1] for o in out)
|
||||
|
||||
dens = sorted(math.sqrt(sig(f)[0] * sig(f)[1]) for f in bm.faces if max(l[uvl].uv.x for l in f.loops) < 2.5 and f.calc_area() > 1e-9)
|
||||
rho = dens[len(dens) // 2]
|
||||
edges = [e for e in bm.edges if bw and e[bw] > 0]
|
||||
res = bmesh.ops.bevel(bm, geom=edges, offset=bev.width, offset_type=bev.offset_type, segments=bev.segments, profile=bev.profile,
|
||||
affect='EDGES', clamp_overlap=bev.use_clamp_overlap, loop_slide=bev.loop_slide, miter_outer=bev.miter_outer.replace('MITER_', ''),
|
||||
miter_inner=bev.miter_inner.replace('MITER_', ''), profile_type='SUPERELLIPSE')
|
||||
rows = []
|
||||
for f in [f for f in res['faces'] if f.is_valid]:
|
||||
us = [l[uvl].uv.x for l in f.loops]; smin, smax = sig(f)
|
||||
rows.append((smin / rho, smax / rho, 'both' if min(us) < 2.5 <= max(us) else ('hull' if max(us) < 2.5 else 'brush')))
|
||||
bm.free()
|
||||
q = lambda xs, p: sorted(xs)[min(len(xs) - 1, int(p * len(xs)))] if xs else None
|
||||
smin = [r[0] for r in rows]; smax = [r[1] for r in rows]
|
||||
return dict(weighted_edges=len(edges), strips=len(rows), spans={k: sum(r[2] == k for r in rows) for k in ('hull', 'brush', 'both')},
|
||||
sigma_min_p5=q(smin, .05), sigma_min_median=q(smin, .5), sigma_max_median=q(smax, .5), sigma_max_p95=q(smax, .95),
|
||||
sigma_max_max=max(smax, default=None), collapsed_lt_0p05=sum(x < 0.05 for x in smin), rho=rho)
|
||||
|
||||
|
||||
def build(stem, tubes, uvgrid=False):
|
||||
V, F, loop, VT, FT = load(stem)
|
||||
used = sorted({i for f in F for i in f}); remap = {o: n for n, o in enumerate(used)}
|
||||
m = bpy.data.meshes.new(stem)
|
||||
m.from_pydata([V[i] for i in used], [], [tuple(remap[i] for i in f) for f in F])
|
||||
m.materials.append(grey)
|
||||
if VT:
|
||||
uvl = m.uv_layers.new(name='UVMap')
|
||||
for poly, ft in zip(m.polygons, FT):
|
||||
for li, ti in zip(poly.loop_indices, ft):
|
||||
uvl.data[li].uv = VT[ti]
|
||||
m.materials.append(gmat if uvgrid else grey)
|
||||
ob = bpy.data.objects.new(stem, m); scene.collection.objects.link(ob)
|
||||
bm = bmesh.new(); bm.from_mesh(m)
|
||||
bw = bm.edges.layers.float.get('bevel_weight_edge') or bm.edges.layers.float.new('bevel_weight_edge')
|
||||
|
|
@ -99,7 +145,7 @@ def build(stem, tubes):
|
|||
f.smooth = True
|
||||
bm.to_mesh(m); bm.free()
|
||||
b = ob.modifiers.new('Bevel', 'BEVEL')
|
||||
for k in ('width', 'segments', 'limit_method', 'offset_type', 'profile', 'harden_normals', 'miter_outer', 'miter_inner', 'clamp_overlap', 'loop_slide'):
|
||||
for k in ('width', 'segments', 'limit_method', 'offset_type', 'profile', 'harden_normals', 'miter_outer', 'miter_inner', 'loop_slide'):
|
||||
if hasattr(bev_src, k):
|
||||
setattr(b, k, getattr(bev_src, k))
|
||||
b.use_clamp_overlap = bev_src.use_clamp_overlap if os.environ.get('CLAMP0') != '1' else False
|
||||
|
|
@ -108,6 +154,8 @@ def build(stem, tubes):
|
|||
if hasattr(wn_src, k):
|
||||
setattr(w, k, getattr(wn_src, k))
|
||||
print('BUILT', stem, 'loop edges', nloop, 'hull weighted edges', nhull)
|
||||
if stem not in MEAS:
|
||||
MEAS[stem] = bevel_uv(m, b); print('BEVELUV', stem, MEAS[stem])
|
||||
objs = [ob]
|
||||
if tubes:
|
||||
cu = bpy.data.curves.new(stem + '_own', 'CURVE'); cu.dimensions = '3D'; cu.bevel_depth = 0.0006
|
||||
|
|
@ -125,10 +173,11 @@ for line in open(jobsf):
|
|||
if not s or s[0].startswith('#'):
|
||||
continue
|
||||
png, scale, d = s[0], float(s[1]), Vector(tuple(map(float, s[2:5]))).normalized()
|
||||
stems = s[5].split(','); tubes = len(s) > 6 and s[6] == 'tubes'
|
||||
stems = s[5].split(','); tubes = 'tubes' in s[6:]; uvgrid = 'uvgrid' in s[6:]
|
||||
scene.display.shading.color_type = 'TEXTURE' if uvgrid else 'MATERIAL'
|
||||
objs, pts = [], []
|
||||
for st in stems:
|
||||
o, p = build(st, tubes); objs += o; pts += p
|
||||
o, p = build(st, tubes, uvgrid); objs += o; pts += p
|
||||
target = max(pts, key=lambda p: p.dot(d)) if s[0].startswith('split') or 'crease' in s[0] else sum(pts, Vector()) / len(pts)
|
||||
cam.location = target + d * 2.0
|
||||
cam.rotation_euler = (-d).to_track_quat('-Z', 'Y').to_euler()
|
||||
|
|
@ -138,4 +187,5 @@ for line in open(jobsf):
|
|||
print('RENDERED', png)
|
||||
for o in objs:
|
||||
bpy.data.objects.remove(o, do_unlink=True)
|
||||
json.dump(MEAS, open(f'{outd}/bevel_uv.json', 'w'), indent=1)
|
||||
print('ALLDONE')
|
||||
|
|
|
|||
|
|
@ -1,280 +0,0 @@
|
|||
"""Round 3 (Self's calls): a flat split keeps its seam exactly on the cutter plane. Hull vertices survive; hull-side
|
||||
slivers along the seam get edge flips only (loop and crease edges constrained); each cap polygon is re-triangulated
|
||||
with a constrained Delaunay (loop as boundary), plain ('p') or with interior-only Steiner refinement ('pq<deg>Y').
|
||||
Usage: round3.py <fixtures> <cases.json> <runs> <out-dir>. Scratch. Uses the `triangle` package (Shewchuk's Triangle)."""
|
||||
import sys, os, json, numpy as np
|
||||
from collections import defaultdict
|
||||
from scipy.spatial import cKDTree
|
||||
import triangle
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from geo import *
|
||||
from weld import Hull, Cutter, loops_of, densify, angles
|
||||
|
||||
fx, casesf, runs, outd = sys.argv[1:5]
|
||||
os.makedirs(outd, exist_ok=True)
|
||||
hull = Hull(fx); TOL = 1e-6 * hull.diag
|
||||
cases = {c['name']: c for c in json.load(open(casesf))}
|
||||
FLIP_DIHEDRAL_COS = np.cos(np.radians(20))
|
||||
|
||||
|
||||
def load_run(name):
|
||||
V, F = load_obj(f'{runs}/boolmesh_{name}.obj'); T = triangulate(F)
|
||||
return V, T, np.array([int(x) for x in open(f'{runs}/boolmesh_{name}.prov').read().split()])
|
||||
|
||||
|
||||
def tri_min_angle(V, t):
|
||||
return min(angles(V[list(t)]))
|
||||
|
||||
|
||||
def flip_hull(V, T, prov, loopedges, band_faces):
|
||||
"""Greedy Delaunay-style flips on hull-provenance faces near the loop. Constrained: loop edges, hull crease edges.
|
||||
A flip must raise the pair's worst angle, keep both normals within 20 deg of the old ones, and not duplicate an edge."""
|
||||
T = [list(t) for t in T]; nflip = 0
|
||||
crease_pos = hull.crease
|
||||
for _ in range(20):
|
||||
ef = defaultdict(list)
|
||||
for fi, t in enumerate(T):
|
||||
for k in range(3):
|
||||
a, b = t[k], t[(k + 1) % 3]; ef[(min(a, b), max(a, b))].append(fi)
|
||||
changed = False
|
||||
for e, fs in ef.items():
|
||||
if len(fs) != 2 or e in loopedges:
|
||||
continue
|
||||
f1, f2 = fs
|
||||
if prov[f1] or prov[f2] or not (f1 in band_faces or f2 in band_faces):
|
||||
continue
|
||||
he = hull.edge_of(V[e[0]], TOL), hull.edge_of(V[e[1]], TOL)
|
||||
if any(h is not None and h in crease_pos for h in he) and he[0] == he[1]:
|
||||
continue
|
||||
a, b = e; c = [x for x in T[f1] if x not in e][0]; d = [x for x in T[f2] if x not in e][0]
|
||||
if (min(c, d), max(c, d)) in ef:
|
||||
continue
|
||||
old = min(tri_min_angle(V, T[f1]), tri_min_angle(V, T[f2]))
|
||||
# keep orientation: T[f1] has a->b in some order; build new faces with the same winding
|
||||
t1 = T[f1]; i = t1.index(c); n1 = [t1[i], t1[(i + 1) % 3], t1[(i + 2) % 3]] # c, p, q
|
||||
p, q = n1[1], n1[2]
|
||||
new1, new2 = [c, p, d], [c, d, q]
|
||||
new = min(tri_min_angle(V, new1), tri_min_angle(V, new2))
|
||||
if new <= old + 1e-9:
|
||||
continue
|
||||
on = [np.cross(V[t[1]] - V[t[0]], V[t[2]] - V[t[0]]) for t in (T[f1], T[f2])]
|
||||
nn = [np.cross(V[t[1]] - V[t[0]], V[t[2]] - V[t[0]]) for t in (new1, new2)]
|
||||
on = [x / np.linalg.norm(x) for x in on]; nn = [x / max(np.linalg.norm(x), 1e-300) for x in nn]
|
||||
if min(o @ n for o in on for n in nn) < FLIP_DIHEDRAL_COS:
|
||||
continue
|
||||
T[f1], T[f2] = new1, new2; nflip += 1; changed = True
|
||||
break # edge map is stale after a flip
|
||||
if not changed:
|
||||
break
|
||||
return np.array(T), nflip
|
||||
|
||||
|
||||
def flip_hull_all(V, T, prov, loopedges, band_faces, cap=4000):
|
||||
total = 0
|
||||
for _ in range(cap // 20):
|
||||
T, n = flip_hull(V, T, prov, loopedges, band_faces); total += n
|
||||
if n == 0:
|
||||
break
|
||||
return T, total
|
||||
|
||||
|
||||
def cdt_caps(V, T, prov, cut, opts):
|
||||
"""Replace every cap (cutter-provenance) face set with a CDT of its boundary loop in the cutter plane."""
|
||||
loops, _ = loops_of(T, prov)
|
||||
capF = np.where(prov == 1)[0]
|
||||
old_n = face_normals(V, T[capF])[0].mean(0)
|
||||
keep = [i for i in range(len(T)) if prov[i] == 0]
|
||||
newV = [V]; newT = []; nv = len(V)
|
||||
for L in loops:
|
||||
P = V[L]; n, _ = cut.frame(P.mean(0))
|
||||
e1 = np.cross(n, [1, 0, 0] if abs(n[0]) < .9 else [0, 1, 0]); e1 /= np.linalg.norm(e1); e2 = np.cross(n, e1)
|
||||
o = P.mean(0); P2 = np.stack([(P - o) @ e1, (P - o) @ e2], 1)
|
||||
seg = np.array([[i, (i + 1) % len(L)] for i in range(len(L))])
|
||||
r = triangle.triangulate({'vertices': P2, 'segments': seg}, opts)
|
||||
rv, rt = r['vertices'], r['triangles']
|
||||
assert np.allclose(rv[:len(L)], P2), 'Triangle moved a boundary vertex'
|
||||
idx = list(L) + list(range(nv, nv + len(rv) - len(L)))
|
||||
if len(rv) > len(L):
|
||||
newV.append(o + rv[len(L):, :1] * e1 + rv[len(L):, 1:2] * e2); nv += len(rv) - len(L)
|
||||
for t in rt:
|
||||
tt = [idx[k] for k in t]; newT.append(tt)
|
||||
V2 = np.vstack(newV); NT = np.array(newT)
|
||||
nn = face_normals(V2, NT)[0].mean(0)
|
||||
if nn @ old_n < 0:
|
||||
NT = NT[:, ::-1]
|
||||
T2 = np.vstack([T[keep], NT]); P2 = np.concatenate([prov[keep], np.ones(len(NT), int)])
|
||||
return V2, T2, P2
|
||||
|
||||
|
||||
def side_measures(V, T, prov, ref_loop_pts, plane=None):
|
||||
loops, le = loops_of(T, prov); lv = sorted({v for L in loops for v in L})
|
||||
h = float(np.median(hull.vlen[hull.kd.query(V[lv])[1]]))
|
||||
kd = cKDTree(densify(V, loops)); cen = V[T].mean(1); inb = kd.query(cen)[0] < 2 * h
|
||||
FN, FA = face_normals(V, T); lmax = np.linalg.norm(V[T] - V[np.roll(T, -1, 1)], axis=2).max(1)
|
||||
sl = (lmax ** 2 / np.maximum(2 * FA, 1e-300) > 10) | (FA < 1e-4 * FA[prov == 0].mean())
|
||||
ang = np.array([tri_min_angle(V, t) for t in T])
|
||||
hs, cs = inb & (prov == 0), prov == 1
|
||||
flips = 0
|
||||
for fi in np.where(hs)[0]:
|
||||
n, _, _ = hull.frame(cen[fi]); flips += int(FN[fi] @ n < 0)
|
||||
out = dict(h=h, hull_band_tris=int(hs.sum()), hull_slivers=int((sl & hs).sum()), hull_min_angle=float(ang[hs].min()),
|
||||
hull_p5=float(np.percentile(ang[hs], 5)), cap_tris=int(cs.sum()), cap_slivers=int((sl & cs).sum()),
|
||||
cap_min_angle=float(ang[cs].min()) if cs.any() else None, flipped_hull=flips,
|
||||
loop_verts=len(lv), loop_to_naive_max=float(cKDTree(ref_loop_pts).query(V[lv])[0].max()))
|
||||
if plane is not None:
|
||||
n, d = plane; out['seam_off_plane_max'] = float(np.abs(V[lv] @ n - d).max())
|
||||
ls = [np.linalg.norm(V[a] - V[b]) for a, b in edge_faces(T) if a in set(lv) or b in set(lv)]
|
||||
out['loop_edges_under_bevel'] = int(sum(l < 0.001 for l in ls))
|
||||
return out
|
||||
|
||||
|
||||
def save(stem, V, T, prov):
|
||||
save_obj(f'{outd}/{stem}.obj', V, T)
|
||||
_, le = loops_of(T, prov)
|
||||
with open(f'{outd}/{stem}.loop', 'w') as f:
|
||||
for a, b in le:
|
||||
f.write(f'{a} {b} 0\n')
|
||||
|
||||
|
||||
def boundary_loops(T):
|
||||
nxt = {}
|
||||
ef = edge_faces(T)
|
||||
for t in T:
|
||||
for k in range(3):
|
||||
a, b = int(t[k]), int(t[(k + 1) % 3])
|
||||
if len(ef[(min(a, b), max(a, b))]) == 1:
|
||||
nxt[a] = b
|
||||
loops, seen = [], set()
|
||||
for s0 in list(nxt):
|
||||
if s0 in seen:
|
||||
continue
|
||||
L = [s0]; seen.add(s0); x = nxt[s0]
|
||||
while x != s0 and x not in seen:
|
||||
L.append(x); seen.add(x); x = nxt[x]
|
||||
loops.append(L)
|
||||
return loops
|
||||
|
||||
|
||||
def short_loop_merge(pieces, bevel_w=0.001):
|
||||
"""Split only: merge consecutive seam vertices closer than the bevel width, both pieces jointly. Both endpoints lie
|
||||
on the cutter plane, so the seam stays on it; only boolean-inserted seam vertices are merge sources (hull vertices
|
||||
survive). Caps are dropped first (rebuilt afterwards by the CDT), so the guard sees hull faces only."""
|
||||
import owner_weld as OW
|
||||
Ps = [OW.Piece(V, T[p == 0], np.zeros(int((p == 0).sum()), int)) for V, T, p in pieces]
|
||||
L = boundary_loops(np.array([f for f in Ps[0].faces]))
|
||||
st = defaultdict(int); n = 0
|
||||
for lp in L:
|
||||
for i in range(len(lp)):
|
||||
a, b = lp[i], lp[(i + 1) % len(lp)]
|
||||
pa, pb = Ps[0].V[a], Ps[0].V[b]
|
||||
if not (Ps[0].alive[a] and Ps[0].alive[b]) or np.linalg.norm(pa - pb) >= bevel_w:
|
||||
continue
|
||||
src, dst = (pb, pa) if hull.kd.query(pb)[0] > TOL else (pa, pb)
|
||||
if hull.kd.query(src)[0] < TOL:
|
||||
st['refused_both_hull_vertices'] += 1; continue
|
||||
plan = []
|
||||
for P in Ps:
|
||||
v, w = P.at(src, TOL), P.at(dst, TOL)
|
||||
if v is None or w is None:
|
||||
plan = None; st['refused_missing'] += 1; break
|
||||
r = P.check_collapse(v, w)
|
||||
if r:
|
||||
plan = None; st['refused_' + r] += 1; break
|
||||
plan.append((P, v, w))
|
||||
if plan:
|
||||
for P, v, w in plan:
|
||||
P.apply_collapse(v, w)
|
||||
n += 1
|
||||
out = []
|
||||
for P in Ps:
|
||||
V, T, _ = P.result(); out.append((V, T))
|
||||
return out, n, dict(st)
|
||||
|
||||
|
||||
def cdt_boundary(V, T, cut, opts, flip_orient):
|
||||
newV, newT, nv = [V], [], len(V)
|
||||
for L in boundary_loops(T):
|
||||
P = V[L]; n, _ = cut.frame(P.mean(0))
|
||||
e1 = np.cross(n, [1, 0, 0] if abs(n[0]) < .9 else [0, 1, 0]); e1 /= np.linalg.norm(e1); e2 = np.cross(n, e1)
|
||||
o = P.mean(0); P2 = np.stack([(P - o) @ e1, (P - o) @ e2], 1)
|
||||
r = triangle.triangulate({'vertices': P2, 'segments': np.array([[i, (i + 1) % len(L)] for i in range(len(L))])}, opts)
|
||||
idx = list(L) + list(range(nv, nv + len(r['vertices']) - len(L)))
|
||||
if len(r['vertices']) > len(L):
|
||||
newV.append(o + r['vertices'][len(L):, :1] * e1 + r['vertices'][len(L):, 1:2] * e2); nv += len(r['vertices']) - len(L)
|
||||
# boundary runs a->b in the hull faces, so the cap must run b->a: orient each cap triangle against the loop
|
||||
tri = [[idx[k] for k in t] for t in r['triangles']]
|
||||
newT += tri
|
||||
V2 = np.vstack(newV); NT = np.array(newT)
|
||||
# orientation: the cap must use each boundary edge in the opposite direction to the hull face that owns it
|
||||
hd = {(int(t[k]), int(t[(k + 1) % 3])) for t in T for k in range(3)}
|
||||
bad = sum(1 for t in NT for k in range(3) if (int(t[k]), int(t[(k + 1) % 3])) in hd)
|
||||
if bad:
|
||||
NT = NT[:, ::-1]
|
||||
return V2, np.vstack([T, NT]), np.concatenate([np.zeros(len(T), int), np.ones(len(NT), int)])
|
||||
|
||||
|
||||
rows = []
|
||||
for base in [b for b in ('split_fwd', 'probe_crease') if os.environ.get('SKIP_SPLITS') != '1']:
|
||||
c = cases[base + '_sub']; cut = Cutter(c)
|
||||
lo, hi = np.array(c['lo']), np.array(c['hi'])
|
||||
pieces = {'sub': load_run(base + '_sub'), 'int': load_run(base + '_int')}
|
||||
V0, T0, p0 = pieces['sub']; L0, _ = loops_of(T0, p0); refl = V0[sorted({v for L in L0 for v in L})]
|
||||
n, _ = cut.frame(refl.mean(0)); plane = (n, float(refl.mean(0) @ n))
|
||||
out = {}
|
||||
for variant, opts in ((('naive', None), ('flip+cdt', 'p'), ('flip+cdt-q', 'pq20Y')) if os.environ.get('ONLY_SHORT') != '1' else (('naive', None),)):
|
||||
for pk, (V, T, p) in pieces.items():
|
||||
if variant != 'naive':
|
||||
loops, le = loops_of(T, p); lset = {(min(a, b), max(a, b)) for a, b in le}
|
||||
kd = cKDTree(densify(V, loops)); h = float(np.median(hull.vlen))
|
||||
band = set(np.where(kd.query(V[T].mean(1))[0] < 2 * 0.0256)[0].tolist())
|
||||
T1, nf = flip_hull_all(V, T, p, lset, band)
|
||||
V2, T2, P2 = cdt_caps(V, T1, p, cut, opts)
|
||||
else:
|
||||
V2, T2, P2, nf = V, T, p, 0
|
||||
m = side_measures(V2, T2, P2, refl, plane)
|
||||
out[(variant, pk)] = (V2, T2, P2)
|
||||
rows.append(dict(case=f'{base}_{pk}', variant=variant, flips_applied=nf, **m))
|
||||
save(f'{base}_{pk}_{variant}', V2, T2, P2)
|
||||
A, B = out[(variant, 'sub')], out[(variant, 'int')]
|
||||
la = A[0][sorted({v for L in loops_of(A[1], A[2])[0] for v in L})]; lb = B[0][sorted({v for L in loops_of(B[1], B[2])[0] for v in L})]
|
||||
rows.append(dict(case=base, variant=f'{variant} seam crack', crack=float(max(cKDTree(lb).query(la)[0].max(), cKDTree(la).query(lb)[0].max()))))
|
||||
merged, nm, stm = short_loop_merge([pieces['sub'], pieces['int']])
|
||||
naive_dense = cKDTree(densify(V0, L0, 64)); res = {}
|
||||
for pk, (Vm, Tm) in zip(('sub', 'int'), merged):
|
||||
p0 = np.zeros(len(Tm), int); L = boundary_loops(Tm)
|
||||
lset = {(min(a, b), max(a, b)) for lp in L for a, b in zip(lp, lp[1:] + lp[:1])}
|
||||
kd = cKDTree(densify(Vm, L)); band = set(np.where(kd.query(Vm[Tm].mean(1))[0] < 2 * 0.0256)[0].tolist())
|
||||
T1, nf = flip_hull_all(Vm, Tm, p0, lset, band)
|
||||
V2, T2, P2 = cdt_boundary(Vm, T1, cut, 'pq20Y', None)
|
||||
m = side_measures(V2, T2, P2, refl, plane)
|
||||
chord = float(naive_dense.query(densify(V2, loops_of(T2, P2)[0], 16))[0].max())
|
||||
rows.append(dict(case=f'{base}_{pk}', variant='short+flip+cdt-q', flips_applied=nf, merges=nm, merge_stats=stm,
|
||||
seam_chord_dev=chord, seam_chord_dev_pct=chord / hull.diag * 100, **m))
|
||||
save(f'{base}_{pk}_short+flip+cdt-q', V2, T2, P2); res[pk] = (V2, T2, P2)
|
||||
A, B = res['sub'], res['int']
|
||||
la = A[0][sorted({v for L in loops_of(A[1], A[2])[0] for v in L})]; lb = B[0][sorted({v for L in loops_of(B[1], B[2])[0] for v in L})]
|
||||
rows.append(dict(case=base, variant='short+flip+cdt-q seam crack', crack=float(max(cKDTree(lb).query(la)[0].max(), cKDTree(la).query(lb)[0].max()))))
|
||||
print('done', base, nm, stm, flush=True)
|
||||
|
||||
# Box cut-ins into the curved hull: the flat faces own nothing (the hull owns every stretch, corners kept), so the
|
||||
# hull-side repair is the same edge flips; the pocket walls and floor are the cutter's own faces, not a cap.
|
||||
for base in [b for b in ('probe_box_flank', 'probe_box_ridge') if b in cases]:
|
||||
c = cases[base]; cut = Cutter(c); V, T, p = load_run(base)
|
||||
L0, le = loops_of(T, p); refl = V[sorted({v for L in L0 for v in L})]
|
||||
lset = {(min(a, b), max(a, b)) for a, b in le}
|
||||
kd = cKDTree(densify(V, L0)); band = set(np.where(kd.query(V[T].mean(1))[0] < 2 * 0.0256)[0].tolist())
|
||||
for variant in ('naive', 'flip'):
|
||||
T2, nf = (T, 0) if variant == 'naive' else flip_hull_all(V, T, p, lset, band)
|
||||
m = side_measures(V, T2, p, refl)
|
||||
rows.append(dict(case=base, variant=variant, flips_applied=nf, **m)); save(f'{base}_{variant}', V, T2, p)
|
||||
print('done', base, flush=True)
|
||||
|
||||
json.dump(rows, open(f'{outd}/measures3.json', 'w'), indent=1, default=float)
|
||||
cols = ['case', 'variant', 'merges', 'seam_chord_dev_pct', 'flips_applied', 'hull_band_tris', 'hull_slivers', 'hull_min_angle', 'hull_p5', 'cap_tris', 'cap_slivers',
|
||||
'cap_min_angle', 'flipped_hull', 'seam_off_plane_max', 'loop_to_naive_max', 'loop_edges_under_bevel', 'crack']
|
||||
f = lambda v: '' if v is None else (f'{v:.3g}' if isinstance(v, float) else str(v))
|
||||
with open(f'{outd}/table3.md', 'w') as o:
|
||||
o.write('| ' + ' | '.join(cols) + ' |\n|' + '---|' * len(cols) + '\n')
|
||||
for r in rows:
|
||||
o.write('| ' + ' | '.join(f(r.get(k)) for k in cols) + ' |\n')
|
||||
print(open(f'{outd}/table3.md').read())
|
||||
588
spikes/boolean-weld/py/round4.py
Normal file
588
spikes/boolean-weld/py/round4.py
Normal file
|
|
@ -0,0 +1,588 @@
|
|||
"""Round 4 (target r4, Self's calls a-f). Replaces round3.py and its Triangle dependency.
|
||||
a. slide: a hull vertex closer to the loop than the bevel width slides inside its own surface onto the loop, and
|
||||
the loop vertices its own edges made merge into it (see slide()). Never a crease or corner vertex; joint on both
|
||||
pieces of a split.
|
||||
b. no snapping of the loop onto owner vertices on any stretch (owner_weld.py has no 'snap' kind any more).
|
||||
c. constrained Delaunay by spade (MIT OR Apache-2.0) through the spike driver's `cdt` subcommand.
|
||||
d. planar brush facets trimmed by the hull are re-triangulated in their own plane; facet boundary edges (loop and
|
||||
brush edges) are constraints and are never split.
|
||||
e. add mode (union) cases.
|
||||
f. UV0 carry-through: every output face is matched to the operand face it is a fragment of and takes its UVs by
|
||||
barycentric interpolation; checks fragment coverage, UV flips and island change under the weld.
|
||||
Usage: round4.py <fixtures> <cases.json> <runs> <out-dir> <driver-exe> <hull_uv.obj>. Scratch."""
|
||||
import sys, os, json, copy, subprocess, tempfile, numpy as np
|
||||
os.environ.setdefault('MIN_ANGLE', '5')
|
||||
from collections import defaultdict
|
||||
from scipy.spatial import cKDTree
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from geo import *
|
||||
from weld import Hull, Cutter, loops_of, densify, angles, tri_dist
|
||||
import owner_weld as OW
|
||||
|
||||
fx, casesf, runs, outd, EXE, hull_uv_path = sys.argv[1:7]
|
||||
os.makedirs(outd, exist_ok=True)
|
||||
hull = Hull(fx); TOL = 1e-6 * hull.diag; BW = 0.001
|
||||
cases = {c['name']: c for c in json.load(open(casesf))}
|
||||
FLIP_COS = np.cos(np.radians(20))
|
||||
ONLY = os.environ.get('CASES', '').split(',') if os.environ.get('CASES') else None
|
||||
|
||||
|
||||
def tri_min_angle(V, t):
|
||||
return min(angles(V[list(t)]))
|
||||
|
||||
|
||||
def load_run(name):
|
||||
V, F = load_obj(f'{runs}/boolmesh_{name}.obj'); T = triangulate(F)
|
||||
return V, T, np.array([int(x) for x in open(f'{runs}/boolmesh_{name}.prov').read().split()])
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ UV sources
|
||||
def load_obj_uv(path):
|
||||
V, VT, F, FT = [], [], [], []
|
||||
for line in open(path):
|
||||
s = line.split()
|
||||
if not s: continue
|
||||
if s[0] == 'v': V.append([float(x) for x in s[1:4]])
|
||||
elif s[0] == 'vt': VT.append([float(x) for x in s[1:3]])
|
||||
elif s[0] == 'f':
|
||||
F.append([int(x.split('/')[0]) - 1 for x in s[1:]]); FT.append([int(x.split('/')[1]) - 1 for x in s[1:]])
|
||||
return np.array(V), np.array(VT), F, FT
|
||||
|
||||
|
||||
HV, HVT, HF, HFT = load_obj_uv(hull_uv_path)
|
||||
assert len(HV) == len(hull.V) and len(HF) == len(load_obj(fx + '/hull_nobevel.obj')[1])
|
||||
UV_FIXTURE_DIFF = float(np.abs(HV - hull.V).max())
|
||||
assert UV_FIXTURE_DIFF < 1e-6, UV_FIXTURE_DIFF
|
||||
HUV = np.array([[HVT[ft[0]], HVT[ft[i]], HVT[ft[i + 1]]] for ft in HFT for i in range(1, len(ft) - 1)])
|
||||
assert len(HUV) == len(hull.T)
|
||||
|
||||
|
||||
def uv_islands(T, UV):
|
||||
"""Triangles connected across an edge whose two endpoints carry the same UVs on both sides."""
|
||||
key = {}
|
||||
par = list(range(len(T)))
|
||||
def f(x):
|
||||
while par[x] != x: par[x] = par[par[x]]; x = par[x]
|
||||
return x
|
||||
for fi, t in enumerate(T):
|
||||
for k in range(3):
|
||||
a, b = int(t[k]), int(t[(k + 1) % 3]); ua, ub = tuple(np.round(UV[fi, k], 7)), tuple(np.round(UV[fi, (k + 1) % 3], 7))
|
||||
e = (a, b, ua, ub) if a < b else (b, a, ub, ua)
|
||||
if e in key: par[f(fi)] = f(key[e])
|
||||
else: key[e] = fi
|
||||
return np.array([f(i) for i in range(len(T))])
|
||||
|
||||
|
||||
def uv_area(UV):
|
||||
return 0.5 * ((UV[:, 1, 0] - UV[:, 0, 0]) * (UV[:, 2, 1] - UV[:, 0, 1]) - (UV[:, 2, 0] - UV[:, 0, 0]) * (UV[:, 1, 1] - UV[:, 0, 1]))
|
||||
|
||||
|
||||
HFN, HFA = face_normals(hull.V, hull.T)
|
||||
H_ISL = uv_islands(hull.T, HUV)
|
||||
RHO = float(np.median(np.sqrt(np.abs(uv_area(HUV)) / np.maximum(HFA, 1e-300)))) # UV units per world unit
|
||||
|
||||
|
||||
def cutter_uv(cut):
|
||||
"""A stand-in brush UV chart at the hull's texel density, placed at u >= 3 so a face's side is readable from its UVs.
|
||||
Planar facets: projection on the facet's own axes, one tile per facet. Cylinder side: unrolled (r * theta, height)."""
|
||||
V, T = cut.V, cut.T; FN, _ = face_normals(V, T); UV = np.zeros((len(T), 3, 2))
|
||||
groups = facet_groups(V, T); gi = {g: i for i, g in enumerate(sorted(set(groups)))}
|
||||
for fi, t in enumerate(T):
|
||||
P = V[t]; n = FN[fi]
|
||||
if cut.kind == 'cyl' and abs(n @ cut.a) < 0.5:
|
||||
d = P - cut.p; h = d @ cut.a; e1 = np.cross(cut.a, [1, 0, 0] if abs(cut.a[0]) < .9 else [0, 1, 0]); e1 /= np.linalg.norm(e1); e2 = np.cross(cut.a, e1)
|
||||
th = np.arctan2(d @ e2, d @ e1); th = np.where(th - th[0] > np.pi, th - 2 * np.pi, np.where(th - th[0] < -np.pi, th + 2 * np.pi, th))
|
||||
UV[fi] = np.stack([3 + RHO * cut.r * (th + np.pi), 0.5 + RHO * h], 1)
|
||||
else:
|
||||
e1 = np.cross(n, [1, 0, 0] if abs(n[0]) < .9 else [0, 1, 0]); e1 /= np.linalg.norm(e1); e2 = np.cross(n, e1)
|
||||
o = np.array([4 + 0.6 * (gi[groups[fi]] % 4), 0.6 * (gi[groups[fi]] // 4)])
|
||||
UV[fi] = o + RHO * np.stack([P @ e1, P @ e2], 1) - RHO * np.array([V @ e1, V @ e2]).min(1)
|
||||
return UV
|
||||
|
||||
|
||||
def facet_groups(V, T):
|
||||
"""Planar facets of a brush mesh: edge-adjacent triangles with the same plane."""
|
||||
FN, _ = face_normals(V, T); ef = edge_faces(T); par = list(range(len(T)))
|
||||
def f(x):
|
||||
while par[x] != x: par[x] = par[par[x]]; x = par[x]
|
||||
return x
|
||||
for e, fs in ef.items():
|
||||
if len(fs) == 2 and FN[fs[0]] @ FN[fs[1]] > 1 - 1e-9 and abs((V[T[fs[1]]].mean(0) - V[T[fs[0]]].mean(0)) @ FN[fs[0]]) < 1e-9:
|
||||
par[f(fs[0])] = f(fs[1])
|
||||
return [f(i) for i in range(len(T))]
|
||||
|
||||
|
||||
class Source:
|
||||
"""An operand: its triangles, their UVs and the polygon (operand face) each triangle belongs to."""
|
||||
def __init__(s, V, T, UV, poly):
|
||||
s.V, s.T, s.UV, s.poly = V, np.asarray(T), UV, np.asarray(poly); s.kd = cKDTree(V); s.vf = defaultdict(list)
|
||||
s.ptris = defaultdict(list)
|
||||
for fi, pl in enumerate(s.poly): s.ptris[int(pl)].append(fi)
|
||||
for fi, t in enumerate(s.T):
|
||||
for v in t: s.vf[int(v)].append(fi)
|
||||
s.key = {tuple(sorted(map(int, t))): fi for fi, t in enumerate(s.T)}
|
||||
|
||||
def near_faces(s, pts, k=6):
|
||||
out = set()
|
||||
for p in pts:
|
||||
for a in s.kd.query(p, k)[1]: out.update(s.vf[int(a)])
|
||||
return out
|
||||
|
||||
def bary(s, f, p):
|
||||
a, b, c = s.V[s.T[f]]; v0, v1, v2 = b - a, c - a, p - a
|
||||
d00, d01, d11, d20, d21 = v0 @ v0, v0 @ v1, v1 @ v1, v2 @ v0, v2 @ v1; den = d00 * d11 - d01 * d01
|
||||
v = (d11 * d20 - d01 * d21) / den; w = (d00 * d21 - d01 * d20) / den
|
||||
return np.array([1 - v - w, v, w])
|
||||
|
||||
|
||||
def assign_uv(V, T, prov, srcs):
|
||||
"""Per output triangle: the source (operand) triangle that contains all three corners, and UVs by interpolation in
|
||||
it. A triangle no single source face contains (a weld changed it) takes each corner's UV from a source face that
|
||||
contains that corner, preferring the triangle's majority source face's UV island."""
|
||||
UV = np.zeros((len(T), 3, 2)); frag = np.zeros(len(T), bool); src = np.full(len(T), -1); far = np.zeros(len(T))
|
||||
for fi, t in enumerate(T):
|
||||
S = srcs[int(prov[fi])]; P = V[t]
|
||||
d0, i0 = S.kd.query(P)
|
||||
if d0.max() < 1e-12:
|
||||
sf = S.key.get(tuple(sorted(map(int, i0))))
|
||||
if sf is not None:
|
||||
o = [list(S.T[sf]).index(int(x)) for x in i0]; UV[fi] = S.UV[sf][o]; frag[fi] = True; src[fi] = sf; continue
|
||||
best, bd = None, 1e9
|
||||
for f in S.near_faces(P):
|
||||
d = max(tri_dist(p, S.V[S.T[f]])[0] for p in P)
|
||||
if d < bd: best, bd = f, d
|
||||
src[fi] = best; far[fi] = bd
|
||||
if bd < TOL:
|
||||
frag[fi] = True; UV[fi] = np.array([S.bary(best, p) @ S.UV[best] for p in P]); continue
|
||||
# a fragment of the operand polygon (a hull quad, a planar brush facet) that spans two of its triangles
|
||||
cen = P.mean(0); cf = min(S.near_faces([cen]), key=lambda f: tri_dist(cen, S.V[S.T[f]])[0])
|
||||
pt = S.ptris[int(S.poly[cf])]; per = [min(pt, key=lambda f: tri_dist(p, S.V[S.T[f]])[0]) for p in P]
|
||||
dd = max(tri_dist(p, S.V[S.T[f]])[0] for p, f in zip(P, per))
|
||||
if dd < TOL:
|
||||
frag[fi] = True; src[fi] = cf; far[fi] = dd; UV[fi] = np.array([S.bary(f, p) @ S.UV[f] for p, f in zip(P, per)]); continue
|
||||
isl = S.isl[best] if hasattr(S, 'isl') else None
|
||||
for k, p in enumerate(P):
|
||||
cands = sorted(((tri_dist(p, S.V[S.T[f]])[0], (isl is not None and S.isl[f] != isl), f) for f in S.near_faces([p], 4)), key=lambda z: (z[0] > TOL, z[1], z[0]))
|
||||
f = cands[0][2]; UV[fi, k] = S.bary(f, p) @ S.UV[f]
|
||||
return UV, frag, src, far
|
||||
|
||||
|
||||
def jac_sigma(P, Q):
|
||||
"""Singular values of the map from a 3D triangle to its UV triangle, in units of the hull's median density."""
|
||||
e1 = P[1] - P[0]; e2 = P[2] - P[0]; n = np.cross(e1, e2); a = np.linalg.norm(e1)
|
||||
if a < 1e-300 or np.linalg.norm(n) < 1e-300: return 0.0, 0.0
|
||||
x = e1 / a; y = np.cross(n / np.linalg.norm(n), x)
|
||||
A = np.array([[e1 @ x, e2 @ x], [e1 @ y, e2 @ y]]); B = np.stack([Q[1] - Q[0], Q[2] - Q[0]], 1)
|
||||
try: J = B @ np.linalg.inv(A)
|
||||
except np.linalg.LinAlgError: return 0.0, 0.0
|
||||
s = np.linalg.svd(J, compute_uv=False) / RHO
|
||||
return float(s.min()), float(s.max())
|
||||
|
||||
|
||||
def uv_report(V, T, prov, UV, frag, src, srcs):
|
||||
out = dict(faces=len(T), fragments=int(frag.sum()), not_fragments=int((~frag).sum()))
|
||||
sgn = np.sign(uv_area(UV)); ssgn = np.array([np.sign(uv_area(srcs[int(p)].UV[[s]])[0]) for p, s in zip(prov, src)])
|
||||
fl = sgn != ssgn; out['uv_flipped_hull'] = int((fl & (prov == 0)).sum()); out['uv_flipped_brush'] = int((fl & (prov == 1)).sum())
|
||||
out['not_fragments_hull'] = int((~frag & (prov == 0)).sum()); out['not_fragments_brush'] = int((~frag & (prov == 1)).sum())
|
||||
h = prov == 0; isl = uv_islands(T[h], UV[h])
|
||||
out['hull_islands'] = len(set(isl)); out['hull_uv_area'] = float(np.abs(uv_area(UV[h])).sum())
|
||||
out['hull_src_islands'] = len(set(H_ISL[src[h]]))
|
||||
nf = np.where(~frag)[0]
|
||||
if len(nf):
|
||||
sg = np.array([jac_sigma(V[T[i]], UV[i]) for i in nf]); r = sg[:, 0] / np.maximum(sg[:, 1], 1e-300)
|
||||
out['moved_face_sigma_min'] = float(sg[:, 0].min()); out['moved_face_sigma_max'] = float(sg[:, 1].max())
|
||||
out['moved_face_aniso_min'] = float(r.min())
|
||||
return out
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ constrained Delaunay (spade, via the driver)
|
||||
CDT_CALLS = defaultdict(int)
|
||||
|
||||
|
||||
def spade_cdt(P2, segs, ang=20.0, max_add=5000):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
i, o = os.path.join(d, 'in.txt'), os.path.join(d, 'out.txt')
|
||||
with open(i, 'w') as f:
|
||||
f.write(f'{len(P2)} {len(segs)} {ang} {max_add}\n')
|
||||
for p in P2: f.write(f'{p[0]:.17e} {p[1]:.17e}\n')
|
||||
for a, b in segs: f.write(f'{a} {b}\n')
|
||||
subprocess.run([EXE, 'cdt', i, o], check=True, capture_output=True)
|
||||
L = open(o).read().split('\n'); nv = int(L[0].split()[1])
|
||||
pts = np.array([[float(x) for x in l.split()] for l in L[1:1 + nv]]); nt = int(L[1 + nv].split()[1])
|
||||
tri = np.array([[int(x) for x in l.split()] for l in L[2 + nv:2 + nv + nt]]); res = L[2 + nv + nt]
|
||||
CDT_CALLS['calls'] += 1; CDT_CALLS['complete' if 'complete=true' in res else 'incomplete'] += 1
|
||||
CDT_CALLS['steiner'] += nv - len(P2)
|
||||
assert np.array_equal(pts[:len(P2)], np.asarray(P2)), 'spade moved an input vertex'
|
||||
return pts, tri
|
||||
|
||||
|
||||
def plane_frame(n):
|
||||
e1 = np.cross(n, [1, 0, 0] if abs(n[0]) < .9 else [0, 1, 0]); e1 /= np.linalg.norm(e1); return e1, np.cross(n, e1)
|
||||
|
||||
|
||||
def cdt_region(V, faces, n, constrained, splits=None):
|
||||
"""Re-triangulate a planar face set within its plane. Constraints: its boundary edges plus `constrained` interior
|
||||
edges. Returns new vertex positions (appended after len(V)) and triangles, oriented like the old faces."""
|
||||
ef = defaultdict(int)
|
||||
for t in faces:
|
||||
for k in range(3): a, b = int(t[k]), int(t[(k + 1) % 3]); ef[(min(a, b), max(a, b))] += 1
|
||||
cons = []
|
||||
for e, c in ef.items():
|
||||
if c == 1 or e in constrained:
|
||||
ch = [e[0]] + list((splits or {}).get(e, [])) + [e[1]]; cons += list(zip(ch, ch[1:]))
|
||||
vs = sorted({int(x) for t in faces for x in t} | {int(x) for e in cons for x in e}); li = {v: i for i, v in enumerate(vs)}
|
||||
e1, e2 = plane_frame(n); o = V[vs].mean(0); P2 = np.stack([(V[vs] - o) @ e1, (V[vs] - o) @ e2], 1)
|
||||
pts, tri = spade_cdt(P2, [(li[a], li[b]) for a, b in cons])
|
||||
newV = o + pts[len(vs):, :1] * e1 + pts[len(vs):, 1:2] * e2
|
||||
idx = vs + list(range(len(V), len(V) + len(newV)))
|
||||
NT = np.array([[idx[k] for k in t] for t in tri])
|
||||
VV = np.vstack([V, newV])
|
||||
old = face_normals(V, np.asarray(faces))[0].sum(0)
|
||||
if face_normals(VV, NT)[0].sum(0) @ old < 0: NT = NT[:, ::-1]
|
||||
got = {(min(a, b), max(a, b)) for t in NT for a, b in zip(t, np.roll(t, -1))}
|
||||
missing = sum(1 for a, b in cons if (min(a, b), max(a, b)) not in got)
|
||||
return newV, NT, missing, len(cons)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ hull-side repairs
|
||||
def flip_hull_all(V, T, prov, loopedges, band_faces, cap=4000):
|
||||
"""Greedy flips on hull faces near the loop (round 3). Constrained: loop edges, hull crease edges and (round 4) UV0
|
||||
seams: both faces must lie in the same source UV island. A flip must raise the pair's worst angle and keep both
|
||||
normals within 20 deg."""
|
||||
isl = {f: H_ISL[hull.frame(V[T[f]].mean(0))[2]] for f in band_faces if not prov[f]}
|
||||
T = [list(map(int, t)) for t in T]; nflip = 0
|
||||
for _ in range(cap):
|
||||
ef = defaultdict(list)
|
||||
for fi, t in enumerate(T):
|
||||
for k in range(3): a, b = t[k], t[(k + 1) % 3]; ef[(min(a, b), max(a, b))].append(fi)
|
||||
changed = False
|
||||
for e, fs in ef.items():
|
||||
if len(fs) != 2 or e in loopedges: continue
|
||||
f1, f2 = fs
|
||||
if prov[f1] or prov[f2] or not (f1 in band_faces and f2 in band_faces) or isl[f1] != isl[f2]: continue
|
||||
he = hull.edge_of(V[e[0]], TOL), hull.edge_of(V[e[1]], TOL)
|
||||
if any(h is not None and h in hull.crease for h in he) and he[0] == he[1]: continue
|
||||
c = [x for x in T[f1] if x not in e][0]; d = [x for x in T[f2] if x not in e][0]
|
||||
if (min(c, d), max(c, d)) in ef: continue
|
||||
old = min(tri_min_angle(V, T[f1]), tri_min_angle(V, T[f2]))
|
||||
t1 = T[f1]; i = t1.index(c); p, q = t1[(i + 1) % 3], t1[(i + 2) % 3]; new1, new2 = [c, p, d], [c, d, q]
|
||||
if min(tri_min_angle(V, new1), tri_min_angle(V, new2)) <= old + 1e-9: continue
|
||||
on = [np.cross(V[t[1]] - V[t[0]], V[t[2]] - V[t[0]]) for t in (T[f1], T[f2])]
|
||||
nn = [np.cross(V[t[1]] - V[t[0]], V[t[2]] - V[t[0]]) for t in (new1, new2)]
|
||||
on = [x / np.linalg.norm(x) for x in on]; nn = [x / max(np.linalg.norm(x), 1e-300) for x in nn]
|
||||
if min(o @ n for o in on for n in nn) < FLIP_COS: continue
|
||||
T[f1], T[f2] = new1, new2; nflip += 1; changed = True; break
|
||||
if not changed: break
|
||||
return np.array(T), nflip
|
||||
|
||||
|
||||
def boundary_loops(T):
|
||||
nxt = {}; ef = edge_faces(T)
|
||||
for t in T:
|
||||
for k in range(3):
|
||||
a, b = int(t[k]), int(t[(k + 1) % 3])
|
||||
if len(ef[(min(a, b), max(a, b))]) == 1: nxt[a] = b
|
||||
loops, seen = [], set()
|
||||
for s0 in list(nxt):
|
||||
if s0 in seen: continue
|
||||
L = [s0]; seen.add(s0); x = nxt[s0]
|
||||
while x != s0 and x not in seen: L.append(x); seen.add(x); x = nxt[x]
|
||||
loops.append(L)
|
||||
return loops
|
||||
|
||||
|
||||
def loop_vertices(P):
|
||||
"""Loop vertices of a piece: between hull and cutter faces, or the open boundary of a cap-dropped split piece."""
|
||||
alive = [i for i, f in enumerate(P.faces) if f is not None]
|
||||
T = np.array([P.faces[i] for i in alive]); pr = np.array([P.prov[i] for i in alive])
|
||||
if (pr == 1).any():
|
||||
L, _ = loops_of(T, pr)
|
||||
else:
|
||||
L = boundary_loops(T)
|
||||
return {v for l in L for v in l}
|
||||
|
||||
|
||||
def hull_index(p):
|
||||
d, i = hull.kd.query(p); return int(i) if d < TOL else None
|
||||
|
||||
|
||||
def short_loop_merge(Ps):
|
||||
"""Split only (round 3): consecutive seam vertices closer than the bevel width merge, both pieces jointly; only
|
||||
boolean-inserted seam vertices are merge sources. Round 4 guards it like the slide (compound(): local worst angle)."""
|
||||
L = boundary_loops(np.array([f for f in Ps[0].faces])); st = defaultdict(int); n = 0
|
||||
for lp in L:
|
||||
for i in range(len(lp)):
|
||||
a, b = lp[i], lp[(i + 1) % len(lp)]
|
||||
pa, pb = Ps[0].V[a], Ps[0].V[b]
|
||||
if not (Ps[0].alive[a] and Ps[0].alive[b]) or np.linalg.norm(pa - pb) >= BW: continue
|
||||
src, dst = (pb, pa) if hull_index(pb) is None else (pa, pb)
|
||||
if hull_index(src) is not None: st['refused_both_hull_vertices'] += 1; continue
|
||||
trial = []
|
||||
for P in Ps:
|
||||
v, w = P.at(src, TOL), P.at(dst, TOL)
|
||||
if v is None or w is None: trial = None; st['refused_missing'] += 1; break
|
||||
Q = copy.deepcopy(P); r = compound(Q, [('c', v, w)])
|
||||
if r: trial = None; st['refused_' + r] += 1; break
|
||||
trial.append(Q)
|
||||
if trial:
|
||||
for i, Q in enumerate(trial): Ps[i] = Q
|
||||
n += 1
|
||||
st['applied'] = n
|
||||
return dict(st)
|
||||
|
||||
|
||||
def compound(Q, ops):
|
||||
"""Apply a compound weld operation to piece Q and guard its end state: each collapse must be an edge and pass the
|
||||
link condition; then no face it touched may invert, and the worst angle over the faces it touched (deleted ones
|
||||
included) may not end below the floor if it got worse (target r4: no step drops the band's worst angle below the floor)."""
|
||||
before, touched = {}, set()
|
||||
for op, v, w in ops:
|
||||
if op == 'c':
|
||||
r = Q.check_collapse(v, w)
|
||||
if r in ('not_edge', 'link'): return r
|
||||
for f in Q.vf[v] + Q.vf[w]:
|
||||
if Q.faces[f] is not None and f not in before: before[f] = Q.V[Q.faces[f]].copy()
|
||||
Q.apply_collapse(v, w); touched |= set(Q.vf[w])
|
||||
else:
|
||||
for f in Q.vf[v]:
|
||||
if Q.faces[f] is not None and f not in before: before[f] = Q.V[Q.faces[f]].copy()
|
||||
Q.apply_move(v, w); touched |= set(Q.vf[v])
|
||||
new_min = 180.0
|
||||
for f in touched:
|
||||
if Q.faces[f] is None or f not in before: continue
|
||||
P, N = before[f], Q.V[Q.faces[f]]
|
||||
if np.cross(P[1] - P[0], P[2] - P[0]) @ np.cross(N[1] - N[0], N[2] - N[0]) <= 0: return 'flip'
|
||||
new_min = min(new_min, min(angles(N)))
|
||||
old_min = min(min(angles(P)) for P in before.values())
|
||||
if new_min < OW.MIN_ANGLE and new_min < old_min: return 'angle'
|
||||
return None
|
||||
|
||||
|
||||
def slide(Ps, corners, joint_absent=True):
|
||||
"""Call (a), joint over the pieces. A hull vertex H (not a crease vertex, not a corner, not on the loop) whose own
|
||||
edges cross the loop at loop vertices C(H) (consecutive along the loop), and whose nearest point M on the loop
|
||||
polyline between them is closer than the bevel width, slides inside its own surface to M; the loop vertices C(H)
|
||||
merge into it. M lies on the intersection, so the loop stays on it (a flat seam stays on the plane). In a split the
|
||||
piece without H gets the same loop: its first C(H) vertex moves to M and the others merge into it. Every operation
|
||||
must pass every piece's guards, or none is applied. Ps is edited in place (pieces are replaced by their copies)."""
|
||||
import copy
|
||||
st = defaultdict(int); moved = []
|
||||
P0 = Ps[0]; alive = [f for f in P0.faces if f is not None]
|
||||
pr0 = np.array([P0.prov[i] for i, f in enumerate(P0.faces) if f is not None])
|
||||
loops = loops_of(np.array(alive), pr0)[0] if (pr0 == 1).any() else boundary_loops(np.array(alive))
|
||||
cand = []
|
||||
for L in loops:
|
||||
n = len(L); pos = {v: i for i, v in enumerate(L)}
|
||||
cross = defaultdict(list)
|
||||
for v in L:
|
||||
he = hull.edge_of(P0.V[v], TOL)
|
||||
if he is not None and hull.kd.query(P0.V[v])[0] > TOL:
|
||||
for h in he: cross[int(h)].append(v)
|
||||
for h, C in cross.items():
|
||||
if h in hull.crease_v or any(np.linalg.norm(hull.V[h] - q) < TOL for q in corners): continue
|
||||
idx = sorted(pos[v] for v in C)
|
||||
# consecutive along the loop (allow wrap-around)
|
||||
span = None
|
||||
for s0 in range(len(idx)):
|
||||
seq = [(idx[(s0 + k) % len(idx)]) for k in range(len(idx))]
|
||||
if all((seq[k + 1] - seq[k]) % n == 1 for k in range(len(seq) - 1)): span = seq; break
|
||||
if span is None: st['skip_not_consecutive'] += 1; continue
|
||||
Cs = [L[i] for i in span]
|
||||
if any(any(np.linalg.norm(P0.V[c] - q) < TOL for q in corners) for c in Cs): st['skip_corner_on_loop'] += 1; continue
|
||||
pts = [P0.V[c] for c in Cs]; best = (np.linalg.norm(hull.V[h] - pts[0]), pts[0])
|
||||
for a, b in zip(pts, pts[1:]):
|
||||
ab = b - a; t = np.clip((hull.V[h] - a) @ ab / max(ab @ ab, 1e-300), 0, 1); m = a + t * ab
|
||||
d = np.linalg.norm(hull.V[h] - m)
|
||||
if d < best[0]: best = (d, m)
|
||||
if best[0] < BW: cand.append((best[0], h, [P0.V[c].copy() for c in Cs], best[1].copy()))
|
||||
cand.sort(key=lambda z: z[0]); used = set()
|
||||
for d, h, Cpos, M in cand:
|
||||
keys = {tuple(np.round(c, 9)) for c in Cpos}
|
||||
if keys & used: st['skip_overlap'] += 1; continue
|
||||
trial, reason = [], None
|
||||
npres = 0
|
||||
for P in Ps:
|
||||
Q = copy.deepcopy(P); cs = [Q.at(c, TOL) for c in Cpos]
|
||||
if any(c is None for c in cs): reason = 'loop_vertex_gone'; break
|
||||
hv = Q.at(hull.V[h], TOL)
|
||||
if hv is not None:
|
||||
npres += 1; r = compound(Q, [('c', c, hv) for c in cs] + [('m', hv, M)])
|
||||
else:
|
||||
if not joint_absent: trial.append(Q); continue
|
||||
r = compound(Q, [('c', c, cs[0]) for c in cs[1:]] + [('m', cs[0], M)])
|
||||
if r: reason = r; break
|
||||
trial.append(Q)
|
||||
if reason or npres == 0: st['refused_' + (reason or 'h_absent')] += 1; continue
|
||||
for i, Q in enumerate(trial): Ps[i] = Q
|
||||
used |= keys; st['applied'] += 1; st['loop_vertices_merged'] += len(Cpos); moved.append(d)
|
||||
st['candidates'] = len(cand); st['max_move'] = max(moved, default=0.0); st['max_move_over_bw'] = st['max_move'] / BW
|
||||
return dict(st)
|
||||
|
||||
|
||||
def band_of(V, T, loops, h=0.0256):
|
||||
kd = cKDTree(densify(V, loops)); return set(np.where(kd.query(V[T].mean(1))[0] < 2 * h)[0].tolist())
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ measures
|
||||
def measure(V, T, prov, ref_pts, plane=None):
|
||||
loops, le = loops_of(T, prov); lv = sorted({v for L in loops for v in L}); lset = set(lv)
|
||||
h = float(np.median(hull.vlen[hull.kd.query(V[lv])[1]]))
|
||||
kd = cKDTree(densify(V, loops)); cen = V[T].mean(1); inb = kd.query(cen)[0] < 2 * h
|
||||
FN, FA = face_normals(V, T); lmax = np.linalg.norm(V[T] - V[np.roll(T, -1, 1)], axis=2).max(1)
|
||||
sl = (lmax ** 2 / np.maximum(2 * FA, 1e-300) > 10) | (FA < 1e-4 * FA[prov == 0].mean())
|
||||
ang = np.array([tri_min_angle(V, t) for t in T])
|
||||
out = dict(loop_verts=len(lv))
|
||||
for nm, m in (('hull', inb & (prov == 0)), ('brush', inb & (prov == 1))):
|
||||
out[f'{nm}_tris'] = int(m.sum()); out[f'{nm}_slivers'] = int((sl & m).sum())
|
||||
out[f'{nm}_worst'] = float(ang[m].min()) if m.any() else None; out[f'{nm}_p5'] = float(np.percentile(ang[m], 5)) if m.any() else None
|
||||
out['hull_flipped'] = int(sum(FN[fi] @ hull.frame(cen[fi])[0] < 0 for fi in np.where(inb & (prov == 0))[0]))
|
||||
out['dev_max_pct'] = float(cKDTree(ref_pts).query(densify(V, loops, 16))[0].max() / hull.diag * 100)
|
||||
if plane is not None: out['seam_off_plane'] = float(np.abs(V[lv] @ plane[0] - plane[1]).max())
|
||||
ls = [np.linalg.norm(V[a] - V[b]) for a, b in edge_faces(T) if a in lset or b in lset]
|
||||
out['loop_edges_under_bw'] = int(sum(l < BW for l in ls)); out['shortest_loop_edge'] = float(min(ls))
|
||||
return out
|
||||
|
||||
|
||||
def save(stem, V, T, prov, UV, info=None):
|
||||
with open(f'{outd}/{stem}.obj', 'w') as f:
|
||||
for v in V: f.write(f'v {v[0]:.12f} {v[1]:.12f} {v[2]:.12f}\n')
|
||||
for uv in UV.reshape(-1, 2): f.write(f'vt {uv[0]:.9f} {uv[1]:.9f}\n')
|
||||
for i, t in enumerate(T): f.write('f ' + ' '.join(f'{t[k] + 1}/{3 * i + k + 1}' for k in range(3)) + '\n')
|
||||
_, le = loops_of(T, prov)
|
||||
with open(f'{outd}/{stem}.loop', 'w') as f:
|
||||
for a, b in le: f.write(f"{a} {b} {info[a]['owner'] if info and a in info else 0}\n")
|
||||
|
||||
|
||||
def piece_arrays(P):
|
||||
V, T, pr = P.result(); used = np.unique(T); return V, T, pr
|
||||
|
||||
|
||||
rows = []
|
||||
HS = Source(hull.V, hull.T, HUV, [i for i, f in enumerate(HF) for _ in range(len(f) - 2)]); HS.isl = H_ISL
|
||||
|
||||
|
||||
def cutter_source(cut):
|
||||
return Source(cut.V, cut.T, cutter_uv(cut), facet_groups(cut.V, cut.T))
|
||||
|
||||
|
||||
def finish(case, variant, V, T, prov, srcs, ref, plane=None, extra=None, info=None, stem=None):
|
||||
UV, frag, src, far = assign_uv(V, T, prov, srcs)
|
||||
m = measure(V, T, prov, ref, plane); u = uv_report(V, T, prov, UV, frag, src, srcs)
|
||||
rows.append(dict(case=case, variant=variant, **m, **{'uv_' + k: v for k, v in u.items()}, **(extra or {})))
|
||||
save(stem or f'{case}_{variant}', V, T, prov, UV, info)
|
||||
print(case, variant, {k: rows[-1][k] for k in ('hull_slivers', 'hull_worst', 'brush_slivers', 'brush_worst', 'loop_edges_under_bw', 'uv_not_fragments_hull', 'uv_not_fragments_brush', 'uv_uv_flipped_hull', 'uv_uv_flipped_brush')}, flush=True)
|
||||
return UV
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ flat splits
|
||||
for base in ('split_fwd', 'probe_crease'):
|
||||
if ONLY and base not in ONLY: continue
|
||||
c = cases[base + '_sub']; cut = Cutter(c); CS = cutter_source(cut); srcs = {0: HS, 1: CS}
|
||||
pieces = {'sub': load_run(base + '_sub'), 'int': load_run(base + '_int')}
|
||||
V0, T0, p0 = pieces['sub']; L0, _ = loops_of(T0, p0); refl = densify(V0, L0, 64)
|
||||
n, _ = cut.frame(V0[L0[0]].mean(0)); plane = (n, float(V0[L0[0][0]] @ n))
|
||||
for pk, (V, T, p) in pieces.items():
|
||||
finish(f'{base}_{pk}', 'naive', V, T, p, srcs, refl, plane)
|
||||
corners = [V0[v] for v in {v for L in L0 for v in L} if (lambda e: e is not None and e in hull.crease)(hull.edge_of(V0[v], TOL))]
|
||||
capuv = {}
|
||||
for variant in ('r4-noslide', 'r4'):
|
||||
Ps = [OW.Piece(V, T[p == 0], np.zeros(int((p == 0).sum()), int)) for V, T, p in pieces.values()]
|
||||
stm = short_loop_merge(Ps)
|
||||
sls = slide(Ps, corners) if variant == 'r4' else {}
|
||||
res = {}
|
||||
for pk, P in zip(pieces, Ps):
|
||||
V, T, _ = P.result(); L = boundary_loops(T)
|
||||
lset = {(min(a, b), max(a, b)) for lp in L for a, b in zip(lp, lp[1:] + lp[:1])}
|
||||
T1, nf = flip_hull_all(V, T, np.zeros(len(T), int), lset, band_of(V, T, L))
|
||||
VV = V
|
||||
# caps: one CDT per seam loop, boundary edges are the constraints
|
||||
capT = []
|
||||
for lp in L:
|
||||
e1, e2 = plane_frame(n); o = VV[lp].mean(0)
|
||||
pts, tri = spade_cdt(np.stack([(VV[lp] - o) @ e1, (VV[lp] - o) @ e2], 1), [(i, (i + 1) % len(lp)) for i in range(len(lp))])
|
||||
idx = list(lp) + list(range(len(VV), len(VV) + len(pts) - len(lp)))
|
||||
VV = np.vstack([VV, o + pts[len(lp):, :1] * e1 + pts[len(lp):, 1:2] * e2]); capT += [[idx[k] for k in t] for t in tri]
|
||||
capT = np.array(capT); hd = {(int(t[k]), int(t[(k + 1) % 3])) for t in T1 for k in range(3)}
|
||||
if any((int(t[k]), int(t[(k + 1) % 3])) in hd for t in capT for k in range(3)): capT = capT[:, ::-1]
|
||||
T2 = np.vstack([T1, capT]); P2 = np.concatenate([np.zeros(len(T1), int), np.ones(len(capT), int)])
|
||||
UV = finish(f'{base}_{pk}', variant, VV, T2, P2, srcs, refl, plane, dict(flips=nf, short_merges=stm.get('applied'), slide=sls))
|
||||
res[pk] = (VV, T2, P2); capuv[(variant, pk)] = (VV, T2, P2, UV)
|
||||
A, B = res['sub'], res['int']
|
||||
la = A[0][sorted({v for L in loops_of(A[1], A[2])[0] for v in L})]; lb = B[0][sorted({v for L in loops_of(B[1], B[2])[0] for v in L})]
|
||||
crack = float(max(cKDTree(lb).query(la)[0].max(), cKDTree(la).query(lb)[0].max()))
|
||||
# split caps: both pieces' caps are fragments of the same cutter face, so carried UVs coincide
|
||||
ua = capuv[(variant, 'sub')]; ub = capuv[(variant, 'int')]
|
||||
ca = ua[3][ua[2] == 1].reshape(-1, 2); cb = ub[3][ub[2] == 1].reshape(-1, 2)
|
||||
rows.append(dict(case=base, variant=f'{variant} pieces', crack=crack, cap_uv_overlap=float(cKDTree(cb).query(ca)[0].max()),
|
||||
cap_uv_area_sub=float(np.abs(uv_area(ua[3][ua[2] == 1])).sum()), cap_uv_area_int=float(np.abs(uv_area(ub[3][ub[2] == 1])).sum())))
|
||||
print(rows[-1], flush=True)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ cut-ins and adds
|
||||
def facet_cdt(V, T, prov, cut, src, split_brush_edges=False):
|
||||
"""Call (d): re-triangulate each planar brush facet the hull trimmed (it holds a loop edge), inside its own plane.
|
||||
split_brush_edges (a variant, not Self's call): a trimmed facet's brush edges (never loop edges) longer than twice
|
||||
the facet's median loop edge get evenly spaced collinear vertices, shared by both facets on that edge (the other
|
||||
facet is re-triangulated too), so the edge stays where it is and both halves keep its bevel weight."""
|
||||
groups = facet_groups(cut.V, cut.T); FNc, _ = face_normals(cut.V, cut.T)
|
||||
by = defaultdict(list)
|
||||
for fi in np.where(prov == 1)[0]: by[groups[src[fi]]].append(fi)
|
||||
loops, le = loops_of(T, prov); lset = {(min(a, b), max(a, b)) for a, b in le}
|
||||
keep = np.ones(len(T), bool); add = []; VV = V; st = defaultdict(int)
|
||||
def bnd(fs):
|
||||
ef = defaultdict(int)
|
||||
for fi in fs:
|
||||
for k in range(3): a, b = int(T[fi][k]), int(T[fi][(k + 1) % 3]); ef[(min(a, b), max(a, b))] += 1
|
||||
return [e for e, c in ef.items() if c == 1]
|
||||
todo = {g for g, fs in by.items() if any(e in lset for e in bnd(fs))}
|
||||
splits = {}
|
||||
if split_brush_edges:
|
||||
for g in list(todo):
|
||||
be = bnd(by[g]); ll = [np.linalg.norm(V[a] - V[b]) for a, b in be if (a, b) in lset]
|
||||
s_ = float(np.median(ll))
|
||||
for a, b in be:
|
||||
L = np.linalg.norm(V[a] - V[b])
|
||||
if (a, b) in lset or (a, b) in splits or L <= 2 * s_: continue
|
||||
k = int(round(L / s_)) - 1; P = [V[a] + (V[b] - V[a]) * (i + 1) / (k + 1) for i in range(k)]
|
||||
splits[(a, b)] = list(range(len(VV), len(VV) + k)); VV = np.vstack([VV, P]); st['brush_edge_points'] += k
|
||||
for g, fs in by.items():
|
||||
if any(e in splits for e in bnd(fs)): todo.add(g)
|
||||
for g, fs in by.items():
|
||||
if g not in todo: continue
|
||||
nv, nt, miss, nc = cdt_region(VV, T[fs], FNc[g], set(), splits)
|
||||
VV = np.vstack([VV, nv]); keep[fs] = False; add.append(nt)
|
||||
st['facets'] += 1; st['old_tris'] += len(fs); st['new_tris'] += len(nt); st['constraint_edges'] += nc; st['constraint_edges_missing'] += miss; st['steiner'] += len(nv)
|
||||
if not add: return VV, T, prov, dict(st)
|
||||
NT = np.vstack(add)
|
||||
return VV, np.vstack([T[keep], NT]), np.concatenate([prov[keep], np.ones(len(NT), int)]), dict(st)
|
||||
|
||||
|
||||
for name in ('port_flank_s16', 'probe_switch_s48', 'probe_crease_cyl_s16', 'probe_box_flank', 'probe_box_ridge', 'add_box_flank', 'add_cyl_flank_s16'):
|
||||
if ONLY and name not in ONLY: continue
|
||||
c = cases[name]; cut = Cutter(c); CS = cutter_source(cut); srcs = {0: HS, 1: CS}
|
||||
V, T, p = load_run(name)
|
||||
if c['kind'] == 'cyl':
|
||||
Vr, Tr, pr = load_run(name + '_REF'); ref = densify(Vr, loops_of(Tr, pr)[0], 4)
|
||||
else:
|
||||
ref = densify(V, loops_of(T, p)[0], 64)
|
||||
finish(name, 'naive', V, T, p, srcs, ref)
|
||||
welded, st, done, infos = OW.owner_weld([(V, T, p)], hull, cut, TOL)
|
||||
Vw, Tw, pw = welded[0]; info = infos[0][1]
|
||||
own = dict(hull=sum(1 for i in info.values() if i['owner'] == 0), brush=sum(1 for i in info.values() if i['owner'] == 1))
|
||||
finish(name, 'owner-r4', Vw, Tw, pw, srcs, ref, extra=dict(weld=st, owners=own), info=info)
|
||||
corners = OW.corners_of(OW.Piece(Vw, Tw, pw), {v: i for v, i in info.items()}, hull, cut, TOL)
|
||||
PL = [OW.Piece(Vw, Tw, pw)]; sls = slide(PL, corners, joint_absent=False); Vs, Ts, ps = PL[0].result()
|
||||
L, le = loops_of(Ts, ps); lset = {(min(a, b), max(a, b)) for a, b in le}
|
||||
T1, nf = flip_hull_all(Vs, Ts, ps, lset, band_of(Vs, Ts, L))
|
||||
_, _, srcf, _ = assign_uv(Vs, T1, ps, srcs)
|
||||
if os.environ.get('SPLIT_BRUSH_EDGES') != '0':
|
||||
V3, T3, p3, fst3 = facet_cdt(Vs, T1, ps, cut, srcf, split_brush_edges=True)
|
||||
finish(name, 'r4-split-brush-edges', V3, T3, p3, srcs, ref, extra=dict(facet_cdt=fst3), info=info)
|
||||
V2, T2, p2, fst = facet_cdt(Vs, T1, ps, cut, srcf)
|
||||
kept = sum(int(np.linalg.norm(V2[np.unique(T2)] - q, axis=1).min() < TOL) for q in corners)
|
||||
finish(name, 'r4', V2, T2, p2, srcs, ref, extra=dict(weld=st, slide=sls, flips=nf, facet_cdt=fst, corners=len(corners), corners_kept=kept), info=info)
|
||||
|
||||
rows.append(dict(case='spade', variant='cdt calls', **CDT_CALLS))
|
||||
rows.append(dict(case='uv', variant='fixture', uv_fixture_max_diff=UV_FIXTURE_DIFF, hull_islands=len(set(H_ISL)), rho=RHO))
|
||||
json.dump(rows, open(f'{outd}/measures4.json', 'w'), indent=1, default=lambda x: x if not hasattr(x, 'item') else x.item())
|
||||
print('ALLDONE')
|
||||
25
spikes/boolean-weld/py/table4.py
Normal file
25
spikes/boolean-weld/py/table4.py
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
"""Round 4 tables from measures4.json (and bevel_uv.json when given). Usage: table4.py <measures4.json> <out.md> [bevel_uv.json]"""
|
||||
import sys, json
|
||||
rows = json.load(open(sys.argv[1])); out = open(sys.argv[2], 'w')
|
||||
f = lambda v: '' if v is None else (f'{v:.3g}' if isinstance(v, float) else str(v))
|
||||
geo = ['case', 'variant', 'hull_slivers', 'hull_worst', 'hull_p5', 'brush_slivers', 'brush_worst', 'brush_p5', 'hull_flipped',
|
||||
'dev_max_pct', 'seam_off_plane', 'loop_edges_under_bw', 'shortest_loop_edge']
|
||||
uv = ['case', 'variant', 'uv_faces', 'uv_not_fragments_hull', 'uv_not_fragments_brush', 'uv_uv_flipped_hull', 'uv_uv_flipped_brush',
|
||||
'uv_hull_islands', 'uv_hull_src_islands', 'uv_hull_uv_area', 'uv_moved_face_sigma_min', 'uv_moved_face_sigma_max', 'uv_moved_face_aniso_min']
|
||||
for title, cols in (('Geometry (band = within 2 local edge lengths of the loop)', geo), ('UV0 carry-through', uv)):
|
||||
out.write(f'## {title}\n\n| ' + ' | '.join(cols) + ' |\n|' + '---|' * len(cols) + '\n')
|
||||
for r in rows:
|
||||
if 'uv_faces' in r: out.write('| ' + ' | '.join(f(r.get(k)) for k in cols) + ' |\n')
|
||||
out.write('\n')
|
||||
out.write('## Operations\n\n')
|
||||
for r in rows:
|
||||
ex = {k: r[k] for k in ('short_merges', 'slide', 'weld', 'owners', 'flips', 'facet_cdt', 'corners', 'corners_kept', 'crack', 'cap_uv_overlap',
|
||||
'cap_uv_area_sub', 'cap_uv_area_int', 'calls', 'complete', 'incomplete', 'steiner', 'uv_fixture_max_diff', 'hull_islands', 'rho') if k in r}
|
||||
if ex: out.write(f"- {r['case']} {r['variant']}: {json.dumps(ex, default=str)}\n")
|
||||
if len(sys.argv) > 3:
|
||||
b = json.load(open(sys.argv[3]))
|
||||
cols = ['weighted_edges', 'strips', 'spans', 'sigma_min_p5', 'sigma_min_median', 'sigma_max_median', 'sigma_max_p95', 'sigma_max_max', 'collapsed_lt_0p05']
|
||||
out.write('\n## Bevel strips (bmesh.ops.bevel with the modifier settings; sigma = 3D-to-UV singular values / hull median density)\n\n| mesh | ' + ' | '.join(cols) + ' |\n|' + '---|' * (len(cols) + 1) + '\n')
|
||||
for k, v in b.items():
|
||||
if v: out.write(f'| {k} | ' + ' | '.join(f(v.get(c)) if not isinstance(v.get(c), dict) else json.dumps(v[c]) for c in cols) + ' |\n')
|
||||
out.close(); print(open(sys.argv[2]).read())
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
//! Boolean driver for the boolean-weld spike. Reads two closed OBJ meshes (hull, cutter), runs one
|
||||
//! boolean in one kernel, writes the result OBJ and a per-triangle provenance file (0 = hull face,
|
||||
//! 1 = cutter face). Usage: spike-boolean-weld <boolmesh|manifold> <sub|int> <hull.obj> <cutter.obj> <out-prefix>
|
||||
//! 1 = cutter face). Usage: spike-boolean-weld <boolmesh|manifold> <sub|int|add> <hull.obj> <cutter.obj> <out-prefix>
|
||||
//! Round 4: `spike-boolean-weld cdt <in.txt> <out.txt>` runs spade's constrained Delaunay triangulation with
|
||||
//! refinement (interior Steiner points only, constraint edges never split) on one planar polygon set.
|
||||
use std::{fs, time::Instant};
|
||||
|
||||
fn load_obj(p: &str) -> (Vec<f64>, Vec<usize>) {
|
||||
|
|
@ -34,7 +36,7 @@ fn run_boolmesh(op: &str, a: &(Vec<f64>, Vec<usize>), b: &(Vec<f64>, Vec<usize>)
|
|||
let vb = vec![1.0f64; b.1.len()];
|
||||
let ma = Manifold::new_with_values(&a.0, &a.1, &va).expect("hull not manifold for boolmesh");
|
||||
let mb = Manifold::new_with_values(&b.0, &b.1, &vb).expect("cutter not manifold for boolmesh");
|
||||
let op = if op == "sub" { OpType::Subtract } else { OpType::Intersect };
|
||||
let op = match op { "sub" => OpType::Subtract, "add" => OpType::Add, _ => OpType::Intersect };
|
||||
let r = compute_boolean(&ma, &mb, op).expect("boolmesh failed");
|
||||
let v: Vec<f64> = r.ps.iter().flat_map(|p| [p.x as f64, p.y as f64, p.z as f64]).collect();
|
||||
let t: Vec<usize> = r.hs.iter().map(|h| h.tail).collect();
|
||||
|
|
@ -51,7 +53,7 @@ fn run_manifold(op: &str, a: &(Vec<f64>, Vec<usize>), b: &(Vec<f64>, Vec<usize>)
|
|||
};
|
||||
let (ha, hb) = (mk(a), mk(b));
|
||||
let hull_id = ha.original_id() as u32;
|
||||
let r = if op == "sub" { ha.difference(&hb) } else { ha.intersection(&hb) };
|
||||
let r = match op { "sub" => ha.difference(&hb), "add" => ha.union(&hb), _ => ha.intersection(&hb) };
|
||||
let g = r.to_meshgl64();
|
||||
let v = g.vert_properties();
|
||||
let np = g.num_prop();
|
||||
|
|
@ -65,8 +67,48 @@ fn run_manifold(op: &str, a: &(Vec<f64>, Vec<usize>), b: &(Vec<f64>, Vec<usize>)
|
|||
(v, t, prov)
|
||||
}
|
||||
|
||||
/// Input: `n m angle_deg max_add`, then n lines `x y`, then m lines `a b` (constraint edges, 0-based).
|
||||
/// Output: `V k` then k lines `x y` (the n inputs first, in order, then the Steiner points), `T j` then j lines
|
||||
/// `a b c` (inner faces only, counter-clockwise), and a last line `R complete=<bool> added=<k-n>`.
|
||||
fn run_cdt(inp: &str, out: &str) {
|
||||
use spade::{AngleLimit, ConstrainedDelaunayTriangulation, Point2, RefinementParameters, Triangulation};
|
||||
let s = fs::read_to_string(inp).expect("read cdt input");
|
||||
let mut it = s.split_whitespace();
|
||||
let mut nx = || it.next().expect("short cdt input");
|
||||
let (n, m): (usize, usize) = (nx().parse().unwrap(), nx().parse().unwrap());
|
||||
let (ang, max_add): (f64, usize) = (nx().parse().unwrap(), nx().parse().unwrap());
|
||||
let pts: Vec<Point2<f64>> = (0..n).map(|_| Point2::new(nx().parse().unwrap(), nx().parse().unwrap())).collect();
|
||||
let edges: Vec<[usize; 2]> = (0..m).map(|_| [nx().parse().unwrap(), nx().parse().unwrap()]).collect();
|
||||
let mut cdt = ConstrainedDelaunayTriangulation::<Point2<f64>>::bulk_load_cdt(pts.clone(), edges).expect("cdt bulk load");
|
||||
assert_eq!(cdt.num_vertices(), n, "spade merged duplicate input points");
|
||||
for (i, v) in cdt.fixed_vertices().enumerate().take(n) {
|
||||
let p = cdt.vertex(v).position();
|
||||
assert!(v.index() == i && p.x == pts[i].x && p.y == pts[i].y, "spade reordered input vertices");
|
||||
}
|
||||
let params = RefinementParameters::<f64>::new()
|
||||
.with_angle_limit(AngleLimit::from_deg(ang))
|
||||
.keep_constraint_edges()
|
||||
.exclude_outer_faces(true)
|
||||
.with_max_additional_vertices(max_add);
|
||||
let r = cdt.refine(params);
|
||||
let excluded: std::collections::HashSet<_> = r.excluded_faces.iter().copied().collect();
|
||||
let mut o = format!("V {}
|
||||
", cdt.num_vertices());
|
||||
for v in cdt.vertices() { let p = v.position(); o += &format!("{:.17e} {:.17e}
|
||||
", p.x, p.y); }
|
||||
let faces: Vec<_> = cdt.inner_faces().filter(|f| !excluded.contains(&f.fix())).collect();
|
||||
o += &format!("T {}
|
||||
", faces.len());
|
||||
for f in faces { let [a, b, c] = f.vertices().map(|v| v.fix().index()); o += &format!("{a} {b} {c}
|
||||
"); }
|
||||
o += &format!("R complete={} added={}
|
||||
", r.refinement_complete, cdt.num_vertices() - n);
|
||||
fs::write(out, o).unwrap();
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let a: Vec<String> = std::env::args().collect();
|
||||
if a[1] == "cdt" { return run_cdt(&a[2], &a[3]); }
|
||||
let (kernel, op, hull, cutter, out) = (&a[1], &a[2], &a[3], &a[4], &a[5]);
|
||||
let (h, c) = (load_obj(hull), load_obj(cutter));
|
||||
let t0 = Instant::now();
|
||||
|
|
|
|||
Loading…
Reference in a new issue