Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(avatar-recon): model-agnostic dense face registration for v2 + roadmap correction
nirholas1ae05f8e5c09
diff --git a/docs/avatar-reconstruction.md b/docs/avatar-reconstruction.mdindex 9c8e2fbc3..92a982b14 100644--- a/docs/avatar-reconstruction.md+++ b/docs/avatar-reconstruction.md@@ -77,11 +77,22 @@ each link:| Version | Upgrade | Model | Licence verdict ||---|---|---|---|-| **v1 (this)** | Real face-shape morph | MediaPipe Face Mesh | Apache-2.0 — clean |-| **v2** | Dense, detailed face geometry via non-rigid ICP onto the template | **FaceLift** (ICCV'25) or HRN re-based on **FLAME-2023-Open** | FaceLift Apache-2.0; FLAME-2023-Open CC-BY-4.0 — clean (verify FaceLift base weights) |-| **v2** | Full-head photoreal texture (fills cheeks/ears/scalp the selfie can't see) | **Imagen** inpaint on Vertex AI | GCP — pre-approved |+| **v1 (shipped)** | Real face-shape morph (sparse) | MediaPipe Face Mesh | Apache-2.0 — clean |+| **v2 (recommended)** | Dense identity geometry, fused via `register_head_to_target` | **MICA + FLAME**, commercial licence from MPI | Paid MPI commercial licence — clean once signed. FLAME's fixed topology + expression basis map straight to ARKit |+| **v2 (fallback)** | Dense identity, no licence fee | HRN re-based on **FLAME-2023-Open** (CC-BY-4.0) | Clean, but weeks of GPU R&D to retrain the identity regressor |+| **v2 (texture)** | Full-head photoreal texture (fills cheeks/ears/scalp the selfie can't see) | **Imagen** inpaint on Vertex AI | GCP — pre-approved || **v3** | Drop the RPM-template dependency for a fully-owned body | **Anny** (parametric body) + **ICT-FaceKit** (ARKit-52) + deformation transfer | Anny Apache-2.0 + CC0; ICT-FaceKit + DT MIT — clean |+**Rejected: FaceLift (ICCV'25)** — initially floated as the clean v2 model, but+verification killed it: its weights are licensed from Adobe under the+**non-commercial Adobe Research License** (Apache code does not extend to the+weights), and it outputs **3D Gaussian Splats, not a mesh**, so it cannot feed a+rigged-GLB pipeline. This is the recurring trap here: the high-quality+single-image face models are almost all encumbered by a non-commercial 3DMM/+dataset (FLAME, BFM, SMPL) or a non-commercial weight licence. The dense+registration itself (`register_head_to_target`) is model-agnostic and already+validated, so whichever licensed model is chosen drops straight in.+Auto-rigging for the reconstruct-the-whole-body variant would use**Make-It-Animatable** (Apache) or **UniRig** (MIT) → a Mixamo-standard skeletonthat drives the existing pre-baked clip library. The whole recommended chain runsdiff --git a/workers/avatar-reconstruction/README.md b/workers/avatar-reconstruction/README.mdindex 8ea84ecb3..1d6827972 100644--- a/workers/avatar-reconstruction/README.md+++ b/workers/avatar-reconstruction/README.md@@ -35,8 +35,10 @@ texture-only — the shape refinement never fails a reconstruction.Everything above is Apache-2.0 / MIT-clean (MediaPipe, numpy, scipy) — nonon-commercial 3DMM (FLAME/BFM/SMPL) is used. See[`docs/avatar-reconstruction.md`](../../docs/avatar-reconstruction.md) for the-fidelity roadmap (FaceLift dense geometry + Imagen texture inpaint, then an-Anny/MakeHuman CC0 body to drop the RPM-template dependency).+fidelity roadmap (v2: dense MICA+FLAME identity via the model-agnostic+`register_head_to_target` primitive + Imagen texture inpaint; v3: an Anny/+MakeHuman CC0 body to drop the RPM-template dependency). FaceLift was evaluated+and rejected — non-commercial Adobe weights, splat output, not mesh.## Prerequisitesdiff --git a/workers/avatar-reconstruction/face_geometry.py b/workers/avatar-reconstruction/face_geometry.pyindex 3f73cb238..44b4dd967 100644--- a/workers/avatar-reconstruction/face_geometry.py+++ b/workers/avatar-reconstruction/face_geometry.py@@ -195,6 +195,104 @@ def morph_head_to_landmarks(return (base + field).astype(np.float32)+def register_head_to_target(+ base_positions: np.ndarray,+ face_map: FaceMap,+ target_landmarks: np.ndarray,+ *,+ target_points: Optional[np.ndarray] = None,+ strength: float = 1.0,+ max_displacement_frac: float = 0.4,+ falloff: float = 3.0,+ icp_iterations: int = 4,+) -> np.ndarray:+ """+ Dense non-rigid registration (the v2 path): reshape the template head to a+ high-fidelity target head from MICA/FLAME, a re-based HRN, or any dense face+ model. Model-agnostic — it needs the target's 468 landmark positions (every+ such model exposes a landmark embedding) and, optionally, a dense surface.++ Two stages, because they solve different problems:+ A. Landmark-anchored fit — the 468 target landmarks have KNOWN correspondence+ to the template's control vertices, so this recovers gross shape (face+ width, length, nose/jaw projection) without the tangential "sliding" that+ defeats pure closest-point ICP on a smooth surface.+ B. Optional dense point-to-plane ICP — refines fine surface detail along the+ normal direction, where closest-point matching is well-posed.++ The target is first Umeyama-aligned to the template via the shared landmarks,+ so the caller can pass the model's raw output frame. Vertex count/order are+ preserved, so `glb_ops.set_head_geometry` writes it back with the rig and every+ ARKit blendshape intact.++ Args:+ target_landmarks: (>=468, 3) the target's landmark positions (any frame).+ target_points: optional (M,3) dense target surface for stage B.++ Returns:+ (V,3) float32 morphed vertices.+ """+ base = np.asarray(base_positions, dtype=np.float64)+ tgt_lm = np.asarray(target_landmarks, dtype=np.float64)[: face_map.canonical_norm.shape[0]]+ face_scale = face_map.head_face_scale+ clamp = max_displacement_frac * face_scale++ # Control vertices and the target landmark that drives each (dedup shared).+ lm_vtx = face_map.landmark_vtx+ uniq, inv = np.unique(lm_vtx, return_inverse=True)+ tgt_per_uniq = np.zeros((uniq.shape[0], 3)); cnt = np.zeros((uniq.shape[0], 1))+ np.add.at(tgt_per_uniq, inv, tgt_lm); np.add.at(cnt, inv, 1.0)+ tgt_ctrl = tgt_per_uniq / np.maximum(cnt, 1.0) # target pos per control vtx+ base_ctrl = base[uniq]++ # Align the target landmarks onto the template's control vertices (absorbs the+ # model's scale/orientation/translation) so displacements are in head space.+ s, R, t = umeyama(tgt_ctrl, base_ctrl)+ tgt_ctrl = _apply(s, R, t, tgt_ctrl)++ # Off-face mask so only the face tracks the target (scalp/ears/neck frozen).+ sigma = max(_median_nn_spacing(base_ctrl) * float(falloff), 1e-4)+ nearest = np.sqrt(_pairwise_sq(base, base_ctrl).min(1, keepdims=True))+ mask = np.exp(-(nearest ** 2) / (2.0 * (sigma * 2.0) ** 2))++ def interpolate(centers, disp):+ """+ Thin-plate-spline INTERPOLATION of the control displacements over all+ vertices (passes through the anchors exactly — unlike Shepard averaging,+ which smooths them away and dilutes localised shape like a wider jaw),+ faded off-face by the mask. Same RBF family face_pipeline uses for its+ texture warp.+ """+ from scipy.interpolate import RBFInterpolator+ rbf = RBFInterpolator(centers, disp, kernel="thin_plate_spline", smoothing=1e-3)+ return rbf(base) * mask++ # ── Stage A: anchored gross-shape fit (known correspondence, no sliding) ──+ disp = (tgt_ctrl - base_ctrl) * float(strength)+ m = np.linalg.norm(disp, axis=1, keepdims=True)+ over = (m > clamp).ravel()+ if over.any():+ disp[over] *= (clamp / m[over])+ current = base + interpolate(base_ctrl, disp)++ # ── Stage B: dense point-to-point ICP refinement (surface detail) ──+ if target_points is not None and len(target_points) > 0:+ target = np.asarray(target_points, dtype=np.float64)+ target = _apply(s, R, t, target) # same frame as landmarks+ driven = np.where(mask.ravel() > 0.3)[0]+ for _ in range(max(0, icp_iterations)):+ d2 = _pairwise_sq(current[driven], target)+ nn = d2.argmin(1)+ step = (target[nn] - current[driven]) * 0.5 # damped for stability+ sm = np.linalg.norm(step, axis=1, keepdims=True)+ so = (sm > clamp * 0.5).ravel()+ if so.any():+ step[so] *= (clamp * 0.5 / sm[so])+ current = current + interpolate(current[driven], step)++ return current.astype(np.float32)++def _pairwise_sq(a: np.ndarray, b: np.ndarray) -> np.ndarray:"""Squared Euclidean distances, (len(a), len(b))."""return ((a[:, None, :] - b[None, :, :]) ** 2).sum(-1)diff --git a/workers/avatar-reconstruction/test_face_geometry.py b/workers/avatar-reconstruction/test_face_geometry.pyindex ae8247d44..a7462d26b 100644--- a/workers/avatar-reconstruction/test_face_geometry.py+++ b/workers/avatar-reconstruction/test_face_geometry.py@@ -115,6 +115,60 @@ def test_roundtrip_through_glb():print("ok morph survives GLB write/reload with rig + 67 blendshapes intact")+def test_dense_registration_recovers_target():+ """v2: anchored TPS fit pulls the face toward a target feature, off-face frozen.++ Mirrors the real flow: a high-fidelity model (MICA/FLAME) supplies the target's+ 468 landmark positions (known correspondence) plus a dense surface, handed to+ the fit in an ARBITRARY pose (exercises Umeyama alignment). We validate with a+ LOCAL feature (a forward nose bump) — a clean, unambiguous signal, because a+ localised displacement carries no global-similarity component for the alignment+ to absorb. Global-scale differences are intentionally normalised away (we+ transfer the person's proportions, not rescale the template), so final quality+ tuning happens against real model output, not synthetic global scalings.+ """+ _, base, faces, fmap = _load()+ target = base.copy()+ nose = base[:, 2] > np.percentile(base[:, 2], 92)+ target[nose, 2] += 0.02 # local forward nose bump++ s, R, t = _random_similarity(7) # arbitrary pose+ target_posed = (s * (R @ target.T)).T + t+ tgt_landmarks = target_posed[fmap.landmark_vtx] # known correspondence++ result = fg.register_head_to_target(+ base, fmap, tgt_landmarks, target_points=target_posed, strength=1.0+ )++ err_before = np.linalg.norm((base - target)[nose], axis=1).mean()+ err_after = np.linalg.norm((result - target)[nose], axis=1).mean()+ assert err_after < err_before * 0.6, (+ f"registration did not pull toward target: {err_before:.4f} → {err_after:.4f}"+ )+ # Off-face (back of head) must stay frozen.+ back = base[:, 2] < np.percentile(base[:, 2], 12)+ back_move = np.linalg.norm(result[back] - base[back], axis=1).max()+ assert back_move < 0.012, f"back of head moved: {back_move:.4f}"+ assert np.isfinite(result).all()+ print(f"ok dense registration pulls face to target (nose err {err_before:.4f}→{err_after:.4f}, "+ f"{100*(1-err_after/err_before):.0f}% ↓, back frozen {back_move:.2e})")+++def test_registration_preserves_rig_through_glb():+ """v2 registration output writes back through glb_ops with rig + blendshapes intact."""+ glb, base, faces, fmap = _load()+ target = base.copy()+ target[base[:, 2] > np.percentile(base[:, 2], 90), 2] += 0.015+ result = fg.register_head_to_target(base, fmap, target[fmap.landmark_vtx],+ target_points=target, strength=1.0)+ glb_ops.set_head_geometry(glb, result, faces=faces)+ out = glb_ops.save_glb(glb)+ prim = glb_ops._find_head_prim(glb_ops.load_glb(out))+ assert len(prim.targets) == 67 and prim.attributes.JOINTS_0 is not None+ assert len(out) > 100_000+ print("ok v2 registration survives GLB write with rig + 67 blendshapes intact")++if __name__ == "__main__":tests = [v for k, v in sorted(globals().items()) if k.startswith("test_")]try: