Skip to content

armgit / forma

Public Imported from GitHub
0

A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server

bench: add Wave 2 deep UV utilization autoresearch engine with non-overlap raster verification

wrong-nebula2e559dd85c85
diff --git a/bench/colab_autoresearch_w2.py b/bench/colab_autoresearch_w2.py
new file mode 100644
index 0000000..99b9687
--- /dev/null
+++ b/bench/colab_autoresearch_w2.py
@@ -0,0 +1,1213 @@
+#!/usr/bin/env python3
+"""
+Forma Wave 2 Deep UV Utilization Autoresearch Engine (Colab CLI / High-RAM VM).
+
+Starts from Wave 1's verified baseline (67.88% 12-mesh / 68.17% Tier-1 UV util, 0 inv)
+and runs deep structural + plateau-aware evolutionary + optional LLM autoresearch over
+`crates/forma-core/src/uv.rs` to push UV packing utilization as high as mathematically
+possible while preserving strict 1:1 invariants:
+ - 12 diverse meshes: ALL `WT=ok`, `NM=0`, `inv == 0`, UVs strictly in `[0, 1]^2`
+ - Strict inter-chart UV triangle overlap check (zero overlapping charts!)
+ - Bounded conformal stretch (`mean_stretch <= 1.045`)
+ - Full `cargo test --release -p forma-core` (`kernel_tests` + 10,000-op `fuzz_invariants`)
+
+Stops ONLY when `no_improve_streak >= uv_plateau` (default 18 consecutive non-improving rounds)
+or `--max-minutes` safety guard is reached.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import os
+import random
+import re
+import shutil
+import struct
+import subprocess
+import sys
+import tarfile
+import tempfile
+import time
+import urllib.request
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple
+
+
+ROOT = Path(__file__).resolve().parent.parent
+FORMA_BIN = ROOT / "target" / "release" / "forma"
+
+UV_SUITE: List[Tuple[str, str]] = [
+ ("box", "m = box(2, 1.5, 1) | unwrap(45, 0.01)"),
+ ("flange", "m = box(4, 2, 0.4) | cut(cyl(0.5, 1)) | cut(cyl(0.25, 1), at=[(-1.4,-0.5,0),(-1.4,0.5,0),(1.4,-0.5,0),(1.4,0.5,0)]) | unwrap(45, 0.01)"),
+ ("enclosure", "m = box(2.4, 1.6, 1.0, z0=0) | bevel(vertical, 0.2, segs=3) | shell(0.15) | unwrap(45, 0.01)"),
+ ("bevel_cyl", "m = cyl(1.0, 2.0, segs=32) | bevel(top_rim, 0.15, segs=3) | unwrap(45, 0.01)"),
+ ("sphere", "m = sphere(1.0) | unwrap(45, 0.01)"),
+ ("mug", "b = cyl(0.5, 1.0, segs=24, z0=0) | shell(0.08)\nh = arc_tube(center=(0.48,0,0.5), rx=0.25, rz=0.28, r=0.06)\nm = b | add(h) | unwrap(45, 0.01)"),
+ ("l_bracket", "h = box(2.0, 1.0, 0.4, center=(0,0,-0.8))\nv = box(0.4, 1.0, 2.0, center=(-0.8,0,0))\nm = h | add(v) | cut(cyl(0.25, 1.0, segs=24, center=(0.4,0,-0.8))) | unwrap(45, 0.01)"),
+ ("pipe_tee", "a = cyl(0.6, 4.0, segs=24, axis=x)\nb = cyl(0.5, 2.0, segs=24, center=(0,0,1))\nm = a | add(b) | cut(cyl(0.4, 4.4, segs=24, axis=x)) | unwrap(45, 0.01)"),
+ ("floorplan", "m = extrude2d([(0,0),(6,0),(6,4),(0,4)], 0.0, 0.6, holes=[[(1,1),(2.5,1),(2.5,3),(1,3)],[(3.5,1),(5,1),(5,3),(3.5,3)]]) | unwrap(45, 0.01)"),
+ ("twist_bar", "m = box(0.6, 0.6, 3.0) | deform(\"twist\", axis=z, angle=90) | unwrap(45, 0.01)"),
+ ("nurbs_swp", "r = nurbs([(0,0,0),(0,0,1.2),(1.0,0.6,2.2),(2.2,0,2.8)], degree=3, segs=24)\nm = sweep([(-0.2,-0.15),(0.2,-0.15),(0.2,0.15),(-0.2,0.15)], r, scale_end=0.5, twist=90) | unwrap(45, 0.01)"),
+ ("l_shell", "m = extrude2d([(0,0),(3,0),(3,1),(1,1),(1,3),(0,3)], 0.0, 1.2) | solidify(0.16, offset=-1.0, open_top=true) | unwrap(45, 0.01)"),
+]
+
+
+def cargo_env() -> Dict[str, str]:
+ env = os.environ.copy()
+ ncpu = os.cpu_count() or 2
+ env.setdefault("CARGO_BUILD_JOBS", str(min(ncpu, 8)))
+ if Path("/Library/Developer/CommandLineTools").exists():
+ env.setdefault("DEVELOPER_DIR", "/Library/Developer/CommandLineTools")
+ return env
+
+
+def build_forma() -> Tuple[bool, str]:
+ p = subprocess.run(
+ ["cargo", "build", "--release", "-p", "forma-cli"],
+ cwd=str(ROOT),
+ env=cargo_env(),
+ text=True,
+ capture_output=True,
+ timeout=300,
+ )
+ if p.returncode != 0:
+ return False, p.stderr[-1500:]
+ return True, "ok"
+
+
+def run_rust_tests() -> Tuple[bool, str]:
+ p = subprocess.run(
+ ["cargo", "test", "--release", "-p", "forma-core", "--", "--test-threads=1"],
+ cwd=str(ROOT),
+ env=cargo_env(),
+ text=True,
+ capture_output=True,
+ timeout=240,
+ )
+ return p.returncode == 0, (p.stdout + "\n" + p.stderr)[-1200:]
+
+
+def verify_glb_uvs_and_nonoverlap(glb_path: Path, reported_util_pct: float) -> Tuple[bool, str]:
+ """Verify UVs are finite, inside [0,1]^2, and real rasterized coverage matches reported utilization (catches overlaps!)."""
+ raw = glb_path.read_bytes()
+ jlen = int.from_bytes(raw[12:16], "little")
+ gltf = json.loads(raw[20:20 + jlen].decode())
+ bin_start = 20 + jlen + 8
+ prim = gltf["meshes"][0]["primitives"][0]
+ if "TEXCOORD_0" not in prim["attributes"]:
+ return False, "missing TEXCOORD_0"
+
+ uv_acc = gltf["accessors"][prim["attributes"]["TEXCOORD_0"]]
+ uv_bv = gltf["bufferViews"][uv_acc["bufferView"]]
+ uv_off = bin_start + uv_bv.get("byteOffset", 0) + uv_acc.get("byteOffset", 0)
+ n_verts = uv_acc["count"]
+ uvs = struct.unpack_from(f"<{n_verts * 2}f", raw, uv_off)
+ if not all(math.isfinite(x) for x in uvs):
+ return False, "non-finite UV"
+ mn, mx = min(uvs), max(uvs)
+ if mn < -1e-4 or mx > 1.0 + 1e-4:
+ return False, f"UV OOB [{mn:.4f}, {mx:.4f}]"
+
+ # Extract triangle indices
+ if "indices" in prim:
+ idx_acc = gltf["accessors"][prim["indices"]]
+ idx_bv = gltf["bufferViews"][idx_acc["bufferView"]]
+ idx_off = bin_start + idx_bv.get("byteOffset", 0) + idx_acc.get("byteOffset", 0)
+ ctype = idx_acc["componentType"]
+ fmt = "H" if ctype == 5123 else "I"
+ indices = struct.unpack_from(f"<{idx_acc['count']}{fmt}", raw, idx_off)
+ else:
+ indices = tuple(range(n_verts))
+
+ # Fast 128x128 raster coverage check: if two islands overlap, unique covered area < summed tri area!
+ G = 128
+ covered = bytearray(G * G)
+ sum_tri_area = 0.0
+ for t in range(0, len(indices) - 2, 3):
+ i0, i1, i2 = indices[t], indices[t + 1], indices[t + 2]
+ ax, ay = uvs[2 * i0], uvs[2 * i0 + 1]
+ bx, by = uvs[2 * i1], uvs[2 * i1 + 1]
+ cx, cy = uvs[2 * i2], uvs[2 * i2 + 1]
+ a2 = abs((bx - ax) * (cy - ay) - (cx - ax) * (by - ay))
+ sum_tri_area += 0.5 * a2
+ if a2 < 1e-10:
+ continue
+ x0 = max(0, min(G - 1, int(min(ax, bx, cx) * G)))
+ x1 = max(0, min(G - 1, int(max(ax, bx, cx) * G)))
+ y0 = max(0, min(G - 1, int(min(ay, by, cy) * G)))
+ y1 = max(0, min(G - 1, int(max(ay, by, cy) * G)))
+ inv_a = 1.0 / ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay))
+ for py in range(y0, y1 + 1):
+ y = (py + 0.5) / G
+ row = py * G
+ for px in range(x0, x1 + 1):
+ x = (px + 0.5) / G
+ u = ((bx - ax) * (y - ay) - (by - ay) * (x - ax)) * inv_a
+ if u < -1e-4:
+ continue
+ v = ((cx - bx) * (y - by) - (cy - by) * (x - bx)) * inv_a
+ if v < -1e-4:
+ continue
+ w = 1.0 - u - v
+ if w >= -1e-4:
+ covered[row + px] = 1
+ unique_cov_pct = sum(covered) / (G * G) * 100.0
+ sum_area_pct = sum_tri_area * 100.0
+ # Allow small rasterization discretization slack (~3.5%), catch real overlaps!
+ if sum_area_pct - unique_cov_pct > 4.5:
+ return False, f"UV overlap detected! sum_area={sum_area_pct:.1f}% vs unique_cov={unique_cov_pct:.1f}%"
+ if abs(sum_area_pct - reported_util_pct) > 2.0:
+ return False, f"UV util mismatch: reported={reported_util_pct:.1f}% vs glb={sum_area_pct:.1f}%"
+ return True, "ok"
+
+
+def eval_uv_suite(repeats: int = 2) -> Tuple[bool, Dict[str, Any]]:
+ per_mesh: Dict[str, Any] = {}
+ utils, stretches, times_ms, charts_list = [], [], [], []
+ with tempfile.TemporaryDirectory() as td:
+ tdp = Path(td)
+ for name, code in UV_SUITE:
+ out_glb = tdp / f"{name}.glb"
+ run_times = []
+ last_out = ""
+ for _ in range(repeats):
+ t0 = time.perf_counter()
+ r = subprocess.run(
+ [str(FORMA_BIN), "eval", "--strict", "--out", str(out_glb)],
+ input=code,
+ text=True,
+ capture_output=True,
+ timeout=35,
+ )
+ ms = (time.perf_counter() - t0) * 1000.0
+ if r.returncode != 0:
+ return False, {"error": f"{name} failed: {r.stderr[:240]}"}
+ last_out = r.stdout
+ run_times.append(ms)
+ if "WT=ok" not in last_out or "NM=0" not in last_out:
+ return False, {"error": f"{name} not watertight"}
+ m = re.search(r"uv: charts=(\d+) util=([\d.]+)% stretch=([\d.]+) inv=(\d+)", last_out)
+ if not m:
+ return False, {"error": f"{name} missing UV stats"}
+ charts = int(m.group(1))
+ util = float(m.group(2))
+ stretch = float(m.group(3))
+ inv = int(m.group(4))
+ if inv != 0:
+ return False, {"error": f"{name} has {inv} inverted UV tris"}
+ ok_ov, msg_ov = verify_glb_uvs_and_nonoverlap(out_glb, util)
+ if not ok_ov:
+ return False, {"error": f"{name}: {msg_ov}"}
+ med_ms = sorted(run_times)[len(run_times) // 2]
+ per_mesh[name] = {
+ "charts": charts,
+ "util": util,
+ "stretch": stretch,
+ "inv": inv,
+ "ms": round(med_ms, 2),
+ }
+ utils.append(util)
+ stretches.append(stretch)
+ times_ms.append(med_ms)
+ charts_list.append(charts)
+
+ mean_util = sum(utils) / len(utils)
+ mean_stretch = sum(stretches) / len(stretches)
+ total_ms = sum(times_ms)
+ mean_charts = sum(charts_list) / len(charts_list)
+ tier1_util = sum(per_mesh[k]["util"] for k in ("box", "flange", "enclosure", "bevel_cyl", "sphere", "mug")) / 6.0
+
+ if mean_stretch > 1.045:
+ return False, {"error": f"mean_stretch {mean_stretch:.4f} > 1.045"}
+ if mean_charts > 60:
+ return False, {"error": f"too many fragmented charts (mean={mean_charts:.1f} > 60)"}
+ if total_ms > 900.0:
+ return False, {"error": f"too slow ({total_ms:.1f}ms > 900ms)"}
+
+ # Wave 2 objective: strongly prioritizes UV utilization % while keeping stretch low,
+ # avoiding excessive chart fragmentation, and staying fast!
+ score = mean_util - 25.0 * (mean_stretch - 1.0) - 0.012 * total_ms - 0.04 * max(0.0, mean_charts - 24.0)
+ return True, {
+ "score": round(score, 4),
+ "mean_util": round(mean_util, 3),
+ "tier1_util": round(tier1_util, 3),
+ "mean_stretch": round(mean_stretch, 4),
+ "mean_charts": round(mean_charts, 2),
+ "total_ms": round(total_ms, 2),
+ "per_mesh": per_mesh,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Wave 2 Deep Structural UV Algorithmic Upgrades
+# ---------------------------------------------------------------------------
+
+def patch_w2_multicut_concave_split(src: str) -> Optional[str]:
+ """W2-1: Multi-cut concave bisection — tests cuts at [0.25, 0.38, 0.50, 0.62, 0.75] along U and V to slice right along narrow necks & holes!"""
+ old = """ for split_u in [true, false] {
+ let mid = if split_u { ch.w * 0.5 } else { ch.h * 0.5 };
+ let mut a_faces = Vec::new();
+ let mut b_faces = Vec::new();
+ for (lfi, &fi) in ch.faces.iter().enumerate() {
+ let lv = &ch.face_local_verts[lfi];
+ let avg = lv.iter().map(|&v| if split_u { ch.uvs[v][0] } else { ch.uvs[v][1] }).sum::<f64>()
+ / (lv.len().max(1) as f64);
+ if avg <= mid { a_faces.push(fi); } else { b_faces.push(fi); }
+ }
+ if a_faces.is_empty() || b_faces.is_empty() { continue; }
+ let mut comps = Vec::new();
+ let mut sum_bb = 0.0;
+ for half in [a_faces, b_faces] {
+ for comp in split_connected_components(&half, &face_nbrs) {
+ let sub = solve_chart_lscm(mesh, &comp);
+ sum_bb += (sub.w + 0.02 * ch.w.max(ch.h)) * (sub.h + 0.02 * ch.w.max(ch.h));
+ comps.push(comp);
+ }
+ }
+ if sum_bb < ch_bb * split_gain_ratio {
+ if best_children.as_ref().map_or(true, |(b, _)| sum_bb < *b) {
+ best_children = Some((sum_bb, comps));
+ }
+ }
+ }"""
+ new = """ let split_pad_weight: f64 = 0.018;
+ for split_u in [true, false] {
+ let span = if split_u { ch.w } else { ch.h };
+ for &frac in &[0.28f64, 0.40, 0.50, 0.60, 0.72] {
+ let cut = span * frac;
+ let mut a_faces = Vec::new();
+ let mut b_faces = Vec::new();
+ for (lfi, &fi) in ch.faces.iter().enumerate() {
+ let lv = &ch.face_local_verts[lfi];
+ let avg = lv.iter().map(|&v| if split_u { ch.uvs[v][0] } else { ch.uvs[v][1] }).sum::<f64>()
+ / (lv.len().max(1) as f64);
+ if avg <= cut { a_faces.push(fi); } else { b_faces.push(fi); }
+ }
+ if a_faces.len() < 2 || b_faces.len() < 2 { continue; }
+ let mut comps = Vec::new();
+ let mut sum_bb = 0.0;
+ for half in [a_faces, b_faces] {
+ for comp in split_connected_components(&half, &face_nbrs) {
+ let sub = solve_chart_lscm(mesh, &comp);
+ let p = split_pad_weight * ch.w.max(ch.h);
+ sum_bb += (sub.w + p) * (sub.h + p);
+ comps.push(comp);
+ }
+ }
+ if sum_bb < ch_bb * split_gain_ratio {
+ if best_children.as_ref().map_or(true, |(b, _)| sum_bb < *b) {
+ best_children = Some((sum_bb, comps));
+ }
+ }
+ }
+ }"""
+ if old not in src:
+ return None
+ return src.replace(old, new, 1)
+
+
+def patch_w2_rich_packers_and_skyline(src: str) -> Optional[str]:
+ """W2-2: Add BLSF + ContactPoint MaxRects + 7 sort orders + Skyline Bottom-Left packer + deterministic 2-opt swap refinement!"""
+ old_enum = """#[derive(Clone, Copy)]
+enum PackHeuristic {
+ Bssf, // Best Short Side Fit
+ Baf, // Best Area Fit
+ Bl, // Bottom-Left
+}"""
+ new_enum = """#[derive(Clone, Copy)]
+enum PackHeuristic {
+ Bssf, // Best Short Side Fit
+ Blsf, // Best Long Side Fit
+ Baf, // Best Area Fit
+ Bl, // Bottom-Left
+ Cp, // Contact Point (maximizes touching perimeter!)
+}"""
+ if old_enum not in src:
+ return None
+ out = src.replace(old_enum, new_enum, 1)
+
+ old_try = """fn try_pack_single(
+ sizes: &[(f64, f64)],
+ order: &[usize],
+ heur: PackHeuristic,
+ bin: f64,
+ pad: f64,
+) -> Option<Vec<(f64, f64, bool)>> {
+ let mut free = vec![Rect { x: 0.0, y: 0.0, w: bin, h: bin }];
+ let mut placed = vec![(0.0, 0.0, false); sizes.len()];
+
+ for &idx in order {
+ let rw = sizes[idx].0 + pad;
+ let rh = sizes[idx].1 + pad;
+ let mut best_p1 = f64::INFINITY;
+ let mut best_p2 = f64::INFINITY;
+ let mut best_pos: Option<(f64, f64, f64, f64, bool)> = None;
+
+ for fr in &free {
+ for &(cand_w, cand_h, rot) in &[(rw, rh, false), (rh, rw, true)] {
+ if cand_w <= fr.w + 1e-9 && cand_h <= fr.h + 1e-9 {
+ let (p1, p2) = match heur {
+ PackHeuristic::Bssf => ((fr.w - cand_w).min(fr.h - cand_h), (fr.w - cand_w).max(fr.h - cand_h)),
+ PackHeuristic::Baf => (fr.w * fr.h - cand_w * cand_h, (fr.w - cand_w).min(fr.h - cand_h)),
+ PackHeuristic::Bl => (fr.y + cand_h, fr.x),
+ };
+ if p1 < best_p1 - 1e-9 || ((p1 - best_p1).abs() <= 1e-9 && p2 < best_p2) {
+ best_p1 = p1;
+ best_p2 = p2;
+ best_pos = Some((fr.x, fr.y, cand_w, cand_h, rot));
+ }
+ }
+ }
+ }
+
+ let (px, py, pw, ph, rot) = best_pos?;
+ placed[idx] = (px + pad * 0.5, py + pad * 0.5, rot);"""
+
+ new_try = """fn try_pack_single(
+ sizes: &[(f64, f64)],
+ order: &[usize],
+ heur: PackHeuristic,
+ bin: f64,
+ pad: f64,
+) -> Option<Vec<(f64, f64, bool)>> {
+ let mut free = vec![Rect { x: 0.0, y: 0.0, w: bin, h: bin }];
+ let mut placed = vec![(0.0, 0.0, false); sizes.len()];
+ let mut used: Vec<Rect> = if matches!(heur, PackHeuristic::Cp) {
+ Vec::with_capacity(sizes.len())
+ } else {
+ Vec::new()
+ };
+
+ for &idx in order {
+ let rw = sizes[idx].0 + pad;
+ let rh = sizes[idx].1 + pad;
+ let mut best_p1 = f64::INFINITY;
+ let mut best_p2 = f64::INFINITY;
+ let mut best_pos: Option<(f64, f64, f64, f64, bool)> = None;
+
+ for fr in &free {
+ for &(cand_w, cand_h, rot) in &[(rw, rh, false), (rh, rw, true)] {
+ if cand_w <= fr.w + 1e-9 && cand_h <= fr.h + 1e-9 {
+ let (p1, p2) = match heur {
+ PackHeuristic::Bssf => ((fr.w - cand_w).min(fr.h - cand_h), (fr.w - cand_w).max(fr.h - cand_h)),
+ PackHeuristic::Blsf => ((fr.w - cand_w).max(fr.h - cand_h), (fr.w - cand_w).min(fr.h - cand_h)),
+ PackHeuristic::Baf => (fr.w * fr.h - cand_w * cand_h, (fr.w - cand_w).min(fr.h - cand_h)),
+ PackHeuristic::Bl => (fr.y + cand_h, fr.x),
+ PackHeuristic::Cp => {
+ let mut contact = 0.0f64;
+ if fr.x < 1e-6 || (fr.x + cand_w - bin).abs() < 1e-6 { contact += cand_h; }
+ if fr.y < 1e-6 || (fr.y + cand_h - bin).abs() < 1e-6 { contact += cand_w; }
+ for u in &used {
+ if (u.x - (fr.x + cand_w)).abs() < 1e-5 || (u.x + u.w - fr.x).abs() < 1e-5 {
+ let ov = (u.y + u.h).min(fr.y + cand_h) - u.y.max(fr.y);
+ if ov > 0.0 { contact += ov; }
+ }
+ if (u.y - (fr.y + cand_h)).abs() < 1e-5 || (u.y + u.h - fr.y).abs() < 1e-5 {
+ let ov = (u.x + u.w).min(fr.x + cand_w) - u.x.max(fr.x);
+ if ov > 0.0 { contact += ov; }
+ }
+ }
+ (-contact, (fr.w - cand_w).min(fr.h - cand_h))
+ }
+ };
+ if p1 < best_p1 - 1e-9 || ((p1 - best_p1).abs() <= 1e-9 && p2 < best_p2) {
+ best_p1 = p1;
+ best_p2 = p2;
+ best_pos = Some((fr.x, fr.y, cand_w, cand_h, rot));
+ }
+ }
+ }
+ }
+
+ let (px, py, pw, ph, rot) = best_pos?;
+ placed[idx] = (px + pad * 0.5, py + pad * 0.5, rot);
+ if matches!(heur, PackHeuristic::Cp) {
+ used.push(Rect { x: px, y: py, w: pw, h: ph });
+ }"""
+ if old_try not in out:
+ return None
+ out = out.replace(old_try, new_try, 1)
+
+ old_multi = """ for ord in [&ord_max, &ord_area, &ord_perim] {
+ for heur in [PackHeuristic::Bssf, PackHeuristic::Baf, PackHeuristic::Bl] {
+ if let Some(p) = try_pack_single(sizes, ord, heur, bin, pad) {
+ return Some(p);
+ }
+ }
+ }
+ None"""
+ new_multi = """ let mut ord_diff: Vec<usize> = (0..n).collect();
+ ord_diff.sort_by(|&a, &b| {
+ (sizes[b].0 - sizes[b].1).abs().total_cmp(&(sizes[a].0 - sizes[a].1).abs())
+ .then_with(|| (sizes[b].0 * sizes[b].1).total_cmp(&(sizes[a].0 * sizes[a].1)))
+ });
+ let mut ord_min: Vec<usize> = (0..n).collect();
+ ord_min.sort_by(|&a, &b| {
+ sizes[b].0.min(sizes[b].1).total_cmp(&sizes[a].0.min(sizes[a].1))
+ .then_with(|| sizes[b].0.max(sizes[b].1).total_cmp(&sizes[a].0.max(sizes[a].1)))
+ });
+ let mut ord_ratio: Vec<usize> = (0..n).collect();
+ ord_ratio.sort_by(|&a, &b| {
+ let ra = sizes[a].0.max(sizes[a].1) / sizes[a].0.min(sizes[a].1).max(1e-6);
+ let rb = sizes[b].0.max(sizes[b].1) / sizes[b].0.min(sizes[b].1).max(1e-6);
+ rb.total_cmp(&ra).then_with(|| (sizes[b].0 * sizes[b].1).total_cmp(&(sizes[a].0 * sizes[a].1)))
+ });
+
+ // Fast heuristics first, then deeper ContactPoint & extra sort orders
+ for ord in [&ord_max, &ord_area, &ord_perim, &ord_diff, &ord_min, &ord_ratio] {
+ for heur in [PackHeuristic::Bssf, PackHeuristic::Blsf, PackHeuristic::Baf, PackHeuristic::Bl] {
+ if let Some(p) = try_pack_single(sizes, ord, heur, bin, pad) {
+ return Some(p);
+ }
+ }
+ }
+ if n <= 36 {
+ for ord in [&ord_area, &ord_max, &ord_perim] {
+ if let Some(p) = try_pack_single(sizes, ord, PackHeuristic::Cp, bin, pad) {
+ return Some(p);
+ }
+ }
+ }
+ // Deterministic local 2-opt order swap search for compact chart sets (boosts 5-28 chart meshes!)
+ let perm_trials: usize = 16;
+ if n >= 4 && n <= 28 {
+ let mut ord = ord_area.clone();
+ let mut seed: u64 = 0x9E37_79B9_7F4A_7C15 ^ (n as u64);
+ for _ in 0..perm_trials {
+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ let i = ((seed >> 33) as usize) % n;
+ seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ let j = ((seed >> 33) as usize) % n;
+ if i == j { continue; }
+ ord.swap(i, j);
+ if let Some(p) = try_pack_single(sizes, &ord, PackHeuristic::Bssf, bin, pad) {
+ return Some(p);
+ }
+ if let Some(p) = try_pack_single(sizes, &ord, PackHeuristic::Baf, bin, pad) {
+ return Some(p);
+ }
+ ord.swap(i, j);
+ }
+ }
+ None"""
+ if old_multi not in out:
+ return None
+ return out.replace(old_multi, new_multi, 1)
+
+
+def patch_w2_pack_helper_and_bottleneck_split(src: str) -> Optional[str]:
+ """W2-3: Atlas-feedback anti-bottleneck iterative chart splitter!
+ Packs charts, and if atlas utilization is held back by a single oversized/square/long bottleneck chart
+ (e.g. 6 equal sphere petals in a 3x3 grid, or long curved cylinder strips), splits that bottleneck chart
+ and keeps the split ONLY if total atlas utilization strictly rises with 0 UV inversions!"""
+ old = """ let sizes: Vec<(f64, f64)> = charts.iter().map(|c| (c.w, c.h)).collect();
+ let total_rect_area: f64 = sizes.iter().map(|(w, h)| w * h).sum();
+ let max_dim: f64 = sizes.iter().map(|(w, h)| w.max(*h)).fold(0.0, f64::max);
+ let m_frac = (margin as f64).clamp(0.0, 0.05);
+
+ // Multi-strategy MaxRects binary search
+ let mut lo = total_rect_area.sqrt().max(max_dim) * 0.96;
+ let mut hi = (total_rect_area.sqrt() * 2.5).max(max_dim * 2.0) + 1e-4;
+ while try_pack_maxrects(&sizes, hi, hi * m_frac).is_none() {
+ hi *= 1.5;
+ }
+ // Pack with `bin + pad` virtual space so outer edges don't waste an extra full margin,
+ // while keeping strict >= margin separation between every pair of islands!
+ let mut mr_pack = try_pack_maxrects(&sizes, hi + hi * m_frac, hi * m_frac).unwrap();
+ let mut best_bin = hi;
+ for _ in 0..16 {
+ let mid = 0.5 * (lo + hi);
+ let pad = mid * m_frac;
+ if let Some(p) = try_pack_maxrects(&sizes, mid + pad, pad) {
+ // Verify all placed islands fit within [0, mid] after removing outer half-pad
+ let ok = p.iter().enumerate().all(|(i, &(x, y, rot))| {
+ let (w, h) = if rot { (sizes[i].1, sizes[i].0) } else { sizes[i] };
+ let nx = x - pad * 0.5;
+ let ny = y - pad * 0.5;
+ nx >= -1e-9 && ny >= -1e-9 && nx + w <= mid + 1e-6 && ny + h <= mid + 1e-6
+ });
+ if ok {
+ mr_pack = p.into_iter().map(|(x, y, rot)| ((x - pad * 0.5).max(0.0), (y - pad * 0.5).max(0.0), rot)).collect();
+ best_bin = mid;
+ hi = mid;
+ } else {
+ lo = mid;
+ }
+ } else {
+ lo = mid;
+ }
+ }
+ let best_pack: Vec<(f64, f64, u8)> = mr_pack
+ .into_iter()
+ .map(|(x, y, rot)| (x, y, if rot { 1 } else { 0 }))
+ .collect();"""
+
+ new = """ let m_frac = (margin as f64).clamp(0.0, 0.05);
+ let pack_charts_maxrects = |chs: &[Chart]| -> (f64, Vec<(f64, f64, u8)>) {
+ let sizes: Vec<(f64, f64)> = chs.iter().map(|c| (c.w, c.h)).collect();
+ let total_rect_area: f64 = sizes.iter().map(|(w, h)| w * h).sum();
+ let max_dim: f64 = sizes.iter().map(|(w, h)| w.max(*h)).fold(0.0, f64::max);
+ let mut lo = total_rect_area.sqrt().max(max_dim) * 0.94;
+ let mut hi = (total_rect_area.sqrt() * 2.5).max(max_dim * 2.0) + 1e-4;
+ while try_pack_maxrects(&sizes, hi + hi * m_frac, hi * m_frac).is_none() {
+ hi *= 1.5;
+ }
+ let pad0 = hi * m_frac;
+ let mut mr_pack: Vec<(f64, f64, bool)> = try_pack_maxrects(&sizes, hi + pad0, pad0)
+ .unwrap()
+ .into_iter()
+ .map(|(x, y, rot)| ((x - pad0 * 0.5).max(0.0), (y - pad0 * 0.5).max(0.0), rot))
+ .collect();
+ let mut b_bin = hi;
+ for _ in 0..16 {
+ let mid = 0.5 * (lo + hi);
+ let pad = mid * m_frac;
+ if let Some(p) = try_pack_maxrects(&sizes, mid + pad, pad) {
+ let ok = p.iter().enumerate().all(|(i, &(x, y, rot))| {
+ let (w, h) = if rot { (sizes[i].1, sizes[i].0) } else { sizes[i] };
+ let nx = x - pad * 0.5;
+ let ny = y - pad * 0.5;
+ nx >= -1e-9 && ny >= -1e-9 && nx + w <= mid + 1e-6 && ny + h <= mid + 1e-6
+ });
+ if ok {
+ mr_pack = p.into_iter().map(|(x, y, rot)| ((x - pad * 0.5).max(0.0), (y - pad * 0.5).max(0.0), rot)).collect();
+ b_bin = mid;
+ hi = mid;
+ } else {
+ lo = mid;
+ }
+ } else {
+ lo = mid;
+ }
+ }
+ let pack_u8 = mr_pack.into_iter().map(|(x, y, rot)| (x, y, if rot { 1 } else { 0 })).collect();
+ (b_bin, pack_u8)
+ };
+
+ let (mut best_bin, mut best_pack) = pack_charts_maxrects(&charts);
+
+ // Atlas-Feedback Anti-Bottleneck Splitter:
+ // Directly optimizes real UV bin size by testing splits of the largest / most-wasteful / longest
+ // bottleneck charts (e.g. breaks 6-in-3x3 sphere grid deadlocks and long cylinder/bevel strips!)
+ // and ONLY keeps a split if it strictly shrinks `best_bin` with 0 inverted UV tris!
+ let max_repack_splits: usize = 5;
+ let repack_min_gain: f64 = 0.985;
+ let repack_min_faces: usize = 4;
+ let max_total_charts: usize = 42;
+ let chart_has_inversions = |ch: &Chart| -> bool {
+ for (lfi, &fi) in ch.faces.iter().enumerate() {
+ let lv = &ch.face_local_verts[lfi];
+ for [ca, cb, cc] in mesh.triangulate_face_corners(fi) {
+ let ua = ch.uvs[lv[ca]];
+ let ub = ch.uvs[lv[cb]];
+ let uc = ch.uvs[lv[cc]];
+ let sa = 0.5 * ((ub[0] - ua[0]) * (uc[1] - ua[1]) - (uc[0] - ua[0]) * (ub[1] - ua[1]));
+ if sa < -1e-10 { return true; }
+ }
+ }
+ false
+ };
+
+ for _step in 0..max_repack_splits {
+ if charts.len() >= max_total_charts { break; }
+ // Rank top-4 bottleneck charts by (rect_area * (1.2 - fill) + max_dim^2 * 0.25)
+ let mut cands: Vec<(usize, f64)> = charts.iter().enumerate()
+ .filter(|(_, c)| c.faces.len() >= repack_min_faces)
+ .map(|(i, c)| {
+ let bb = c.w * c.h;
+ let a3: f64 = c.faces.iter().map(|&fi| mesh.face_area(fi)).sum();
+ let fill = (a3 / bb.max(1e-9)).clamp(0.1, 1.0);
+ let long = c.w.max(c.h);
+ let score = bb * (1.35 - fill) + long * long * 0.30;
+ (i, score)
+ })
+ .collect();
+ cands.sort_by(|a, b| b.1.total_cmp(&a.1));
+
+ let mut improved_this_step = false;
+ for &(ci, _) in cands.iter().take(4) {
+ let ch = &charts[ci];
+ let split_u = ch.w >= ch.h;
+ let mid = if split_u { ch.w * 0.5 } else { ch.h * 0.5 };
+ let mut a_faces = Vec::new();
+ let mut b_faces = Vec::new();
+ for (lfi, &fi) in ch.faces.iter().enumerate() {
+ let lv = &ch.face_local_verts[lfi];
+ let avg = lv.iter().map(|&v| if split_u { ch.uvs[v][0] } else { ch.uvs[v][1] }).sum::<f64>()
+ / (lv.len().max(1) as f64);
+ if avg <= mid { a_faces.push(fi); } else { b_faces.push(fi); }
+ }
+ if a_faces.len() < 2 || b_faces.len() < 2 { continue; }
+ let mut new_subs: Vec<Chart> = Vec::new();
+ let mut bad = false;
+ for half in [a_faces, b_faces] {
+ for comp in split_connected_components(&half, &face_nbrs) {
+ let sub = solve_chart_lscm(mesh, &comp);
+ if chart_has_inversions(&sub) {
+ bad = true;
+ break;
+ }
+ new_subs.push(sub);
+ }
+ if bad { break; }
+ }
+ if bad || new_subs.is_empty() || charts.len() - 1 + new_subs.len() > max_total_charts {
+ continue;
+ }
+ let mut trial = Vec::with_capacity(charts.len() + new_subs.len());
+ for (idx, c) in charts.iter().enumerate() {
+ if idx != ci { trial.push(c.clone()); }
+ }
+ trial.extend(new_subs);
+ let (cand_bin, cand_pack) = pack_charts_maxrects(&trial);
+ if cand_bin < best_bin * repack_min_gain {
+ charts = trial;
+ best_bin = cand_bin;
+ best_pack = cand_pack;
+ improved_this_step = true;
+ break;
+ }
+ }
+ if !improved_this_step { break; }
+ }"""
+ if old not in src:
+ return None
+ return src.replace(old, new, 1)
+
+
+def patch_w2_exact_cylindrical_strip_unwrap(src: str) -> Optional[str]:
+ """W2-4: Analytic developable/cylindrical unwrap for curved smooth quad strips (bevel_cyl, mug, pipe_tee)!
+ Detects charts whose face normals lie mostly in a single plane (cylinder/cone/extruded fillet) and
+ unrolls them by exact arc-length x axis-height into near-100%-fill straight rectangles with ~1.000 stretch!"""
+ old = """ // Check if chart is nearly planar (all face normals within ~2 deg of avg_n)
+ let is_planar = faces.iter().all(|&fi| mesh.face_normal(fi).dot(n_dir) > 0.9994);"""
+ new = """ // Check if chart is nearly planar (all face normals within ~2 deg of avg_n)
+ let is_planar = faces.iter().all(|&fi| mesh.face_normal(fi).dot(n_dir) > 0.9994);
+
+ // Analytic cylindrical/developable strip fast-path:
+ // If all face normals are nearly perpendicular to a dominant cylinder axis (e.g. X, Y, or Z),
+ // unroll directly into (arc_length, axial_height) -> exact 1.000 stretch & 100% rectangular fill!
+ let mut used_cyl_unwrap = false;
+ let cyl_perp_tol: f64 = 0.035;
+ if !is_planar && faces.len() >= 3 {
+ let mut best_axis: Option<Vec3> = None;
+ for ax in [Vec3::Z, Vec3::Y, Vec3::X] {
+ if faces.iter().all(|&fi| mesh.face_normal(fi).dot(ax).abs() < cyl_perp_tol) {
+ best_axis = Some(ax);
+ break;
+ }
+ }
+ if let Some(ax) = best_axis {
+ let u_ref = if ax.z.abs() < 0.9 { Vec3::Z } else { Vec3::X };
+ let b1 = u_ref.cross(ax).normalized();
+ let b2 = ax.cross(b1).normalized();
+ // Estimate cylinder center from vertex centroid in (b1, b2) plane
+ let mut c2 = [0.0f64; 2];
+ for &gvi in &local_to_global {
+ let p = mesh.verts[gvi];
+ c2[0] += p.dot(b1);
+ c2[1] += p.dot(b2);
+ }
+ c2[0] /= n_verts.max(1) as f64;
+ c2[1] /= n_verts.max(1) as f64;
+ let mut mean_r = 0.0f64;
+ let mut angles = Vec::with_capacity(n_verts);
+ for &gvi in &local_to_global {
+ let p = mesh.verts[gvi];
+ let dx = p.dot(b1) - c2[0];
+ let dy = p.dot(b2) - c2[1];
+ let r = dx.hypot(dy);
+ mean_r += r;
+ angles.push(dy.atan2(dx));
+ }
+ mean_r /= n_verts.max(1) as f64;
+ // Check angular span < 300 deg (open cylindrical chart, no seam wraparound!)
+ if mean_r > 1e-4 {
+ let ref_ang = angles[0];
+ let mut unwrapped_ang = Vec::with_capacity(n_verts);
+ let (mut mn_a, mut mx_a) = (f64::INFINITY, f64::NEG_INFINITY);
+ for &a in &angles {
+ let mut d = a - ref_ang;
+ while d > std::f64::consts::PI { d -= 2.0 * std::f64::consts::PI; }
+ while d < -std::f64::consts::PI { d += 2.0 * std::f64::consts::PI; }
+ let ua = ref_ang + d;
+ mn_a = mn_a.min(ua);
+ mx_a = mx_a.max(ua);
+ unwrapped_ang.push(ua);
+ }
+ if (mx_a - mn_a) < 5.0 {
+ let mut cand_uvs = Vec::with_capacity(n_verts);
+ for (lvi, &gvi) in local_to_global.iter().enumerate() {
+ let p = mesh.verts[gvi];
+ cand_uvs.push([unwrapped_ang[lvi] * mean_r, p.dot(ax)]);
+ }
+ // Verify strictly positive orientation & 0 inverted tris before accepting!
+ let mut pos = 0usize;
+ let mut neg = 0usize;
+ for (idx, &fi) in faces.iter().enumerate() {
+ let lv = &face_local_verts[idx];
+ for [ca, cb, cc] in mesh.triangulate_face_corners(fi) {
+ let (a, b, c) = (lv[ca], lv[cb], lv[cc]);
+ let sa = (cand_uvs[b][0] - cand_uvs[a][0]) * (cand_uvs[c][1] - cand_uvs[a][1])
+ - (cand_uvs[c][0] - cand_uvs[a][0]) * (cand_uvs[b][1] - cand_uvs[a][1]);
+ if sa > 1e-10 { pos += 1; } else if sa < -1e-10 { neg += 1; }
+ }
+ }
+ if neg == 0 && pos > 0 {
+ uvs = cand_uvs;
+ used_cyl_unwrap = true;
+ } else if pos == 0 && neg > 0 {
+ for uv in &mut cand_uvs { uv[0] = -uv[0]; }
+ uvs = cand_uvs;
+ used_cyl_unwrap = true;
+ }
+ }
+ }
+ }
+ }"""
+ if old not in src:
+ return None
+ out = src.replace(old, new, 1)
+ old_if = " if !is_planar && n_verts >= 4 {"
+ new_if = " if !is_planar && !used_cyl_unwrap && n_verts >= 4 {"
+ if old_if not in out:
+ return None
+ return out.replace(old_if, new_if, 1)
+
+
+def patch_w2_true_margin_silhouette_nesting(src: str) -> Optional[str]:
+ """W2-5: True-margin 128x128 exact silhouette bitmask nesting (fixes Wave 1's 2x over-padding bug so islands actually tuck into hollow flange bores & circle corners!)."""
+ anchor = " let inv_bin = 1.0 / best_bin.max(1e-9);"
+ if anchor not in src:
+ return None
+ helper = """/// True-margin 128x128 exact-silhouette bitmask atlas packer:
+/// Dilates triangles by exact half-margin (no 2x over-padding!) and scans 4 rotations (0/90/180/270),
+/// letting small charts nest directly inside concave flange holes & circular cap corners!
+fn try_pack_silhouette_128(
+ mesh: &PolyMesh,
+ charts: &[Chart],
+ bin: f64,
+ margin_frac: f64,
+) -> Option<Vec<(f64, f64, u8)>> {
+ const GRID: usize = 128;
+ let scale = (GRID as f64) / bin.max(1e-9);
+ let pad_f = (margin_frac * (GRID as f64) * 0.5).max(0.55);
+ let pad_i = (pad_f.ceil() as i32).clamp(1, 3);
+
+ let mut order: Vec<usize> = (0..charts.len()).collect();
+ order.sort_by(|&a, &b| {
+ (charts[b].w * charts[b].h)
+ .total_cmp(&(charts[a].w * charts[a].h))
+ .then_with(|| charts[b].w.max(charts[b].h).total_cmp(&charts[a].w.max(charts[a].h)))
+ });
+
+ let mut atlas = [0u128; GRID];
+ let mut placed = vec![(0.0, 0.0, 0u8); charts.len()];
+
+ for idx in order {
+ let ch = &charts[idx];
+ let mut best: Option<(usize, usize, usize, u8, Vec<u128>)> = None;
+
+ for rot in 0..4u8 {
+ let (cw, ch_h) = if rot % 2 == 0 { (ch.w, ch.h) } else { (ch.h, ch.w) };
+ let gw = ((cw * scale).ceil() as usize + (pad_i as usize) * 2).min(GRID);
+ let gh = ((ch_h * scale).ceil() as usize + (pad_i as usize) * 2).min(GRID);
+ if gw > GRID || gh > GRID { continue; }
+ let mut rows = vec![0u128; gh];
+ let xform = |u: f64, v: f64| -> (f64, f64) {
+ let (ru, rv) = match rot {
+ 0 => (u, v),
+ 1 => (v, ch.w - u),
+ 2 => (ch.w - u, ch.h - v),
+ _ => (ch.h - v, u),
+ };
+ (ru * scale + (pad_i as f64), rv * scale + (pad_i as f64))
+ };
+ for (lfi, &fi) in ch.faces.iter().enumerate() {
+ let lv = &ch.face_local_verts[lfi];
+ for [ca, cb, cc] in mesh.triangulate_face_corners(fi) {
+ let (ax, ay) = xform(ch.uvs[lv[ca]][0], ch.uvs[lv[ca]][1]);
+ let (bx, by) = xform(ch.uvs[lv[cb]][0], ch.uvs[lv[cb]][1]);
+ let (cx, cy) = xform(ch.uvs[lv[cc]][0], ch.uvs[lv[cc]][1]);
+ let min_x = (ax.min(bx).min(cx).floor() as i32 - pad_i).clamp(0, gw as i32 - 1);
+ let max_x = (ax.max(bx).max(cx).ceil() as i32 + pad_i).clamp(0, gw as i32 - 1);
+ let min_y = (ay.min(by).min(cy).floor() as i32 - pad_i).clamp(0, gh as i32 - 1);
+ let max_y = (ay.max(by).max(cy).ceil() as i32 + pad_i).clamp(0, gh as i32 - 1);
+ let area = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
+ let sgn = if area >= 0.0 { 1.0 } else { -1.0 };
+ let e01 = ((bx - ax).hypot(by - ay)).max(1e-6);
+ let e12 = ((cx - bx).hypot(cy - by)).max(1e-6);
+ let e20 = ((ax - cx).hypot(ay - cy)).max(1e-6);
+ let tol = pad_f + 0.35;
+ for py in min_y..=max_y {
+ let y = py as f64 + 0.5;
+ let mut m = rows[py as usize];
+ for px in min_x..=max_x {
+ let x = px as f64 + 0.5;
+ let w0 = ((bx - ax) * (y - ay) - (by - ay) * (x - ax)) * sgn / e01;
+ let w1 = ((cx - bx) * (y - by) - (cy - by) * (x - bx)) * sgn / e12;
+ let w2 = ((ax - cx) * (y - cy) - (ay - cy) * (x - cx)) * sgn / e20;
+ if w0 >= -tol && w1 >= -tol && w2 >= -tol {
+ m |= 1u128 << (px as u32);
+ }
+ }
+ rows[py as usize] = m;
+ }
+ }
+ }
+ let max_y = GRID - gh;
+ let max_x = GRID - gw;
+ 'scan: for gy in 0..=max_y {
+ for gx in 0..=max_x {
+ let mut hit = false;
+ for ry in 0..gh {
+ if (atlas[gy + ry] & (rows[ry] << (gx as u32))) != 0 {
+ hit = true;
+ break;
+ }
+ }
+ if !hit {
+ let score = (gy + gh).max(gx + gw) * 256 + gy * 4 + gx;
+ if best.as_ref().map_or(true, |b| score < b.0) {
+ best = Some((score, gx, gy, rot, rows));
+ }
+ break 'scan;
+ }
+ }
+ }
+ }
+
+ let (_, gx, gy, rot, rows) = best?;
+ let ox = ((gx as f64) + (pad_i as f64)) / scale;
+ let oy = ((gy as f64) + (pad_i as f64)) / scale;
+ let (cw, ch_h) = if rot % 2 == 0 { (ch.w, ch.h) } else { (ch.h, ch.w) };
+ if ox + cw > bin + 1e-5 || oy + ch_h > bin + 1e-5 {
+ return None;
+ }
+ for (ry, &rm) in rows.iter().enumerate() {
+ atlas[gy + ry] |= rm << (gx as u32);
+ }
+ placed[idx] = (ox, oy, rot);
+ }
+ Some(placed)
+}
+
+"""
+ fn_anchor = "pub fn unwrap_lscm("
+ if fn_anchor not in src:
+ return None
+ out = src.replace(fn_anchor, helper + fn_anchor, 1)
+ call_snip = """ // True-margin exact silhouette nesting: beats MaxRects whenever hollow/curved charts have >10% bbox slack!
+ let total_mesh_area: f64 = charts.iter().flat_map(|c| c.faces.iter()).map(|&fi| mesh.face_area(fi)).sum();
+ let total_rect_area_now: f64 = charts.iter().map(|c| c.w * c.h).sum();
+ let max_dim_now: f64 = charts.iter().map(|c| c.w.max(c.h)).fold(0.0, f64::max);
+ let hollow_slack_ratio: f64 = 1.10;
+ if charts.len() >= 4 && charts.len() <= 40 && total_rect_area_now > total_mesh_area * hollow_slack_ratio {
+ let mut blo = total_mesh_area.sqrt().max(max_dim_now * 1.01);
+ let mut bhi = best_bin;
+ if bhi > blo * 1.02 {
+ for _ in 0..7 {
+ let mid = 0.5 * (blo + bhi);
+ if let Some(bp) = try_pack_silhouette_128(mesh, &charts, mid, m_frac) {
+ best_pack = bp;
+ best_bin = mid;
+ bhi = mid;
+ } else {
+ blo = mid;
+ }
+ }
+ }
+ }
+
+ let inv_bin = 1.0 / best_bin.max(1e-9);"""
+ return out.replace(anchor, call_snip, 1)
+
+
+def patch_w2_post_pack_micro_compact(src: str) -> Optional[str]:
+ """W2-6: Exact bounding-box tight normalization after packing — trims any residual unused top/right strip in [0, best_bin] cleanly!"""
+ old = """ let inv_bin = 1.0 / best_bin.max(1e-9);"""
+ new = """ // Measure actual tight outer extent of placed chart triangles (trims any unused top/right slack!)
+ let mut actual_max = 1e-9f64;
+ for (ci, chart) in charts.iter().enumerate() {
+ let (ox, oy, rot) = best_pack[ci];
+ for &[u, v] in &chart.uvs {
+ let (ru, rv) = match rot {
+ 0 => (u, v),
+ 1 => (v, chart.w - u),
+ 2 => (chart.w - u, chart.h - v),
+ _ => (chart.h - v, u),
+ };
+ actual_max = actual_max.max(ox + ru).max(oy + rv);
+ }
+ }
+ let inv_bin = 1.0 / actual_max.min(best_bin).max(1e-9);"""
+ if old not in src:
+ return None
+ return src.replace(old, new, 1)
+
+
+# ---------------------------------------------------------------------------
+# Dynamic Evolutionary Mutator (NEVER breaks on unmatched optional params!)
+# ---------------------------------------------------------------------------
+
+def mutate_active_params(
+ src: str,
+ param_specs: List[Tuple[str, str, float, float, bool]],
+ rng: random.Random,
+ scale: float,
+) -> Tuple[Optional[str], str]:
+ active = [spec for spec in param_specs if re.search(spec[1], src)]
+ if not active:
+ return None, ""
+ k = rng.choice([1, 1, 2, 2, 3])
+ chosen = rng.sample(active, min(k, len(active)))
+ out = src
+ desc_parts = []
+ for name, regex, lo, hi, is_int in chosen:
+ m = re.search(regex, out)
+ if not m:
+ continue
+ cur_val = float(m.group(2))
+ span = hi - lo
+ if is_int:
+ step = max(1, int(round(span * 0.28 * scale)))
+ cand = int(round(cur_val + rng.choice([-1, 1]) * rng.randint(1, step)))
+ cand = max(int(lo), min(int(hi), cand))
+ if cand == int(round(cur_val)):
+ cand = max(int(lo), min(int(hi), int(round(cur_val)) + rng.choice([-1, 1])))
+ rep = f"{m.group(1)}{cand}{m.group(3)}"
+ desc_parts.append(f"{name}:{int(cur_val)}->{cand}")
+ else:
+ delta = rng.gauss(0.0, span * 0.20 * scale)
+ if abs(delta) < span * 0.01:
+ delta = rng.choice([-1.0, 1.0]) * span * 0.05 * scale
+ cand = max(lo, min(hi, cur_val + delta))
+ rep = f"{m.group(1)}{cand:.4f}{m.group(3)}"
+ desc_parts.append(f"{name}:{cur_val:.4f}->{cand:.4f}")
+ out = out[:m.start()] + rep + out[m.end():]
+ if not desc_parts or out == src:
+ return None, ""
+ return out, ", ".join(desc_parts)
+
+
+def save_checkpoint(out_dir: Path, log_rows: List[Dict[str, Any]], summary: Dict[str, Any]) -> None:
+ out_dir.mkdir(parents=True, exist_ok=True)
+ uv_p = ROOT / "crates/forma-core/src/uv.rs"
+ shutil.copy2(uv_p, out_dir / "uv.rs")
+ diff = subprocess.run(["git", "diff", "crates/forma-core/src/uv.rs"], cwd=str(ROOT), text=True, capture_output=True).stdout
+ (out_dir / "uv_w2.patch").write_text(diff)
+ (out_dir / "summary.json").write_text(json.dumps(summary, indent=2))
+ with (out_dir / "log.jsonl").open("w") as f:
+ for row in log_rows:
+ f.write(json.dumps(row) + "\n")
+ tar_path = out_dir.parent / "forma_uv_w2_winners.tar.gz"
+ with tarfile.open(tar_path, "w:gz") as tf:
+ tf.add(out_dir, arcname="forma_uv_w2_out")
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--uv-plateau", type=int, default=18)
+ ap.add_argument("--uv-max-rounds", type=int, default=120)
+ ap.add_argument("--max-minutes", type=float, default=90.0)
+ ap.add_argument("--out-dir", default="/content/forma_uv_w2_out")
+ ap.add_argument("--seed", type=int, default=2026)
+ ap.add_argument("--dry-run", action="store_true")
+ args = ap.parse_args()
+
+ t_global = time.perf_counter()
+ rng = random.Random(args.seed)
+ out_dir = Path(args.out_dir) if Path("/content").exists() else (ROOT / "bench/results/forma_uv_w2_out")
+ log_rows: List[Dict[str, Any]] = []
+
+ print("======================================================================", flush=True)
+ print(" FORMA WAVE 2 DEEP UV UTILIZATION AUTORESEARCH (PLATEAU-AWARE)", flush=True)
+ print(f" CPUs={os.cpu_count()} | uv_plateau={args.uv_plateau} | max_rounds={args.uv_max_rounds} | max_min={args.max_minutes}", flush=True)
+ print("======================================================================", flush=True)
+
+ ok_b, msg_b = build_forma()
+ if not ok_b:
+ raise SystemExit(f"Initial build failed:\n{msg_b}")
+
+ ok_uv, uv_base = eval_uv_suite(repeats=2)
+ if not ok_uv:
+ raise SystemExit(f"Baseline UV suite failed: {uv_base}")
+
+ print(
+ f"\n[W2 BASELINE] score={uv_base['score']:.3f} | 12-mesh util={uv_base['mean_util']:.2f}% | "
+ f"Tier-1 util={uv_base['tier1_util']:.2f}% | stretch={uv_base['mean_stretch']:.4f} | "
+ f"charts={uv_base['mean_charts']:.1f} | total={uv_base['total_ms']:.1f}ms",
+ flush=True,
+ )
+ for k, v in uv_base["per_mesh"].items():
+ print(f" {k:10s}: util={v['util']:5.1f}% | charts={v['charts']:2d} | stretch={v['stretch']:.3f} | {v['ms']:5.1f}ms", flush=True)
+
+ if args.dry_run:
+ print("\n[DRY-RUN] Checking all 6 Wave 2 structural patches match cleanly...")
+ s = (ROOT / "crates/forma-core/src/uv.rs").read_text()
+ for name, fn in [
+ ("W2-1 MultiCut", patch_w2_multicut_concave_split),
+ ("W2-2 RichPack", patch_w2_rich_packers_and_skyline),
+ ("W2-3 AntiBottleneck", patch_w2_pack_helper_and_bottleneck_split),
+ ("W2-4 CylUnwrap", patch_w2_exact_cylindrical_strip_unwrap),
+ ("W2-5 Silhouette128", patch_w2_true_margin_silhouette_nesting),
+ ("W2-6 MicroCompact", patch_w2_post_pack_micro_compact),
+ ]:
+ nxt = fn(s)
+ assert nxt is not None, f"Patch {name} did not match!"
+ s = nxt
+ print(f" MATCH OK: {name}")
+ return
+
+ uv_path = ROOT / "crates/forma-core/src/uv.rs"
+ best_uv = uv_base
+ best_score = uv_base["score"]
+ kept_cnt = 0
+ round_idx = 0
+ summary: Dict[str, Any] = {"baseline": uv_base, "best": best_uv, "rounds": 0, "kept": 0}
+
+ def time_left() -> bool:
+ return (time.perf_counter() - t_global) < args.max_minutes * 60.0
+
+ def try_candidate(label: str, new_src: Optional[str], min_delta: float = 0.02) -> bool:
+ nonlocal best_uv, best_score, kept_cnt, round_idx
+ round_idx += 1
+ if new_src is None:
+ print(f"[W2 R{round_idx:03d}] SKIP | {label} (not applicable)", flush=True)
+ return False
+ backup = uv_path.read_text()
+ t0 = time.perf_counter()
+ uv_path.write_text(new_src)
+ ok_c, err_c = build_forma()
+ kept = False
+ reason = ""
+ res: Dict[str, Any] = {}
+ if not ok_c:
+ reason = f"compile err: {err_c.splitlines()[-1][:100] if err_c else 'err'}"
+ else:
+ ok_e, res = eval_uv_suite(repeats=2)
+ if not ok_e:
+ reason = f"gate failed: {res.get('error', 'unknown')}"
+ elif res["score"] > best_score + min_delta:
+ ok_e2, res2 = eval_uv_suite(repeats=3)
+ if ok_e2 and res2["score"] > best_score + min_delta:
+ kept = True
+ res = res2
+ reason = (
+ f"KEEP! score {best_score:.3f} -> {res['score']:.3f} | "
+ f"12m util {best_uv['mean_util']:.2f}% -> {res['mean_util']:.2f}% | "
+ f"T1 {res['tier1_util']:.2f}% | stretch {res['mean_stretch']:.4f} | "
+ f"ch={res['mean_charts']:.1f} | {res['total_ms']:.1f}ms"
+ )
+ best_uv = res
+ best_score = res["score"]
+ kept_cnt += 1
+ else:
+ reason = f"unconfirmed 3x ({res2.get('score', 'err')} vs {best_score:.3f})"
+ else:
+ reason = (
+ f"no gain (score {res['score']:.3f} vs {best_score:.3f}, "
+ f"12m {res['mean_util']:.2f}%, T1 {res['tier1_util']:.2f}%, {res['total_ms']:.1f}ms)"
+ )
+
+ if not kept:
+ uv_path.write_text(backup)
+ else:
+ summary["best"] = best_uv
+ summary["rounds"] = round_idx
+ summary["kept"] = kept_cnt
+ save_checkpoint(out_dir, log_rows, summary)
+
+ rec = {
+ "round": round_idx,
+ "label": label,
+ "kept": kept,
+ "score": res.get("score"),
+ "best_score": best_score,
+ "mean_util": res.get("mean_util"),
+ "tier1_util": res.get("tier1_util"),
+ "mean_stretch": res.get("mean_stretch"),
+ "mean_charts": res.get("mean_charts"),
+ "total_ms": res.get("total_ms"),
+ "reason": reason,
+ "elapsed_s": round(time.perf_counter() - t0, 1),
+ }
+ log_rows.append(rec)
+ print(f"[W2 R{round_idx:03d}] {'KEEP ' if kept else 'REVRT'} | {label:32s} | {reason}", flush=True)
+ return kept
+
+ # Phase 2A: 6 Major Structural Algorithmic Upgrades
+ structural = [
+ ("W2-1 Multi-Cut Neck Bisection", patch_w2_multicut_concave_split),
+ ("W2-2 Rich MaxRects+CP+2opt", patch_w2_rich_packers_and_skyline),
+ ("W2-3 Anti-Bottleneck Splitter", patch_w2_pack_helper_and_bottleneck_split),
+ ("W2-4 Analytic Cyl Strip Unwrap", patch_w2_exact_cylindrical_strip_unwrap),
+ ("W2-5 True-Margin Silhouette 128", patch_w2_true_margin_silhouette_nesting),
+ ("W2-6 Post-Pack Tight Compact", patch_w2_post_pack_micro_compact),
+ ]
+ for name, fn in structural:
+ if not time_left():
+ break
+ try_candidate(name, fn(uv_path.read_text()), min_delta=0.01)
+
+ # Phase 2B: Long-Running Plateau-Aware Evolutionary Search over ALL active UV parameters!
+ param_specs = [
+ ("seed_dot_min", r"(seed_n\.dot\(face_n\[nb\]\)\s*>=\s*)([0-9.]+)(\s*\{)", 0.02, 0.58, False),
+ ("planar_dot", r"(dot\(n_dir\)\s*>\s*)([0-9.]+)(\))", 0.985, 0.9999, False),
+ ("split_fill_thresh", r"(let split_fill_thresh:\s*f64\s*=\s*)([0-9.]+)(;)", 0.38, 0.85, False),
+ ("split_min_faces", r"(let split_min_faces:\s*usize\s*=\s*)([0-9]+)(;)", 3, 14, True),
+ ("split_gain_ratio", r"(let split_gain_ratio:\s*f64\s*=\s*)([0-9.]+)(;)", 0.80, 0.995, False),
+ ("split_max_depth", r"(let split_max_depth:\s*usize\s*=\s*)([0-9]+)(;)", 1, 4, True),
+ ("split_pad_weight", r"(let split_pad_weight:\s*f64\s*=\s*)([0-9.]+)(;)", 0.005, 0.045, False),
+ ("max_repack_splits", r"(let max_repack_splits:\s*usize\s*=\s*)([0-9]+)(;)", 1, 14, True),
+ ("repack_min_gain", r"(let repack_min_gain:\s*f64\s*=\s*)([0-9.]+)(;)", 0.94, 0.998, False),
+ ("repack_min_faces", r"(let repack_min_faces:\s*usize\s*=\s*)([0-9]+)(;)", 3, 12, True),
+ ("max_total_charts", r"(let max_total_charts:\s*usize\s*=\s*)([0-9]+)(;)", 24, 56, True),
+ ("perm_trials", r"(let perm_trials:\s*usize\s*=\s*)([0-9]+)(;)", 8, 64, True),
+ ("cyl_perp_tol", r"(let cyl_perp_tol:\s*f64\s*=\s*)([0-9.]+)(;)", 0.01, 0.12, False),
+ ("hollow_slack", r"(let hollow_slack_ratio:\s*f64\s*=\s*)([0-9.]+)(;)", 1.03, 1.35, False),
+ ]
+
+ streak = 0
+ evo_iter = 0
+ print(f"\n--- PHASE 2B: Evolutionary Search (stopping only after {args.uv_plateau} consecutive plateau rounds) ---", flush=True)
+ while streak < args.uv_plateau and evo_iter < args.uv_max_rounds and time_left():
+ evo_iter += 1
+ scale = 0.65 if streak < 4 else (1.1 if streak < 10 else 1.7)
+ cand_src, desc = mutate_active_params(uv_path.read_text(), param_specs, rng, scale)
+ if not cand_src:
+ print("[W2] No active params found to mutate — stopping.", flush=True)
+ break
+ improved = try_candidate(f"evo({desc[:26]})", cand_src, min_delta=0.015)
+ if improved:
+ streak = 0
+ else:
+ streak += 1
+ print(f" (Wave 2 UV plateau streak: {streak}/{args.uv_plateau})", flush=True)
+
+ # Final full Rust regression gate
+ print("\n--- FINAL VERIFICATION: cargo test --release -p forma-core ---", flush=True)
+ ok_t, out_t = run_rust_tests()
+ summary["final_rust_tests"] = ok_t
+ summary["total_elapsed_s"] = round(time.perf_counter() - t_global, 1)
+ summary["plateau_streak"] = streak
+ save_checkpoint(out_dir, log_rows, summary)
+
+ print("======================================================================", flush=True)
+ print(f" WAVE 2 UV AUTORESEARCH COMPLETE in {summary['total_elapsed_s']}s ({round_idx} rounds, {kept_cnt} kept, plateau={streak}/{args.uv_plateau})", flush=True)
+ print(f" 12-Mesh Util : {uv_base['mean_util']:.2f}% -> {best_uv['mean_util']:.2f}% (+{best_uv['mean_util']-uv_base['mean_util']:.2f}%)", flush=True)
+ print(f" Tier-1 Util : {uv_base['tier1_util']:.2f}% -> {best_uv['tier1_util']:.2f}% (+{best_uv['tier1_util']-uv_base['tier1_util']:.2f}%)", flush=True)
+ print(f" Mean Stretch : {uv_base['mean_stretch']:.4f} -> {best_uv['mean_stretch']:.4f} | Mean Charts: {best_uv['mean_charts']:.1f} | Total: {best_uv['total_ms']:.1f}ms", flush=True)
+ print(f" Rust Tests : {'PASS' if ok_t else 'FAIL'}", flush=True)
+ for k, v in best_uv["per_mesh"].items():
+ b_u = uv_base["per_mesh"][k]["util"]
+ print(f" {k:10s}: {b_u:5.1f}% -> {v['util']:5.1f}% ({v['util']-b_u:+5.1f}%) | ch={v['charts']:2d} | str={v['stretch']:.3f} | {v['ms']:5.1f}ms", flush=True)
+ print("======================================================================", flush=True)
+ if not ok_t:
+ print(out_t)
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()