Added python server with Auto UV and Auto Retopo in Mesh Editor

This commit is contained in:
Bruno Fargnoli 2026-06-30 12:33:26 +02:00
parent eacc945722
commit 1b19aee43a
51 changed files with 4114 additions and 6 deletions

5
python-server/.gitignore vendored Normal file
View file

@ -0,0 +1,5 @@
.venv/
__pycache__/
*.pyc
*.egg-info/
.pytest_cache/

87
python-server/README.md Normal file
View file

@ -0,0 +1,87 @@
# 3D Gen Studio — Mesh Tools (Python service)
A small FastAPI service for CPU/GPU-heavy mesh operations implemented in Python.
The Node backend (`server.js`) proxies browser requests here, exactly like it
proxies to ComfyUI — so this service can run on the same machine or a different
host/port, configured under **Settings → Mesh Tools (Python) server**.
```
Browser ──POST /api/meshes/auto-uv──▶ Node (server.js) ──POST /meshes/auto-uv──▶ Python (this service)
◀── processed GLB ──────────────────────┘
```
## Endpoints
| Method | Path | Purpose |
| ------ | -------------------- | ------------------------------------ |
| GET | `/health` | Readiness probe |
| POST | `/meshes/auto-uv` | Auto UV unwrap |
| POST | `/meshes/auto-retopo`| Auto retopology |
Both mesh endpoints take `multipart/form-data`:
- `meshFile` — the mesh (GLB/OBJ/PLY/STL)
- `options` — JSON string of operation options (optional)
- `format` — output format, default `glb` (optional)
They respond with the processed mesh as a binary body and stats in headers:
`X-Vertex-Count`, `X-Face-Count`, `X-Has-Uv`.
Interactive API docs at `http://<host>:<port>/docs`.
## Run
```bat
run.bat
```
First run creates `.venv`, installs `requirements.txt`, and serves on
`0.0.0.0:8200`. Override with env vars:
| Variable | Default |
| -------------------------- | ------------------------ |
| `MESHTOOLS_HOST` | `0.0.0.0` |
| `MESHTOOLS_PORT` | `8200` |
| `MESHTOOLS_ALLOWED_ORIGINS`| dev origins |
| `MESHTOOLS_MAX_UPLOAD_BYTES`| `536870912` (512 MB) |
| `MESHTOOLS_WORK_DIR` | OS temp / scratch folder |
## Pipelines
The two operations are backed by the bundled packages:
- `app/services/autouv/` — the AutoUV unwrapper (`autouv.unwrap`)
- `app/services/autoretopo/` — the Auto-Retopo pipeline (`autoretopo.AutoRetopo`)
The thin bridges that the routes call:
- `app/services/auto_uv.py` → `run_auto_uv(mesh, options)` → `(trimesh, stats)`
- `app/services/auto_retopo.py` → `run_auto_retopo(mesh, options)` → `(trimesh, stats)`
Each receives a loaded `trimesh.Trimesh` and parsed options, and returns the
processed mesh plus a stats dict. Serialization, uploads, and error handling are
done in `app/routes/meshes.py`; the stats dict is returned to the browser in the
`X-Stats` response header. Every pipeline parameter is exposed in `app/schemas.py`
(`AutoUvOptions` / `AutoRetopoOptions`), which mirror `autouv.unwrap()` and
`autoretopo.RetopoConfig` 1:1.
## Layout
```
python-server/
├── main.py # FastAPI app + CORS + router wiring
├── requirements.txt
├── run.bat
└── app/
├── config.py # host/port/limits from env vars
├── schemas.py # option + stats models
├── meshio.py # trimesh load/export/stats
├── routes/
│ ├── health.py
│ └── meshes.py # /meshes/auto-uv, /meshes/auto-retopo
└── services/
├── auto_uv.py # bridge -> autouv.unwrap
├── auto_retopo.py # bridge -> autoretopo.AutoRetopo
├── autouv/ # bundled AutoUV package
└── autoretopo/ # bundled Auto-Retopo package
```

View file

@ -0,0 +1,5 @@
"""3D Gen Studio — Python mesh-processing service.
A small FastAPI app that the Node backend (server.js) proxies to for
CPU/GPU-heavy mesh operations implemented in Python (Auto UV, Auto Retopo, ...).
"""

View file

@ -0,0 +1,47 @@
"""Runtime configuration for the mesh-processing service.
All values can be overridden with environment variables so the service can run
on a different machine/port than the Node backend — mirroring how ComfyUI is
configured in the main app.
"""
from __future__ import annotations
import os
import tempfile
from pathlib import Path
def _env_int(name: str, default: int) -> int:
raw = os.environ.get(name)
try:
return int(raw) if raw is not None and raw != "" else default
except ValueError:
return default
# Network — uvicorn binds here. 0.0.0.0 makes the service reachable from the
# machine running Node when they are different hosts.
HOST: str = os.environ.get("MESHTOOLS_HOST", "0.0.0.0")
PORT: int = _env_int("MESHTOOLS_PORT", 8200)
# CORS — the Node backend calls this service server-to-server, so the browser
# origin is not strictly required. We still allow the dev origins for the rare
# case of calling the service directly during debugging.
ALLOWED_ORIGINS: list[str] = [
o.strip()
for o in os.environ.get(
"MESHTOOLS_ALLOWED_ORIGINS",
"http://localhost:5173,http://localhost:3001",
).split(",")
if o.strip()
]
# Upload guard rails.
MAX_UPLOAD_BYTES: int = _env_int("MESHTOOLS_MAX_UPLOAD_BYTES", 512 * 1024 * 1024)
# Scratch space for temp files when a tool needs real paths on disk
# (many mesh CLIs/libraries only accept file paths, not in-memory buffers).
WORK_DIR: Path = Path(
os.environ.get("MESHTOOLS_WORK_DIR", str(Path(tempfile.gettempdir()) / "3dgenstudio-meshtools"))
)
WORK_DIR.mkdir(parents=True, exist_ok=True)

View file

@ -0,0 +1,57 @@
"""Mesh load/export helpers built on trimesh.
The editor speaks GLB natively, so GLB is the default exchange format. OBJ is
also accepted on input. Keep all format knowledge in this module so the route
handlers and services stay format-agnostic.
"""
from __future__ import annotations
import io
from pathlib import Path
import trimesh
from .schemas import MeshStats
# Extensions we know how to load on input.
SUPPORTED_INPUT_EXTS = {".glb", ".gltf", ".obj", ".ply", ".stl"}
def load_mesh(data: bytes, filename: str) -> trimesh.Trimesh:
"""Load a single mesh from raw bytes.
Scenes (multi-mesh GLBs) are concatenated into one mesh so downstream tools
receive a single Trimesh. Adjust if your scripts need the scene graph.
"""
ext = Path(filename or "mesh.glb").suffix.lower() or ".glb"
if ext not in SUPPORTED_INPUT_EXTS:
raise ValueError(f"Unsupported input format '{ext}'. Supported: {sorted(SUPPORTED_INPUT_EXTS)}")
file_type = ext.lstrip(".")
loaded = trimesh.load(io.BytesIO(data), file_type=file_type, process=False)
if isinstance(loaded, trimesh.Scene):
if len(loaded.geometry) == 0:
raise ValueError("The uploaded file contains no geometry.")
loaded = trimesh.util.concatenate(tuple(loaded.geometry.values()))
if not isinstance(loaded, trimesh.Trimesh):
raise ValueError("The uploaded file did not resolve to a triangle mesh.")
return loaded
def export_mesh(mesh: trimesh.Trimesh, fmt: str = "glb") -> bytes:
"""Serialize a mesh to bytes in the requested format (default GLB)."""
fmt = (fmt or "glb").lstrip(".").lower()
exported = mesh.export(file_type=fmt)
return exported if isinstance(exported, (bytes, bytearray)) else str(exported).encode("utf-8")
def mesh_stats(mesh: trimesh.Trimesh) -> MeshStats:
has_uv = bool(getattr(getattr(mesh, "visual", None), "uv", None) is not None)
return MeshStats(
vertex_count=int(len(mesh.vertices)),
face_count=int(len(mesh.faces)),
has_uv=has_uv,
)

View file

View file

@ -0,0 +1,11 @@
"""Health/readiness probe used by the Node backend to check connectivity."""
from __future__ import annotations
from fastapi import APIRouter
router = APIRouter(tags=["health"])
@router.get("/health")
def health() -> dict:
return {"status": "ok", "service": "3dgenstudio-meshtools"}

View file

@ -0,0 +1,107 @@
"""Mesh-processing endpoints: Auto UV and Auto Retopo.
Contract (shared by both routes):
Request : multipart/form-data
- meshFile : the mesh to process (GLB/OBJ/PLY/STL)
- options : JSON string of the operation options (optional)
- format : desired output format, default "glb" (optional)
Response : application/json
{
"format": "glb",
"mesh_b64": "<base64 of the processed mesh bytes>",
"stats": { "vertex_count", "face_count", "has_uv", "tool": {...} },
"preview_b64": "<base64 PNG>" | null # UV layout for Auto UV
}
A JSON envelope (rather than a binary body + custom headers) is used because the
browser cannot read custom response headers across origins, and it gives a clean
channel for the UV-layout preview image. These meshes are low-poly, so the base64
overhead is negligible.
"""
from __future__ import annotations
import base64
import json
from fastapi import APIRouter, File, Form, HTTPException, UploadFile
from fastapi.responses import JSONResponse
from pydantic import ValidationError
from ..config import MAX_UPLOAD_BYTES
from ..meshio import export_mesh, load_mesh, mesh_stats
from ..schemas import AutoRetopoOptions, AutoUvOptions
from ..services.auto_retopo import run_auto_retopo
from ..services.auto_uv import run_auto_uv
router = APIRouter(prefix="/meshes", tags=["meshes"])
def _parse_options(raw: str | None, model):
try:
data = json.loads(raw) if raw else {}
except json.JSONDecodeError as exc:
raise HTTPException(status_code=400, detail=f"Invalid options JSON: {exc}") from exc
if not isinstance(data, dict):
raise HTTPException(status_code=400, detail="options must be a JSON object.")
try:
return model(**data)
except ValidationError as exc:
raise HTTPException(status_code=422, detail=exc.errors()) from exc
async def _read_upload(mesh_file: UploadFile) -> bytes:
data = await mesh_file.read()
if not data:
raise HTTPException(status_code=400, detail="meshFile is empty.")
if len(data) > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="meshFile exceeds the maximum allowed size.")
return data
def _tool_response(mesh, fmt: str, tool_stats: dict | None = None, preview_png: bytes | None = None) -> JSONResponse:
fmt = (fmt or "glb").lstrip(".").lower()
payload = export_mesh(mesh, fmt)
stats = mesh_stats(mesh)
return JSONResponse({
"format": fmt,
"mesh_b64": base64.b64encode(payload).decode("ascii"),
"stats": {
"vertex_count": stats.vertex_count,
"face_count": stats.face_count,
"has_uv": stats.has_uv,
"tool": tool_stats,
},
"preview_b64": base64.b64encode(preview_png).decode("ascii") if preview_png else None,
})
@router.post("/auto-uv")
async def auto_uv(
meshFile: UploadFile = File(...),
options: str | None = Form(None),
format: str = Form("glb"),
) -> JSONResponse:
opts = _parse_options(options, AutoUvOptions)
data = await _read_upload(meshFile)
mesh = load_mesh(data, meshFile.filename or "mesh.glb")
try:
result, tool_stats, preview_png = run_auto_uv(mesh, opts)
except Exception as exc: # noqa: BLE001 — surface tool errors as 500 with detail
raise HTTPException(status_code=500, detail=f"Auto UV failed: {exc}") from exc
return _tool_response(result, format, tool_stats, preview_png)
@router.post("/auto-retopo")
async def auto_retopo(
meshFile: UploadFile = File(...),
options: str | None = Form(None),
format: str = Form("glb"),
) -> JSONResponse:
opts = _parse_options(options, AutoRetopoOptions)
data = await _read_upload(meshFile)
mesh = load_mesh(data, meshFile.filename or "mesh.glb")
try:
result, tool_stats, preview_png = run_auto_retopo(mesh, opts)
except Exception as exc: # noqa: BLE001
raise HTTPException(status_code=500, detail=f"Auto Retopo failed: {exc}") from exc
return _tool_response(result, format, tool_stats, preview_png)

View file

@ -0,0 +1,103 @@
"""Request option models and response metadata.
Meshes are exchanged as binary file bodies (GLB by default), so these models
describe only the *options* that ride alongside the upload as a JSON form field,
plus the stats we report back in response headers.
The option fields mirror the parameters of the bundled pipelines 1:1:
- AutoUvOptions -> autouv.unwrap(...)
- AutoRetopoOptions -> autoretopo.RetopoConfig(...)
Defaults match the libraries' own defaults.
"""
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, Field
class AutoUvOptions(BaseModel):
"""Every parameter accepted by autouv.unwrap()."""
# --- segmentation ---
max_cone_deg: float = Field(default=50.0, ge=1.0, le=180.0,
description="Normal-cone cap (deg). Higher = fewer, more distorted charts.")
sharp_weight: float = Field(default=0.35, ge=0.0, le=1.0,
description="How strongly sharp edges attract seams.")
min_faces: int = Field(default=20, ge=1, le=100000,
description="Charts smaller than this are dissolved into neighbours.")
min_area_frac: float = Field(default=0.004, ge=0.0, le=1.0,
description="Min chart area as a fraction of total surface area.")
fold_cap_deg: float = Field(default=88.0, ge=1.0, le=180.0,
description="Dihedral fold cap that forces a seam.")
# --- refinement (LSCM-validated chart merge) ---
refine: bool = Field(default=True, description="Run the LSCM-validated merge pass (off = faster, more charts).")
refine_target_faces: int = Field(default=80, ge=1, le=100000,
description="Charts below this face count are merge candidates.")
refine_ad_thresh: float = Field(default=1.32, ge=1.0, le=10.0,
description="Max angle-distortion ratio a merge may introduce.")
# --- parameterization ---
method: Literal["auto", "lscm", "arap", "planar"] = Field(
default="auto", description="Per-chart flattening method.")
arap_iters: int = Field(default=4, ge=0, le=100,
description="As-rigid-as-possible iterations (0 = LSCM/planar only).")
# --- packing ---
resolution: int = Field(default=1024, ge=64, le=8192,
description="Atlas resolution used to size padding (px).")
padding_texels: int = Field(default=4, ge=0, le=64, description="Inter-island padding in texels.")
# --- topology repair ---
weld: bool = Field(default=True, description="Proximity-weld coincident verts before unwrapping.")
weld_tol_frac: float = Field(default=0.1, ge=0.0, le=1.0,
description="Weld tolerance as a fraction of median edge length.")
class AutoRetopoOptions(BaseModel):
"""Every field of autoretopo.RetopoConfig."""
# --- target ---
target_faces: int = Field(default=6000, ge=50, le=5_000_000,
description="Approximate face budget of the output.")
quads: bool = Field(default=False, description="Convert the final mesh to quad-dominant (reported in metrics).")
# --- base generation (watertight shell) ---
watertight: bool = Field(default=True,
description="Build a unified voxel shell (robust) vs. remesh the surface directly.")
shell_resolution: int = Field(default=256, ge=16, le=1024,
description="Voxel grid cells along the longest bbox axis.")
shell_close_iter: int = Field(default=1, ge=0, le=20,
description="Morphological closing iterations to bridge cracks.")
shell_smooth: float = Field(default=0.6, ge=0.0, le=5.0,
description="Gaussian sigma on the occupancy field (lower = sharper).")
shell_samples_per_pitch: float = Field(default=2.0, ge=1.0, le=8.0,
description="Surface sampling density (>=2 = gap-free coverage).")
max_memory_gb: float = Field(default=4.0, ge=0.0, le=128.0,
description="Auto-lower shell resolution to fit this budget (0 disables).")
# --- clean topology (field-adaptive isotropic remeshing) ---
adaptive: bool = Field(default=True, description="Curvature-adaptive density (more faces where it bends).")
remesh_iters: int = Field(default=10, ge=1, le=100, description="Isotropic remesh iterations.")
feature_deg: float = Field(default=30.0, ge=0.0, le=180.0, description="Crease angle preserved as a feature.")
calibrate_passes: int = Field(default=1, ge=0, le=10, description="Rough edge-length correction passes.")
# --- silhouette projection ---
project: bool = Field(default=True, description="Project the remesh back onto the original surface.")
project_iters: int = Field(default=10, ge=0, le=100, description="Projection iterations.")
project_clamp: float = Field(default=1.5, ge=0.0, le=10.0,
description="Max per-vertex move as a multiple of local edge length.")
relax_strength: float = Field(default=0.4, ge=0.0, le=1.0,
description="Tangential relaxation factor per iteration.")
# --- misc ---
seed: int = Field(default=0, ge=0, description="RNG seed for reproducibility.")
class MeshStats(BaseModel):
"""Reported back to the caller (also surfaced via response headers)."""
vertex_count: int
face_count: int
has_uv: bool

View file

View file

@ -0,0 +1,47 @@
"""Auto Retopology — bridges the FastAPI route to the bundled `autoretopo` package.
AutoRetopo.run() accepts a trimesh.Trimesh directly (it repairs it internally),
so we pass the uploaded mesh straight through and return the retopologized
trimesh.Trimesh plus the metrics/timings for the UI.
"""
from __future__ import annotations
import trimesh
from ..schemas import AutoRetopoOptions
from .autoretopo import AutoRetopo, RetopoConfig
def run_auto_retopo(mesh: trimesh.Trimesh, options: AutoRetopoOptions) -> tuple[trimesh.Trimesh, dict, None]:
cfg = RetopoConfig(
target_faces=options.target_faces,
quads=options.quads,
watertight=options.watertight,
shell_resolution=options.shell_resolution,
shell_close_iter=options.shell_close_iter,
shell_smooth=options.shell_smooth,
shell_samples_per_pitch=options.shell_samples_per_pitch,
max_memory_gb=options.max_memory_gb,
adaptive=options.adaptive,
remesh_iters=options.remesh_iters,
feature_deg=options.feature_deg,
calibrate_passes=options.calibrate_passes,
project=options.project,
project_iters=options.project_iters,
project_clamp=options.project_clamp,
relax_strength=options.relax_strength,
seed=options.seed,
verbose=False,
)
result = AutoRetopo(cfg).run(mesh)
stats = {
"metrics": result.metrics,
"timings": result.timings,
"quad_face_count": (len(result.quad_faces) if result.quad_faces is not None else None),
}
# result.mesh is a triangle trimesh.Trimesh (GLB is triangles-only; the
# quad-dominant face list, when requested, is summarized in stats above).
# No preview image for retopo (third tuple element kept for a uniform contract).
return result.mesh, stats, None

View file

@ -0,0 +1,71 @@
"""Auto UV unwrap — bridges the FastAPI route to the bundled `autouv` package.
The route hands us a loaded trimesh.Trimesh; we run autouv.unwrap on its
geometry and hand back a trimesh.Trimesh that carries the new UV channel, plus
the unwrap stats dict for the UI.
"""
from __future__ import annotations
import os
import tempfile
import numpy as np
import trimesh
from ..config import WORK_DIR
from ..schemas import AutoUvOptions
from . import autouv
def _render_uv_preview(result) -> bytes | None:
"""Render the packed UV atlas to a PNG and return its bytes (None on failure).
autouv.render_uv writes to a path, so we go through a temp file in WORK_DIR.
Failures (e.g. matplotlib missing) are non-fatal — the unwrap still succeeds.
"""
path = None
try:
fd, path = tempfile.mkstemp(suffix=".png", dir=str(WORK_DIR))
os.close(fd)
autouv.render_uv(result, path, size=512)
with open(path, "rb") as f:
return f.read()
except Exception: # noqa: BLE001 — preview is best-effort
return None
finally:
if path and os.path.exists(path):
try:
os.remove(path)
except OSError:
pass
def run_auto_uv(mesh: trimesh.Trimesh, options: AutoUvOptions) -> tuple[trimesh.Trimesh, dict, bytes | None]:
src = autouv.Mesh(np.asarray(mesh.vertices), np.asarray(mesh.faces))
result = autouv.unwrap(
src,
max_cone_deg=options.max_cone_deg,
sharp_weight=options.sharp_weight,
min_faces=options.min_faces,
min_area_frac=options.min_area_frac,
fold_cap_deg=options.fold_cap_deg,
refine=options.refine,
refine_target_faces=options.refine_target_faces,
refine_ad_thresh=options.refine_ad_thresh,
resolution=options.resolution,
padding_texels=options.padding_texels,
method=options.method,
arap_iters=options.arap_iters,
weld=options.weld,
weld_tol_frac=options.weld_tol_frac,
verbose=False,
)
# Build a GLB-ready mesh with the new vertex UV channel (seam-split geometry).
out = trimesh.Trimesh(vertices=result.vertices, faces=result.faces, process=False)
out.visual = trimesh.visual.TextureVisuals(
uv=np.asarray(result.uv),
material=trimesh.visual.material.PBRMaterial(name="autouv"),
)
return out, dict(result.stats), _render_uv_preview(result)

