rig-parts 2.67.0 → 2.69.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,5 +1,5 @@
1
1
  import { refuseStaleAssembly, type AssemblyRules } from './assembly-reading.ts';
2
- import { checkRow, checkSlotRow, checkSlotParts, serializeCheckRows } from './checkrow.ts';
2
+ import { checkRow, checkSlotRow, checkSlotParts, serializeCheckRows, type CheckRowLabels } from './checkrow.ts';
3
3
  import { readSetupFigureMask } from './setupfiguremask.ts';
4
4
  import { readSetupBackdrop } from './setupbackdrop.ts';
5
5
  import { COINCIDE_LINE, type SupportReport } from './coincide.ts';
@@ -96,7 +96,8 @@ import { PHYSICS_CONTRIBUTES_LINE, measurePhysicsContribution, physicsLine, type
96
96
  import { jointContactReading, type JointContactReading } from './jointcontact.ts';
97
97
  import { createHash } from 'node:crypto';
98
98
  import { createRequire } from 'node:module';
99
- import type { Candidate, Piece, Viewport as RootCoverageViewport } from '@rig-c/core/render-shared';
99
+ import { poseSlider, readModel, underNoSkin } from '@rig-c/core/core';
100
+ import type { AttachmentPose, AttachmentRest, Candidate, Piece, Viewport as RootCoverageViewport } from '@rig-c/core/render-shared';
100
101
  import { fillHoles } from './raster/morph.ts';
101
102
  import { closeSync, copyFileSync, cpSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs';
102
103
  import { argvPathFromOut, diagnosticSegment, diagnosticSiblings, unsafeSegmentReason } from './outputpaths.ts';
@@ -106,7 +107,7 @@ import { type BoneTransform, computeExactFrameTransforms, cropToSpineY, normalis
106
107
  import { capBox, inDisc } from './limbs.ts';
107
108
  import { motionSeamProblems, type MotionSeamDeclaration } from './motionseams.ts';
108
109
  import { seamPoseFrame, seamStaticRange, type SeamPoseAtWorst } from './motionseampose.ts';
109
- import { coreCompileGuideLine, PartsError, type Problem, refuseIfAny } from './errors.ts';
110
+ import { coreCompileGuideLine, failLine, PartsError, type Problem, refuseIfAny } from './errors.ts';
110
111
  import { framesInside, IDLE_FPS, TIME_SLACK } from './motion.ts';
111
112
  import {
112
113
  blinkFigures,
@@ -2983,6 +2984,8 @@ export interface CheckFigures {
2983
2984
  TIP_OVER_ROOT: JudgementLine;
2984
2985
  STILL_REGIONS_DARK: JudgementLine;
2985
2986
  TEXTURE_STRETCH: JudgementLine;
2987
+ /** Texture stretch at the authored slider inputs. Stock check reports these rows as advisories. */
2988
+ slider_stretch?: SliderStretchBlock;
2986
2989
  /** Written whenever motion.json holds an animation, the idle included (issues #320, #333): {@link FoldsLine}. */
2987
2990
  [FOLD_LINE]?: FoldsLine;
2988
2991
  /** Written only where a `footwear` part rides a bone with a parent and motion.json holds an animation (issue #348): {@link LevelLine}. */
@@ -3465,8 +3468,16 @@ export function barsSummary(r: Pick<CheckReport, 'bars'>): string {
3465
3468
  /** The summary's warning clause: each warning line that read something, named, with the warnings they printed together, and `PHYSICS_CONTRIBUTES` (issue #1320) and `SETUP_PAINTING_MOSTLY_UNCOVERED` only when they printed one (issue #1421); empty when none read. */
3466
3469
  export function warningsClause(r: Pick<CheckReport, 'motionSeam' | 'cloth' | 'figures'>): string {
3467
3470
  const read = [...(r.motionSeam.status === 'SKIP' || (r.motionSeam.roots !== undefined && r.motionSeam.pairs.every(p => p.root !== undefined)) ? [] : [{ name: MOTION_SEAM_LINE, n: r.motionSeam.warnings }]), ...(r.cloth.status === 'SKIP' ? [] : [{ name: CLOTH_LINE, n: r.cloth.warnings }]), ...((r.figures[PHYSICS_CONTRIBUTES_LINE]?.warnings ?? 0) === 0 ? [] : [{ name: PHYSICS_CONTRIBUTES_LINE, n: r.figures[PHYSICS_CONTRIBUTES_LINE]?.warnings ?? 0 }]), ...(setupPaintingWarningCount(r.figures[SETUP_PAINTING_LINE]) === 0 ? [] : [{ name: SETUP_PAINTING_UNCOVERED_WARNING, n: setupPaintingWarningCount(r.figures[SETUP_PAINTING_LINE]) }])];
3468
- if (read.length === 0) return '';
3469
- return `; ${read.reduce((a, x) => a + x.n, 0)} warning(s) (${read.map((x) => x.name).join(', ')}, not a bar)`;
3471
+ const sliders = r.figures.slider_stretch;
3472
+ let sliderTally = '';
3473
+ if (sliders !== undefined) {
3474
+ const counts = { PASS: 0, FAIL: 0, SKIP: 0 };
3475
+ for (const row of sliders.rows) counts[row.status]++;
3476
+ if (counts.FAIL > 0) read.push({ name: SLIDER_STRETCH_RULE, n: counts.FAIL });
3477
+ sliderTally = `; ${SLIDER_STRETCH_RULE} advisory rows: ${counts.PASS} PASS, ${counts.FAIL} FAIL, ${counts.SKIP} SKIP`;
3478
+ }
3479
+ const warnings = read.length === 0 ? '' : `; ${read.reduce((a, x) => a + x.n, 0)} warning(s) (${read.map((x) => x.name).join(', ')}, not a bar)`;
3480
+ return warnings + sliderTally;
3470
3481
  }
3471
3482
 
3472
3483
  /**
@@ -7411,6 +7422,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7411
7422
  stretchFailedWithoutReading = stretch.status === 'SKIP' && problems.length > beforeStretch;
7412
7423
  if (full !== null) still = stillLine(full, idle, geometry, geometryPath, problems, notPlanted, readingSkip('STILL_REGIONS_DARK'));
7413
7424
  }
7425
+ const sliderStretch = readSliderStretch(buildDir, sliderStretchBindings(inp.rig));
7414
7426
 
7415
7427
  // 3c. a sleeve on one chain, its first link turned large (issue #347): a throwaway copy, physics left out, posed by rigc
7416
7428
  let stress: JudgementLine | null = null;
@@ -7959,6 +7971,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7959
7971
  TIP_OVER_ROOT: tip,
7960
7972
  STILL_REGIONS_DARK: still,
7961
7973
  TEXTURE_STRETCH: stretch,
7974
+ ...(sliderStretch === undefined ? {} : { slider_stretch: sliderStretch }),
7962
7975
  ...(folds === null ? {} : { [FOLD_LINE]: folds }),
7963
7976
  ...(level === null ? {} : { [LEVEL_LINE]: level }),
7964
7977
  ...(stress === null ? {} : { [STRESS_LINE]: stress }),
@@ -10284,6 +10297,373 @@ export function measureTextureStretch(meshes: readonly MeshRest[], frames: reado
10284
10297
  });
10285
10298
  }
10286
10299
 
10300
+ const SLIDER_STRETCH_RULE = 'CHECK_SLIDER_STRETCH';
10301
+ const SLIDER_STRETCH_SAMPLES = 13;
10302
+
10303
+ export interface SliderStretchBinding {
10304
+ slider: string;
10305
+ clip: string;
10306
+ bone?: unknown;
10307
+ from?: unknown;
10308
+ max?: unknown;
10309
+ }
10310
+
10311
+ export type SliderStretchProvider = (candidate: Candidate, binding: SliderStretchBinding, dial: number) => {
10312
+ attachments: readonly AttachmentPose[];
10313
+ time: number;
10314
+ };
10315
+
10316
+ export interface SliderStretchPeak {
10317
+ severity: number;
10318
+ gate: number;
10319
+ dial_value: number;
10320
+ sample: number;
10321
+ clip_frame: number | null;
10322
+ clip_time_s: number;
10323
+ slot: string;
10324
+ attachment: string;
10325
+ triangle: number;
10326
+ vertices: StretchAt['vertices'];
10327
+ edge: StretchAt['edge'];
10328
+ area_share: number;
10329
+ on_hull: boolean;
10330
+ }
10331
+
10332
+ export interface SliderStretchPassingDial {
10333
+ lower: number | null;
10334
+ upper: number | null;
10335
+ }
10336
+
10337
+ export interface SliderStretchRow {
10338
+ slider: string;
10339
+ clip: string;
10340
+ status: 'PASS' | 'FAIL' | 'SKIP';
10341
+ range: [number, number] | null;
10342
+ sample_count: number;
10343
+ last_passing_dial?: SliderStretchPassingDial;
10344
+ peak?: SliderStretchPeak;
10345
+ reason?: string;
10346
+ }
10347
+
10348
+ export interface SliderStretchBlock {
10349
+ fps: number;
10350
+ limit: number;
10351
+ rows: Array<SliderStretchRow & CheckRowLabels>;
10352
+ }
10353
+
10354
+ /** Read authored endpoints before the compiler fills in defaults. */
10355
+ export function sliderStretchBindings(rig: Record<string, unknown>): SliderStretchBinding[] {
10356
+ const bindings: SliderStretchBinding[] = [];
10357
+ if (!Array.isArray(rig.constraints)) return bindings;
10358
+ for (const c of rig.constraints) {
10359
+ if (!isRecord(c) || c.type !== 'slider' || typeof c.name !== 'string' || typeof c.animation !== 'string') continue;
10360
+ bindings.push({ slider: c.name, clip: c.animation,
10361
+ ...(Object.hasOwn(c, 'bone') ? { bone: c.bone } : {}),
10362
+ ...(Object.hasOwn(c, 'from') ? { from: c.from } : {}),
10363
+ ...(Object.hasOwn(c, 'max') ? { max: c.max } : {}) });
10364
+ }
10365
+ return bindings;
10366
+ }
10367
+
10368
+ function sliderStretchObject(binding: Pick<SliderStretchBinding, 'slider' | 'clip'>): string {
10369
+ return `slider-applied clip ${JSON.stringify(binding.clip)} via dial ${JSON.stringify(binding.slider)}`;
10370
+ }
10371
+
10372
+ function sliderStretchRefusal(api: OfficialRenderer, err: unknown): string {
10373
+ if (err instanceof PartsError) {
10374
+ const [first] = err.problems;
10375
+ return err.problems.length === 1 && first?.code === SLIDER_STRETCH_RULE ? first.detail : err.message;
10376
+ }
10377
+ if (err instanceof api.CandidateAtlasError || err instanceof api.CandidatePairError || err instanceof api.CoreInputError ||
10378
+ err instanceof api.PoserChoiceError || err instanceof api.SlotSubsetError || err instanceof api.SpineRuntimeError) return err.message;
10379
+ throw err;
10380
+ }
10381
+
10382
+ function sliderSampleLabel(sample: number, dial: number): string {
10383
+ return `sample ${sample}, dial ${dial}`;
10384
+ }
10385
+
10386
+ function finiteSliderNumber(value: unknown): value is number {
10387
+ return typeof value === 'number' && Number.isFinite(value);
10388
+ }
10389
+
10390
+ function sliderDialGrid([from, max]: [number, number]): number[] {
10391
+ const span = max - from;
10392
+ return Array.from({ length: SLIDER_STRETCH_SAMPLES }, (_, i) => {
10393
+ const last = SLIDER_STRETCH_SAMPLES - 1;
10394
+ if (i === 0) return from;
10395
+ if (i === last) return max;
10396
+ const t = i / last;
10397
+ return Number.isFinite(span) ? from + span * t : from * (1 - t) + max * t;
10398
+ });
10399
+ }
10400
+
10401
+ type SliderPose = ReturnType<SliderStretchProvider> & { sample: number; dial: number };
10402
+
10403
+ function sliderMeshGeometry(mesh: AttachmentRest, pose: AttachmentPose): string | undefined {
10404
+ const { vertices, triangles } = mesh;
10405
+ if (!numberArray(vertices) || vertices.length % 2 !== 0 || vertices.length !== pose.vertices.length ||
10406
+ !numberArray(triangles) || triangles.length % 3 !== 0 || !triangles.every(i => Number.isInteger(i) && i >= 0 && 2 * i < vertices.length)) {
10407
+ return 'requires finite setup vertices matching the posed vertex count and triangle triplets indexing those vertices';
10408
+ }
10409
+ // Finite vertices can still yield an overflowing length. The shared extrema
10410
+ // alone cannot detect a NaN ratio between finite readings of other edges.
10411
+ for (let i = 0; i < triangles.length; i += 3) {
10412
+ const triangle = triangles.slice(i, i + 3);
10413
+ for (let edge = 0; edge < 3; edge++) {
10414
+ const a = triangle[edge], b = triangle[(edge + 1) % 3];
10415
+ if ([vertices, pose.vertices].some(v => !Number.isFinite(edgeLength(v[2 * a] - v[2 * b], v[2 * a + 1] - v[2 * b + 1])))) {
10416
+ return `triangle ${i / 3} edge ${a}-${b} has a non-finite setup or posed length`;
10417
+ }
10418
+ }
10419
+ }
10420
+ }
10421
+
10422
+ interface SliderMeshFacts {
10423
+ triangle: (index: number) => { area_share: number; on_hull: boolean };
10424
+ }
10425
+
10426
+ function sliderMeshFacts(mesh: MeshRest): SliderMeshFacts | null {
10427
+ const { vertices: v, triangles: t } = mesh;
10428
+ const twiceAreas: number[] = [];
10429
+ const edgeUses = new Map<string, number>();
10430
+ const edgeKey = (p: number, q: number) => `${Math.min(p, q)},${Math.max(p, q)}`;
10431
+ for (let i = 0; i < t.length; i += 3) {
10432
+ const a = t[i], b = t[i + 1], c = t[i + 2];
10433
+ const twice = Math.abs((v[2 * b] - v[2 * a]) * (v[2 * c + 1] - v[2 * a + 1]) - (v[2 * b + 1] - v[2 * a + 1]) * (v[2 * c] - v[2 * a]));
10434
+ if (!Number.isFinite(twice)) return null;
10435
+ twiceAreas.push(twice);
10436
+ for (const key of new Set([edgeKey(a, b), edgeKey(b, c), edgeKey(c, a)])) {
10437
+ edgeUses.set(key, (edgeUses.get(key) ?? 0) + 1);
10438
+ }
10439
+ }
10440
+ const totalTwiceArea = twiceAreas.reduce((sum, area) => sum + area, 0);
10441
+ if (!Number.isFinite(totalTwiceArea) || totalTwiceArea <= 0) return null;
10442
+ return {
10443
+ triangle: index => {
10444
+ const i = 3 * index;
10445
+ const a = t[i], b = t[i + 1], c = t[i + 2];
10446
+ return {
10447
+ area_share: round6(twiceAreas[index] / totalTwiceArea),
10448
+ on_hull: [edgeKey(a, b), edgeKey(b, c), edgeKey(c, a)].some(key => edgeUses.get(key) === 1),
10449
+ };
10450
+ },
10451
+ };
10452
+ }
10453
+
10454
+ function sliderLastPassingDial(dials: readonly number[], passes: (sample: number) => boolean): SliderStretchPassingDial {
10455
+ const mid = (dials.length - 1) / 2;
10456
+ if (!passes(mid)) return { lower: null, upper: null };
10457
+ const norm = (d: number) => d === 0 ? 0 : d;
10458
+ let lower = norm(dials[mid]);
10459
+ for (let i = mid - 1; i >= 0 && passes(i); i--) lower = norm(dials[i]);
10460
+ let upper = norm(dials[mid]);
10461
+ for (let i = mid + 1; i < dials.length && passes(i); i++) upper = norm(dials[i]);
10462
+ return { lower, upper };
10463
+ }
10464
+
10465
+ function measureSliderStretch(api: OfficialRenderer, candidate: Candidate, binding: SliderStretchBinding, range: [number, number], provide: SliderStretchProvider): SliderStretchRow {
10466
+ const dials = sliderDialGrid(range);
10467
+ const poses: SliderPose[] = [];
10468
+ const missed = new Set<number>();
10469
+ const sampleExceeds = new Set<number>();
10470
+ let incomplete: { sample: number; reason: string } | undefined;
10471
+ const miss = (sample: number, dial: number, detail: string) => {
10472
+ missed.add(sample);
10473
+ if (incomplete === undefined || sample < incomplete.sample) incomplete = { sample, reason: `${sliderSampleLabel(sample, dial)}: ${detail}` };
10474
+ };
10475
+ for (const [sample, dial] of dials.entries()) {
10476
+ try {
10477
+ const { attachments, time } = provide(candidate, binding, dial);
10478
+ if (!finiteSliderNumber(time) || time < 0) {
10479
+ miss(sample, dial, `applied clip time is ${String(time)}; requires a finite nonnegative time`);
10480
+ } else if (!Array.isArray(attachments) || attachments.some(a => !isRecord(a) || typeof a.slot !== 'string' ||
10481
+ typeof a.attachment !== 'string' || !numberArray(a.vertices) || a.vertices.length === 0 || a.vertices.length % 2 !== 0)) {
10482
+ miss(sample, dial, `clip time ${time} s: requires named attachment geometry with finite x/y vertex pairs`);
10483
+ } else {
10484
+ poses.push({ sample, dial, attachments, time });
10485
+ }
10486
+ } catch (err) {
10487
+ miss(sample, dial, sliderStretchRefusal(api, err));
10488
+ }
10489
+ }
10490
+
10491
+ let peak: SliderStretchPeak | undefined;
10492
+ let worstSeverity = 0;
10493
+ let exceeds = false;
10494
+ if (poses.length > 0) {
10495
+ let rest: AttachmentRest[] = [];
10496
+ try {
10497
+ rest = api.throughPoser(candidate.choice, poser => {
10498
+ const setup = poser.setup(undefined).attachments();
10499
+ return poser.rest(undefined, [setup, ...poses.map(p => [...p.attachments])]);
10500
+ }).value;
10501
+ } catch (err) {
10502
+ const { sample, dial } = poses[0];
10503
+ if (!(err instanceof Error)) throw err;
10504
+ miss(sample, dial, `setup geometry: ${err.message}`);
10505
+ }
10506
+ const byAttachment = new Map(rest.map(mesh => [JSON.stringify([mesh.slot, mesh.attachment]), mesh]));
10507
+ const byFacts = new Map<string, SliderMeshFacts | null>();
10508
+ for (const { sample, dial, time, attachments } of poses) {
10509
+ const meshes: MeshRest[] = [];
10510
+ const seen = new Set<string>();
10511
+ const unmeasured = (detail: string) => miss(sample, dial, `clip time ${time} s: ${detail}`);
10512
+ for (const attachment of attachments) {
10513
+ const key = JSON.stringify([attachment.slot, attachment.attachment]);
10514
+ const object = `slot ${JSON.stringify(attachment.slot)} attachment ${JSON.stringify(attachment.attachment)}`;
10515
+ const mesh = byAttachment.get(key);
10516
+ if (seen.has(key) || mesh === undefined) {
10517
+ unmeasured(`${object} ${seen.has(key) ? 'appears more than once' : 'has no setup geometry'}`);
10518
+ continue;
10519
+ }
10520
+ seen.add(key);
10521
+ if (mesh.kind !== 'mesh') continue;
10522
+ const bad = sliderMeshGeometry(mesh, attachment);
10523
+ if (bad !== undefined) unmeasured(`${object}: ${bad}`);
10524
+ else meshes.push(mesh);
10525
+ }
10526
+ let measurable = false;
10527
+ const figures = measureTextureStretch(meshes, [{ index: sample, attachments }]);
10528
+ for (const [meshIndex, { mesh, peak: hit }] of figures.entries()) {
10529
+ const restMesh = meshes[meshIndex];
10530
+ const object = `mesh ${JSON.stringify(mesh.slot)} attachment ${JSON.stringify(mesh.attachment)}`;
10531
+ const degenerate = mesh.degenerate[0];
10532
+ if (degenerate !== undefined) unmeasured(`${object} triangle ${degenerate.triangle} edge ${degenerate.edge.join('-')} has zero setup length`);
10533
+ if (hit === null) continue;
10534
+ const { at, raw, rounded } = hit;
10535
+ if (!Number.isFinite(raw) || !Number.isFinite(rounded) || !Number.isFinite(at.ratio) || at.ratio <= 0) {
10536
+ unmeasured(`${object} triangle ${at.triangle} edge ${at.edge.join('-')} has no finite stretch severity (ratio ${at.ratio})`);
10537
+ continue;
10538
+ }
10539
+ const key = JSON.stringify([restMesh.slot, restMesh.attachment]);
10540
+ let facts = byFacts.get(key);
10541
+ if (facts === undefined) {
10542
+ facts = sliderMeshFacts(restMesh);
10543
+ byFacts.set(key, facts);
10544
+ }
10545
+ if (facts === null) {
10546
+ unmeasured(`${object} has zero or non-finite rest area`);
10547
+ continue;
10548
+ }
10549
+ measurable = true;
10550
+ exceeds ||= hit.exceeds;
10551
+ if (hit.exceeds) sampleExceeds.add(sample);
10552
+ if (peak !== undefined && raw <= worstSeverity) continue;
10553
+ worstSeverity = raw;
10554
+ const frame = Math.round(time * IDLE_FPS);
10555
+ const { area_share, on_hull } = facts.triangle(at.triangle);
10556
+ peak = {
10557
+ severity: round6(raw), gate: rounded, dial_value: dial === 0 ? 0 : dial, sample,
10558
+ clip_frame: Number.isSafeInteger(frame) && Math.abs(time - frame / IDLE_FPS) <= TIME_SLACK ? frame : null,
10559
+ clip_time_s: time, slot: mesh.slot, attachment: mesh.attachment, triangle: at.triangle, vertices: at.vertices, edge: at.edge,
10560
+ area_share, on_hull,
10561
+ };
10562
+ }
10563
+ if (!measurable) unmeasured('no posed mesh triangle edge could be measured');
10564
+ }
10565
+ }
10566
+ return {
10567
+ slider: binding.slider,
10568
+ clip: binding.clip,
10569
+ status: incomplete !== undefined || exceeds ? 'FAIL' : 'PASS',
10570
+ range,
10571
+ sample_count: dials.length - missed.size,
10572
+ ...(peak === undefined ? {} : {
10573
+ last_passing_dial: sliderLastPassingDial(dials, s => !missed.has(s) && !sampleExceeds.has(s)),
10574
+ peak,
10575
+ }),
10576
+ ...(incomplete === undefined ? {} : { reason: incomplete.reason }),
10577
+ };
10578
+ }
10579
+
10580
+ /** Measure each slider binding on the pre-gated build. Stock check never votes these rows into its verdict. */
10581
+ export function readSliderStretch(buildDir: string, bindings: readonly SliderStretchBinding[], provide?: SliderStretchProvider): SliderStretchBlock | undefined {
10582
+ if (bindings.length === 0) return undefined;
10583
+ const rows: SliderStretchRow[] = [];
10584
+ let source: { api: OfficialRenderer; candidate: Candidate; provider: SliderStretchProvider } | { reason: string } | undefined;
10585
+ for (const binding of bindings) {
10586
+ const { slider, clip, bone, max } = binding;
10587
+ const from = finiteSliderNumber(binding.from) ? (binding.from === 0 ? 0 : binding.from) : 0;
10588
+ const base = { slider, clip, range: null, sample_count: 0 };
10589
+ const bad = (['from', 'max'] as const).find(key => Object.hasOwn(binding, key) && !finiteSliderNumber(binding[key]));
10590
+ if (bad !== undefined) {
10591
+ rows.push({ ...base, status: 'FAIL', reason: `declared dial bound ${bad} is ${String(binding[bad])}; requires a finite number` });
10592
+ } else if (finiteSliderNumber(max) && from > max) {
10593
+ rows.push({ ...base, status: 'FAIL', reason: `declared dial range [${from}, ${max === 0 ? 0 : max}] is reversed; requires from <= max` });
10594
+ } else if (Object.hasOwn(binding, 'bone') && (typeof bone !== 'string' || bone.length === 0)) {
10595
+ rows.push({ ...base, status: 'FAIL', reason: `declared driving bone is ${String(bone)}; requires a bone name` });
10596
+ } else if (bone === undefined || !finiteSliderNumber(max)) {
10597
+ const reason = bone === undefined ? 'no declared dial range; the slider is time-driven' : 'no declared dial range; declare max to measure texture stretch';
10598
+ rows.push({ ...base, status: 'SKIP', reason });
10599
+ } else if (from === max) {
10600
+ rows.push({ ...base, status: 'SKIP', range: [from, from], reason: `declared dial range [${from}, ${from}] has equal endpoints` });
10601
+ } else {
10602
+ const range: [number, number] = [from, max === 0 ? 0 : max];
10603
+ if (source === undefined) {
10604
+ const api = officialRenderer();
10605
+ const skeleton = join(buildDir, 'skeleton.json'), atlas = join(buildDir, 'skeleton.atlas');
10606
+ if (!existsSync(skeleton)) source = { reason: 'gated skeleton.json is missing' };
10607
+ else {
10608
+ try {
10609
+ const candidate = api.loadCandidate({ skeletonText: readFileSync(skeleton, 'utf8'), atlasText: existsSync(atlas) ? readFileSync(atlas, 'utf8') : null,
10610
+ atlasDir: buildDir, label: 'slider stretch' }, { skeleton, atlas }, undefined);
10611
+ let provider = provide;
10612
+ if (provider === undefined) {
10613
+ const modelPath = join(buildDir, 'skeleton.model.json');
10614
+ const doc = underNoSkin(readModel(readFileSync(modelPath, 'utf8'), modelPath));
10615
+ provider = (_candidate, target, value) => {
10616
+ const { pose, appliedTime } = poseSlider(doc, target.slider, value);
10617
+ return {
10618
+ attachments: pose.drawn.map(({ slot, attachment, vertices, colour }) => ({ slot, attachment, vertices, color: colour })),
10619
+ time: appliedTime,
10620
+ };
10621
+ };
10622
+ }
10623
+ source = { api, candidate, provider };
10624
+ } catch (err) {
10625
+ source = { reason: sliderStretchRefusal(api, err) };
10626
+ }
10627
+ }
10628
+ }
10629
+ if ('reason' in source) {
10630
+ rows.push({ slider, clip, status: 'FAIL', range, sample_count: 0,
10631
+ reason: `${sliderSampleLabel(0, from)}: ${source.reason}` });
10632
+ } else {
10633
+ rows.push(measureSliderStretch(source.api, source.candidate, binding, range, source.provider));
10634
+ }
10635
+ }
10636
+ }
10637
+ return {
10638
+ fps: IDLE_FPS,
10639
+ limit: TEXTURE_STRETCH_CEILING,
10640
+ rows: rows.map(row => ({ ...row, ...checkRow('slider_stretch.rows', 'rig', row.status === 'FAIL', []) })),
10641
+ };
10642
+ }
10643
+
10644
+ function sliderPassingText(value: number | null, bound: number | undefined): string {
10645
+ if (value === null) return 'none (midpoint fails)';
10646
+ return value === bound ? `${value} (range end)` : String(value);
10647
+ }
10648
+
10649
+ export function sliderStretchLine(row: SliderStretchRow, advisory = false): string {
10650
+ const object = sliderStretchObject(row);
10651
+ const { last_passing_dial: reach, peak, range, reason, sample_count: samples } = row;
10652
+ const coverage = samples === SLIDER_STRETCH_SAMPLES ? String(samples) : `${samples} of ${SLIDER_STRETCH_SAMPLES}`;
10653
+ const grid = range === null || row.status === 'SKIP' ? '' : `${coverage} dial samples in [${range.join(', ')}]`;
10654
+ const reachClause = reach === undefined ? '' :
10655
+ `, last passing dial lower ${sliderPassingText(reach.lower, range?.[0])}, upper ${sliderPassingText(reach.upper, range?.[1])}`;
10656
+ const reading = peak === undefined ? grid :
10657
+ `peak ${peak.severity.toFixed(6)}x (gate ${peak.gate.toFixed(3)}x, limit ${TEXTURE_STRETCH_CEILING}x), ${grid}, ` +
10658
+ `dial ${peak.dial_value}, sample ${peak.sample}, clip frame ${peak.clip_frame ?? 'off-grid'} at ${peak.clip_time_s.toFixed(6)} s, ` +
10659
+ `mesh ${JSON.stringify(peak.slot)} attachment ${JSON.stringify(peak.attachment)}, triangle ${peak.triangle} (vertices ${peak.vertices.join(' ')}), ` +
10660
+ `edge ${peak.edge.join('-')}, area share ${peak.area_share.toFixed(6)}, ${peak.on_hull ? 'hull' : 'interior'}${reachClause}`;
10661
+ const detail = [reading, reason].filter(Boolean).join('; ');
10662
+ if (row.status === 'FAIL' && !advisory) return failLine({ code: SLIDER_STRETCH_RULE, object, detail });
10663
+ const level = row.status === 'FAIL' ? 'WARN' : row.status;
10664
+ return ` ${level} ${SLIDER_STRETCH_RULE}: ${object} — ${detail}`;
10665
+ }
10666
+
10287
10667
  /**
10288
10668
  * (6) No visible texture stretch: for every mesh triangle, each edge's length
10289
10669
  * in each idle frame over its rest length (the setup pose's bones, no deform —
package/src/checkrow.ts CHANGED
@@ -85,6 +85,7 @@ export const CHECK_ROW_PATHS = {
85
85
  'seam_scope.pairs': ['seam_scope.pairs', 'sets.*.seam_scope.pairs'],
86
86
  'seam_scope.population.pairs': ['seam_scope.population.pairs', 'sets.*.seam_scope.population.pairs'],
87
87
  'seam_scope.population.single_art': ['seam_scope.population.single_art', 'sets.*.seam_scope.population.single_art'],
88
+ 'slider_stretch.rows': ['slider_stretch.rows'],
88
89
  } as const;
89
90
  export type CheckRowFamily = keyof typeof CHECK_ROW_PATHS;
90
91
  /** Enumerable so object spread preserves provenance; JSON never serializes symbols. */
@@ -3,8 +3,8 @@ import { join } from 'node:path';
3
3
  import type { AttachmentRest, Frame } from '@rig-c/core/render-shared';
4
4
  import { gateThroughRigc, type Log } from './build.ts';
5
5
  import {
6
- DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, edgeBonesText, measureTextureStretch, officialRenderer, rigcRanClause,
7
- TEXTURE_STRETCH_CEILING, type RigcRunner,
6
+ DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, edgeBonesText, measureTextureStretch, officialRenderer, readSliderStretch, rigcRanClause,
7
+ sliderStretchBindings, sliderStretchLine, TEXTURE_STRETCH_CEILING, type RigcRunner, type SliderStretchProvider,
8
8
  } from './check.ts';
9
9
  import { failLine, PartsError } from './errors.ts';
10
10
  import { IDLE_FPS } from './motion.ts';
@@ -56,9 +56,11 @@ export function clipStretchReading(
56
56
  }
57
57
 
58
58
  /** Compose in scratch, gate once, then sample each retained take without rasterizing or emitting a report. */
59
- export function checkClipStretch(scene: string, scratch: string, rigc: RigcRunner, log: Log): boolean {
59
+ export function checkClipStretch(scene: string, scratch: string, rigc: RigcRunner, log: Log, provide?: SliderStretchProvider): boolean {
60
60
  const mode = { pageEdges: DEFAULT_PAGE_EDGES, packShape: DEFAULT_PACK_SHAPE };
61
- const { rig, motion, images } = readSceneForClipStretch(scene, mode);
61
+ const { rig, motion, images, explicitlyPlayed } = readSceneForClipStretch(scene, mode);
62
+ const bindings = sliderStretchBindings({ ...rig });
63
+ const sliderClips = new Set(bindings.map(binding => binding.clip));
62
64
  let passed = true;
63
65
  const [gate] = gateThroughRigc(images, [['rig.json', rigJsonText(rig)], ['motion.json', rigJsonText(motion)]], rigc, scratch, mode, build => {
64
66
  const api = officialRenderer();
@@ -68,7 +70,8 @@ export function checkClipStretch(scene: string, scratch: string, rigc: RigcRunne
68
70
  let object = sceneObject;
69
71
  try {
70
72
  const candidate = api.loadCandidate({ skeletonText: readFileSync(skeleton, 'utf8'), atlasText: readFileSync(atlas, 'utf8'), atlasDir: build, label: sceneObject }, { skeleton, atlas }, undefined);
71
- const sides = Object.keys(motion.animations).filter(name => name !== 'idle');
73
+ const sides = Object.keys(motion.animations).filter(name =>
74
+ name !== 'idle' && (!sliderClips.has(name) || explicitlyPlayed.has(name)));
72
75
  for (const name of [...sides, 'idle']) {
73
76
  object = `${name === 'idle' ? 'declared idle' : 'side clip'} ${JSON.stringify(name)}`;
74
77
  const { value } = api.throughPoser(candidate.choice, poser => {
@@ -85,6 +88,10 @@ export function checkClipStretch(scene: string, scratch: string, rigc: RigcRunne
85
88
  for (const line of value.lines) log(line);
86
89
  if (!value.passed) passed = false;
87
90
  }
91
+ for (const row of readSliderStretch(build, bindings, provide)?.rows ?? []) {
92
+ log(sliderStretchLine(row));
93
+ if (row.status === 'FAIL') passed = false;
94
+ }
88
95
  } catch (err) {
89
96
  if (!(err instanceof api.CandidateAtlasError || err instanceof api.CandidatePairError || err instanceof api.CoreInputError ||
90
97
  err instanceof api.PoserChoiceError || err instanceof api.SpineRuntimeError)) throw err;
@@ -3,8 +3,8 @@ import type { PartVisibility } from './partvisibility.ts';
3
3
  import { createHash } from 'node:crypto';
4
4
  import { readFileSync } from 'node:fs';
5
5
  import { dirname, resolve } from 'node:path';
6
- import type { EditorReceipt } from './editreceipt.ts';
7
- import { parseReceiptProducer, type ReceiptProducer } from './receiptproducer.ts';
6
+ import { SHA256_PATTERN, type EditorReceipt } from './editreceipt.ts';
7
+ import { parseReceiptProducer, receiptObject, receiptText, type ReceiptProducer } from './receiptproducer.ts';
8
8
  import { refuseIfAny, type Problem } from './errors.ts';
9
9
  import { OPAQUE_ALPHA_ABOVE } from './layers.ts';
10
10
  import { AUTOMATIC_WRITERS, EXCLUDED_PIXEL, NOT_OVERRIDDEN_PIXEL, rgbaEqual, type AutomaticWriter, type PartStageMap, type PixelProvenance, type StageMap, type ValueBaseline } from './provenance.ts';
@@ -17,6 +17,23 @@ import type { PaintingOwner } from './paintingowner.ts';
17
17
  export type EditedPartReceipt = Omit<EditorReceipt, 'editor'> & { part: string } &
18
18
  ({ editor: string; producer?: never } | { producer: ReceiptProducer; editor?: never });
19
19
 
20
+ export function editedPartReceiptProblem(value: unknown): string | undefined {
21
+ if (!receiptObject(value)) return 'missing or invalid receipt object';
22
+ if (!receiptText(value.part)) return 'missing or invalid part';
23
+ if (!receiptText(value.file) || /^(?:[\\/]|[A-Za-z]:[\\/])/.test(value.file)) return 'missing or invalid relative file';
24
+ for (const key of ['sha256', 'from_sha256'] as const) {
25
+ const hash = value[key];
26
+ if (typeof hash !== 'string' || !SHA256_PATTERN.test(hash)) return `missing or invalid ${key}`;
27
+ }
28
+ const keys = Object.keys(value).sort().join(',');
29
+ if (keys === 'editor,file,from_sha256,part,sha256') return receiptText(value.editor) ? undefined : 'invalid editor';
30
+ if (keys === 'file,from_sha256,part,producer,sha256') {
31
+ try { parseReceiptProducer(value.producer, 'edited part producer'); return undefined; }
32
+ catch { return 'invalid producer'; }
33
+ }
34
+ return 'missing exclusive editor or producer, or unexpected receipt field';
35
+ }
36
+
20
37
  export function orderedEditedPartReceipt(receipt: EditedPartReceipt): EditedPartReceipt {
21
38
  const { part, file, sha256, from_sha256, editor, producer } = receipt;
22
39
  const fields = { part, file, sha256, from_sha256 };
@@ -31,10 +48,7 @@ export interface VerifiedEditedPart {
31
48
  bytes: Uint8Array;
32
49
  image: Raster;
33
50
  }
34
- export interface EditedPartProvenance {
35
- edit: string;
36
- dir: string;
37
- receipt: EditedPartReceipt;
51
+ export interface EditedPixelCounts {
38
52
  changed_px: number;
39
53
  changed_counted_px: number;
40
54
  changed_excluded_px: number;
@@ -49,8 +63,33 @@ export interface EditedPartProvenance {
49
63
  */
50
64
  removed_opaque_regions?: EditedPartRemovedRegion[];
51
65
  }
66
+ export interface EditedPartProvenance extends EditedPixelCounts {
67
+ edit: string;
68
+ dir: string;
69
+ receipt: EditedPartReceipt;
70
+ }
52
71
  export interface EditedPartRemovedRegion { box: [number, number, number, number]; px: number }
53
72
 
73
+ export function editedPixelCounts(): EditedPixelCounts {
74
+ return { changed_px: 0, changed_counted_px: 0, changed_excluded_px: 0, removed_opaque_px: 0 };
75
+ }
76
+
77
+ /** One shared census for edits applied during or after assembly. */
78
+ export function editedPixelChanged(old: Raster, next: Raster, p: number, counts: EditedPixelCounts, removed: Uint8Array): boolean {
79
+ const offset = p * 4;
80
+ if (rgbaEqual(old.data, offset, next.data, offset)) return false;
81
+ counts.changed_px++;
82
+ if (next.data[offset + 3] > OPAQUE_ALPHA_ABOVE) counts.changed_counted_px++;
83
+ else {
84
+ counts.changed_excluded_px++;
85
+ if (old.data[offset + 3] > OPAQUE_ALPHA_ABOVE) {
86
+ counts.removed_opaque_px++;
87
+ removed[p] = 1;
88
+ }
89
+ }
90
+ return true;
91
+ }
92
+
54
93
  /** 8-connected regions of a part-sized 0/1 mask, ordered as `removed_opaque_regions` requires. */
55
94
  export function removedOpaqueRegions(removed: Uint8Array, width: number, height: number): EditedPartRemovedRegion[] {
56
95
  const seen = new Uint8Array(removed.length), out: EditedPartRemovedRegion[] = [];
@@ -107,6 +146,13 @@ export interface EditedPartContext {
107
146
  const AT = 'config.assemble.edited_parts';
108
147
  const sha = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');
109
148
 
149
+ export function decodeEditedPart(bytes: Uint8Array, receipt: EditedPartReceipt): { image: Raster } | { kind: 'hash' | 'decode'; detail: string } {
150
+ const found = sha(bytes);
151
+ if (found !== receipt.sha256) return { kind: 'hash', detail: `file sha256 is ${found}; receipt sha256 ${receipt.sha256} is required` };
152
+ try { return { image: decodePngBytes(bytes, receipt.file) }; }
153
+ catch (error) { return { kind: 'decode', detail: `file "${receipt.file}" is not a decodable PNG: ${(error as Error).message.split('\n')[0]}` }; }
154
+ }
155
+
110
156
  /** Read once: validation, decoding and final emission all use these exact bytes. */
111
157
  export function readEditedParts(spec: EditedParts | undefined, configPath: string, plan: ReadonlyArray<readonly [string, string, string]>): VerifiedEditedPart[] {
112
158
  if (spec === undefined) return [];
@@ -121,13 +167,9 @@ export function readEditedParts(spec: EditedParts | undefined, configPath: strin
121
167
  let bytes: Uint8Array;
122
168
  try { bytes = new Uint8Array(readFileSync(path)); }
123
169
  catch { problems.push({ code: 'ASSEMBLE_EDITED_PART_FILE', object, detail: `file "${receipt.file}" in dir "${spec.dir}" is not readable; a PNG relative to edited_parts.dir is required` }); continue; }
124
- const found = sha(bytes);
125
- if (found !== receipt.sha256) {
126
- problems.push({ code: 'ASSEMBLE_EDITED_PART_SHA256', object, detail: `file sha256 is ${found}; receipt sha256 ${receipt.sha256} is required` });
127
- continue;
128
- }
129
- try { out.push({ index, dir: spec.dir, receipt, bytes, image: decodePngBytes(bytes, receipt.file) }); }
130
- catch (error) { problems.push({ code: 'ASSEMBLE_EDITED_PART_DECODES', object, detail: `file "${receipt.file}" is not a decodable PNG: ${(error as Error).message.split('\n')[0]}` }); }
170
+ const decoded = decodeEditedPart(bytes, receipt);
171
+ if ('image' in decoded) out.push({ index, dir: spec.dir, receipt, bytes, image: decoded.image });
172
+ else problems.push({ code: decoded.kind === 'hash' ? 'ASSEMBLE_EDITED_PART_SHA256' : 'ASSEMBLE_EDITED_PART_DECODES', object, detail: decoded.detail });
131
173
  }
132
174
  refuseIfAny(problems);
133
175
  return out;
@@ -191,8 +233,7 @@ export function replaceEditedParts(
191
233
  let id = map.edits.indexOf(name) + 1;
192
234
  if (id === 0) { map.edits.push(name); id = map.edits.length; }
193
235
  const metadata: EditedPartProvenance = { edit: name, dir: edit.dir,
194
- receipt: orderedEditedPartReceipt(edit.receipt),
195
- changed_px: 0, changed_counted_px: 0, changed_excluded_px: 0, removed_opaque_px: 0 };
236
+ receipt: orderedEditedPartReceipt(edit.receipt), ...editedPixelCounts() };
196
237
  const next: PartStageMap = { name: stage.name, x: stage.x, y: stage.y, w: stage.w, h: stage.h,
197
238
  excluded_px: 0, runs: [], pre_seam_writer_runs: [], edited_part: metadata };
198
239
  const provenance: PixelProvenance = { unchanged_layer_px: 0, hand_px: 0, automatic_px: 0, edits: [], automatic: [],
@@ -206,14 +247,9 @@ export function replaceEditedParts(
206
247
  const baseline = context.baseline;
207
248
  for (let p = 0; p < old.width * old.height; p++) {
208
249
  const offset = p * 4, prior = previous(), priorSeam = preSeam();
209
- const changed = !rgbaEqual(old.data, offset, edit.image.data, offset);
250
+ const changed = editedPixelChanged(old, edit.image, p, metadata, removed);
210
251
  const counted = edit.image.data[offset + 3] > OPAQUE_ALPHA_ABOVE;
211
252
  if (!changed && counted) visibility?.copy(edit.image, p, old);
212
- if (changed) {
213
- metadata.changed_px++;
214
- if (counted) metadata.changed_counted_px++; else metadata.changed_excluded_px++;
215
- }
216
- if (old.data[offset + 3] > OPAQUE_ALPHA_ABOVE && !counted) { metadata.removed_opaque_px++; removed[p] = 1; }
217
253
  if (!counted) { next.excluded_px++; append(next.runs, EXCLUDED_PIXEL); append(next.pre_seam_writer_runs, EXCLUDED_PIXEL); continue; }
218
254
  opaque++;
219
255
  const x = record.x + p % record.w, y = record.y + Math.floor(p / record.w);