@rig-c/parts 2.8.1 → 2.9.1

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';
@@ -2711,6 +2714,7 @@ export interface CheckFigures {
2711
2714
  [MOTION_SEAM_LINE]?: MotionSeamLine;
2712
2715
  /** Written only when the rig declares a physics constraint and has an idle (issue #501): {@link ClothLine}, a warning, never a bar. */
2713
2716
  [CLOTH_LINE]?: ClothLine;
2717
+ [COINCIDE_LINE]?: SupportReport;
2714
2718
  RECOMPOSITE_HOLES: ReportedLine;
2715
2719
  /** Issue #933: openings inside the figure over motion across undeclared setup-overlapping layer pairs; omitted when SKIP. */
2716
2720
  figure_openings?: FigureOpeningReading;
@@ -3085,7 +3089,7 @@ export function checkSummaryLine(r: Pick<CheckReport, 'figures' | 'problems' | '
3085
3089
  }
3086
3090
 
3087
3091
  /** A block's status as {@link checkStatuses} reads it off `check.json`. */
3088
- export type CheckStatus = 'PASS' | 'FAIL' | 'SKIP' | 'WARN' | 'CLEAR' | 'REPORTED';
3092
+ export type CheckStatus = 'PASS' | 'FAIL' | 'SKIP' | 'WARN' | 'CLEAR' | 'REPORTED' | 'UNCLASSIFIED';
3089
3093
 
3090
3094
  /**
3091
3095
  * Every block's status as `check.json` records it (issue #541), read off the figures object `check.json` is written
@@ -3102,7 +3106,7 @@ export function checkStatuses(fig: CheckFigures): Record<string, CheckStatus> {
3102
3106
  const bar = (name: string, measured: boolean): CheckStatus => (!measured ? 'SKIP' : notMet.includes(name) ? 'FAIL' : 'PASS');
3103
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) };
3104
3108
  for (const n of JUDGEMENT_LINES) out[n] = fig[n].status;
3105
- 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) {
3106
3110
  const l = fig[n];
3107
3111
  if (l !== undefined) out[n] = l.status;
3108
3112
  }
@@ -3325,7 +3329,7 @@ export const FOLD_TRIANGLES_SHOWN = 6;
3325
3329
  * the skin does not hold, a mesh with no triangle table, or a triangle the table does not reach is said rather than
3326
3330
  * guessed.
3327
3331
  */
3328
- 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 {
3329
3333
  const head = `at worst frame ${frame}`;
3330
3334
  if (triangles.length === 0) return `${head} rigc lists no folded triangle`;
3331
3335
  const skins = isRecord(rig.skins) ? rig.skins : {};
@@ -3371,7 +3375,8 @@ export function foldBonesText(rig: Record<string, unknown>, motion: Record<strin
3371
3375
  const which = g.triangles.length === 1 ? `triangle ${first}` : `triangles ${g.triangles.slice(0, FOLD_TRIANGLES_SHOWN).join(', ')}${more > 0 ? ` and ${more} more` : ''}`;
3372
3376
  const by = g.bones.length === 0 ? '' : ` dominated by ${quoted(g.bones)}`;
3373
3377
  const spelled = g.triangles.length === 1 ? `vertices ${vs.join(' ')}` : `triangle ${first}, vertices ${vs.join(' ')}`;
3374
- 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}`})`;
3375
3380
  });
3376
3381
  const rest = groups.slice(FOLD_GROUPS_SHOWN);
3377
3382
  const restText = rest.length === 0 ? '' : `; … and ${rest.length} more group(s), ${rest.reduce((n, g) => n + g.triangles.length, 0)} triangle(s)`;
