@rig-c/parts 1.69.0 → 1.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,553 @@
1
+ /** Source-space waist subdivision. Exact predicates identify shared edges; emitted bindings keep OFFSET6/f32. */
2
+ import { computeExactFrameTransforms, computeWorldTransforms, cropToSpineY, toBoneLocal, toWorld, type BoneTransform } from './coords.ts';
3
+ import { PartsError } from './errors.ts';
4
+ import { counterClockwiseInSpineWorld, type LatticeMesh } from './mesh.ts';
5
+ import type { MeshAttachment, RegionAttachment, RigBone, WeightEntry } from './rig.ts';
6
+ import { pyRound } from './round.ts';
7
+ import { f32 } from 'rig-c/compile';
8
+
9
+ type Q = readonly [bigint, bigint];
10
+ type P = readonly [Q, Q];
11
+ type Line = readonly [Q, Q, Q];
12
+ function fail(code: string, object: string, detail: string): never { throw new PartsError([{ code, object, detail }]); }
13
+ const gcd = (a: bigint, b: bigint): bigint => { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b !== 0n) [a, b] = [b, a % b]; return a; };
14
+ const q = (n: bigint, d = 1n): Q => { if (d < 0n) { n = -n; d = -d; } const g = gcd(n, d); return [n / g, d / g]; };
15
+ const add = (a: Q, b: Q): Q => q(a[0] * b[1] + b[0] * a[1], a[1] * b[1]);
16
+ const sub = (a: Q, b: Q): Q => q(a[0] * b[1] - b[0] * a[1], a[1] * b[1]);
17
+ const mul = (a: Q, b: Q): Q => q(a[0] * b[0], a[1] * b[1]);
18
+ const div = (a: Q, b: Q): Q => q(a[0] * b[1], a[1] * b[0]);
19
+ const number = (a: Q): number => Number(a[0]) / Number(a[1]);
20
+ const decimal = (v: number): Q => {
21
+ if (!Number.isFinite(v)) fail('RIG_WAIST_GEOMETRY', 'waist arrangement', `coordinate ${v} is not finite`);
22
+ const [m, e = '0'] = String(v).split('e'), places = (m.split('.')[1] ?? '').length - Number(e);
23
+ const n = BigInt(m.replace('.', ''));
24
+ return places >= 0 ? q(n, 10n ** BigInt(places)) : q(n * 10n ** BigInt(-places));
25
+ };
26
+ const point = (x: number, y: number): P => [decimal(x), decimal(y)];
27
+ const key = (p: P): string => p.map((v) => `${v[0]}/${v[1]}`).join(',');
28
+ const cross = (a: P, b: P, c: P): Q => sub(mul(sub(b[0], a[0]), sub(c[1], a[1])), mul(sub(b[1], a[1]), sub(c[0], a[0])));
29
+ const lineOf = (a: P, b: P): Line => [sub(a[1], b[1]), sub(b[0], a[0]), sub(mul(a[0], b[1]), mul(b[0], a[1]))];
30
+ const at = (l: Line, p: P): Q => add(add(mul(l[0], p[0]), mul(l[1], p[1])), l[2]);
31
+ const lineKey = (l: Line): string => { const first = l.find((x) => x[0] !== 0n); return first === undefined ? '' : l.map((x) => div(x, first).join('/')).join(','); };
32
+ function clip(poly: readonly P[], line: Line, side: bigint): P[] {
33
+ const out: P[] = [];
34
+ for (let i = 0; i < poly.length; i++) {
35
+ const a = poly[i], b = poly[(i + 1) % poly.length], da = at(line, a), db = at(line, b);
36
+ if (da[0] * side >= 0n) out.push(a);
37
+ if (da[0] * db[0] < 0n) {
38
+ const t = div(da, sub(da, db));
39
+ out.push([add(a[0], mul(t, sub(b[0], a[0]))), add(a[1], mul(t, sub(b[1], a[1])))]);
40
+ }
41
+ }
42
+ return out.filter((p, i) => key(p) !== key(out[(i + out.length - 1) % out.length]));
43
+ }
44
+ function split(polys: P[][], line: Line): P[][] {
45
+ return polys.flatMap((poly) => {
46
+ const sides = poly.map((p) => at(line, p)[0]);
47
+ return sides.some((n) => n < 0n) && sides.some((n) => n > 0n) ? [clip(poly, line, 1n), clip(poly, line, -1n)] : [poly];
48
+ });
49
+ }
50
+ /** Metadata needed to invert a native page UV into the original drawing, in texels. */
51
+ export interface StoredWaistAtlas {
52
+ pageWidth: number; pageHeight: number; scale: number | null | undefined;
53
+ x: number; y: number; width: number; height: number;
54
+ offsetX: number; offsetY: number; originalWidth: number; originalHeight: number; degrees: number;
55
+ }
56
+
57
+ /** Exact binary64 value, including the float32 values native UV arrays hold. */
58
+ function binary(value: number): Q {
59
+ if (!Number.isFinite(value)) fail('RIG_WAIST_STORED_UV', 'native waist UV', `non-finite value ${value}`);
60
+ const v = new DataView(new ArrayBuffer(8)); v.setFloat64(0, value);
61
+ const bits = v.getBigUint64(0), exponent = Number((bits >> 52n) & 2047n), fraction = bits & ((1n << 52n) - 1n);
62
+ let n = exponent === 0 ? fraction : fraction | (1n << 52n);
63
+ if ((bits >> 63n) !== 0n) n = -n;
64
+ const e = (exponent === 0 ? -1022 : exponent - 1023) - 52;
65
+ return e >= 0 ? q(n << BigInt(e)) : q(n, 1n << BigInt(-e));
66
+ }
67
+ const twiceArea = (poly: readonly P[]): Q => {
68
+ const a = poly.reduce((sum, p, i) => add(sum, sub(mul(p[0], poly[(i + 1) % poly.length][1]), mul(p[1], poly[(i + 1) % poly.length][0]))), q(0n));
69
+ return a[0] < 0n ? q(-a[0], a[1]) : a;
70
+ };
71
+
72
+ /**
73
+ * Whole last-row pixel cells, using ACTUAL native page UVs, never nominal row positions.
74
+ * Exact clipping and coverage leave no epsilon that could swallow a positive mixed-support sliver.
75
+ * The caller supplies stored H-only support from the gated compiled bindings in the same vertex order.
76
+ */
77
+ export function storedWaistHem(
78
+ uvs: readonly number[], triangles: readonly number[], onlyLower: readonly boolean[],
79
+ art: { width: number; height: number; data: ArrayLike<number> }, atlas: StoredWaistAtlas,
80
+ ): { pass: boolean; hem: number; pixels: number; uncovered: number[]; mixed: number[] } {
81
+ const ints = [atlas.pageWidth, atlas.pageHeight, atlas.x, atlas.y, atlas.width, atlas.height, atlas.offsetX, atlas.offsetY, atlas.originalWidth, atlas.originalHeight, atlas.degrees];
82
+ if (ints.some((n) => !Number.isSafeInteger(n)) || atlas.pageWidth < 1 || atlas.pageHeight < 1 || atlas.pageWidth > 2048 || atlas.pageHeight > 2048 || atlas.width < 1 || atlas.height < 1 || atlas.originalWidth !== art.width || atlas.originalHeight !== art.height || art.width < 1 || art.height < 1 || art.width > 2048 || art.height > 2048 || (atlas.scale !== null && atlas.scale !== 1) || ![0, 90, 180, 270].includes(atlas.degrees)) {
83
+ fail('RIG_WAIST_STORED_METADATA', 'native waist atlas', 'requires integral unscaled metadata, positive original/page dimensions at most 2048, matching source drawing dimensions, and a right-angle rotation');
84
+ }
85
+ if (art.data.length !== art.width * art.height || uvs.length !== 2 * onlyLower.length || uvs.length === 0 || uvs.some((n) => !Number.isFinite(n) || Math.fround(n) !== n) || triangles.length === 0 || triangles.length % 3 !== 0 || triangles.some((n) => !Number.isInteger(n) || n < 0 || n >= onlyLower.length)) fail('RIG_WAIST_STORED_UV', 'native waist mesh', 'requires nonempty native float32 page UVs, matching support and valid complete triangles');
86
+ let hem = -1;
87
+ for (let y = 0; y < art.height; y++) for (let x = 0; x < art.width; x++) if (art.data[y * art.width + x] !== 0) hem = y;
88
+ if (hem < 0) fail('RIG_WAIST_STORED_EMPTY', 'native waist hem', 'no painted row; an empty read cannot pass');
89
+ const integer = (n: number): Q => q(BigInt(n));
90
+ const vertices: P[] = [];
91
+ for (let i = 0; i < uvs.length; i += 2) {
92
+ const u = sub(mul(binary(uvs[i]), integer(atlas.pageWidth)), integer(atlas.x));
93
+ const v = sub(mul(binary(uvs[i + 1]), integer(atlas.pageHeight)), integer(atlas.y));
94
+ const ow = integer(atlas.originalWidth), oh = integer(atlas.originalHeight);
95
+ switch (atlas.degrees) {
96
+ case 90: vertices.push([sub(ow, add(v, integer(atlas.originalWidth - atlas.offsetX - atlas.width))), add(u, integer(atlas.originalHeight - atlas.offsetY - atlas.height))]); break;
97
+ case 180: vertices.push([sub(ow, add(u, integer(atlas.originalWidth - atlas.offsetX - atlas.width))), sub(oh, add(v, integer(atlas.offsetY)))]); break;
98
+ case 270: vertices.push([add(v, integer(atlas.offsetX)), sub(oh, add(u, integer(atlas.offsetY)))]); break;
99
+ default: vertices.push([add(u, integer(atlas.offsetX)), add(v, integer(atlas.originalHeight - atlas.offsetY - atlas.height))]);
100
+ }
101
+ }
102
+ const uncovered: number[] = [], mixed: number[] = [];
103
+ let pixels = 0;
104
+ for (let x = 0; x < art.width; x++) {
105
+ if (art.data[hem * art.width + x] === 0) continue;
106
+ pixels++;
107
+ let covered = q(0n), hasMixed = false, overlap = false;
108
+ const pieces: P[][] = [];
109
+ for (let t = 0; t < triangles.length; t += 3) {
110
+ const ids = triangles.slice(t, t + 3);
111
+ let poly = ids.map((v) => vertices[v]);
112
+ for (const [axis, low, high] of [[0, x, x + 1], [1, hem, hem + 1]]) {
113
+ const a = axis === 0 ? q(1n) : q(0n), b = axis === 1 ? q(1n) : q(0n);
114
+ poly = clip(poly, [a, b, integer(-low)], 1n);
115
+ poly = clip(poly, [a, b, integer(-high)], -1n);
116
+ }
117
+ const area = twiceArea(poly);
118
+ if (area[0] === 0n) continue;
119
+ for (const previous of pieces) {
120
+ let intersection = poly;
121
+ const orientation = previous.map((a, i) => cross(a, previous[(i + 1) % previous.length], previous[(i + 2) % previous.length])[0]).find((n) => n !== 0n);
122
+ if (orientation === undefined) continue;
123
+ for (let k = 0; k < previous.length; k++) intersection = clip(intersection, lineOf(previous[k], previous[(k + 1) % previous.length]), orientation > 0n ? 1n : -1n);
124
+ if (twiceArea(intersection)[0] !== 0n) overlap = true;
125
+ }
126
+ pieces.push(poly);
127
+ covered = add(covered, area);
128
+ if (ids.some((v) => !onlyLower[v])) hasMixed = true;
129
+ }
130
+ if (overlap || covered[0] !== 2n * covered[1]) uncovered.push(x);
131
+ if (hasMixed) mixed.push(x);
132
+ }
133
+ return { pass: pixels > 0 && uncovered.length === 0 && mixed.length === 0, hem, pixels, uncovered, mixed };
134
+ }
135
+
136
+ export interface Correspondence { indices: number[]; barycentric: number[] }
137
+ interface Arrangement { exact: P[]; vertices: Array<[number, number]>; triangles: number[]; hull: number }
138
+ const exactVertices = new WeakMap<object, P[]>();
139
+ function arrangement(polys: P[][]): Arrangement {
140
+ const pts: P[] = [], ids = new Map<string, number>(), triangles: number[] = [];
141
+ const id = (p: P): number => { const k = key(p), old = ids.get(k); if (old !== undefined) return old; const v = pts.length; pts.push(p); ids.set(k, v); return v; };
142
+ for (let poly of polys) {
143
+ if (poly.length < 3) continue;
144
+ const area = poly.reduce((sum, p, i) => add(sum, sub(mul(p[0], poly[(i + 1) % poly.length][1]), mul(p[1], poly[(i + 1) % poly.length][0]))), q(0n));
145
+ if (area[0] === 0n) continue;
146
+ if (area[0] < 0n) poly = [...poly].reverse();
147
+ const collinear = poly.some((p, i) => cross(poly[(i + poly.length - 1) % poly.length], p, poly[(i + 1) % poly.length])[0] === 0n);
148
+ if (collinear) {
149
+ const centre: P = [div(poly.reduce((s, p) => add(s, p[0]), q(0n)), q(BigInt(poly.length))), div(poly.reduce((s, p) => add(s, p[1]), q(0n)), q(BigInt(poly.length)))];
150
+ for (let i = 0; i < poly.length; i++) triangles.push(id(centre), id(poly[i]), id(poly[(i + 1) % poly.length]));
151
+ } else for (let i = 1; i + 1 < poly.length; i++) triangles.push(id(poly[0]), id(poly[i]), id(poly[i + 1]));
152
+ }
153
+ const edges = new Map<string, { a: number; b: number; n: number }>();
154
+ for (let t = 0; t < triangles.length; t += 3) for (let k = 0; k < 3; k++) {
155
+ const a = triangles[t + k], b = triangles[t + (k + 1) % 3], ek = `${Math.min(a, b)},${Math.max(a, b)}`, old = edges.get(ek);
156
+ if (old === undefined) edges.set(ek, { a, b, n: 1 }); else old.n++;
157
+ }
158
+ const adj = new Map<number, number[]>();
159
+ for (const e of edges.values()) {
160
+ if (e.n > 2) fail('RIG_WAIST_TOPOLOGY', 'waist arrangement', `edge ${e.a}/${e.b} belongs to ${e.n} triangles, expected one or two`);
161
+ if (e.n === 1) { adj.set(e.a, [...(adj.get(e.a) ?? []), e.b]); adj.set(e.b, [...(adj.get(e.b) ?? []), e.a]); }
162
+ }
163
+ if (adj.size === 0 || [...adj.values()].some((v) => v.length !== 2)) fail('RIG_WAIST_TOPOLOGY', 'waist arrangement', 'boundary is not a closed non-pinched loop');
164
+ const order: number[] = [], seen = new Set<number>();
165
+ let cur = adj.keys().next().value as number;
166
+ while (!seen.has(cur)) { seen.add(cur); order.push(cur); cur = (adj.get(cur) as number[]).find((n) => !seen.has(n)) ?? order[0]; }
167
+ if (seen.size !== adj.size) fail('RIG_WAIST_TOPOLOGY', 'waist arrangement', `has more than one boundary loop (${seen.size}/${adj.size} boundary vertices reached)`);
168
+ const hull = order.length;
169
+ for (let i = 0; i < pts.length; i++) if (!seen.has(i)) order.push(i);
170
+ const remap = new Map(order.map((v, i) => [v, i]));
171
+ const exact = order.map((i) => pts[i]);
172
+ const vertices = exact.map((p) => [number(p[0]), number(p[1])] as [number, number]);
173
+ exactVertices.set(vertices, exact);
174
+ return { exact, vertices, triangles: counterClockwiseInSpineWorld(triangles.map((i) => remap.get(i) as number)), hull };
175
+ }
176
+ function polygons(vertices: readonly (readonly [number, number])[], triangles: readonly number[]): P[][] {
177
+ const pts = exactVertices.get(vertices) ?? vertices.map(([x, y]) => point(x, y)), out: P[][] = [];
178
+ for (let t = 0; t < triangles.length; t += 3) out.push(triangles.slice(t, t + 3).map((i) => pts[i]));
179
+ return out;
180
+ }
181
+ function locate(p: P, vertices: readonly (readonly [number, number])[], triangles: readonly number[]): Correspondence | null {
182
+ const pts = exactVertices.get(vertices) ?? vertices.map(([x, y]) => point(x, y));
183
+ for (let t = 0; t < triangles.length; t += 3) {
184
+ const indices = triangles.slice(t, t + 3), [a, b, c] = indices.map((i) => pts[i]), area = cross(a, b, c);
185
+ const bary = [div(cross(b, c, p), area), div(cross(c, a, p), area), div(cross(a, b, p), area)];
186
+ if (bary.every((v) => v[0] >= 0n)) return { indices, barycentric: bary.map(number) };
187
+ }
188
+ return null;
189
+ }
190
+ /** Subdivide ORIGINAL triangles at the driver rows, retaining their diagonal/UV partition. */
191
+ export function refineWaistMesh(old: LatticeMesh, rows: readonly number[]): LatticeMesh {
192
+ let polys = polygons(old.vertices, old.triangles);
193
+ for (const y of [...new Set(rows)]) polys = split(polys, [q(0n), q(1n), mul(q(-1n), decimal(y))]);
194
+ const a = arrangement(polys);
195
+ return { ...old, vertices: a.vertices, triangles: a.triangles, hull: a.hull };
196
+ }
197
+ export function waistCorrespondence(vertices: readonly (readonly [number, number])[], old: LatticeMesh): Correspondence[] {
198
+ return vertices.map(([x, y], i) => {
199
+ const hit = locate(exactVertices.get(vertices)?.[i] ?? point(x, y), old.vertices, old.triangles);
200
+ if (hit === null) fail('RIG_WAIST_CORRESPONDENCE', 'topwear subdivision', `point [${x}, ${y}] is outside its original supplied triangle domain`);
201
+ return hit;
202
+ });
203
+ }
204
+ export const storedWorld = (bones: readonly RigBone[]): Map<string, BoneTransform> => computeWorldTransforms(bones.map((b) => ({ ...b, x: Math.fround(b.x), y: Math.fround(b.y), ...(b.rotation === undefined ? {} : { rotation: Math.fround(b.rotation) }) })));
205
+ export function nativePoint(weights: readonly WeightEntry[], world: ReadonlyMap<string, BoneTransform>): [number, number] {
206
+ let x = 0, y = 0;
207
+ for (const w of weights) { const p = toWorld(world.get(w.bone) as BoneTransform, Math.fround(w.x), Math.fround(w.y)); x += p[0] * Math.fround(w.weight); y += p[1] * Math.fround(w.weight); }
208
+ return [x, y];
209
+ }
210
+ const interpolate = (map: Correspondence, values: readonly number[]): number => map.indices.reduce((s, v, i) => s + map.barycentric[i] * values[v], 0);
211
+ export interface WaistMapping { old: MeshAttachment; current: MeshAttachment; source: Correspondence[]; positions: Array<[number, number]>; maxRestResidual: number; maxUvStorageResidual: number }
212
+ const mappings = new WeakMap<MeshAttachment, WaistMapping>();
213
+ const bottomLayouts = new WeakMap<MeshAttachment, LatticeMesh>();
214
+ export const waistMappingOf = (mesh: MeshAttachment): WaistMapping | undefined => mappings.get(mesh);
215
+ export const waistBottomLayoutOf = (mesh: MeshAttachment): LatticeMesh | undefined => bottomLayouts.get(mesh);
216
+ /** Alternative1: inverse-bind the old native point, OFFSET6, then ordinary runtime f32. No image-dependent search. */
217
+ export function preserveWaistRest(old: MeshAttachment, oldLm: LatticeMesh, mesh: MeshAttachment, lm: LatticeMesh, world: ReadonlyMap<string, BoneTransform>, anchor: number): WaistMapping {
218
+ const source = waistCorrespondence(lm.vertices, oldLm), before = old.weights.map((w) => nativePoint(w, world));
219
+ let maxRestResidual = 0, maxUvStorageResidual = 0;
220
+ for (let i = 0; i < source.length; i++) {
221
+ const map = source[i], target: [number, number] = [interpolate(map, before.map((p) => p[0])), interpolate(map, before.map((p) => p[1]))];
222
+ const original = oldLm.vertices.findIndex(([x, y]) => x === lm.vertices[i][0] && y === lm.vertices[i][1]);
223
+ if (original >= 0 && lm.vertices[i][1] <= anchor) mesh.weights[i] = old.weights[original].map((w) => ({ ...w }));
224
+ else mesh.weights[i] = mesh.weights[i].map((w) => { const p = toBoneLocal(world.get(w.bone) as BoneTransform, ...target); return { ...w, x: pyRound(p[0], 6), y: pyRound(p[1], 6) }; });
225
+ for (const k of [0, 1]) {
226
+ const uv = interpolate(map, old.weights.map((_, v) => old.uvs[2 * v + k]));
227
+ mesh.uvs[2 * i + k] = uv;
228
+ maxUvStorageResidual = Math.max(maxUvStorageResidual, Math.abs(Math.fround(uv) - uv));
229
+ }
230
+ const actual = nativePoint(mesh.weights[i], world);
231
+ maxRestResidual = Math.max(maxRestResidual, Math.abs(actual[0] - target[0]), Math.abs(actual[1] - target[1]));
232
+ }
233
+ const mapping = { old, current: mesh, source, positions: lm.vertices, maxRestResidual, maxUvStorageResidual };
234
+ mappings.set(mesh, mapping);
235
+ return mapping;
236
+ }
237
+ /** Actual STORED per-bone moments, not independently recomputed distance shares or recapped weights. */
238
+ export function waistMoments(mesh: MeshAttachment, source: Correspondence): WeightEntry[] {
239
+ const common = source.barycentric.findIndex((n) => n === 1);
240
+ if (common >= 0 && source.barycentric.every((n, i) => i === common || n === 0)) return mesh.weights[source.indices[common]].map((w) => ({ ...w }));
241
+ const moments = new Map<string, { w: number; x: number; y: number }>();
242
+ source.indices.forEach((vi, k) => {
243
+ const lambda = source.barycentric[k];
244
+ if (lambda === 0) return;
245
+ for (const v of mesh.weights[vi]) {
246
+ const w = lambda * Math.fround(v.weight), m = moments.get(v.bone) ?? { w: 0, x: 0, y: 0 };
247
+ m.w += w; m.x += w * Math.fround(v.x); m.y += w * Math.fround(v.y); moments.set(v.bone, m);
248
+ }
249
+ });
250
+ return [...moments].filter(([, m]) => m.w > 0).map(([bone, m]) => ({ bone, weight: m.w, x: pyRound(m.x / m.w, 6), y: pyRound(m.y / m.w, 6) }));
251
+ }
252
+ /** Extend the top's actual triangle arrangement over the supplied bottom rectangle. No inferred waistband extent. */
253
+ export function waistBottomMesh(top: MeshAttachment, lm: LatticeMesh, topOrigin: readonly [number, number], bottom: RegionAttachment, bottomOrigin: readonly [number, number], size: readonly [number, number], lower: string, bones: readonly RigBone[]): MeshAttachment {
254
+ const vertices = lm.vertices.map(([x, y]) => [x + topOrigin[0], y + topOrigin[1]] as [number, number]);
255
+ exactVertices.set(vertices, (exactVertices.get(lm.vertices) ?? lm.vertices.map(([x,y])=>point(x,y))).map(([x,y])=>[add(x,decimal(topOrigin[0])),add(y,decimal(topOrigin[1]))]));
256
+ const [ox, oy] = bottomOrigin, [w, h] = size;
257
+ let polys: P[][] = [[point(ox, oy), point(ox + w, oy), point(ox + w, oy + h), point(ox, oy + h)]];
258
+ const lines = new Map<string, Line>();
259
+ for (const poly of polygons(vertices, top.triangles)) for (let i = 0; i < 3; i++) { const l = lineOf(poly[i], poly[(i + 1) % 3]); lines.set(lineKey(l), l); }
260
+ for (const line of lines.values()) polys = split(polys, line);
261
+ const a = arrangement(polys), world = storedWorld(bones);
262
+ // A private frame evaluates the existing region centre/counterrotation through the coordinate door; never emitted.
263
+ let marker = '__waist_region_frame';
264
+ while (bones.some((b) => b.name === marker)) marker += '_';
265
+ const regionWorld = computeWorldTransforms([...bones.map((b) => ({ ...b, x: Math.fround(b.x), y: Math.fround(b.y), ...(b.rotation === undefined ? {} : { rotation: Math.fround(b.rotation) }) })), { name: marker, parent: lower, x: bottom.x, y: bottom.y, rotation: bottom.rotation ?? 0 }]).get(marker) as BoneTransform;
266
+ const weights = a.exact.map((p, i) => {
267
+ const hit = locate(p, vertices, top.triangles);
268
+ if (hit !== null) return waistMoments(top, hit);
269
+ const [x, y] = a.vertices[i], target = toWorld(regionWorld, x - ox - w / 2, cropToSpineY(y - oy, h) - h / 2);
270
+ const local = toBoneLocal(world.get(lower) as BoneTransform, ...target);
271
+ return [{ bone: lower, x: pyRound(local[0], 6), y: pyRound(local[1], 6), weight: 1 }];
272
+ });
273
+ const mesh: MeshAttachment = { type: 'mesh', image: bottom.image, width: w, height: h, uvs: a.vertices.flatMap(([x, y]) => [(x - ox) / w, (y - oy) / h]), triangles: a.triangles, hull: a.hull, weights };
274
+ bottomLayouts.set(mesh, { vertices: a.vertices.map(([x,y])=>[x-ox,y-oy]), triangles:a.triangles,hull:a.hull,loops:1,pinchedVertices:0,cells:polys.length,passes:0 });
275
+ return mesh;
276
+ }
277
+
278
+ /** Targeted numeric deformation only. Sparse/odd runs are expanded against OLD per-influence indexing. */
279
+ export function remapWaistDeforms(motion: { animations: Record<string, unknown> }, targets: ReadonlyMap<string, WaistMapping>, regionTargets: ReadonlySet<string> = new Set(), beforeRebind: ReadonlyMap<string, string> = new Map()): void {
280
+ const record = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
281
+ for (const [animation, value] of Object.entries(motion.animations)) {
282
+ if (!record(value) || !Array.isArray(value.deform)) continue;
283
+ if (!value.deform.some((t) => record(t) && (targets.has(`${String(t.skin ?? 'default')}/${String(t.slot)}/${String(t.attachment)}`) || regionTargets.has(`${String(t.skin ?? 'default')}/${String(t.slot)}/${String(t.attachment)}`)))) continue;
284
+ const tracks: unknown[] = value.deform.map((t) => record(t) && targets.has(`${String(t.skin ?? 'default')}/${String(t.slot)}/${String(t.attachment)}`) && Array.isArray(t.keys) ? { ...t, keys: t.keys.map((k) => record(k) ? { ...k } : k) } : t);
285
+ motion.animations[animation] = { ...value, deform: tracks };
286
+ for (const track of tracks) {
287
+ if (!record(track)) continue;
288
+ const name = `${String(track.skin ?? 'default')}/${String(track.slot)}/${String(track.attachment)}`, map = targets.get(name);
289
+ if (regionTargets.has(name)) fail('RIG_WAIST_DEFORM_REGION', `animation "${animation}" deform ${name}`, 'the authored bottomwear was a rigid region without a deform array; conversion cannot reinterpret an authored mesh timeline');
290
+ if (map === undefined || !Array.isArray(track.keys)) continue;
291
+ for (const key of track.keys) {
292
+ if (!record(key)) continue;
293
+ const object = `animation "${animation}" deform ${name} t=${String(key.t)}`;
294
+ if (key.transform !== undefined) fail('RIG_WAIST_DEFORM_MODEL', object, 'whole-attachment transform on a subdivided waist mesh is not proven equivalent to the old evaluated field; supply a representable numeric old-topology run');
295
+ if (key.vertices === undefined || key.vertices === null) continue;
296
+ if (!Array.isArray(key.vertices) || !key.vertices.every((n): n is number => typeof n === 'number' && Number.isFinite(n))) fail('RIG_WAIST_DEFORM_RUN', object, 'requires a finite numeric old-topology run');
297
+ const old = map.old.weights, offsets = [0];
298
+ for (const v of old) offsets.push(offsets[offsets.length - 1] + 2 * v.length);
299
+ if (key.offset !== undefined && key.fromVertex !== undefined) fail('RIG_WAIST_DEFORM_RUN', object, 'offset and fromVertex cannot coexist');
300
+ const start = key.fromVertex === undefined ? key.offset ?? 0 : typeof key.fromVertex === 'number' ? offsets[key.fromVertex] : undefined;
301
+ if (typeof start !== 'number' || !Number.isInteger(start) || start < 0 || start + key.vertices.length > offsets[offsets.length - 1] || key.vertices.length === 0) fail('RIG_WAIST_DEFORM_RUN', object, `old deform length is ${offsets[offsets.length - 1]}; sparse run start ${String(start)}, length ${key.vertices.length} does not fit`);
302
+ const run = new Array<number>(offsets[offsets.length - 1]).fill(0);
303
+ key.vertices.forEach((v, i) => { run[start + i] = Math.fround(v); });
304
+ if (run.some((n) => n !== 0) && beforeRebind.has(name) && JSON.stringify(map.current.weights) !== beforeRebind.get(name)) fail('RIG_WAIST_DEFORM_REBIND', object, 'stops/turn changed the waist binding frames; old numeric local offsets have no proved rebind correspondence');
305
+ const result: number[] = [];
306
+ for (const [vi, source] of map.source.entries()) {
307
+ const moments = new Map<string, [number, number]>();
308
+ source.indices.forEach((oi, k) => old[oi].forEach((w, j) => {
309
+ const n = source.barycentric[k] * Math.fround(w.weight), d = moments.get(w.bone) ?? [0, 0];
310
+ d[0] += n * run[offsets[oi] + 2*j]; d[1] += n * run[offsets[oi] + 2*j + 1]; moments.set(w.bone, d);
311
+ }));
312
+ const bindings = map.current.weights[vi];
313
+ for (const [bone, d] of moments) if (!bindings.some((w) => w.bone === bone) && (d[0] !== 0 || d[1] !== 0)) fail('RIG_WAIST_DEFORM_SUPPORT', object, `new vertex ${vi} has no "${bone}" influence but its old barycentric deform moment is [${d.join(', ')}]; arbitrary bone motion cannot carry that moment through another bone`);
314
+ for (const w of bindings) { const d = moments.get(w.bone) ?? [0, 0]; result.push(d[0] / Math.fround(w.weight), d[1] / Math.fround(w.weight)); }
315
+ }
316
+ delete key.offset; delete key.fromVertex; key.vertices = result;
317
+ }
318
+ }
319
+ }
320
+ }
321
+
322
+ /** Source-derived stations for an explicit, single-pivot waist candidate. */
323
+ export interface WaistPivotProfile {
324
+ columns: number[];
325
+ topRows: number[];
326
+ centre: [number, number];
327
+ lower: number;
328
+ hem: number;
329
+ }
330
+ export interface WaistPivotRequest {
331
+ top: string; bottom: string; upper: string; lower: string;
332
+ bone: string; constraint: string;
333
+ topOrigin: readonly [number, number]; bottomOrigin: readonly [number, number];
334
+ canvas: readonly [number, number];
335
+ }
336
+ interface PivotArt { width: number; height: number; data: ArrayLike<number> }
337
+ export function waistPivotProfile(top: PivotArt, bottom: PivotArt, topOrigin: readonly [number, number], bottomOrigin: readonly [number, number]): WaistPivotProfile {
338
+ for (const [name, art] of [['top', top], ['bottom', bottom]] as const) if (!Number.isSafeInteger(art.width) || !Number.isSafeInteger(art.height) || art.width < 1 || art.height < 1 || art.data.length !== art.width * art.height) fail('RIG_WAIST_PIVOT_SOURCE', name, 'requires the original nonempty alpha mask and integral dimensions');
339
+ const columns: number[] = [], topRows: number[] = [];
340
+ const painted = (a: PivotArt, origin: readonly [number, number], x: number, y: number): boolean => x >= origin[0] && x < origin[0] + a.width && y >= origin[1] && y < origin[1] + a.height && a.data[(y - origin[1]) * a.width + x - origin[0]] !== 0;
341
+ let hem = -1;
342
+ for (let y = 0; y < bottom.height; y++) for (let x = 0; x < bottom.width; x++) if (bottom.data[y * bottom.width + x] !== 0) hem = Math.max(hem, y + bottomOrigin[1]);
343
+ for (let x = Math.max(topOrigin[0], bottomOrigin[0]); x < Math.min(topOrigin[0] + top.width, bottomOrigin[0] + bottom.width); x++) {
344
+ let contact = false, first = -1;
345
+ for (let y = bottomOrigin[1]; y < bottomOrigin[1] + bottom.height; y++) if (painted(bottom, bottomOrigin, x, y)) { if (first < 0) first = y; if (painted(top, topOrigin, x, y)) contact = true; }
346
+ if (contact) { columns.push(x); topRows.push(first); }
347
+ }
348
+ if (columns.length === 0 || columns.some((x, i) => i > 0 && x !== columns[i - 1] + 1)) fail('RIG_WAIST_PIVOT_SOURCE', 'waist contact', `requires one contiguous original shared-alpha column run; found [${columns.join(',')}]`);
349
+ const left = columns[0], right = columns.at(-1) as number, full = Math.max(...topRows);
350
+ let lower = -1;
351
+ for (let y = full + 1; y < hem; y++) {
352
+ const xs: number[] = [];
353
+ for (let x = bottomOrigin[0]; x < bottomOrigin[0] + bottom.width; x++) if (painted(bottom, bottomOrigin, x, y)) xs.push(x);
354
+ if (xs.length > 0 && xs[0] < left && xs[xs.length - 1] > right) { lower = y; break; }
355
+ }
356
+ if (lower <= full || hem <= lower) fail('RIG_WAIST_PIVOT_SOURCE', 'waist lower span', `first full top row ${full}, first bilateral source expansion ${lower}, last painted hem ${hem}; require full < lower < hem, without a guessed band height`);
357
+ const cx = (left + right + 1) / 2, centreColumn = Math.floor(cx), cy = topRows[columns.indexOf(centreColumn)];
358
+ return { columns, topRows, centre: [cx, cy], lower, hem };
359
+ }
360
+ export interface WaistPivotResult {
361
+ mesh: MeshAttachment; bone: RigBone; constraint: Record<string, unknown>;
362
+ profile: WaistPivotProfile; mapping: WaistMapping; layout: LatticeMesh;
363
+ anchorWorld: [number, number];
364
+ }
365
+ const pivots = new WeakMap<MeshAttachment, WaistPivotResult>();
366
+ export const waistPivotOf = (mesh: MeshAttachment): WaistPivotResult | undefined => pivots.get(mesh);
367
+ /** The explicit 4.3 rotate-to-rotate contract; missing properties are not rotation. */
368
+ export function waistPivotConstraint(name: string, source: string, bone: string): Record<string, unknown> {
369
+ return { type: 'transform', name, source, bones: [bone], localSource: false, localTarget: false, additive: false,
370
+ properties: { rotate: { to: { rotate: {} } } }, mixRotate: 1, mixX: 0, mixY: 0, mixScaleX: 0, mixScaleY: 0, mixShearY: 0 };
371
+ }
372
+ /** Rebind only the supplied bottom. Original top, bones, motion and art are not mutated. */
373
+ export function pivotWaistMesh(old: MeshAttachment, oldLm: LatticeMesh, topArt: PivotArt, bottomArt: PivotArt, bones: readonly RigBone[], request: WaistPivotRequest): WaistPivotResult {
374
+ if (bones.some((b) => b.name === request.bone) || request.bone.length === 0 || request.constraint.length === 0) fail('RIG_WAIST_PIVOT_NAME', 'waist pivot', `bone "${request.bone}" must be new and constraint "${request.constraint}" nonempty`);
375
+ const world = storedWorld(bones), upper = world.get(request.upper), lower = world.get(request.lower);
376
+ // Eligibility measures the authored frame; inverse binding below keeps runtime arithmetic.
377
+ const authored = computeExactFrameTransforms(bones), frames = [authored.get(request.upper), authored.get(request.lower)];
378
+ if (upper === undefined || lower === undefined || frames.some((w) => w === undefined || w.a !== 1 || w.b !== 0 || w.c !== 0 || w.d !== 1)) fail('RIG_WAIST_PIVOT_FRAME', 'waist pivot', `requires declared unturned unit rest frames "${request.upper}"/"${request.lower}"; found authored ${JSON.stringify(frames)}; no constraint-blind inverse or baked animation adapter`);
379
+ const profile = waistPivotProfile(topArt, bottomArt, request.topOrigin, request.bottomOrigin);
380
+ const anchorWorld: [number, number] = [profile.centre[0] - request.canvas[0] / 2, cropToSpineY(profile.centre[1], request.canvas[1])];
381
+ const local = toBoneLocal(upper, ...anchorWorld), bone: RigBone = { name: request.bone, parent: request.upper, x: pyRound(local[0], 6), y: pyRound(local[1], 6) };
382
+ const layout = refineWaistMesh(oldLm, [profile.lower - request.bottomOrigin[1], profile.hem - request.bottomOrigin[1]]);
383
+ const mesh: MeshAttachment = { ...old, uvs: [], triangles: layout.triangles, hull: layout.hull, weights: layout.vertices.map(([, y]) => {
384
+ const t = pyRound(Math.max(0, Math.min(1, (y + request.bottomOrigin[1] - profile.lower) / (profile.hem - profile.lower))), 6);
385
+ return [{ bone: request.bone, x: 0, y: 0, weight: 1 - t }, { bone: request.lower, x: 0, y: 0, weight: t }].filter((w) => w.weight > 0);
386
+ }) };
387
+ const mapping = preserveWaistRest(old, oldLm, mesh, layout, storedWorld([...bones, bone]), -Infinity);
388
+ bottomLayouts.set(mesh, layout);
389
+ const result = { mesh, bone, constraint: waistPivotConstraint(request.constraint, request.lower, request.bone), profile, mapping, layout, anchorWorld };
390
+ pivots.set(mesh, result);
391
+ return result;
392
+ }
393
+
394
+ export interface WaistCopyResult {
395
+ mesh: MeshAttachment;
396
+ layout: LatticeMesh;
397
+ mapping: WaistMapping;
398
+ profile: WaistPivotProfile;
399
+ anchor: number;
400
+ oldToNew: number[];
401
+ upperTriangles: number[][];
402
+ storage: WaistCopyStorage;
403
+ }
404
+ const copies = new WeakMap<MeshAttachment, WaistCopyResult>();
405
+ export const waistCopyOf = (mesh: MeshAttachment): WaistCopyResult | undefined => copies.get(mesh);
406
+
407
+ /** The original stored UV field is the source domain; no regenerated lattice. */
408
+ export function suppliedWaistLayout(mesh: MeshAttachment): LatticeMesh {
409
+ const vertices = mesh.weights.map((_, i) => [mesh.uvs[2*i] * mesh.width, mesh.uvs[2*i+1] * mesh.height] as [number, number]);
410
+ return { vertices, triangles: mesh.triangles, hull: mesh.hull, loops: 1, pinchedVertices: 0, cells: 0, passes: 0 };
411
+ }
412
+ function copyPoints(profile: WaistPivotProfile, origin: readonly [number, number]): P[] {
413
+ return profile.columns.map((x, i) => point(x + 0.5 - origin[0], profile.topRows[i] - origin[1]));
414
+ }
415
+ function copyLine(x: Q, points: readonly P[]): Line {
416
+ if (sub(x, points[0][0])[0] <= 0n) return [q(0n), q(1n), mul(q(-1n), points[0][1])];
417
+ for (let i = 1; i < points.length; i++) if (sub(x, points[i][0])[0] <= 0n) return lineOf(points[i-1], points[i]);
418
+ return [q(0n), q(1n), mul(q(-1n), points.at(-1)![1])];
419
+ }
420
+ function copyHeight(x: number, points: readonly P[]): number {
421
+ const l = copyLine(decimal(x), points);
422
+ return number(div(mul(q(-1n), add(mul(l[0], decimal(x)), l[2])), l[1]));
423
+ }
424
+ /** Stronger than painted-cell sampling: no mixed triangle has positive area below C. */
425
+ export function waistCopyCoverage(vertices: readonly (readonly [number, number])[], triangles: readonly number[], onlyWaist: readonly boolean[], profile: WaistPivotProfile, origin: readonly [number, number]): { mixedTriangles: number[] } {
426
+ const pts = exactVertices.get(vertices) ?? vertices.map(([x,y]) => point(x,y)), points = copyPoints(profile, origin), mixedTriangles: number[] = [];
427
+ for (let t = 0; t < triangles.length; t += 3) {
428
+ const ids = triangles.slice(t,t+3);
429
+ if (ids.every(i => onlyWaist[i])) continue;
430
+ const poly = ids.map(i => pts[i]), xs = poly.map(p => p[0]).sort((a,b) => sub(a,b)[0] < 0n ? -1 : sub(a,b)[0] > 0n ? 1 : 0);
431
+ const cuts = [xs[0], ...points.map(p => p[0]).filter(x => sub(x,xs[0])[0] > 0n && sub(x,xs[2])[0] < 0n), xs[2]];
432
+ for (let i = 1; i < cuts.length; i++) {
433
+ let region = clip(poly, [q(1n),q(0n),mul(q(-1n),cuts[i-1])], 1n);
434
+ region = clip(region, [q(1n),q(0n),mul(q(-1n),cuts[i])], -1n);
435
+ region = clip(region, copyLine(div(add(cuts[i-1],cuts[i]),q(2n)),points), 1n);
436
+ if (twiceArea(region)[0] !== 0n) { mixedTriangles.push(t/3); break; }
437
+ }
438
+ }
439
+ return { mixedTriangles };
440
+ }
441
+
442
+ /** Actual runtime source UVs, kept as exact binary values for the coverage proof. */
443
+ export function nativeWaistCopyCoverage(uvs: readonly number[], triangles: readonly number[], onlyWaist: readonly boolean[], width: number, height: number, profile: WaistPivotProfile, origin: readonly [number, number]): { mixedTriangles: number[] } {
444
+ if(uvs.length!==2*onlyWaist.length)fail('RIG_WAIST_COPY_COVERAGE','native copy field','source UV/support populations differ');
445
+ const exact:P[]=onlyWaist.map((_,i)=>[mul(binary(uvs[2*i]),q(BigInt(width))),mul(binary(uvs[2*i+1]),q(BigInt(height)))]);
446
+ const vertices=exact.map(p=>p.map(number) as [number,number]);exactVertices.set(vertices,exact);
447
+ return waistCopyCoverage(vertices,triangles,onlyWaist,profile,origin);
448
+ }
449
+
450
+ export interface WaistCopyStorage {
451
+ normalizedCellBound: number;
452
+ sourceXBound: number;
453
+ sourceYBound: number;
454
+ maxSlope: number;
455
+ inward: number;
456
+ }
457
+ /**
458
+ * Core's f32 spelling and its input round to the SAME binary32. On [0,1],
459
+ * a complete rounding cell is at most 2^-23 wide (including the cell at 1).
460
+ * Thus |dx|<=width*2^-23 and |dy|<=height*2^-23. For Lipschitz C with
461
+ * constant L, y<=C(x)-(dyBound+L*dxBound) implies stored y'<=C(x').
462
+ * This moves support inward; it does not relax the proof's original C.
463
+ */
464
+ export function waistCopyStorage(profile: WaistPivotProfile, width: number, height: number): WaistCopyStorage {
465
+ const normalizedCellBound=2**-23;
466
+ const maxSlope=Math.max(0,...profile.topRows.slice(1).map((y,i)=>Math.abs(y-profile.topRows[i])/(profile.columns[i+1]-profile.columns[i])));
467
+ const sourceXBound=width*normalizedCellBound,sourceYBound=height*normalizedCellBound;
468
+ return{normalizedCellBound,sourceXBound,sourceYBound,maxSlope,inward:sourceYBound+maxSlope*sourceXBound};
469
+ }
470
+ /** Verify the precondition exactly for EVERY actual UV, including arithmetic before f32. */
471
+ export function waistCopyStorageViolations(vertices: readonly (readonly [number,number])[], uvs: readonly number[], width: number, height: number): number[] {
472
+ const pts=exactVertices.get(vertices)??vertices.map(([x,y])=>point(x,y)),outside:number[]=[];
473
+ for(let i=0;i<pts.length;i++)for(const k of[0,1]){
474
+ const uv=uvs[2*i+k],size=k===0?width:height;
475
+ if(!Number.isFinite(uv)||uv<0||uv>1){outside.push(i);break;}
476
+ const delta=sub(mul(binary(f32(uv)),q(BigInt(size))),pts[i][k]);
477
+ const abs=q(delta[0]<0n?-delta[0]:delta[0],delta[1]);
478
+ if(sub(abs,q(BigInt(size),1n<<23n))[0]>0n){outside.push(i);break;}
479
+ }
480
+ return outside;
481
+ }
482
+
483
+ /** Only lower polygons are subdivided. Interface points are propagated below A. */
484
+ function copyArrangement(old: LatticeMesh, anchor: number, points: readonly P[]): Arrangement {
485
+ const upper: P[][] = [], blend: P[][] = [], lower: P[][] = [];
486
+ const floor = points.reduce((a,p) => sub(p[1],a)[0] < 0n ? p[1] : a, points[0][1]);
487
+ const horizontal: Line = [q(0n),q(1n),mul(q(-1n),floor)];
488
+ for (const poly of polygons(old.vertices,old.triangles)) {
489
+ const ys = poly.map(p => number(p[1]));
490
+ if (Math.max(...ys) <= anchor) { upper.push(poly); continue; }
491
+ if (Math.min(...ys) < anchor) fail('RIG_WAIST_COPY_SOURCE', 'stored upper boundary', `triangle ${JSON.stringify(poly.map(p=>p.map(number)))} crosses existing row ${anchor}; no upper field refinement is allowed`);
492
+ for (const part of split([poly],horizontal)) {
493
+ if (part.every(p => sub(p[1],floor)[0] >= 0n)) lower.push(part); else blend.push(part);
494
+ }
495
+ }
496
+ let slabs = lower;
497
+ for (const p of points) slabs = split(slabs,[q(1n),q(0n),mul(q(-1n),p[0])]);
498
+ const below = slabs.flatMap(poly => {
499
+ const x = div(poly.reduce((sum,p)=>add(sum,p[0]),q(0n)),q(BigInt(poly.length)));
500
+ return split([poly],copyLine(x,points));
501
+ });
502
+ const interfacePoints = new Map<string,P>();
503
+ for (const poly of below) for (const p of poly) if (sub(p[1],floor)[0] === 0n) interfacePoints.set(key(p),p);
504
+ const stitched = blend.map(poly => poly.flatMap((p,i) => {
505
+ const next=poly[(i+1)%poly.length];
506
+ if (sub(p[1],floor)[0] !== 0n || sub(next[1],floor)[0] !== 0n) return [p];
507
+ const direction=sub(next[0],p[0])[0];
508
+ const inside=[...interfacePoints.values()].filter(v=>sub(v[0],p[0])[0]*direction>0n && sub(next[0],v[0])[0]*direction>0n);
509
+ inside.sort((a,b)=>sub(a[0],b[0])[0]*direction<0n?-1:sub(a[0],b[0])[0]*direction>0n?1:0);
510
+ return [p,...inside];
511
+ }));
512
+ return arrangement([...upper,...stitched,...below]);
513
+ }
514
+
515
+ /** Transfer only the supplied top to an existing waist frame, preserving original moments. */
516
+ export function sharedWaistCopy(old: MeshAttachment, topArt: PivotArt, bottomArt: PivotArt, bones: readonly RigBone[], request: WaistPivotRequest): WaistCopyResult {
517
+ const world=storedWorld(bones),W=world.get(request.bone),oldLm=suppliedWaistLayout(old),profile=waistPivotProfile(topArt,bottomArt,request.topOrigin,request.bottomOrigin),originalPoints=copyPoints(profile,request.topOrigin),storage=waistCopyStorage(profile,old.width,old.height);
518
+ const points:P[]=originalPoints.map(p=>[p[0],sub(p[1],binary(storage.inward))]);
519
+ if (W===undefined || old.weights.some(ws=>ws.some(w=>w.bone===request.bone))) fail('RIG_WAIST_COPY_FRAME','shared waist copy',`existing frame "${request.bone}" is required and original top must not already use it`);
520
+ const authored=computeExactFrameTransforms(bones);
521
+ for(const name of[request.upper,request.lower,request.bone]){const f=authored.get(name);if(!f||f.a!==1||f.b!==0||f.c!==0||f.d!==1)fail('RIG_WAIST_COPY_FRAME','shared waist copy',`requires original authored unit rest frame "${name}", found ${JSON.stringify(f)}`);}
522
+ const first=Math.min(...profile.topRows)-request.topOrigin[1],rows=oldLm.vertices.map(p=>p[1]).filter(y=>y<first);
523
+ if (!rows.length) fail('RIG_WAIST_COPY_SOURCE','shared waist copy',`no existing source row strictly above copy edge ${first+request.topOrigin[1]}`);
524
+ const anchor=Math.max(...rows),a=copyArrangement(oldLm,anchor,points),layout={...oldLm,vertices:a.vertices,triangles:a.triangles,hull:a.hull};
525
+ if(Math.min(...points.map(p=>number(p[1])))<=anchor)fail('RIG_WAIST_COPY_SOURCE','copy storage support',`derived inward boundary no longer lies above existing upper anchor ${anchor}`);
526
+ const oldIds=new Map(oldLm.vertices.map((p,i)=>[key(point(...p)),i])),oldToNew=oldLm.vertices.map(()=>-1),source:Correspondence[]=[],before=old.weights.map(ws=>nativePoint(ws,world)),uvs:number[]=[],weights:WeightEntry[][]=[],positions=layout.vertices;
527
+ let maxRestResidual=0,maxUvStorageResidual=0;
528
+ for (let i=0;i<a.exact.length;i++) {
529
+ const p=a.exact[i],original=oldIds.get(key(p)),hit=original===undefined?locate(p,oldLm.vertices,oldLm.triangles):{indices:[original],barycentric:[1]};
530
+ if (hit===null) fail('RIG_WAIST_COPY_SOURCE','shared waist copy',`derived point ${JSON.stringify(p.map(number))} is outside original triangles`);
531
+ source.push(hit);if(original!==undefined)oldToNew[original]=i;
532
+ const target:[number,number]=[interpolate(hit,before.map(p=>p[0])),interpolate(hit,before.map(p=>p[1]))];
533
+ const x=number(p[0]),y=number(p[1]),edge=copyHeight(x,points),l=copyLine(p[0],points);
534
+ const t=y<=anchor?0:at(l,p)[0]>=0n?1:(y-anchor)/(edge-anchor),s=t*t*(3-2*t),moments=waistMoments(old,hit);
535
+ const local=toBoneLocal(W,...target);
536
+ const bound=original!==undefined&&y<=anchor?old.weights[original].map(w=>({...w})):s===0?moments:[...moments.map(w=>({...w,weight:w.weight*(1-s)})).filter(w=>w.weight>0),{bone:request.bone,x:pyRound(local[0],6),y:pyRound(local[1],6),weight:s}];
537
+ weights.push(bound);
538
+ for(const axis of[0,1]){const uv=original===undefined?interpolate(hit,old.weights.map((_,v)=>old.uvs[2*v+axis])):old.uvs[2*original+axis];uvs.push(uv);maxUvStorageResidual=Math.max(maxUvStorageResidual,Math.abs(Math.fround(uv)-uv));}
539
+ const actual=nativePoint(bound,world);maxRestResidual=Math.max(maxRestResidual,Math.abs(actual[0]-target[0]),Math.abs(actual[1]-target[1]));
540
+ }
541
+ if(oldToNew.some(i=>i<0))fail('RIG_WAIST_COPY_SOURCE','shared waist copy','an original support vertex was lost');
542
+ const storageOutside=waistCopyStorageViolations(positions,uvs,old.width,old.height);
543
+ if(storageOutside.length)fail('RIG_WAIST_COPY_COVERAGE','copy storage contract',`source UV vertex(s) ${storageOutside.join(',')} exceed the core float32 rounding-cell bound`);
544
+ const mesh:MeshAttachment={...old,uvs,weights,triangles:a.triangles,hull:a.hull},proof=waistCopyCoverage(positions,a.triangles,weights.map(ws=>ws.length===1&&ws[0].bone===request.bone&&ws[0].weight===1),profile,request.topOrigin);
545
+ if(proof.mixedTriangles.length)fail('RIG_WAIST_COPY_COVERAGE','shared waist copy',`non-W triangle(s) ${proof.mixedTriangles.join(',')} overlap copy support below source C`);
546
+ const upperTriangles:number[][]=[];
547
+ for(let t=0;t<old.triangles.length;t+=3){const ids=old.triangles.slice(t,t+3);if(ids.every(i=>oldLm.vertices[i][1]<=anchor))upperTriangles.push(ids);}
548
+ const actualTriangles=new Set(Array.from({length:a.triangles.length/3},(_,t)=>a.triangles.slice(3*t,3*t+3).sort((x,y)=>x-y).join(',')));
549
+ for(const ids of upperTriangles)if(!actualTriangles.has(ids.map(i=>oldToNew[i]).sort((x,y)=>x-y).join(',')))fail('RIG_WAIST_COPY_SOURCE','upper field',`original triangle [${ids.join(',')}] was changed above row ${anchor}`);
550
+ for(let i=0;i<old.weights.length;i++)if(oldLm.vertices[i][1]<=anchor){const n=oldToNew[i];if(JSON.stringify(old.weights[i])!==JSON.stringify(weights[n])||old.uvs[2*i]!==uvs[2*n]||old.uvs[2*i+1]!==uvs[2*n+1])fail('RIG_WAIST_COPY_SOURCE','upper field',`original vertex ${i} binding or UV changed above row ${anchor}`);}
551
+ const mapping={old,current:mesh,source,positions,maxRestResidual,maxUvStorageResidual},result={mesh,layout,mapping,profile,anchor:anchor+request.topOrigin[1],oldToNew,upperTriangles,storage};
552
+ mappings.set(mesh,mapping);copies.set(mesh,result);return result;
553
+ }