View file

@ -0,0 +1,10 @@
"""autoretopo - automatic retopology for low-poly meshes.
Generates a clean, watertight, silhouette-following topology layer over a messy
(often AI-generated) input mesh, without manual work.
"""
from .config import RetopoConfig
from .pipeline import AutoRetopo, RetopoResult
__all__ = ["AutoRetopo", "RetopoResult", "RetopoConfig"]
__version__ = "0.1.0"

View file

@ -0,0 +1,3 @@
from .cli import main
import sys
sys.exit(main())

View file

@ -0,0 +1,76 @@
"""Command-line interface.
python -m autoretopo input.glb -o out.glb --faces 6000
python -m autoretopo in.glb -o out.glb --faces 4000 --no-watertight --quads
python -m autoretopo in.glb -o out.glb --compare compare.png # render a comparison
"""
from __future__ import annotations
import argparse, json, sys
import numpy as np
from .config import RetopoConfig
from .pipeline import AutoRetopo
def build_parser():
p = argparse.ArgumentParser(
"autoretopo", description="Automatic retopology for low-poly meshes.")
p.add_argument("input", help="input mesh (glb/gltf/obj/ply/stl)")
p.add_argument("-o", "--output", default="retopo.glb", help="output mesh path")
p.add_argument("--faces", type=int, default=6000, help="target face budget")
p.add_argument("--shell-res", type=int, default=256, help="voxel grid resolution")
p.add_argument("--shell-smooth", type=float, default=0.6, help="occupancy blur sigma")
p.add_argument("--max-memory", type=float, default=4.0,
help="GB budget; auto-lowers shell resolution to fit (0 disables)")
p.add_argument("--no-watertight", action="store_true",
help="remesh the surface directly (keeps open boundaries)")
p.add_argument("--no-adaptive", action="store_true", help="uniform density")
p.add_argument("--no-project", action="store_true", help="skip silhouette projection")
p.add_argument("--clamp", type=float, default=1.5, help="projection move clamp (x edge length)")
p.add_argument("--quads", action="store_true", help="convert to quad-dominant")
p.add_argument("--compare", metavar="PNG", help="write a wireframe/shaded comparison image")
p.add_argument("--metrics", metavar="JSON", help="write metrics to a JSON file")
p.add_argument("-q", "--quiet", action="store_true")
return p
def main(argv=None):
args = build_parser().parse_args(argv)
cfg = RetopoConfig(
target_faces=args.faces, shell_resolution=args.shell_res,
shell_smooth=args.shell_smooth, watertight=not args.no_watertight,
adaptive=not args.no_adaptive, project=not args.no_project,
project_clamp=args.clamp, quads=args.quads, max_memory_gb=args.max_memory,
verbose=not args.quiet)
result = AutoRetopo(cfg).run(args.input)
result.export(args.output)
if not args.quiet:
print(f"\nwrote {args.output}")
if args.compare:
from . import render
o, r = result.original, result.mesh
Vo, Fo = np.asarray(o.vertices), np.asarray(o.faces)
Vr, Fr = np.asarray(r.vertices), np.asarray(r.faces)
imgs = [render.render_mesh(Vo, Fo, mode="wire", zoom=0.8),
render.render_mesh(Vr, Fr, mode="wire", zoom=0.8),
render.render_mesh(Vo, Fo, mode="shaded", zoom=0.8),
render.render_mesh(Vr, Fr, mode="shaded", zoom=0.8)]
render.panel(imgs, [f"input ({len(Fo)})", f"retopo ({len(Fr)})",
"input shaded", "retopo shaded"],
args.compare, ncols=2, title="Auto-Retopo comparison")
if not args.quiet:
print(f"wrote {args.compare}")
if args.metrics:
with open(args.metrics, "w") as f:
json.dump({"metrics": result.metrics, "timings": result.timings,
"config": result.config}, f, indent=2)
if not args.quiet:
print(json.dumps(result.metrics, indent=2))
return 0
if __name__ == "__main__":
sys.exit(main())

View file

@ -0,0 +1,38 @@
"""Configuration for the Auto-Retopo pipeline."""
from __future__ import annotations
from dataclasses import dataclass, asdict
@dataclass
class RetopoConfig:
# --- target ---
target_faces: int = 6000 # approximate face budget of the output
quads: bool = False # convert the final triangle mesh to quad-dominant
# --- base generation ("the new watertight layer") ---
watertight: bool = True # True: build a unified SDF/voxel shell (robust to messy input)
# False: remesh the original surface directly (keeps open boundaries)
shell_resolution: int = 256 # voxel grid cells along the longest bbox axis (silhouette fidelity)
shell_close_iter: int = 1 # morphological closing to bridge cracks in non-watertight input
shell_smooth: float = 0.6 # gaussian sigma on the occupancy field (lower = sharper, more stairs)
shell_samples_per_pitch: float = 2.0 # surface sampling density (>=2 guarantees gap-free voxel coverage)
max_memory_gb: float = 4.0 # auto-lower shell_resolution so the voxel grid fits this budget
# --- clean topology (field-adaptive isotropic remeshing) ---
adaptive: bool = True # curvature-adaptive density (more faces where the surface bends)
remesh_iters: int = 10
feature_deg: float = 30.0 # crease angle preserved as a feature
calibrate_passes: int = 1 # rough edge-length correction; decimation sets exact count
# --- silhouette projection ("follow the original surface") ---
project: bool = True
project_iters: int = 10
project_clamp: float = 1.5 # max per-vertex move as a multiple of local edge length
relax_strength: float = 0.4 # tangential relaxation factor per iteration (0..1)
# --- misc ---
seed: int = 0
verbose: bool = True
def to_dict(self):
return asdict(self)

View file

@ -0,0 +1,46 @@
"""Stage 0 - ingest & repair.
Loads any trimesh-supported file (glb/gltf/obj/ply/stl...), flattens a scene to a
single mesh, welds coincident vertices, drops degenerate/duplicate faces and
fixes winding. The cleaned mesh is the *projection target* for later stages; we
deliberately do NOT try to make it watertight here, because the watertight shell
stage is far more robust to the fragmented "triangle soup" that AI generators emit.
"""
from __future__ import annotations
import numpy as np
import trimesh
def load_mesh(path: str) -> trimesh.Trimesh:
scene = trimesh.load(path, force="scene")
geoms = [g for g in scene.geometry.values() if isinstance(g, trimesh.Trimesh) and len(g.faces)]
if not geoms:
raise ValueError(f"No triangle geometry found in {path}")
mesh = trimesh.util.concatenate(geoms) if len(geoms) > 1 else geoms[0].copy()
return repair(mesh)
def repair(mesh: trimesh.Trimesh) -> trimesh.Trimesh:
mesh = mesh.copy()
mesh.merge_vertices() # weld coincident verts (closes unwelded cracks)
mesh.remove_duplicate_faces() if hasattr(mesh, "remove_duplicate_faces") else None
mesh.update_faces(mesh.nondegenerate_faces())
mesh.remove_unreferenced_vertices()
try:
mesh.fix_normals() # consistent winding where possible
except Exception:
pass
return mesh
def mesh_stats(mesh: trimesh.Trimesh) -> dict:
from .meshutil import num_components
return {
"vertices": int(len(mesh.vertices)),
"faces": int(len(mesh.faces)),
"components": int(num_components(mesh.vertices, mesh.faces)),
"watertight": bool(mesh.is_watertight),
"winding_consistent": bool(mesh.is_winding_consistent),
"bbox_diagonal": float(np.linalg.norm(mesh.extents)),
"extents": [float(x) for x in mesh.extents],
}

View file

@ -0,0 +1,50 @@
"""Memory-bounded mesh utilities.
`trimesh.Trimesh.split(only_watertight=False)` builds a *separate submesh object for
every connected component*. On a fragmented AI mesh (the 200k-face warriors have
~2000 components) that allocates thousands of vertex/face copies and can blow past
17 GB. We only ever needed (a) the number of components and (b) the largest one, so
these helpers compute both from the edge graph with scipy - O(faces) memory, no
submesh copies.
"""
from __future__ import annotations
import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import connected_components
def _labels(faces, n_verts):
F = np.asarray(faces)
e = np.sort(F[:, [0, 1, 1, 2, 2, 0]].reshape(-1, 2), axis=1)
g = coo_matrix((np.ones(len(e), np.int8), (e[:, 0], e[:, 1])),
shape=(n_verts, n_verts))
n, labels = connected_components(g, directed=False)
return n, labels
def num_components(vertices, faces) -> int:
"""Connected-component count without materialising any submesh."""
if len(faces) == 0:
return 0
n, _ = _labels(faces, len(vertices))
return int(n)
def largest_component(vertices, faces):
"""Return (V, F) of the largest connected component, via a boolean face mask
(no per-component Trimesh objects)."""
V = np.asarray(vertices)
F = np.asarray(faces)
if len(F) == 0:
return V, F
n, labels = _labels(F, len(V))
if n <= 1:
return V, F
face_label = labels[F[:, 0]] # face is connected -> one label
keep_label = np.bincount(face_label).argmax()
fmask = face_label == keep_label
Fk = F[fmask]
used = np.unique(Fk)
remap = np.full(len(V), -1, np.int64)
remap[used] = np.arange(len(used))
return np.ascontiguousarray(V[used]), np.ascontiguousarray(remap[Fk])

View file