@@ -3403,6 +3408,7 @@ export function foldsLine(
3403
3408
  rig: Record<string, unknown> = {},
3404
3409
  physicsList: readonly LoopPhysics[] = [],
3405
3410
  motion: Record<string, unknown> = {},
3411
+ context?: WeightStepContext,
3406
3412
  ): FoldsLine {
3407
3413
  const toSide = (m: FoldingMesh | undefined): FoldSide | null =>
3408
3414
  m === undefined ? null : { frames: m.frames, worst_frame: m.worstFrame, worst_triangles: m.worstTriangles, line: m.line };
@@ -3463,7 +3469,7 @@ export function foldsLine(
3463
3469
  problems.push({
3464
3470
  code: `CHECK_${FOLD_LINE}`,
3465
3471
  object: `animation "${r.animation}", mesh "${r.attachment}" (slot "${r.slot}")`,
3466
- 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": … }`,
3467
3473
  });
3468
3474
  }
3469
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 }));
@@ -3916,8 +3922,10 @@ export interface LimbRow {
3916
3922
  limb: string;
3917
3923
  bone: string;
3918
3924
  status: 'PASS' | 'FAIL';
3919
- /** 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. */
3920
3926
  others: string[];
3927
+ /** Additional carriers declared by this part's contour regions in mesh_report.json. */
3928
+ region_bones?: string[];
3921
3929
  }
3922
3930
 
3923
3931
  /** `check.json`'s `LIMB_ONE_BONE`. */
@@ -3927,13 +3935,18 @@ export interface LimbLine {
3927
3935
  }
3928
3936
 
3929
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. */
3930
- 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 {
3931
3939
  const limbParts = parts.parts.filter((p) => p.limb !== undefined);
3932
3940
  if (limbParts.length === 0) return null;
3933
3941
  const slots = (Array.isArray(rig.slots) ? rig.slots : []).filter(isRecord);
3934
3942
  const rows: LimbRow[] = limbParts.map((p) => {
3935
3943
  const l = p.limb as NonNullable<PartRecord['limb']>;
3936
- 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)])]);
3937
3950
  const slot = slots.find((sl) => sl.name === p.name);
3938
3951
  const bound = slot === undefined ? new Set<string>() : boundBones(rig, p.name);
3939
3952
  const others = [...bound].filter((b) => !own.has(b));
