@rig-c/parts 1.55.2 → 1.57.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/rig.ts CHANGED
@@ -83,8 +83,9 @@
83
83
  * transparent edge and the render changes at rest — measured on the demo
84
84
  * example, 36 px of the setup pose (max 7 levels) — while a clear-row cut
85
85
  * changes no pixel outside the blink (issue #26, `RG16`). A `painting:`
86
- * patch (`assemble.patches`) is always a region; its slot sits where
87
- * parts.json puts it, which is where its `draw` put it.
86
+ * patch (`assemble.patches`) is always a region. With declared limbs, an
87
+ * exclusively bound rider joins its limb's slot block (issue #646), keeping
88
+ * that limb's internal draw order; other patches keep the parts order.
88
89
  * - **The idle** and, under `idleKeys: 'ctl'` (the default), its control
89
90
  * bones (`src/motion.ts`). Under `idleKeys: 'direct'` the keys stay on the
90
91
  * bones the meshes are weighted to, no `<bone>_ctl` is added, and the rig
@@ -167,6 +168,8 @@ import { type ContourChainRibs, type ContourReport, contourMesh, type ContourReg
167
168
  import { type LocalInfluence, localInfluences } from './localweights.ts';
168
169
  import { edgeLength } from './length.ts';
169
170
  import { skeletonLimbJoints } from './limbs.ts';
171
+ import { coalesceLimbSlots } from './limbslots.ts';
172
+ import { layoutAlias, placeLimbLayouts, type LayoutPlan } from './limblayout.ts';
170
173
  import { artCoverage, ART_ALPHA, latticeCells, latticeMesh, latticeStray, ONE_LOOP_PASSES } from './mesh.ts';
171
174
  import { bindFaceSurfaceDeform, BLINK, blinkHoldMisses, blinkSpan, CONTROL_SUFFIX, controlledBones, IDLE_FPS, idleMotion, type MotionSpec, moveKeysToControls } from './motion.ts';
172
175
  import { type AlternateSetMap, PAINTING_RUN, type PartsFile, readFrom, tagOf } from './parts.ts';
@@ -1077,6 +1080,8 @@ export interface AttachmentSetsFile {
1077
1080
 
1078
1081
  export interface RigOutput {
1079
1082
  rig: RigSpec;
1083
+ /** Internal explicit-layout provenance; serialized only as an external companion. */
1084
+ layout?: LayoutPlan;
1080
1085
  motion: MotionSpec;
1081
1086
  meshReport: MeshReport[];
1082
1087
  /** The padded images, by file name (`<part>.png`), in parts.json order. */
@@ -1239,6 +1244,43 @@ export function buildRig(
1239
1244
  const CX = W / 2;
1240
1245
  const byPart = new Map(parts.parts.map((p) => [p.name, p]));
1241
1246
 
1247
+ // Standalone rig checks source-bound normalization, never reconstructing
1248
+ // original dimensions from nominal scale or treating source points as rig points.
1249
+ for (const a of parts.alternates ?? []) {
1250
+ if (a.tips === undefined && a.tips_source_size === undefined) continue;
1251
+ const size = a.tips_source_size;
1252
+ if (a.tips === undefined || !Array.isArray(size) || size.length !== 2 || !size.every((n) => typeof n === 'number' && Number.isInteger(n) && n > 0)
1253
+ || Math.trunc(size[0] * parts.scale_rig_per_source) !== W || Math.trunc(size[1] * parts.scale_rig_per_source) !== H) {
1254
+ fail('RIG_ALT_TIPS_SOURCE', `parts.json alternate set "${a.name}" tips_source_size`, 'requires the original source dimensions that produce rig_size at scale_rig_per_source; re-run assemble to record normalization provenance');
1255
+ }
1256
+ }
1257
+ refuseIfAny(problems);
1258
+ for (const a of cfg.assemble.alternates ?? cfg.alternates ?? []) {
1259
+ const record = parts.alternates?.find((p) => p.name === a.name);
1260
+ if (a.tips === undefined) {
1261
+ if (record?.tips !== undefined) {
1262
+ fail('RIG_ALT_TIPS_MATCH_CONFIG', `parts.json alternate set "${a.name}" tips`, 'records endpoints while the matching config set has no tips; re-run assemble after removing source-crop tips');
1263
+ }
1264
+ continue;
1265
+ }
1266
+ if (record?.tips === undefined) {
1267
+ fail('RIG_ALT_TIPS_RECORDED', `parts.json alternate set "${a.name}" tips`, 'is absent while config declares source-crop tips; re-run assemble to record normalized endpoints before rig');
1268
+ continue;
1269
+ }
1270
+ const [sw, sh] = record.tips_source_size as [number, number];
1271
+ const configured = Object.keys(a.tips).sort(), recorded = Object.keys(record.tips).sort();
1272
+ if (configured.length !== recorded.length || configured.some((bone, i) => bone !== recorded[i])) {
1273
+ fail('RIG_ALT_TIPS_MATCH_CONFIG', `parts.json alternate set "${a.name}" tips`, `records bones [${recorded.join(', ')}] while config declares [${configured.join(', ')}]; re-run assemble after changing source-crop tips`);
1274
+ } else for (const bone of configured) {
1275
+ const raw = a.tips[bone], found = record.tips[bone];
1276
+ const expected: Point = [raw[0] * (W / sw), raw[1] * (H / sh)];
1277
+ if (!Array.isArray(found) || found.length !== 2 || found[0] !== expected[0] || found[1] !== expected[1]) {
1278
+ fail('RIG_ALT_TIPS_MATCH_CONFIG', `parts.json alternate set "${a.name}" tips.${bone}`, `is ${JSON.stringify(found)}; config source-crop tip ${JSON.stringify(raw)} on ${sw}x${sh} requires rig-crop ${JSON.stringify(expected)}; re-run assemble, never reinterpret or silently replace recorded endpoints`);
1279
+ }
1280
+ }
1281
+ }
1282
+ refuseIfAny(problems);
1283
+
1242
1284
  // ---- bones -------------------------------------------------------------
1243
1285
  const B = new Map<string, Bone>();
1244
1286
  B.set(ROOT_BONE, { name: ROOT_BONE, parent: null, x: CX, y: H });
@@ -1693,6 +1735,11 @@ export function buildRig(
1693
1735
 
1694
1736
  // ---- attachments -------------------------------------------------------
1695
1737
  const slots: RigSpec['slots'] = [];
1738
+ const slotFamilies = new Map<string, string[]>();
1739
+ const addSlots = (part: string, ...rows: RigSpec['slots']): void => {
1740
+ slots.push(...rows);
1741
+ slotFamilies.set(part, [...(slotFamilies.get(part) ?? []), ...rows.map((s) => s.name)]);
1742
+ };
1696
1743
  const skin: RigSpec['skins']['default'] = {};
1697
1744
  const meshReport: MeshReport[] = [];
1698
1745
  const outImages: Array<[string, Raster]> = [];
@@ -2219,12 +2266,12 @@ export function buildRig(
2219
2266
  const cyUp = p.y + r / 2;
2220
2267
  skin[p.name] = { [p.name]: region(file, bone.name, cx, cyLow) };
2221
2268
  skin[still] = { [still]: region(stillFile, sb.name, cx, cyUp) };
2222
- slots.push({ name: p.name, bone: bone.name, attachment: p.name }, { name: still, bone: sb.name, attachment: still });
2269
+ addSlots(p.name, { name: p.name, bone: bone.name, attachment: p.name }, { name: still, bone: sb.name, attachment: still });
2223
2270
  continue;
2224
2271
  }
2225
2272
  const cy = p.y + p.h / 2;
2226
2273
  skin[p.name] = { [p.name]: region(file, bone.name, cx, cy) };
2227
- slots.push({ name: p.name, bone: bone.name, attachment: p.name });
2274
+ addSlots(p.name, { name: p.name, bone: bone.name, attachment: p.name });
2228
2275
  continue;
2229
2276
  }
2230
2277
  const segs = meshSegments.get(p.name) as Segment[];
@@ -2232,7 +2279,7 @@ export function buildRig(
2232
2279
  const row = autoAttachment(p, img, file, mesh.auto, mesh.r, mesh.exponent, segs, mesh.rule ?? 'distance', mesh, problems);
2233
2280
  if (row === null) continue;
2234
2281
  skin[p.name] = { [p.name]: row.attachment };
2235
- slots.push({ name: p.name, bone: segs[0].bone, attachment: p.name });
2282
+ addSlots(p.name, { name: p.name, bone: segs[0].bone, attachment: p.name });
2236
2283
  meshReport.push(row.report);
2237
2284
  autoMotion.push(row.motion);
2238
2285
  continue;
@@ -2241,7 +2288,7 @@ export function buildRig(
2241
2288
  const row = contourAttachment(p, img, file, mesh.contour, mesh.r, mesh.exponent, segs, mesh.rule ?? 'distance', mesh, mesh.influences, problems);
2242
2289
  if (row === null) continue;
2243
2290
  skin[p.name] = { [p.name]: row.attachment };
2244
- slots.push({ name: p.name, bone: segs[0].bone, attachment: p.name });
2291
+ addSlots(p.name, { name: p.name, bone: segs[0].bone, attachment: p.name });
2245
2292
  meshReport.push(row.report);
2246
2293
  continue;
2247
2294
  }
@@ -2249,7 +2296,7 @@ export function buildRig(
2249
2296
  const row = influenceAttachment(p, img, file, mesh, segs, meshSegmentEntries.get(p.name) as number[], problems);
2250
2297
  if (row === null) continue;
2251
2298
  skin[p.name] = { [p.name]: row.attachment };
2252
- slots.push({ name: p.name, bone: segs[0].bone, attachment: p.name });
2299
+ addSlots(p.name, { name: p.name, bone: segs[0].bone, attachment: p.name });
2253
2300
  meshReport.push(row.report);
2254
2301
  continue;
2255
2302
  }
@@ -2329,7 +2376,7 @@ export function buildRig(
2329
2376
  const uvs: number[] = [];
2330
2377
  for (const [x, y] of lm.vertices) uvs.push(pyRound(x / w, 6), pyRound(y / h, 6));
2331
2378
  skin[p.name] = { [p.name]: { type: 'mesh', image: file, width: w, height: h, uvs, triangles: lm.triangles, hull: lm.hull, weights } };
2332
- slots.push({ name: p.name, bone: segs[0].bone, attachment: p.name });
2379
+ addSlots(p.name, { name: p.name, bone: segs[0].bone, attachment: p.name });
2333
2380
  meshReport.push({
2334
2381
  part: p.name,
2335
2382
  vertices: lm.vertices.length,
@@ -2360,6 +2407,13 @@ export function buildRig(
2360
2407
  const setEntries: Record<string, AlternateSetMap> = {};
2361
2408
  for (const [altIdx, alt] of parts.alternates.entries()) {
2362
2409
  const cfgAlt = cfg.alternates?.find((a) => a.name === alt.name);
2410
+ for (const [bone, tip] of Object.entries(alt.tips ?? {})) {
2411
+ if (bone === ROOT_BONE || !B.has(bone)) fail('RIG_NAME_RESOLVES', `parts.json alternates[${altIdx}].tips.${bone}`, `names "${bone}", which config.bones does not declare; re-run assemble with declared bone names`);
2412
+ if (!Array.isArray(tip) || tip.length !== 2 || !tip.every((n) => typeof n === 'number' && Number.isFinite(n))) {
2413
+ fail('RIG_ALT_TIP_POINT', `parts.json alternates[${altIdx}].tips.${bone}`, 'requires a finite [x, y] endpoint in rig-crop pixels');
2414
+ }
2415
+ }
2416
+ refuseIfAny(problems);
2363
2417
  const explicitDrawn = alt.drawn ?? cfgAlt?.drawn;
2364
2418
  const isSubsetSet = alt.parts !== undefined || cfgAlt?.parts !== undefined;
2365
2419
  let coveredBones: Set<string> | null = null;
@@ -2433,6 +2487,7 @@ export function buildRig(
2433
2487
  continue;
2434
2488
  }
2435
2489
  const fullSegs = meshSegments.get(p.name) as Segment[];
2490
+ const explicitSegments = new Map(fullSegs.map((s, k) => [s, typeof mesh.segments[(meshSegmentEntries.get(p.name) as number[])[k]] !== 'string']));
2436
2491
  const baseAtt = skin[p.name]?.[p.name];
2437
2492
  const baseBones = baseAtt !== undefined && 'type' in baseAtt ? new Set(baseAtt.weights.flatMap((v) => v.map((e) => e.bone))) : null;
2438
2493
  const filteredSegs = baseBones !== null && baseBones.size > 0 ? fullSegs.filter((s) => baseBones.has(s.bone)) : fullSegs;
@@ -2450,8 +2505,23 @@ export function buildRig(
2450
2505
  alt.skeleton === undefined ? null : new Map(skeletonLimbJoints(alt.skeleton).map(([bone, a, b]) => [bone, [pt(a), pt(b)] as const]));
2451
2506
  segs = segs.map((s) => {
2452
2507
  const skPair = skSegs?.get(s.bone);
2453
- return skPair !== undefined ? { bone: s.bone, a: skPair[0], b: skPair[1] } : { bone: s.bone, a: movePt(s.bone, s.a), b: movePt(s.bone, s.b) };
2508
+ const moved = skPair !== undefined ? { bone: s.bone, a: skPair[0], b: skPair[1] } : { bone: s.bone, a: movePt(s.bone, s.a), b: movePt(s.bone, s.b) };
2509
+ explicitSegments.set(moved, explicitSegments.get(s) === true);
2510
+ return moved;
2454
2511
  });
2512
+ }
2513
+ if (alt.tips !== undefined) {
2514
+ segs = segs.map((s) => {
2515
+ // Coordinate tuples are independent authored geometry. Only a named
2516
+ // bone/chain endpoint takes the explicit alternate tip.
2517
+ const explicit = explicitSegments.get(s) === true;
2518
+ const end = alt.tips?.[s.bone];
2519
+ return explicit || end === undefined ? s : { ...s, b: [end[0], end[1]] };
2520
+ });
2521
+ }
2522
+ // Select against final endpoints, retaining each original entry's
2523
+ // tuple/named provenance through the preceding pose and base filters.
2524
+ if (drawn !== undefined) {
2455
2525
  const nonSkirt = segs.filter((s) => !hipChainLinks.has(s.bone));
2456
2526
  if (nonSkirt.length > 0) segs = nonSkirt;
2457
2527
  const yOverlapping = segs.filter((s) => Math.max(s.a[1], s.b[1]) >= p.y && Math.min(s.a[1], s.b[1]) <= p.y + p.h);
@@ -2558,14 +2628,19 @@ export function buildRig(
2558
2628
  };
2559
2629
  }
2560
2630
  const hasAlternateFaceSet = sets !== undefined && Object.values(sets.sets).some((e) => Object.hasOwn(e.slots, 'face'));
2631
+ // Read every base/alternate binding before rebinds; publish only the slot
2632
+ // permutation below, after stops/turn have used the original enumeration.
2633
+ const limbLayout = coalesceLimbSlots(cfg.limbs, bones, slots, skin);
2634
+ const explicitLayout = placeLimbLayouts(cfg.limbs, bones, limbLayout, skin, slotFamilies);
2561
2635
  // ---- leg stops (issue #404) --------------------------------------------
2562
2636
  // Only when the config has `stops`: each link after the first (and any bone hanging from a stopped link) hangs
2563
2637
  // from the drawn link `<link>_d` above it, and slots and weights on a stopped link bind `<link>_d`.
2564
- const stops = cfg.stops === undefined ? null : applyStops(cfg.stops, chains, bones, slots, skin);
2638
+ const stops = cfg.stops === undefined ? null : applyStops(cfg.stops, chains, bones, slots, skin, (original, emitted) => layoutAlias(explicitLayout.plan, original, emitted));
2565
2639
  // ---- the turn control (issue #251) -------------------------------------
2566
2640
  // Only when the config has `turn`: every other build adds nothing here, so no byte moves.
2567
2641
  if (cfg.turn !== undefined) refuseIfAny(turnRiderProblems(cfg.turn, cfg, parts.parts));
2568
2642
  const turned = cfg.turn === undefined ? null : applyTurn(cfg.turn, parts.parts.map((p) => p.name), bones, slots, skin, cfg.constraints ?? []);
2643
+ for (const row of turned?.rows ?? []) for (const t of row.twins) layoutAlias(explicitLayout.plan, t.bone, t.twin);
2569
2644
  // issue #536: every row names the bones the emitted attachment binds, read once the turn and the stops have
2570
2645
  // rebound the weights; a rig with neither rebinds nothing, so this reads back the names each row already holds.
2571
2646
  for (const row of meshReport) {
@@ -2580,7 +2655,7 @@ export function buildRig(
2580
2655
  images: 'images',
2581
2656
  skeleton: { x: -CX, y: 0, width: W, height: H },
2582
2657
  bones,
2583
- slots,
2658
+ slots: explicitLayout.slots,
2584
2659
  skins: { default: skin },
2585
2660
  };
2586
2661
  if (cfg.constraints !== undefined) rig.constraints = cfg.constraints.map(constraintForRig);
@@ -2633,6 +2708,7 @@ export function buildRig(
2633
2708
  faceAxis,
2634
2709
  turn: turned?.rows ?? null,
2635
2710
  ...(sets === undefined ? {} : { sets }),
2711
+ ...(explicitLayout.plan === undefined ? {} : { layout: explicitLayout.plan }),
2636
2712
  };
2637
2713
  }
2638
2714
 
@@ -2829,12 +2905,13 @@ function applyStops(
2829
2905
  bones: RigBone[],
2830
2906
  slots: RigSpec['slots'],
2831
2907
  skin: RigSpec['skins']['default'],
2908
+ alias?: (original: string, emitted: string) => void,
2832
2909
  ): RigStop[] {
2833
2910
  const out: RigStop[] = [];
2834
2911
  const drawn = new Map<string, string>();
2835
2912
  for (const s of stops) {
2836
2913
  const links = s.links ?? chains.get(s.chain) ?? [];
2837
- for (const l of links) drawn.set(l, `${l}_d`);
2914
+ for (const l of links) { drawn.set(l, `${l}_d`); alias?.(l, `${l}_d`); }
2838
2915
  out.push(stopForRig(s, links));
2839
2916
  }
2840
2917
  for (const b of bones) {