@ -0,0 +1,98 @@
"""Stage 4 - quality metrics.
Quantifies (a) how faithfully the retopo follows the original silhouette and
(b) how clean the resulting topology is. Distances are reported both in world
units and as a percentage of the bounding-box diagonal so they are scale-free.
"""
from __future__ import annotations
import numpy as np
import trimesh
from scipy.spatial import cKDTree
def _sample(mesh, n):
pts, fid = trimesh.sample.sample_surface(mesh, n)
nrm = mesh.face_normals[fid]
return np.asarray(pts), np.asarray(nrm)
def geometric_fidelity(original, result, n_samples=60000):
diag = float(np.linalg.norm(original.extents))
a_pts, a_nrm = _sample(original, n_samples)
b_pts, b_nrm = _sample(result, n_samples)
ta, tb = cKDTree(a_pts), cKDTree(b_pts)
dab, ia = tb.query(a_pts) # original -> result
dba, ib = ta.query(b_pts) # result -> original
chamfer = float(dab.mean() + dba.mean())
hausdorff = float(max(dab.max(), dba.max()))
mean_dist = float(0.5 * (dab.mean() + dba.mean()))
# normal agreement (result sample vs nearest original sample)
dot = np.sum(b_nrm * a_nrm[ib], axis=1)
normal_deg = float(np.degrees(np.arccos(np.clip(np.abs(dot), 0, 1))).mean())
within = float((dba < 0.01 * diag).mean() * 100.0) # % within 1% of diag
return {
"chamfer": chamfer,
"chamfer_pct_diag": 100.0 * chamfer / diag,
"hausdorff": hausdorff,
"hausdorff_pct_diag": 100.0 * hausdorff / diag,
"mean_surface_dist": mean_dist,
"mean_dist_pct_diag": 100.0 * mean_dist / diag,
"mean_normal_deviation_deg": normal_deg,
"pct_within_1pct_diag": within,
}
def triangle_quality(mesh):
V, F = np.asarray(mesh.vertices), np.asarray(mesh.faces)
a = V[F[:, 0]]; b = V[F[:, 1]]; c = V[F[:, 2]]
def ang(p, q, r):
u = q - p; w = r - p
u /= (np.linalg.norm(u, axis=1, keepdims=True) + 1e-12)
w /= (np.linalg.norm(w, axis=1, keepdims=True) + 1e-12)
return np.degrees(np.arccos(np.clip(np.sum(u * w, axis=1), -1, 1)))
angs = np.stack([ang(a, b, c), ang(b, c, a), ang(c, a, b)], axis=1)
minang = angs.min(1)
# radius-edge aspect ratio: 1.0 == equilateral
e0 = np.linalg.norm(b - a, axis=1); e1 = np.linalg.norm(c - b, axis=1); e2 = np.linalg.norm(a - c, axis=1)
s = (e0 + e1 + e2) / 2
area = np.sqrt(np.maximum(s * (s - e0) * (s - e1) * (s - e2), 1e-20))
longest = np.maximum.reduce([e0, e1, e2])
inradius = area / np.maximum(s, 1e-12)
aspect = longest / (2 * np.sqrt(3) * inradius + 1e-12) # 1 == equilateral
return {
"min_angle_mean_deg": float(minang.mean()),
"min_angle_p05_deg": float(np.percentile(minang, 5)),
"pct_well_shaped": float((minang > 30).mean() * 100.0), # min angle > 30 deg
"aspect_ratio_median": float(np.median(aspect)),
"aspect_ratio_mean": float(aspect.mean()),
"aspect_ratio_p95": float(np.percentile(aspect, 95)),
}
def topology(mesh):
from .meshutil import num_components
V, F = np.asarray(mesh.vertices), np.asarray(mesh.faces)
val = np.bincount(F.reshape(-1), minlength=len(V)).astype(float)
nz = val[val > 0]
# For triangle meshes the ideal interior valence is 6; 5-7 is "regular-ish".
regular = float(np.mean((nz >= 5) & (nz <= 7)) * 100.0)
return {
"vertices": int(len(V)),
"faces": int(len(F)),
"watertight": bool(mesh.is_watertight),
"winding_consistent": bool(mesh.is_winding_consistent),
"components": int(num_components(V, F)),
"euler_number": int(mesh.euler_number),
"genus": int((2 - mesh.euler_number) // 2) if mesh.is_watertight else None,
"mean_valence": float(nz.mean()),
"valence_std": float(nz.std()),
"pct_valence_5_to_7": regular,
}
def compute_all(original, result, n_samples=60000):
return {
"fidelity": geometric_fidelity(original, result, n_samples),
"triangle_quality": triangle_quality(result),
"topology": topology(result),
}

View file

@ -0,0 +1,127 @@
"""Auto-Retopo pipeline orchestrator.
from autoretopo import AutoRetopo, RetopoConfig
ar = AutoRetopo(RetopoConfig(target_faces=6000))
result = ar.run("BabyRaptor.glb")
result.export("baby_retopo.glb")
print(result.metrics)
Pipeline: ingest -> watertight shell -> field-adaptive remesh -> silhouette
projection -> (optional quad) -> metrics.
"""
from __future__ import annotations
import time
import numpy as np
import trimesh
from .config import RetopoConfig
from . import ingest, shell, remesh, project, metrics, meshutil
class RetopoResult:
def __init__(self, original, mesh, metrics_dict, timings, config, quad_faces=None):
self.original = original
self.mesh = mesh # trimesh.Trimesh (triangles)
self.metrics = metrics_dict
self.timings = timings
self.config = config
self.quad_faces = quad_faces # list of polygonal faces if quads requested
def export(self, path: str):
self.mesh.export(path)
return path
@property
def vertices(self):
return np.asarray(self.mesh.vertices)
@property
def faces(self):
return np.asarray(self.mesh.faces)
class AutoRetopo:
def __init__(self, config: RetopoConfig | None = None):
self.cfg = config or RetopoConfig()
def _log(self, *a):
if self.cfg.verbose:
print(*a, flush=True)
def run(self, path_or_mesh) -> RetopoResult:
cfg = self.cfg
t = {}
t0 = time.time()
if isinstance(path_or_mesh, str):
original = ingest.load_mesh(path_or_mesh)
else:
original = ingest.repair(path_or_mesh)
t["ingest"] = time.time() - t0
self._log(f"[ingest] {len(original.faces)} faces, "
f"{meshutil.num_components(original.vertices, original.faces)} components, "
f"watertight={original.is_watertight}")
# Stage 1: base layer
t0 = time.time()
if cfg.watertight:
res = cfg.shell_resolution
fitted, peak_mb = shell.fit_resolution_to_budget(original, res, cfg.max_memory_gb)
if fitted != res:
self._log(f"[shell] resolution {res} -> {fitted} to fit "
f"{cfg.max_memory_gb:.1f} GB budget (est. peak {peak_mb:.0f} MB)")
V, F = shell.voxel_shell(original, fitted, cfg.shell_close_iter,
cfg.shell_smooth, cfg.shell_samples_per_pitch)
V, F = shell.largest_component(V, F)
self._log(f"[shell] {len(F)} faces (watertight base)")
else:
V, F = np.asarray(original.vertices), np.asarray(original.faces)
self._log("[shell] skipped (surface mode)")
t["shell"] = time.time() - t0
# Stage 2: clean topology
t0 = time.time()
V, F = remesh.isotropic_remesh(
V, F, cfg.target_faces, adaptive=cfg.adaptive, iters=cfg.remesh_iters,
feature_deg=cfg.feature_deg, calibrate_passes=cfg.calibrate_passes,
verbose=cfg.verbose)
# hit the budget exactly: decimate the (slightly over) adaptive result
if len(F) > cfg.target_faces * 1.05:
V, F = remesh.decimate_to_target(V, F, cfg.target_faces)
self._log(f"[decimate] -> {len(F)} faces (budget {cfg.target_faces})")
t["remesh"] = time.time() - t0
self._log(f"[remesh] {len(F)} faces")
# Stage 3: silhouette projection
t0 = time.time()
if cfg.project:
V = project.project_to_surface(
V, F, original, iters=cfg.project_iters,
clamp=cfg.project_clamp, relax_strength=cfg.relax_strength)
V, F = remesh.finalize_watertight(V, F) if cfg.watertight else remesh.clean_slivers(V, F)
t["project"] = time.time() - t0
result_mesh = trimesh.Trimesh(V, F, process=False)
result_mesh.fix_normals()
# Stage 4 (optional): quad-dominant conversion
quad_faces = None
t0 = time.time()
if cfg.quads:
try:
Vq, quad_faces = remesh.to_quad_dominant(V, F)
self._log(f"[quad] quad-dominant conversion -> {len(quad_faces)} polys")
except Exception as e:
self._log(f"[quad] conversion failed ({e}); keeping triangles")
t["quad"] = time.time() - t0
# Stage 5: metrics
t0 = time.time()
m = metrics.compute_all(original, result_mesh)
t["metrics"] = time.time() - t0
t["total"] = sum(t.values())
self._log(f"[done] {t['total']:.1f}s | "
f"hausdorff={m['fidelity']['hausdorff_pct_diag']:.2f}% diag | "
f"well-shaped tris={m['triangle_quality']['pct_well_shaped']:.0f}%")
return RetopoResult(original, result_mesh, m, t, cfg.to_dict(), quad_faces)

View file

@ -0,0 +1,67 @@
"""Stage 3 - silhouette projection ("walk the surface, don't just shrinkwrap").
The shell+remesh result has clean topology but rides slightly outside the true
surface and rounds sharp features. We pull it back onto the *original* surface
while keeping the topology and watertightness intact.
Each iteration:
1. Tangential relaxation: move every vertex toward its neighbours' centroid, but
remove the component along the vertex normal so the vertex slides *along* the
surface rather than sinking into it. This is the "Relax" behaviour from manual
retopo tools - it evens out quad/triangle spacing without denting the form.
2. Clamped closest-point snap: project each vertex onto the nearest point of the
original surface, but cap the move at `clamp x local_edge_length`. The clamp is
what makes this robust on fragmented input: a vertex can never be yanked across
a gap onto a distant internal shell, which is the classic failure of naive
shrinkwrap.
Because connectivity never changes, a watertight input stays watertight.
"""
from __future__ import annotations
import numpy as np
import trimesh
def _vertex_adjacency(n_verts, F):
e = np.vstack([F[:, [0, 1]], F[:, [1, 2]], F[:, [2, 0]]])
e = np.vstack([e, e[:, ::-1]])
nbr = [[] for _ in range(n_verts)]
for a, b in e:
nbr[a].append(b)
return [np.unique(np.asarray(n, int)) for n in nbr]
def _vertex_edge_length(V, F):
e = np.vstack([F[:, [0, 1]], F[:, [1, 2]], F[:, [2, 0]]])
d = np.linalg.norm(V[e[:, 0]] - V[e[:, 1]], axis=1)
s = np.zeros(len(V)); c = np.zeros(len(V))
np.add.at(s, e[:, 0], d); np.add.at(s, e[:, 1], d)
np.add.at(c, e[:, 0], 1.0); np.add.at(c, e[:, 1], 1.0)
return s / np.maximum(c, 1.0)
def _tangential_relax(V, F, normals, adjacency, strength):
Q = V.copy()
for i, nb in enumerate(adjacency):
if len(nb) == 0:
continue
d = V[nb].mean(0) - V[i]
d = d - normals[i] * np.dot(d, normals[i]) # project onto tangent plane
Q[i] = V[i] + strength * d
return Q
def project_to_surface(V, F, target_mesh, iters=10, clamp=1.5, relax_strength=0.4):
pq = trimesh.proximity.ProximityQuery(target_mesh)
adjacency = _vertex_adjacency(len(V), F)
Vc = np.asarray(V, float).copy()
for _ in range(int(iters)):
normals = trimesh.Trimesh(Vc, F, process=False).vertex_normals
Vc = _tangential_relax(Vc, F, normals, adjacency, relax_strength)
elen = _vertex_edge_length(Vc, F)
closest, _, _ = pq.on_surface(Vc)
move = closest - Vc
mlen = np.linalg.norm(move, axis=1) + 1e-12
scale = np.minimum(1.0, (clamp * elen) / mlen)
Vc = Vc + move * scale[:, None]
return np.ascontiguousarray(Vc)

View file

@ -0,0 +1,159 @@
"""Stage 2 - clean topology via field-adaptive isotropic remeshing.
Isotropic explicit remeshing (split/collapse/flip/smooth + reproject) turns the
dense marching-cubes shell into evenly-spaced, near-equilateral triangles. With
`adaptive=True` the target edge length is modulated by local curvature, so spikes,
claws and the head get more resolution while flat areas (belly, flanks) stay light
- the hallmark of good low-poly topology.
Because adaptive density makes the final face count hard to predict from a single
edge-length, we run a short calibration loop: estimate L from the area budget, then
rescale L by sqrt(actual/target) and remesh again. Two passes land within a few
percent of the requested budget on typical meshes.
If a `quadriflow` binary is on PATH it can be used instead (field-aligned pure-quad
output); otherwise we optionally post-process tris into quad-dominant topology with
MeshLab's curvature-aware pairing.
"""
from __future__ import annotations
import shutil, subprocess, tempfile, os
import numpy as np
import trimesh
import pymeshlab as ml
def _edge_len_for_faces(V, F, target_faces):
area = float(trimesh.Trimesh(V, F, process=False).area)
return float(np.sqrt(4.0 * area / (max(1, target_faces) * np.sqrt(3.0))))
def isotropic_remesh(V, F, target_faces, adaptive=True, iters=10,
feature_deg=30.0, calibrate_passes=2, verbose=False):
"""Remesh to ~target_faces. Each calibration pass remeshes the *same source*
with a corrected edge length (n ~ 1/L^2), and we keep the pass closest to the
budget so adaptive density can't make us drift."""
L = _edge_len_for_faces(V, F, target_faces)
Vsrc, Fsrc = np.asarray(V, float), np.asarray(F, np.int64)
best = None
for p in range(1 + max(0, calibrate_passes)):
ms = ml.MeshSet()
ms.add_mesh(ml.Mesh(Vsrc, Fsrc))
ms.meshing_isotropic_explicit_remeshing(
iterations=int(iters), adaptive=bool(adaptive),
targetlen=ml.PureValue(L), featuredeg=float(feature_deg),
checksurfdist=False)
mm = ms.current_mesh()
Vc, Fc = np.asarray(mm.vertex_matrix()), np.asarray(mm.face_matrix())
n = len(Fc)
if verbose:
print(f" remesh pass {p}: L={L:.5f} -> {n} faces")
if n == 0:
break
err = abs(n - target_faces) / float(target_faces)
if best is None or err < best[0]:
best = (err, Vc, Fc)
if err < 0.05 or p == calibrate_passes:
break
L *= np.sqrt(n / float(target_faces)) # bigger edges -> fewer faces
_, Vb, Fb = best
return np.ascontiguousarray(Vb), np.ascontiguousarray(Fb.astype(np.int64))
def decimate_to_target(V, F, target_faces, preserve_boundary=True):
"""Quadric edge-collapse decimation to an exact face budget.
Adaptive remeshing nails edge flow but lands a little above the budget (it keeps
a curvature-driven density floor on features). A single quality-quadric pass
brings the count down to the exact target while preserving the silhouette; the
subsequent projection/relax stage re-regularises the triangles.
"""
ms = ml.MeshSet()
ms.add_mesh(ml.Mesh(np.asarray(V, float), np.asarray(F, np.int64)))
ms.meshing_decimation_quadric_edge_collapse(
targetfacenum=int(target_faces),
qualitythr=0.5, preserveboundary=bool(preserve_boundary),
preservenormal=True, preservetopology=True, optimalplacement=True,
planarquadric=True, autoclean=True)
mm = ms.current_mesh()
return np.ascontiguousarray(mm.vertex_matrix()), \
np.ascontiguousarray(mm.face_matrix().astype(np.int64))
def finalize_watertight(V, F, close_holes=200):
"""Clean up after decimation + projection while preserving connectivity.
Projection never changes topology, so the mesh arrives as one component. We only
drop exactly-degenerate (zero-area) faces and weld, then - if a few boundary edges
appeared - seal them by *adding* faces (close_holes). We deliberately do NOT run
face-removing non-manifold repair: on multi-part figures (a warrior + weapon +
shield) it cuts thin bridges and shatters the single shell into many pieces.
"""
import trimesh as _tm
m = _tm.Trimesh(np.asarray(V, float), np.asarray(F, np.int64), process=False)
m.update_faces(m.nondegenerate_faces())
m.merge_vertices()
m.remove_unreferenced_vertices()
if m.is_watertight:
return np.ascontiguousarray(m.vertices), np.ascontiguousarray(m.faces.astype(np.int64))
ms = ml.MeshSet()
ms.add_mesh(ml.Mesh(np.asarray(m.vertices, float), np.asarray(m.faces, np.int64)))
try:
ms.meshing_close_holes(maxholesize=int(close_holes), selfintersection=False)
except Exception:
pass
mm = ms.current_mesh()
return np.ascontiguousarray(mm.vertex_matrix()), \
np.ascontiguousarray(mm.face_matrix().astype(np.int64))
def clean_slivers(V, F, min_quality=0.02):
"""Drop degenerate / extreme-sliver faces and unreferenced vertices."""
import trimesh as _tm
m = _tm.Trimesh(np.asarray(V, float), np.asarray(F, np.int64), process=False)
tri = m.triangles
e0 = np.linalg.norm(tri[:, 1] - tri[:, 0], axis=1)
e1 = np.linalg.norm(tri[:, 2] - tri[:, 1], axis=1)
e2 = np.linalg.norm(tri[:, 0] - tri[:, 2], axis=1)
longest = np.maximum.reduce([e0, e1, e2]) + 1e-12
quality = (2.0 * m.area_faces) / (longest * longest) # ~ height/base, 0 == degenerate
keep = quality > min_quality
m.update_faces(keep)
m.remove_unreferenced_vertices()
return np.ascontiguousarray(m.vertices), np.ascontiguousarray(m.faces.astype(np.int64))
def to_quad_dominant(V, F):
ms = ml.MeshSet()
ms.add_mesh(ml.Mesh(np.asarray(V, float), np.asarray(F, np.int64)))
# align edges to curvature first, then pair triangles into quads
try:
ms.meshing_edge_flip_by_curvature_optimization(iterations=2)
except Exception:
pass
ms.meshing_tri_to_quad_by_smart_triangle_pairing()
mm = ms.current_mesh()
# pymeshlab stores quads as two coplanar tris with a face-flag; expose polygonal
# faces if available, else return the (quad-paired) triangle matrix.
try:
polys = mm.polygonal_face_list()
return np.asarray(mm.vertex_matrix()), polys
except Exception:
return np.asarray(mm.vertex_matrix()), np.asarray(mm.face_matrix())
def quadriflow_available():
return shutil.which("quadriflow") is not None
def quadriflow_remesh(V, F, target_faces):
"""Optional: use an external QuadriFlow binary for field-aligned pure quads."""
if not quadriflow_available():
raise RuntimeError("quadriflow binary not found on PATH")
with tempfile.TemporaryDirectory() as d:
inp, out = os.path.join(d, "in.obj"), os.path.join(d, "out.obj")
trimesh.Trimesh(V, F, process=False).export(inp)
subprocess.run(["quadriflow", "-i", inp, "-o", out,
"-f", str(int(target_faces))], check=True)
m = trimesh.load(out, process=False)
return np.asarray(m.vertices), np.asarray(m.faces)

View file

@ -0,0 +1,127 @@
"""Dependency-light software renderer: z-buffered flat shading + wireframe overlay.
Pure numpy + scikit-image line drawing. Works headless (no OpenGL)."""
import numpy as np
from skimage.draw import line_aa
def _look_at(cam, target, up=(0, 1, 0)):
f = target - cam
f = f / (np.linalg.norm(f) + 1e-12)
up = np.asarray(up, float)
r = np.cross(f, up); r /= (np.linalg.norm(r) + 1e-12)
u = np.cross(r, f)
R = np.stack([r, u, -f], axis=0)
return R
def render_mesh(verts, faces, azim=35.0, elev=20.0, res=900, zoom=1.0,
mode="shaded", bg=1.0, line_color=(0.10, 0.10, 0.12),
face_color=(0.62, 0.66, 0.72), light_dir=(0.3, 0.6, 0.7)):
"""Render a triangle mesh. mode in {'shaded','wire','shaded_wire'}.
Returns HxWx3 float image in [0,1]."""
V = np.asarray(verts, float).copy()
F = np.asarray(faces, int)
c = 0.5 * (V.min(0) + V.max(0))
V -= c
radius = np.linalg.norm(V, axis=1).max() + 1e-9
a, e = np.radians(azim), np.radians(elev)
cam_dir = np.array([np.cos(e) * np.sin(a), np.sin(e), np.cos(e) * np.cos(a)])
cam = cam_dir * radius * 3.0
R = _look_at(cam, np.zeros(3))
Vc = (V - cam) @ R.T # camera space (-z forward)
z = -Vc[:, 2]
fov_scale = (res * 0.5 * zoom) * (3.0) # orth-ish framing scaled to radius
s = fov_scale / radius
xs = Vc[:, 0] * s / (z / (radius * 3.0)) # mild perspective
ys = Vc[:, 1] * s / (z / (radius * 3.0))
px = (res * 0.5 + xs)
py = (res * 0.5 - ys)
img = np.ones((res, res, 3), float) * bg
zbuf = np.full((res, res), np.inf)
# face depth + normals (camera space) for shading & back-face cull
p0, p1, p2 = Vc[F[:, 0]], Vc[F[:, 1]], Vc[F[:, 2]]
n = np.cross(p1 - p0, p2 - p0)
nlen = np.linalg.norm(n, axis=1, keepdims=True) + 1e-12
n = n / nlen
L = np.asarray(light_dir, float); L /= np.linalg.norm(L)
shade = np.clip(np.abs(n @ L), 0.0, 1.0) * 0.75 + 0.25
fc = np.asarray(face_color, float)
fz = z[F].mean(1)
order = np.argsort(-fz) # far to near (painter) for fill
sx, sy = px[F], py[F] # (nf,3)
if mode in ("shaded", "shaded_wire"):
# scanline-ish: rasterize each triangle with a bounding-box test (vectorized per-tri)
for fi in order:
x0, x1, x2 = sx[fi]; y0, y1, y2 = sy[fi]
minx = int(max(0, np.floor(min(x0, x1, x2)))); maxx = int(min(res - 1, np.ceil(max(x0, x1, x2))))
miny = int(max(0, np.floor(min(y0, y1, y2)))); maxy = int(min(res - 1, np.ceil(max(y0, y1, y2))))
if minx > maxx or miny > maxy:
continue
xx, yy = np.meshgrid(np.arange(minx, maxx + 1), np.arange(miny, maxy + 1))
d = ((y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2))
if abs(d) < 1e-9:
continue
wa = ((y1 - y2) * (xx - x2) + (x2 - x1) * (yy - y2)) / d
wb = ((y2 - y0) * (xx - x2) + (x0 - x2) * (yy - y2)) / d
wc = 1 - wa - wb
inside = (wa >= -1e-4) & (wb >= -1e-4) & (wc >= -1e-4)
if not inside.any():
continue
yI, xI = yy[inside], xx[inside]
zval = float(fz[fi])
better = zval < zbuf[yI, xI]
yb, xb = yI[better], xI[better]
zbuf[yb, xb] = zval
img[yb, xb] = fc * shade[fi]
if mode in ("wire", "shaded_wire"):
# draw front-facing edges; in pure-wire mode keep bg
ec = np.asarray(line_color, float)
camN = -Vc[F].mean(1)
front = (n * (camN / (np.linalg.norm(camN, axis=1, keepdims=True) + 1e-12))).sum(1) > -0.15
alpha_base = 0.9 if mode == "wire" else 0.55
seen = set()
for fi in np.argsort(fz): # near to far so near edges drawn last (on top)
if not front[fi]:
continue
tri = F[fi]
for a_, b_ in ((0, 1), (1, 2), (2, 0)):
ia, ib = tri[a_], tri[b_]
key = (ia, ib) if ia < ib else (ib, ia)
if key in seen:
continue
seen.add(key)
rr, cc_, val = line_aa(int(py[ia]), int(px[ia]), int(py[ib]), int(px[ib]))
ok = (rr >= 0) & (rr < res) & (cc_ >= 0) & (cc_ < res)
rr, cc_, val = rr[ok], cc_[ok], val[ok]
al = (val * alpha_base)[:, None]
img[rr, cc_] = img[rr, cc_] * (1 - al) + ec * al
return np.clip(img, 0, 1)
def panel(views, labels, path, ncols=None, title=None, pad=10, label_h=34):
"""Stack a grid of rendered images with labels into one PNG."""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
n = len(views)
ncols = ncols or n
nrows = int(np.ceil(n / ncols))
fig, axes = plt.subplots(nrows, ncols, figsize=(ncols * 3.6, nrows * 3.8))
axes = np.atleast_1d(axes).ravel()
for i, ax in enumerate(axes):
if i < n:
ax.imshow(views[i]); ax.set_title(labels[i], fontsize=11)
ax.axis("off")
if title:
fig.suptitle(title, fontsize=14, fontweight="bold")
fig.tight_layout()
fig.savefig(path, dpi=110, bbox_inches="tight", facecolor="white")
plt.close(fig)
return path

View file

@ -0,0 +1,149 @@
"""Stage 1 - watertight silhouette shell.
The user's goal: "follow the silhouette of the mesh and generate a new layer of
faces that is watertight." We do this with a robust occupancy field rather than a
signed-distance field, because the input is typically a non-manifold triangle soup
(the BabyRaptor test mesh has 810 disconnected components) for which the *sign* of
an SDF is undefined and MeshLab-style resampling fragments.
Method:
1. Surface-voxelize the mesh at pitch = diag / resolution (memory-bounded, below).
2. Morphologically close (dilate) to bridge unwelded cracks between patches.
3. Flood-fill the interior (binary_fill_holes) -> a solid occupancy volume.
Enclosed cavities are filled; genuine openings (e.g. an open mouth wider than
the voxel pitch) stay open.
4. Erode back to undo the dilation bias, then union the original surface voxels.
5. Blur the occupancy field slightly and extract the 0.5 iso-surface with
marching cubes -> a single, guaranteed-watertight, 2-manifold triangle mesh
that tightly tracks the outer silhouette.
The result is dense (it is an intermediate); the remesh stage decimates it to the
face budget with clean topology.
Memory note
-----------
We do NOT use trimesh's `mesh.voxelized()`: it subdivides every triangle until its
edges are below the voxel pitch, so its peak memory scales with surface_area/pitch^2
AND with triangle size (a single large face quadruples per subdivision level). That
makes RAM explode unpredictably on coarse or uneven meshes. `bounded_surface_voxelize`
instead streams an area-proportional barycentric lattice straight into the grid in
chunks, so peak memory depends only on the grid size and a fixed chunk - never on the
input triangle count or size.
"""
from __future__ import annotations
import numpy as np
import trimesh
from scipy import ndimage
from skimage import measure
def _lattice_bary(k: int) -> np.ndarray:
"""Barycentric lattice for subdivision level k: (i/k, j/k, 1-i/k-j/k), i+j<=k."""
ij = np.array([(i, j) for i in range(k + 1) for j in range(k + 1 - i)], float)
a = ij[:, 0] / k
b = ij[:, 1] / k
return np.stack([a, b, 1.0 - a - b], axis=1) # (P, 3)
def bounded_surface_voxelize(mesh, pitch, samples_per_pitch=2.0, kmax=128, chunk=200_000):
"""Memory-bounded surface voxelization.
Returns (occupancy_grid: bool[X,Y,Z], origin: float[3]). The occupancy is the set
of voxels touched by the surface, sampled densely enough (lattice spacing <=
pitch/samples_per_pitch) that flood-fill cannot leak through. Peak memory is
O(grid + chunk), independent of triangle size distribution.
"""
lo = mesh.bounds[0].astype(np.float64)
hi = mesh.bounds[1].astype(np.float64)
pad = 3
dims = (np.ceil((hi - lo) / pitch).astype(int) + 1 + 2 * pad)
origin = lo - pad * pitch
grid = np.zeros(tuple(int(d) for d in dims), dtype=bool)
dmax = np.array(dims, np.int32) - 1
tris = np.asarray(mesh.triangles, np.float64) # (F, 3, 3)
if len(tris) == 0:
return grid, origin
edges = np.stack([
np.linalg.norm(tris[:, 1] - tris[:, 0], axis=1),
np.linalg.norm(tris[:, 2] - tris[:, 1], axis=1),
np.linalg.norm(tris[:, 0] - tris[:, 2], axis=1)], axis=1)
spacing = pitch / float(samples_per_pitch)
k = np.clip(np.ceil(edges.max(1) / spacing).astype(int), 1, int(kmax))
for kk in np.unique(k):
sel = np.where(k == kk)[0]
bary = _lattice_bary(int(kk)) # (P, 3)
P = len(bary)
step = max(1, chunk // max(P, 1)) # rows per chunk so rows*P<=chunk
for s in range(0, len(sel), step):
T = tris[sel[s:s + step]] # (m, 3, 3)
pts = np.einsum("pj,mjc->mpc", bary, T).reshape(-1, 3)
vi = np.floor((pts - origin) / pitch).astype(np.int32)
np.clip(vi, 0, dmax, out=vi)
grid[vi[:, 0], vi[:, 1], vi[:, 2]] = True
return grid, origin
def voxel_shell(mesh: trimesh.Trimesh, resolution: int = 256,
close_iter: int = 1, smooth_sigma: float = 0.6,
samples_per_pitch: float = 2.0):
diag = float(np.linalg.norm(mesh.extents))
pitch = diag / max(32, int(resolution))
dense, origin = bounded_surface_voxelize(mesh, pitch, samples_per_pitch)
if not dense.any():
raise RuntimeError("Voxelization produced an empty volume; lower shell_resolution.")
solid = ndimage.binary_dilation(dense, iterations=close_iter) if close_iter else dense.copy()
solid = ndimage.binary_fill_holes(solid)
if close_iter:
solid = ndimage.binary_erosion(solid, iterations=close_iter)
solid |= dense
del dense
# blur in place-ish, then free the bool volume before marching cubes allocates
field = ndimage.gaussian_filter(solid.astype(np.float32), float(smooth_sigma))
del solid
verts, faces, _, _ = measure.marching_cubes(field, level=0.5)
del field
V = verts * pitch + origin
return np.ascontiguousarray(V), np.ascontiguousarray(faces.astype(np.int64))
def estimate_grid_voxels(mesh, resolution):
"""Predict the occupancy grid size (voxels) for a memory guard, without building it."""
diag = float(np.linalg.norm(mesh.extents))
pitch = diag / max(32, int(resolution))
dims = np.ceil(mesh.extents / pitch).astype(int) + 7
return int(np.prod(dims)), pitch
# The shell stage's peak memory is dominated by a handful of full-grid arrays
# (bool occupancy + dilations + fill + a float32 field + marching-cubes output).
# Empirically that is ~12 bytes per voxel of peak working set.
_BYTES_PER_VOXEL = 12.0
_SHELL_RESERVE_MB = 260.0 # base interpreter + later pymeshlab working set
def fit_resolution_to_budget(mesh, resolution, max_memory_gb):
"""Lower `resolution` until the predicted shell grid fits the memory budget.
Returns (resolution, predicted_peak_mb). A no-op when it already fits."""
if not max_memory_gb:
return int(resolution), None
budget_mb = float(max_memory_gb) * 1024.0
res = int(resolution)
while res > 64:
nvox, _ = estimate_grid_voxels(mesh, res)
peak_mb = _SHELL_RESERVE_MB + nvox * _BYTES_PER_VOXEL / 1e6
if peak_mb <= budget_mb:
return res, peak_mb
res -= 16
nvox, _ = estimate_grid_voxels(mesh, res)
return res, _SHELL_RESERVE_MB + nvox * _BYTES_PER_VOXEL / 1e6
def largest_component(V, F):
from .meshutil import largest_component as _lc
return _lc(V, F)

View file

@ -0,0 +1,13 @@
"""AutoUV: a low-poly-focused automatic UV unwrapper.
Public API
----------
from autouv import load, unwrap, save_glb, render_uv
"""
from .mesh import Mesh
from .io import load, save_glb
from .unwrap import unwrap, UnwrapResult
from .render import render_uv
__all__ = ["Mesh", "load", "save_glb", "unwrap", "UnwrapResult", "render_uv"]
__version__ = "0.1.0"

View file

@ -0,0 +1,3 @@
from .cli import main
raise SystemExit(main())

View file

@ -0,0 +1,129 @@
"""Command-line interface for AutoUV.
Examples
--------
# Unwrap a mesh, write a UV'd GLB next to it and a layout preview PNG
python -m autouv unwrap Cave_10K.glb -o Cave_uv.glb --preview layout.png
# Faster, coarser result (skip the validated-merge refinement)
python -m autouv unwrap model.glb -o out.glb --no-refine
# Tune island size / distortion trade-off
python -m autouv unwrap model.glb -o out.glb --cone 60 --island-faces 120
"""
from __future__ import annotations
import argparse
import json
import sys
import time
from . import load, save_glb, render_uv, __version__
from .unwrap import unwrap
def _add_unwrap_args(p: argparse.ArgumentParser) -> None:
p.add_argument("input", help="input mesh (.glb/.gltf/.obj/.ply/.stl)")
p.add_argument("-o", "--output", help="output GLB with the new UV channel")
p.add_argument("--preview", help="write a UV-layout preview PNG to this path")
p.add_argument("--cone", type=float, default=55.0, dest="max_cone_deg",
help="normal-cone cap in degrees; higher = fewer, more "
"distorted charts (default 55)")
p.add_argument("--island-faces", type=int, default=80,
dest="refine_target_faces",
help="charts smaller than this are merge candidates in the "
"refinement pass; higher = fewer, larger islands "
"(default 80)")
p.add_argument("--no-refine", action="store_false", dest="refine",
help="skip the LSCM-validated merge pass (much faster, "
"more charts)")
p.add_argument("--no-weld", action="store_false", dest="weld",
help="skip topology repair (proximity vertex weld). Only "
"use this if your mesh is already clean and you want "
"to preserve its exact vertex set")
p.add_argument("--weld-tol", type=float, default=0.1, dest="weld_tol_frac",
help="weld tolerance as a fraction of the median edge "
"length; vertices closer than this are merged "
"(default 0.1)")
p.add_argument("--arap-iters", type=int, default=4, dest="arap_iters",
help="as-rigid-as-possible flattening iterations per chart; "
"0 disables ARAP (LSCM/planar only). Higher = lower "
"area distortion (default 4)")
p.add_argument("--resolution", type=int, default=1024,
help="target texture resolution used for padding (default 1024)")
p.add_argument("--padding", type=int, default=4, dest="padding_texels",
help="inter-island padding in texels (default 4)")
p.add_argument("--quiet", action="store_true", help="suppress progress output")
def _cmd_unwrap(args: argparse.Namespace) -> int:
if not args.output and not args.preview:
print("nothing to do: pass -o/--output and/or --preview", file=sys.stderr)
return 2
t0 = time.time()
mesh = load(args.input)
if not args.quiet:
print(f"loaded {args.input}: {mesh.n_faces} faces", file=sys.stderr)
# lightweight terminal progress bar (no extra deps)
_bar = {"stage": ""}
def _progress(stage, frac):
if args.quiet:
return
if stage != _bar["stage"]:
_bar["stage"] = stage
n = int(frac * 30)
sys.stderr.write(
f"\r {stage:<13} [{'#' * n}{'.' * (30 - n)}] {frac * 100:3.0f}%")
sys.stderr.flush()
if frac >= 1.0 and stage in ("parameterize",):
sys.stderr.write("\n")
result = unwrap(
mesh,
max_cone_deg=args.max_cone_deg,
refine=args.refine,
refine_target_faces=args.refine_target_faces,
resolution=args.resolution,
padding_texels=args.padding_texels,
weld=args.weld,
weld_tol_frac=args.weld_tol_frac,
arap_iters=args.arap_iters,
progress=None if args.quiet else _progress,
verbose=not args.quiet,
)
if args.output:
save_glb(args.output, result.vertices, result.faces, result.uv)
if not args.quiet:
print(f"wrote {args.output}", file=sys.stderr)
if args.preview:
render_uv(result, args.preview)
if not args.quiet:
print(f"wrote {args.preview}", file=sys.stderr)
# machine-readable stats on stdout
print(json.dumps(result.stats, indent=2))
if not args.quiet:
print(f"done in {time.time() - t0:.2f}s", file=sys.stderr)
return 0
def main(argv=None) -> int:
parser = argparse.ArgumentParser(
prog="autouv", description="Automatic UV unwrapping for low-poly meshes.")
parser.add_argument("--version", action="version",
version=f"autouv {__version__}")
sub = parser.add_subparsers(dest="command", required=True)
p_unwrap = sub.add_parser("unwrap", help="unwrap a mesh")
_add_unwrap_args(p_unwrap)
p_unwrap.set_defaults(func=_cmd_unwrap)
args = parser.parse_args(argv)
return args.func(args)
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -0,0 +1,31 @@
"""GLB/OBJ I/O via trimesh. Kept separate so the core stays dependency-light."""
from __future__ import annotations
import numpy as np
import trimesh
from .mesh import Mesh
def load(path: str) -> Mesh:
scene = trimesh.load(path, process=True)
if isinstance(scene, trimesh.Scene):
geoms = list(scene.geometry.values())
if not geoms:
raise ValueError("no geometry in file")
# concatenate all geometries into one mesh
m = trimesh.util.concatenate(geoms) if len(geoms) > 1 else geoms[0]
else:
m = scene
return Mesh(np.asarray(m.vertices), np.asarray(m.faces))
def save_glb(path, vertices, faces, uv):
"""Write a GLB with a vertex UV channel and a checker material."""
mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False)
mesh.visual = trimesh.visual.TextureVisuals(
uv=np.asarray(uv),
material=trimesh.visual.material.PBRMaterial(name="autouv"),
)
mesh.export(path)
return path

View file

@ -0,0 +1,125 @@
"""Mesh container and topology helpers for the AutoUV pipeline.
We keep this dependency-light: only numpy is required here. Loading/saving GLB
lives in io.py (which uses trimesh). Everything the unwrapper needs about the
connectivity of the mesh is computed once and cached on the Mesh object.
"""
from __future__ import annotations
import numpy as np
class Mesh:
"""A triangle mesh with cached topology.
Attributes
----------
vertices : (V, 3) float64
faces : (F, 3) int32
"""
def __init__(self, vertices: np.ndarray, faces: np.ndarray):
self.vertices = np.asarray(vertices, dtype=np.float64)
self.faces = np.asarray(faces, dtype=np.int64)
self._face_normals = None
self._face_areas = None
self._adjacency = None # (E,2) face pairs sharing an edge
self._adjacency_edges = None # (E,2) the shared vertex pair
self._adjacency_angle = None # (E,) dihedral angle in radians
self._components = None # per-face component id
# ------------------------------------------------------------------ basic
@property
def n_faces(self) -> int:
return len(self.faces)
@property
def face_normals(self) -> np.ndarray:
if self._face_normals is None:
v = self.vertices[self.faces]
n = np.cross(v[:, 1] - v[:, 0], v[:, 2] - v[:, 0])
ln = np.linalg.norm(n, axis=1, keepdims=True)
ln[ln == 0] = 1.0
self._face_normals = n / ln
return self._face_normals
@property
def face_areas(self) -> np.ndarray:
if self._face_areas is None:
v = self.vertices[self.faces]
cr = np.cross(v[:, 1] - v[:, 0], v[:, 2] - v[:, 0])
self._face_areas = 0.5 * np.linalg.norm(cr, axis=1)
return self._face_areas
# ----------------------------------------------------------- adjacency
def _build_adjacency(self):
"""Build face adjacency over shared edges plus dihedral angles."""
faces = self.faces
# For every face, its three undirected edges (sorted vertex pair).
e0 = faces[:, [0, 1]]
e1 = faces[:, [1, 2]]
e2 = faces[:, [2, 0]]
edges = np.concatenate([e0, e1, e2], axis=0)
edges_sorted = np.sort(edges, axis=1)
face_of_edge = np.tile(np.arange(len(faces)), 3)
# Group identical edges. An interior manifold edge is shared by 2 faces.
order = np.lexsort((edges_sorted[:, 1], edges_sorted[:, 0]))
es = edges_sorted[order]
fo = face_of_edge[order]
same = np.all(es[1:] == es[:-1], axis=1)
# indices i where es[i]==es[i+1] -> a shared edge between fo[i],fo[i+1]
idx = np.nonzero(same)[0]
fa = fo[idx]
fb = fo[idx + 1]
shared_edges = es[idx]
normals = self.face_normals
dots = np.einsum("ij,ij->i", normals[fa], normals[fb])
dots = np.clip(dots, -1.0, 1.0)
ang = np.arccos(dots)
self._adjacency = np.stack([fa, fb], axis=1)
self._adjacency_edges = shared_edges
self._adjacency_angle = ang
@property
def adjacency(self) -> np.ndarray:
if self._adjacency is None:
self._build_adjacency()
return self._adjacency
@property
def adjacency_edges(self) -> np.ndarray:
if self._adjacency_edges is None:
self._build_adjacency()
return self._adjacency_edges
@property
def adjacency_angle(self) -> np.ndarray:
if self._adjacency_angle is None:
self._build_adjacency()
return self._adjacency_angle
# --------------------------------------------------------- components
@property
def components(self) -> np.ndarray:
"""Connected-component id per face (over the adjacency graph)."""
if self._components is None:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components
adj = self.adjacency
n = self.n_faces
if len(adj) == 0:
self._components = np.arange(n)
else:
data = np.ones(len(adj))
g = csr_matrix(
(data, (adj[:, 0], adj[:, 1])), shape=(n, n)
)
g = g + g.T
_, labels = connected_components(g, directed=False)
self._components = labels
return self._components

View file

@ -0,0 +1,137 @@
"""Atlas packing.
A *skyline* (bottom-left) bin packer. Each island is reduced to its (padded)
bounding box; boxes are placed tallest-first at the lowest, left-most spot the
skyline allows, optionally rotated 90 degrees when that wastes less vertical
space. This packs the irregular islands that come out of a low-poly unwrap far
more tightly than fixed shelves (typically 80-90% bbox coverage vs ~60% for
shelves), which matters because wasted atlas space is wasted texture memory.
Everything is finally scaled by a single global factor into the unit square, so
the uniform texel density set in :mod:`postprocess` is preserved.
Padding is expressed in texels for a target resolution -- this is what prevents
mip/bilinear bleed between islands at low texture resolutions.
"""
from __future__ import annotations
import numpy as np
def _skyline_pack(boxes, bin_w):
"""Place [w, h] boxes (already padded). Returns placements, used_w, used_h.
placements[i] = (x, y, rotated). Skyline = list of [x, top_y, width].
"""
skyline = [[0.0, 0.0, bin_w]]
placements = {}
def level_for(start, w):
"""Lowest y at which a span of width w starting at segment ``start`` fits."""
x0 = skyline[start][0]
if x0 + w > bin_w + 1e-9:
return None
rem, y, i = w, 0.0, start
while rem > 1e-12:
if i >= len(skyline):
return None
y = max(y, skyline[i][1])
rem -= skyline[i][2]
i += 1
return y
def add_at(x, y, w, h):
"""Insert a box of width w at x and raise the skyline to y + h."""
new_top = y + h
out = []
placed = False
x_end = x + w
for seg in skyline:
sx, sy, sw = seg
sx_end = sx + sw
if sx_end <= x + 1e-12 or sx >= x_end - 1e-12:
out.append(seg) # untouched
continue
# trim left remainder
if sx < x - 1e-12:
out.append([sx, sy, x - sx])
if not placed:
out.append([x, new_top, w])
placed = True
# trim right remainder
if sx_end > x_end + 1e-12:
out.append([x_end, sy, sx_end - x_end])
# merge adjacent segments at equal height
merged = [out[0]]
for seg in out[1:]:
if abs(seg[1] - merged[-1][1]) < 1e-12:
merged[-1][2] += seg[2]
else:
merged.append(seg)
skyline[:] = merged
order = sorted(range(len(boxes)), key=lambda b: (-boxes[b][2], -boxes[b][1]))
used_w = used_h = 0.0
for bi in order:
_, w, h, _ = boxes[bi]
best = None # (top_y, x, rotated, w, h)
for rot, (cw, ch) in enumerate(((w, h), (h, w))):
for start in range(len(skyline)):
x = skyline[start][0]
y = level_for(start, cw)
if y is None:
continue
key = (y + ch, x)
if best is None or key < (best[0], best[1]):
best = (y + ch, x, rot, cw, ch, y)
if best is None: # forced overflow (rare)
x, y = 0.0, max((s[1] for s in skyline), default=0.0)
cw, ch, rot = w, h, 0
add_at(x, y, cw, ch)
else:
_, x, rot, cw, ch, y = best
add_at(x, y, cw, ch)
placements[bi] = (x, y, bool(rot))
used_w = max(used_w, x + cw)
used_h = max(used_h, y + ch)
return placements, used_w, used_h
def pack(islands, resolution=1024, padding_texels=4):
"""Pack a list of (V,2) islands into ``[0,1]^2``.
Returns ``(packed_islands, fill_ratio)`` where ``fill_ratio`` is the share of
the unit square covered by island bounding boxes.
"""
pad = padding_texels / float(resolution)
boxes = []
for i, uv in enumerate(islands):
mn = uv.min(axis=0)
ext = uv.max(axis=0) - mn
boxes.append([i, float(ext[0]) + pad, float(ext[1]) + pad, mn])
total_area = sum(b[1] * b[2] for b in boxes)
# aim a bit denser than square; skyline usually realises ~85%
bin_w = np.sqrt(total_area / 0.85)
# never make the bin narrower than the widest single box
bin_w = max(bin_w, max(b[1] for b in boxes))
placements, used_w, used_h = _skyline_pack(boxes, bin_w)
scale = 1.0 / max(used_w, used_h, 1e-9)
packed = [None] * len(islands)
used = 0.0
for bi in range(len(islands)):
i, w, h, mn = boxes[bi]
ox, oy, rot = placements[bi]
uv = islands[bi] - mn
if rot: # rotate 90 degrees
uv = np.column_stack((uv[:, 1], (w - pad) - uv[:, 0]))
uv = uv * scale
uv[:, 0] += (ox + pad * 0.5) * scale
uv[:, 1] += (oy + pad * 0.5) * scale
packed[bi] = uv
used += ((w - pad) * scale) * ((h - pad) * scale)
return packed, float(used)

View file

@ -0,0 +1,388 @@
"""Per-chart flattening.
Three methods, best-of kept per chart:
* **LSCM** (Levy et al. 2002): minimises *angle* distortion, needs two pinned
vertices. Conformal, so it preserves angles at the cost of *area* — a large
chart spanning curvature comes out with uneven texel density.
* **ARAP** (Liu et al. 2008, "A Local/Global Approach to Mesh Parameterization"):
minimises deviation from a *rigid* (isometric) map, so it balances angle *and*
area distortion. It needs an initial flattening to start from; we seed it with
the LSCM result (or planar) and run a few local/global iterations. This is what
flattens the area distortion that LSCM leaves on the larger islands the weld +
merge passes now produce.
* **planar**: orthographic projection onto the chart's best-fit plane. Always
succeeds; the only sane answer for closed charts with no boundary (LSCM
degenerate) and a very good one for near-flat charts.
For each chart we compute the viable candidates and keep whichever has the
lowest combined (angle + area) distortion with no flips.
"""
from __future__ import annotations
import numpy as np
from scipy.sparse import coo_matrix, csc_matrix
from scipy.sparse.linalg import spsolve, splu
# --------------------------------------------------------------------- helpers
def _chart_local(vertices, faces, face_ids):
"""Extract a chart as a compact (V',3) / (F',3) local mesh."""
f = faces[face_ids]
uniq, inv = np.unique(f.reshape(-1), return_inverse=True)
local_faces = inv.reshape(-1, 3)
local_verts = vertices[uniq]
return local_verts, local_faces, uniq
def _boundary_vertices(local_faces, n_verts):
"""Indices of vertices lying on the chart boundary (open edges)."""
e = np.concatenate([local_faces[:, [0, 1]],
local_faces[:, [1, 2]],
local_faces[:, [2, 0]]], axis=0)
es = np.sort(e, axis=1)
# an edge is on the boundary if it occurs exactly once
uniq, counts = np.unique(es, axis=0, return_counts=True)
bedges = uniq[counts == 1]
if len(bedges) == 0:
return np.array([], dtype=np.int64)
return np.unique(bedges.reshape(-1))
def _triangle_local_coords(p0, p1, p2):
"""Isometrically flatten one triangle into 2D local coordinates."""
e1 = p1 - p0
len1 = np.linalg.norm(e1)
if len1 < 1e-12:
return None
x_axis = e1 / len1
e2 = p2 - p0
proj = np.dot(e2, x_axis)
perp = e2 - proj * x_axis
h = np.linalg.norm(perp)
# (x,y) of the three corners
return np.array([[0.0, 0.0], [len1, 0.0], [proj, h]])
# ------------------------------------------------------------------------ LSCM
def lscm(local_verts, local_faces):
"""Solve LSCM. Returns (uv, ok)."""
n = len(local_verts)
bnd = _boundary_vertices(local_faces, n)
if len(bnd) < 2:
return None, False # closed chart -> degenerate for LSCM
# pin the two most distant boundary vertices
bpos = local_verts[bnd]
c = bpos.mean(axis=0)
far = bnd[np.argmax(np.linalg.norm(bpos - c, axis=1))]
far_pos = local_verts[far]
p1 = bnd[np.argmax(np.linalg.norm(local_verts[bnd] - far_pos, axis=1))]
p0 = far
if p0 == p1:
return None, False
rows, cols, vals = [], [], []
nt = len(local_faces)
for t, (i, j, k) in enumerate(local_faces):
loc = _triangle_local_coords(local_verts[i], local_verts[j],
local_verts[k])
if loc is None:
continue
(x0, y0), (x1, y1), (x2, y2) = loc
# W = opposite edge of each vertex, as a complex number a + i b
W = np.array([
(x2 - x1) + 1j * (y2 - y1),
(x0 - x2) + 1j * (y0 - y2),
(x1 - x0) + 1j * (y1 - y0),
])
area2 = abs((x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0))
w = 1.0 / np.sqrt(area2 + 1e-12)
idx = (i, j, k)
r_real = 2 * t
r_imag = 2 * t + 1
for vtx, Wv in zip(idx, W):
a, b = w * Wv.real, w * Wv.imag
# Real: a*u - b*v
rows += [r_real, r_real]
cols += [vtx, n + vtx]
vals += [a, -b]
# Imag: b*u + a*v
rows += [r_imag, r_imag]
cols += [vtx, n + vtx]
vals += [b, a]
M = coo_matrix((vals, (rows, cols)), shape=(2 * nt, 2 * n)).tocsc()
pinned = np.array([p0, n + p0, p1, n + p1])
pin_val = np.array([0.0, 0.0, 1.0, 0.0]) # p0->(0,0), p1->(1,0)
free = np.setdiff1d(np.arange(2 * n), pinned)
Mf = M[:, free]
Mp = M[:, pinned]
rhs = -Mp.dot(pin_val)
A = (Mf.T @ Mf).tocsc()
bvec = Mf.T @ rhs
try:
xf = spsolve(A, bvec)
except Exception:
return None, False
if not np.all(np.isfinite(xf)):
return None, False
x = np.zeros(2 * n)
x[free] = xf
x[pinned] = pin_val
uv = np.stack([x[:n], x[n:]], axis=1)
return uv, True
# ------------------------------------------------------------------- planar
def planar(local_verts, local_faces):
"""Project onto the area-weighted mean-normal plane.
Projecting along the surface normal guarantees no triangle flips as long as
every face normal stays within 90 degrees of the mean -- which is exactly
the invariant the bounded-cone segmentation maintains. In-plane axes are
aligned to the chart's principal direction for a tidy result.
"""
v = local_verts[local_faces]
fn = np.cross(v[:, 1] - v[:, 0], v[:, 2] - v[:, 0])
a = np.linalg.norm(fn, axis=1, keepdims=True)
n = (fn).sum(axis=0)
nn = np.linalg.norm(n)
if nn < 1e-12:
n = np.array([0.0, 0.0, 1.0])
else:
n = n / nn
# build an in-plane basis
ref = np.array([1.0, 0.0, 0.0]) if abs(n[0]) < 0.9 else np.array([0.0, 1.0, 0.0])
t1 = np.cross(n, ref)
t1 /= max(np.linalg.norm(t1), 1e-12)
t2 = np.cross(n, t1)
c = local_verts.mean(axis=0)
X = local_verts - c
uv = np.stack([X @ t1, X @ t2], axis=1)
return uv
# --------------------------------------------------------------------- ARAP
def _flatten_triangles(local_verts, local_faces):
"""Isometric 2D coords + corner cotangents for every triangle (vectorised).
Returns (P, cot, area) where P is (F,3,2) the isometrically flattened corners,
cot is (F,3) the cotangent of the angle at corner 0/1/2, and area is (F,).
"""
v = local_verts[local_faces] # (F,3,3)
e1 = v[:, 1] - v[:, 0]
e2 = v[:, 2] - v[:, 0]
len1 = np.linalg.norm(e1, axis=1)
len1 = np.where(len1 < 1e-12, 1e-12, len1)
x_axis = e1 / len1[:, None]
proj = np.einsum("ij,ij->i", e2, x_axis)
perp = e2 - proj[:, None] * x_axis
h = np.linalg.norm(perp, axis=1)
P = np.zeros((len(local_faces), 3, 2))
P[:, 1, 0] = len1
P[:, 2, 0] = proj
P[:, 2, 1] = h
area = 0.5 * len1 * h # = 0.5 * base * height
# cotangent of the angle at each corner, from the flattened coords
p0, p1, p2 = P[:, 0], P[:, 1], P[:, 2]
twoA = np.where(2.0 * area < 1e-12, 1e-12, 2.0 * area)
cot = np.empty((len(local_faces), 3))
cot[:, 0] = np.einsum("ij,ij->i", p1 - p0, p2 - p0) / twoA # angle at 0
cot[:, 1] = np.einsum("ij,ij->i", p0 - p1, p2 - p1) / twoA # angle at 1
cot[:, 2] = np.einsum("ij,ij->i", p0 - p2, p1 - p2) / twoA # angle at 2
return P, cot, area
def arap(local_verts, local_faces, uv_init, iters=4):
"""Refine an initial UV toward an as-rigid-as-possible map.
Local/global iteration: (local) fit the best rotation per triangle between
the flattened reference and the current UV; (global) re-solve vertex
positions for those rotations through a cotangent-Laplacian system whose
factorisation is reused across iterations. Returns (uv, ok).
"""
n = len(local_verts)
if n < 3 or len(local_faces) < 1:
return None, False
P, cot, area = _flatten_triangles(local_verts, local_faces)
# the three within-triangle edges (a,b) and the cotangent weighting each:
# edge (0,1) is opposite corner 2, etc.
E = [(0, 1, 2), (1, 2, 0), (2, 0, 1)]
ai = np.concatenate([local_faces[:, a] for a, _, _ in E])
bi = np.concatenate([local_faces[:, b] for _, b, _ in E])
w = np.concatenate([cot[:, c] for _, _, c in E]) # (3F,)
# reference edge vectors P[a]-P[b] for each edge (3F,2)
dP = np.concatenate([P[:, a] - P[:, b] for a, b, _ in E], axis=0)
# cotangent Laplacian A (constant across iterations) -------------------
rows = np.concatenate([ai, bi, ai, bi])
cols = np.concatenate([ai, bi, bi, ai])
data = np.concatenate([w, w, -w, -w])
A = coo_matrix((data, (rows, cols)), shape=(n, n)).tolil()
# pin vertex 0 to remove the translational null space
A[0, :] = 0.0
A[0, 0] = 1.0
try:
lu = splu(csc_matrix(A))
except Exception:
return None, False
nf = len(local_faces)
uv = uv_init.astype(np.float64).copy()
fa = local_faces # (F,3)
for _ in range(max(1, iters)):
# ---- local step: best rotation per triangle (batched 2x2 SVD) -----
# S_t = sum_edges w * du * dx^T (du = current uv diff, dx = ref diff)
du = np.concatenate([uv[fa[:, a]] - uv[fa[:, b]] for a, b, _ in E], axis=0)
we = w[:, None]
# accumulate per-triangle 2x2 covariance
S = np.zeros((nf, 2, 2))
contrib = (we * du)[:, :, None] * dP[:, None, :] # (3F,2,2)
for k in range(3):
S += contrib[k * nf:(k + 1) * nf]
U, _, Vt = np.linalg.svd(S)
R = np.matmul(U, Vt) # (F,2,2)
det = np.linalg.det(R)
flip = det < 0
if np.any(flip): # enforce proper rotation
U[flip, :, -1] *= -1.0
R = np.matmul(U, Vt)
# ---- global step: solve A uv = rhs --------------------------------
# rhs[a] += w * R_t dx ; rhs[b] -= w * R_t dx
Rt_per_edge = np.concatenate([R, R, R], axis=0) # (3F,2,2)
rot_dP = np.einsum("eij,ej->ei", Rt_per_edge, dP) * w[:, None]
rhs = np.zeros((n, 2))
np.add.at(rhs, ai, rot_dP)
np.add.at(rhs, bi, -rot_dP)
rhs[0] = uv_init[0] # match the pin
try:
uv = np.stack([lu.solve(rhs[:, 0]), lu.solve(rhs[:, 1])], axis=1)
except Exception:
return None, False
if not np.all(np.isfinite(uv)):
return None, False
return uv, True
# ------------------------------------------------------------- distortion
def distortion(local_verts, local_faces, uv):
"""Mean per-triangle (angle, area) distortion. Lower is better.
Angle distortion uses a *quasi-conformal* measure 0.5*(s0/s1 + s1/s0) from
the singular values of the per-triangle Jacobian, clamped so a few folded
triangles cannot send the average to infinity. A perfect conformal map
gives 1.0.
"""
eps = 1e-12
cap = 50.0
tot_w = 0.0
tot = 0.0
areas3, areas2 = [], []
for (i, j, k) in local_faces:
loc = _triangle_local_coords(local_verts[i], local_verts[j],
local_verts[k])
if loc is None:
continue
P = loc
Q = uv[[i, j, k]]
a3 = abs((P[1, 0] - P[0, 0]) * (P[2, 1] - P[0, 1]) -
(P[2, 0] - P[0, 0]) * (P[1, 1] - P[0, 1])) * 0.5
a2 = abs((Q[1, 0] - Q[0, 0]) * (Q[2, 1] - Q[0, 1]) -
(Q[2, 0] - Q[0, 0]) * (Q[1, 1] - Q[0, 1])) * 0.5
if a3 < eps:
continue
Pm = np.array([P[1] - P[0], P[2] - P[0]]).T
Qm = np.array([Q[1] - Q[0], Q[2] - Q[0]]).T
try:
J = Qm @ np.linalg.inv(Pm)
except np.linalg.LinAlgError:
continue
s = np.linalg.svd(J, compute_uv=False)
s = np.clip(s, eps, None)
qc = 0.5 * (s[0] / s[1] + s[1] / s[0]) # >= 1, =1 if conformal
qc = min(qc, cap)
tot += a3 * qc
tot_w += a3
areas3.append(a3)
areas2.append(a2)
if tot_w == 0:
return cap, cap
angle_d = tot / tot_w
areas3 = np.array(areas3)
areas2 = np.array(areas2)
if areas2.sum() > 0:
ratio = areas2 / areas3
ratio /= (ratio * areas3).sum() / areas3.sum()
area_d = float(np.sqrt(np.average((ratio - 1.0) ** 2, weights=areas3)))
else:
area_d = cap
return angle_d, area_d
def count_flips(local_faces, uv):
"""Number of triangles whose orientation flipped in UV space."""
signs = []
for (i, j, k) in local_faces:
Q = uv[[i, j, k]]
s = (Q[1, 0] - Q[0, 0]) * (Q[2, 1] - Q[0, 1]) - \
(Q[2, 0] - Q[0, 0]) * (Q[1, 1] - Q[0, 1])
signs.append(s)
signs = np.array(signs)
pos = np.sum(signs > 0)
neg = np.sum(signs < 0)
return int(min(pos, neg))
def parameterize_chart(vertices, faces, face_ids, method="auto", arap_iters=4):
"""Flatten one chart. Returns (local_uv, uniq_vertex_ids, local_faces, info)."""
lv, lf, uniq = _chart_local(vertices, faces, face_ids)
info = {"method": None, "angle_d": None, "area_d": None, "flips": 0}
candidates = []
lscm_uv = None
if method in ("auto", "lscm", "arap"):
uv, ok = lscm(lv, lf)
if ok:
# fix mirrored orientation if the whole chart came out flipped
if count_flips(lf, uv) > len(lf) // 2:
uv[:, 1] *= -1.0
lscm_uv = uv
if method in ("auto", "lscm"):
ad, ar = distortion(lv, lf, uv)
candidates.append(("lscm", uv, ad, ar, count_flips(lf, uv)))
if method in ("auto", "planar", "arap") or not candidates:
uv = planar(lv, lf)
ad, ar = distortion(lv, lf, uv)
candidates.append(("planar", uv, ad, ar, count_flips(lf, uv)))
# ARAP: refine the best available initialisation toward an isometric map.
# Conformal LSCM preserves angles but lets area (texel density) drift on the
# larger islands; ARAP pulls that back. Seed from LSCM when we have it, else
# from the planar projection.
if method in ("auto", "arap") and arap_iters > 0:
seed = lscm_uv if lscm_uv is not None else candidates[-1][1]
uv, ok = arap(lv, lf, seed, iters=arap_iters)
if ok:
if count_flips(lf, uv) > len(lf) // 2:
uv[:, 1] *= -1.0
ad, ar = distortion(lv, lf, uv)
candidates.append(("arap", uv, ad, ar, count_flips(lf, uv)))
# choose the candidate with fewest flips, then lowest combined distortion
def score(c):
_, _, ad, ar, fl = c
return (fl, ad + 2.0 * ar)
name, uv, ad, ar, fl = min(candidates, key=score)
info.update(method=name, angle_d=float(ad), area_d=float(ar), flips=int(fl))
return uv, uniq, lf, info

View file

@ -0,0 +1,60 @@
"""Per-chart post-processing: straighten and normalise texel density.
* PCA-align: rotate each island so its dominant axis is horizontal. Artists do
this by hand because axis-aligned, roughly-rectangular islands pack tighter
and make texture painting predictable.
* Texel density: scale every island by a single global factor so that
``uv_area / surface_area`` is identical across charts -- no island ends up
blurrier than its neighbours.
"""
from __future__ import annotations
import numpy as np
def align_island(uv):
"""Rotate UVs so the principal axis is horizontal; return rotated copy."""
c = uv.mean(axis=0)
X = uv - c
if len(X) < 2:
return uv.copy()
cov = X.T @ X
w, V = np.linalg.eigh(cov)
axis = V[:, np.argmax(w)] # principal direction
angle = np.arctan2(axis[1], axis[0])
ca, sa = np.cos(-angle), np.sin(-angle)
R = np.array([[ca, -sa], [sa, ca]])
out = X @ R.T
# keep islands "wide" (w >= h) for tidy shelf packing
w_ext = np.ptp(out[:, 0])
h_ext = np.ptp(out[:, 1])
if h_ext > w_ext:
out = out[:, ::-1].copy()
# move to positive quadrant
out -= out.min(axis=0)
return out
def uv_area(uv, faces):
"""True UV area = sum of triangle areas in parameter space."""
Q = uv[faces]
a = (Q[:, 1, 0] - Q[:, 0, 0]) * (Q[:, 2, 1] - Q[:, 0, 1]) - \
(Q[:, 2, 0] - Q[:, 0, 0]) * (Q[:, 1, 1] - Q[:, 0, 1])
return float(np.abs(a).sum() * 0.5)
def normalize_texel_density(islands, faces_list, areas3d):
"""Scale every island so uv_area / surface_area is the same constant.
The constant is irrelevant (packing rescales the whole atlas afterwards);
what matters is that the *ratio* is uniform, i.e. identical texel density.
"""
out = []
for uv, faces, a3 in zip(islands, faces_list, areas3d):
ua = uv_area(uv, faces)
# want uv_area_new / a3 == 1 -> scale^2 * ua / a3 == 1
s = np.sqrt(max(a3, 1e-12) / max(ua, 1e-12))
scaled = uv * s
scaled -= scaled.min(axis=0)
out.append(scaled)
return out

View file

@ -0,0 +1,75 @@
"""Render a packed UV atlas to a PNG, in the style of the reference images:
coloured islands with a thin wireframe, on a square canvas with the [0,1] border.
"""
from __future__ import annotations
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection, LineCollection
def _chart_colors(n):
rng = np.random.default_rng(7)
cols = []
for i in range(n):
h = (i * 0.61803398875) % 1.0
s = 0.45 + 0.2 * rng.random()
v = 0.80 + 0.15 * rng.random()
cols.append(_hsv(h, s, v))
return cols
def _hsv(h, s, v):
import colorsys
return colorsys.hsv_to_rgb(h, s, v)
def render_uv(result, path, size=860, show_stats=True):
uv = result.uv
faces = result.faces
fc = result.face_chart
n_charts = int(fc.max()) + 1
colors = _chart_colors(n_charts)
fig = plt.figure(figsize=(size / 100, size / 100), dpi=100)
ax = fig.add_axes([0, 0, 1, 1])
ax.set_xlim(-0.02, 1.02)
ax.set_ylim(-0.02, 1.02)
ax.set_aspect("equal")
ax.axis("off")
ax.set_facecolor("#3b3b3b")
fig.patch.set_facecolor("#3b3b3b")
# filled triangles coloured per chart
tri = uv[faces] # (F,3,2)
poly = PolyCollection(tri, facecolors=[colors[c] for c in fc],
edgecolors="none", alpha=0.85, linewidths=0)
ax.add_collection(poly)
# wireframe
segs = []
for t in tri:
segs += [[t[0], t[1]], [t[1], t[2]], [t[2], t[0]]]
lc = LineCollection(segs, colors="#101010", linewidths=0.35, alpha=0.7)
ax.add_collection(lc)
# unit-square border
ax.add_collection(LineCollection(
[[(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), (0, 1)], [(0, 1), (0, 0)]],
colors="#888888", linewidths=1.0))
if show_stats:
s = result.stats
txt = (f"charts: {s['n_charts']} faces: {s['n_faces']}\n"
f"fill: {s['fill_ratio']:.1%} flips: {s['flipped_triangles']}\n"
f"angle dist: {s['mean_angle_distortion']:.3f} "
f"area dist: {s['mean_area_distortion']:.3f}")
ax.text(0.015, 0.985, txt, va="top", ha="left", fontsize=9,
family="monospace", color="#f0f0f0",
bbox=dict(boxstyle="round,pad=0.4", fc="#000000aa", ec="none"))
fig.savefig(path, facecolor=fig.get_facecolor())
plt.close(fig)
return path

View file

@ -0,0 +1,338 @@
"""Chart segmentation.
The single most important stage for *beautiful* low-poly UVs. The goal is the
opposite of what xatlas does by default: produce **as few charts as possible**
while keeping each chart near-developable (low distortion) and placing seams on
natural creases.
Algorithm: greedy agglomerative region merging with an *exact* normal-cone
constraint.
* Start with one chart per face.
* Repeatedly merge the cheapest adjacent chart pair, where
cost = angle(meanNormalA, meanNormalB) + sharp_weight * sharpest_shared_edge
* A merge is only *allowed* if the merged chart's normal-cone half-angle stays
below ``max_cone`` (this is the quality dial: bigger cone -> fewer charts,
more distortion). Bounding the normal cone bounds the Gaussian curvature
inside the chart, which bounds the flattening distortion.
* Finally, slivers (charts with too few faces or too little area) are folded
into a neighbour that keeps the merged cone smallest, to eliminate the
few-triangle islands that plague bottom-up methods.
The normal cone half-angle is the **exact** maximum angle between the chart's
area-weighted mean normal and any member face normal -- *not* a cumulative
upper bound. An earlier version accumulated ``cone + angle(mean_shift)`` on
every merge; that triangle-inequality bound inflates without limit and rejects
legal merges, stranding hundreds of tiny charts. Here we keep a cheap upper
bound only as a fast-accept test and fall back to the exact cone (a single
vectorised dot product over the chart's faces) whenever the bound is close to
the cap.
"""
from __future__ import annotations
import heapq
import numpy as np
from .mesh import Mesh
class _Chart:
__slots__ = ("faces", "area", "nsum", "mean", "cone", "version", "alive")
def __init__(self, face, area, normal):
self.faces = [face]
self.area = float(area)
self.nsum = normal * area # area-weighted normal accumulator
self.mean = normal.copy() # unit mean normal
self.cone = 0.0 # EXACT half-angle of normal cone (rad)
self.version = 0
self.alive = True
def _angle(a, b):
return float(np.arccos(np.clip(np.dot(a, b), -1.0, 1.0)))
def segment(
mesh: Mesh,
max_cone_deg: float = 50.0,
sharp_weight: float = 0.35,
min_faces: int = 20,
min_area_frac: float = 0.004,
fold_cap_deg: float = 88.0,
) -> np.ndarray:
"""Return an int array of length ``n_faces`` giving a chart id per face."""
F = mesh.n_faces
normals = mesh.face_normals
areas = mesh.face_areas
adj = mesh.adjacency
adj_ang = mesh.adjacency_angle
max_cone = np.radians(max_cone_deg)
total_area = float(areas.sum())
min_area = min_area_frac * total_area
charts = {i: _Chart(i, areas[i], normals[i]) for i in range(F)}
face_chart = np.arange(F)
# adjacency between charts: chart_id -> {neighbour: sharpest shared edge ang}
nbr = [dict() for _ in range(F)]
for (fa, fb), ang in zip(adj, adj_ang):
ca, cb = int(fa), int(fb)
nbr[ca][cb] = max(nbr[ca].get(cb, 0.0), ang)
nbr[cb][ca] = max(nbr[cb].get(ca, 0.0), ang)
def merge_cost(a, b):
ca, cb = charts[a], charts[b]
sharp = nbr[a].get(b, 0.0)
return _angle(ca.mean, cb.mean) + sharp_weight * sharp
def exact_cone(faces, mean):
"""Exact normal-cone half-angle: max angle(mean, face_normal)."""
d = normals[faces] @ mean
return float(np.arccos(np.clip(d.min(), -1.0, 1.0)))
def try_merge(a, b):
"""Return (cone, mean, nsum, faces) if merge is legal, else None.
Uses a cheap cumulative upper bound as a fast accept; only computes the
exact cone when the bound is over the cap (the bound never under-states
the true cone, so bound <= cap guarantees exact <= cap).
"""
ca, cb = charts[a], charts[b]
nsum = ca.nsum + cb.nsum
n = np.linalg.norm(nsum)
if n < 1e-12: # opposing normals -> reject
return None
mean = nsum / n
bound = max(ca.cone + _angle(mean, ca.mean),
cb.cone + _angle(mean, cb.mean))
if bound <= max_cone:
faces = ca.faces + cb.faces
return bound, mean, nsum, faces # bound is a safe (slightly loose) cone
# bound exceeds cap: check the exact cone before rejecting
faces = ca.faces + cb.faces
cone = exact_cone(faces, mean)
if cone <= max_cone:
return cone, mean, nsum, faces
return None
# priority queue of (cost, a, b, va, vb)
heap = []
for a in range(F):
for b in nbr[a]:
if a < b:
heapq.heappush(heap, (merge_cost(a, b), a, b,
charts[a].version, charts[b].version))
def push_pair(a, b):
heapq.heappush(heap, (merge_cost(a, b), a, b,
charts[a].version, charts[b].version))
# -------------------------------------------------- main merge loop
while heap:
cost, a, b, va, vb = heapq.heappop(heap)
ca = charts.get(a)
cb = charts.get(b)
if ca is None or cb is None or not ca.alive or not cb.alive:
continue
if ca.version != va or cb.version != vb:
continue # stale entry
res = try_merge(a, b)
if res is None:
continue # would bend too much; leave the seam here
cone, mean, nsum, faces = res
# merge b into a
ca.faces = faces
for f in cb.faces:
face_chart[f] = a
ca.area += cb.area
ca.nsum = nsum
ca.mean = mean
# store the EXACT cone so future bounds stay tight
ca.cone = exact_cone(faces, mean)
ca.version += 1
cb.alive = False
# rewire neighbours of b onto a
for c, sharp in nbr[b].items():
if c == a:
continue
if charts[c].alive:
nbr[a][c] = max(nbr[a].get(c, 0.0), sharp)
nbr[c][a] = max(nbr[c].get(a, 0.0), sharp)
nbr[c].pop(b, None)
nbr[a].pop(b, None)
charts.pop(b, None)
for c in nbr[a]:
if charts[c].alive:
push_pair(a, c)
# -------------------------------------------------- sliver cleanup
# Collapse the long tail of tiny charts: a noisy organic mesh leaves many
# few-triangle slivers in crevices (typically a large *count* but a tiny
# fraction of the surface area). Fold every chart below ``min_faces`` /
# ``min_area`` into the neighbour that keeps the merged normal cone
# smallest, refusing only when even the best choice would fold the chart
# past flat (cone > ``fold_cap``), which would create UV overlaps. We
# iterate to a fixpoint so chains of slivers coalesce.
cleanup_cap = np.radians(fold_cap_deg)
def cone_if_merged(a, b):
ca, cb = charts[a], charts[b]
nsum = ca.nsum + cb.nsum
n = np.linalg.norm(nsum)
if n < 1e-12:
return np.pi, None, None
mean = nsum / n
cone = exact_cone(ca.faces + cb.faces, mean)
return cone, mean, nsum
changed = True
while changed:
changed = False
for cid in list(charts.keys()):
ch = charts.get(cid)
if ch is None or not ch.alive:
continue
if len(ch.faces) >= min_faces and ch.area >= min_area:
continue
cands = [c for c in nbr[cid] if charts.get(c) and charts[c].alive]
if not cands:
continue
scored = []
for c in cands:
cone, mean, nsum = cone_if_merged(cid, c)
if mean is None:
continue
scored.append((cone, merge_cost(cid, c), c, mean, nsum))
if not scored:
continue
scored.sort(key=lambda x: (x[0], x[1]))
cone, _, best, mean, nsum = scored[0]
if cone > cleanup_cap:
continue # leave this sliver alone rather than fold a chart
cb_, ca_ = charts[cid], charts[best]
ca_.faces = ca_.faces + cb_.faces
for f in cb_.faces:
face_chart[f] = best
ca_.area += cb_.area
ca_.nsum = nsum
ca_.mean = mean
ca_.cone = cone
ca_.version += 1
cb_.alive = False
for c, sharp in nbr[cid].items():
if c == best or not (charts.get(c) and charts[c].alive):
continue
nbr[best][c] = max(nbr[best].get(c, 0.0), sharp)
nbr[c][best] = max(nbr[c].get(best, 0.0), sharp)
nbr[c].pop(cid, None)
nbr[best].pop(cid, None)
charts.pop(cid, None)
changed = True
# -------------------------------------------------- relabel 0..K-1
_, labels = np.unique(face_chart, return_inverse=True)
return labels.astype(np.int64)
def refine_merge(
mesh: Mesh,
labels: np.ndarray,
target_faces: int = 80,
ad_thresh: float = 1.32,
min_packfill: float = 0.30,
union_cap: int = 4000,
max_passes: int = 6,
progress=None,
) -> np.ndarray:
"""Merge adjacent charts validated by the *actual* flattening.
The cone constraint in :func:`segment` is a conservative proxy: it bounds
distortion locally but, on a noisy organic mesh, leaves a long tail of small
charts that *could* in fact be flattened together without overlap. This
pass repeatedly tries to merge each small chart into a neighbour, accepting
the merge only when the union actually parameterises **flip-free** and below
a distortion threshold. It optimises the true objective (no UV overlaps, low
distortion, few charts) instead of the proxy, and is the main reason the
final atlas has a handful of large islands rather than hundreds of slivers.
``target_faces`` is the size below which a chart is considered "small" and
worth trying to absorb. Larger -> fewer, larger islands (slower).
"""
from . import param as _param # local import: param has no segment dep
V = mesh.vertices
Fc = mesh.faces
areas = mesh.face_areas
adj = mesh.adjacency
labels = labels.copy()
cache: dict[tuple, tuple] = {}
def quality(faces_tuple):
cached = cache.get(faces_tuple)
if cached is not None:
return cached
fid = np.asarray(faces_tuple, dtype=np.int64)
uv, _, lf, info = _param.parameterize_chart(V, Fc, fid)
# compactness = how much of the UV bounding box the island actually
# fills. Spindly / branchy islands (low pack-fill) waste atlas space and
# look ugly, so we track it and refuse merges that create them.
ext = uv.max(axis=0) - uv.min(axis=0)
bbox = float(ext[0] * ext[1])
e0 = uv[lf[:, 1]] - uv[lf[:, 0]]
e1 = uv[lf[:, 2]] - uv[lf[:, 0]]
uv_area = 0.5 * float(np.abs(e0[:, 0] * e1[:, 1] - e0[:, 1] * e1[:, 0]).sum())
packfill = uv_area / bbox if bbox > 1e-12 else 0.0
cache[faces_tuple] = (info["flips"], info["angle_d"], packfill)
return cache[faces_tuple]
for _pass in range(max_passes):
if progress is not None:
progress(_pass / max_passes)
chart_faces: dict[int, list] = {}
for f, l in enumerate(labels):
chart_faces.setdefault(int(l), []).append(f)
cadj: dict[int, set] = {c: set() for c in chart_faces}
for fa, fb in adj:
la, lb = int(labels[fa]), int(labels[fb])
if la != lb:
cadj[la].add(lb)
cadj[lb].add(la)
dead: set[int] = set()
merged = 0
# smallest charts first -- they are the slivers we most want gone
for c in sorted(chart_faces, key=lambda k: len(chart_faces[k])):
if c in dead or len(chart_faces[c]) >= target_faces:
continue
best = None
for nb in cadj[c]:
if nb in dead:
continue
union = chart_faces[c] + chart_faces[nb]
if len(union) > union_cap:
continue
fl, ad, pf = quality(tuple(sorted(union)))
if fl == 0 and ad < ad_thresh and pf >= min_packfill:
# prefer the neighbour that yields the most compact island
if best is None or pf > best[1]:
best = (nb, pf, union)
if best is not None:
nb, _, union = best
for f in chart_faces[nb]:
labels[f] = c
chart_faces[c] = union
cadj[c] |= cadj[nb]
cadj[c].discard(c)
dead.add(nb)
merged += 1
if merged == 0:
break
if progress is not None:
progress(1.0)
_, labels = np.unique(labels, return_inverse=True)
return labels.astype(np.int64)

View file

@ -0,0 +1,175 @@
"""End-to-end unwrap orchestrator."""
from __future__ import annotations
import time
from dataclasses import dataclass, field
import numpy as np
from .mesh import Mesh
from . import segment as _seg
from . import param as _param
from . import postprocess as _post
from . import pack as _pack
from . import weld as _weld
@dataclass
class UnwrapResult:
vertices: np.ndarray # (Vn,3) output positions (seam-duplicated)
faces: np.ndarray # (F,3) indices into vertices
uv: np.ndarray # (Vn,2) in [0,1]
face_chart: np.ndarray # (F,) chart id per face
stats: dict = field(default_factory=dict)
def unwrap(
mesh: Mesh,
max_cone_deg: float = 50.0,
sharp_weight: float = 0.35,
min_faces: int = 20,
min_area_frac: float = 0.004,
fold_cap_deg: float = 88.0,
refine: bool = True,
refine_target_faces: int = 80,
refine_ad_thresh: float = 1.32,
resolution: int = 1024,
padding_texels: int = 4,
method: str = "auto",
arap_iters: int = 4,
weld: bool = True,
weld_tol_frac: float = 0.1,
progress=None,
verbose: bool = True,
) -> UnwrapResult:
t0 = time.time()
def report(stage, frac):
if progress is not None:
progress(stage, float(frac))
# ---- topology repair: weld coincident-but-unshared vertices -------------
# The hard floor on chart count is the number of connected components, so a
# mesh shattered into hundreds of shells (AI/scan output) is forced to
# hundreds of charts regardless of how good the parameterisation is. Welding
# by true distance stitches those shells back into a few components; on
# already-clean meshes it is a no-op. See autouv.weld.
comps_before = int(len(np.unique(mesh.components)))
weld_info = None
report("weld", 0.0)
if weld:
nv, nf, weld_info = _weld.proximity_weld(
mesh.vertices, mesh.faces, tol_frac=weld_tol_frac
)
if weld_info["verts_after"] != weld_info["verts_before"]:
mesh = Mesh(nv, nf)
comps_after = int(len(np.unique(mesh.components)))
if verbose and weld:
print(f"[weld] {comps_before} -> {comps_after} components "
f"({weld_info['verts_before']}->{weld_info['verts_after']} verts, "
f"tol={weld_info['tol']:.5f})")
report("weld", 1.0)
labels = _seg.segment(
mesh,
max_cone_deg=max_cone_deg,
sharp_weight=sharp_weight,
min_faces=min_faces,
min_area_frac=min_area_frac,
fold_cap_deg=fold_cap_deg,
)
if verbose:
print(f"[segment] {int(labels.max()) + 1} charts in "
f"{time.time() - t0:.2f}s")
report("segment", 1.0)
if refine:
labels = _seg.refine_merge(
mesh, labels,
target_faces=refine_target_faces,
ad_thresh=refine_ad_thresh,
progress=lambda p: report("refine", p),
)
n_charts = int(labels.max()) + 1
t_seg = time.time()
if verbose and refine:
print(f"[refine] -> {n_charts} charts (total seg {t_seg - t0:.2f}s)")
faces = mesh.faces
verts = mesh.vertices
islands = [] # per-chart uv (local)
island_uniq = [] # per-chart global vertex ids
island_faces = [] # per-chart local faces
island_area3d = [] # per-chart surface area
angle_ds, area_ds, flips, methods = [], [], [], []
for c in range(n_charts):
fids = np.nonzero(labels == c)[0]
uv, uniq, lf, info = _param.parameterize_chart(
verts, faces, fids, method=method, arap_iters=arap_iters
)
report("parameterize", (c + 1) / n_charts)
uv = _post.align_island(uv)
islands.append(uv)
island_uniq.append(uniq)
island_faces.append(lf)
island_area3d.append(float(mesh.face_areas[fids].sum()))
angle_ds.append(info["angle_d"])
area_ds.append(info["area_d"])
flips.append(info["flips"])
methods.append(info["method"])
t_param = time.time()
if verbose:
print(f"[param] {n_charts} charts in {t_param - t_seg:.2f}s")
islands = _post.normalize_texel_density(islands, island_faces, island_area3d)
packed, fill = _pack.pack(
islands, resolution=resolution, padding_texels=padding_texels
)
t_pack = time.time()
if verbose:
print(f"[pack] fill={fill:.2%} in {t_pack - t_param:.2f}s")
# ---- assemble output mesh (duplicate vertices per chart for seam UVs) ----
out_v = []
out_uv = []
out_f = []
out_fc = []
voff = 0
for c in range(n_charts):
uniq = island_uniq[c]
lf = island_faces[c]
uv = packed[c]
out_v.append(verts[uniq])
out_uv.append(uv)
out_f.append(lf + voff)
out_fc.append(np.full(len(lf), c))
voff += len(uniq)
out_v = np.concatenate(out_v, axis=0)
out_uv = np.concatenate(out_uv, axis=0)
out_f = np.concatenate(out_f, axis=0)
out_fc = np.concatenate(out_fc, axis=0)
total_flips = int(np.sum(flips))
stats = {
"n_faces": int(mesh.n_faces),
"n_charts": n_charts,
"components_before_weld": comps_before,
"components_after_weld": comps_after,
"fill_ratio": float(fill),
"flipped_triangles": total_flips,
"mean_angle_distortion": float(np.average(
angle_ds, weights=island_area3d)),
"mean_area_distortion": float(np.average(
area_ds, weights=island_area3d)),
"method_counts": {m: int(methods.count(m)) for m in set(methods)},
"time_seconds": round(time.time() - t0, 3),
"time_breakdown": {
"segment": round(t_seg - t0, 3),
"parameterize": round(t_param - t_seg, 3),
"pack": round(t_pack - t_param, 3),
},
}
return UnwrapResult(out_v, out_f, out_uv, out_fc, stats)

View file

@ -0,0 +1,49 @@
"""Minimal example: unwrap a mesh from a plain Python script.
This is the other half of "one core, two front ends": the exact same
``autouv.unwrap`` that the web server calls, used directly.
python examples/unwrap_example.py path/to/mesh.glb
"""
import sys
import autouv
def main(path: str) -> None:
mesh = autouv.load(path)
print(f"{path}: {mesh.n_faces} faces")
result = autouv.unwrap(
mesh,
max_cone_deg=60, # curvature cap; higher -> fewer islands
refine_target_faces=120, # merge charts smaller than this when it helps
refine=True, # LSCM-validated merge (set False for speed)
padding_texels=1,
method='auto',
min_faces=50,
min_area_frac=0.1,
refine_ad_thresh=5.0
)
s = result.stats
print(
f"-> {s['n_charts']} islands, "
f"{s['flipped_triangles']} flipped triangles, "
f"angle distortion {s['mean_angle_distortion']:.3f}, "
f"atlas fill {s['fill_ratio'] * 100:.0f}%"
)
autouv.save_glb("unwrapped.glb", result.vertices, result.faces, result.uv)
autouv.render_uv(result, "uv_layout.png")
print("wrote unwrapped.glb and uv_layout.png")
# result.uv is an (n_vertices, 2) array in [0, 1]; result.vertices /
# result.faces are the (re-indexed, seam-split) geometry that matches it.
if __name__ == "__main__":
if len(sys.argv) != 2:
print("usage: python examples/unwrap_example.py <mesh.glb>")
raise SystemExit(2)
main(sys.argv[1])

View file

@ -0,0 +1,102 @@
"""Topological repair: proximity vertex welding.
The single biggest cause of "too many charts" is **not** the segmentation -- it
is the *input topology*. A chart grows along shared edges, so it can never span
two geometrically disconnected pieces. On clean meshes that is fine (a cave is
2-4 shells). But meshes from photogrammetry, sculpt-retopo and especially
AI generators (Tripo/Meshy/Rodin) are routinely shattered into hundreds of
shells whose seams are lined with vertices that are *coincident in space but
never welded* -- so the surface that should be one connected sheet is split
into 600-800 components, and the unwrapper is forced to emit one chart per
component no matter how good it is. (On the BabyRaptor sample: 810 components ->
810 charts; every component already collapses to exactly one chart.)
trimesh's default ``merge_vertices`` snaps coordinates to a grid, which misses
pairs straddling a grid boundary and leaves the shells split. This module welds
by *true distance* with a KD-tree + union-find, which reconnects the shells:
on BabyRaptor it takes 810 components -> 3 at a tolerance of one tenth of the
median edge length, while leaving genuinely-clean meshes untouched (Cave 4->4,
Church 2->2).
The tolerance is expressed as a fraction of the **median edge length** so it
scales with the model and is conservative: at 0.1x it only ever merges vertices
that are, for all practical purposes, the same point. Welding never deletes real
geometry -- only the degenerate faces whose corners collapse onto each other are
dropped (a handful, all zero-area).
"""
from __future__ import annotations
import numpy as np
from scipy.spatial import cKDTree
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components
def median_edge_length(vertices: np.ndarray, faces: np.ndarray) -> float:
v = vertices[faces]
e = np.concatenate([
np.linalg.norm(v[:, 1] - v[:, 0], axis=1),
np.linalg.norm(v[:, 2] - v[:, 1], axis=1),
np.linalg.norm(v[:, 0] - v[:, 2], axis=1),
])
e = e[e > 0]
return float(np.median(e)) if len(e) else 0.0
def proximity_weld(
vertices: np.ndarray,
faces: np.ndarray,
tol_frac: float = 0.1,
tol_abs: float | None = None,
):
"""Weld vertices closer than ``tol`` into one, by true distance.
``tol`` is ``tol_abs`` if given, else ``tol_frac * median_edge_length``.
Returns ``(new_vertices, new_faces, info)`` where ``info`` carries the vertex
and face counts before/after so the caller can report what was repaired.
Degenerate faces (two welded corners coincide) are removed.
"""
vertices = np.asarray(vertices, dtype=np.float64)
faces = np.asarray(faces, dtype=np.int64)
n = len(vertices)
info = {
"verts_before": n,
"faces_before": len(faces),
"verts_after": n,
"faces_after": len(faces),
"tol": 0.0,
}
tol = tol_abs if tol_abs is not None else tol_frac * median_edge_length(vertices, faces)
info["tol"] = float(tol)
if tol <= 0.0:
return vertices, faces, info
tree = cKDTree(vertices)
pairs = tree.query_pairs(tol, output_type="ndarray")
if len(pairs) == 0:
return vertices, faces, info
# union-find via connected components of the "within tol" graph
g = csr_matrix((np.ones(len(pairs)), (pairs[:, 0], pairs[:, 1])), shape=(n, n))
n_groups, label = connected_components(g + g.T, directed=False)
# representative position = centroid of each welded group
new_v = np.zeros((n_groups, 3))
count = np.zeros(n_groups)
np.add.at(new_v, label, vertices)
np.add.at(count, label, 1)
new_v /= count[:, None]
new_f = label[faces]
nondegen = (
(new_f[:, 0] != new_f[:, 1])
& (new_f[:, 1] != new_f[:, 2])
& (new_f[:, 0] != new_f[:, 2])
)
new_f = new_f[nondegen]
info["verts_after"] = int(n_groups)
info["faces_after"] = int(len(new_f))
return new_v, new_f, info

41
python-server/main.py Normal file
View file

@ -0,0 +1,41 @@
"""Entry point for the 3D Gen Studio mesh-processing service.
Run directly:
python main.py
or via uvicorn (auto-reload during development):
uvicorn main:app --reload --host 0.0.0.0 --port 8200
The Node backend (server.js) proxies browser requests here; see
buildMeshToolsBaseUrl() in server.js and Settings > Mesh Tools (Python) server.
"""
from __future__ import annotations
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app import config
from app.routes import health, meshes
app = FastAPI(
title="3D Gen Studio — Mesh Tools",
description="Python mesh-processing service (Auto UV, Auto Retopo, ...).",
version="0.1.0",
)
app.add_middleware(
CORSMiddleware,
allow_origins=config.ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["X-Vertex-Count", "X-Face-Count", "X-Has-Uv", "X-Stats"],
)
app.include_router(health.router)
app.include_router(meshes.router)
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host=config.HOST, port=config.PORT, reload=False)

