@rig-c/parts 1.52.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rig-c/parts",
3
- "version": "1.52.0",
3
+ "version": "1.53.0",
4
4
  "description": "AI-authored 2D character parts from one anime painting and its See-through layer decomposition: measured parts, weighted-mesh rig specs, verified through rig-c before anything is written. A CLI for agents that cannot see the image.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/assemble.ts CHANGED
@@ -2755,17 +2755,26 @@ export function shortCapLint(j: LimbCount['joints'][number]): string | null {
2755
2755
  ...(k.image_px === undefined ? [] : [`${k.image_px} px from ${k.image_layer === undefined ? 'the cap image' : `the hidden-art layer ${k.image_layer}`}`]),
2756
2756
  `${k.layer_px} px from "${j.part}"'s layer`,
2757
2757
  `${k.upper_px ?? 0} px from "${j.upper}"`,
2758
+ // Issue #579: under cap_shape "ball", the lower half's written and kept pixels.
2759
+ ...(k.shape === 'ball' ? [`on the lower side ${k.lower_px ?? 0} px written, ${k.lower_kept_px ?? 0} px left as painted`] : []),
2758
2760
  ].join(', ');
2761
+ const lowerMiss = k.lower_missing_px ?? 0;
2762
+ const which =
2763
+ lowerMiss === 0
2764
+ ? `${n} px of the disc on the upper side of the cut, where ${where}`
2765
+ : lowerMiss === n
2766
+ ? `${n} px of the disc on the lower side of the cut (cap_shape "ball"), where "${j.part}"'s layer is transparent and no cap image gives a pixel`
2767
+ : `${n} px of the disc, ${n - lowerMiss} on the upper side of the cut, where ${where}, and ${lowerMiss} on the lower side (cap_shape "ball"), where "${j.part}"'s layer is transparent and no cap image gives a pixel`;
2759
2768
  const half = j.half ?? 0;
2760
2769
  const disc =
2761
- k.shape === 'disc' || j.shortInHalf === undefined
2770
+ k.shape !== undefined || j.shortInHalf === undefined
2762
2771
  ? ''
2763
2772
  : j.shortInHalf === 0
2764
2773
  ? `; under cap_shape "disc" the disc is the half-width about the joint, ${half} px, and none of them lies within it`
2765
2774
  : `; under cap_shape "disc" the disc is the half-width about the joint, ${half} px, and ${j.shortInHalf} of them lie within it`;
2766
2775
  return (
2767
2776
  ` LINT "${j.part}" cap at [${k.at[0]}, ${k.at[1]}] (limb "${j.limb}", joint "${j.joint}", radius ${k.radius} px): short_px left ${k.short_px.left}, right ${k.short_px.right}: ` +
2768
- `no layer gives them — ${n} px of the disc on the upper side of the cut, where ${where}; the rest of the disc is filled, ${filled}${disc}`
2777
+ `no layer gives them — ${which}; the rest of the disc is filled, ${filled}${disc}`
2769
2778
  );
2770
2779
  }
2771
2780
 
