rig-parts 2.66.0 → 2.68.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 }),
@@ -10271,6 +10284,301 @@ export function edgeBonesText(rig: Record<string, unknown>, motion: Record<strin
10271
10284
  return `${parts.join(' and ')}; ${chains}`;
10272
10285
  }
10273
10286
 
10287
+ /** The stock bar and the clip diagnostic use the same ratios, peak per mesh, rounding and limit. */
10288
+ export function measureTextureStretch(meshes: readonly MeshRest[], frames: readonly GeometryPose[]) {
10289
+ return stretchFigures(meshes, frames).map(mesh => {
10290
+ if (mesh.max === null || mesh.min === null) return { mesh, peak: null };
10291
+ const sMax = stretchSeverity(mesh.max.ratio);
10292
+ const sMin = stretchSeverity(mesh.min.ratio);
10293
+ const at = sMin > sMax ? mesh.min : mesh.max;
10294
+ const raw = Math.max(sMax, sMin);
10295
+ const rounded = round3(raw);
10296
+ return { mesh, peak: { at, raw, rounded, exceeds: rounded > TEXTURE_STRETCH_CEILING } };
10297
+ });
10298
+ }
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
+ }
10329
+
10330
+ export interface SliderStretchRow {
10331
+ slider: string;
10332
+ clip: string;
10333
+ status: 'PASS' | 'FAIL' | 'SKIP';
10334
+ range: [number, number] | null;
10335
+ sample_count: number;
10336
+ peak?: SliderStretchPeak;
10337
+ reason?: string;
10338
+ }
10339
+
10340
+ export interface SliderStretchBlock {
10341
+ fps: number;
10342
+ limit: number;
10343
+ rows: Array<SliderStretchRow & CheckRowLabels>;
10344
+ }
10345
+
10346
+ /** Read authored endpoints before the compiler fills in defaults. */
10347
+ export function sliderStretchBindings(rig: Record<string, unknown>): SliderStretchBinding[] {
10348
+ const bindings: SliderStretchBinding[] = [];
10349
+ if (!Array.isArray(rig.constraints)) return bindings;
10350
+ for (const c of rig.constraints) {
10351
+ if (!isRecord(c) || c.type !== 'slider' || typeof c.name !== 'string' || typeof c.animation !== 'string') continue;
10352
+ bindings.push({ slider: c.name, clip: c.animation,
10353
+ ...(Object.hasOwn(c, 'bone') ? { bone: c.bone } : {}),
10354
+ ...(Object.hasOwn(c, 'from') ? { from: c.from } : {}),
10355
+ ...(Object.hasOwn(c, 'max') ? { max: c.max } : {}) });
10356
+ }
10357
+ return bindings;
10358
+ }
10359
+
10360
+ function sliderStretchObject(binding: Pick<SliderStretchBinding, 'slider' | 'clip'>): string {
10361
+ return `slider-applied clip ${JSON.stringify(binding.clip)} via dial ${JSON.stringify(binding.slider)}`;
10362
+ }
10363
+
10364
+ function sliderStretchRefusal(api: OfficialRenderer, err: unknown): string {
10365
+ if (err instanceof PartsError) {
10366
+ const [first] = err.problems;
10367
+ return err.problems.length === 1 && first?.code === SLIDER_STRETCH_RULE ? first.detail : err.message;
10368
+ }
10369
+ if (err instanceof api.CandidateAtlasError || err instanceof api.CandidatePairError || err instanceof api.CoreInputError ||
10370
+ err instanceof api.PoserChoiceError || err instanceof api.SlotSubsetError || err instanceof api.SpineRuntimeError) return err.message;
10371
+ throw err;
10372
+ }
10373
+
10374
+ function sliderSampleLabel(sample: number, dial: number): string {
10375
+ return `sample ${sample}, dial ${dial}`;
10376
+ }
10377
+
10378
+ function finiteSliderNumber(value: unknown): value is number {
10379
+ return typeof value === 'number' && Number.isFinite(value);
10380
+ }
10381
+
10382
+ function sliderDialGrid([from, max]: [number, number]): number[] {
10383
+ const span = max - from;
10384
+ return Array.from({ length: SLIDER_STRETCH_SAMPLES }, (_, i) => {
10385
+ const last = SLIDER_STRETCH_SAMPLES - 1;
10386
+ if (i === 0) return from;
10387
+ if (i === last) return max;
10388
+ const t = i / last;
10389
+ return Number.isFinite(span) ? from + span * t : from * (1 - t) + max * t;
10390
+ });
10391
+ }
10392
+
10393
+ type SliderPose = ReturnType<SliderStretchProvider> & { sample: number; dial: number };
10394
+
10395
+ function sliderMeshGeometry(mesh: AttachmentRest, pose: AttachmentPose): string | undefined {
10396
+ const { vertices, triangles } = mesh;
10397
+ if (!numberArray(vertices) || vertices.length % 2 !== 0 || vertices.length !== pose.vertices.length ||
10398
+ !numberArray(triangles) || triangles.length % 3 !== 0 || !triangles.every(i => Number.isInteger(i) && i >= 0 && 2 * i < vertices.length)) {
10399
+ return 'requires finite setup vertices matching the posed vertex count and triangle triplets indexing those vertices';
10400
+ }
10401
+ // Finite vertices can still yield an overflowing length. The shared extrema
10402
+ // alone cannot detect a NaN ratio between finite readings of other edges.
10403
+ for (let i = 0; i < triangles.length; i += 3) {
10404
+ const triangle = triangles.slice(i, i + 3);
10405
+ for (let edge = 0; edge < 3; edge++) {
10406
+ const a = triangle[edge], b = triangle[(edge + 1) % 3];
10407
+ if ([vertices, pose.vertices].some(v => !Number.isFinite(edgeLength(v[2 * a] - v[2 * b], v[2 * a + 1] - v[2 * b + 1])))) {
10408
+ return `triangle ${i / 3} edge ${a}-${b} has a non-finite setup or posed length`;
10409
+ }
10410
+ }
10411
+ }
10412
+ }
10413
+
10414
+ function measureSliderStretch(api: OfficialRenderer, candidate: Candidate, binding: SliderStretchBinding, range: [number, number], provide: SliderStretchProvider): SliderStretchRow {
10415
+ const dials = sliderDialGrid(range);
10416
+ const base = { slider: binding.slider, clip: binding.clip, range };
10417
+ const poses: SliderPose[] = [];
10418
+ const missed = new Set<number>();
10419
+ let incomplete: { sample: number; reason: string } | undefined;
10420
+ const miss = (sample: number, dial: number, detail: string) => {
10421
+ missed.add(sample);
10422
+ if (incomplete === undefined || sample < incomplete.sample) incomplete = { sample, reason: `${sliderSampleLabel(sample, dial)}: ${detail}` };
10423
+ };
10424
+ for (const [sample, dial] of dials.entries()) {
10425
+ try {
10426
+ const { attachments, time } = provide(candidate, binding, dial);
10427
+ if (!finiteSliderNumber(time) || time < 0) {
10428
+ miss(sample, dial, `applied clip time is ${String(time)}; requires a finite nonnegative time`);
10429
+ } else if (!Array.isArray(attachments) || attachments.some(a => !isRecord(a) || typeof a.slot !== 'string' ||
10430
+ typeof a.attachment !== 'string' || !numberArray(a.vertices) || a.vertices.length === 0 || a.vertices.length % 2 !== 0)) {
10431
+ miss(sample, dial, `clip time ${time} s: requires named attachment geometry with finite x/y vertex pairs`);
10432
+ } else {
10433
+ poses.push({ sample, dial, attachments, time });
10434
+ }
10435
+ } catch (err) {
10436
+ miss(sample, dial, sliderStretchRefusal(api, err));
10437
+ }
10438
+ }
10439
+
10440
+ let peak: SliderStretchPeak | undefined;
10441
+ let worstSeverity = 0;
10442
+ let exceeds = false;
10443
+ if (poses.length > 0) {
10444
+ let rest: AttachmentRest[] = [];
10445
+ try {
10446
+ rest = api.throughPoser(candidate.choice, poser => {
10447
+ const setup = poser.setup(undefined).attachments();
10448
+ return poser.rest(undefined, [setup, ...poses.map(p => [...p.attachments])]);
10449
+ }).value;
10450
+ } catch (err) {
10451
+ const { sample, dial } = poses[0];
10452
+ if (!(err instanceof Error)) throw err;
10453
+ miss(sample, dial, `setup geometry: ${err.message}`);
10454
+ }
10455
+ const byAttachment = new Map(rest.map(mesh => [JSON.stringify([mesh.slot, mesh.attachment]), mesh]));
10456
+ for (const { sample, dial, time, attachments } of poses) {
10457
+ const meshes: MeshRest[] = [];
10458
+ const seen = new Set<string>();
10459
+ const unmeasured = (detail: string) => miss(sample, dial, `clip time ${time} s: ${detail}`);
10460
+ for (const attachment of attachments) {
10461
+ const key = JSON.stringify([attachment.slot, attachment.attachment]);
10462
+ const object = `slot ${JSON.stringify(attachment.slot)} attachment ${JSON.stringify(attachment.attachment)}`;
10463
+ const mesh = byAttachment.get(key);
10464
+ if (seen.has(key) || mesh === undefined) {
10465
+ unmeasured(`${object} ${seen.has(key) ? 'appears more than once' : 'has no setup geometry'}`);
10466
+ continue;
10467
+ }
10468
+ seen.add(key);
10469
+ if (mesh.kind !== 'mesh') continue;
10470
+ const bad = sliderMeshGeometry(mesh, attachment);
10471
+ if (bad !== undefined) unmeasured(`${object}: ${bad}`);
10472
+ else meshes.push(mesh);
10473
+ }
10474
+ let measurable = false;
10475
+ for (const { mesh, peak: hit } of measureTextureStretch(meshes, [{ index: sample, attachments }])) {
10476
+ const object = `mesh ${JSON.stringify(mesh.slot)} attachment ${JSON.stringify(mesh.attachment)}`;
10477
+ const degenerate = mesh.degenerate[0];
10478
+ if (degenerate !== undefined) unmeasured(`${object} triangle ${degenerate.triangle} edge ${degenerate.edge.join('-')} has zero setup length`);
10479
+ if (hit === null) continue;
10480
+ const { at, raw, rounded } = hit;
10481
+ if (!Number.isFinite(raw) || !Number.isFinite(rounded) || !Number.isFinite(at.ratio) || at.ratio <= 0) {
10482
+ unmeasured(`${object} triangle ${at.triangle} edge ${at.edge.join('-')} has no finite stretch severity (ratio ${at.ratio})`);
10483
+ continue;
10484
+ }
10485
+ measurable = true;
10486
+ exceeds ||= hit.exceeds;
10487
+ if (peak !== undefined && raw <= worstSeverity) continue;
10488
+ worstSeverity = raw;
10489
+ const frame = Math.round(time * IDLE_FPS);
10490
+ peak = {
10491
+ severity: round6(raw), gate: rounded, dial_value: dial, sample,
10492
+ clip_frame: Number.isSafeInteger(frame) && Math.abs(time - frame / IDLE_FPS) <= TIME_SLACK ? frame : null,
10493
+ clip_time_s: time, slot: mesh.slot, attachment: mesh.attachment, triangle: at.triangle, vertices: at.vertices, edge: at.edge,
10494
+ };
10495
+ }
10496
+ if (!measurable) unmeasured('no posed mesh triangle edge could be measured');
10497
+ }
10498
+ }
10499
+ return { ...base, status: incomplete !== undefined || exceeds ? 'FAIL' : 'PASS', sample_count: dials.length - missed.size,
10500
+ ...(peak === undefined ? {} : { peak }), ...(incomplete === undefined ? {} : { reason: incomplete.reason }) };
10501
+ }
10502
+
10503
+ /** Measure each slider binding on the pre-gated build. Stock check never votes these rows into its verdict. */
10504
+ export function readSliderStretch(buildDir: string, bindings: readonly SliderStretchBinding[], provide?: SliderStretchProvider): SliderStretchBlock | undefined {
10505
+ if (bindings.length === 0) return undefined;
10506
+ const rows: SliderStretchRow[] = [];
10507
+ let source: { api: OfficialRenderer; candidate: Candidate; provider: SliderStretchProvider } | { reason: string } | undefined;
10508
+ for (const binding of bindings) {
10509
+ const { slider, clip, bone, max } = binding;
10510
+ const from = finiteSliderNumber(binding.from) ? binding.from : 0;
10511
+ const base = { slider, clip, range: null, sample_count: 0 };
10512
+ const bad = (['from', 'max'] as const).find(key => Object.hasOwn(binding, key) && !finiteSliderNumber(binding[key]));
10513
+ if (bad !== undefined) {
10514
+ rows.push({ ...base, status: 'FAIL', reason: `declared dial bound ${bad} is ${String(binding[bad])}; requires a finite number` });
10515
+ } else if (finiteSliderNumber(max) && from > max) {
10516
+ rows.push({ ...base, status: 'FAIL', reason: `declared dial range [${from}, ${max}] is reversed; requires from <= max` });
10517
+ } else if (Object.hasOwn(binding, 'bone') && (typeof bone !== 'string' || bone.length === 0)) {
10518
+ rows.push({ ...base, status: 'FAIL', reason: `declared driving bone is ${String(bone)}; requires a bone name` });
10519
+ } else if (bone === undefined || !finiteSliderNumber(max)) {
10520
+ const reason = bone === undefined ? 'no declared dial range; the slider is time-driven' : 'no declared dial range; declare max to measure texture stretch';
10521
+ rows.push({ ...base, status: 'SKIP', reason });
10522
+ } else if (from === max) {
10523
+ rows.push({ ...base, status: 'SKIP', range: [from, max], reason: `declared dial range [${from}, ${max}] has equal endpoints` });
10524
+ } else {
10525
+ const range: [number, number] = [from, max];
10526
+ if (source === undefined) {
10527
+ const api = officialRenderer();
10528
+ const skeleton = join(buildDir, 'skeleton.json'), atlas = join(buildDir, 'skeleton.atlas');
10529
+ if (!existsSync(skeleton)) source = { reason: 'gated skeleton.json is missing' };
10530
+ else {
10531
+ try {
10532
+ const candidate = api.loadCandidate({ skeletonText: readFileSync(skeleton, 'utf8'), atlasText: existsSync(atlas) ? readFileSync(atlas, 'utf8') : null,
10533
+ atlasDir: buildDir, label: 'slider stretch' }, { skeleton, atlas }, undefined);
10534
+ let provider = provide;
10535
+ if (provider === undefined) {
10536
+ const modelPath = join(buildDir, 'skeleton.model.json');
10537
+ const doc = underNoSkin(readModel(readFileSync(modelPath, 'utf8'), modelPath));
10538
+ provider = (_candidate, target, value) => {
10539
+ const { pose, appliedTime } = poseSlider(doc, target.slider, value);
10540
+ return {
10541
+ attachments: pose.drawn.map(({ slot, attachment, vertices, colour }) => ({ slot, attachment, vertices, color: colour })),
10542
+ time: appliedTime,
10543
+ };
10544
+ };
10545
+ }
10546
+ source = { api, candidate, provider };
10547
+ } catch (err) {
10548
+ source = { reason: sliderStretchRefusal(api, err) };
10549
+ }
10550
+ }
10551
+ }
10552
+ if ('reason' in source) {
10553
+ rows.push({ slider, clip, status: 'FAIL', range, sample_count: 0,
10554
+ reason: `${sliderSampleLabel(0, from)}: ${source.reason}` });
10555
+ } else {
10556
+ rows.push(measureSliderStretch(source.api, source.candidate, binding, range, source.provider));
10557
+ }
10558
+ }
10559
+ }
10560
+ return {
10561
+ fps: IDLE_FPS,
10562
+ limit: TEXTURE_STRETCH_CEILING,
10563
+ rows: rows.map(row => ({ ...row, ...checkRow('slider_stretch.rows', 'rig', row.status === 'FAIL', []) })),
10564
+ };
10565
+ }
10566
+
10567
+ export function sliderStretchLine(row: SliderStretchRow, advisory = false): string {
10568
+ const object = sliderStretchObject(row);
10569
+ const { peak, range, reason, sample_count: samples } = row;
10570
+ const coverage = samples === SLIDER_STRETCH_SAMPLES ? String(samples) : `${samples} of ${SLIDER_STRETCH_SAMPLES}`;
10571
+ const grid = range === null || row.status === 'SKIP' ? '' : `${coverage} dial samples in [${range.join(', ')}]`;
10572
+ const reading = peak === undefined ? grid :
10573
+ `peak ${peak.severity.toFixed(6)}x (gate ${peak.gate.toFixed(3)}x, limit ${TEXTURE_STRETCH_CEILING}x), ${grid}, ` +
10574
+ `dial ${peak.dial_value}, sample ${peak.sample}, clip frame ${peak.clip_frame ?? 'off-grid'} at ${peak.clip_time_s.toFixed(6)} s, ` +
10575
+ `mesh ${JSON.stringify(peak.slot)} attachment ${JSON.stringify(peak.attachment)}, triangle ${peak.triangle} (vertices ${peak.vertices.join(' ')}), edge ${peak.edge.join('-')}`;
10576
+ const detail = [reading, reason].filter(Boolean).join('; ');
10577
+ if (row.status === 'FAIL' && !advisory) return failLine({ code: SLIDER_STRETCH_RULE, object, detail });
10578
+ const level = row.status === 'FAIL' ? 'WARN' : row.status;
10579
+ return ` ${level} ${SLIDER_STRETCH_RULE}: ${object} — ${detail}`;
10580
+ }
10581
+
10274
10582
  /**
10275
10583
  * (6) No visible texture stretch: for every mesh triangle, each edge's length
10276
10584
  * in each idle frame over its rest length (the setup pose's bones, no deform —
@@ -10285,13 +10593,13 @@ export function edgeBonesText(rig: Record<string, unknown>, motion: Record<strin
10285
10593
  export function stretchLine(geo: IdleGeometry | null, path: string, problems: Problem[], bound?: Pick<CheckInputs, 'rig' | 'motion'> & WeightStepContext, slotParts?: ReadonlyMap<string, string>, skipped: ReadingSkip<'TEXTURE_STRETCH'> = skip): JudgementLine {
10286
10594
  if (geo === null) return skipped(`${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`, 'no-reading');
10287
10595
  if (geo.meshes.length === 0) return skipped('the rig draws no mesh attachment (every slot is a region), so there is no triangle to stretch', 'no-meshes');
10288
- const figures = stretchFigures(geo.meshes, geo.frames);
10596
+ const figures = measureTextureStretch(geo.meshes, geo.frames);
10289
10597
  const rows: Array<Record<string, unknown>> = [];
10290
- let worst: { mesh: (typeof figures)[number]; at: NonNullable<(typeof figures)[number]['max']>; severity: number } | null = null;
10598
+ let worst: { mesh: (typeof figures)[number]['mesh']; at: StretchAt; severity: number } | null = null;
10291
10599
  let maxAll: number | null = null;
10292
10600
  let minAll: number | null = null;
10293
10601
  let failed = false;
10294
- for (const m of figures) {
10602
+ for (const { mesh: m, peak } of figures) {
10295
10603
  if (m.degenerate.length > 0) {
10296
10604
  failed = true;
10297
10605
  problems.push({
@@ -10300,19 +10608,16 @@ export function stretchLine(geo: IdleGeometry | null, path: string, problems: Pr
10300
10608
  detail: `${m.degenerate.length} rest edge(s) of length 0, the first triangle ${m.degenerate[0].triangle} edge ${m.degenerate[0].edge.join('-')}; no stretch ratio can be read off an edge with no rest length — two of the mesh's vertices coincide at the setup pose`,
10301
10609
  });
10302
10610
  }
10303
- if (m.max === null || m.min === null) {
10611
+ if (peak === null || m.max === null || m.min === null) {
10304
10612
  rows.push({ ...checkSlotRow('TEXTURE_STRETCH.per_mesh', false, m.slot, slotParts), slot: m.slot, triangles: m.triangles, unmeasured: 'no idle frame shows this attachment' });
10305
10613
  continue;
10306
10614
  }
10307
- const sMax = stretchSeverity(m.max.ratio);
10308
- const sMin = stretchSeverity(m.min.ratio);
10309
- const at = sMin > sMax ? m.min : m.max;
10310
- const severity = round3(Math.max(sMax, sMin));
10615
+ const { at, rounded: severity, exceeds } = peak;
10311
10616
  if (worst === null || severity > worst.severity) worst = { mesh: m, at, severity };
10312
10617
  maxAll = maxAll === null ? m.max.ratio : Math.max(maxAll, m.max.ratio);
10313
10618
  minAll = minAll === null ? m.min.ratio : Math.min(minAll, m.min.ratio);
10314
- rows.push({ ...checkSlotRow('TEXTURE_STRETCH.per_mesh', severity > TEXTURE_STRETCH_CEILING, m.slot, slotParts), 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 });
10315
- if (severity > TEXTURE_STRETCH_CEILING) {
10619
+ rows.push({ ...checkSlotRow('TEXTURE_STRETCH.per_mesh', exceeds, m.slot, slotParts), 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 });
10620
+ if (exceeds) {
10316
10621
  failed = true;
10317
10622
  const step = bound === undefined ? '' : weightStepText(bound.rig, m.slot, m.attachment, at.edge, bound);
10318
10623
  const band = bound === undefined ? '' : contourBandText(bound.rig, m.slot, m.attachment, at.edge, bound, slotParts);
@@ -10323,11 +10628,11 @@ export function stretchLine(geo: IdleGeometry | null, path: string, problems: Pr
10323
10628
  });
10324
10629
  }
10325
10630
  }
10326
- if (worst === null) return skipped(`no idle frame shows any of the rig's ${figures.length} mesh(es): ${figures.map((m) => `"${m.slot}"`).join(', ')}`, 'no-visible-meshes');
10631
+ if (worst === null) return skipped(`no idle frame shows any of the rig's ${figures.length} mesh(es): ${figures.map(({ mesh }) => `"${mesh.slot}"`).join(', ')}`, 'no-visible-meshes');
10327
10632
  return {
10328
10633
  status: failed ? 'FAIL' : 'PASS',
10329
10634
  meshes: figures.length,
10330
- triangles: figures.reduce((n, m) => n + m.triangles, 0),
10635
+ triangles: figures.reduce((n, m) => n + m.mesh.triangles, 0),
10331
10636
  frames: geo.frames.length,
10332
10637
  severity: worst.severity,
10333
10638
  severity_ceiling: TEXTURE_STRETCH_CEILING,
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. */
@@ -0,0 +1,104 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import type { AttachmentRest, Frame } from '@rig-c/core/render-shared';
4
+ import { gateThroughRigc, type Log } from './build.ts';
5
+ import {
6
+ DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, edgeBonesText, measureTextureStretch, officialRenderer, readSliderStretch, rigcRanClause,
7
+ sliderStretchBindings, sliderStretchLine, TEXTURE_STRETCH_CEILING, type RigcRunner, type SliderStretchProvider,
8
+ } from './check.ts';
9
+ import { failLine, PartsError } from './errors.ts';
10
+ import { IDLE_FPS } from './motion.ts';
11
+ import { rigJsonText } from './rig.ts';
12
+ import { readSceneForClipStretch } from './scene.ts';
13
+
14
+ const CODE = 'CHECK_CLIP_STRETCH';
15
+
16
+ /** Read one take using the same Parts metric as CHECK_TEXTURE_STRETCH. */
17
+ export function clipStretchReading(
18
+ take: string,
19
+ rest: readonly AttachmentRest[],
20
+ frames: readonly Frame[],
21
+ rig: Record<string, unknown>,
22
+ motion: Record<string, unknown>,
23
+ log: Log,
24
+ ): boolean {
25
+ const meshes = rest.filter(mesh => mesh.kind === 'mesh');
26
+ const poses = frames.map(({ index, attachments }) => {
27
+ if (attachments === undefined) throw new PartsError([{ code: CODE, object: take, detail: `frame ${index} has no attachment geometry` }]);
28
+ return { index, attachments };
29
+ });
30
+ const figures = measureTextureStretch(meshes, poses);
31
+ type Peak = NonNullable<(typeof figures)[number]['peak']>;
32
+ let worst: (Peak & { mesh: (typeof figures)[number]['mesh'] }) | undefined;
33
+ let failed = false;
34
+ for (const { mesh, peak } of figures) {
35
+ const first = mesh.degenerate[0];
36
+ if (first !== undefined) {
37
+ failed = true;
38
+ log(failLine({ code: CODE, object: take,
39
+ detail: `mesh ${JSON.stringify(mesh.slot)} attachment ${JSON.stringify(mesh.attachment)} has ${mesh.degenerate.length} rest edge(s) of length 0. First is triangle ${first.triangle}, edge ${first.edge.join('-')}, with no stretch ratio` }));
40
+ }
41
+ if (peak === null) continue;
42
+ if (worst === undefined || peak.raw > worst.raw) worst = { ...peak, mesh };
43
+ if (peak.exceeds) failed = true;
44
+ }
45
+ if (worst === undefined) {
46
+ if (!failed) log(` SKIP ${CODE}: ${take} — no sampled frame shows a measurable mesh triangle edge`);
47
+ return false;
48
+ }
49
+ const { at, raw, rounded, mesh } = worst;
50
+ const time = frames.find(frame => frame.index === at.frame)!.time;
51
+ const detail = `peak ${raw.toFixed(6)}x (gate ${rounded.toFixed(3)}x, limit ${TEXTURE_STRETCH_CEILING}x), ${frames.length} frame${frames.length === 1 ? '' : 's'} at ${IDLE_FPS} fps, ` +
52
+ `mesh ${JSON.stringify(mesh.slot)} attachment ${JSON.stringify(mesh.attachment)}, triangle ${at.triangle} (vertices ${at.vertices.join(' ')}), ` +
53
+ `edge ${at.edge.join('-')}, frame ${at.frame} at ${time.toFixed(6)} s; ${edgeBonesText(rig, motion, mesh.slot, mesh.attachment, at.edge)}`;
54
+ log(failed ? failLine({ code: CODE, object: take, detail }) : ` PASS ${CODE}: ${take} — ${detail}`);
55
+ return !failed;
56
+ }
57
+
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, provide?: SliderStretchProvider): boolean {
60
+ const mode = { pageEdges: DEFAULT_PAGE_EDGES, packShape: DEFAULT_PACK_SHAPE };
61
+ const { rig, motion, images, explicitlyPlayed } = readSceneForClipStretch(scene, mode);
62
+ const bindings = sliderStretchBindings({ ...rig });
63
+ const sliderClips = new Set(bindings.map(binding => binding.clip));
64
+ let passed = true;
65
+ const [gate] = gateThroughRigc(images, [['rig.json', rigJsonText(rig)], ['motion.json', rigJsonText(motion)]], rigc, scratch, mode, build => {
66
+ const api = officialRenderer();
67
+ const skeleton = join(build, 'skeleton.json');
68
+ const atlas = join(build, 'skeleton.atlas');
69
+ const sceneObject = `scene ${JSON.stringify(scene)}`;
70
+ let object = sceneObject;
71
+ try {
72
+ const candidate = api.loadCandidate({ skeletonText: readFileSync(skeleton, 'utf8'), atlasText: readFileSync(atlas, 'utf8'), atlasDir: build, label: sceneObject }, { skeleton, atlas }, undefined);
73
+ const sides = Object.keys(motion.animations).filter(name =>
74
+ name !== 'idle' && (!sliderClips.has(name) || explicitlyPlayed.has(name)));
75
+ for (const name of [...sides, 'idle']) {
76
+ object = `${name === 'idle' ? 'declared idle' : 'side clip'} ${JSON.stringify(name)}`;
77
+ const { value } = api.throughPoser(candidate.choice, poser => {
78
+ if (!poser.animations.some(animation => animation.name === name)) {
79
+ return { passed: false, lines: [` SKIP ${CODE}: ${object} — the gated model retained no animation by that name`] };
80
+ }
81
+ const setup = api.sampleSetupPose(poser, { geometry: true })[0];
82
+ const frames = api.sampleAnimation(poser, name, IDLE_FPS, { geometry: true });
83
+ const rest = poser.rest(undefined, [setup, ...frames].map(frame => frame.attachments ?? []));
84
+ const lines: string[] = [];
85
+ const passed = clipStretchReading(object, rest, frames, { ...rig }, { ...motion }, line => lines.push(line));
86
+ return { passed, lines };
87
+ });
88
+ for (const line of value.lines) log(line);
89
+ if (!value.passed) passed = false;
90
+ }
91
+ for (const row of readSliderStretch(build, bindings, provide)?.rows ?? []) {
92
+ log(sliderStretchLine(row));
93
+ if (row.status === 'FAIL') passed = false;
94
+ }
95
+ } catch (err) {
96
+ if (!(err instanceof api.CandidateAtlasError || err instanceof api.CandidatePairError || err instanceof api.CoreInputError ||
97
+ err instanceof api.PoserChoiceError || err instanceof api.SpineRuntimeError)) throw err;
98
+ throw new PartsError([{ code: CODE, object, detail: err.message }]);
99
+ }
100
+ });
101
+ if (gate.status !== 0) throw new PartsError([{ code: CODE, object: `scene ${JSON.stringify(scene)}`,
102
+ detail: `rigc ${gate.label} exited ${gate.status}${rigcRanClause(gate)}${gate.lines.length === 0 ? '' : `: ${gate.lines.map(line => line.trim()).join(' | ')}`}` }]);
103
+ return passed;
104
+ }