@@ -3947,10 +3960,12 @@ export function limbLine(parts: PartsFile, rig: Record<string, unknown>, problem
3947
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`
3948
3961
  : bound.size === 0
3949
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`
3950
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`,
3951
3966
  });
3952
3967
  }
3953
- 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 }) };
3954
3969
  });
3955
3970
  return { status: rows.some((r) => r.status === 'FAIL') ? 'FAIL' : 'PASS', parts: rows };
3956
3971
  }
@@ -6386,7 +6401,7 @@ function renderExtremes(build: string, out: string, animations: readonly string[
6386
6401
  * MEASURABLE is a problem. Without it nothing here reads, writes or prints
6387
6402
  * anything it did not before.
6388
6403
  */
6389
- 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 {
6390
6405
  let inp: CheckInputs;
6391
6406
  let reqFile: RequirementsFile | null = null;
6392
6407
  let reqRecord: RequirementsFileRecord | null = null;
@@ -6561,7 +6576,17 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6561
6576
  let level: LevelLine | null = null;
6562
6577
  // Issue #349: the limb parts' bones, off rig.json and parts.json; none, and nothing is written.
6563
6578
  const limbProblems: Problem[] = [];
6564
- 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);
6565
6590
  const levelProblems: Problem[] = [];
6566
6591
  try {
6567
6592
  if (inp.idleDuration !== null) {
@@ -6651,7 +6676,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6651
6676
  const fr = measured(['render', '--candidate', buildDir, '--folds', ...geometry, '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), '--out', foldDir]);
6652
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:'))));
6653
6678
  const readings = filterFolds(readFoldSets(foldDir, animationNames, fps, fr.out));
6654
- 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 });
6655
6680
  if (feet.length > 0) {
6656
6681
  const sets = readJson(join(foldDir, 'frames.json'), []);
6657
6682
  const listed = sets !== null && Array.isArray(sets.sets) ? sets.sets.filter(isRecord) : [];
@@ -6672,7 +6697,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6672
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:'))));
6673
6698
  const readingsOn = filterFolds(readFoldSets(onDir, animationNames, fps, frOn.out));
6674
6699
  const readingsOff = filterFolds(readFoldSets(offDir, animationNames, fps, frOff.out));
6675
- 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 });
6676
6701
  if (feet.length > 0) {
6677
6702
  const sets = readJson(join(offDir, 'frames.json'), []);
6678
6703
  const listed = sets !== null && Array.isArray(sets.sets) ? sets.sets.filter(isRecord) : [];
@@ -6748,7 +6773,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6748
6773
  const geometryPath = join(idle.dir, GEOMETRY_FILE);
6749
6774
  const geometry = readGeometry(geometryPath, idle.written);
6750
6775
  idleGeometry = geometry;
6751
- stretch = stretchLine(geometry, geometryPath, problems, inp);
6776
+ stretch = stretchLine(geometry, geometryPath, problems, { ...inp, config });
6752
6777
  if (full !== null) still = stillLine(full, idle, geometry, geometryPath, problems, notPlanted);
6753
6778
  }
6754
6779
 
@@ -6994,6 +7019,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6994
7019
  const setHints = new Map<string, string>();
6995
7020
  const fixedSkeleton = reqFile?.fixed_skeleton;
6996
7021
  let artJoints: ArtJointLine | null = null;
7022
+ let partSupport: SupportReport | null = null;
6997
7023
  let setupPainting: SetupPaintingObservation | null = inp.source !== null && reqFile?.setup_painting === undefined
6998
7024
  ? { status: 'SKIP', reason: UNDECLARED_SETUP_PAINTING_REASON } : null;
6999
7025
  if (inp.parts !== null || inp.source !== null || fixedSkeleton !== undefined) {
@@ -7023,6 +7049,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7023
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')]);
7024
7050
  if (sr.status !== 0) refuseIfAny(rigcFailed('render (the setup-pose still)', sr, sr.out.split('\n').filter((l) => l.includes('FAIL'))));
7025
7051
  const stillSet = readFrameSet(join(stillDir, 'render'));
7052
+ partSupport = observeSupport(join(stillDir, 'build'), inp, supportSource, supportFigure);
7026
7053
  if (reqFile?.setup_painting !== undefined && inp.source !== null) setupPainting = measureSetupPainting(join(stillDir, 'build'), inp.stage, inp.source.painting, reqFile.setup_painting, problems, setupBackdrop);
7027
7054
  if (fixedSkeleton !== undefined) {
7028
7055
  const geometryPath = join(stillSet.dir, GEOMETRY_FILE);
@@ -7230,6 +7257,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7230
7257
  ...(windBandRead === null ? {} : { [WIND_BAND_LINE]: windBandRead }),
7231
7258
  ...(Object.keys(skipped).length === 0 ? {} : { skipped }),
7232
7259
  ...(Object.keys(setsFigures).length === 0 ? {} : { sets: setsFigures }),
7260
+ ...(partSupport === null ? {} : { [COINCIDE_LINE]: partSupport }),
7233
7261
  ...(config === undefined ? {} : { config }),
7234
7262
  ...(artJoints === null ? {} : { [ART_JOINT_LINE]: artJoints }),
7235
7263
  ...(setupPainting === null ? {} : { [SETUP_PAINTING_LINE]: setupPainting }),
@@ -9096,6 +9124,120 @@ function stretchAtText(s: { triangle: number; vertices: readonly number[]; edge:
9096
9124
  return `triangle ${s.triangle} (vertices ${s.vertices.join(' ')}), edge ${s.edge.join('-')}, idle frame ${s.frame}`;
9097
9125
  }
9098
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
+
9099
9241
  /**
9100
9242
  * Issue #314: what a failing edge's two vertices hang on, read off rig.json and motion.json — so the cause reads off
9101
9243
  * the line rather than off a hand decoding of the weight runs. Each vertex's bones from the default skin's weights,
@@ -9165,7 +9307,7 @@ export function edgeBonesText(rig: Record<string, unknown>, motion: Record<strin
9165
9307
  * bones its two vertices hang on and their chains ({@link edgeBonesText}, issue
9166
9308
  * #314).
9167
9309
  */
9168
- 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 {
9169
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`);
9170
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');
9171
9313
  const figures = stretchFigures(geo.meshes, geo.frames);
