rig-parts 2.8.0 → 2.9.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
@@ -1,4 +1,6 @@
1
1
  import { readSetupBackdrop } from './setupbackdrop.ts';
2
+ import { COINCIDE_LINE, type SupportReport } from './coincide.ts';
3
+ import { observeSupport } from './coincideio.ts';
2
4
  import { SETUP_PAINTING_LINE, UNDECLARED_SETUP_PAINTING_REASON, setupPaintingBounds, setupPaintingLine, type SetupPainting, type SetupPaintingLine, type SetupPaintingObservation } from './setuppainting.ts';
3
5
  import { readMaterialSources } from './cutmaterialio.ts';
4
6
  import { CUT_MATERIAL_LINE, checkJointMaterial, type MaterialLine } from './cutmaterial.ts';
@@ -142,9 +144,10 @@ import {
142
144
  type WorldBox,
143
145
  } from './instruments.ts';
144
146
  import { type AlternatePartsRecord, FRONT_SUFFIX, type LimbRecord, type PartRecord, type PartsFile, readParts } from './parts.ts';
145
- import { ARM_SPLIT_MIGRATION, poseRigBonesForDrawn, type RigBone, SETS_FILE } from './rig.ts';
147
+ import { ARM_SPLIT_MIGRATION, poseRigBonesForDrawn, type RigBone, SETS_FILE, writtenShares } from './rig.ts';
146
148
  import { TURN_BONE, turnConstraintName, turnTwin } from './turn.ts';
