@rig-c/parts 1.51.0 → 1.53.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
@@ -58,8 +58,8 @@
58
58
  * setup pose with the flat stack of parts, and a pixel no part holds is
59
59
  * missing from both. When `motion.json` holds an animation, one more bar,
60
60
  * `ANIMATIONS_DO_NOT_FOLD` (issues #320, #333): rigc's own `render --folds`
61
- * over every animation, the idle included, physics constraints left out
62
- * ({@link FOLD_LINE}). Beside it, where a `footwear` part rides a bone that
61
+ * over every animation, the idle included, posed with physics stepping and
62
+ * again with the physics constraints left out (issue #363; {@link FOLD_LINE}). Beside it, where a `footwear` part rides a bone that
63
63
  * hangs from another, `FEET_STAY_LEVEL` (issue #348): the same render, with
64
64
  * `--geometry`, read for how far each such part's drawing turns while a bone
65
65
  * above it is turned ({@link LEVEL_LINE}). The part-alone renders, the shut-eye still, the keyed
@@ -124,6 +124,7 @@ import {
124
124
  halfTravels,
125
125
  chainToward,
126
126
  type Toward,
127
+ type ChainEdge,
127
128
  type WorldBox,
128
129
  } from './instruments.ts';
129
130
  import { type AlternatePartsRecord, type LimbRecord, type PartRecord, type PartsFile, readParts } from './parts.ts';
@@ -1922,8 +1923,9 @@ export interface RequirementsBlock {
1922
1923
  * requirements file's `may_fold`, by slot and animation with its why, and is
1923
1924
  * named and not held to the bar.
1924
1925
  *
1925
- * ⭐ **Read with the physics constraints left out**, as the loop is, from the
1926
- * same build ({@link withoutPhysics}). rig-c's render steps physics by 1/fps
1926
+ * ⭐ **Judged with physics on, and read again with the physics constraints left
1927
+ * out** (issue #363; before it, only the latter, from the same build as the loop,
1928
+ * {@link withoutPhysics}). rig-c's render steps physics by 1/fps
1927
1929
  * from frame 0, so a fold a physics constraint makes is the sampling rate's:
1928
1930
  * on the public `scarf` example `hop` folds `bottomwear` (3 of 308 triangles,
1929
1931
  * frames 7-8) at 12 fps, and at none of 10, 15, 24, 30, 36, 48 and 60 fps;
@@ -2294,6 +2296,8 @@ export interface FoldingMesh {
2294
2296
  frames: number;
2295
2297
  worstFrame: number;
2296
2298
  worstTriangles: number;
2299
+ /** The worst frame's folded triangles, by index into the mesh's triangle table, as rigc lists them (issue #567). */
2300
+ worstTriangleList: number[];
2297
2301
  line: string;
2298
2302
  }
2299
2303
 
@@ -2347,13 +2351,19 @@ export function readFoldSets(dir: string, named: readonly string[], fps: number,
2347
2351
  bad(at, `worst is ${JSON.stringify(m.worst)?.slice(0, 40)}; null or { index, triangles, … } is required`);
2348
2352
  return;
2349
2353
  }
2354
+ const list = worst.triangles;
2355
+ const notIndex = list.findIndex((t) => typeof t !== 'number' || !Number.isInteger(t) || t < 0);
2356
+ if (notIndex >= 0) {
2357
+ bad(at, `worst.triangles[${notIndex}] is ${JSON.stringify(list[notIndex])}; a triangle index, a whole number from 0, is required`);
2358
+ return;
2359
+ }
2350
2360
  const prefix = `${JSON.stringify(name)}: mesh "${m.attachment}" (slot "${m.slot}") folds on `;
2351
2361
  const line = lines.find((l) => l.startsWith(prefix));
2352
2362
  if (line === undefined) {
2353
2363
  bad(at, `folds on ${m.frames.length} frame(s), and rigc printed no line beginning ${prefix.trim()}`);
2354
2364
  return;
2355
2365
  }
2356
- rows.push({ slot: m.slot, attachment: m.attachment, triangleCount: m.triangleCount, frames: m.frames.length, worstFrame: worst.index, worstTriangles: worst.triangles.length, line });
2366
+ rows.push({ slot: m.slot, attachment: m.attachment, triangleCount: m.triangleCount, frames: m.frames.length, worstFrame: worst.index, worstTriangles: list.length, worstTriangleList: list as number[], line });
2357
2367
  });
2358
2368
  out.set(name, rows);
2359
2369
  }
@@ -2395,6 +2405,76 @@ export function meshPhysicsConstraints(rig: Record<string, unknown>, slot: strin
2395
2405
  return (direct.length > 0 ? direct : physics).map((p) => `${p.name} on ${p.bone}`);
2396
2406
  }
2397
2407
 
2408
+ /** How many groups of folded triangles {@link foldBonesText} spells out before it counts the rest (issue #567). */
2409
+ export const FOLD_GROUPS_SHOWN = 3;
2410
+ /** How many triangle indices one group lists before it counts the rest (issue #567). */
2411
+ export const FOLD_TRIANGLES_SHOWN = 6;
2412
+
2413
+ /**
2414
+ * Issue #567: what the folded triangles of a mesh's worst frame hang on, read off rig.json and motion.json, in the
2415
+ * stretch line's shape ({@link edgeBonesText}, issue #314) — so the cause reads off the line rather than off a hand
2416
+ * decoding of the weight runs. Each folded triangle's vertices are its three entries in the attachment's `triangles`
2417
+ * (rigc names a triangle by that index); each vertex's dominant bone is its largest weight (equal weights in rig.json's
2418
+ * order, as {@link edgeBonesText} ranks them); the triangles whose vertices share one set of dominant bones are one
2419
+ * group, in the order of their first triangle, the set written in rig.json's bone order. Each group lists its first
2420
+ * {@link FOLD_TRIANGLES_SHOWN} triangles and counts the rest, and spells out its first triangle's vertices with
2421
+ * {@link edgeBonesText}; the first {@link FOLD_GROUPS_SHOWN} groups are written and the rest counted. An attachment
2422
+ * the skin does not hold, a mesh with no triangle table, or a triangle the table does not reach is said rather than
2423
+ * guessed.
2424
+ */
2425
+ export function foldBonesText(rig: Record<string, unknown>, motion: Record<string, unknown>, slot: string, attachment: string, frame: number, triangles: readonly number[]): string {
2426
+ const head = `at worst frame ${frame}`;
2427
+ if (triangles.length === 0) return `${head} rigc lists no folded triangle`;
2428
+ const skins = isRecord(rig.skins) ? rig.skins : {};
2429
+ const skin = isRecord(skins.default) ? skins.default : {};
2430
+ const onSlot = isRecord(skin[slot]) ? skin[slot] : {};
2431
+ const att = onSlot[attachment];
2432
+ if (!isRecord(att)) return `${head} the folded triangles' bones are not read: rig.json's default skin holds no attachment "${attachment}" on slot "${slot}"`;
2433
+ const table = att.triangles;
2434
+ if (!Array.isArray(table) || !table.every((x) => typeof x === 'number' && Number.isInteger(x) && x >= 0)) return `${head} the folded triangles' bones are not read: rig.json's mesh "${attachment}" holds no triangle table of vertex indices`;
2435
+ const count = Math.floor(table.length / 3);
2436
+ const outside = triangles.filter((t) => t >= count);
2437
+ if (outside.length > 0) return `${head} the folded triangles' bones are not read: rig.json's mesh "${attachment}" lists ${count} triangle(s), and rigc names triangle ${outside.join(', ')}`;
2438
+ const verticesOf = (t: number): number[] => [table[3 * t] as number, table[3 * t + 1] as number, table[3 * t + 2] as number];
2439
+ const weights = Array.isArray(att.weights) ? att.weights : null;
2440
+ if (weights === null || verticesOf(triangles[0]).some((v) => !Array.isArray(weights[v]))) return `${head}, triangle ${triangles[0]} (vertices ${verticesOf(triangles[0]).join(' ')}): ${edgeBonesText(rig, motion, slot, attachment, verticesOf(triangles[0]))}`;
2441
+ const order = new Map((Array.isArray(rig.bones) ? rig.bones : []).filter(isRecord).map((b, i) => [String(b.name), i]));
2442
+ const dominant = (v: number): string | null => {
2443
+ const raw = weights[v];
2444
+ if (!Array.isArray(raw)) return null;
2445
+ const list = raw.filter(isRecord).filter((w) => typeof w.bone === 'string' && typeof w.weight === 'number') as Array<{ bone: string; weight: number }>;
2446
+ const top = [...list].sort((a, b) => b.weight - a.weight)[0];
2447
+ return top === undefined ? null : top.bone;
2448
+ };
2449
+ const groups: Array<{ key: string; bones: string[]; triangles: number[] }> = [];
2450
+ for (const t of triangles) {
2451
+ const vs = verticesOf(t);
2452
+ const doms = vs.map(dominant);
2453
+ if (doms.some((d) => d === null)) {
2454
+ groups.push({ key: `\u0000${t}`, bones: [], triangles: [t] });
2455
+ continue;
2456
+ }
2457
+ const bones = [...new Set(doms as string[])].sort((a, b) => (order.get(a) ?? Infinity) - (order.get(b) ?? Infinity) || (a < b ? -1 : a > b ? 1 : 0));
2458
+ const key = bones.join('\u0000');
2459
+ const g = groups.find((x) => x.key === key);
2460
+ if (g === undefined) groups.push({ key, bones, triangles: [t] });
2461
+ else g.triangles.push(t);
2462
+ }
2463
+ const quoted = (l: readonly string[]): string => l.map((n) => `"${n}"`).join(', ');
2464
+ const shown = groups.slice(0, FOLD_GROUPS_SHOWN).map((g) => {
2465
+ const first = g.triangles[0];
2466
+ const vs = verticesOf(first);
2467
+ const more = g.triangles.length - FOLD_TRIANGLES_SHOWN;
2468
+ const which = g.triangles.length === 1 ? `triangle ${first}` : `triangles ${g.triangles.slice(0, FOLD_TRIANGLES_SHOWN).join(', ')}${more > 0 ? ` and ${more} more` : ''}`;
2469
+ const by = g.bones.length === 0 ? '' : ` dominated by ${quoted(g.bones)}`;
2470
+ const spelled = g.triangles.length === 1 ? `vertices ${vs.join(' ')}` : `triangle ${first}, vertices ${vs.join(' ')}`;
2471
+ return `${which}${by} (${spelled}: ${edgeBonesText(rig, motion, slot, attachment, vs)})`;
2472
+ });
2473
+ const rest = groups.slice(FOLD_GROUPS_SHOWN);
2474
+ const restText = rest.length === 0 ? '' : `; … and ${rest.length} more group(s), ${rest.reduce((n, g) => n + g.triangles.length, 0)} triangle(s)`;
2475
+ return `${head} the ${triangles.length} folded triangle(s) hang on, by the bone each vertex weighs most: ${shown.join('; ')}${restText}`;
2476
+ }
2477
+
2398
2478
  /**
2399
2479
  * The fold line (issues #320, #333, #363) from the reading: posed with physics
2400
2480
  * stepping on the render clock (`readings`, and `readingsWithoutPhysics`
@@ -2404,7 +2484,9 @@ export function meshPhysicsConstraints(rig: Record<string, unknown>, slot: strin
2404
2484
  * animation, the slot, the physics constraint(s) on its bones and the worst
2405
2485
  * frame when the fold appears only with physics on, and rigc's line, and an
2406
2486
  * entry no row matches a problem of its own — a declaration that excepts
2407
- * nothing.
2487
+ * nothing. Since issue #567 the problem also names, for the worst frame's
2488
+ * folded triangles, the bones their vertices weigh most ({@link foldBonesText},
2489
+ * read off `rig` and `motion`).
2408
2490
  */
2409
2491
  export function foldsLine(
2410
2492
  named: readonly string[],
@@ -2417,10 +2499,13 @@ export function foldsLine(
2417
2499
  readingsWithoutPhysics: ReadonlyMap<string, readonly FoldingMesh[]> = readings,
2418
2500
  rig: Record<string, unknown> = {},
2419
2501
  physicsList: readonly LoopPhysics[] = [],
2502
+ motion: Record<string, unknown> = {},
2420
2503
  ): FoldsLine {
2421
2504
  const toSide = (m: FoldingMesh | undefined): FoldSide | null =>
2422
2505
  m === undefined ? null : { frames: m.frames, worst_frame: m.worstFrame, worst_triangles: m.worstTriangles, line: m.line };
2423
2506
  const folding: FoldRow[] = [];
2507
+ // Issue #567: each row's worst triangles, kept beside the row rather than in it, so check.json's row is unchanged.
2508
+ const worstOf = new Map<FoldRow, readonly number[]>();
2424
2509
  for (const name of named) {
2425
2510
  const onList = readings.get(name) ?? [];
2426
2511
  const offList = readingsWithoutPhysics.get(name) ?? [];
@@ -2440,7 +2525,7 @@ export function foldsLine(
2440
2525
  const entry = mayFold.find((e) => e.slot === slot && e.animation === name);
2441
2526
  const onlyPhysicsOn = on !== undefined && off === undefined;
2442
2527
  const constraints = onlyPhysicsOn ? meshPhysicsConstraints(rig, slot, attachment, physicsList) : [];
2443
- folding.push({
2528
+ const row: FoldRow = {
2444
2529
  animation: name,
2445
2530
  slot,
2446
2531
  attachment,
@@ -2453,7 +2538,9 @@ export function foldsLine(
2453
2538
  physics_constraints: constraints,
2454
2539
  declared: entry === undefined ? null : entry.why,
2455
2540
  line: primary.line,
2456
- });
2541
+ };
2542
+ folding.push(row);
2543
+ worstOf.set(row, primary.worstTriangleList);
2457
2544
  }
2458
2545
  }
2459
2546
  const physics =
@@ -2473,7 +2560,7 @@ export function foldsLine(
2473
2560
  problems.push({
2474
2561
  code: `CHECK_${FOLD_LINE}`,
2475
2562
  object: `animation "${r.animation}", mesh "${r.attachment}" (slot "${r.slot}")`,
2476
- detail: `rigc render --folds at ${fps} fps${physics}${sideClause}: ${r.line}; no triangle turned over against the setup pose is required — a fold the art means is declared in the --requirements file's may_fold, { "slot": "${r.slot}", "animation": "${r.animation}", "why": … }`,
2563
+ detail: `rigc render --folds at ${fps} fps${physics}${sideClause}: ${r.line}; ${foldBonesText(rig, motion, r.slot, r.attachment, r.worst_frame, worstOf.get(r) ?? [])}; no triangle turned over against the setup pose is required — a fold the art means is declared in the --requirements file's may_fold, { "slot": "${r.slot}", "animation": "${r.animation}", "why": … }`,
2477
2564
  });
2478
2565
  }
2479
2566
  const declaredNotFolding = mayFold.filter((e) => !folding.some((r) => r.slot === e.slot && r.animation === e.animation)).map((e) => ({ slot: e.slot, animation: e.animation }));
@@ -4048,7 +4135,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
4048
4135
  const fr = measured(['render', '--candidate', buildDir, '--folds', ...geometry, '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), '--out', foldDir]);
4049
4136
  if (fr.status !== 0) refuseIfAny(rigcFailed(`render --folds${geometry.map((g) => ` ${g}`).join('')} --fps ${fps}`, fr, fr.out.split('\n').filter((l) => l.includes('FAIL') || l.includes('rigc:'))));
4050
4137
  const readings = filterFolds(readFoldSets(foldDir, animationNames, fps, fr.out));
4051
- folds = foldsLine(animationNames, fps, 0, readings, mayFoldForRun, reqFile === null ? null : reqFile.path, foldProblems, readings, inp.rig, []);
4138
+ folds = foldsLine(animationNames, fps, 0, readings, mayFoldForRun, reqFile === null ? null : reqFile.path, foldProblems, readings, inp.rig, [], inp.motion);
4052
4139
  if (feet.length > 0) {
4053
4140
  const sets = readJson(join(foldDir, 'frames.json'), []);
4054
4141
  const listed = sets !== null && Array.isArray(sets.sets) ? sets.sets.filter(isRecord) : [];
@@ -4069,7 +4156,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
4069
4156
  if (frOff.status !== 0) refuseIfAny(rigcFailed(`render --folds${geometry.map((g) => ` ${g}`).join('')} --fps ${fps} (physics constraint(s) left out)`, frOff, frOff.out.split('\n').filter((l) => l.includes('FAIL') || l.includes('rigc:'))));
4070
4157
  const readingsOn = filterFolds(readFoldSets(onDir, animationNames, fps, frOn.out));
4071
4158
  const readingsOff = filterFolds(readFoldSets(offDir, animationNames, fps, frOff.out));
4072
- folds = foldsLine(animationNames, fps, stripped.physics.length, readingsOn, mayFoldForRun, reqFile === null ? null : reqFile.path, foldProblems, readingsOff, inp.rig, stripped.physics);
4159
+ folds = foldsLine(animationNames, fps, stripped.physics.length, readingsOn, mayFoldForRun, reqFile === null ? null : reqFile.path, foldProblems, readingsOff, inp.rig, stripped.physics, inp.motion);
4073
4160
  if (feet.length > 0) {
4074
4161
  const sets = readJson(join(offDir, 'frames.json'), []);
4075
4162
  const listed = sets !== null && Array.isArray(sets.sets) ? sets.sets.filter(isRecord) : [];
@@ -5799,6 +5886,46 @@ function fmt3(x: number): string {
5799
5886
  return x.toFixed(3);
5800
5887
  }
5801
5888
 
5889
+ /** A phase in cycles carried into [0, 1) at three decimals, so 0.9995 prints 0.000 and not 1.000. */
5890
+ function phase3(x: number): number {
5891
+ const r = round3((((x % 1) + 1) % 1));
5892
+ return r >= 1 ? 0 : r;
5893
+ }
5894
+
5895
+ /**
5896
+ * The child phases whose step from `parent` passes the floor: a step from {@link CHAIN_LAG_MIN_STEP} to 1/4 inclusive,
5897
+ * which, the step being read modulo half a cycle, is two windows a half cycle apart. Each is carried into [0, 1) and
5898
+ * split where it crosses the cycle's end, so every window printed is one an author can type.
5899
+ */
5900
+ export function chainLagWindows(parent: number): Array<[number, number]> {
5901
+ const out: Array<[number, number]> = [];
5902
+ for (const half of [0, 0.5]) {
5903
+ const lo = phase3(parent + half + CHAIN_LAG_MIN_STEP);
5904
+ const hi = phase3(parent + half + 0.25);
5905
+ if (lo <= hi) out.push([lo, hi]);
5906
+ else out.push([lo, 1], [0, hi]);
5907
+ }
5908
+ return out.sort((a, b) => a[0] - b[0]);
5909
+ }
5910
+
5911
+ /**
5912
+ * Issue #580: the detail of a step refusal. The step alone ("-0.230") read as advice to raise the phase or flip the
5913
+ * amplitude's sign, neither of which moves it until the phase has gone half a cycle; so the line says the raw phases
5914
+ * it read, that the step is their difference folded into (-1/4, 1/4] (a sine's sign is half a cycle, so a sign flip
5915
+ * does not change it), and the child phases that would pass for this parent.
5916
+ */
5917
+ export function chainStepDetail(e: Pick<ChainEdge, 'parent' | 'child' | 'step' | 'parentPhase' | 'childPhase'>): string {
5918
+ const windows = chainLagWindows(e.parentPhase)
5919
+ .map(([lo, hi]) => (hi === 1 ? `[${fmt3(lo)}, 1)` : `[${fmt3(lo)}, ${fmt3(hi)}]`))
5920
+ .join(' or ');
5921
+ return (
5922
+ `phase step ${fmt3(e.step)} cycle(s); >= ${CHAIN_LAG_MIN_STEP} is required — a link must lag the one above it. ` +
5923
+ `Phases read: "${e.parent}" ${fmt3(phase3(e.parentPhase))}, "${e.child}" ${fmt3(phase3(e.childPhase))} (a negative amplitude is read as amplitude > 0 at phase + 0.5); ` +
5924
+ `the step is their difference, ${fmt3(phase3(e.childPhase - e.parentPhase))}, folded into (-1/4, 1/4] cycle, since a sine's sign is half a cycle — so flipping an amplitude's sign does not change it. ` +
5925
+ `To pass, the child's phase is the parent's + ${CHAIN_LAG_MIN_STEP} to + 0.25, modulo 0.5: here a "${e.child}" phase in ${windows} (its "phase", or the "lag" on the chain track)`
5926
+ );
5927
+ }
5928
+
5802
5929
  /** The scene file's `rests` parts as `CHAIN_LAG` reads them (issue #245), and the file they were read from. */
5803
5930
  export interface ChainRests {
5804
5931
  path: string;
@@ -5835,7 +5962,7 @@ export function chainLine(inp: Pick<CheckInputs, 'rig' | 'motion'>, problems: Pr
5835
5962
  if (round3(e.step) < CHAIN_LAG_MIN_STEP) {
5836
5963
  const v = `"${e.child}" follows its keyed ancestor "${e.parent}" by ${fmt3(e.step)} cycle(s)`;
5837
5964
  violations.push(v);
5838
- problems.push({ code: 'CHECK_CHAIN_LAG', object: `bone "${e.child}" under "${e.parent}"`, detail: `phase step ${fmt3(e.step)} cycle(s); >= ${CHAIN_LAG_MIN_STEP} is required — a link must lag the one above it (a larger "phase", or a positive "lag" on the chain track)` });
5965
+ problems.push({ code: 'CHECK_CHAIN_LAG', object: `bone "${e.child}" under "${e.parent}"`, detail: chainStepDetail(e) });
5839
5966
  }
5840
5967
  }
5841
5968
  for (const c of long) {
@@ -15,9 +15,12 @@
15
15
  * move keeps the input's bytes.
16
16
  */
17
17
 
18
+ import type { CharacterConfig } from './config.ts';
18
19
  import { PartsError, type Problem } from './errors.ts';
20
+ import { chainFigures } from './instruments.ts';
19
21
  import { type ConfigEdit, splicedEdits } from './meshdraft.ts';
20
- import { PROPOSAL_CONFIG_SECTIONS, type Proposal } from './propose.ts';
22
+ import { idleMotion } from './motion.ts';
23
+ import { type ChainLeftBehindFinding, PROPOSAL_CONFIG_SECTIONS, type Proposal } from './propose.ts';
21
24
 
22
25
  function isPlain(v: unknown): v is Record<string, unknown> {
23
26
  return typeof v === 'object' && v !== null && !Array.isArray(v);
@@ -279,3 +282,77 @@ export function previousCount(edits: readonly ClothEdit[]): number {
279
282
  export function editPaths(edits: readonly ClothEdit[]): string[] {
280
283
  return edits.map((e) => e.label);
281
284
  }
285
+
286
+ /** One config's keyed chains as `CHAIN_LAG` reads them: the rig's bone tree from `bones`, and the idle `idleMotion` writes. */
287
+ function keyedChains(cfg: CharacterConfig): { figures: ReturnType<typeof chainFigures>; field: Map<string, string> } {
288
+ const bones: Array<{ name: string; parent: string | null }> = [];
289
+ const links = new Map<string, string[]>();
290
+ for (const e of cfg.bones) {
291
+ if ('chain' in e) {
292
+ const names = e.points.map((_, k) => `${e.chain}${k}`);
293
+ names.forEach((n, k) => bones.push({ name: n, parent: k === 0 ? e.parent : names[k - 1] }));
294
+ links.set(e.chain, names);
295
+ } else bones.push({ name: e.name, parent: e.parent });
296
+ }
297
+ // The config field that keys each bone's rotation, as the author would edit it.
298
+ const field = new Map<string, string>();
299
+ for (const t of cfg.motion.tracks) {
300
+ if ('chain' in t) (links.get(t.chain) ?? []).forEach((n, i) => field.set(n, `motion.tracks chain "${t.chain}" amps[${i}]`));
301
+ else if (t.prop === 'rotate') field.set(t.bone, `motion.tracks bone "${t.bone}" prop "rotate" amp`);
302
+ }
303
+ // check reads motion.json as written; the round trip through JSON is that file's shape.
304
+ const motion = JSON.parse(JSON.stringify(idleMotion(cfg, links))) as Record<string, unknown>;
305
+ return { figures: chainFigures({ bones }, motion), field };
306
+ }
307
+
308
+ /** The config field keying `bone`; every rotate-keyed bone of the idle is keyed by a config track, so a miss is this module's error. */
309
+ function fieldOf(field: ReadonlyMap<string, string>, bone: string): string {
310
+ const f = field.get(bone);
311
+ if (f === undefined) throw new Error(`chainsLeftBehind: no config track keys the rotation of "${bone}"`);
312
+ return f;
313
+ }
314
+
315
+ /** Python's `round(x, 3)`, as check's `CHAIN_LAG` rounds both amplitudes before it compares them (`src/check.ts`, `chainLine`). */
316
+ function round3(x: number): number {
317
+ return Number(x.toFixed(3));
318
+ }
319
+
320
+ /**
321
+ * Issue #572: the links `CHAIN_LAG` would refuse after the recipe that it did not read before. `before` is the config
322
+ * the recipe drafts into (the plain draft, or the `--cloth` config `--write-config` splices) and `after` the one it
323
+ * hands back (the draft with the recipe, or the config written), each read with `CHAIN_LAG`'s own reader,
324
+ * `chainFigures` over the bone tree and the idle the rig stage writes. A pair `above > bone` adjacent in a run of
325
+ * `after` and in no run of `before` is a run the recipe made — it took the idle keys off `above`'s other keyed
326
+ * children — and where `bone`'s amplitude falls below `above`'s (both to three places, as check compares them) it is a
327
+ * finding. A pair `before` already ran is check's to name, as it was. Nothing is changed: the amplitude is the
328
+ * author's. Rotate tracks under one control (`<bone>_ctl`) keep the same tree, so the config's bones read as the rig's.
329
+ */
330
+ export function chainsLeftBehind(before: CharacterConfig, after: CharacterConfig): ChainLeftBehindFinding[] {
331
+ const b = keyedChains(before).figures;
332
+ const a = keyedChains(after);
333
+ const ran = new Set<string>();
334
+ for (const c of b.chains) for (let i = 1; i < c.length; i++) ran.add(`${c[i - 1].bone}>${c[i].bone}`);
335
+ const keyedUnder = (f: ReturnType<typeof chainFigures>, p: string): string[] => [...f.edges.filter((e) => e.parent === p).map((e) => e.child), ...f.otherPeriod.filter((e) => e.parent === p).map((e) => e.child)];
336
+ const out: ChainLeftBehindFinding[] = [];
337
+ for (const c of a.figures.chains) {
338
+ for (let i = 1; i < c.length; i++) {
339
+ const above = c[i - 1].bone;
340
+ const bone = c[i].bone;
341
+ const hi = round3(c[i - 1].reading.amp);
342
+ const lo = round3(c[i].reading.amp);
343
+ if (!(lo < hi) || ran.has(`${above}>${bone}`)) continue;
344
+ const now = new Set(keyedUnder(a.figures, above));
345
+ out.push({
346
+ kind: 'chain-left-behind',
347
+ bone,
348
+ above,
349
+ chain: c.map((l) => l.bone),
350
+ amp: lo,
351
+ aboveAmp: hi,
352
+ siblings: keyedUnder(b, above).filter((s) => !now.has(s)),
353
+ field: fieldOf(a.field, bone),
354
+ });
355
+ }
356
+ }
357
+ return out;
358
+ }
package/src/config.ts CHANGED
@@ -213,7 +213,9 @@ export interface Patch {
213
213
  * `draw` places a patch. What the config alone cannot know — whether the
214
214
  * polygon lies inside the rig, takes any of the layer's art, or overlaps
215
215
  * another cut of the same part — the assemble stage refuses
216
- * (`ASSEMBLE_CUT_INSIDE`, `ASSEMBLE_CUT_PIXELS`, `ASSEMBLE_CUT_OVERLAP`).
216
+ * (`ASSEMBLE_CUT_INSIDE`, `ASSEMBLE_CUT_PIXELS`, `ASSEMBLE_CUT_OVERLAP`), and,
217
+ * for a `from` a limb takes (issue #564), whether the polygon takes a pixel a
218
+ * segment of the limb holds (`ASSEMBLE_CUT_CROSSES_LIMB`).
217
219
  */
218
220
  export interface Cut {
219
221
  from: string;
@@ -891,7 +893,9 @@ export interface ConfigStop {
891
893
  * the joint (issue #360, `src/limbs.ts`): `edge: "feather"` fades the upper
892
894
  * piece out across the cap, and `cap_shape: "disc"` sizes the cap by the
893
895
  * limb's half-width about the joint and fills it from the art, the upper
894
- * segment's included. Absent, the cut
896
+ * segment's included; `cap_shape: "ball"` (issue #579) is that disc on both
897
+ * sides of the joint line, its lower half written into the lower piece from
898
+ * the cap image where the piece's layer is transparent. Absent, the cut
895
899
  * is hard and the cap the layer's half-disc of half the limb's width. A third,
896
900
  * `cut_band: N` (issue #360, item 14), places the cut on the line within N px
897
901
  * of the joint line that crosses the fewest stroke pixels; absent, the cut is
@@ -905,7 +909,7 @@ export interface LimbSegment {
905
909
  range?: [number, number];
906
910
  cap?: string;
907
911
  edge?: 'feather';
908
- cap_shape?: 'disc';
912
+ cap_shape?: 'disc' | 'ball';
909
913
  /** Issue #360 (item 14): the half-width, whole rig px, of the band about the joint line the cut is placed in (`placeCut` in `src/limbs.ts`). Absent, the cut is the joint line. */
910
914
  cut_band?: number;
911
915
  }
@@ -1537,7 +1541,7 @@ function parseConfigFrom(raw: Json, base: string | null): { config: CharacterCon
1537
1541
  if ('cloth' in t) checkCloth(c, t.cloth);
1538
1542
  if ('requirements' in t && c.string('config.requirements', t.requirements) && base !== null) checkRequirementsFile(c, resolve(base, t.requirements));
1539
1543
  const from = isPlainObject(t.motion) ? t.motion.animations_from : undefined;
1540
- const animations = base !== null && typeof from === 'string' && from !== '' ? readAnimationsFrom(c, resolve(base, from)) : null;
1544
+ const animations = base !== null && typeof from === 'string' && from !== '' ? readAnimationsFrom(c, base, from) : null;
1541
1545
  if (animations !== null) {
1542
1546
  checkFaceAnimationBand(c, animations, hasAltFace, t.turn, attached);
1543
1547
  checkAnimationSetKeys(c, animations, t.assemble, new Set<string>([...parts, ...patches, ...cuts, ...(limbs?.parts.keys() ?? [])]));
@@ -1592,13 +1596,18 @@ function checkRequirementsFile(c: Check, file: string): void {
1592
1596
  * Read the file `motion.animations_from` names (issue #183) and vouch for what
1593
1597
  * merging its animations beside the idle needs, every problem collected in `c`:
1594
1598
  *
1595
- * - `CONFIG_FILE_PRESENT`: no such file, or a file that cannot be read.
1599
+ * - `CONFIG_FILE_PRESENT`: no such file, or a file that cannot be read. The
1600
+ * line names the path as typed, the config's directory it was resolved
1601
+ * against and what that gave (issue #569): the path is read beside the
1602
+ * config, not in the working directory, and a reader who cannot see the
1603
+ * disk needs all three to tell which was wrong.
1596
1604
  * - `CONFIG_IS_JSON`: the text does not parse.
1597
1605
  * - `CONFIG_FIELD_TYPE`: the file is not an object, its `spec` is not
1598
1606
  * "rigc-motion/1", its `animations` is not an object, or an animation in it
1599
1607
  * is not one. `CONFIG_KEY_KNOWN` / `CONFIG_FIELD_PRESENT`: a key besides
1600
1608
  * `spec` and `animations` (and the annotation and record doors), or one of
1601
- * the two absent. rig-c's `easings`, `groups`, `setup`, `physics` and `mix`
1609
+ * the two absent; an absent `spec` is told the line to write and the whole
1610
+ * file's shape (issue #569), from {@link ANIMATIONS_FROM_SPEC}. rig-c's `easings`, `groups`, `setup`, `physics` and `mix`
1602
1611
  * are refused rather than dropped: `motion.json`'s own are this package's,
1603
1612
  * and a table read and not written would be a value lost without a word.
1604
1613
  * - `CONFIG_ANIMATION_NAME_FREE`: an animation named `idle`, the one the
@@ -1609,18 +1618,21 @@ function checkRequirementsFile(c: Check, file: string): void {
1609
1618
  *
1610
1619
  * Returns the animations when this file added no problem, else null.
1611
1620
  */
1612
- function readAnimationsFrom(c: Check, file: string): AnimationsFrom | null {
1621
+ function readAnimationsFrom(c: Check, base: string, from: string): AnimationsFrom | null {
1613
1622
  const field = 'config.motion.animations_from';
1614
- const shape = `a file in rig-c's motion-spec shape, {"spec": "${ANIMATIONS_FROM_SPEC}", "animations": {"<name>": {"duration": …, "tracks": [...]}}}, its path relative to the config's directory`;
1623
+ const file = resolve(base, from);
1624
+ const form = `{"spec": "${ANIMATIONS_FROM_SPEC}", "animations": {"<name>": {"duration": …, "tracks": [...]}}}`;
1625
+ const shape = `a file in rig-c's motion-spec shape, ${form}, its path relative to the config's directory`;
1626
+ const where = `names ${JSON.stringify(from)}, resolved against the config's directory ${base} (not the working directory) to ${file}`;
1615
1627
  if (!existsSync(file) || !statSync(file).isFile()) {
1616
- c.fail('CONFIG_FILE_PRESENT', field, `names ${file}, which is no such file; ${shape} is required`);
1628
+ c.fail('CONFIG_FILE_PRESENT', field, `${where}, which is no such file; ${shape} is required`);
1617
1629
  return null;
1618
1630
  }
1619
1631
  let text: string;
1620
1632
  try {
1621
1633
  text = readFileSync(file, 'utf8');
1622
1634
  } catch (err) {
1623
- c.fail('CONFIG_FILE_PRESENT', field, `names ${file}, which cannot be read: ${(err as Error).message}; ${shape} is required`);
1635
+ c.fail('CONFIG_FILE_PRESENT', field, `${where}, which cannot be read: ${(err as Error).message}; ${shape} is required`);
1624
1636
  return null;
1625
1637
  }
1626
1638
  let raw: Json;
@@ -1643,7 +1655,13 @@ function readAnimationsFrom(c: Check, file: string): AnimationsFrom | null {
1643
1655
  `names "${r.key}" ${r.count === 2 ? 'twice' : `${r.count} times`}; each key once is required — JSON keeps only the last, so ${r.at === 'animations' ? 'every animation of that name but the last' : 'every value but the last'} would be dropped without a word`,
1644
1656
  );
1645
1657
  }
1646
- const o = c.object(at, raw, ['spec', 'animations'], []);
1658
+ // Both keys are required; `c.object` is given them as optional so an absent
1659
+ // `spec` can be told the line to write, in the order `c.object` names them.
1660
+ const o = c.object(at, raw, [], ['spec', 'animations']);
1661
+ if (o !== null && !('spec' in o)) {
1662
+ c.fail('CONFIG_FIELD_PRESENT', `${at}.spec`, `is absent and required: write "spec": "${ANIMATIONS_FROM_SPEC}" beside "animations", the motion-spec version motion.json states — the whole file is ${form}`);
1663
+ }
1664
+ if (o !== null && !('animations' in o)) c.fail('CONFIG_FIELD_PRESENT', `${at}.animations`, 'is absent and required');
1647
1665
  if (o !== null && 'spec' in o && o.spec !== ANIMATIONS_FROM_SPEC) {
1648
1666
  c.fail('CONFIG_FIELD_TYPE', `${at}.spec`, `is ${show(o.spec)}; "${ANIMATIONS_FROM_SPEC}" is required, the motion-spec version motion.json states`);
1649
1667
  }
@@ -2922,9 +2940,9 @@ interface LimbNames {
2922
2940
  * one (`CONFIG_KEY_KNOWN`, `CONFIG_FIELD_PRESENT`); `range` two finite
2923
2941
  * degrees `[min, max]` with `min <= 0 <= max` (`CONFIG_LIMB_RANGE`: the range
2924
2942
  * is measured from rest, so rest is in it); `cap` a non-empty path; `edge`
2925
- * `"feather"` and `cap_shape` `"disc"` (issue #360), each the one value its
2926
- * field takes — absent is the hard cut and the layer's half-disc
2927
- * (`CONFIG_FIELD_TYPE` on any other); `cut_band` a whole number of px, 1 or
2943
+ * `"feather"` (issue #360), the one value its field takes, and `cap_shape`
2944
+ * `"disc"` (issue #360) or `"ball"` (issue #579) — absent is the hard cut and
2945
+ * the layer's half-disc (`CONFIG_FIELD_TYPE` on any other); `cut_band` a whole number of px, 1 or
2928
2946
  * more (`CONFIG_FIELD_TYPE`), on a segment that takes the segment above's
2929
2947
  * part (`CONFIG_KEY_KNOWN`: between two layers nothing is cut). A limb
2930
2948
  * has two segments or more. With `names` null (no `bones`), bones are not
@@ -3031,8 +3049,8 @@ function checkLimbs(c: Check, v: Json, made: { parts: string[]; patches: string[
3031
3049
  if ('edge' in e && e.edge !== 'feather') {
3032
3050
  c.fail('CONFIG_FIELD_TYPE', `${sat}.edge`, `is ${show(e.edge)}; "feather" is required — the upper piece fades out across the cap instead of stopping at the joint line; leave edge out for the hard cut`);
3033
3051
  }
3034
- if ('cap_shape' in e && e.cap_shape !== 'disc') {
3035
- c.fail('CONFIG_FIELD_TYPE', `${sat}.cap_shape`, `is ${show(e.cap_shape)}; "disc" is required — the cap a disc of the limb's half-width about the joint, filled from the art, the upper segment's included; leave cap_shape out for the layer's half-disc of half the limb's width`);
3052
+ if ('cap_shape' in e && e.cap_shape !== 'disc' && e.cap_shape !== 'ball') {
3053
+ c.fail('CONFIG_FIELD_TYPE', `${sat}.cap_shape`, `is ${show(e.cap_shape)}; "disc" or "ball" is required — "disc" the cap a disc of the limb's half-width about the joint, filled from the art, the upper segment's included; "ball" that disc on both sides of the joint line, its lower half written into the lower piece from the cap image where the piece's layer is transparent (issue #579); leave cap_shape out for the layer's half-disc of half the limb's width`);
3036
3054
  }
3037
3055
  // Issue #360 (item 14): the band the cut is placed in, whole px, on a joint whose two segments take one part.
3038
3056
  if ('cut_band' in e && i > 0) {
@@ -567,7 +567,11 @@ export interface ChainLink {
567
567
  export interface ChainEdge {
568
568
  parent: string;
569
569
  child: string;
570
+ /** {@link lagStep} of the two phases below. */
570
571
  step: number;
572
+ /** The phases the step was folded from, as {@link readSine} returns them (issue #580): a negative amplitude already read as amplitude > 0 at phase + 0.5. */
573
+ parentPhase: number;
574
+ childPhase: number;
571
575
  }
572
576
 
573
577
  export interface ChainFigures {
@@ -634,8 +638,11 @@ export function chainFigures(rig: Record<string, unknown>, motion: Record<string
634
638
  for (const b of keyed) {
635
639
  const p = keyedParent.get(b) ?? null;
636
640
  if (p === null) continue;
637
- if (samePeriod(p, b)) edges.push({ parent: p, child: b, step: lagStep((reading.get(p) as SineReading).phase, (reading.get(b) as SineReading).phase) });
638
- else otherPeriod.push({ parent: p, child: b });
641
+ if (samePeriod(p, b)) {
642
+ const from = (reading.get(p) as SineReading).phase;
643
+ const to = (reading.get(b) as SineReading).phase;
644
+ edges.push({ parent: p, child: b, step: lagStep(from, to), parentPhase: from, childPhase: to });
645
+ } else otherPeriod.push({ parent: p, child: b });
639
646
  }
640
647
  const continues = (b: string): string | null => {
641
648
  const k = kids.get(b) ?? [];
package/src/limbs.ts CHANGED
@@ -53,6 +53,16 @@
53
53
  * off the limb's middle, a corner trimmed to the disc leaves a notch at
54
54
  * rest when nothing takes it, or a stub out of the bent lower piece's
55
55
  * outline when the lower takes it (issue #360, unit B's sheets).
56
+ * - **`cap_shape: "ball"`** (issue #579; opt-in on the segment below the
57
+ * joint). The disc of `"disc"` — the same radius, its upper half filled as
58
+ * `"disc"` fills it — and its half past the cut as well: a pixel there
59
+ * whose centre lies within the radius is written into the lower piece from
60
+ * the cap image only where the piece's own pixel is transparent (alpha 0,
61
+ * the reading the upper half gives a layer's pixel and the image's), kept
62
+ * where the piece paints one, and missing where the image gives none. A
63
+ * hinge whose painting shows a notch beside the joint turns on a whole disc
64
+ * about its pivot, which a turn maps onto itself; no pixel the lower layer
65
+ * paints changes.
56
66
  * - **`edge: "feather"`** (issue #360, item 9; opt-in on the segment below the
57
67
  * joint). The overlap band is the disc about the joint that the lower
58
68
  * piece covers at every turn ({@link coveredRadius}: the cap's disc, less
@@ -0,0 +1,57 @@
1
+ /**
2
+ * `mesh-stats` (issue #566): the vertices and triangles of every mesh a config states, against an assembled parts
3
+ * directory, before a build.
4
+ *
5
+ * It is the rig stage without rigc: the same inputs ({@link readRigInputs}) through the same `buildRig`, whose
6
+ * `meshReport` rows are what `rig/mesh_report.json` is written from. Nothing triangulates a second time, so a count
7
+ * printed here is the count the rig stage writes for the same config and parts — with one exception, which the line
8
+ * says: an `auto` part whose motion gate refuses the full reduction is replayed by the rig stage to an earlier
9
+ * accepted step (`rigStage`, `src/autoreplay.ts`), and that search runs rigc, so it does not run here. A problem
10
+ * `buildRig` refuses is the build's own refusal, by the same name. Nothing is written: no skeleton data leaves memory,
11
+ * no image, no report; rigc's gate is the gate of the commands that emit, and this one emits nothing.
12
+ */
13
+ import { readRigInputs } from './build.ts';
14
+ import { buildRig, DEFAULT_IDLE_KEYS, type MeshReport } from './rig.ts';
15
+
16
+ /** One mesh's counts, as the rig stage's `mesh_report.json` row holds them; `mode` is `lattice` for a `grid` entry, whose row carries no mode. */
17
+ export interface MeshStatsRow {
18
+ part: string;
19
+ mode: 'lattice' | 'contour' | 'auto' | 'influence';
20
+ vertices: number;
21
+ triangles: number;
22
+ }
23
+
24
+ /** The counts of each row of a mesh report, in its order (parts.json's, the order the rig stage writes). */
25
+ export function meshStatsRows(report: readonly MeshReport[]): MeshStatsRow[] {
26
+ return report.map((m) => ({ part: m.part, mode: 'mode' in m ? m.mode : 'lattice', vertices: m.vertices, triangles: m.triangles }));
27
+ }
28
+
29
+ /** What `auto` adds to its line: the count is the reduction's, before the motion gate that may replay it. */
30
+ export const AUTO_BEFORE_GATE = "the reduction's result; when rigc's motion gate refuses it, the rig stage replays an earlier accepted step, which this command does not run";
31
+
32
+ /** The printed lines: one per mesh, then the total. No budget line: the tree holds no triangle budget. */
33
+ export function meshStatsLines(rows: readonly MeshStatsRow[]): string[] {
34
+ const out = rows.map((r) => `mesh-stats: ${r.part} — ${r.mode} ${r.vertices} vertices, ${r.triangles} triangles${r.mode === 'auto' ? ` (${AUTO_BEFORE_GATE})` : ''}`);
35
+ const total = rows.reduce((n, r) => n + r.triangles, 0);
36
+ out.push(`mesh-stats: total ${total} triangles over ${rows.length} mesh(es)`);
37
+ return out;
38
+ }
39
+
40
+ export interface MeshStatsInput {
41
+ /** The config, as `rig --config` reads it. */
42
+ config: string;
43
+ /** The directory holding parts.json and parts/<name>.png, as `rig --parts` reads it. */
44
+ parts: string;
45
+ }
46
+
47
+ /**
48
+ * The counts of every mesh `buildRig` makes from the config and the parts, printed through `log`. The idle's keys
49
+ * go where `rig` puts them by default (`ctl`): where they go moves no vertex and no triangle, since a control bone
50
+ * stands at its bone's origin and no mesh is weighted to it. Throws the rig stage's own `PartsError` on a refusal.
51
+ */
52
+ export function meshStatsStage(input: MeshStatsInput, log: (line: string) => void): MeshStatsRow[] {
53
+ const { cfg, parts, images } = readRigInputs(input.config, input.parts);
54
+ const rows = meshStatsRows(buildRig(cfg, parts, images, undefined, DEFAULT_IDLE_KEYS).meshReport);
55
+ for (const l of meshStatsLines(rows)) log(l);
56
+ return rows;
57
+ }