@rig-c/parts 2.43.0 → 2.45.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.
@@ -0,0 +1,198 @@
1
+ /** Scene-authored clips use final names and Core's motion parser and poser. */
2
+ import { CompileError } from '@rig-c/core/errors';
3
+ import { parseMotionSpec, type MotionSpec as CoreMotion } from '@rig-c/core/motion';
4
+ import { CoreInputError, poseRawAnimation, readModel, type RawPose } from '@rig-c/core/core';
5
+ import { PartsError, refuseIfAny, type Problem } from './errors.ts';
6
+ import type { MotionSpec } from './motion.ts';
7
+ import type { RigSpec } from './rig.ts';
8
+
9
+ export type SceneAnimations = CoreMotion['animations'];
10
+
11
+ /** Core owns shape, required numbers, key times and all target families. */
12
+ export function readSceneAnimations(raw: unknown, where: string): SceneAnimations {
13
+ try {
14
+ return parseMotionSpec({ spec: 'rigc-motion/1', archetype: 'scene', cut: 'scene', easings: {}, groups: {}, animations: raw }, where).animations;
15
+ } catch (err) {
16
+ if (!(err instanceof CompileError) || err.code === undefined) throw err;
17
+ throw new PartsError([{ code: err.code, object: 'scene.animations', detail: err.message }]);
18
+ }
19
+ }
20
+
21
+ /** Core slider source properties and the bone timeline channels that feed them. */
22
+ function sliderInputChannel(source: unknown, property: string): number | null {
23
+ switch (source) {
24
+ case 'rotate': return property === 'rotate' ? 0 : null;
25
+ case 'x': return property === 'translatex' || property === 'translate' ? 0 : null;
26
+ case 'y': return property === 'translatey' ? 0 : property === 'translate' ? 1 : null;
27
+ case 'scaleX': return property === 'scalex' || property === 'scale' ? 0 : null;
28
+ case 'scaleY': return property === 'scaley' ? 0 : property === 'scale' ? 1 : null;
29
+ case 'shearY': return property === 'sheary' ? 0 : property === 'shear' ? 1 : null;
30
+ default: return null; // Core names unsupported slider source properties at its gate.
31
+ }
32
+ }
33
+
34
+ /** Append timelines without changing existing idle payloads or character physics. */
35
+ export function mergeSceneAnimations(rig: RigSpec, motion: MotionSpec, clips: SceneAnimations): void {
36
+ const problems: Problem[] = [];
37
+ const animations = motion.animations as unknown as SceneAnimations;
38
+ for (const [name, clip] of Object.entries(clips)) {
39
+ const existing = Object.hasOwn(animations, name) ? animations[name] : undefined;
40
+ if (existing !== undefined && name !== 'idle') {
41
+ problems.push({ code: 'SCENE_ANIMATION_NAME_FREE', object: `scene.animations.${name}`, detail: `already names an imported animation; only idle may be extended` });
42
+ continue;
43
+ }
44
+ if (existing !== undefined && clip.duration !== existing.duration) {
45
+ problems.push({ code: 'SCENE_DURATION_AGREES', object: `scene.animations.${name}.duration`, detail: `is ${clip.duration}; composed idle declares ${existing.duration}; equal durations are required, without retiming` });
46
+ continue;
47
+ }
48
+ // Bounds belong to the actual final slider, never to a guessed dial-name list.
49
+ // `from` is the declared bottom and `max` the editor's declared top (Core's RigSliderConstraint).
50
+ for (const track of clip.tracks) {
51
+ if (track.group !== undefined && (!Object.hasOwn(motion.groups, track.group) || !Array.isArray(motion.groups[track.group]))) {
52
+ problems.push({ code: 'CE_COMPILE_ANIMATION_GROUP_UNKNOWN', object: `scene.animations.${name}`,
53
+ detail: `animation "${name}": unknown group "${track.group}"; an own declared group is required` });
54
+ continue;
55
+ }
56
+ const targets = track.bone === undefined ? (track.group === undefined ? [] : motion.groups[track.group]) : [track.bone];
57
+ for (const bone of targets) for (const slider of rig.constraints ?? []) {
58
+ if (slider.type !== 'slider' || slider.bone !== bone) continue;
59
+ const channel = sliderInputChannel(slider.property, track.property);
60
+ if (channel === null) continue;
61
+ const from = slider.from, max = slider.max;
62
+ if (typeof from !== 'number' || !Number.isFinite(from) || typeof max !== 'number' || !Number.isFinite(max) || from > max) {
63
+ problems.push({ code: 'SCENE_DIAL_RANGE_DECLARED', object: `scene.animations.${name} bone "${bone}" slider "${String(slider.name)}"`, detail: `has no readable declared range: from ${String(from)}, max ${String(max)}; declare both bounds before keying this dial` });
64
+ continue;
65
+ }
66
+ for (const key of track.keys) {
67
+ if (key.derive !== undefined) {
68
+ problems.push({ code: 'SCENE_DIAL_KEY_DECLARED', object: `scene.animations.${name} bone "${bone}" slider "${String(slider.name)}" key t=${key.t}`,
69
+ detail: `uses derive on the slider's ${String(slider.property)} input; declare an explicit numeric v in [${from}, ${max}] so its own bounds can be checked` });
70
+ continue;
71
+ }
72
+ const value = key.v !== null && typeof key.v === 'object' && !Array.isArray(key.v) ? key.v[bone] : key.v;
73
+ if (!Array.isArray(value)) continue; // Core refuses missing/malformed values; derived slider inputs were refused above.
74
+ const v = value[channel];
75
+ if (typeof v === 'number' && (v < from || v > max)) problems.push({
76
+ code: 'SCENE_DIAL_KEY_RANGE', object: `scene.animations.${name} bone "${bone}" slider "${String(slider.name)}" key t=${key.t}`,
77
+ detail: `value ${v} is outside declared range [${from}, ${max}]`,
78
+ });
79
+ }
80
+ }
81
+ }
82
+ if (existing === undefined) Object.defineProperty(animations, name, { value: structuredClone(clip), enumerable: true, configurable: true, writable: true });
83
+ else {
84
+ // Core rejects overlapping property claims after expansion, including group/bone collisions.
85
+ // Keep the existing idle metadata; every timeline collection is appended in producer order.
86
+ for (const field of ['tracks', 'deform', 'ik', 'transform', 'sequence', 'events', 'drawOrder'] as const) {
87
+ const added = clip[field];
88
+ if (added !== undefined) Object.assign(existing, { [field]: [...(existing[field] ?? []), ...structuredClone(added)] });
89
+ }
90
+ }
91
+ }
92
+ refuseIfAny(problems);
93
+ }
94
+
95
+ /** Add character context to Core's existing unknown-bone sentence, without changing its code. */
96
+ export function sceneBoneContext(line: string, ids: readonly string[]): string {
97
+ const bone = /keys unknown bone "([^"]+)"/.exec(line)?.[1];
98
+ const id = bone === undefined ? undefined : ids.find(id => bone.startsWith(`${id}:`));
99
+ return id === undefined ? line : `${line}; character "${id}" declares no bone "${bone}"`;
100
+ }
101
+
102
+ /** Time and fired events are not pose state. Geometry includes alpha, deforms and invisible bones. */
103
+ export function scenePoseState(pose: RawPose): string {
104
+ return JSON.stringify({ bones: pose.bones, slots: pose.slots, drawOrder: pose.drawOrder, drawn: pose.drawn, clips: pose.clips, clipped: pose.clipped });
105
+ }
106
+
107
+ interface PoseDifference {
108
+ path: Array<string | number>;
109
+ start: unknown;
110
+ end: unknown;
111
+ }
112
+
113
+ /** Walk the same JSON values the closure gate compares, in producer field/array order.
114
+ * No rounding or epsilon: the existing numeric tolerance is exactly zero.
115
+ */
116
+ function firstPoseDifference(start: unknown, end: unknown, path: Array<string | number> = []): PoseDifference | null {
117
+ if (JSON.stringify(start) === JSON.stringify(end)) return null;
118
+ if (Array.isArray(start) && Array.isArray(end)) {
119
+ for (let i = 0; i < Math.max(start.length, end.length); i++) {
120
+ const difference = firstPoseDifference(start[i], end[i], [...path, i]);
121
+ if (difference !== null) return difference;
122
+ }
123
+ } else if (start !== null && end !== null && typeof start === 'object' && typeof end === 'object') {
124
+ const a = start as Record<string, unknown>, b = end as Record<string, unknown>;
125
+ for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
126
+ const difference = firstPoseDifference(a[key], b[key], [...path, key]);
127
+ if (difference !== null) return difference;
128
+ }
129
+ }
130
+ return { path, start, end };
131
+ }
132
+
133
+ /** Name geometry-only differences too, including invisible slots and clipping. */
134
+ function poseDifferenceDetail(start: RawPose, end: RawPose): string {
135
+ const difference = firstPoseDifference(JSON.parse(scenePoseState(start)), JSON.parse(scenePoseState(end)));
136
+ if (difference === null) return 'endpoint sample clocks differ';
137
+ const [family, index, ...fields] = difference.path;
138
+ const i = typeof index === 'number' ? index : -1;
139
+ let object = 'pose', channel = difference.path.map(String).join('.');
140
+ if (family === 'bones') {
141
+ object = `bone ${JSON.stringify(start.bones[i]?.name ?? end.bones[i]?.name)}`;
142
+ channel = fields.map(String).join('.') || 'presence';
143
+ } else if (family === 'slots') {
144
+ object = `slot ${JSON.stringify(start.slots[i]?.[0] ?? end.slots[i]?.[0])}`;
145
+ const [field, ...rest] = fields;
146
+ const channels = ['name', 'attachment', 'r', 'g', 'b', 'a', 'dark', 'path', 'blend'];
147
+ channel = [typeof field === 'number' ? channels[field] : 'presence', ...rest].join('.');
148
+ } else if (family === 'drawOrder') {
149
+ object = `slot ${JSON.stringify(start.drawOrder[i] ?? end.drawOrder[i])}`;
150
+ channel = `drawOrder[${i}]`;
151
+ } else if (family === 'drawn' || family === 'clips' || family === 'clipped') {
152
+ const a = start[family][i], b = end[family][i];
153
+ const slot = (row: typeof a) => row === undefined ? undefined : Array.isArray(row) ? row[0] : row.slot;
154
+ object = `slot ${JSON.stringify(slot(a) ?? slot(b))}`;
155
+ channel = `${family}.${fields.map(String).join('.') || 'presence'}`;
156
+ }
157
+ const value = (v: unknown) => v === undefined ? 'absent' : JSON.stringify(v);
158
+ return `${object} channel ${channel}: start ${value(difference.start)} at t=0; end ${value(difference.end)} at t=${end.trackTime}; tolerance 0 (exact equality)`;
159
+ }
160
+
161
+ /** A throwaway keyed-pose view; simulation is retained in the emitted document. */
162
+ export function sceneKeyedModel(modelText: string) {
163
+ const raw = JSON.parse(modelText) as Record<string, unknown>;
164
+ // Remove simulation only from the read view, retaining all non-physics constraints and timelines.
165
+ const constraints = raw.constraints as Array<{ kind: string; name: string }>;
166
+ const physics = constraints.filter(c => c.kind === 'physics').map(c => c.name);
167
+ raw.constraints = constraints.filter(c => c.kind !== 'physics');
168
+ for (const skin of raw.skins as Array<{ constraints?: Record<string, unknown> }>) if (skin.constraints !== undefined) skin.constraints = { ...skin.constraints, physics: [] };
169
+ for (const animation of Object.values(raw.animations as Record<string, { constraints: Record<string, unknown> }>)) animation.constraints = { ...animation.constraints, physics: [] };
170
+ const doc = readModel(JSON.stringify(raw), 'composed scene model');
171
+ return { doc, physics };
172
+ }
173
+
174
+ /** Measure the actual gated poses at both endpoints, without wrapping duration to zero.
175
+ * Physics is omitted only from this observation, as in check's keyed-loop bar;
176
+ * the gated/emitted motion and physics constraints are never edited.
177
+ */
178
+ export function sceneClipLoopProblems(modelText: string, clips: SceneAnimations): Problem[] {
179
+ try {
180
+ const { doc, physics } = sceneKeyedModel(modelText);
181
+ const problems: Problem[] = [];
182
+ for (const [name, clip] of Object.entries(clips)) {
183
+ const poses = poseRawAnimation(doc, name, [clip.duration]);
184
+ if (poses.length !== 2 || poses[0].animationTime !== 0 || poses[1].trackTime !== clip.duration || scenePoseState(poses[0]) !== scenePoseState(poses[1])) {
185
+ const difference = poses.length !== 2
186
+ ? `pose sample count ${poses.length}; required 2 at t=0 and t=${clip.duration}`
187
+ : poses[0].animationTime !== 0 || poses[1].trackTime !== clip.duration
188
+ ? `pose sample clocks start ${poses[0].animationTime}, end ${poses[1].trackTime}; required 0 and ${clip.duration}; tolerance 0 (exact equality)`
189
+ : poseDifferenceDetail(poses[0], poses[1]);
190
+ problems.push({ code: 'SCENE_ANIMATION_LOOP_CLOSES', object: `scene.animations.${name}`, detail: `${difference}; identical endpoint poses are required (physics left out: ${physics.join(', ') || 'none'})` });
191
+ }
192
+ }
193
+ return problems;
194
+ } catch (err) {
195
+ if (!(err instanceof CoreInputError)) throw err;
196
+ return [{ code: 'SCENE_ANIMATION_POSE_READABLE', object: 'scene.animations', detail: err.message }];
197
+ }
198
+ }
package/src/turn.ts CHANGED
@@ -28,6 +28,7 @@
28
28
  * that the depth maps do not carry relief inside a layer, so a part moves as