View file

@ -0,0 +1,17 @@
# --- Web framework -----------------------------------------------------------
fastapi>=0.115
uvicorn[standard]>=0.30
python-multipart>=0.0.9 # required by FastAPI for multipart/form-data uploads
# --- Mesh I/O ----------------------------------------------------------------
trimesh>=4.4
numpy>=1.26
# --- autouv / autoretopo pipeline dependencies -------------------------------
scipy>=1.11 # sparse solvers (LSCM/ARAP), KD-trees, ndimage
scikit-image>=0.22 # marching cubes for the watertight voxel shell
pymeshlab>=2023.12 # isotropic remesh / decimation / quad conversion
# --- Optional ----------------------------------------------------------------
matplotlib>=3.8 # only needed for the CLI's UV-layout / compare PNGs
retree

20
python-server/run.bat Normal file
View file

@ -0,0 +1,20 @@
@echo off
:: Start the 3D Gen Studio Python mesh-processing service.
:: Creates a local virtual environment on first run, installs deps, then serves.
setlocal
cd /d "%~dp0"
if not exist ".venv\Scripts\python.exe" (
echo Creating virtual environment...
python -m venv .venv
call ".venv\Scripts\activate.bat"
python -m pip install --upgrade pip
pip install -r requirements.txt
) else (
call ".venv\Scripts\activate.bat"
)
:: Override host/port via env if needed, e.g. set MESHTOOLS_PORT=8200
python main.py
endlocal

View file

@ -843,6 +843,21 @@ function buildComfyUiBaseUrl(settings = {}) {
return parsedUrl.toString().replace(/\/$/, '');
}
function buildMeshToolsBaseUrl(settings = {}) {
const meshSettings = settings?.apis?.meshtools || {};
const rawUrl = String(meshSettings.url || 'http://127.0.0.1').trim();
const normalizedUrl = /^https?:\/\//i.test(rawUrl) ? rawUrl : `http://${rawUrl}`;
const parsedUrl = new URL(normalizedUrl);
const port = String(meshSettings.port || parsedUrl.port || '8200').trim();
parsedUrl.port = port;
parsedUrl.pathname = '';
parsedUrl.search = '';
parsedUrl.hash = '';
return parsedUrl.toString().replace(/\/$/, '');
}
function buildComfyUiWebSocketUrl(baseUrl, clientId) {
const parsedUrl = new URL(baseUrl);
const currentPath = parsedUrl.pathname && parsedUrl.pathname !== '/' ? parsedUrl.pathname.replace(/\/$/, '') : '';
@ -4960,6 +4975,80 @@ app.get('/api/filesystem/folders', async (req, res) => {
});
// Write exported mesh files (mesh + companions) into a user-chosen folder.
// --- Python mesh-tools proxy (Auto UV / Auto Retopo) -------------------------
// The browser uploads a mesh to one of these routes; Node forwards it to the
// configurable Python service (Settings > Mesh Tools) and relays the JSON
// envelope it returns ({ mesh_b64, stats, preview_b64 }). Mirrors how the
// ComfyUI integration proxies external compute.
const meshToolsUpload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 512 * 1024 * 1024 },
});
async function proxyMeshTool(operationPath, req, res) {
const meshFile = req.file;
if (!meshFile?.buffer?.length) {
return res.status(400).json({ error: 'meshFile is required' });
}
const settings = await getSettings();
const baseUrl = buildMeshToolsBaseUrl(settings);
const form = new FormData();
form.append(
'meshFile',
new Blob([meshFile.buffer], { type: meshFile.mimetype || 'model/gltf-binary' }),
meshFile.originalname || 'mesh.glb',
);
if (typeof req.body?.options === 'string' && req.body.options.length) {
form.append('options', req.body.options);
}
if (typeof req.body?.format === 'string' && req.body.format.length) {
form.append('format', req.body.format);
}
let upstream;
try {
upstream = await fetch(`${baseUrl}${operationPath}`, { method: 'POST', body: form });
} catch (err) {
console.error(`Mesh tool proxy (${operationPath}) could not reach the Python service:`, err);
return res.status(502).json({
error: `Could not reach the Mesh Tools (Python) service at ${baseUrl}. Is it running?`,
});
}
if (!upstream.ok) {
const detail = await upstream.text().catch(() => '');
return res.status(upstream.status).json({
error: `Mesh tool failed (${upstream.status})`,
detail: detail.slice(0, 2000),
});
}
// Relay the JSON envelope verbatim (mesh_b64 + stats + preview_b64).
const body = await upstream.text();
res.setHeader('Content-Type', upstream.headers.get('content-type') || 'application/json');
return res.status(200).send(body);
}
app.post('/api/meshes/auto-uv', meshToolsUpload.single('meshFile'), async (req, res) => {
try {
await proxyMeshTool('/meshes/auto-uv', req, res);
} catch (err) {
console.error('Auto UV proxy failed:', err);
if (!res.headersSent) res.status(500).json({ error: err.message || 'Auto UV failed' });
}
});
app.post('/api/meshes/auto-retopo', meshToolsUpload.single('meshFile'), async (req, res) => {
try {
await proxyMeshTool('/meshes/auto-retopo', req, res);
} catch (err) {
console.error('Auto Retopo proxy failed:', err);
if (!res.headersSent) res.status(500).json({ error: err.message || 'Auto Retopo failed' });
}
});
app.post('/api/export/mesh', multer({ storage: multer.memoryStorage(), limits: { fileSize: 512 * 1024 * 1024 } }).array('files'), async (req, res) => {
try {
const folder = typeof req.body?.folder === 'string' ? req.body.folder.trim() : '';

View file

@ -66,6 +66,12 @@ export default function SettingsModal({ onClose }) {
>
ComfyUI
</button>
<button
className={`settings-tab ${activeTab === 'meshtools' ? 'settings-tab--active' : ''}`}
onClick={() => setActiveTab('meshtools')}
>
Mesh Tools
</button>
</div>
{activeTab === 'apis' && (
@ -375,6 +381,65 @@ export default function SettingsModal({ onClose }) {
</div>
</section>
)}
{activeTab === 'meshtools' && (
<section className="settings-section">
<h3 className="settings-section-title font-label">Mesh Tools (Python) Connection</h3>
<div className="settings-api-card">
<div className="settings-api-header">
<div className="settings-api-icon">
<span className="material-symbols-outlined" style={{ fontSize: '18px' }}>deployed_code</span>
</div>
<span className="settings-api-name">Mesh Tools</span>
</div>
<div className="settings-grid settings-grid--triple">
<div className="settings-input-group">
<label className="settings-label">Url</label>
<input
className="settings-input"
placeholder="http://127.0.0.1"
value={localSettings?.apis?.meshtools?.url || ''}
onChange={e => setLocalSettings(prev => ({
...prev,
apis: {
...prev?.apis,
meshtools: {
...prev?.apis?.meshtools,
url: e.target.value
}
}
}))}
/>
</div>
<div className="settings-input-group">
<label className="settings-label">Port</label>
<input
className="settings-input"
placeholder="8200"
value={localSettings?.apis?.meshtools?.port || ''}
onChange={e => setLocalSettings(prev => ({
...prev,
apis: {
...prev?.apis,
meshtools: {
...prev?.apis?.meshtools,
port: e.target.value
}
}
}))}
/>
</div>
</div>
<p className="settings-helper-text">
The Python mesh-processing service (Auto UV, Auto Retopo). Start it from
python-server/run.bat. Can run on another machine or port.
</p>
</div>
</section>
)}
</div>
<div className="settings-footer">

View file

@ -0,0 +1,129 @@
// Auto Retopo mode left panel. Exposes every autoretopo.RetopoConfig field, runs
// the retopology via the Python mesh-tools service, and offers Keep/Revert on the
// result. Presentational: option state + handlers come from MeshEditorPage.
import { RangeField, NumberField, ToggleField } from './MeshToolField'
import MeshToolResult from './MeshToolResult'
export default function AutoRetopoToolsPanel({
options,
setOption,
running,
result,
onRun,
onKeepResult,
onRevertResult,
disabled,
}) {
const o = options
const fieldsDisabled = disabled || running
return (
<>{/* AUTO RETOPO */}
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Auto Retopo</span>
<button
type="button"
className="mesh-editor-btn mesh-editor-btn--primary"
onClick={onRun}
disabled={disabled || running}
title="Rebuild clean topology with the Python service"
>
<span className="material-symbols-outlined">{running ? 'progress_activity' : 'grain'}</span>
<span>{running ? 'Retopologizing…' : 'Run Auto Retopo'}</span>
</button>
{result && (
<MeshToolResult
title="Retopology applied"
rows={result.rows}
onKeep={onKeepResult}
onRevert={onRevertResult}
disabled={running}
/>
)}
</div>
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Target</span>
<NumberField label="Target faces" min={50} max={5000000} step={100}
value={o.target_faces} onChange={v => setOption('target_faces', v)} disabled={fieldsDisabled}
hint="Approximate face budget of the output" />
<ToggleField label="Quad-dominant" value={o.quads}
onChange={v => setOption('quads', v)} disabled={fieldsDisabled}
hint="Convert to quad-dominant (reported in metrics; GLB stays triangulated)" />
</div>
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Watertight shell</span>
<ToggleField label="Watertight shell" value={o.watertight}
onChange={v => setOption('watertight', v)} disabled={fieldsDisabled}
hint="Build a unified voxel shell (robust) vs. remesh the surface directly" />
<NumberField label="Shell resolution" min={16} max={1024} step={8}
value={o.shell_resolution} onChange={v => setOption('shell_resolution', v)}
disabled={fieldsDisabled || !o.watertight}
hint="Voxel grid cells along the longest bbox axis" />
<RangeField label="Close iterations" min={0} max={20} step={1}
value={o.shell_close_iter} onChange={v => setOption('shell_close_iter', v)}
disabled={fieldsDisabled || !o.watertight}
hint="Morphological closing to bridge cracks" />
<RangeField label="Smooth (sigma)" min={0} max={5} step={0.05} decimals={2}
value={o.shell_smooth} onChange={v => setOption('shell_smooth', v)}
disabled={fieldsDisabled || !o.watertight}
hint="Gaussian sigma on the occupancy field (lower = sharper)" />
<RangeField label="Samples / pitch" min={1} max={8} step={0.5} decimals={1}
value={o.shell_samples_per_pitch} onChange={v => setOption('shell_samples_per_pitch', v)}
disabled={fieldsDisabled || !o.watertight}
hint=">= 2 guarantees gap-free voxel coverage" />
<NumberField label="Max memory (GB)" min={0} max={128} step={0.5}
value={o.max_memory_gb} onChange={v => setOption('max_memory_gb', v)}
disabled={fieldsDisabled || !o.watertight}
hint="Auto-lower shell resolution to fit this budget (0 disables)" />
</div>
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Remesh</span>
<ToggleField label="Curvature-adaptive" value={o.adaptive}
onChange={v => setOption('adaptive', v)} disabled={fieldsDisabled}
hint="More faces where the surface bends" />
<NumberField label="Remesh iterations" min={1} max={100} step={1}
value={o.remesh_iters} onChange={v => setOption('remesh_iters', v)} disabled={fieldsDisabled} />
<RangeField label="Feature angle" suffix="°" min={0} max={180} step={1}
value={o.feature_deg} onChange={v => setOption('feature_deg', v)} disabled={fieldsDisabled}
hint="Crease angle preserved as a feature" />
<RangeField label="Calibrate passes" min={0} max={10} step={1}
value={o.calibrate_passes} onChange={v => setOption('calibrate_passes', v)} disabled={fieldsDisabled}
hint="Rough edge-length correction passes" />
</div>
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Silhouette projection</span>
<ToggleField label="Project to surface" value={o.project}
onChange={v => setOption('project', v)} disabled={fieldsDisabled}
hint="Project the remesh back onto the original surface" />
<NumberField label="Projection iterations" min={0} max={100} step={1}
value={o.project_iters} onChange={v => setOption('project_iters', v)}
disabled={fieldsDisabled || !o.project} />
<RangeField label="Move clamp" min={0} max={10} step={0.1} decimals={1}
value={o.project_clamp} onChange={v => setOption('project_clamp', v)}
disabled={fieldsDisabled || !o.project}
hint="Max per-vertex move as a multiple of local edge length" />
<RangeField label="Relax strength" min={0} max={1} step={0.05} decimals={2}
value={o.relax_strength} onChange={v => setOption('relax_strength', v)}
disabled={fieldsDisabled || !o.project}
hint="Tangential relaxation factor per iteration" />
</div>
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Misc</span>
<NumberField label="Seed" min={0} step={1}
value={o.seed} onChange={v => setOption('seed', v)} disabled={fieldsDisabled}
hint="RNG seed for reproducibility" />
</div>
<div className="mesh-editor-panel__notes">
<span className="mesh-editor-panel__hint">Auto Retopo runs on the Python mesh-tools service (Settings → Mesh Tools).</span>
<span className="mesh-editor-panel__hint">The result replaces the mesh; use Keep or Revert to decide.</span>
</div>
</>
)
}

View file

@ -0,0 +1,122 @@
// Auto UV mode left panel. Exposes every autouv.unwrap() parameter, runs the
// unwrap via the Python mesh-tools service, and offers Keep/Revert on the result.
// Presentational: option state + handlers come from MeshEditorPage.
import { RangeField, NumberField, ToggleField, SelectField } from './MeshToolField'
import MeshToolResult from './MeshToolResult'
export default function AutoUvToolsPanel({
options,
setOption,
running,
result,
onRun,
onKeepResult,
onRevertResult,
disabled,
}) {
const o = options
const fieldsDisabled = disabled || running
return (
<>{/* AUTO UV */}
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Auto UV</span>
<button
type="button"
className="mesh-editor-btn mesh-editor-btn--primary"
onClick={onRun}
disabled={disabled || running}
title="Unwrap UVs with the Python service"
>
<span className="material-symbols-outlined">{running ? 'progress_activity' : 'auto_awesome'}</span>
<span>{running ? 'Unwrapping…' : 'Run Auto UV'}</span>
</button>
{result && (
<MeshToolResult
title="UV unwrap applied"
rows={result.rows}
previewUrl={result.previewUrl}
previewAlt="UV layout"
onKeep={onKeepResult}
onRevert={onRevertResult}
disabled={running}
/>
)}
</div>
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Segmentation</span>
<RangeField label="Normal-cone cap" suffix="°" min={1} max={180} step={1}
value={o.max_cone_deg} onChange={v => setOption('max_cone_deg', v)} disabled={fieldsDisabled}
hint="Higher = fewer, more distorted charts" />
<RangeField label="Sharp-edge weight" min={0} max={1} step={0.01} decimals={2}
value={o.sharp_weight} onChange={v => setOption('sharp_weight', v)} disabled={fieldsDisabled}
hint="How strongly sharp edges attract seams" />
<RangeField label="Fold cap" suffix="°" min={1} max={180} step={1}
value={o.fold_cap_deg} onChange={v => setOption('fold_cap_deg', v)} disabled={fieldsDisabled}
hint="Dihedral fold angle that forces a seam" />
<NumberField label="Min faces / chart" min={1} step={1}
value={o.min_faces} onChange={v => setOption('min_faces', v)} disabled={fieldsDisabled}
hint="Charts smaller than this are dissolved into neighbours" />
<NumberField label="Min area fraction" min={0} max={1} step={0.001}
value={o.min_area_frac} onChange={v => setOption('min_area_frac', v)} disabled={fieldsDisabled}
hint="Min chart area as a fraction of total surface area" />
</div>
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Refinement</span>
<ToggleField label="Validated merge pass" value={o.refine}
onChange={v => setOption('refine', v)} disabled={fieldsDisabled}
hint="LSCM-validated chart merge (off = faster, more charts)" />
<NumberField label="Merge below faces" min={1} step={1}
value={o.refine_target_faces} onChange={v => setOption('refine_target_faces', v)}
disabled={fieldsDisabled || !o.refine}
hint="Charts below this face count are merge candidates" />
<RangeField label="Merge distortion cap" min={1} max={10} step={0.01} decimals={2}
value={o.refine_ad_thresh} onChange={v => setOption('refine_ad_thresh', v)}
disabled={fieldsDisabled || !o.refine}
hint="Max angle-distortion ratio a merge may introduce" />
</div>
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Parameterization</span>
<SelectField label="Method" value={o.method} onChange={v => setOption('method', v)} disabled={fieldsDisabled}
options={[
{ value: 'auto', label: 'Auto' },
{ value: 'lscm', label: 'LSCM' },
{ value: 'arap', label: 'ARAP' },
{ value: 'planar', label: 'Planar' },
]} />
<RangeField label="ARAP iterations" min={0} max={100} step={1}
value={o.arap_iters} onChange={v => setOption('arap_iters', v)} disabled={fieldsDisabled}
hint="0 disables ARAP (LSCM/planar only)" />
</div>
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Packing</span>
<SelectField label="Atlas resolution" value={String(o.resolution)}
onChange={v => setOption('resolution', Number(v))} disabled={fieldsDisabled}
options={[256, 512, 1024, 2048, 4096, 8192].map(n => ({ value: String(n), label: `${n} px` }))} />
<RangeField label="Padding" suffix=" texels" min={0} max={64} step={1}
value={o.padding_texels} onChange={v => setOption('padding_texels', v)} disabled={fieldsDisabled} />
</div>
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Topology repair</span>
<ToggleField label="Proximity weld" value={o.weld}
onChange={v => setOption('weld', v)} disabled={fieldsDisabled}
hint="Weld coincident verts before unwrapping (stitches shattered shells)" />
<RangeField label="Weld tolerance" min={0} max={1} step={0.01} decimals={2}
value={o.weld_tol_frac} onChange={v => setOption('weld_tol_frac', v)}
disabled={fieldsDisabled || !o.weld}
hint="As a fraction of median edge length" />
</div>
<div className="mesh-editor-panel__notes">
<span className="mesh-editor-panel__hint">Auto UV runs on the Python mesh-tools service (Settings → Mesh Tools).</span>
<span className="mesh-editor-panel__hint">The result replaces the mesh; use Keep or Revert to decide.</span>
</div>
</>
)
}

View file

@ -0,0 +1,74 @@
// Reusable labeled controls for the Auto UV / Auto Retopo parameter panels.
// Presentational only — value + onChange come from the parent.
export function RangeField({ label, hint, value, min, max, step, suffix = '', decimals = null, onChange, disabled }) {
const shown = decimals != null ? Number(value).toFixed(decimals) : value
return (
<label className="mesh-editor-range-field" title={hint || label}>
<span>{label}</span>
<input
type="range"
min={min}
max={max}
step={step}
value={value}
onChange={event => onChange(Number(event.target.value))}
disabled={disabled}
/>
<strong>{shown}{suffix}</strong>
</label>
)
}
export function NumberField({ label, hint, value, min, max, step = 1, onChange, disabled }) {
return (
<div className="mesh-editor-workflow-field" title={hint || label}>
<span>{label}</span>
<input
className="mesh-editor-panel__input"
type="number"
min={min}
max={max}
step={step}
value={value}
onChange={event => {
const next = event.target.value === '' ? '' : Number(event.target.value)
onChange(next)
}}
disabled={disabled}
/>
</div>
)
}
export function ToggleField({ label, hint, value, onChange, disabled }) {
return (
<label className="mesh-editor-workflow-field mesh-editor-workflow-field--checkbox" title={hint || label}>
<input
type="checkbox"
checked={value}
onChange={event => onChange(event.target.checked)}
disabled={disabled}
/>
<span>{label}</span>
</label>
)
}
export function SelectField({ label, hint, value, options, onChange, disabled }) {
return (
<div className="mesh-editor-workflow-field" title={hint || label}>
<span>{label}</span>
<select
className="mesh-editor-panel__input mesh-editor-panel__select"
value={value}
onChange={event => onChange(event.target.value)}
disabled={disabled}
>
{options.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
</div>
)
}

View file

@ -0,0 +1,50 @@
// Result + rollback banner shown after an Auto UV / Auto Retopo run.
// Reuses the existing patch-preview styling. `rows` is [{ label, value }].
export default function MeshToolResult({ title, rows = [], previewUrl, previewAlt = 'Preview', onKeep, onRevert, disabled }) {
return (
<div className="mesh-editor-patch-preview">
<strong className="mesh-editor-patch-preview__title">
<span className="material-symbols-outlined">check_circle</span>
{title}
</strong>
{previewUrl && (
<img
src={previewUrl}
alt={previewAlt}
className="mesh-editor-tool-preview"
style={{ width: '100%', borderRadius: 'var(--radius-md)', display: 'block' }}
/>
)}
<div className="mesh-editor-texture-workflow-meta">
{rows.map(row => (
<span key={row.label}><strong>{row.label}:</strong> {row.value}</span>
))}
</div>
<div className="mesh-editor-icon-grid mesh-editor-icon-grid--double mesh-editor-patch-preview__actions">
<button
type="button"
className="mesh-editor-btn mesh-editor-btn--primary"
onClick={onKeep}
disabled={disabled}
title="Keep this result"
>
<span className="material-symbols-outlined">check</span>
<span>Keep</span>
</button>
<button
type="button"
className="mesh-editor-btn mesh-editor-btn--ghost"
onClick={onRevert}
disabled={disabled}
title="Revert to the mesh before this operation"
>
<span className="material-symbols-outlined">undo</span>
<span>Revert</span>
</button>
</div>
</div>
)
}

View file

@ -22,6 +22,7 @@ import {
getGeometryHoleLoops,
getSelectedHoleLoops,
loadEditableGeometryFromObject,
loadEditableGeometryFromGlbBuffer,
mergeSelectedVertices,
smoothSelectedVertices,
subdivideSelectedFaces
@ -143,6 +144,49 @@ import TexturingToolsPanel from '../components/meshEditor/TexturingToolsPanel'
import ProjectionToolsPanel from '../components/meshEditor/ProjectionToolsPanel'
import { saveWorkflowDefaults } from '../utils/workflowDefaults'
import PaintingToolsPanel from '../components/meshEditor/PaintingToolsPanel'
import AutoUvToolsPanel from '../components/meshEditor/AutoUvToolsPanel'
import AutoRetopoToolsPanel from '../components/meshEditor/AutoRetopoToolsPanel'
import { autoUv as runAutoUvService, autoRetopo as runAutoRetopoService } from '../utils/meshTools'
// Default option sets for the Python mesh-tools panels. These mirror the
// defaults of autouv.unwrap() and autoretopo.RetopoConfig 1:1 (see
// python-server/app/schemas.py).
const DEFAULT_AUTO_UV_OPTIONS = {
max_cone_deg: 50,
sharp_weight: 0.35,
min_faces: 20,
min_area_frac: 0.004,
fold_cap_deg: 88,
refine: true,
refine_target_faces: 80,
refine_ad_thresh: 1.32,
method: 'auto',
arap_iters: 4,
resolution: 1024,
padding_texels: 4,
weld: true,
weld_tol_frac: 0.1,
}
const DEFAULT_AUTO_RETOPO_OPTIONS = {
target_faces: 6000,
quads: false,
watertight: true,
shell_resolution: 256,
shell_close_iter: 1,
shell_smooth: 0.6,
shell_samples_per_pitch: 2,
max_memory_gb: 4,
adaptive: true,
remesh_iters: 10,
feature_deg: 30,
calibrate_passes: 1,
project: true,
project_iters: 10,
project_clamp: 1.5,
relax_strength: 0.4,
seed: 0,
}
// ── Projection per-layer mask helpers ───────────────────────────────────────
// A projection layer can carry a user-drawn UV-space mask so the layer's view is
@ -316,6 +360,9 @@ export default function MeshEditorPage() {
const [geometry, setGeometry] = useState(null)
const [texturableMesh, setTexturableMesh] = useState(null)
const [textureRevision, setTextureRevision] = useState(0)
// Resolution used when a UV-only mesh (no baked texture) starts from a blank
// texture, so painting/texturing/projection can be enabled.
const [blankTextureSize, setBlankTextureSize] = useState(1024)
const [contextRevision, setContextRevision] = useState(0)
const [comfyLoading, setComfyLoading] = useState(false)
const [comfyWorkflows, setComfyWorkflows] = useState([])
@ -345,6 +392,13 @@ export default function MeshEditorPage() {
const [modelingCanRedo, setModelingCanRedo] = useState(false)
const modelingUndoStackRef = useRef([])
const modelingRedoStackRef = useRef([])
// Auto UV / Auto Retopo (Python mesh-tools service)
const [autoUvOptions, setAutoUvOptions] = useState(DEFAULT_AUTO_UV_OPTIONS)
const [autoRetopoOptions, setAutoRetopoOptions] = useState(DEFAULT_AUTO_RETOPO_OPTIONS)
const [autoUvRunning, setAutoUvRunning] = useState(false)
const [autoRetopoRunning, setAutoRetopoRunning] = useState(false)
const [autoUvResult, setAutoUvResult] = useState(null)
const [autoRetopoResult, setAutoRetopoResult] = useState(null)
const [booleanOperation, setBooleanOperation] = useState('out')
const [booleanPlaceMode, setBooleanPlaceMode] = useState(false)
const [booleanBrushSource, setBooleanBrushSource] = useState('asset')
@ -1760,7 +1814,7 @@ export default function MeshEditorPage() {
return loadedGeometry
})
const texturableMeshPromise = loadTexturableMeshFromRoot(loadedRoot, { url: modelUrl, startedAt: texturableStartedAt })
const texturableMeshPromise = loadTexturableMeshFromRoot(loadedRoot, { url: modelUrl, startedAt: texturableStartedAt, blankTextureSize })
.then(loadedTexturableMesh => {
return loadedTexturableMesh
})
@ -3657,6 +3711,130 @@ export default function MeshEditorPage() {
setFeedback('Redo.')
}, [geometry])
// Rebuild the texturable-mesh state from a (possibly UV-only) geometry, so the
// painting/texturing/projection modes stay in sync after a topology change.
// A UV-only mesh yields a blank-texture texturable (loadTexturableMeshFromRoot);
// a UV-less one yields a supportError that correctly disables those modes.
const buildTexturableFromGeometry = useCallback(async (geom, size) => {
if (!geom) return null
const root = new THREE.Mesh(
geom.clone(),
new THREE.MeshStandardMaterial({ color: '#cfd8ff', metalness: 0.08, roughness: 0.62 })
)
root.name = 'MeshEditorResult'
const loaded = await loadTexturableMeshFromRoot(root, { url: modelUrl, blankTextureSize: size })
if (loaded?.textureCanvas) {
return {
...loaded,
maskCanvas: Object.assign(document.createElement('canvas'), {
width: loaded.textureCanvas.width,
height: loaded.textureCanvas.height,
}),
}
}
return loaded
}, [modelUrl])
const handleBlankTextureSizeChange = useCallback(async (size) => {
setBlankTextureSize(size)
if (texturableMesh?.isBlank && geometry) {
const next = await buildTexturableFromGeometry(geometry, size)
setTexturableMesh(next)
setTextureRevision(0)
setPaintLayers([])
setSelectedLayerId(null)
}
}, [texturableMesh, geometry, buildTexturableFromGeometry])
// ── Auto UV / Auto Retopo (Python mesh-tools service) ────────────────────
// Both run the same round-trip: export the current geometry to GLB, POST it
// to the Node proxy (which forwards to the Python service), then load the
// returned GLB back as editable geometry. applyGeometryUpdate pushes the
// pre-op mesh onto the modeling undo stack, so "Revert" is just an undo.
// After applying, the texturable-mesh state is rebuilt so the new UVs (Auto
// UV) immediately enable painting/texturing/projection.
const runMeshTool = useCallback(async (service, options, { setRunning, setResult, buildRows, label }) => {
if (!geometry || autoUvRunning || autoRetopoRunning) {
return
}
setRunning(true)
setResult(null)
setError('')
setFeedback(`${label}…`)
try {
const glbBuffer = await exportGeometryToGlb(geometry)
const meshBlob = new Blob([glbBuffer], { type: 'model/gltf-binary' })
const { blob, stats, previewUrl } = await service(meshBlob, { options, fileName: 'mesh.glb' })
const resultBuffer = await blob.arrayBuffer()
const nextGeometry = await loadEditableGeometryFromGlbBuffer(resultBuffer)
applyGeometryUpdate(nextGeometry, [], { pushUndo: true })
// Resync texture editing to the new topology/UVs (enables the texture
// modes when the result carries UVs, disables them otherwise).
const nextTexturable = await buildTexturableFromGeometry(nextGeometry, blankTextureSize)
setTexturableMesh(nextTexturable)
setTextureRevision(0)
setPaintLayers([])
setSelectedLayerId(null)
setResult({ rows: buildRows(stats), previewUrl })
setFeedback(`${label} complete.`)
} catch (err) {
console.error(`${label} failed:`, err)
setError(err?.message || `${label} failed.`)
} finally {
setRunning(false)
}
}, [geometry, autoUvRunning, autoRetopoRunning, applyGeometryUpdate, buildTexturableFromGeometry, blankTextureSize])
const handleRunAutoUv = useCallback(() => {
runMeshTool(runAutoUvService, autoUvOptions, {
setRunning: setAutoUvRunning,
setResult: setAutoUvResult,
label: 'Auto UV',
buildRows: stats => {
const t = stats?.tool || {}
const rows = []
if (t.n_charts != null) rows.push({ label: 'UV islands', value: t.n_charts })
if (t.fill_ratio != null) rows.push({ label: 'Atlas fill', value: `${(t.fill_ratio * 100).toFixed(0)}%` })
if (t.flipped_triangles != null) rows.push({ label: 'Flipped tris', value: t.flipped_triangles })
if (t.mean_angle_distortion != null) rows.push({ label: 'Angle distortion', value: t.mean_angle_distortion.toFixed(3) })
return rows
},
})
}, [runMeshTool, autoUvOptions])
const handleRunAutoRetopo = useCallback(() => {
runMeshTool(runAutoRetopoService, autoRetopoOptions, {
setRunning: setAutoRetopoRunning,
setResult: setAutoRetopoResult,
label: 'Auto Retopo',
buildRows: stats => {
const m = stats?.tool?.metrics || {}
const rows = [
{ label: 'Vertices', value: stats?.vertexCount ?? '—' },
{ label: 'Faces', value: stats?.faceCount ?? '—' },
]
const haus = m?.fidelity?.hausdorff_pct_diag
if (haus != null) rows.push({ label: 'Hausdorff', value: `${haus.toFixed(2)}% diag` })
const wellShaped = m?.triangle_quality?.pct_well_shaped
if (wellShaped != null) rows.push({ label: 'Well-shaped tris', value: `${wellShaped.toFixed(0)}%` })
if (stats?.tool?.quad_face_count != null) rows.push({ label: 'Quad faces', value: stats.tool.quad_face_count })
return rows
},
})
}, [runMeshTool, autoRetopoOptions])
const setAutoUvOption = useCallback((key, value) => {
setAutoUvOptions(prev => ({ ...prev, [key]: value }))
}, [])
const setAutoRetopoOption = useCallback((key, value) => {
setAutoRetopoOptions(prev => ({ ...prev, [key]: value }))
}, [])
const handleRevertMeshTool = useCallback((clearResult) => {
handleModelingUndo()
clearResult(null)
}, [handleModelingUndo])
// Keyboard shortcuts within modeling mode: Ctrl/Cmd+Z = undo,
// Ctrl/Cmd+Shift+Z and Ctrl+Y = redo.
useEffect(() => {
@ -5654,8 +5832,48 @@ export default function MeshEditorPage() {
<span className="material-symbols-outlined">back_hand</span>
<span>Sculpting</span>
</button>
<button
type="button"
className={`mesh-editor-mode-btn ${activeMenu === 'autouv' ? 'mesh-editor-mode-btn--active' : ''}`}
onClick={() => setActiveMenu('autouv')}
title="Automatic UV unwrapping (Python service)"
>
<span className="material-symbols-outlined">dashboard_customize</span>
<span>Auto UV</span>
</button>
<button
type="button"
className={`mesh-editor-mode-btn ${activeMenu === 'autoretopo' ? 'mesh-editor-mode-btn--active' : ''}`}
onClick={() => setActiveMenu('autoretopo')}
title="Automatic retopology (Python service)"
>
<span className="material-symbols-outlined">grid_4x4</span>
<span>Auto Retopo</span>
</button>
</div>
{texturableMesh?.isBlank && (
<div className="mesh-editor-panel__section">
<span className="mesh-editor-panel__section-title">Base texture</span>
<div className="mesh-editor-workflow-field">
<span>Resolution</span>
<select
className="mesh-editor-panel__input mesh-editor-panel__select"
value={String(blankTextureSize)}
onChange={event => handleBlankTextureSizeChange(Number(event.target.value))}
>
{[512, 1024, 2048, 4096].map(n => (
<option key={n} value={String(n)}>{n} × {n}</option>
))}
</select>
</div>
<span className="mesh-editor-panel__hint">
This mesh has UVs but no texture yet — painting/texturing/projection
start from a blank {blankTextureSize}×{blankTextureSize} canvas.
</span>
</div>
)}
{activeMenu === 'modeling' ? (
<ModelingToolsPanel {...{
selectionMode, setSelectionMode, resetSelection,
@ -5704,6 +5922,24 @@ export default function MeshEditorPage() {
projectionWorkflowInputs, setProjectionWorkflowInputs,
projectionSetAsDefault, setProjectionSetAsDefault
}} />
) : activeMenu === 'autouv' ? (
<AutoUvToolsPanel {...{
options: autoUvOptions, setOption: setAutoUvOption,
running: autoUvRunning, result: autoUvResult,
onRun: handleRunAutoUv,
onKeepResult: () => setAutoUvResult(null),
onRevertResult: () => handleRevertMeshTool(setAutoUvResult),
disabled: !geometry
}} />
) : activeMenu === 'autoretopo' ? (
<AutoRetopoToolsPanel {...{
options: autoRetopoOptions, setOption: setAutoRetopoOption,
running: autoRetopoRunning, result: autoRetopoResult,
onRun: handleRunAutoRetopo,
onKeepResult: () => setAutoRetopoResult(null),
onRevertResult: () => handleRevertMeshTool(setAutoRetopoResult),
disabled: !geometry
}} />
) : activeMenu === 'sculpting' ? (
<>{/* SCULPTING */}
<SculptToolsPanel

View file

@ -263,6 +263,36 @@ export function loadEditableGeometryFromObject(object) {
return createIndexedGeometry(positions, indices, uvs)
}
// Parse an in-memory GLB (ArrayBuffer) into an editable BufferGeometry without
// going through a URL. Used for results returned by the Python mesh-tools
// service (Auto UV / Auto Retopo), which arrive as binary blobs with no
// file extension for the URL-based loaders to key off.
export function loadEditableGeometryFromGlbBuffer(arrayBuffer) {
return new Promise((resolve, reject) => {
try {
new GLTFLoader().parse(
arrayBuffer,
'',
gltf => {
const scene = gltf?.scene || (Array.isArray(gltf?.scenes) ? gltf.scenes[0] : null)
if (!scene) {
reject(new Error('The returned mesh did not contain a scene.'))
return
}
try {
resolve(loadEditableGeometryFromObject(scene))
} catch (err) {
reject(err instanceof Error ? err : new Error('Failed to read the returned mesh geometry.'))
}
},
error => reject(error instanceof Error ? error : new Error('Failed to parse the returned GLB mesh.')),
)
} catch (error) {
reject(error instanceof Error ? error : new Error('Failed to parse the returned GLB mesh.'))
}
})
}
async function loadGeometryFromUrl(url) {
const extension = getExtensionFromUrl(url)

View file

@ -615,7 +615,7 @@ export async function loadTexturableMeshFromUrl(url) {
return loadTexturableMeshFromRoot(root, { url, startedAt })
}
export async function loadTexturableMeshFromRoot(root, { url = '', startedAt: explicitStartedAt = null } = {}) {
export async function loadTexturableMeshFromRoot(root, { url = '', startedAt: explicitStartedAt = null, blankTextureSize = 1024 } = {}) {
const startedAt = explicitStartedAt ?? (typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now())
if (!root) {
@ -654,12 +654,64 @@ export async function loadTexturableMeshFromRoot(root, { url = '', startedAt: ex
}
if (texturedMaterials.length === 0) {
// The mesh has UVs but no baked texture map yet (e.g. fresh from Auto UV, or
// a UV-only GLB). Painting onto a blank texture is perfectly valid, so start
// from a clean white canvas at the requested resolution instead of refusing.
const size = Math.max(64, Math.round(blankTextureSize) || 1024)
const textureCanvas = document.createElement('canvas')
textureCanvas.width = size
textureCanvas.height = size
const ctx = textureCanvas.getContext('2d')
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, size, size)
// glTF convention (matches GLTFLoader-loaded textures): flipY = false.
const textureConfig = {
wrapS: THREE.ClampToEdgeWrapping,
wrapT: THREE.ClampToEdgeWrapping,
repeat: new THREE.Vector2(1, 1),
offset: new THREE.Vector2(0, 0),
center: new THREE.Vector2(0, 0),
rotation: 0,
flipY: false,
colorSpace: THREE.SRGBColorSpace,
minFilter: THREE.LinearMipmapLinearFilter,
magFilter: THREE.LinearFilter
}
// The display pipeline (TexturedMesh) only binds the live painted texture to
// materials whose map key matches `textureKey`. A UV-only mesh has no map, so
// we attach this blank texture as the materials' map and derive the key from
// it — otherwise painting/projection would update the canvas but never show.
const placeholderTexture = createCanvasTexture(textureCanvas, textureConfig)
const textureKey = getTextureKey(placeholderTexture)
const paintTargetsByMeshUuid = {}
root.traverse(child => {
if (!child.isMesh || !child.geometry?.attributes?.uv?.count) {
return
}
getMaterialList(child.material).forEach(material => {
if (material) {
material.map = placeholderTexture
material.needsUpdate = true
}
})
const paintTarget = buildUvPaintTarget(child.geometry, size, size, textureConfig)
if (paintTarget) {
paintTargetsByMeshUuid[child.uuid] = paintTarget
}
})
return {
root,
textureCanvas: null,
textureKey: '',
textureConfig: null,
supportError: 'This mesh has no texture map to edit.'
textureCanvas,
textureKey,
isBlank: true,
blankTextureSize: size,
paintTargetsByMeshUuid,
textureConfig,
supportError: ''
}
}

64
src/utils/meshTools.js Normal file
View file

@ -0,0 +1,64 @@
// Client helpers for the Python mesh-tools service (Auto UV / Auto Retopo).
//
// These call the Node proxy routes (/api/meshes/auto-uv, /api/meshes/auto-retopo),
// which forward to the configurable Python service. Pass the mesh as a Blob/File
// (a GLB exported from the editor via utils/meshExport.js works directly).
//
// The service returns a JSON envelope { format, mesh_b64, stats, preview_b64 };
// this helper decodes it into { blob, stats, previewUrl }.
import { API_BASE } from '../config'
// Decode a base64 string into a Blob of the given MIME type.
function base64ToBlob(base64, type) {
const binary = atob(base64)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i += 1) {
bytes[i] = binary.charCodeAt(i)
}
return new Blob([bytes], { type })
}
async function callMeshTool(endpoint, meshBlob, { options = {}, fileName = 'mesh.glb', format = 'glb' } = {}) {
const form = new FormData()
form.append('meshFile', meshBlob, fileName)
form.append('options', JSON.stringify(options))
form.append('format', format)
const response = await fetch(`${API_BASE}${endpoint}`, { method: 'POST', body: form })
if (!response.ok) {
let message = `Request failed (${response.status})`
try {
const payload = await response.json()
message = payload.detail ? `${payload.error}: ${JSON.stringify(payload.detail)}` : (payload.error || message)
} catch {
// non-JSON error body — keep the status message
}
throw new Error(message)
}
const data = await response.json()
const outFormat = data.format || 'glb'
const mimeType = outFormat === 'glb' ? 'model/gltf-binary' : 'application/octet-stream'
const blob = base64ToBlob(data.mesh_b64, mimeType)
const s = data.stats || {}
return {
blob,
stats: {
vertexCount: s.vertex_count ?? null,
faceCount: s.face_count ?? null,
hasUv: !!s.has_uv,
tool: s.tool || null,
},
previewUrl: data.preview_b64 ? `data:image/png;base64,${data.preview_b64}` : null,
}
}
export function autoUv(meshBlob, opts = {}) {
return callMeshTool('/meshes/auto-uv', meshBlob, opts)
}
export function autoRetopo(meshBlob, opts = {}) {
return callMeshTool('/meshes/auto-retopo', meshBlob, opts)
}

View file

@ -165,6 +165,10 @@ export const DEFAULT_SETTINGS = {
url: 'http://127.0.0.1',
port: '8188'
},
meshtools: {
url: 'http://127.0.0.1',
port: '8200'
},
custom: []
}
};