@@ -2787,15 +2796,21 @@ export function limbLines(counts: readonly LimbCount[]): string[] {
2787
2796
  const radius =
2788
2797
  k.shape === undefined
2789
2798
  ? `a disc of radius ${k.radius} px (the limb ${k.width} px across the joint line)`
2790
- : `a disc of radius ${k.radius} px (cap_shape "disc": the joint's distance to the nearer side of the limb, ${k.width} px across the joint line)`;
2799
+ : `a disc of radius ${k.radius} px (cap_shape "${k.shape}": the joint's distance to the nearer side of the limb, ${k.width} px across the joint line)`;
2800
+ // Issue #579: the ball's lower half, counted apart; the missing pixels the line names on the upper side are that side's.
2801
+ const lowerMiss = k.lower_missing_px ?? 0;
2802
+ const upperMiss = k.missing_px - lowerMiss;
2803
+ const paintThem = `paint them into a ${k.box[2]}x${k.box[3]} image whose pixel (i, j) is rig pixel (${k.box[0]} + i, ${k.box[1]} + j), and name it in the segment's "cap"`;
2791
2804
  const shaped = [
2805
+ ...(k.shape === 'ball'
2806
+ ? [
2807
+ `cap_shape "ball": on the lower side of the line ${k.lower_px ?? 0} px written into "${j.part}" from ${k.image_px === undefined ? 'a cap image (none is named)' : k.image_layer === undefined ? 'the cap image' : `the hidden-art layer ${k.image_layer}`} where its layer is transparent (alpha 0), ${k.lower_kept_px ?? 0} px left as painted, ${lowerMiss === 0 ? 'none missing' : `${lowerMiss} px missing — the layer is transparent there and no cap image gives a pixel, and the tool invents none: ${paintThem}`}`,
2808
+ ]
2809
+ : []),
2792
2810
  ...(k.edge === undefined ? [] : [`edge "feather": ${k.feathered_px ?? 0} px of "${j.upper}" faded across the ${k.feather_radius ?? 0} px about the joint that "${j.part}" covers at every turn`]),
2793
2811
  ...(k.cut_band === undefined ? [] : [cutPhrase(k, j.upper, j.part)]),
2794
2812
  ];
2795
- const miss =
2796
- k.missing_px === 0
2797
- ? 'none missing'
2798
- : `${k.missing_px} px missing — the layer has no pixel there (hidden in the painting, or past the limb's outline), and the tool invents none: paint them into a ${k.box[2]}x${k.box[3]} image whose pixel (i, j) is rig pixel (${k.box[0]} + i, ${k.box[1]} + j), and name it in the segment's "cap"`;
2813
+ const miss = upperMiss === 0 ? 'none missing' : `${upperMiss} px missing — the layer has no pixel there (hidden in the painting, or past the limb's outline), and the tool invents none: ${paintThem}`;
2799
2814
  out.push(
2800
2815
  ` limb cap: "${j.limb}" joint "${j.joint}" at [${k.at[0]}, ${k.at[1]}], on "${j.part}": ${radius}, box [${k.box.join(', ')}] — on the upper side of the line ${from}, ${miss}${shaped.map((q) => `; ${q}`).join('')}`,
2801
2816
  );
@@ -3161,13 +3176,15 @@ function cutLimbs(
3161
3176
  // The width to 3 places (src/round.ts): a measured length, and a radius the line and the record print as read.
3162
3177
  const w3 = pyRound(run[1] - run[0] + 1, 3);
3163
3178
  // Issue #360: under cap_shape "disc" the radius is the half-width about the joint (src/limbs.ts), to 3 places as well.
3164
- const disc = sg.cap_shape === 'disc';
3179
+ // Issue #579: cap_shape "ball" is that disc and its upper half, and its lower half too (below).
3180
+ const ball = sg.cap_shape === 'ball';
3181
+ const disc = sg.cap_shape === 'disc' || ball;
3165
3182
  const half = halfWidthAbout(run);
3166
3183
  if (disc && half <= 0) {
3167
3184
  problems.push({
3168
3185
  code: 'ASSEMBLE_LIMB_JOINT_ON_ART',
3169
3186
  object,
3170
- detail: `the joint, "${sg.bone}"'s origin at [${line.at.join(', ')}], lies on the edge of the limb's art along its joint line — the run of art reaches ${pyRound(run[1] + 0.5, 3)} px from it one way and ${pyRound(0.5 - run[0], 3)} px the other — so cap_shape "disc" has no half-width about it; a bone origin inside the limb's art is required — move the bone onto the joint`,
3187
+ detail: `the joint, "${sg.bone}"'s origin at [${line.at.join(', ')}], lies on the edge of the limb's art along its joint line — the run of art reaches ${pyRound(run[1] + 0.5, 3)} px from it one way and ${pyRound(0.5 - run[0], 3)} px the other — so cap_shape "${String(sg.cap_shape)}" has no half-width about it; a bone origin inside the limb's art is required — move the bone onto the joint`,
3171
3188
  });
3172
3189
  return;
3173
3190
  }
@@ -3210,11 +3227,32 @@ function cutLimbs(
3210
3227
  let shortLeft = 0;
3211
3228
  let shortRight = 0;
3212
3229
  let shortInHalf = 0;
3230
+ // Issue #579: the ball's lower half — written from the image where the lower piece's pixel is transparent, kept
3231
+ // where the piece has a pixel, missing where neither gives one.
3232
+ let lowerPx = 0;
3233
+ let lowerKept = 0;
3234
+ let lowerMissing = 0;
3213
3235
  for (let y = Math.max(0, box[1]); y < Math.min(H, box[1] + box[3]); y++) {
3214
3236
  for (let x = Math.max(0, box[0]); x < Math.min(W, box[0] + box[2]); x++) {
3215
- if (!inDisc(line.at, radius, x, y) || pastJoint(cut, x, y)) continue;
3237
+ if (!inDisc(line.at, radius, x, y)) continue;
3216
3238
  const p = y * W + x;
3217
3239
  const u = img === null ? -1 : ((y - box[1]) * img.width + (x - box[0])) * 4;
3240
+ if (pastJoint(cut, x, y)) {
3241
+ if (!ball) continue;
3242
+ // Transparent is alpha 0, the reading the upper half's fill gives a layer's and the image's pixel: no pixel the
3243
+ // lower piece paints, however faint, changes.
3244
+ if (lower.data[p * 4 + 3] > 0) lowerKept++;
3245
+ else if (img !== null && img.data[u + 3] > 0) {
3246
+ lower.data.set(img.data.subarray(u, u + 4), p * 4);
3247
+ lowerPx++;
3248
+ } else {
3249
+ lowerMissing++;
3250
+ missing++;
3251
+ if (jointOffsets(line, x, y).across >= 0) shortLeft++;
3252
+ else shortRight++;
3253
+ }
3254
+ continue;
3255
+ }
3218
3256
  if (img !== null && img.data[u + 3] > 0) {
3219
3257
  lower.data.set(img.data.subarray(u, u + 4), p * 4);
3220
3258
  imagePx++;
@@ -3235,8 +3273,14 @@ function cutLimbs(
3235
3273
  }
3236
3274
  }
3237
3275
  }
3238
- if (img !== null && imagePx === 0 && hidden === null) {
3239
- problems.push({ code: 'ASSEMBLE_LIMB_CAP_EMPTY', object: `${object}.cap`, detail: `${String(sg.cap)} is transparent over every one of the cap's pixels; an image that gives at least one is required — to keep the layer's cap, drop cap` });
3276
+ if (img !== null && imagePx + lowerPx === 0 && hidden === null) {
3277
+ problems.push({
3278
+ code: 'ASSEMBLE_LIMB_CAP_EMPTY',
3279
+ object: `${object}.cap`,
3280
+ detail: ball
3281
+ ? `${String(sg.cap)} gives none of the cap's pixels: it is transparent over the disc's upper half and over every pixel of its lower half where "${sg.part}"'s layer is transparent (cap_shape "ball", issue #579); an image that gives at least one is required — to keep the layer's cap, drop cap`
3282
+ : `${String(sg.cap)} is transparent over every one of the cap's pixels; an image that gives at least one is required — to keep the layer's cap, drop cap`,
3283
+ });
3240
3284
  return;
3241
3285
  }
3242
3286
  // Issue #360: under edge "feather", the upper piece fades out across the cap, over the lower's opaque pixels only.
@@ -3278,7 +3322,13 @@ function cutLimbs(
3278
3322
  ...(hidden === null ? {} : { image_layer: hidden.layer }),
3279
3323
  missing_px: missing,
3280
3324
  ...(missing === 0 ? {} : { short_px: { left: shortLeft, right: shortRight } }),
3281
- ...(disc ? { shape: 'disc' as const, upper_px: upperPx } : upperPx === 0 ? {} : { upper_px: upperPx }),
3325
+ ...(ball
3326
+ ? { shape: 'ball' as const, upper_px: upperPx, lower_px: lowerPx, lower_kept_px: lowerKept, lower_missing_px: lowerMissing }
3327
+ : disc
3328
+ ? { shape: 'disc' as const, upper_px: upperPx }
3329
+ : upperPx === 0
3330
+ ? {}
3331
+ : { upper_px: upperPx }),
3282
3332
  ...(sg.edge === 'feather' ? { edge: 'feather' as const, feather_radius: band, feathered_px: featheredPx } : {}),
3283
3333
  ...(placed === undefined
3284
3334
  ? {}
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
@@ -893,7 +893,9 @@ export interface ConfigStop {
893
893
  * the joint (issue #360, `src/limbs.ts`): `edge: "feather"` fades the upper
894
894
  * piece out across the cap, and `cap_shape: "disc"` sizes the cap by the
895
895
  * limb's half-width about the joint and fills it from the art, the upper
896
- * 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
897
899
  * is hard and the cap the layer's half-disc of half the limb's width. A third,
898
900
  * `cut_band: N` (issue #360, item 14), places the cut on the line within N px
899
901
  * of the joint line that crosses the fewest stroke pixels; absent, the cut is
@@ -907,7 +909,7 @@ export interface LimbSegment {
907
909
  range?: [number, number];
908
910
  cap?: string;
909
911
  edge?: 'feather';
910
- cap_shape?: 'disc';
912
+ cap_shape?: 'disc' | 'ball';
911
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. */
912
914
  cut_band?: number;
913
915
  }
@@ -2938,9 +2940,9 @@ interface LimbNames {
2938
2940
  * one (`CONFIG_KEY_KNOWN`, `CONFIG_FIELD_PRESENT`); `range` two finite
2939
2941
  * degrees `[min, max]` with `min <= 0 <= max` (`CONFIG_LIMB_RANGE`: the range
2940
2942
  * is measured from rest, so rest is in it); `cap` a non-empty path; `edge`
2941
- * `"feather"` and `cap_shape` `"disc"` (issue #360), each the one value its
2942
- * field takes — absent is the hard cut and the layer's half-disc
2943
- * (`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
2944
2946
  * more (`CONFIG_FIELD_TYPE`), on a segment that takes the segment above's
2945
2947
  * part (`CONFIG_KEY_KNOWN`: between two layers nothing is cut). A limb
2946
2948
  * has two segments or more. With `names` null (no `bones`), bones are not
@@ -3047,8 +3049,8 @@ function checkLimbs(c: Check, v: Json, made: { parts: string[]; patches: string[
3047
3049
  if ('edge' in e && e.edge !== 'feather') {
3048
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`);
3049
3051
  }
3050
- if ('cap_shape' in e && e.cap_shape !== 'disc') {
3051
- 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`);
3052
3054
  }
3053
3055
  // Issue #360 (item 14): the band the cut is placed in, whole px, on a joint whose two segments take one part.
3054
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