import type { Document } from '@gltf-transform/core'; import { type V3 } from './poseFit/math'; import { type Measurement } from './poseFit/measure'; import { type GarmentUnit } from './poseFit/model'; import { type GroupGraph, type WeldResult } from './poseFit/offsetField'; /** * POSE-AWARE GARMENT FIT — the conform stage that clears poke-through across the canonical pose set, and * refuses its own result unless the poke-through checker says it is strictly better. * * ── WHAT IT FIXES ────────────────────────────────────────────────────────────────────────────────────────── * `addonPushOut.ts` pushes garment VERTICES that sit too close to the REST-pose body. That misses the two * shapes the wearables re-check (61 of 76 live add-ons failing, 2026-09-28) is actually made of: * 1. Chords, not vertices. A coarse garment facet between two vertices that are each 10-15mm clear can * still cut inside the body's curvature; the body's own vertices poke through the flat chord. Only a * BODY-vertex-driven test sees this (garment-refit lane, Male Casual Blazer body vertex #747). * 2. Motion. Poke-through is a function of pose: a waistband that clears at bind pose opens up in a * crouch, a sleeve in a stride. * So this stage measures exactly what `pokethrough-check.mjs` measures — every body vertex, in every pose, * against the nearest posed garment triangle along that triangle's normal — and moves the garment until the * body sits at least `clearanceMm` BEHIND the garment surface. * * ── HOW ──────────────────────────────────────────────────────────────────────────────────────────────────── * Per iteration, per pose, per garment mesh (each LOD separately — each LOD is drawn alone, and a garment * whose every LOD clears the body also clears it in the checker's union-of-LODs measurement): * a. Body vertex b (inside the slot's region scope) whose nearest garment point q on triangle T has signed * distance s = (b−q)·n > −clearance (n oriented away from the body — see the guards below) (and ≤ ceiling — deeper than that is a point the garment was never * meant to cover, per the checker's CEILING_REASONING) needs q moved d = s + clearance along n. * b. d is split over T's corners with the minimum-norm barycentric split (`minNormCornerPush`) — exact in * one step at any point of the triangle. * c. A posed-space requirement n·(posed move) ≥ δ becomes a REST-space half-space (Lᵀn)·Δ ≥ δ, where L is * the linear part of that vertex's blended skinning matrix IN THAT POSE. Linear blend skinning is affine * in the rest position, so this is exact — no linearisation, no matrix inverse to get wrong. Every pose * contributes its own half-space; a vertex must satisfy all of them at once (`projectOntoHalfSpaces`). * d. The per-vertex solutions are smoothed as an obstacle membrane (`offsetField.ts`) — the smoothest field * that still satisfies every requirement — so fixes read as gentle, cloth-like easing, not lumps. * e. Hems keep their shape: open-boundary vertices (cuffs, waistbands, collars) may move at most * `hemMaxPushMm`, ramping to the full `maxPushMm` over `hemBandMm` of surface inward — a cuff eases * instead of flaring, at the cost of leaving a residual at the very edge where it needs more. * Only REST positions change: skin weights, joints, normals, UVs and materials are untouched, and coincident * (seam-split) vertices always receive the identical displacement so no seam can open. * * Guards beyond the checker's own rules (each measured on real items, see `poseFit/measure.ts`): * - Orientation: a garment triangle whose normal faces INTO the body at that point (an inward-facing * lining, an inverted face) is measured and pushed along the FLIPPED normal — away from the body — exactly * as the gate measures it. Pushing along the raw normal would drive a lining into the body while the * pre-orientation checker's count went down. (On a lined jacket that was ~90% of that checker's count.) * - Coverage: a body point with another sheet of the same garment over it along its own normal (beyond * the face being measured) is covered — invisible — so no cloth is moved for it. Clearance is enforced * against the outermost layer only. * - Layer order: a vertex whose move would carry it through another sheet of the same garment is stopped * short of it and that sheet is asked to move instead (`resolveLayerCrossings`); a candidate that still * leaves any vertex on the wrong side of another sheet is rejected by the gate. * Skipped points are counted in the report, never silently dropped. * * ── THE GATE (automatic; there is no way to skip it) ────────────────────────────────────────────────────── * The poke-through measurement (`poseFit/measure.ts`, a port of `pokethrough-check.mjs`) runs on the * garment before the fit and after every iteration. A candidate counts only if its total violation count is * STRICTLY lower than before, no pose's EXPOSED (visible) count got worse, and no vertex ended up on the wrong * side of another sheet of the garment; the best such candidate wins (see `gateRejection`). If none qualifies — or the * garment already measures clean — the garment document is not touched at all: every computation happens * on copies, and POSITION accessors are written only after the gate has accepted a result. */ export interface PoseAwareFitOptions { /** Target clearance: body vertices end at least this far behind the garment surface (default 3mm; to be * replaced by the visual-gate calibration's smallest in-motion-visible value). */ clearanceMm?: number; /** Gate violation floor, the checker's `--threshold` (default 0.5mm). */ thresholdMm?: number; /** Ceiling above which a body point is "not meant to be covered", the checker's `--ceiling` (default 10mm). */ ceilingMm?: number; /** A body vertex farther than this from the garment is not under it at all, the checker's `--proximity` (default 50mm). */ proximityMm?: number; /** Largest total move for any interior garment vertex (default 8mm — on Male Casual Blazer 15mm bought 173 vs 179 violations at the price of 10-15mm armpit bulges). */ maxPushMm?: number; /** Largest total move ON a hem/cuff/collar boundary (default 4mm). */ hemMaxPushMm?: number; /** Surface distance over which the cap ramps from `hemMaxPushMm` back to `maxPushMm` (default 20mm). */ hemBandMm?: number; /** Falloff radius of the smoothing membrane (default 20mm). */ smoothRadiusMm?: number; /** Outer measure→push iterations (default 6). */ iterations?: number; /** Slot region scope — the slot type's granted hide globs, as the checker's `--hidden-regions` ([] = unscoped). */ hiddenRegions?: readonly string[]; /** Pose subset (default: all five canonical poses). */ poses?: readonly string[]; onProgress?: (message: string) => void; } export type PoseAwareFitOutcome = 'improved' | 'unchanged-no-improvement' | 'unchanged-already-clean' | 'skipped'; export interface PoseAwareFitIteration { iteration: number; requirements: number; /** Requirements handed on from the previous iteration by a stopped layer crossing. */ carriedLayerRequirements: number; /** Group moves stopped short of another sheet of the same garment this iteration. */ stoppedAtLayer: number; groupsMoved: number; maxTotalMoveMm: number; capped: number; /** Requirements measured against an inward-facing (flipped) garment face. */ orientationFlipped: number; /** Body points outside their nearest face but covered by another sheet of the garment along their normal. */ coveredSkipped: number; totalViolations: number; totalBeyondCeiling: number; totalRawViolations: number; totalExposedViolations: number | null; layerCrossings: number; qualifies: boolean; /** Per pose: [violations, exposed] for this candidate. */ perPose: Record; /** Why the candidate does not qualify (null when it does). */ rejectedBecause: string | null; } export interface PoseAwareFitReport { outcome: PoseAwareFitOutcome; /** Human-readable reason for any outcome other than 'improved'. */ reason: string | null; settings: Required> & { poses: string[]; hiddenRegions: string[]; }; before: Measurement | null; /** The gate measurement of the geometry actually kept (== before unless outcome is 'improved') — measured * fresh from the written float32 positions, so it equals what `pokethrough-check.mjs` prints for the file. */ after: Measurement | null; /** The best candidate as measured inside the loop (float64), even when the gate rejected it. */ bestCandidate: Measurement | null; chosenIteration: number | null; iterations: PoseAwareFitIteration[]; /** Geometry actually written (zeros unless 'improved'). */ applied: { verticesMoved: number; groupsMoved: number; maxMoveMm: number; meanMoveMm: number; hemGroupsMoved: number; /** Distribution of per-group move magnitudes, for judging silhouette impact at a glance. */ p50MoveMm: number; p90MoveMm: number; p99MoveMm: number; groupsOver5Mm: number; groupsOver10Mm: number; }; meshes: Array<{ name: string; vertices: number; welded: number; triangles: number; hemGroups: number; meanEdgeMm: number; smoothingSweeps: number; }>; excluded: string[]; elapsedMs: number; } interface UnitState { unit: GarmentUnit; weld: WeldResult; triGroups: Int32Array; graph: GroupGraph; caps: Float64Array; sweeps: number; groupDelta: Float64Array; vertexDelta: Float64Array; } export interface LayerCrossing { group: number; /** Segment parameter of the first crossing along the group's move. */ t: number; length: number; /** Unit rest-space direction of the move. */ dir: V3; /** The crossed triangle (index into triGroups / 3) and the crossing point's barycentrics on it. */ triangle: number; bary: V3; } /** * Groups whose rest-space move from (rest + `from`) to (rest + `to`) passes through another triangle of the * same mesh as it stands AFTER the move — i.e. the vertex ended up on the other side of another sheet of * cloth (a lining shoved through its shell, a lapel pushed through the panel under it, or a local fold-over * where a vertex outran its own neighbourhood). No body-vs-garment measurement can see this, so the stage * checks it itself. */ export declare function findLayerCrossings(state: Pick, from: Float64Array, to: Float64Array, minMoveM?: number): LayerCrossing[]; export declare function countLayerCrossings(state: Pick, groupDelta: Float64Array): number; /** * Runs the pose-aware fit on `garment` against `body`, gated by the poke-through measurement. Mutates * `garment`'s POSITION accessors ONLY when the report's outcome is 'improved'. */ export declare function poseAwareFit(garment: Document, body: Document, options?: PoseAwareFitOptions): PoseAwareFitReport; export {};