147
- import { ROOT_BONE } from './config.ts';
149
+ import { ROOT_BONE, loadConfigWithBytes, type Point } from './config.ts';
150
+ import { influences, meshLimits, type Segment, type Influence, type InfluenceLimits } from './weights.ts';
148
151
  import {
149
152
  aimLine,
150
153
  contactLine,
@@ -182,7 +185,7 @@ import { connectedComponents } from './raster/components.ts';
182
185
  import { alphaComposite } from './raster/composite.ts';
183
186
  import { alphaAbove } from './raster/index.ts';
184
187
  import { readPng, writePng } from './raster/png.ts';
185
- import { newFloatImage, newRaster, type Raster } from './raster/types.ts';
188
+ import { type Mask, newFloatImage, newRaster, type Raster } from './raster/types.ts';
186
189
  import type { BaseTag } from './tags.ts';
187
190
  import { type ScaleTranslate, warpAffine } from './raster/warp.ts';
188
191
  import { edgeLength } from './length.ts';
@@ -236,6 +239,8 @@ export const BLINK_PATCH_LEVEL = SEAM_PX_LEVEL;
236
239
  /** The smallest lag the reading resolves, in cycles: phases are written to three places. */
237
240
  export const CHAIN_LAG_MIN_STEP = 0.001;
238
241
  export const TIP_RATIO_FLOOR = 1.4725;
242
+ /** Issue #994 sets half a rig pixel as the floor on the larger half travel. */
243
+ export const TIP_TRAVEL_FLOOR = 0.5;
239
244
  /**
240
245
  * Issue #245: the bar a part the scene declares `rests` is held to — its tip
241
246
  * half travels no further than its root half, tip / root <= 1, read at the
@@ -2709,6 +2714,7 @@ export interface CheckFigures {
2709
2714
  [MOTION_SEAM_LINE]?: MotionSeamLine;
2710
2715
  /** Written only when the rig declares a physics constraint and has an idle (issue #501): {@link ClothLine}, a warning, never a bar. */
2711
2716
  [CLOTH_LINE]?: ClothLine;
2717
+ [COINCIDE_LINE]?: SupportReport;
2712
2718
  RECOMPOSITE_HOLES: ReportedLine;
2713
2719
  /** Issue #933: openings inside the figure over motion across undeclared setup-overlapping layer pairs; omitted when SKIP. */
2714
2720
  figure_openings?: FigureOpeningReading;
@@ -3083,7 +3089,7 @@ export function checkSummaryLine(r: Pick<CheckReport, 'figures' | 'problems' | '
3083
3089
  }
3084
3090
 
3085
3091
  /** A block's status as {@link checkStatuses} reads it off `check.json`. */
3086
- export type CheckStatus = 'PASS' | 'FAIL' | 'SKIP' | 'WARN' | 'CLEAR' | 'REPORTED';
3092
+ export type CheckStatus = 'PASS' | 'FAIL' | 'SKIP' | 'WARN' | 'CLEAR' | 'REPORTED' | 'UNCLASSIFIED';
3087
3093
 
3088
3094
  /**
3089
3095
  * Every block's status as `check.json` records it (issue #541), read off the figures object `check.json` is written
@@ -3100,7 +3106,7 @@ export function checkStatuses(fig: CheckFigures): Record<string, CheckStatus> {
3100
3106
  const bar = (name: string, measured: boolean): CheckStatus => (!measured ? 'SKIP' : notMet.includes(name) ? 'FAIL' : 'PASS');
3101
3107
  const out: Record<string, CheckStatus> = { gate: bar('gate', true), loop: bar('loop', fig.loop_max_diff !== null), seam: bar('seam', fig.seam_mean !== null) };
3102
3108
  for (const n of JUDGEMENT_LINES) out[n] = fig[n].status;
3103
- for (const n of [FOLD_LINE, LEVEL_LINE, STRESS_LINE, LIMB_LINE, SWEEP_LINE, MOTION_SEAM_LINE, CLOTH_LINE, ...REPORTED_LINES, 'figure_openings', SOURCE_LINE, WIND_BAND_LINE, ART_JOINT_LINE, CUT_MATERIAL_LINE, SETUP_PAINTING_LINE, BOUNDARY_COLOUR_LINE] as const) {
3109
+ for (const n of [FOLD_LINE, LEVEL_LINE, STRESS_LINE, LIMB_LINE, SWEEP_LINE, MOTION_SEAM_LINE, CLOTH_LINE, ...REPORTED_LINES, 'figure_openings', SOURCE_LINE, WIND_BAND_LINE, ART_JOINT_LINE, CUT_MATERIAL_LINE, SETUP_PAINTING_LINE, BOUNDARY_COLOUR_LINE, COINCIDE_LINE] as const) {
3104
3110
  const l = fig[n];
3105
3111
  if (l !== undefined) out[n] = l.status;
3106
3112
  }
@@ -3323,7 +3329,7 @@ export const FOLD_TRIANGLES_SHOWN = 6;
3323
3329
  * the skin does not hold, a mesh with no triangle table, or a triangle the table does not reach is said rather than
3324
3330
  * guessed.
3325
3331
  */
3326
- export function foldBonesText(rig: Record<string, unknown>, motion: Record<string, unknown>, slot: string, attachment: string, frame: number, triangles: readonly number[]): string {
3332
+ export function foldBonesText(rig: Record<string, unknown>, motion: Record<string, unknown>, slot: string, attachment: string, frame: number, triangles: readonly number[], context?: WeightStepContext): string {
3327
3333
  const head = `at worst frame ${frame}`;
3328
3334
  if (triangles.length === 0) return `${head} rigc lists no folded triangle`;
3329
3335
  const skins = isRecord(rig.skins) ? rig.skins : {};
@@ -3369,7 +3375,8 @@ export function foldBonesText(rig: Record<string, unknown>, motion: Record<strin
3369
3375
  const which = g.triangles.length === 1 ? `triangle ${first}` : `triangles ${g.triangles.slice(0, FOLD_TRIANGLES_SHOWN).join(', ')}${more > 0 ? ` and ${more} more` : ''}`;
3370
3376
  const by = g.bones.length === 0 ? '' : ` dominated by ${quoted(g.bones)}`;
3371
3377
  const spelled = g.triangles.length === 1 ? `vertices ${vs.join(' ')}` : `triangle ${first}, vertices ${vs.join(' ')}`;
3372
- return `${which}${by} (${spelled}: ${edgeBonesText(rig, motion, slot, attachment, vs)})`;
3378
+ const step = weightStepText(rig, slot, attachment, vs, context);
3379
+ return `${which}${by} (${spelled}: ${edgeBonesText(rig, motion, slot, attachment, vs)}${step === '' ? '' : `; ${step}`})`;
3373
3380
  });
3374
3381
  const rest = groups.slice(FOLD_GROUPS_SHOWN);
3375
3382
  const restText = rest.length === 0 ? '' : `; … and ${rest.length} more group(s), ${rest.reduce((n, g) => n + g.triangles.length, 0)} triangle(s)`;
@@ -3401,6 +3408,7 @@ export function foldsLine(
3401
3408
  rig: Record<string, unknown> = {},
3402
3409
  physicsList: readonly LoopPhysics[] = [],
3403
3410
  motion: Record<string, unknown> = {},
3411
+ context?: WeightStepContext,
3404
3412
  ): FoldsLine {
3405
3413
  const toSide = (m: FoldingMesh | undefined): FoldSide | null =>
3406
3414
  m === undefined ? null : { frames: m.frames, worst_frame: m.worstFrame, worst_triangles: m.worstTriangles, line: m.line };
@@ -3461,7 +3469,7 @@ export function foldsLine(
3461
3469
  problems.push({
3462
3470
  code: `CHECK_${FOLD_LINE}`,
3463
3471
  object: `animation "${r.animation}", mesh "${r.attachment}" (slot "${r.slot}")`,
3464
- 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": … }`,
3472
+ detail: `rigc render --folds at ${fps} fps${physics}${sideClause}: ${r.line}; ${foldBonesText(rig, motion, r.slot, r.attachment, r.worst_frame, worstOf.get(r) ?? [], context)}; 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": … }`,
3465
3473
  });
3466
3474
  }
3467
3475
  const declaredNotFolding = mayFold.filter((e) => !folding.some((r) => r.slot === e.slot && r.animation === e.animation)).map((e) => ({ slot: e.slot, animation: e.animation }));
@@ -3914,8 +3922,10 @@ export interface LimbRow {
3914
3922
  limb: string;
3915
3923
  bone: string;
3916
3924
  status: 'PASS' | 'FAIL';
3917
- /** The bones besides its own the part is bound to, in rig.json's order; empty on a PASS. */
3925
+ /** The bones outside the permitted carriers, in rig.json's order; empty on a PASS. */
3918
3926
  others: string[];
3927
+ /** Additional carriers declared by this part's contour regions in mesh_report.json. */
3928
+ region_bones?: string[];
3919
3929
  }
3920
3930
 
3921
3931
  /** `check.json`'s `LIMB_ONE_BONE`. */
@@ -3925,13 +3935,18 @@ export interface LimbLine {
3925
3935
  }
3926
3936
 
3927
3937
  /** The line from parts.json's limb records and rig.json's slots and skins; each FAIL row adds one `CHECK_LIMB_ONE_BONE` problem naming the part and every second bone. Null when no part is a limb's. */
3928
- export function limbLine(parts: PartsFile, rig: Record<string, unknown>, problems: Problem[]): LimbLine | null {
3938
+ export function limbLine(parts: PartsFile, rig: Record<string, unknown>, problems: Problem[], meshReport: unknown = []): LimbLine | null {
3929
3939
  const limbParts = parts.parts.filter((p) => p.limb !== undefined);
3930
3940
  if (limbParts.length === 0) return null;
3931
3941
  const slots = (Array.isArray(rig.slots) ? rig.slots : []).filter(isRecord);
3932
3942
  const rows: LimbRow[] = limbParts.map((p) => {
3933
3943
  const l = p.limb as NonNullable<PartRecord['limb']>;
3934
- const own = new Set([l.bone, turnTwin(p.name, l.bone), ...(l.band === undefined ? [] : [l.band.upper, turnTwin(p.name, l.band.upper)])]);
3944
+ const regionBones = l.band === undefined && Array.isArray(meshReport)
3945
+ ? [...new Set(meshReport.filter(isRecord).filter(row => row.part === p.name && row.mode === 'contour')
3946
+ .flatMap(row => Array.isArray(row.regions) ? row.regions.filter(isRecord) : [])
3947
+ .flatMap(region => typeof region.bone === 'string' && region.bone.length > 0 ? [region.bone] : []))]
3948
+ : [];
3949
+ const own = new Set([l.bone, turnTwin(p.name, l.bone), ...regionBones.flatMap(bone => [bone, turnTwin(p.name, bone)]), ...(l.band === undefined ? [] : [l.band.upper, turnTwin(p.name, l.band.upper)])]);
3935
3950
  const slot = slots.find((sl) => sl.name === p.name);
3936
3951
  const bound = slot === undefined ? new Set<string>() : boundBones(rig, p.name);
3937
3952
  const others = [...bound].filter((b) => !own.has(b));
@@ -3945,10 +3960,12 @@ export function limbLine(parts: PartsFile, rig: Record<string, unknown>, problem
3945
3960
  ? `binds [${[...bound].join(', ')}]; the band requires both "${l.band.upper}" and "${l.bone}" and no other carrier — re-run rig with the recorded joint band`
3946
3961
  : bound.size === 0
3947
3962
  ? `is bound to no bone in rig.json (no slot of its name, or no attachment); its one bone "${l.bone}", with weight 1, is required`
3963
+ : regionBones.length > 0
3964
+ ? `is weighted to ${others.map(b => `"${b}"`).join(', ')}; only segment bone "${l.bone}" (or its turn twin) and this part's declared contour region bones [${regionBones.join(', ')}] are permitted`
3948
3965
  : `is weighted to ${others.map((b) => `"${b}"`).join(', ')} besides "${l.bone}"; a limb part rides its one bone with weight 1 — a bend is a rotation at the joint, never a deformed mesh — so a region on "${l.bone}" (config.regions.${p.name}), or a mesh whose segments name "${l.bone}" alone, is required`,
3949
3966
  });
3950
3967
  }
3951
- return { part: p.name, limb: l.name, bone: l.bone, status: fail ? 'FAIL' : 'PASS', others };
3968
+ return { part: p.name, limb: l.name, bone: l.bone, status: fail ? 'FAIL' : 'PASS', others, ...(regionBones.length === 0 ? {} : { region_bones: regionBones }) };
3952
3969
  });
3953
3970
  return { status: rows.some((r) => r.status === 'FAIL') ? 'FAIL' : 'PASS', parts: rows };
3954
3971
  }
@@ -6384,7 +6401,7 @@ function renderExtremes(build: string, out: string, animations: readonly string[
6384
6401
  * MEASURABLE is a problem. Without it nothing here reads, writes or prints
6385
6402
  * anything it did not before.
6386
6403
  */
6387
- export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, partsHome?: string, mode: PackMode = DEFAULT_PACK_MODE, source?: string, requirements?: string, seamPairsAsked = false, keepStills = false, set?: string, allSets = false, environment?: string, requirementsAs: string | undefined = requirements, config?: InputFileRecord, windBand?: string, noExtremes = false): CheckReport {
6404
+ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, partsHome?: string, mode: PackMode = DEFAULT_PACK_MODE, source?: string, requirements?: string, seamPairsAsked = false, keepStills = false, set?: string, allSets = false, environment?: string, requirementsAs: string | undefined = requirements, config?: InputFileRecord, windBand?: string, noExtremes = false, supportSource?: string, supportFigure?: Mask): CheckReport {
6388
6405
  let inp: CheckInputs;
6389
6406
  let reqFile: RequirementsFile | null = null;
6390
6407
  let reqRecord: RequirementsFileRecord | null = null;
@@ -6559,7 +6576,17 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6559
6576
  let level: LevelLine | null = null;
6560
6577
  // Issue #349: the limb parts' bones, off rig.json and parts.json; none, and nothing is written.
6561
6578
  const limbProblems: Problem[] = [];
6562
- const limbs = inp.parts === null ? null : limbLine(inp.parts, inp.rig, limbProblems);
6579
+ const meshReportPath = join(inp.rigDir, 'mesh_report.json');
6580
+ let meshReport: unknown = [];
6581
+ if (inp.parts?.parts.some(part => part.limb !== undefined) && existsSync(meshReportPath)) {
6582
+ try {
6583
+ meshReport = JSON.parse(readFileSync(meshReportPath, 'utf8')) as unknown;
6584
+ } catch (err) {
6585
+ refuseIfAny([{ code: 'CHECK_INPUT_IS_JSON', object: meshReportPath, detail: `does not parse as JSON: ${(err as Error).message}` }]);
6586
+ }
6587
+ if (!Array.isArray(meshReport)) refuseIfAny([{ code: 'CHECK_INPUT_IS_JSON', object: meshReportPath, detail: 'an array of per-part mesh reports is required' }]);
6588
+ }
6589
+ const limbs = inp.parts === null ? null : limbLine(inp.parts, inp.rig, limbProblems, meshReport);
6563
6590
  const levelProblems: Problem[] = [];
6564
6591
  try {
6565
6592
  if (inp.idleDuration !== null) {
@@ -6649,7 +6676,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6649
6676
  const fr = measured(['render', '--candidate', buildDir, '--folds', ...geometry, '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), '--out', foldDir]);
6650
6677
  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:'))));
6651
6678
  const readings = filterFolds(readFoldSets(foldDir, animationNames, fps, fr.out));
6652
- folds = foldsLine(animationNames, fps, 0, readings, mayFoldForRun, reqFile === null ? null : reqFile.path, foldProblems, readings, inp.rig, [], inp.motion);
6679
+ folds = foldsLine(animationNames, fps, 0, readings, mayFoldForRun, reqFile === null ? null : reqFile.path, foldProblems, readings, inp.rig, [], inp.motion, { config, stage: inp.stage });
6653
6680
  if (feet.length > 0) {
6654
6681
  const sets = readJson(join(foldDir, 'frames.json'), []);
6655
6682
  const listed = sets !== null && Array.isArray(sets.sets) ? sets.sets.filter(isRecord) : [];
@@ -6670,7 +6697,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6670
6697
  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:'))));
6671
6698
  const readingsOn = filterFolds(readFoldSets(onDir, animationNames, fps, frOn.out));
6672
6699
  const readingsOff = filterFolds(readFoldSets(offDir, animationNames, fps, frOff.out));
6673
- folds = foldsLine(animationNames, fps, stripped.physics.length, readingsOn, mayFoldForRun, reqFile === null ? null : reqFile.path, foldProblems, readingsOff, inp.rig, stripped.physics, inp.motion);
6700
+ folds = foldsLine(animationNames, fps, stripped.physics.length, readingsOn, mayFoldForRun, reqFile === null ? null : reqFile.path, foldProblems, readingsOff, inp.rig, stripped.physics, inp.motion, { config, stage: inp.stage });
6674
6701
  if (feet.length > 0) {
6675
6702
  const sets = readJson(join(offDir, 'frames.json'), []);
6676
6703
  const listed = sets !== null && Array.isArray(sets.sets) ? sets.sets.filter(isRecord) : [];
@@ -6746,7 +6773,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6746
6773
  const geometryPath = join(idle.dir, GEOMETRY_FILE);
6747
6774
  const geometry = readGeometry(geometryPath, idle.written);
6748
6775
  idleGeometry = geometry;
6749
- stretch = stretchLine(geometry, geometryPath, problems, inp);
6776
+ stretch = stretchLine(geometry, geometryPath, problems, { ...inp, config });
6750
6777
  if (full !== null) still = stillLine(full, idle, geometry, geometryPath, problems, notPlanted);
6751
6778
  }
6752
6779
 
@@ -6992,6 +7019,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6992
7019
  const setHints = new Map<string, string>();
6993
7020
  const fixedSkeleton = reqFile?.fixed_skeleton;
6994
7021
  let artJoints: ArtJointLine | null = null;
7022
+ let partSupport: SupportReport | null = null;
6995
7023
  let setupPainting: SetupPaintingObservation | null = inp.source !== null && reqFile?.setup_painting === undefined
6996
7024
  ? { status: 'SKIP', reason: UNDECLARED_SETUP_PAINTING_REASON } : null;
6997
7025
  if (inp.parts !== null || inp.source !== null || fixedSkeleton !== undefined) {
@@ -7021,6 +7049,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7021
7049
  const sr = rigc(['render', '--candidate', join(stillDir, 'build'), '--animation', 'still', '--fps', String(STILL_FPS), '--max', String(maxSide), ...(fixedSkeleton === undefined ? [] : ['--geometry']), '--out', join(stillDir, 'render')]);
7022
7050
  if (sr.status !== 0) refuseIfAny(rigcFailed('render (the setup-pose still)', sr, sr.out.split('\n').filter((l) => l.includes('FAIL'))));
7023
7051
  const stillSet = readFrameSet(join(stillDir, 'render'));
7052
+ partSupport = observeSupport(join(stillDir, 'build'), inp, supportSource, supportFigure);
7024
7053
  if (reqFile?.setup_painting !== undefined && inp.source !== null) setupPainting = measureSetupPainting(join(stillDir, 'build'), inp.stage, inp.source.painting, reqFile.setup_painting, problems, setupBackdrop);
7025
7054
  if (fixedSkeleton !== undefined) {
7026
7055
  const geometryPath = join(stillSet.dir, GEOMETRY_FILE);
@@ -7228,6 +7257,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7228
7257
  ...(windBandRead === null ? {} : { [WIND_BAND_LINE]: windBandRead }),
7229
7258
  ...(Object.keys(skipped).length === 0 ? {} : { skipped }),
7230
7259
  ...(Object.keys(setsFigures).length === 0 ? {} : { sets: setsFigures }),
7260
+ ...(partSupport === null ? {} : { [COINCIDE_LINE]: partSupport }),
7231
7261
  ...(config === undefined ? {} : { config }),
7232
7262
  ...(artJoints === null ? {} : { [ART_JOINT_LINE]: artJoints }),
7233
7263
  ...(setupPainting === null ? {} : { [SETUP_PAINTING_LINE]: setupPainting }),
@@ -7908,6 +7938,11 @@ export const TIP_INSTRUMENT = 'geometry, carrier frame';
7908
7938
  * nothing or the walk leaves the tree, and the part is then read in the world.
7909
7939
  */
7910
7940
  export function hangBone(rig: Record<string, unknown>, motion: Record<string, unknown>, part: string): string | null {
7941
+ return tipHang(rig, motion, part).bone;
7942
+ }
7943
+
7944
+ /** The same walk also identifies a link below the carrier for the art-grid policy. */
7945
+ function tipHang(rig: Record<string, unknown>, motion: Record<string, unknown>, part: string): { bone: string | null; onLink: boolean } {
7911
7946
  const bones = (Array.isArray(rig.bones) ? rig.bones : []).filter(isRecord).filter((b) => typeof b.name === 'string');
7912
7947
  const parent = new Map(bones.map((b) => [String(b.name), typeof b.parent === 'string' ? b.parent : null]));
7913
7948
  const upFrom = (b: string): string[] => {
@@ -7916,10 +7951,10 @@ export function hangBone(rig: Record<string, unknown>, motion: Record<string, un
7916
7951
  return path;
7917
7952
  };
7918
7953
  const bound = [...boundBones(rig, part)];
7919
- if (bound.length === 0) return null;
7954
+ if (bound.length === 0) return { bone: null, onLink: false };
7920
7955
  const paths = bound.map(upFrom);
7921
7956
  const common = paths[0].find((b) => paths.every((p) => p.includes(b)));
7922
- if (common === undefined) return null;
7957
+ if (common === undefined) return { bone: null, onLink: false };
7923
7958
  // A link: a bone of a chain CHAIN_LAG reads, or a bone a physics constraint drives. The rig stage keys a chain's
7924
7959
  // `<link>_ctl` and binds the mesh to its child the physics drives, and a physics-only chain has no keys at all, so
7925
7960
  // both are walked up through until the body bone that carries them.
@@ -7967,7 +8002,8 @@ export function hangBone(rig: Record<string, unknown>, motion: Record<string, un
7967
8002
  seen.add(at);
7968
8003
  at = parent.get(at) ?? null;
7969
8004
  }
7970
- return at;
8005
+ const onLink = paths.some((path) => path.slice(0, at === null ? path.length : path.indexOf(at)).some((b) => links.has(b)));
8006
+ return { bone: at, onLink };
7971
8007
  }
7972
8008
 
7973
8009
  /**
@@ -8032,7 +8068,8 @@ export function carrierFrame(geo: IdleGeometry | null, bone: string | null): ((i
8032
8068
  * body's carry is not scored as a tip that moves less; the row names that bone
8033
8069
  * (`hang_from`) and keeps the world reading (`world_*`). A half that travels 0
8034
8070
  * at the line's precision is 0, so a part that rides its carrier whole reads
8035
- * 0 / 0 and fails, not a ratio of round-off.
8071
+ * 0 / 0 and fails, not a ratio of round-off. Issue #994 applies the fixed
8072
+ * 0.5 rig px art-grid policy to max(root, tip) of a link part after this guard.
8036
8073
  */
8037
8074
  function tipLine(inp: FullInputs, geometryPath: string, frames: number, problems: Problem[], excepted: TipExceptions = NO_TIP_EXCEPTIONS): JudgementLine {
8038
8075
  const swing = partsTagged(inp.parts, SWING_TAGS);
@@ -8067,6 +8104,7 @@ function tipLine(inp: FullInputs, geometryPath: string, frames: number, problems
8067
8104
  }
8068
8105
  const rows: Array<Record<string, unknown>> = [];
8069
8106
  let measured = 0;
8107
+ let belowGrid = 0;
8070
8108
  let failed = false;
8071
8109
  for (const p of swing) {
8072
8110
  if (excepted.not_swinging.includes(p.name)) {
@@ -8085,7 +8123,8 @@ function tipLine(inp: FullInputs, geometryPath: string, frames: number, problems
8085
8123
  const shown = poses.map((f) => f.get(p.name) ?? null);
8086
8124
  const w = halfTravels(art, p, inp.stage, shown, rises ? 'up' : 'down');
8087
8125
  // Issue #987: the halves are read in the frame of the bone the part hangs from; the world reading rides beside them.
8088
- const hangFound = hangBone(inp.rig, inp.motion, p.name);
8126
+ const hanging = tipHang(inp.rig, inp.motion, p.name);
8127
+ const hangFound = hanging.bone;
8089
8128
  const frameOf = carrierFrame(idleGeo, hangFound);
8090
8129
  const hang = frameOf === null ? null : hangFound;
8091
8130
  const toCarrier = frameOf ?? ((_i: number, posed: readonly number[]) => posed.slice());
@@ -8098,19 +8137,27 @@ function tipLine(inp: FullInputs, geometryPath: string, frames: number, problems
8098
8137
  rows.push({ part: p.name, ...said, unmeasured: shown[0] === null ? 'its slot shows no attachment on idle frame 0' : `on idle frame 0 the ${half} half of its box holds no art its attachment draws` });
8099
8138
  continue;
8100
8139
  }
8101
- measured++;
8102
8140
  // Issue #987: a half that does not move against its carrier, read at the line's precision, is 0 and not the
8103
8141
  // arithmetic's residue — a rigid part reads 0 / 0, not a ratio of two round-off figures.
8104
8142
  const t = { root: round3(c.root) === 0 ? 0 : c.root, tip: round3(c.tip) === 0 ? 0 : c.tip };
8105
8143
  const ratio = t.root > 0 ? round3(t.tip / t.root) : null;
8106
8144
  const worldRatio = w.root > 0 ? round3(w.tip / w.root) : null;
8107
8145
  // Issue #245: a resting tip is held to the opposite relation — no further than its root, at the line's precision.
8108
- const ok = rests ? (ratio === null ? t.tip === 0 : ratio <= TIP_REST_RATIO_CEILING) : ratio === null ? t.tip > 0 : ratio >= TIP_RATIO_FLOOR;
8146
+ const rigid = t.root === 0 && t.tip === 0;
8147
+ const ok = !rigid && (rests ? (ratio === null ? t.tip === 0 : ratio <= TIP_REST_RATIO_CEILING) : ratio === null ? t.tip > 0 : ratio >= TIP_RATIO_FLOOR);
8109
8148
  rows.push({ part: p.name, ...said, hang_from: hang, root_rig_px: round3(t.root), tip_rig_px: round3(t.tip), ratio, world_root_rig_px: round3(w.root), world_tip_rig_px: round3(w.tip), world_ratio: worldRatio });
8149
+ // Structural 0 / 0 stays a failure before the link-only magnitude policy (issue #994).
8150
+ if (!rigid && hanging.onLink && Math.max(c.root, c.tip) < TIP_TRAVEL_FLOOR) {
8151
+ belowGrid++;
8152
+ rows[rows.length - 1] = { ...rows[rows.length - 1], travel_floor_rig_px: TIP_TRAVEL_FLOOR,
8153
+ unmeasured: "below half a rig pixel: the motion does not show on the art's own grid" };
8154
+ continue;
8155
+ }
8156
+ measured++;
8110
8157
  const against = hang === null ? 'in the world' : `against \`${hang}\`, the bone it hangs from`;
8111
8158
  const inWorld = hang === null ? '' : `; in the world ${round3(w.tip)} and ${round3(w.root)}, ratio ${worldRatio ?? 'undefined'}`;
8112
8159
  const travels = `the art in its ${tipHalf} half travels ${round3(t.tip)} rig px and in its ${rootHalf} half ${round3(t.root)} rig px ${against}`;
8113
- if (!ok && rests) {
8160
+ if (!ok && rests && !rigid) {
8114
8161
  failed = true;
8115
8162
  problems.push({
8116
8163
  code: 'CHECK_TIP_OVER_ROOT',
@@ -8141,7 +8188,7 @@ function tipLine(inp: FullInputs, geometryPath: string, frames: number, problems
8141
8188
  problems.push({
8142
8189
  code: 'CHECK_TIP_OVER_ROOT',
8143
8190
  object: `part "${p.name}", box ${p.x},${p.y} ${p.w}x${p.h} rig px, posed by the idle's geometry${rises ? ', declared rises' : ''}`,
8144
- detail: `${travels} (ratio ${ratio ?? (hang === null ? 'undefined: nothing moves' : `undefined: nothing moves against \`${hang}\``)}${inWorld}); a ratio >= ${TIP_RATIO_FLOOR} is required — ${misplaced ?? why}`,
8191
+ detail: `${travels} (ratio ${ratio ?? (hang === null ? 'undefined: nothing moves' : `undefined: nothing moves against \`${hang}\``)}${inWorld}); a ratio >= ${TIP_RATIO_FLOOR} is required — ${misplaced ?? why}${rigid && rests ? '; declare it in `not_swinging` if it is meant to ride rigidly' : ''}`,
8145
8192
  });
8146
8193
  }
8147
8194
  }
@@ -8150,8 +8197,17 @@ function tipLine(inp: FullInputs, geometryPath: string, frames: number, problems
8150
8197
  ...(excepted.rises.length === 0 ? {} : { declared_rises: swing.filter((p) => excepted.rises.includes(p.name)).map((p) => p.name) }),
8151
8198
  ...(excepted.rests.length === 0 ? {} : { declared_rests: swing.filter((p) => excepted.rests.includes(p.name)).map((p) => p.name) }),
8152
8199
  };
8153
- if (measured === 0) return { status: 'SKIP', reason: `none of ${quoteParts(swing)} could be measured: ${rows.map((r) => `${String(r.part)}: ${String(r.unmeasured)}`).join('; ')}` };
8154
- return { status: failed ? 'FAIL' : 'PASS', ...declared, instrument: TIP_INSTRUMENT, parts: rows, ratio_floor: TIP_RATIO_FLOOR, ...(excepted.rests.length === 0 ? {} : { rest_ratio_ceiling: TIP_REST_RATIO_CEILING }) };
8200
+ const figures = { ...declared, instrument: TIP_INSTRUMENT, parts: rows, ratio_floor: TIP_RATIO_FLOOR,
8201
+ ...(excepted.rests.length === 0 ? {} : { rest_ratio_ceiling: TIP_REST_RATIO_CEILING }) };
8202
+ if (measured === 0) {
8203
+ const reasons = rows.map((r) => {
8204
+ const travel = r.travel_floor_rig_px === undefined ? '' : `; root ${String(r.root_rig_px)} rig px, tip ${String(r.tip_rig_px)} rig px, floor ${String(r.travel_floor_rig_px)} rig px`;
8205
+ return `${String(r.part)}: ${String(r.unmeasured)}${travel}`;
8206
+ });
8207
+ return { status: 'SKIP', reason: `none of ${quoteParts(swing)} could be measured: ${reasons.join('; ')}`,
8208
+ ...(belowGrid === 0 ? {} : figures) };
8209
+ }
8210
+ return { status: failed ? 'FAIL' : 'PASS', ...figures };
8155
8211
  }
8156
8212
 
8157
8213
  /**
@@ -9068,6 +9124,120 @@ function stretchAtText(s: { triangle: number; vertices: readonly number[]; edge:
9068
9124
  return `triangle ${s.triangle} (vertices ${s.vertices.join(' ')}), edge ${s.edge.join('-')}, idle frame ${s.frame}`;
9069
9125
  }
9070
9126
 
9127
+ /** Config provenance is optional for standalone check and older generated rigs. */
9128
+ export interface WeightStepContext {
9129
+ config?: InputFileRecord;
9130
+ stage?: StageBox;
9131
+ }
9132
+
9133
+ type StepBinding = { bone: string; x: number; y: number; weight: number };
9134
+
9135
+ /** Recover only a replay that reproduces every written share on the named vertices. */
9136
+ function weightCutReplay(rig: Record<string, unknown>, part: string, rows: ReadonlyMap<number, StepBinding[]>, context?: WeightStepContext): { raw: Map<number, Influence[]>; limits: InfluenceLimits } | null {
9137
+ if (context?.config === undefined || context.stage === undefined) return null;
9138
+ try {
9139
+ const loaded = loadConfigWithBytes(context.config.path);
9140
+ if (inputFileRecord(loaded.bytes, context.config.path).sha256 !== context.config.sha256) return null;
9141
+ const mesh = loaded.config.meshes[part];
9142
+ if (mesh === undefined || !('grid' in mesh || 'contour' in mesh) || (mesh.rule !== undefined && mesh.rule !== 'distance')) return null;
9143
+ const named = new Map<string, Segment[]>();
9144
+ const chains = new Map<string, Segment[]>();
9145
+ for (const bone of loaded.config.bones) {
9146
+ if ('chain' in bone) {
9147
+ const chain = bone.points.map((point, i): Segment => ({ bone: `${bone.chain}${i}`, a: point, b: bone.points[i + 1] ?? bone.tip }));
9148
+ chains.set(bone.chain, chain);
9149
+ for (const segment of chain) named.set(segment.bone, [segment]);
9150
+ } else if (bone.tip !== undefined) named.set(bone.name, [{ bone: bone.name, a: bone.at, b: bone.tip }]);
9151
+ }
9152
+ const segments: Segment[] = [];
9153
+ for (const entry of mesh.segments) {
9154
+ if (typeof entry !== 'string') segments.push({ bone: entry[0], a: entry[1], b: entry[2] });
9155
+ else {
9156
+ const found = chains.get(entry) ?? named.get(entry);
9157
+ if (found === undefined) return null;
9158
+ segments.push(...found);
9159
+ }
9160
+ }
9161
+ const transforms = setupWorld(rig);
9162
+ const limits = meshLimits(mesh.influences);
9163
+ const raw = new Map<number, Influence[]>();
9164
+ for (const [vertex, bindings] of rows) {
9165
+ const first = bindings[0];
9166
+ if (first === undefined) return null;
9167
+ const transform = transforms.get(first.bone);
9168
+ if (transform === undefined) return null;
9169
+ const point: Point = [transform.a * first.x + transform.b * first.y + transform.worldX - context.stage.x,
9170
+ cropToSpineY(transform.c * first.x + transform.d * first.y + transform.worldY - context.stage.y, context.stage.height)];
9171
+ const cut = influences(point, segments, mesh.r, limits, mesh.exponent);
9172
+ const written = writtenShares({ influences: cut, region: -1, g: 0 }, limits.floor);
9173
+ const actual = new Map(bindings.map((binding) => [binding.bone, binding.weight]));
9174
+ if (written.length !== actual.size || written.some((binding) => actual.get(binding.bone) !== binding.weight)) return null;
9175
+ raw.set(vertex, influences(point, segments, mesh.r, { maxInfluences: Number.MAX_SAFE_INTEGER, minWeight: 0 }, mesh.exponent));
9176
+ }
9177
+ return { raw, limits };
9178
+ } catch {
9179
+ // A missing, stale or unsupported config cannot prove the cause of emitted weights.
9180
+ return null;
9181
+ }
9182
+ }
9183
+
9184
+ /** Show the first differing bone per edge in written-share order; a cut cause needs a matching production replay. */
9185
+ export function weightStepText(rig: Record<string, unknown>, slot: string, attachment: string, vertices: readonly number[], context?: WeightStepContext): string {
9186
+ const skins = isRecord(rig.skins) ? rig.skins : {};
9187
+ const skin = isRecord(skins.default) ? skins.default : {};
9188
+ const onSlot = isRecord(skin[slot]) ? skin[slot] : {};
9189
+ const att = onSlot[attachment];
9190
+ if (!isRecord(att) || !Array.isArray(att.weights)) return '';
9191
+ const rows = new Map<number, StepBinding[]>();
9192
+ for (const vertex of vertices) {
9193
+ const row = att.weights[vertex];
9194
+ if (!Array.isArray(row) || row.some((binding) => !isRecord(binding) || typeof binding.bone !== 'string' ||
9195
+ typeof binding.x !== 'number' || typeof binding.y !== 'number' || typeof binding.weight !== 'number')) return '';
9196
+ rows.set(vertex, (row as StepBinding[]).filter((binding) => binding.weight > 0));
9197
+ }
9198
+ const steps: Array<{ a: number; b: number; bone: string; aShare: number; bShare: number }> = [];
9199
+ const ordered = [...rows.keys()];
9200
+ for (let i = 0; i < ordered.length; i++) {
9201
+ for (let j = i + 1; j < ordered.length; j++) {
9202
+ const a = ordered[i], b = ordered[j];
9203
+ const left = new Map(rows.get(a)!.map((binding) => [binding.bone, binding.weight]));
9204
+ const right = new Map(rows.get(b)!.map((binding) => [binding.bone, binding.weight]));
9205
+ for (const bone of new Set([...left.keys(), ...right.keys()])) {
9206
+ if (left.has(bone) !== right.has(bone)) {
9207
+ steps.push({ a, b, bone, aShare: left.get(bone) ?? 0, bShare: right.get(bone) ?? 0 });
9208
+ break;
9209
+ }
9210
+ }
9211
+ }
9212
+ }
9213
+ if (steps.length === 0) return '';
9214
+ const replay = weightCutReplay(rig, slot, rows, context);
9215
+ let madeByCut = false;
9216
+ const text = steps.map((step) => {
9217
+ const observed = `edge ${step.a}-${step.b} bone "${step.bone}": vertex ${step.a} share ${step.aShare}, vertex ${step.b} share ${step.bShare}`;
9218
+ if (replay === null) return observed;
9219
+ const missing = step.aShare === 0 ? step.a : step.b;
9220
+ const raw = replay.raw.get(missing)!;
9221
+ const rank = raw.findIndex((binding) => binding.bone === step.bone);
9222
+ if (rank < 0 || raw[rank].weight <= 0) return observed;
9223
+ const before = `pre-cut share ${round6(raw[rank].weight)} on vertex ${missing}`;
9224
+ if (rank >= replay.limits.maxInfluences) {
9225
+ madeByCut = true;
9226
+ return `${observed}, made by the influence cut (maxInfluences ${replay.limits.maxInfluences}; ${before})`;
9227
+ }
9228
+ const total = raw.slice(0, replay.limits.maxInfluences).reduce((sum, binding) => sum + binding.weight, 0);
9229
+ const capped = raw[rank].weight / total;
9230
+ if ((replay.limits.floor ?? 'cut') === 'cut' && capped < replay.limits.minWeight) {
9231
+ madeByCut = true;
9232
+ return `${observed}, made by the influence cut (floor ${replay.limits.minWeight}; capped share ${round6(capped)}; ${before})`;
9233
+ }
9234
+ return `${observed}, replayed floor "${replay.limits.floor ?? 'cut'}"; ${before}`;
9235
+ });
9236
+ const fix = `meshes.${slot}.influences {"maxInfluences": null, "floor": "continuous"}`;
9237
+ const remedy = replay === null ? `; pre-cut shares unavailable; if the influence cut made this step: ${fix}` : madeByCut ? `; use ${fix}` : '';
9238
+ return `weight step ${text.join('; ')}${remedy}`;
9239
+ }
9240
+
9071
9241
  /**
9072
9242
  * Issue #314: what a failing edge's two vertices hang on, read off rig.json and motion.json — so the cause reads off
9073
9243
  * the line rather than off a hand decoding of the weight runs. Each vertex's bones from the default skin's weights,
@@ -9137,7 +9307,7 @@ export function edgeBonesText(rig: Record<string, unknown>, motion: Record<strin
9137
9307
  * bones its two vertices hang on and their chains ({@link edgeBonesText}, issue
9138
9308
  * #314).
9139
9309
  */
9140
- export function stretchLine(geo: IdleGeometry | null, path: string, problems: Problem[], bound?: Pick<CheckInputs, 'rig' | 'motion'>): JudgementLine {
9310
+ export function stretchLine(geo: IdleGeometry | null, path: string, problems: Problem[], bound?: Pick<CheckInputs, 'rig' | 'motion'> & WeightStepContext): JudgementLine {
9141
9311
  if (geo === null) return skip(`${path} does not exist; \`rigc render --geometry\` (rig-c ${RIGC_GEOMETRY_VERSION} or later) writes it, and the skinned mesh vertices are read from it`);
9142
9312
  if (geo.meshes.length === 0) return skip('the rig draws no mesh attachment (every slot is a region), so there is no triangle to stretch');
9143
9313
  const figures = stretchFigures(geo.meshes, geo.frames);
@@ -9169,10 +9339,11 @@ export function stretchLine(geo: IdleGeometry | null, path: string, problems: Pr
9169
9339
  rows.push({ slot: m.slot, triangles: m.triangles, max_ratio: round3(m.max.ratio), max_at: stretchAtText(m.max), min_ratio: round3(m.min.ratio), min_at: stretchAtText(m.min), severity });
9170
9340
  if (severity > TEXTURE_STRETCH_CEILING) {
9171
9341
  failed = true;
9342
+ const step = bound === undefined ? '' : weightStepText(bound.rig, m.slot, m.attachment, at.edge, bound);
9172
9343
  problems.push({
9173
9344
  code: 'CHECK_TEXTURE_STRETCH',
9174
9345
  object: `mesh "${m.slot}" ${stretchAtText(at)}`,
9175
- detail: `the edge is ${round3(at.ratio)} times its rest length (max(ratio, 1/ratio) ${severity}); <= ${TEXTURE_STRETCH_CEILING} is required${bound === undefined ? '' : `; ${edgeBonesText(bound.rig, bound.motion, m.slot, m.attachment, at.edge)}`} — the texture on it is ${at.ratio >= 1 ? 'stretched' : 'squeezed'}: the bones this mesh is weighted to move apart (amplitudes too large down a chain), or a vertex blends bones that move against each other`,
9346
+ detail: `the edge is ${round3(at.ratio)} times its rest length (max(ratio, 1/ratio) ${severity}); <= ${TEXTURE_STRETCH_CEILING} is required${bound === undefined ? '' : `; ${edgeBonesText(bound.rig, bound.motion, m.slot, m.attachment, at.edge)}${step === '' ? '' : `; ${step}`}`} — the texture on it is ${at.ratio >= 1 ? 'stretched' : 'squeezed'}: the bones this mesh is weighted to move apart (amplitudes too large down a chain), or a vertex blends bones that move against each other`,
9176
9347
  });
9177
9348
  }
9178
9349
  }