29
29
  * one piece. Pure: no file, no clock.
30
30
  */
31
+ import { boundaryDepthSamplers, type BoundaryDepths } from './boundarydepth.ts';
31
32
  import { computeWorldTransforms, setupToPaintingPoint, toBoneLocalVector, toWorld, type BoneTransform } from './coords.ts';
32
33
  import { extendDepthSilhouette, sampleDepthFloat, type PartDepthReference } from './depthsheets.ts';
33
34
  import { type Problem, refuseIfAny } from './errors.ts';
@@ -265,6 +266,7 @@ export interface TurnBodySpec {
265
266
  counter?: number;
266
267
  grid?: [number, number] | Record<string, [number, number]>;
267
268
  unitDepths?: Record<string, number>;
269
+ boundaryDepths?: BoundaryDepths;
268
270
  }
269
271
 
270
272
  /** `config.turn`: either the legacy `{ pivot, depths }` turn spec or the 2.5D depth-sampled `{ roles, body?, pivot?, counter?, grid?, unitDepths?, band? }` spec (#763, #787). */
@@ -276,6 +278,7 @@ export interface TurnSpec {
276
278
  counter?: number;
277
279
  grid?: [number, number] | Record<string, [number, number]>;
278
280
  unitDepths?: Record<string, number>;
281
+ boundaryDepths?: BoundaryDepths;
279
282
  head?: { pivot?: number; radius?: number };
280
283
  surface?: { radius?: number };
281
284
  radius?: number;
@@ -1516,6 +1519,7 @@ interface Depth25DGroupSpec {
1516
1519
  pivot: number;
1517
1520
  counter: number;
1518
1521
  unitDepths?: Record<string, number>;
1522
+ boundaryDepths?: BoundaryDepths;
1519
1523
  carrierBone: string;
1520
1524
  rearCarrierBone: string;
1521
1525
  unitGroupName: string;
@@ -1629,6 +1633,11 @@ function buildDepth25DTurnGroup(
1629
1633
  if (primarySurface !== undefined) {
1630
1634
  for (const sheet of surfaceSheets.values()) sheet.zRef = primarySurface.zRef;
1631
1635
  }
1636
+ // Resolve on original sheets AFTER choosing the original shared anchor.
1637
+ const boundary = boundaryDepthSamplers(group.boundaryDepths, opts.parts, opts.images, group.roles, group.fieldPrefix);
1638
+ problems.push(...boundary.problems);
1639
+ if (problems.length > startProblems) return;
1640
+ const boundarySamples = boundary.samplers;
1632
1641
  const pivot = pyRound(group.pivot, 4);
1633
1642
  const counter = group.counter;
1634
1643
  const rearDepth = pyRound(-counter * pivot, 4);
@@ -1865,7 +1874,14 @@ function buildDepth25DTurnGroup(
1865
1874
  }>;
1866
1875
  }> = [];
1867
1876
  for (const [part, { rec, ext, zRef }] of surfaceSheets) {
1877
+ const boundarySample = boundarySamples.get(part);
1868
1878
  const authored = opts.surfaceMeshes?.filter((m) => m.part === part) ?? [];
1879
+ // Core grids already expose their exact topology as neighbour support.
1880
+ // Only an opted-in grid needs explicit offsets; legacy transforms stay intact.
1881
+ if (boundarySample !== undefined && authored.length === 0) {
1882
+ authored.push(...(opts.neighbourMeshes?.filter(m => m.part === part && m.gridSamples !== undefined) ?? []));
1883
+ if (authored.length === 0) problems.push({ code: 'RIG_TURN_BOUNDARY_DEPTH', object: `${group.fieldPrefix}.boundaryDepths.${part}`, detail: 'has no resolved grid sampling topology; supply the generated grid support' });
1884
+ }
1869
1885
  if (authored.length > 0) {
1870
1886
  const setup = surfaceSetupGraph(rig);
1871
1887
  const world = computeWorldTransforms(setup.bones);
@@ -1884,7 +1900,7 @@ function buildDepth25DTurnGroup(
1884
1900
  }
1885
1901
  // A unit/rear mesh sharing this root would move our bindings too.
1886
1902
  let ancestor = setup.bones.find((b) => b.name === setup.resolve(w.bone));
1887
- while (ancestor !== undefined) {
1903
+ while (ancestor !== undefined && mesh.gridSamples === undefined) {
1888
1904
  if ([FACESHIFT_BONE, REAR_SHIFT_BONE, BODYSHIFT_BONE, BODY_REAR_SHIFT_BONE].includes(ancestor.name)) {
1889
1905
  problems.push({ code: 'RIG_TURN_SURFACE_MESH_BINDINGS', object: `${group.fieldPrefix}.roles.${part}`, detail: `binds "${w.bone}" through turn carrier "${ancestor.name}" shared with another role; surface mesh bindings must retain their authored frame` });
1890
1906
  break;
@@ -1898,8 +1914,11 @@ function buildDepth25DTurnGroup(
1898
1914
  problems.push({ code: 'RIG_TURN_SURFACE_MESH_BINDINGS', object: `surface mesh "${mesh.slot}/${mesh.attachment}" vertex ${index}`, detail: `has influence sum ${total}; weights closing at 1 are required to sample a setup position` });
1899
1915
  }
1900
1916
  const [cx, cy] = setupToPaintingPoint([wx, wy], mesh.canvas, mesh.canvas);
1901
- const z = levelToDepthZ(sampleDepthFloat(ext, cx - rec.x, cy - rec.y), rec.depth);
1902
- return { row, depth: pivot + z - zRef };
1917
+ const point = mesh.gridSamples?.[index] ?? [cx, cy];
1918
+ const level = boundarySample?.(point[0], point[1]) ?? sampleDepthFloat(ext, point[0] - rec.x, point[1] - rec.y);
1919
+ const z = levelToDepthZ(level, rec.depth);
1920
+ // Grid carrier tracks already contribute pivot-zRef once.
1921
+ return { row, depth: mesh.gridSamples === undefined ? pivot + z - zRef : z };
1903
1922
  });
1904
1923
  if (problems.length > startProblems || !active) continue;
1905
1924
  deform.push({
@@ -2183,6 +2202,7 @@ export function buildDepth25DTurn(
2183
2202
  pivot: opts.turn.pivot ?? DEFAULT_TURN_PIVOT_25D,
2184
2203
  counter: opts.turn.counter ?? DEFAULT_TURN_COUNTER_25D,
2185
2204
  unitDepths: opts.turn.unitDepths,
2205
+ boundaryDepths: opts.turn.boundaryDepths,
2186
2206
  carrierBone: FACESHIFT_BONE,
2187
2207
  rearCarrierBone: REAR_SHIFT_BONE,
2188
2208
  unitGroupName: 'turn_units',
@@ -2210,6 +2230,7 @@ export function buildDepth25DTurn(
2210
2230
  pivot: body.pivot ?? opts.turn.pivot ?? DEFAULT_TURN_PIVOT_25D,
2211
2231
  counter: body.counter ?? opts.turn.counter ?? DEFAULT_TURN_COUNTER_25D,
2212
2232
  unitDepths: body.unitDepths ?? opts.turn.unitDepths,
2233
+ boundaryDepths: body.boundaryDepths,
2213
2234
  carrierBone: BODYSHIFT_BONE,
2214
2235
  rearCarrierBone: BODY_REAR_SHIFT_BONE,
2215
2236
  unitGroupName: 'body_turn_units',
@@ -4,6 +4,7 @@ import { readFileSync } from 'node:fs';
4
4
  import { dirname, relative, resolve } from 'node:path';
5
5
  import { parseConfig } from '../src/config.ts';
6
6
  import type { EditedPartReceipt } from '../src/editedparts.ts';
7
+ import { receiptProducerJson } from '../src/receiptproducer.ts';
7
8
  import { PartsError } from '../src/errors.ts';
8
9
  import { decodePngBytes } from '../src/raster/png.ts';
9
10
  import { readConfigWriteTarget, stageConfigWriteBatch, type StagedConfigWriteBatch } from './configwrite.ts';
@@ -14,7 +15,8 @@ export interface EditedPartInput {
14
15
  part: string;
15
16
  file: string;
16
17
  from: string;
17
- editor: string;
18
+ editor?: string;
19
+ producer?: string;
18
20
  }
19
21
  function refuse(code: string, object: string, detail: string): never {
20
22
  throw new PartsError([{ code, object, detail }]);
@@ -37,13 +39,20 @@ export interface EditedPartWriteResult { receipt: EditedPartReceipt; writes: Sta
37
39
  export function writeEditedPart(input: EditedPartInput): EditedPartWriteResult {
38
40
  for (const [flag, value] of [
39
41
  ['--config', input.config], ['--part', input.part], ['--file', input.file],
40
- ['--from', input.from], ['--editor', input.editor],
42
+ ['--from', input.from],
43
+ ...(input.editor === undefined ? [] : [['--editor', input.editor]]),
41
44
  ...(input.rigConfig === undefined ? [] : [['--rig-config', input.rigConfig]]),
42
45
  ]) if (typeof value !== 'string' || value.trim() === '') refuse('EDITED_PART_ARGUMENT', flag, 'is missing or blank; a non-empty value is required');
46
+ if ((input.editor === undefined) === (input.producer === undefined)) {
47
+ refuse('EDITED_PART_ARGUMENT', 'edited-part', 'requires exactly one of --producer or --editor');
48
+ }
49
+ const author = input.editor === undefined
50
+ ? { producer: receiptProducerJson(input.producer!, '--producer') }
51
+ : { editor: input.editor };
43
52
  const edited = png(input.file, '--file'), from = png(input.from, '--from');
44
53
  if (edited.width !== from.width || edited.height !== from.height) refuse('EDITED_PART_SIZE', input.part,
45
54
  `edited PNG is ${edited.width}x${edited.height}; --from PNG dimensions ${from.width}x${from.height} are required`);
46
- const receipt = { part: input.part, file: input.file, sha256: hash(edited.bytes), from_sha256: hash(from.bytes), editor: input.editor };
55
+ const receipt = { part: input.part, file: input.file, sha256: hash(edited.bytes), from_sha256: hash(from.bytes), ...author };
47
56
  const targets = [input.config, ...(input.rigConfig === undefined ? [] : [input.rigConfig])].map(readConfigWriteTarget);
48
57
  const receipts: EditedPartReceipt[] = [];
49
58
  const requests = targets.map(target => {