@@ -9197,10 +9339,11 @@ export function stretchLine(geo: IdleGeometry | null, path: string, problems: Pr
9197
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 });
9198
9340
  if (severity > TEXTURE_STRETCH_CEILING) {
9199
9341
  failed = true;
9342
+ const step = bound === undefined ? '' : weightStepText(bound.rig, m.slot, m.attachment, at.edge, bound);
9200
9343
  problems.push({
9201
9344
  code: 'CHECK_TEXTURE_STRETCH',
9202
9345
  object: `mesh "${m.slot}" ${stretchAtText(at)}`,
9203
- 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`,
9204
9347
  });
9205
9348
  }
9206
9349
  }
@@ -0,0 +1,157 @@
1
+ /** Report-only missing support observations on the native setup grid (#998). */
2
+ import { refuseIfAny } from './errors.ts';
3
+ import { connectedComponents } from './raster/components.ts';
4
+ import { assertBinary, type Mask } from './raster/types.ts';
5
+
6
+ export const COINCIDE_LINE = 'PART_SUPPORT_REPORT';
7
+ export const SUPPORT_GRID_CODE = 'CHECK_SUPPORT_GRID';
8
+ export type SupportBox = [number, number, number, number];
9
+ /** Independent stage-grid witness, supplied by the producer. Never derive it
10
+ * from the final alpha or from the part's cropped PNG rectangle. */
11
+ export interface SupportDomain {
12
+ part: string;
13
+ mask: Mask;
14
+ provenance: { kind: 'cut-polygon' | 'limb-capsule'; entry: string };
15
+ }
16
+ export interface UnavailableSupportDomain { part: string; reason: string }
17
+ export type SupportDomainReading = SupportDomain | UnavailableSupportDomain;
18
+ export interface SupportPart { name: string; mask: Mask }
19
+ export interface SupportPair {
20
+ front: string;
21
+ back: string;
22
+ status: 'measured' | 'unavailable';
23
+ reason?: string;
24
+ boundary_length_px: number | null;
25
+ /** Bounds of the shared unit segments, exclusive far edge. */
26
+ box: SupportBox | null;
27
+ /** Missing cells in B's domain under F, a candidate bound, not inferred art. */
28
+ continuation_candidate_area_px: number | null;
29
+ }
30
+ export interface RawSupportPair {
31
+ front: string;
32
+ back: string;
33
+ boundary_length_px: number;
34
+ /** Bounds of shared unit segments and overlapping cells. */
35
+ box: SupportBox;
36
+ overlap_area_px: number;
37
+ classification: 'ownership unknown, unclassified';
38
+ }
39
+ export interface UnownedReading {
40
+ status: 'measured' | 'unavailable';
41
+ reason?: string;
42
+ area_px: number | null;
43
+ regions: Array<{ box: SupportBox; area_px: number }>;
44
+ }
45
+ export interface SupportReport {
46
+ status: 'REPORTED' | 'WARN' | 'UNCLASSIFIED';
47
+ grid: [number, number];
48
+ alpha: 'alpha >= 128';
49
+ pair_registration: string;
50
+ unowned_registration: string;
51
+ boundary: '4-neighbour unit pixel-cell edges, exact coincidence';
52
+ pairs: SupportPair[];
53
+ raw_pairs: RawSupportPair[];
54
+ coverage: { measured: number; total: number };
55
+ unowned: UnownedReading;
56
+ reason?: string;
57
+ }
58
+
59
+ /** Parts are ordered back to front. A boundary segment is counted only when
60
+ * the adjacent F cell is missing from B AND belongs to B's independent domain.
61
+ * No dilation, inferred continuation, limit or gate is applied. */
62
+ export function supportReport(
63
+ width: number, height: number, parts: readonly SupportPart[],
64
+ domains: readonly SupportDomainReading[], paintedFigure: Mask | null,
65
+ unavailableReason = 'independent support domain is unavailable',
66
+ ): SupportReport {
67
+ const check = (mask: Mask): void => {
68
+ assertBinary('support report', mask);
69
+ if (mask.data.length !== width * height || mask.width !== width || mask.height !== height) refuseIfAny([{ code: SUPPORT_GRID_CODE, object: 'support report mask', detail: `is ${mask.width}x${mask.height} with ${mask.data.length} cells; requires ${width}x${height} and ${width * height} cells on the native grid` }]);
70
+ };
71
+ for (const part of parts) check(part.mask);
72
+ for (const domain of domains) if ('mask' in domain) check(domain.mask);
73
+ if (paintedFigure !== null) check(paintedFigure);
74
+ if (new Set(parts.map(p => p.name)).size !== parts.length || new Set(domains.map(d => d.part)).size !== domains.length) throw new Error('support report requires unique part and domain names');
75
+ const bounds = parts.map(part => {
76
+ let left = width, top = height, right = 0, bottom = 0;
77
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
78
+ if (part.mask.data[y * width + x] === 0) continue;
79
+ left = Math.min(left, x); top = Math.min(top, y);
80
+ right = Math.max(right, x + 1); bottom = Math.max(bottom, y + 1);
81
+ }
82
+ return { left, top, right, bottom };
83
+ });
84
+ const raw_pairs: RawSupportPair[] = [];
85
+ const pairs: SupportPair[] = [];
86
+ for (let back = 0; back < parts.length; back++) for (let front = back + 1; front < parts.length; front++) {
87
+ const B = parts[back], F = parts[front], domain = domains.find(d => d.part === B.name);
88
+ const bb = bounds[back], fb = bounds[front];
89
+ let rawLength = 0, overlap = 0, rx0 = width, ry0 = height, rx1 = 0, ry1 = 0;
90
+ const include = (x: number, y: number, dx: number, dy: number): void => {
91
+ rx0 = Math.min(rx0, x); ry0 = Math.min(ry0, y);
92
+ rx1 = Math.max(rx1, x + dx); ry1 = Math.max(ry1, y + dy);
93
+ };
94
+ const rawEdge = (a: number, b: number, x: number, y: number, dx: number, dy: number): void => {
95
+ if (B.mask.data[a] !== 0 && B.mask.data[b] === 0 && F.mask.data[a] === 0 && F.mask.data[b] !== 0) {
96
+ rawLength++; include(x, y, dx, dy);
97
+ }
98
+ };
99
+ // Intersect occupied boxes before visiting pixels. The one-cell halo
100
+ // includes touching boxes and both directions of each shared edge.
101
+ const left = Math.max(0, bb.left - 1, fb.left - 1), top = Math.max(0, bb.top - 1, fb.top - 1);
102
+ const right = Math.min(width, bb.right + 1, fb.right + 1), bottom = Math.min(height, bb.bottom + 1, fb.bottom + 1);
103
+ for (let y = top; y < bottom; y++) for (let x = left; x < right; x++) {
104
+ const p = y * width + x;
105
+ if (B.mask.data[p] !== 0 && F.mask.data[p] !== 0) { overlap++; include(x, y, 1, 1); }
106
+ if (x + 1 < width) { rawEdge(p, p + 1, x + 1, y, 0, 1); rawEdge(p + 1, p, x + 1, y, 0, 1); }
107
+ if (y + 1 < height) { rawEdge(p, p + width, x, y + 1, 1, 0); rawEdge(p + width, p, x, y + 1, 1, 0); }
108
+ }
109
+ if (rawLength > 0 || overlap > 0) raw_pairs.push({ front: F.name, back: B.name,
110
+ boundary_length_px: rawLength, box: [rx0, ry0, rx1 - rx0, ry1 - ry0], overlap_area_px: overlap,
111
+ classification: 'ownership unknown, unclassified' });
112
+ if (domain === undefined || !('mask' in domain)) {
113
+ pairs.push({ front: F.name, back: B.name, status: 'unavailable', reason: `${B.name}: ${domain === undefined ? unavailableReason : domain.reason}`, boundary_length_px: null, box: null, continuation_candidate_area_px: null });
114
+ continue;
115
+ }
116
+ let length = 0, area = 0, x0 = width, y0 = height, x1 = 0, y1 = 0;
117
+ const edge = (a: number, b: number, x: number, y: number, dx: number, dy: number): void => {
118
+ if (B.mask.data[a] === 0 || B.mask.data[b] !== 0 || F.mask.data[a] !== 0 || F.mask.data[b] === 0 || domain.mask.data[a] === 0 || domain.mask.data[b] === 0) return;
119
+ length++;
120
+ x0 = Math.min(x0, x); y0 = Math.min(y0, y);
121
+ x1 = Math.max(x1, x + dx); y1 = Math.max(y1, y + dy);
122
+ };
123
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
124
+ const p = y * width + x;
125
+ if (domain.mask.data[p] !== 0 && F.mask.data[p] !== 0 && B.mask.data[p] === 0) area++;
126
+ if (x + 1 < width) { edge(p, p + 1, x + 1, y, 0, 1); edge(p + 1, p, x + 1, y, 0, 1); }
127
+ if (y + 1 < height) { edge(p, p + width, x, y + 1, 1, 0); edge(p + width, p, x, y + 1, 1, 0); }
128
+ }
129
+ pairs.push({ front: F.name, back: B.name, status: 'measured', boundary_length_px: length,
130
+ box: length === 0 ? null : [x0, y0, x1 - x0, y1 - y0], continuation_candidate_area_px: area });
131
+ }
132
+ const unowned = unownedSupport(width, height, parts, paintedFigure);
133
+ return { status: pairs.some(p => (p.boundary_length_px ?? 0) > 0) || (unowned.area_px ?? 0) > 0 ? 'WARN' : pairs.some(p => p.status === 'measured') ? 'REPORTED' : 'UNCLASSIFIED',
134
+ grid: [width, height], alpha: 'alpha >= 128', pair_registration: 'caller-supplied native masks', unowned_registration: 'caller-supplied native masks', boundary: '4-neighbour unit pixel-cell edges, exact coincidence',
135
+ pairs, raw_pairs, coverage: { measured: pairs.filter(p => p.status === 'measured').length, total: pairs.length }, unowned };
136
+ }
137
+
138
+ /** Painted cells outside the supplied actual setup union, including open edges. */
139
+ export function unownedSupport(width: number, height: number, parts: readonly SupportPart[], paintedFigure: Mask | null): UnownedReading {
140
+ let unowned: UnownedReading = { status: 'unavailable', reason: 'source painting and its painted silhouette are unavailable; supply --source', area_px: null, regions: [] };
141
+ if (paintedFigure !== null) {
142
+ const missing = paintedFigure.data.slice();
143
+ for (const part of parts) for (let p = 0; p < missing.length; p++) if (part.mask.data[p] !== 0) missing[p] = 0;
144
+ const regions = connectedComponents({ width, height, data: missing }, 4).stats.slice(1).map(s => ({ box: [s.left, s.top, s.width, s.height] as SupportBox, area_px: s.area }));
145
+ unowned = { status: 'measured', area_px: regions.reduce((sum, r) => sum + r.area_px, 0), regions };
146
+ }
147
+ return unowned;
148
+ }
149
+
150
+ export function supportLines(report: SupportReport): string[] {
151
+ const classified = report.raw_pairs.filter(raw => report.pairs.some(pair => pair.back === raw.back && pair.front === raw.front && pair.status === 'measured')).length;
152
+ return [`${COINCIDE_LINE}: ${report.status} — ${report.raw_pairs.length} pairs adjacent, ${classified} classified${report.coverage.measured === 0 ? ' (no extent witness)' : ''}; ${report.coverage.measured} of ${report.coverage.total} pairs measured; pairs on ${report.pair_registration}; unowned on ${report.unowned_registration}${report.reason === undefined ? '' : `; ${report.reason}`}`,
153
+ ...report.raw_pairs.map(p => `${COINCIDE_LINE}: back "${p.back}" front "${p.front}" shared boundary ${p.boundary_length_px} px, box ${JSON.stringify(p.box)}, overlap ${p.overlap_area_px} px — ${p.classification}`),
154
+ ...report.pairs.map(p => `${COINCIDE_LINE}: back "${p.back}" front "${p.front}" ${p.status} — ${p.status === 'unavailable' ? p.reason : `boundary ${p.boundary_length_px} px, box ${JSON.stringify(p.box)}, continuation candidate ${p.continuation_candidate_area_px} px`}`),
155
+ `${COINCIDE_LINE}: unowned ${report.unowned.status} — ${report.unowned.status === 'unavailable' ? report.unowned.reason : `${report.unowned.area_px} px, ${report.unowned.regions.length} regions`}`,
156
+ ...report.unowned.regions.map(r => `${COINCIDE_LINE}: unowned box ${JSON.stringify(r.box)}, area ${r.area_px} px`)];
157
+ }
@@ -0,0 +1,79 @@
1
+ /** Pre-rig pair domains and actual textured setup observations (#998). */
2
+ import { readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { figureSilhouette, paintedFigure, sourceInRig } from './assemble.ts';
5
+ import { officialRenderer, sourceSizeProblem, type CheckInputs } from './check.ts';
6
+ import { supportReport, unownedSupport, SUPPORT_GRID_CODE, type SupportPart, type SupportReport } from './coincide.ts';
7
+ import { refuseIfAny } from './errors.ts';
8
+ import { readPng } from './raster/png.ts';
9
+ import { assertBinary, newRaster, type Mask, type Raster } from './raster/types.ts';
10
+ import { readSupportDomains } from './supportdomains.ts';
11
+
12
+ /** The setup candidate is already built by check. Only alpha callbacks are
13
+ * sampled here; no additional rigc build/render or renderFrame is run. */
14
+ export function observeSupport(build: string, input: CheckInputs, supportSource?: string, nativeFigure?: Mask): SupportReport {
15
+ const width = input.stage.width, height = input.stage.height;
16
+ if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width <= 0 || height <= 0 ||
17
+ (input.parts !== null && (input.parts.rig_size[0] !== width || input.parts.rig_size[1] !== height))) refuseIfAny([{ code: SUPPORT_GRID_CODE, object: 'support native canvas', detail: `stage ${width}x${height} must match the positive integer parts.json grid ${JSON.stringify(input.parts?.rig_size)}` }]);
18
+ const ordered = input.parts === null ? [] : [...input.parts.parts];
19
+ const slots = new Map((Array.isArray(input.rig.slots) ? input.rig.slots : []).flatMap((s, i) =>
20
+ typeof s === 'object' && s !== null && 'name' in s && typeof s.name === 'string' ? [[s.name, i] as const] : []));
21
+ for (const part of ordered) if (!slots.has(part.name)) refuseIfAny([{ code: 'CHECK_PART_SLOT_PRESENT', object: `part "${part.name}"`, detail: 'support report requires the named setup slot; no draw order is guessed' }]);
22
+ ordered.sort((a, b) => slots.get(a.name)! - slots.get(b.name)!);
23
+ const art = ordered.map<SupportPart>(part => {
24
+ const image = readPng(join(input.partsDir, `${part.name}.png`));
25
+ if (image.width !== part.w || image.height !== part.h) refuseIfAny([{ code: SUPPORT_GRID_CODE, object: `part "${part.name}"`, detail: `PNG is ${image.width}x${image.height}; parts.json requires ${part.w}x${part.h}` }]);
26
+ const mask: Mask = { width, height, data: new Uint8Array(width * height) };
27
+ for (let y = 0; y < image.height; y++) for (let x = 0; x < image.width; x++) {
28
+ const u = part.x + x, v = part.y + y;
29
+ if (u >= 0 && v >= 0 && u < width && v < height && image.data[(y * image.width + x) * 4 + 3] >= 128) mask.data[v * width + u] = 1;
30
+ }
31
+ return { name: part.name, mask };
32
+ });
33
+ const domains = input.parts === null ? [] : readSupportDomains(input.partsPath, input.partsDir, input.parts);
34
+ const report = supportReport(width, height, art, domains, null);
35
+ report.pair_registration = 'pre-rig parts.json placements, setup slot order';
36
+ report.unowned_registration = 'official renderer setup, native stage grid';
37
+ const api = officialRenderer(), skeleton = join(build, 'skeleton.json'), atlas = join(build, 'skeleton.atlas');
38
+ const candidate = api.loadCandidate({ skeletonText: readFileSync(skeleton, 'utf8'), atlasText: readFileSync(atlas, 'utf8'), atlasDir: build, label: 'part support report' }, { skeleton, atlas }, undefined);
39
+ const pose = api.throughPoser(candidate.choice, p => api.sampleSetupPose(p, { geometry: true, texture: true })).value[0];
40
+ if (pose === undefined || pose.pieces.some(p => 'source' in p)) {
41
+ report.unowned.reason = 'actual setup textured pieces are unavailable or clipped';
42
+ return report;
43
+ }
44
+ const viewport = { minX: input.stage.x, minY: input.stage.y, maxX: input.stage.x + width, maxY: input.stage.y + height, scale: 1, width, height };
45
+ const project = api.projector(viewport), union: Mask = { width, height, data: new Uint8Array(width * height) };
46
+ for (const piece of pose.pieces) api.rasterisePiece(api.pageFor(candidate.pages, piece), piece, project, viewport,
47
+ (x, y, _r, _g, _b, a) => { if (a >= 128) union.data[y * width + x] = 1; });
48
+ if (nativeFigure !== undefined && (nativeFigure.width !== width || nativeFigure.height !== height || nativeFigure.data.length !== width * height)) refuseIfAny([{ code: SUPPORT_GRID_CODE, object: 'transient support figure', detail: `requires ${width}x${height} native cells` }]);
49
+ if (nativeFigure !== undefined) assertBinary('transient support figure', nativeFigure);
50
+ const source = nativeFigure !== undefined ? null : input.source?.painting ?? (supportSource === undefined ? null : readPng(supportSource));
51
+ let figure: Mask | null = nativeFigure ?? null;
52
+ if (source !== null) {
53
+ const mismatch = sourceSizeProblem(source.width, source.height, input.stage, input.parts?.scale_rig_per_source ?? null);
54
+ if (mismatch !== null) refuseIfAny([{ code: SUPPORT_GRID_CODE, object: 'support painting', detail: mismatch }]);
55
+ figure = supportFigure(source, width, height);
56
+ }
57
+ report.unowned = unownedSupport(width, height, [{ name: 'setup union', mask: union }], figure);
58
+ report.status = report.pairs.some(p => (p.boundary_length_px ?? 0) > 0) || (report.unowned.area_px ?? 0) > 0 ? 'WARN' : report.coverage.measured > 0 ? 'REPORTED' : 'UNCLASSIFIED';
59
+ return report;
60
+ }
61
+
62
+ /** Reuse assembly's rig-sized painting only when its alpha is fully opaque.
63
+ * Transparent inputs retain source-over-white before the Lanczos resize. */
64
+ export function supportFigure(source: Raster, width: number, height: number, opaquePainting?: Raster): Mask {
65
+ let painting = opaquePainting;
66
+ for (let p = 3; painting !== undefined && p < source.data.length; p += 4) if (source.data[p] !== 255) painting = undefined;
67
+ if (painting === undefined) {
68
+ const white = newRaster(source.width, source.height);
69
+ for (let p = 0; p < source.width * source.height; p++) {
70
+ const alpha = source.data[p * 4 + 3] / 255;
71
+ for (let c = 0; c < 3; c++) white.data[p * 4 + c] = Math.round(source.data[p * 4 + c] * alpha + 255 * (1 - alpha));
72
+ white.data[p * 4 + 3] = 255;
73
+ }
74
+ painting = sourceInRig(white, width, height);
75
+ }
76
+ const painted = paintedFigure(painting), figure = figureSilhouette(painting, painted);
77
+ for (let p = 0; p < painted.length; p++) figure.data[p] &= painted[p];
78
+ return figure;
79
+ }