@rig-c/parts 1.61.0 → 1.63.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.
package/src/check.ts CHANGED
@@ -79,7 +79,7 @@
79
79
  */
80
80
  import { createHash } from 'node:crypto';
81
81
  import { createRequire } from 'node:module';
82
- import type { Frame as RootCoverageFrame, Piece as RootCoveragePiece, Viewport as RootCoverageViewport } from 'rig-c/render-shared';
82
+ import type { Viewport as RootCoverageViewport } from 'rig-c/render-shared';
83
83
  import { copyFileSync, cpSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
84
84
  import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
85
85
  import { measureRecomposite, type RecompositeFigures, recompositeRecord, scenePhrase, sourceInRig } from './assemble.ts';
@@ -164,7 +164,10 @@ import {
164
164
  import { RIG_BONE_INHERIT, type RigSpec as RigcRigSpec } from 'rig-c/src/rig.ts';
165
165
  import { expandStops } from 'rig-c/src/stop.ts';
166
166
  import { ENVIRONMENT_SPEC, EnvironmentError, environmentResponse, readEnvironmentSchedule } from 'rig-c/src/environment.ts';
167
+ import { ART_ALPHA } from './mesh.ts';
168
+ import { connectedComponents } from './raster/components.ts';
167
169
  import { alphaComposite } from './raster/composite.ts';
170
+ import { alphaAbove } from './raster/index.ts';
168
171
  import { readPng, writePng } from './raster/png.ts';
169
172
  import { newFloatImage, newRaster, type Raster } from './raster/types.ts';
170
173
  import type { BaseTag } from './tags.ts';
@@ -1240,16 +1243,180 @@ export interface SeamFigures {
1240
1243
  map: { sx: number; sy: number; tx: number; ty: number };
1241
1244
  }
1242
1245
 
1246
+ /**
1247
+ * Partition a multi-island part's raster into one raster per declared island
1248
+ * slot (`<part>`, `<part>__island2..<part>__island<N>`), ordered by descending
1249
+ * `alpha > ART_ALPHA` 4-connected component area (tie-broken by ascending
1250
+ * row-major label). Anti-aliased fringe pixels (`1 <= alpha <= ART_ALPHA`)
1251
+ * propagate from their connected island seed via 4-connected BFS over
1252
+ * `alpha > 0`, with any disconnected sub-threshold pixel assigned to the
1253
+ * nearest seed centroid so every non-transparent pixel of `image` lands in
1254
+ * exactly one island raster.
1255
+ */
1256
+ export function splitPartIslands(image: Raster, count: number): Raster[] {
1257
+ if (count <= 1) return [image];
1258
+ const { width, height, data } = image;
1259
+ const cc = connectedComponents(alphaAbove(image, ART_ALPHA), 4);
1260
+ const seeds = cc.stats
1261
+ .slice(1)
1262
+ .sort((a, b) => b.area - a.area || a.label - b.label)
1263
+ .slice(0, count);
1264
+ if (seeds.length <= 1) return [image];
1265
+ const owner = new Int16Array(width * height).fill(-1);
1266
+ const labelToSeed = new Int16Array(cc.count + 1).fill(-1);
1267
+ seeds.forEach((s, idx) => {
1268
+ labelToSeed[s.label] = idx;
1269
+ });
1270
+ const queue = new Int32Array(width * height);
1271
+ let head = 0;
1272
+ let tail = 0;
1273
+ for (let i = 0; i < width * height; i++) {
1274
+ const seedIdx = labelToSeed[cc.labels[i]];
1275
+ if (seedIdx >= 0) {
1276
+ owner[i] = seedIdx;
1277
+ queue[tail++] = i;
1278
+ }
1279
+ }
1280
+ while (head < tail) {
1281
+ const cur = queue[head++];
1282
+ const seedIdx = owner[cur];
1283
+ const x = cur % width;
1284
+ const y = (cur - x) / width;
1285
+ if (x > 0) {
1286
+ const n = cur - 1;
1287
+ if (owner[n] < 0 && data[n * 4 + 3] > 0) {
1288
+ owner[n] = seedIdx;
1289
+ queue[tail++] = n;
1290
+ }
1291
+ }
1292
+ if (x + 1 < width) {
1293
+ const n = cur + 1;
1294
+ if (owner[n] < 0 && data[n * 4 + 3] > 0) {
1295
+ owner[n] = seedIdx;
1296
+ queue[tail++] = n;
1297
+ }
1298
+ }
1299
+ if (y > 0) {
1300
+ const n = cur - width;
1301
+ if (owner[n] < 0 && data[n * 4 + 3] > 0) {
1302
+ owner[n] = seedIdx;
1303
+ queue[tail++] = n;
1304
+ }
1305
+ }
1306
+ if (y + 1 < height) {
1307
+ const n = cur + width;
1308
+ if (owner[n] < 0 && data[n * 4 + 3] > 0) {
1309
+ owner[n] = seedIdx;
1310
+ queue[tail++] = n;
1311
+ }
1312
+ }
1313
+ }
1314
+ const out = Array.from({ length: count }, () => newRaster(width, height));
1315
+ for (let y = 0; y < height; y++) {
1316
+ for (let x = 0; x < width; x++) {
1317
+ const i = y * width + x;
1318
+ const p = i * 4;
1319
+ if (data[p + 3] === 0) continue;
1320
+ let idx = owner[i];
1321
+ if (idx < 0) {
1322
+ let best = 0;
1323
+ let bestD2 = Infinity;
1324
+ seeds.forEach((s, si) => {
1325
+ const dx = x - s.cx;
1326
+ const dy = y - s.cy;
1327
+ const d2 = dx * dx + dy * dy;
1328
+ if (d2 < bestD2) {
1329
+ bestD2 = d2;
1330
+ best = si;
1331
+ }
1332
+ });
1333
+ idx = best;
1334
+ }
1335
+ out[idx].data.set(data.subarray(p, p + 4), p);
1336
+ }
1337
+ }
1338
+ return out;
1339
+ }
1340
+
1341
+ export interface ReferencePlacement {
1342
+ name: string;
1343
+ png: string;
1344
+ box: PartRecord;
1345
+ islandIndex?: number;
1346
+ islandCount?: number;
1347
+ }
1348
+
1349
+ function partIslandSlots(part: string, slotOrder?: readonly string[]): string[] {
1350
+ if (slotOrder === undefined || !slotOrder.includes(`${part}__island2`)) return [part];
1351
+ const out = [part];
1352
+ for (let k = 2; slotOrder.includes(`${part}__island${k}`); k++) {
1353
+ out.push(`${part}__island${k}`);
1354
+ }
1355
+ return out;
1356
+ }
1357
+
1358
+ export function resolvePlacedAlpha(placements: readonly ReferencePlacement[], partsDir: string): PlacedAlpha[] {
1359
+ const rawCache = new Map<string, Raster>();
1360
+ const splitCache = new Map<string, Raster[]>();
1361
+ const readRaw = (png: string): Raster => {
1362
+ const hit = rawCache.get(png);
1363
+ if (hit !== undefined) return hit;
1364
+ const img = readPng(join(partsDir, `${png}.png`));
1365
+ rawCache.set(png, img);
1366
+ return img;
1367
+ };
1368
+ return placements.map((pl) => {
1369
+ const raw = readRaw(pl.png);
1370
+ if (pl.islandCount !== undefined && pl.islandCount > 1 && pl.islandIndex !== undefined) {
1371
+ const key = `${pl.png}:${pl.islandCount}`;
1372
+ let islands = splitCache.get(key);
1373
+ if (islands === undefined) {
1374
+ islands = splitPartIslands(raw, pl.islandCount);
1375
+ splitCache.set(key, islands);
1376
+ }
1377
+ return { name: pl.name, from: pl.box.from, x: pl.box.x, y: pl.box.y, image: islands[pl.islandIndex] ?? raw };
1378
+ }
1379
+ return { name: pl.name, from: pl.box.from, x: pl.box.x, y: pl.box.y, image: raw };
1380
+ });
1381
+ }
1382
+
1383
+ export function basePlacements(parts: PartsFile, slotOrder?: readonly string[]): ReferencePlacement[] {
1384
+ return setPlacements(
1385
+ parts,
1386
+ {
1387
+ name: '',
1388
+ slots: {},
1389
+ records: [],
1390
+ ghost_px: {},
1391
+ recomposite: parts.recomposite ?? {
1392
+ mean_abs: 0,
1393
+ within_limit: 0,
1394
+ within_share: 1,
1395
+ error_limit: 0,
1396
+ error_px: 0,
1397
+ covered_alpha: 0,
1398
+ uncovered_error_px: 0,
1399
+ hole_count: 0,
1400
+ holes_listed: 0,
1401
+ holes: [],
1402
+ },
1403
+ },
1404
+ slotOrder,
1405
+ );
1406
+ }
1407
+
1243
1408
  /**
1244
1409
  * The flat stack of parts over the background, in rig pixels: PIL's
1245
- * `alpha_composite` of every part at its `x, y`, in parts.json order, over an
1246
- * opaque canvas of the render's own background colour.
1410
+ * `alpha_composite` of every part at its `x, y`, in parts.json order (with
1411
+ * multi-island explicit slots placed at their declared `slotOrder` positions
1412
+ * when `slotOrder` is supplied), over an opaque canvas of the render's own
1413
+ * background colour.
1247
1414
  */
1248
- export function flatComposite(parts: PartsFile, partsDir: string, background: readonly [number, number, number, number]): Raster {
1415
+ export function flatComposite(parts: PartsFile, partsDir: string, background: readonly [number, number, number, number], slotOrder?: readonly string[]): Raster {
1249
1416
  const [W, H] = parts.rig_size;
1250
1417
  let canvas = newRaster(W, H);
1251
1418
  for (let i = 0; i < W * H; i++) canvas.data.set(background, i * 4);
1252
- for (const p of parts.parts) canvas = alphaComposite(canvas, readPng(join(partsDir, `${p.name}.png`)), p.x, p.y);
1419
+ for (const p of resolvePlacedAlpha(basePlacements(parts, slotOrder), partsDir)) canvas = alphaComposite(canvas, p.image, p.x, p.y);
1253
1420
  return canvas;
1254
1421
  }
1255
1422
 
@@ -1260,9 +1427,11 @@ export function flatComposite(parts: PartsFile, partsDir: string, background: re
1260
1427
  * slot (`alt.front`) is drawn from its record although `alt.hides` names it (the
1261
1428
  * hide is its base slot's) — with `slotOrder`, the rig's final setup slot names,
1262
1429
  * right after the nearest part slot before `<part>_front` there; without it (or
1263
- * with no such slot), in its own place, as the base slot would draw it.
1430
+ * with no such slot), in its own place, as the base slot would draw it. When
1431
+ * `slotOrder` names multi-island explicit slots (`<part>__island2..<part>__island<N>`),
1432
+ * each island's placement follows its declared slot position in `slotOrder`.
1264
1433
  */
1265
- export function setPlacements(parts: PartsFile, alt: AlternatePartsRecord, slotOrder?: readonly string[]): Array<{ name: string; png: string; box: PartRecord }> {
1434
+ export function setPlacements(parts: PartsFile, alt: AlternatePartsRecord, slotOrder?: readonly string[]): ReferencePlacement[] {
1266
1435
  const hides = new Set(alt.hides ?? []);
1267
1436
  const front = new Set(alt.front ?? []);
1268
1437
  const byName = new Map(alt.records.map((r) => [r.name, r]));
@@ -1281,18 +1450,73 @@ export function setPlacements(parts: PartsFile, alt: AlternatePartsRecord, slotO
1281
1450
  }
1282
1451
  }
1283
1452
  const moved = [...after.keys()].sort((a, b) => (slotOrder as readonly string[]).indexOf(`${a}${FRONT_SUFFIX}`) - (slotOrder as readonly string[]).indexOf(`${b}${FRONT_SUFFIX}`));
1284
- const out: Array<{ name: string; png: string; box: PartRecord }> = [];
1453
+ type PlacedIslandEntry = ReferencePlacement & { at: number };
1454
+ const inlineIslands = new Map<string, PlacedIslandEntry[]>();
1455
+ const beforeTarget = new Map<string | null, PlacedIslandEntry[]>();
1456
+ if (slotOrder !== undefined) {
1457
+ for (const p of parts.parts) {
1458
+ if (byName.has(p.name)) continue;
1459
+ const islandSlots = partIslandSlots(p.name, slotOrder);
1460
+ if (islandSlots.length <= 1) continue;
1461
+ const baseIdx = slotOrder.indexOf(p.name);
1462
+ for (let k = 1; k < islandSlots.length; k++) {
1463
+ const islSlot = islandSlots[k];
1464
+ if ((hides.has(p.name) && !front.has(p.name)) || hides.has(islSlot)) continue;
1465
+ const at = slotOrder.indexOf(islSlot);
1466
+ let reordered = at < baseIdx;
1467
+ if (!reordered) {
1468
+ for (let j = baseIdx + 1; j < at; j++) {
1469
+ if (partNames.has(slotOrder[j]) && !after.has(slotOrder[j])) {
1470
+ reordered = true;
1471
+ break;
1472
+ }
1473
+ }
1474
+ }
1475
+ const entry: PlacedIslandEntry = { name: islSlot, png: p.name, box: p, islandIndex: k, islandCount: islandSlots.length, at };
1476
+ if (!reordered) {
1477
+ const list = inlineIslands.get(p.name) ?? [];
1478
+ list.push(entry);
1479
+ inlineIslands.set(p.name, list);
1480
+ } else {
1481
+ let target: string | null = null;
1482
+ for (let j = at + 1; j < slotOrder.length; j++) {
1483
+ if (partNames.has(slotOrder[j]) && !after.has(slotOrder[j])) {
1484
+ target = slotOrder[j];
1485
+ break;
1486
+ }
1487
+ }
1488
+ const list = beforeTarget.get(target) ?? [];
1489
+ list.push(entry);
1490
+ beforeTarget.set(target, list);
1491
+ }
1492
+ }
1493
+ }
1494
+ for (const list of inlineIslands.values()) list.sort((a, b) => a.at - b.at);
1495
+ for (const list of beforeTarget.values()) list.sort((a, b) => a.at - b.at);
1496
+ }
1497
+ const out: ReferencePlacement[] = [];
1498
+ const pushIsland = ({ at: _at, ...pl }: PlacedIslandEntry): void => {
1499
+ out.push(pl);
1500
+ };
1285
1501
  const draw = (name: string, base: PartRecord): void => {
1286
1502
  if (hides.has(name) && !front.has(name)) return;
1287
1503
  const rec = byName.get(name);
1504
+ const islandSlots = rec === undefined ? partIslandSlots(name, slotOrder) : [name];
1505
+ if (islandSlots.length > 1) {
1506
+ out.push({ name, png: name, box: base, islandIndex: 0, islandCount: islandSlots.length });
1507
+ for (const isl of inlineIslands.get(name) ?? []) pushIsland(isl);
1508
+ return;
1509
+ }
1288
1510
  out.push({ name, png: rec === undefined ? name : `${alt.name}_${rec.name}`, box: rec ?? base });
1289
1511
  };
1290
1512
  const baseOf = new Map(parts.parts.map((p) => [p.name, p]));
1291
1513
  for (const p of parts.parts) {
1292
1514
  if (after.has(p.name)) continue;
1515
+ for (const isl of beforeTarget.get(p.name) ?? []) pushIsland(isl);
1293
1516
  draw(p.name, p);
1294
1517
  for (const m of moved) if (after.get(m) === p.name) draw(m, baseOf.get(m) as PartRecord);
1295
1518
  }
1519
+ for (const isl of beforeTarget.get(null) ?? []) pushIsland(isl);
1296
1520
  return out;
1297
1521
  }
1298
1522
 
@@ -1328,16 +1552,17 @@ export function flatCompositeForSet(parts: PartsFile, alt: AlternatePartsRecord,
1328
1552
  const [W, H] = parts.rig_size;
1329
1553
  let canvas = newRaster(W, H);
1330
1554
  for (let i = 0; i < W * H; i++) canvas.data.set(background, i * 4);
1331
- for (const { png, box } of setPlacements(parts, alt, slotOrder)) canvas = alphaComposite(canvas, readPng(join(partsDir, `${png}.png`)), box.x, box.y);
1555
+ for (const p of resolvePlacedAlpha(setPlacements(parts, alt, slotOrder), partsDir)) canvas = alphaComposite(canvas, p.image, p.x, p.y);
1332
1556
  return canvas;
1333
1557
  }
1334
1558
 
1335
1559
  /**
1336
1560
  * The setup-pose rig spec with an alternate set applied (issues #454, #465):
1337
- * hidden slots (and `<slot>_still` for any hidden or covered slot) have no
1338
- * setup attachment, covered slots have `alt.slots[slot]`, and when the set
1339
- * carries `drawn` bone rotations its bones are posed at those world rotations
1340
- * so the throwaway still renders the alternate in the pose it was painted in.
1561
+ * hidden slots (and `<slot>_still` or `<slot>__island<k>` for any hidden or
1562
+ * covered slot) have no setup attachment, covered slots have `alt.slots[slot]`,
1563
+ * and when the set carries `drawn` bone rotations its bones are posed at those
1564
+ * world rotations so the throwaway still renders the alternate in the pose it
1565
+ * was painted in.
1341
1566
  */
1342
1567
  export function stillRigForSet(
1343
1568
  rig: Record<string, unknown>,
@@ -1348,7 +1573,13 @@ export function stillRigForSet(
1348
1573
  const slots = (Array.isArray(rig.slots) ? rig.slots : []).map((s) => {
1349
1574
  if (!isRecord(s) || typeof s.name !== 'string') return s;
1350
1575
  const stillBase = s.name.endsWith('_still') ? s.name.slice(0, -'_still'.length) : null;
1351
- if (hides.has(s.name) || (stillBase !== null && (hides.has(stillBase) || Object.hasOwn(alt.slots, stillBase)))) {
1576
+ const islandMatch = /^(.+)__island[2-9]\d*$/.exec(s.name);
1577
+ const islandBase = islandMatch !== null ? islandMatch[1] : null;
1578
+ if (
1579
+ hides.has(s.name) ||
1580
+ (stillBase !== null && (hides.has(stillBase) || Object.hasOwn(alt.slots, stillBase))) ||
1581
+ (islandBase !== null && (hides.has(islandBase) || Object.hasOwn(alt.slots, islandBase)))
1582
+ ) {
1352
1583
  return { ...s, attachment: null };
1353
1584
  }
1354
1585
  if (Object.hasOwn(alt.slots, s.name)) return { ...s, attachment: alt.slots[s.name] };
@@ -1461,6 +1692,7 @@ export function seamFigures(
1461
1692
  scene = false,
1462
1693
  effect?: Uint8Array,
1463
1694
  sourceGrid = false,
1695
+ observe?: (pixel: number, map: ScaleTranslate) => void,
1464
1696
  ): SeamFigures {
1465
1697
  const [W, H] = [composite.width, composite.height];
1466
1698
  const src = newFloatImage(W, H, 3);
@@ -1497,16 +1729,17 @@ export function seamFigures(
1497
1729
  const edgeCol = scene ? Array.from({ length: vp.pixelWidth }, (_, x) => onEdge(x, map.tx, map.sx, W)) : null;
1498
1730
  const edgeRow = scene ? Array.from({ length: vp.pixelHeight }, (_, y) => onEdge(y, map.ty, map.sy, H)) : null;
1499
1731
  for (let p = 0; p < n; p++) {
1732
+ const u = p % vp.pixelWidth - map.tx, v = Math.floor(p / vp.pixelWidth) - map.ty;
1733
+ const excluded = sourceGrid && scene
1734
+ ? u < 0 || v < 0 || u >= W || v >= H || onEdge(u, 0, 1, W) || onEdge(v, 0, 1, H)
1735
+ : edgeCol !== null && edgeRow !== null && (edgeCol[p % vp.pixelWidth] || edgeRow[Math.floor(p / vp.pixelWidth)]);
1736
+ if (!excluded && (effect === undefined || effect[p] !== 0)) observe?.(p, map);
1500
1737
  let m = 0;
1501
1738
  for (let c = 0; c < 3; c++) {
1502
1739
  const w = Math.fround(warped.data[p * 3 + c] + background[c]);
1503
1740
  const d = Math.abs(w - frame.data[p * 4 + c]);
1504
1741
  if (d > m) m = d;
1505
1742
  }
1506
- const u = p % vp.pixelWidth - map.tx, v = Math.floor(p / vp.pixelWidth) - map.ty;
1507
- const excluded = sourceGrid && scene
1508
- ? u < 0 || v < 0 || u >= W || v >= H || onEdge(u, 0, 1, W) || onEdge(v, 0, 1, H)
1509
- : edgeCol !== null && edgeRow !== null && (edgeCol[p % vp.pixelWidth] || edgeRow[Math.floor(p / vp.pixelWidth)]);
1510
1743
  if (excluded) {
1511
1744
  borderPx++;
1512
1745
  if (m > SEAM_PX_LEVEL) borderOver40++;
@@ -1851,6 +2084,8 @@ export interface SeamScope {
1851
2084
  effects?: SeamEffects['reasons'];
1852
2085
  changes?: SeamEffects['changes'];
1853
2086
  unavailable?: SeamSupportUnavailable;
2087
+ /** Every actually observed pre-threshold reference contributor category, not error-only rows. */
2088
+ population?: SeamPopulation;
1854
2089
  whole_pairs?: Array<Omit<SeamPairRow, 'picture'>>;
1855
2090
  pairs?: Array<{ parts: [string, string]; whole_px_over_40: number; affected_px_over_40: number; inherited_px_over_40: number; reasons: Partial<SeamEffects['reasons']> }>;
1856
2091
  }
@@ -1936,13 +2171,30 @@ export interface PlacedAlpha {
1936
2171
  image: Raster;
1937
2172
  }
1938
2173
 
1939
- /**
1940
- * Split the seam's counted pixels by the pair of parts that answers for each
1941
- * ({@link SeamPairRow}), worst first: by `px_over_40` descending, ties by the
1942
- * pair's names in draw order. `parts` is parts.json's list in its order, each
1943
- * with its image as assembled.
1944
- */
1945
- export function seamPairRows(seam: SeamFigures, parts: readonly PlacedAlpha[], rigSize: readonly [number, number], vp: Viewport): Array<{ row: SeamPairRow; pixels: number[] }> {
2174
+ /** Actual included source-grid sample support, independent of RGB error. */
2175
+ export interface SeamPopulationCounts {
2176
+ whole_sample_px: number;
2177
+ scope_sample_px: number;
2178
+ inherited_sample_px: number;
2179
+ }
2180
+
2181
+ export interface SeamPopulation {
2182
+ basis: 'reference-alpha/top-two-of-2x2';
2183
+ measured_sample_px: number;
2184
+ pair_count: number;
2185
+ pairs: Array<SeamPopulationCounts & { parts: [string, string] }>;
2186
+ single_art: Array<SeamPopulationCounts & { part: string }>;
2187
+ no_reference_art: SeamPopulationCounts;
2188
+ }
2189
+
2190
+ interface SeamReferenceSample {
2191
+ first: number; second: number; u0: number; v0: number;
2192
+ rx0: number; ry0: number; rx1: number; ry1: number;
2193
+ read: Array<[number, number]>;
2194
+ }
2195
+
2196
+ /** The existing 2x2 reference attribution; no posed ownership or anatomical pair is inferred. */
2197
+ function seamReferenceAttribution(parts: readonly PlacedAlpha[], rigSize: readonly [number, number], vp: Viewport) {
1946
2198
  const [W, H] = rigSize;
1947
2199
  // Each rig pixel's two topmost parts with art there (-1 for none): the top two of a union of pixels are among each pixel's own top two.
1948
2200
  const top = new Int32Array(W * H).fill(-1);
@@ -1961,7 +2213,93 @@ export function seamPairRows(seam: SeamFigures, parts: readonly PlacedAlpha[], r
1961
2213
  }
1962
2214
  }
1963
2215
  });
1964
- const { sx, sy, tx, ty } = seam.map;
2216
+ const sample: SeamReferenceSample = { first: -1, second: -1, u0: 0, v0: 0, rx0: 0, ry0: 0, rx1: 0, ry1: 0, read: [] };
2217
+ return (p: number, map: ScaleTranslate, details = false): SeamReferenceSample => {
2218
+ const fx = p % vp.pixelWidth, fy = Math.floor(p / vp.pixelWidth);
2219
+ const { sx, sy, tx, ty } = map;
2220
+ const u0 = Math.floor((fx - tx) / sx), v0 = Math.floor((fy - ty) / sy);
2221
+ let first = -1, second = -1;
2222
+ const read = sample.read; read.length = 0;
2223
+ let rx0 = Infinity, ry0 = Infinity, rx1 = -Infinity, ry1 = -Infinity;
2224
+ for (let dv = 0; dv < 2; dv++) {
2225
+ for (let du = 0; du < 2; du++) {
2226
+ const u = u0 + du, v = v0 + dv;
2227
+ if (u < 0 || u >= W || v < 0 || v >= H) continue;
2228
+ if (details) read.push([u, v]);
2229
+ rx0 = Math.min(rx0, u); ry0 = Math.min(ry0, v);
2230
+ rx1 = Math.max(rx1, u); ry1 = Math.max(ry1, v);
2231
+ for (let layer = 0; layer < 2; layer++) {
2232
+ const k = layer === 0 ? top[v * W + u] : next[v * W + u];
2233
+ if (k < 0 || k === first || k === second) continue;
2234
+ if (k > first) { second = first; first = k; }
2235
+ else if (k > second) second = k;
2236
+ }
2237
+ }
2238
+ }
2239
+ if (rx1 < rx0) {
2240
+ rx0 = rx1 = Math.min(Math.max(u0, 0), W - 1);
2241
+ ry0 = ry1 = Math.min(Math.max(v0, 0), H - 1);
2242
+ }
2243
+ sample.first = first; sample.second = second; sample.u0 = u0; sample.v0 = v0;
2244
+ sample.rx0 = rx0; sample.ry0 = ry0; sample.rx1 = rx1; sample.ry1 = ry1;
2245
+ return sample;
2246
+ };
2247
+ }
2248
+
2249
+ /**
2250
+ * Observe only cells the existing seam loop actually includes. The callback has
2251
+ * no RGB argument: membership cannot be selected from threshold-error pixels.
2252
+ * Source-grid background is a bucket, not a fabricated two-part pair. Counted
2253
+ * residuals still use their old NO_ART attribution, boxes and pictures.
2254
+ */
2255
+ export function createSeamPopulation(parts: readonly PlacedAlpha[], rigSize: readonly [number, number], vp: Viewport, scope?: Uint8Array) {
2256
+ const at = seamReferenceAttribution(parts, rigSize, vp);
2257
+ const counts = (): SeamPopulationCounts => ({ whole_sample_px: 0, scope_sample_px: 0, inherited_sample_px: 0 });
2258
+ const pairs = new Map<number, Map<number, SeamPopulationCounts & { parts: [string, string] }>>();
2259
+ const singles = new Map<number, SeamPopulationCounts & { part: string }>();
2260
+ const noArt = counts();
2261
+ let measured = 0;
2262
+ return {
2263
+ observe: (p: number, map: ScaleTranslate): void => {
2264
+ const { first: b, second: a } = at(p, map);
2265
+ let row: SeamPopulationCounts;
2266
+ if (a >= 0) {
2267
+ let lower = pairs.get(b);
2268
+ if (lower === undefined) { lower = new Map(); pairs.set(b, lower); }
2269
+ let pair = lower.get(a);
2270
+ if (pair === undefined) { pair = { parts: [parts[a].name, parts[b].name], ...counts() }; lower.set(a, pair); }
2271
+ row = pair;
2272
+ } else if (b >= 0) {
2273
+ let single = singles.get(b);
2274
+ if (single === undefined) { single = { part: parts[b].name, ...counts() }; singles.set(b, single); }
2275
+ row = single;
2276
+ } else row = noArt;
2277
+ measured++; row.whole_sample_px++;
2278
+ if (scope === undefined || scope[p] !== 0) row.scope_sample_px++;
2279
+ else row.inherited_sample_px++;
2280
+ },
2281
+ finish: (): SeamPopulation => {
2282
+ const rows = [...pairs.entries()].sort(([a], [b]) => a - b)
2283
+ .flatMap(([, lower]) => [...lower.entries()].sort(([a], [b]) => a - b).map(([, row]) => ({ ...row })));
2284
+ return { basis: 'reference-alpha/top-two-of-2x2', measured_sample_px: measured,
2285
+ pair_count: rows.length, pairs: rows,
2286
+ single_art: [...singles.entries()].sort(([a], [b]) => a - b).map(([, row]) => ({ ...row })),
2287
+ no_reference_art: { ...noArt } };
2288
+ },
2289
+ rows: (seam: SeamFigures) => seamPairRowsFrom(seam, parts, rigSize, vp, at),
2290
+ };
2291
+ }
2292
+
2293
+ /**
2294
+ * Split only counted error pixels into the existing diagnostic rows, worst
2295
+ * first; population metadata does not create zero-error boxes or pictures.
2296
+ */
2297
+ export function seamPairRows(seam: SeamFigures, parts: readonly PlacedAlpha[], rigSize: readonly [number, number], vp: Viewport): Array<{ row: SeamPairRow; pixels: number[] }> {
2298
+ return seamPairRowsFrom(seam, parts, rigSize, vp, seamReferenceAttribution(parts, rigSize, vp));
2299
+ }
2300
+
2301
+ function seamPairRowsFrom(seam: SeamFigures, parts: readonly PlacedAlpha[], rigSize: readonly [number, number], vp: Viewport, attribution: ReturnType<typeof seamReferenceAttribution>): Array<{ row: SeamPairRow; pixels: number[] }> {
2302
+ const [W, H] = rigSize;
1965
2303
  // A part's pixel at rig (u, v) as an offset into its image, or -1 where it holds no art.
1966
2304
  const at = (k: number, u: number, v: number): number => {
1967
2305
  const part = parts[k];
@@ -1984,39 +2322,7 @@ export function seamPairRows(seam: SeamFigures, parts: readonly PlacedAlpha[], r
1984
2322
  seam.counted.forEach((p, idx) => {
1985
2323
  const fx = p % vp.pixelWidth;
1986
2324
  const fy = Math.floor(p / vp.pixelWidth);
1987
- const u0 = Math.floor((fx - tx) / sx);
1988
- const v0 = Math.floor((fy - ty) / sy);
1989
- let first = -1;
1990
- let second = -1;
1991
- const read: Array<[number, number]> = [];
1992
- let rx0 = Infinity;
1993
- let ry0 = Infinity;
1994
- let rx1 = -Infinity;
1995
- let ry1 = -Infinity;
1996
- for (let dv = 0; dv < 2; dv++) {
1997
- for (let du = 0; du < 2; du++) {
1998
- const u = u0 + du;
1999
- const v = v0 + dv;
2000
- if (u < 0 || u >= W || v < 0 || v >= H) continue;
2001
- read.push([u, v]);
2002
- rx0 = Math.min(rx0, u);
2003
- ry0 = Math.min(ry0, v);
2004
- rx1 = Math.max(rx1, u);
2005
- ry1 = Math.max(ry1, v);
2006
- for (const k of [top[v * W + u], next[v * W + u]]) {
2007
- if (k < 0 || k === first || k === second) continue;
2008
- if (k > first) {
2009
- second = first;
2010
- first = k;
2011
- } else if (k > second) second = k;
2012
- }
2013
- }
2014
- }
2015
- // A sample wholly outside the rig reads no rig pixel; its rig box is the nearest rig pixel.
2016
- if (rx1 < rx0) {
2017
- rx0 = rx1 = Math.min(Math.max(u0, 0), W - 1);
2018
- ry0 = ry1 = Math.min(Math.max(v0, 0), H - 1);
2019
- }
2325
+ const { u0, v0, first, second, read, rx0, ry0, rx1, ry1 } = attribution(p, seam.map, true);
2020
2326
  const a = second;
2021
2327
  const b = first;
2022
2328
  const key = `${a},${b}`;
@@ -3981,18 +4287,16 @@ export interface MotionSeamRow {
3981
4287
  banded: number;
3982
4288
  /** The frames over the floor, ascending: the warning's frames. */
3983
4289
  opens: number[];
3984
- /** Beside `opens`: GAP only on roots; the legacy maximum of both kinds elsewhere. */
4290
+ /** Beside `opens`: gapOpen plus UNDER-owned ghost on roots; legacy maximum elsewhere. */
3985
4291
  px: number[];
3986
- /** Maximum gated/warned count over the floor; root ghost is separate INFO. */
4292
+ /** Maximum gated/warned count over the unchanged one-cell floor. */
3987
4293
  max_px: number;
3988
4294
  /** The frames rigc names open whose every opening is one cell thick: under the floor, not reported. */
3989
4295
  under_floor: number[];
3990
4296
  /** New roots only: the worst above-floor hit, retaining rigc's cell and world box. */
3991
- worst?: MotionSeamHit & { kind: 'gap' | 'ghost' };
3992
- /** Roots only: preserve mixed ghost without inferring an owner from rigc-seam/1. */
3993
- ghost_info?: MotionSeamWorldKind & { owner: 'unavailable'; frames: number };
3994
- /** Roots only, above-floor raw GAP hits: sufficient whole-box proof, never a GAP mask. */
3995
- coverage?: RootGapCoverage[];
4297
+ worst?: MotionSeamHit & { kind: 'gap' | 'ghost' | 'gapOpen' | 'underGhost' | 'gapOpen+underGhost' };
4298
+ /** Exact stock partitions and the resolved UNDER owner, retained even below the floor. */
4299
+ cells?: MotionRootCells[];
3996
4300
  }
3997
4301
 
3998
4302
  /** Existing pairs warn; new body roots alone can FAIL. Unavailable readings are named SKIP, never measured zero. */
@@ -4009,7 +4313,7 @@ export interface MotionSeamLine {
4009
4313
  /** Physics-only reference worlds (issue #591); do not participate in warnings or bars. */
4010
4314
  worlds?: MotionSeamWorlds;
4011
4315
  /** Selected body-root pairs and named zero-band roots; existing internal seams remain warnings. */
4012
- roots?: { status: 'PASS' | 'FAIL' | 'SKIP'; mode: 'gap-only'; ghost_owner: 'unavailable'; ghost_followup: 'rig-c/core#1555'; pairs: string[]; failed: number; reason?: string; unmeasured?: MotionUnmeasuredRoot[] };
4316
+ roots?: { status: 'PASS' | 'FAIL' | 'SKIP'; mode: 'gap-open+under-ghost'; ghost_owner: 'resolved-draw-order'; pairs: string[]; failed: number; reason?: string; unmeasured?: MotionUnmeasuredRoot[] };
4013
4317
  }
4014
4318
 
4015
4319
  /**
@@ -4217,193 +4521,57 @@ export interface MotionSeamHit {
4217
4521
  box: [number, number, number, number];
4218
4522
  }
4219
4523
 
4220
- /** Match rig-c's DRAWN_ALPHA (passthrough): alpha, never RGB brightness. */
4221
- const ROOT_DRAWN_ALPHA = 128;
4222
- const ROOT_COVERAGE_DIR = 'root_gap_coverage';
4223
- export interface RootGapCoverage extends MotionSeamHit {
4224
- status: 'exempt' | 'conservative' | 'unavailable';
4225
- reason: string;
4226
- /** Whole box cell centres, NOT the unavailable exact GAP subset. */
4227
- box_cells?: number;
4228
- covered_cells?: number;
4229
- /** Deterministic sidecar relative to check.json, written only for actual examined hits. */
4230
- evidence?: string;
4231
- }
4232
- export type RootGapCoverageReader = (pair: MotionSeamPair, animation: string, hit: MotionSeamHit, time: number | undefined) => RootGapCoverage;
4233
-
4234
- /** All-box coverage is sufficient because the raw GAP cells are a subset of the box. */
4235
- export function rootGapBoxCoverage(hit: MotionSeamHit, alpha: readonly number[] | null, reason = 'composite metadata unavailable', worldMagnitude?: number): RootGapCoverage {
4236
- const width = Math.round((hit.box[2] - hit.box[0]) / hit.cell);
4237
- const height = Math.round((hit.box[3] - hit.box[1]) / hit.cell);
4238
- const unavailable = (): RootGapCoverage => ({ ...hit, status: 'unavailable', reason });
4239
- // Binary64 unit roundoff u. Core seam.ts readFrame/centreX/centreY/take
4240
- // forms each edge with grid-origin multiply, offset multiply, centre add and
4241
- // half-cell add: four rounded operations (cell/2 and integer+.5 are exact
4242
- // in the normal/safe-index domain below). For M bounding the SAME pair's
4243
- // rest/posed coordinates, |origin| <= M+4c, |offset| <= 2M+8c;
4244
- // B=4(M+4c) bounds every intermediate magnitude, including cancellation.
4245
- // Each edge's forward error is <= gamma(4)B. Add both edge errors, the
4246
- // subtraction error u(|lo|+|hi|), and division error u|q|/(1-u).
4247
- // gamma(32) rounds outward over at most 32 arithmetic operations, including
4248
- // B, both gamma evaluations and the error expression below. A bound
4249
- // >= half a cell cannot identify a unique integer and remains unavailable.
4250
- // Without the coordinate bound only EXACT integer extents are accepted.
4251
- const u = Number.EPSILON / 2;
4252
- const gamma = (n: number): number => n * u / (1 - n * u);
4253
- const integerExtent = (lo: number, hi: number, cells: number): boolean => {
4254
- const q = (hi - lo) / hit.cell;
4255
- if (worldMagnitude === undefined) return q === cells;
4256
- const B = 4 * (worldMagnitude + 4 * hit.cell);
4257
- if (!Number.isFinite(worldMagnitude) || worldMagnitude < Math.max(Math.abs(lo), Math.abs(hi)) ||
4258
- hit.cell < 2 ** -1021 || !Number.isFinite(B) || B / hit.cell >= 2 ** 51) return false;
4259
- const error = ((2 * gamma(4) * B + u * (Math.abs(lo) + Math.abs(hi))) / hit.cell +
4260
- u * Math.abs(q) / (1 - u)) / (1 - gamma(32)) + Number.MIN_VALUE;
4261
- return error < 0.5 && Math.abs(q - cells) <= error;
4262
- };
4263
- if (!Number.isFinite(hit.cell) || hit.cell <= 0 || !hit.box.every(Number.isFinite) ||
4264
- !Number.isSafeInteger(width * height) || width <= 0 || height <= 0 ||
4265
- !integerExtent(hit.box[0], hit.box[2], width) || !integerExtent(hit.box[1], hit.box[3], height) ||
4266
- alpha === null || alpha.length !== width * height || alpha.some(a => !Number.isFinite(a) || a < 0 || a > 255)) return unavailable();
4267
- const covered = alpha.filter(a => a >= ROOT_DRAWN_ALPHA).length;
4268
- return { ...hit, status: covered === alpha.length ? 'exempt' : 'conservative',
4269
- reason: covered === alpha.length ? 'whole world-cell box covered at DRAWN_ALPHA 128' : 'uncovered box cells: retain the entire original GAP count; exact GAP subset unavailable',
4270
- box_cells: alpha.length, covered_cells: covered };
4271
- }
4272
-
4273
- /**
4274
- * Root-only lazy reader. The render already made by runCheck supplies every
4275
- * used world vertex, tint, frame time and draw order. The public renderer entry
4276
- * supplies packed UV/page metadata and rasterisation, not a second seam metric.
4277
- * Unsupported clipping/binding or even one replay pixel mismatch retains raw.
4278
- */
4279
- export function motionRootCoverageReader(build: string, rendered: string, out: string): RootGapCoverageReader {
4280
- type Renderer = OfficialRenderer;
4281
- type PoseAttachment = NonNullable<RootCoverageFrame['attachments']>[number];
4282
- interface Prepared { api: Renderer; pages: ReturnType<Renderer['loadCandidate']>['pages']; pieces: RootCoveragePiece[]; attachments: PoseAttachment[] }
4283
- interface Animation { frames: Map<number, { frame: RootCoverageFrame; alphaReplayExact: boolean }>; restMagnitude: number }
4284
- let prepared: Prepared | undefined;
4285
- const animations = new Map<string, Animation>();
4286
- const read = (path: string): unknown => JSON.parse(readFileSync(path, 'utf8')) as unknown;
4287
- const same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);
4288
- class CoverageUnavailable extends Error {}
4289
- const requireFact = (condition: unknown, reason: string): void => { if (!condition) throw new CoverageUnavailable(reason); };
4290
- const attachments = (value: unknown): PoseAttachment[] => {
4291
- requireFact(Array.isArray(value), 'geometry attachment roster unavailable');
4292
- return (value as unknown[]).map(a => {
4293
- if (!isRecord(a) || typeof a.slot !== 'string' || typeof a.attachment !== 'string' ||
4294
- !Array.isArray(a.vertices) || a.vertices.length % 2 !== 0 || !a.vertices.every(v => typeof v === 'number' && Number.isFinite(v)) ||
4295
- !Array.isArray(a.color) || a.color.length !== 4 || !a.color.every(v => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1)) throw new CoverageUnavailable('geometry attachment fields unavailable');
4296
- return { slot: a.slot, attachment: a.attachment, vertices: a.vertices as number[], color: a.color as [number, number, number, number] };
4297
- });
4298
- };
4299
- const prepare = (): Prepared => {
4300
- if (prepared !== undefined) return prepared;
4301
- // Node's module loader is called only here, never for a root-free reading.
4302
- const loaded: unknown = officialRenderer();
4303
- requireFact(isRecord(loaded) && ['loadCandidate', 'throughPoser', 'sampleSetupPose', 'renderFrame'].every(k => typeof loaded[k] === 'function'), 'official renderer exports unavailable');
4304
- const api = loaded as Renderer;
4305
- const skeleton = join(build, 'skeleton.json'), atlas = join(build, 'skeleton.atlas');
4306
- const text = readFileSync(skeleton, 'utf8'), document: unknown = JSON.parse(text);
4307
- const unsupported = (v: unknown): boolean => Array.isArray(v) ? v.some(unsupported) : isRecord(v) &&
4308
- (v.type === 'clipping' || Object.keys(v).some(k => k === 'dark' || k === 'rgba2' || k === 'rgb2' || unsupported(v[k])));
4309
- requireFact(!unsupported(document), 'clipping or dark-tint metadata is not replayable from this geometry');
4310
- const candidate = api.loadCandidate({ skeletonText: text, atlasText: readFileSync(atlas, 'utf8'), atlasDir: build, label: 'root GAP composite' }, { skeleton, atlas }, undefined);
4311
- const metadata = api.throughPoser(candidate.choice, p => api.sampleSetupPose(p, { geometry: true, bones: true })).value[0];
4312
- requireFact(metadata !== undefined && metadata.attachments !== undefined && metadata.pieces.every(p => !('source' in p) && p.dark === undefined), 'unclipped packed metadata unavailable');
4313
- prepared = { api, pages: candidate.pages, pieces: metadata.pieces, attachments: metadata.attachments ?? [] };
4314
- return prepared;
4315
- };
4316
- return (pair, animation, hit, time) => {
4317
- let result = rootGapBoxCoverage(hit, null);
4318
- let alpha: number[] | null = null;
4319
- let frameTime: number | null = null;
4320
- const reason = 'official composite metadata or pixel replay unavailable';
4321
- try {
4322
- requireFact(Number.isInteger(hit.index) && hit.index >= 0 && typeof time === 'number' && Number.isFinite(time), 'actual raw frame time unavailable');
4323
- const { api, pages, pieces, attachments: metadataAttachments } = prepare();
4324
- const sidecar = read(join(rendered, 'frames.json'));
4325
- requireFact(isRecord(sidecar) && Array.isArray(sidecar.sets) && isRecord(sidecar.viewport), 'render viewport unavailable');
4326
- // requireFact deliberately does not narrow unknown values: each reader
4327
- // checks again at its own boundary rather than using an unchecked cast.
4328
- if (!isRecord(sidecar) || !Array.isArray(sidecar.sets) || !isRecord(sidecar.viewport)) throw new CoverageUnavailable(reason);
4329
- const set = sidecar.sets.find(s => isRecord(s) && s.animation === animation);
4330
- requireFact(isRecord(set) && typeof set.dir === 'string' && !isAbsolute(set.dir) && !set.dir.split(/[\\/]/).includes('..'), 'local animation directory unavailable');
4331
- if (!isRecord(set) || typeof set.dir !== 'string') throw new CoverageUnavailable(reason);
4332
- const v = sidecar.viewport;
4333
- requireFact(['x', 'y', 'width', 'height', 'scale', 'pixelWidth', 'pixelHeight'].every(k => typeof v[k] === 'number' && Number.isFinite(v[k])) &&
4334
- Number(v.scale) > 0 && Number.isSafeInteger(v.pixelWidth) && Number(v.pixelWidth) > 0 && Number.isSafeInteger(v.pixelHeight) && Number(v.pixelHeight) > 0, 'finite render viewport unavailable');
4335
- const viewport: RootCoverageViewport = { minX: Number(v.x), minY: Number(v.y), maxX: Number(v.x) + Number(v.width), maxY: Number(v.y) + Number(v.height), scale: Number(v.scale), width: Number(v.pixelWidth), height: Number(v.pixelHeight) };
4336
- requireFact(Array.isArray(sidecar.background) && sidecar.background.length === 4 && sidecar.background.every(x => typeof x === 'number' && Number.isInteger(x) && x >= 0 && x <= 255), 'render background unavailable');
4337
- const background = sidecar.background as [number, number, number, number];
4338
- let state = animations.get(animation);
4339
- if (state === undefined) {
4340
- const geometry = read(join(rendered, set.dir, GEOMETRY_FILE));
4341
- requireFact(isRecord(geometry) && isRecord(geometry.setup) && Array.isArray(geometry.rest) && Array.isArray(geometry.frames) && geometry.animation === animation, 'same-animation geometry unavailable');
4342
- if (!isRecord(geometry) || !isRecord(geometry.setup) || !Array.isArray(geometry.rest) || !Array.isArray(geometry.frames)) throw new CoverageUnavailable(reason);
4343
- const setup = attachments(geometry.setup.attachments);
4344
- requireFact(setup.length === pieces.length && new Set(setup.map(a => a.slot)).size === setup.length, 'setup draw roster unavailable');
4345
- for (const p of pieces) {
4346
- const a = setup.find(a => a.slot === p.slot);
4347
- const rest = geometry.rest.find(r => isRecord(r) && r.slot === p.slot && r.attachment === a?.attachment);
4348
- requireFact(a !== undefined && isRecord(rest) && rest.kind === p.kind && a.vertices.length === p.world.length && same(a.color, p.tint) &&
4349
- (p.kind !== 'mesh' || same(rest.triangles, Array.from(p.triangles))), 'packed metadata topology or tint differs');
4350
- }
4351
- // The metadata poser supplies attachment identity, never world positions.
4352
- // Match it explicitly to the captured setup, including default skin.
4353
- requireFact(setup.every(a => metadataAttachments.some(b => a.slot === b.slot && a.attachment === b.attachment)), 'default attachment identity differs');
4354
- let restMagnitude = 0;
4355
- for (const r of geometry.rest) {
4356
- if (!isRecord(r) || !Array.isArray(r.vertices) || !r.vertices.every(v => typeof v === 'number' && Number.isFinite(v))) throw new CoverageUnavailable('rest coordinate bound unavailable');
4357
- for (const v of r.vertices as number[]) restMagnitude = Math.max(restMagnitude, Math.abs(v));
4358
- }
4359
- state = { restMagnitude, frames: new Map() };
4360
- for (const f of geometry.frames) {
4361
- if (!isRecord(f) || !Number.isInteger(f.index) || typeof f.time !== 'number' || !Number.isFinite(f.time)) throw new CoverageUnavailable('frame identity unavailable');
4362
- const posed = attachments(f.attachments);
4363
- requireFact(posed.length === pieces.length && new Set(posed.map(a => a.slot)).size === posed.length, 'frame draw roster differs');
4364
- const drawn = posed.map(a => {
4365
- const p = pieces.find(p => p.slot === a.slot), original = setup.find(p => p.slot === a.slot);
4366
- if (p === undefined || original?.attachment !== a.attachment || p.world.length !== a.vertices.length) throw new CoverageUnavailable('frame attachment binding differs');
4367
- return { ...p, world: a.vertices, tint: a.color };
4368
- });
4369
- requireFact(!state.frames.has(Number(f.index)), 'duplicate frame index');
4370
- state.frames.set(Number(f.index), { frame: { index: Number(f.index), time: f.time, pieces: drawn }, alphaReplayExact: false });
4371
- }
4372
- animations.set(animation, state);
4373
- }
4374
- const captured = state.frames.get(hit.index);
4375
- frameTime = captured?.frame.time ?? null;
4376
- requireFact(captured !== undefined && captured.frame.time === time, 'raw and geometry frame time differ');
4377
- if (captured === undefined) throw new CoverageUnavailable(reason);
4378
- frameTime = captured.frame.time;
4379
- if (!captured.alphaReplayExact) {
4380
- const png = readPng(join(rendered, set.dir, 'f' + String(hit.index).padStart(4, '0') + '.png'));
4381
- const replay = api.renderFrame(captured.frame, pages, viewport, background);
4382
- requireFact(png.width === replay.width && png.height === replay.height && Buffer.from(png.data).equals(Buffer.from(replay.data)), 'official frame RGBA pixel replay differs');
4383
- captured.alphaReplayExact = true;
4524
+ /** Per-frame body-root metric, using only stock partition counts. */
4525
+ export interface MotionRootCells {
4526
+ index: number;
4527
+ gap: number;
4528
+ gapOpen: number;
4529
+ gapCovered: number;
4530
+ ghostA: number;
4531
+ ghostB: number;
4532
+ under: 'a' | 'b' | null;
4533
+ underGhost: number;
4534
+ overGhost: number;
4535
+ counted: number;
4536
+ /** Original raw-kind box floor, never the narrowed partition box. */
4537
+ floor?: number;
4538
+ floor_box?: MotionSeamHit['box'];
4539
+ }
4540
+ export type RootDrawOrderReader = (pair: MotionSeamPair, animation: string, index: number, time: number | undefined) => 'a' | 'b';
4541
+
4542
+ /** Geometry attachments are the stock poser's resolved draw order on that frame, back to front. */
4543
+ export function motionRootDrawOrderReader(rendered: string): RootDrawOrderReader {
4544
+ const animations = new Map<string, Map<number, { time: number; slots: string[] }>>();
4545
+ return (pair, animation, index, time) => {
4546
+ const fail = (detail: string): never => {
4547
+ refuseIfAny([{ code: 'FRAMES_SIDECAR', object: pair.pair + ' in ' + animation + ' frame ' + index,
4548
+ detail: 'body-root resolved draw order unavailable: ' + detail }]);
4549
+ throw new Error('unreachable');
4550
+ };
4551
+ let frames = animations.get(animation);
4552
+ if (frames === undefined) {
4553
+ const problems: Problem[] = [];
4554
+ const sidecar = readJson(join(rendered, 'frames.json'), problems);
4555
+ const set = Array.isArray(sidecar?.sets) ? sidecar.sets.find(v => isRecord(v) && v.animation === animation) : undefined;
4556
+ if (!isRecord(set) || typeof set.dir !== 'string' || isAbsolute(set.dir) || set.dir.split(/[\\/]/).includes('..')) return fail('local animation directory required');
4557
+ const geometry = readJson(join(rendered, set.dir, GEOMETRY_FILE), problems);
4558
+ refuseIfAny(problems);
4559
+ if (geometry?.animation !== animation || !Array.isArray(geometry.frames)) return fail('same-animation geometry required');
4560
+ frames = new Map();
4561
+ for (const value of geometry.frames) {
4562
+ if (!isRecord(value) || !Number.isInteger(value.index) || typeof value.time !== 'number' || !Number.isFinite(value.time) ||
4563
+ !Array.isArray(value.attachments) || value.attachments.some(v => !isRecord(v) || typeof v.slot !== 'string')) return fail('finite frame identity and attachment roster required');
4564
+ const slots = value.attachments.map(v => String((v as Record<string, unknown>).slot));
4565
+ if (new Set(slots).size !== slots.length || frames.has(Number(value.index))) return fail('duplicate frame or slot');
4566
+ frames.set(Number(value.index), { time: value.time, slots });
4384
4567
  }
4385
- const width = Math.round((hit.box[2] - hit.box[0]) / hit.cell), height = Math.round((hit.box[3] - hit.box[1]) / hit.cell);
4386
- requireFact(Number.isSafeInteger(width * height) && width > 0 && height > 0 && Number.isFinite(hit.cell) && hit.cell > 0, 'world cell box unavailable');
4387
- const grid = { minX: hit.box[0], minY: hit.box[1], maxX: hit.box[2], maxY: hit.box[3], width, height, scale: 1 / hit.cell };
4388
- const composite = api.renderFrame(captured.frame, pages, grid, [0, 0, 0, 0]);
4389
- alpha = Array.from({ length: width * height }, (_, i) => composite.data[i * 4 + 3]);
4390
- let worldMagnitude = state.restMagnitude;
4391
- for (const p of captured.frame.pieces) for (const v of p.world) worldMagnitude = Math.max(worldMagnitude, Math.abs(v));
4392
- // All drawings' magnitude bounds either pair without selecting an owner.
4393
- result = rootGapBoxCoverage(hit, alpha, 'world cell box grid unavailable', worldMagnitude);
4394
- } catch (error) {
4395
- // No guessed coverage and no absolute paths from an upstream exception.
4396
- result = rootGapBoxCoverage(hit, null, error instanceof CoverageUnavailable ? error.message : reason);
4568
+ animations.set(animation, frames);
4397
4569
  }
4398
- const key = createHash('sha256').update(JSON.stringify([pair.pair, animation, hit.index])).digest('hex');
4399
- const evidence = ROOT_COVERAGE_DIR + '/' + key + '.json';
4400
- mkdirSync(join(out, ROOT_COVERAGE_DIR), { recursive: true });
4401
- writeFileSync(join(out, evidence), JSON.stringify({ spec: 'rig-parts-root-gap-box/1', pair: pair.pair, animation,
4402
- raw_time: typeof time === 'number' && Number.isFinite(time) ? time : null, frame_time: frameTime, raw: hit, ...result, alpha_threshold: ROOT_DRAWN_ALPHA,
4403
- scope: 'whole world-cell box centres; not an exact GAP-cell mask',
4404
- grid: { minX: hit.box[0], minY: hit.box[1], maxX: hit.box[2], maxY: hit.box[3], cell: hit.cell, rows: 'top to bottom' },
4405
- alpha, exact_rgba_replay: alpha !== null, followup: 'rig-c/core#1556' }, null, 1) + '\n');
4406
- return { ...result, evidence };
4570
+ const frame = frames.get(index);
4571
+ if (frame === undefined || frame.time !== time) return fail('raw and geometry frame time differ');
4572
+ const a = frame.slots.indexOf(pair.a), b = frame.slots.indexOf(pair.b);
4573
+ if (a < 0 || b < 0 || a === b) return fail('both named pair slots required exactly once');
4574
+ return a < b ? 'a' : 'b';
4407
4575
  };
4408
4576
  }
4409
4577
  export interface MotionSeamWorldKind {
@@ -4451,7 +4619,7 @@ export function motionSeamWorlds(physics: boolean, answersWind: boolean, read: (
4451
4619
  /** The same validated sidecars as the warning, retaining the raw gap and ghost cells. */
4452
4620
  export function readMotionSeamWorldRows(dir: string, animations: readonly string[], fps: number, pairs: readonly MotionSeamPair[]): MotionSeamWorldRow[] {
4453
4621
  const rows: MotionSeamWorldRow[] = [];
4454
- readMotionSeams(dir, animations, fps, pairs, {}, rows);
4622
+ readMotionSeams(dir, animations, fps, pairs.map(({ root: _root, ...pair }) => pair), {}, rows);
4455
4623
  return rows;
4456
4624
  }
4457
4625
 
@@ -4509,8 +4677,8 @@ type SeamHitRead = MotionSeamHit;
4509
4677
  * file that is missing, a file that is not the animation's or not at the rate
4510
4678
  * asked, a pair out of the flag's order, and a field of the wrong shape.
4511
4679
  */
4512
- export function readMotionSeams(dir: string, animations: readonly string[], fps: number, pairs: readonly MotionSeamPair[], plant: MotionSeamPlant = {}, worldRows?: MotionSeamWorldRow[], coverageReader?: RootGapCoverageReader): MotionSeamRow[] {
4513
- return readSeamRows(dir, animations, fps, pairs, plant, worldRows, false, coverageReader);
4680
+ export function readMotionSeams(dir: string, animations: readonly string[], fps: number, pairs: readonly MotionSeamPair[], plant: MotionSeamPlant = {}, worldRows?: MotionSeamWorldRow[], drawOrderReader?: RootDrawOrderReader): MotionSeamRow[] {
4681
+ return readSeamRows(dir, animations, fps, pairs, plant, worldRows, false, drawOrderReader);
4514
4682
  }
4515
4683
 
4516
4684
  /** The same stock seam reader, restricted to one canonical setup-only frame. */
@@ -4535,7 +4703,7 @@ export function readMotionRootSetup(dir: string, fps: number, pairs: readonly Mo
4535
4703
  return rows.map(({ pair, drawn, banded, status }) => ({ pair, drawn, banded, status }));
4536
4704
  }
4537
4705
 
4538
- function readSeamRows(dir: string, animations: readonly string[], fps: number, pairs: readonly MotionSeamPair[], plant: MotionSeamPlant = {}, worldRows?: MotionSeamWorldRow[], setup = false, coverageReader?: RootGapCoverageReader): MotionSeamRow[] {
4706
+ function readSeamRows(dir: string, animations: readonly string[], fps: number, pairs: readonly MotionSeamPair[], plant: MotionSeamPlant = {}, worldRows?: MotionSeamWorldRow[], setup = false, drawOrderReader?: RootDrawOrderReader): MotionSeamRow[] {
4539
4707
  const problems: Problem[] = [];
4540
4708
  const bad = (object: string, detail: string): void => {
4541
4709
  problems.push({ code: 'FRAMES_SIDECAR', object, detail });
@@ -4574,10 +4742,8 @@ function readSeamRows(dir: string, animations: readonly string[], fps: number, p
4574
4742
  }
4575
4743
  const over = new Map<number, number>();
4576
4744
  let rootWorst: MotionSeamRow['worst'];
4577
- let rootGapFrames: number[] = [];
4578
- let ghostFrames = 0;
4579
- const coverage: RootGapCoverage[] = [];
4580
- const exempt = new Set<number>();
4745
+ const rootFrames = new Set<number>();
4746
+ const cells: MotionRootCells[] = [];
4581
4747
  const kinds: Record<'gap' | 'ghost', MotionSeamWorldKind> = { gap: { max_px: 0, worst: null }, ghost: { max_px: 0, worst: null } };
4582
4748
  for (const kind of ['gap', 'ghost'] as const) {
4583
4749
  const k = p[kind];
@@ -4587,22 +4753,72 @@ function readSeamRows(dir: string, animations: readonly string[], fps: number, p
4587
4753
  return;
4588
4754
  }
4589
4755
  const hits = frames as SeamHitRead[];
4590
- if (kind === 'gap') rootGapFrames = hits.map(h => h.index);
4591
- else ghostFrames = hits.length;
4756
+
4592
4757
  const worst = hits.reduce<MotionSeamHit | null>((best, h) => best === null || h.px > best.px || (h.px === best.px && h.index < best.index) ? h : best, null);
4593
4758
  kinds[kind] = { max_px: worst?.px ?? 0, worst };
4594
- // rigc-seam/1 exposes aggregate ghost, not its drawing owner. A drawn
4595
- // overlap band is not proof of a hole; only GAP gates roots until core#1555.
4596
- for (const h of hits) if ((want.root === undefined || kind === 'gap') && (plant.noFloor === true || openingOverFloor(h))) {
4597
- if (want.root !== undefined) {
4598
- const raw = isRecord(k) && Array.isArray(k.frames) ? k.frames.find(v => isRecord(v) && v.index === h.index) : undefined;
4599
- const time = isRecord(raw) && typeof raw.time === 'number' ? raw.time : undefined;
4600
- const proof = coverageReader?.(want, animation, h, time) ?? rootGapBoxCoverage(h, null);
4601
- coverage.push(proof);
4602
- if (proof.status === 'exempt') { exempt.add(h.index); continue; }
4603
- }
4759
+ // Existing internal pairs retain their original maximum-kind warning and floor.
4760
+ for (const h of hits) if (want.root === undefined && (plant.noFloor === true || openingOverFloor(h))) {
4604
4761
  over.set(h.index, Math.max(over.get(h.index) ?? 0, h.px));
4605
- if (want.root !== undefined && (rootWorst === undefined || h.px > rootWorst.px || (h.px === rootWorst.px && h.index < rootWorst.index))) rootWorst = { ...h, kind: 'gap' };
4762
+ }
4763
+ }
4764
+ if (want.root !== undefined && !setup) {
4765
+ const partitions = new Map<string, SeamHitRead[]>();
4766
+ for (const name of ['gap', 'ghost', 'gapOpen', 'gapCovered', 'ghostA', 'ghostB']) {
4767
+ const value = p[name];
4768
+ const hits = isRecord(value) && Array.isArray(value.frames) ? value.frames.map(hitOf) : null;
4769
+ if (hits === null || hits.some(h => h === null)) { bad(at + ' ' + name, 'requires stock per-frame cell partitions from rig-c >=2.69.0'); return; }
4770
+ if (new Set(hits.map(h => h?.index)).size !== hits.length || hits.some(h => h === null || !Number.isSafeInteger(h.index) || h.index < 0 || !Number.isSafeInteger(h.px) || h.px <= 0 || !Number.isFinite(h.cell) || !h.box.every(Number.isFinite) || h.box[2] <= h.box[0] || h.box[3] <= h.box[1])) {
4771
+ bad(at + ' ' + name, 'requires unique nonnegative frame indices, positive whole counts and finite boxes'); return;
4772
+ }
4773
+ if (!isRecord(value) || !Array.isArray(value.frames) || value.frames.some(v => !isRecord(v) || typeof v.time !== 'number' || !Number.isFinite(v.time) || v.time < 0)) {
4774
+ bad(at + ' ' + name, 'requires the actual finite stock frame time'); return;
4775
+ }
4776
+ partitions.set(name, hits as SeamHitRead[]);
4777
+ }
4778
+ const rawHits = (name: string): SeamHitRead[] => {
4779
+ const value = p[name];
4780
+ return isRecord(value) && Array.isArray(value.frames) ? value.frames.map(hitOf).filter((h): h is SeamHitRead => h !== null) : [];
4781
+ };
4782
+ for (const hits of partitions.values()) for (const h of hits) rootFrames.add(h.index);
4783
+ for (const index of [...rootFrames].sort((a, b) => a - b)) {
4784
+ const hit = (name: string): SeamHitRead | undefined => partitions.get(name)?.find(h => h.index === index);
4785
+ const count = (name: string): number => hit(name)?.px ?? 0;
4786
+ if (count('gapOpen') + count('gapCovered') !== count('gap') || count('ghostA') + count('ghostB') !== count('ghost')) {
4787
+ bad(at + ' frame ' + index, 'gapOpen + gapCovered must equal gap and ghostA + ghostB must equal ghost'); continue;
4788
+ }
4789
+ const raw = [...rawHits('gap'), ...rawHits('ghost')].find(h => h.index === index);
4790
+ const source = ['gap', 'ghost'].flatMap(name => {
4791
+ const value = p[name]; return isRecord(value) && Array.isArray(value.frames) ? value.frames.filter(v => isRecord(v) && v.index === index) : [];
4792
+ })[0];
4793
+ const time = isRecord(source) && typeof source.time === 'number' ? source.time : undefined;
4794
+ const coherent = [...partitions].every(([name, hits]) => {
4795
+ const h = hits.find(h => h.index === index);
4796
+ if (h === undefined) return true;
4797
+ const value = p[name];
4798
+ const record = isRecord(value) && Array.isArray(value.frames) ? value.frames.find(v => isRecord(v) && v.index === index) : undefined;
4799
+ return isRecord(record) && record.time === time && h.cell === raw?.cell;
4800
+ });
4801
+ if (!coherent) { bad(at + ' frame ' + index, 'all raw and partition hits must share the actual frame time and stock cell size'); continue; }
4802
+
4803
+ if (count('ghost') > 0 && drawOrderReader === undefined) { bad(at + ' frame ' + index, 'resolved per-frame draw-order reader required for ghost ownership'); continue; }
4804
+ const under = count('ghost') > 0 ? drawOrderReader?.(want, animation, index, time) ?? null : null;
4805
+ const underHit = under === null ? undefined : hit(under === 'a' ? 'ghostA' : 'ghostB');
4806
+ // Visibility changes the count, not the existing raw kind's floor.
4807
+ // With both kinds contributing, their original raw boxes are united.
4808
+ const counted = count('gapOpen') + (underHit?.px ?? 0);
4809
+ const bounds = [count('gapOpen') > 0 ? hit('gap') : undefined, underHit === undefined ? undefined : hit('ghost')].filter((h): h is SeamHitRead => h !== undefined);
4810
+ const cell = raw?.cell ?? 0;
4811
+ const box: MotionSeamHit['box'] | undefined = bounds.length === 0 ? undefined : [Math.min(...bounds.map(h => h.box[0])), Math.min(...bounds.map(h => h.box[1])), Math.max(...bounds.map(h => h.box[2])), Math.max(...bounds.map(h => h.box[3]))];
4812
+ const floor = box === undefined ? undefined : Math.round(Math.max(box[2] - box[0], box[3] - box[1]) / cell);
4813
+ cells.push({ index, gap: count('gap'), gapOpen: count('gapOpen'), gapCovered: count('gapCovered'), ghostA: count('ghostA'), ghostB: count('ghostB'),
4814
+ under, underGhost: underHit?.px ?? 0, overGhost: count('ghost') - (underHit?.px ?? 0), counted,
4815
+ ...(box === undefined ? {} : { floor, floor_box: box }) });
4816
+ if (box === undefined || raw === undefined) continue;
4817
+ const h = { index, px: counted, cell, box };
4818
+ if (plant.noFloor === true || openingOverFloor(h)) {
4819
+ over.set(index, counted);
4820
+ if (rootWorst === undefined || counted > rootWorst.px || (counted === rootWorst.px && index < rootWorst.index)) rootWorst = { ...h, kind: underHit === undefined ? 'gapOpen' : hit('gapOpen') === undefined ? 'underGhost' : 'gapOpen+underGhost' };
4821
+ }
4606
4822
  }
4607
4823
  }
4608
4824
  worldRows?.push({ pair: want.pair, animation, status: p.status, drawn: p.drawn, banded: p.banded, gap: kinds.gap, ghost: kinds.ghost });
@@ -4616,10 +4832,9 @@ function readSeamRows(dir: string, animations: readonly string[], fps: number, p
4616
4832
  opens,
4617
4833
  px: opens.map((f) => over.get(f) ?? 0),
4618
4834
  max_px: opens.reduce((m, f) => Math.max(m, over.get(f) ?? 0), 0),
4619
- under_floor: (want.root === undefined ? p.opens : rootGapFrames).filter((f) => !over.has(f) && !exempt.has(f)),
4835
+ under_floor: (want.root === undefined ? p.opens : [...rootFrames].filter(f => cells.some(c => c.index === f && c.counted > 0))).filter((f) => !over.has(f)),
4620
4836
  ...(rootWorst === undefined ? {} : { worst: rootWorst }),
4621
- ...(coverage.length === 0 ? {} : { coverage }),
4622
- ...(want.root === undefined ? {} : { ghost_info: { ...kinds.ghost, owner: 'unavailable' as const, frames: ghostFrames } }),
4837
+ ...(want.root === undefined ? {} : { cells }),
4623
4838
  });
4624
4839
  });
4625
4840
  }
@@ -4627,7 +4842,7 @@ function readSeamRows(dir: string, animations: readonly string[], fps: number, p
4627
4842
  return rows;
4628
4843
  }
4629
4844
 
4630
- /** Only active proven root GAP rows fail; mixed ghost is INFO. Existing warnings/floor are unchanged. */
4845
+ /** Only active proven roots gate gapOpen plus UNDER-owned ghost; existing warnings/floor are unchanged. */
4631
4846
  export function motionSeamLine(pairs: MotionSeamPair[], animations: string[], fps: number, rows: MotionSeamRow[], reason?: string, problems: Problem[] = [], unmeasuredRoots: readonly MotionUnmeasuredRoot[] = []): MotionSeamLine {
4632
4847
  const roots = pairs.filter(p => p.root !== undefined);
4633
4848
  const rootNames = new Set(roots.map(p => p.pair));
@@ -4635,11 +4850,10 @@ export function motionSeamLine(pairs: MotionSeamPair[], animations: string[], fp
4635
4850
  const failed = rows.filter(r => rootNames.has(r.pair) && r.status === 'read' && r.banded > 0 && r.opens.length > 0);
4636
4851
  for (const row of failed) {
4637
4852
  const h = row.worst;
4638
- const proof = row.coverage?.find(p => p.index === h?.index);
4639
4853
  problems.push({ code: 'CHECK_SEAM_OVER_MOTION', object: 'body-root seam "' + row.pair + '" in "' + row.animation + '"',
4640
4854
  detail: h === undefined
4641
4855
  ? 'opens on frames ' + frameRuns(row.opens) + ', max ' + row.max_px + ' cells; no above-floor root hit metadata was returned'
4642
- : h.kind + ' at frame ' + h.index + ' (t = ' + h.index / fps + 's): ' + h.px + ' cells, cell ' + h.cell + ', world box [' + h.box.join(', ') + ']; at most ' + Math.round(Math.max(h.box[2] - h.box[0], h.box[3] - h.box[1]) / h.cell) + ' cells, the unchanged one-cell floor, is required' + (proof === undefined ? '' : '; ' + proof.status + ': ' + proof.reason + '; entire original GAP count retained') });
4856
+ : h.kind + ' at frame ' + h.index + ' (t = ' + h.index / fps + 's): ' + h.px + ' cells, cell ' + h.cell + ', world box [' + h.box.join(', ') + ']; at most ' + Math.round(Math.max(h.box[2] - h.box[0], h.box[3] - h.box[1]) / h.cell) + ' cells, the unchanged one-cell floor, is required' });
4643
4857
  }
4644
4858
  const missing = roots.flatMap(p => animations.length === 0 ? ['"' + p.pair + '": no animation'] : animations.flatMap(a => {
4645
4859
  const row = rows.find(r => r.pair === p.pair && r.animation === a);
@@ -4649,7 +4863,7 @@ export function motionSeamLine(pairs: MotionSeamPair[], animations: string[], fp
4649
4863
  const rootReasons = [...missing, ...unmeasured.map(root => 'root pair for ' + root.limb + ': ' + root.reason)];
4650
4864
  const rootGate: MotionSeamLine['roots'] = roots.length === 0 && unmeasured.length === 0 ? undefined : {
4651
4865
  status: failed.length > 0 ? 'FAIL' : rootReasons.length > 0 || reason !== undefined ? 'SKIP' : 'PASS',
4652
- mode: 'gap-only', ghost_owner: 'unavailable', ghost_followup: 'rig-c/core#1555',
4866
+ mode: 'gap-open+under-ghost', ghost_owner: 'resolved-draw-order',
4653
4867
  pairs: roots.map(p => p.pair), failed: failed.length,
4654
4868
  ...(rootReasons.length === 0 && reason === undefined ? {} : { reason: unmeasured.length === 0 ? (reason ?? missing.join('; ')) : [reason, ...rootReasons].filter(r => r !== undefined).join('; ') }),
4655
4869
  ...(unmeasured.length === 0 ? {} : { unmeasured }),
@@ -5011,7 +5225,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
5011
5225
  const keptDir = join(out, STILL_DIR);
5012
5226
  const foldDir = join(out, FOLD_SCRATCH);
5013
5227
  const seamMotionDir = join(out, MOTION_SEAM_SCRATCH);
5014
- for (const d of [buildDir, idleDir, stillDir, isoDir, loopDir, seamDir, keptDir, join(out, 'setup_still_auto'), foldDir, seamMotionDir, join(out, ROOT_COVERAGE_DIR)]) rmSync(d, { recursive: true, force: true });
5228
+ for (const d of [buildDir, idleDir, stillDir, isoDir, loopDir, seamDir, keptDir, join(out, 'setup_still_auto'), foldDir, seamMotionDir]) rmSync(d, { recursive: true, force: true });
5015
5229
  const written: string[] = [];
5016
5230
  const write = (name: string, data: string): void => {
5017
5231
  writeFileSync(join(out, name), data);
@@ -5127,7 +5341,15 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
5127
5341
  const checkedAlt = set !== undefined && !allSets && inp.parts !== null ? (inp.parts.alternates ?? []).find((a) => a.name === set) : undefined;
5128
5342
  const subsetFoldSlots =
5129
5343
  checkedAlt !== undefined && checkedAlt.parts !== undefined
5130
- ? new Set<string>([...Object.keys(checkedAlt.slots), ...(checkedAlt.hides ?? [])])
5344
+ ? (() => {
5345
+ const baseSet = new Set<string>([...Object.keys(checkedAlt.slots), ...(checkedAlt.hides ?? [])]);
5346
+ for (const sl of (Array.isArray(inp.rig.slots) ? inp.rig.slots : []).filter(isRecord)) {
5347
+ if (typeof sl.name !== 'string') continue;
5348
+ const m = /^(.+)__island[2-9]\d*$/.exec(sl.name);
5349
+ if (m !== null && baseSet.has(m[1])) baseSet.add(sl.name);
5350
+ }
5351
+ return baseSet;
5352
+ })()
5131
5353
  : null;
5132
5354
  const filterFolds = (map: Map<string, FoldingMesh[]>): Map<string, FoldingMesh[]> => {
5133
5355
  if (subsetFoldSlots === null) return map;
@@ -5419,7 +5641,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
5419
5641
  const r = measured(['render', '--candidate', buildDir, '--seam', list, '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), ...(hasRoots ? ['--geometry'] : []), '--out', activeDest]);
5420
5642
  if (r.status !== 0) refuseIfAny(rigcFailed(`render --seam ${list} --fps ${fps}`, r, r.out.split('\n').filter((l) => l.includes('FAIL') || l.includes('rigc:'))));
5421
5643
  const activeWorldRows: MotionSeamWorldRow[] = [];
5422
- motionSeam = motionSeamLine(pairs, animationNames, fps, readMotionSeams(activeDest, animationNames, fps, read, {}, stripped !== null && env === null ? activeWorldRows : undefined, hasRoots ? motionRootCoverageReader(buildDir, activeDest, out) : undefined), undefined, motionRootProblems, unmeasuredRoots);
5644
+ motionSeam = motionSeamLine(pairs, animationNames, fps, readMotionSeams(activeDest, animationNames, fps, read, {}, stripped !== null && env === null ? activeWorldRows : undefined, hasRoots ? motionRootDrawOrderReader(activeDest) : undefined), undefined, motionRootProblems, unmeasuredRoots);
5423
5645
  if (stripped !== null) {
5424
5646
  const response = environmentResponse(readFileSync(join(buildDir, 'skeleton.json'), 'utf8'));
5425
5647
  motionSeam.worlds = motionSeamWorlds(true, response.wind.length > 0, world => {
@@ -5543,12 +5765,14 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
5543
5765
  const canonicalSet = canonical(join(stillDir, 'build'), join(stillDir, 'seam'));
5544
5766
  seamViewport = canonicalSet.viewport;
5545
5767
  if (keepStills) cpSync(join(stillDir, 'seam'), keptDir, { recursive: true });
5546
- const composite = flatComposite(inp.parts, inp.partsDir, stillSet.background);
5768
+ const rigSlotOrder = (Array.isArray(inp.rig.slots) ? inp.rig.slots : []).filter(isRecord).map((sl) => String(sl.name));
5769
+ const composite = flatComposite(inp.parts, inp.partsDir, stillSet.background, rigSlotOrder);
5547
5770
  const autoSeam = seamFigures(composite, stillSet.frames[0].image, inp.stage, stillSet.viewport, stillSet.background, undefined, inp.parts.scene !== undefined);
5548
- seam = seamFigures(composite, canonicalSet.frames[0].image, inp.stage, canonicalSet.viewport, canonicalSet.background, undefined, inp.parts.scene !== undefined, undefined, true);
5549
- seamScope = { mode: 'source-grid/base', domain, denominator_px: canonicalDenominator(seam), auto_frame_raw: seamReading(autoSeam, stillSet.viewport), whole: seamReading(seam, canonicalSet.viewport) };
5550
- const placed = inp.parts.parts.map(p => ({ name: p.name, from: p.from, x: p.x, y: p.y, image: readPng(join(inp.partsDir, `${p.name}.png`)) }));
5551
- const baseRows = seamPairRows(seam, placed, inp.parts.rig_size, canonicalSet.viewport);
5771
+ const placed = resolvePlacedAlpha(basePlacements(inp.parts, rigSlotOrder), inp.partsDir);
5772
+ const basePopulation = createSeamPopulation(placed, inp.parts.rig_size, canonicalSet.viewport);
5773
+ seam = seamFigures(composite, canonicalSet.frames[0].image, inp.stage, canonicalSet.viewport, canonicalSet.background, undefined, inp.parts.scene !== undefined, undefined, true, basePopulation.observe);
5774
+ seamScope = { mode: 'source-grid/base', domain, denominator_px: canonicalDenominator(seam), auto_frame_raw: seamReading(autoSeam, stillSet.viewport), whole: seamReading(seam, canonicalSet.viewport), population: basePopulation.finish() };
5775
+ const baseRows = basePopulation.rows(seam);
5552
5776
  seamScope.whole_pairs = baseRows.map(({ row: { picture: _picture, ...raw } }) => raw);
5553
5777
  if (seamPairsAsked || seamFails(round3(seam.mean), seam.over40, 1)) {
5554
5778
  const split = baseRows;
@@ -5563,19 +5787,19 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
5563
5787
  if (asr.status !== 0) refuseIfAny(rigcFailed(`render (the setup-pose still of set "${alt.name}")`, asr, asr.out.split('\n').filter((l) => l.includes('FAIL'))));
5564
5788
  const altStillSet = readFrameSet(join(setDir, 'render'));
5565
5789
  if (keepStills) cpSync(join(setDir, 'render'), join(out, 'setup_still_auto', alt.name), { recursive: true });
5566
- const rigSlotOrder = (Array.isArray(inp.rig.slots) ? inp.rig.slots : []).filter(isRecord).map((sl) => String(sl.name));
5567
5790
  const altComposite = flatCompositeForSet(inp.parts, alt, inp.partsDir, altStillSet.background, rigSlotOrder);
5568
5791
  const altCanonical = canonical(join(setDir, 'build'), join(setDir, 'seam'));
5569
5792
  if (keepStills) cpSync(join(setDir, 'seam'), join(keptDir, alt.name), { recursive: true });
5570
- const altPlaced = setPlacements(inp.parts, alt, rigSlotOrder).map(({ name, png, box }) => ({ name, from: box.from, x: box.x, y: box.y, image: readPng(join(inp.partsDir, `${png}.png`)) }));
5793
+ const altPlaced = resolvePlacedAlpha(setPlacements(inp.parts, alt, rigSlotOrder), inp.partsDir);
5571
5794
  const altSupport = seamSupport(join(setDir, 'build'), join(setDir, 'rig.json'), altCanonical, altPlaced, seamStacks, inp.stage);
5572
5795
  const effects = seamEffectSelection(baseSupport, altSupport);
5573
5796
  const autoAltSeam = seamFigures(altComposite, altStillSet.frames[0].image, inp.stage, altStillSet.viewport, altStillSet.background, undefined, alt.scene !== undefined);
5574
- const wholeAltSeam = seamFigures(altComposite, altCanonical.frames[0].image, inp.stage, altCanonical.viewport, altCanonical.background, undefined, inp.parts.scene !== undefined, undefined, true);
5797
+ const population = createSeamPopulation(altPlaced, inp.parts.rig_size, altCanonical.viewport, effects.mask);
5798
+ const wholeAltSeam = seamFigures(altComposite, altCanonical.frames[0].image, inp.stage, altCanonical.viewport, altCanonical.background, undefined, inp.parts.scene !== undefined, undefined, true, population.observe);
5575
5799
  const altSeam = seamFigures(altComposite, altCanonical.frames[0].image, inp.stage, altCanonical.viewport, altCanonical.background, undefined, inp.parts.scene !== undefined, effects.mask, true);
5576
- const wholeRows = seamPairRows(wholeAltSeam, altPlaced, inp.parts.rig_size, altCanonical.viewport);
5800
+ const wholeRows = population.rows(wholeAltSeam);
5577
5801
  const altScope: SeamScope = {
5578
- mode: 'source-grid/affected-set', domain, denominator_px: canonicalDenominator(altSeam),
5802
+ mode: 'source-grid/affected-set', domain, denominator_px: canonicalDenominator(altSeam), population: population.finish(),
5579
5803
  auto_frame_raw: seamReading(autoAltSeam, altStillSet.viewport), whole: seamReading(wholeAltSeam, altCanonical.viewport), effects: effects.reasons, changes: effects.changes,
5580
5804
  ...((baseSupport.unavailable ?? altSupport.unavailable) === undefined ? {} : { unavailable: baseSupport.unavailable ?? altSupport.unavailable }),
5581
5805
  // Raw rows retain every original field except an unwritten picture.
@@ -5596,7 +5820,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
5596
5820
  }
5597
5821
  let altPairs: SeamPairRow[] | null = null;
5598
5822
  if (seamPairsAsked || altFailed) {
5599
- const split = seamPairRows(altSeam, altPlaced, inp.parts.rig_size, altCanonical.viewport);
5823
+ const split = population.rows(altSeam);
5600
5824
  const altSeamDir = join(seamDir, alt.name);
5601
5825
  mkdirSync(altSeamDir, { recursive: true });
5602
5826
  for (const { row, pixels } of split) {