@haiyue/animation-spec 0.1.0 → 0.2.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.
Files changed (77) hide show
  1. package/README.md +40 -6
  2. package/SPECIFICATION.md +12 -2
  3. package/bin/hya-live2d-convert.mjs +76 -0
  4. package/bin/{hya-convert.mjs → hya-lottie-convert.mjs} +1 -1
  5. package/dist/chunks/binary-DvuTJ_hy.js +1 -0
  6. package/dist/chunks/clip-baked-Dv-wjX9d.js +1 -0
  7. package/dist/chunks/errors-Bzs3GOD9.js +1 -0
  8. package/dist/chunks/expression-D1cKtNwM.js +1 -0
  9. package/dist/chunks/extensions-DxL4AxOC.js +1 -0
  10. package/dist/conversion.d.ts +1 -0
  11. package/dist/conversion.js +1 -0
  12. package/dist/cubism.d.ts +1 -0
  13. package/dist/cubism.js +1 -0
  14. package/dist/deformable2d.d.ts +1 -0
  15. package/dist/deformable2d.js +1 -0
  16. package/dist/index.d.ts +1 -10
  17. package/dist/index.js +1 -2927
  18. package/dist/live2d/clip-baked.d.ts +1 -0
  19. package/dist/live2d/clip-baked.js +1 -0
  20. package/dist/live2d.d.ts +1 -0
  21. package/dist/live2d.js +1 -0
  22. package/dist/lottie.d.ts +1 -62
  23. package/dist/lottie.js +1 -2642
  24. package/dist/native3d.d.ts +1 -2
  25. package/dist/native3d.js +1 -907
  26. package/dist/shared.d.ts +1493 -0
  27. package/package.json +30 -10
  28. package/schema/animation.schema.json +92 -0
  29. package/schema/deformable-mesh-2d-extension.schema.json +18 -0
  30. package/schema/deformable-mesh-2d.contract.json +58 -0
  31. package/schema/parameterized-rig-2d.contract.json +63 -0
  32. package/schema/parameterized-rig-2d.schema.json +57 -0
  33. package/schema/parameterized-rig-census-map.json +128 -0
  34. package/schema/responsive-layout-2d-census-map.json +49 -0
  35. package/schema/responsive-layout-2d.contract.json +58 -0
  36. package/schema/responsive-layout-2d.schema.json +34 -0
  37. package/schema/state-machine-v2-census-map.json +1 -0
  38. package/schema/state-machine-v2.contract.json +66 -0
  39. package/schema/state-machine-v2.schema.json +55 -0
  40. package/schema/vector-visual-census-map.json +120 -0
  41. package/schema/vector-visual.contract.json +47 -0
  42. package/schema/vector-visual.schema.json +72 -0
  43. package/dist/binary.d.ts +0 -7
  44. package/dist/chunks/types-l6nBVYwx.js +0 -8
  45. package/dist/chunks/types-l6nBVYwx.js.map +0 -1
  46. package/dist/errors.d.ts +0 -7
  47. package/dist/extensions.d.ts +0 -19
  48. package/dist/index.js.map +0 -1
  49. package/dist/lottie-merge-path.d.ts +0 -11
  50. package/dist/lottie.js.map +0 -1
  51. package/dist/native3d/Animation3DError.d.ts +0 -8
  52. package/dist/native3d/Animation3DParser.d.ts +0 -7
  53. package/dist/native3d/Animation3DTypes.d.ts +0 -285
  54. package/dist/native3d/index.d.ts +0 -5
  55. package/dist/native3d.js.map +0 -1
  56. package/dist/parser.d.ts +0 -2
  57. package/dist/state-machine.d.ts +0 -130
  58. package/dist/text-selector.d.ts +0 -2
  59. package/dist/types.d.ts +0 -419
  60. package/dist/validation.d.ts +0 -32
  61. package/src/binary.ts +0 -1441
  62. package/src/errors.ts +0 -18
  63. package/src/extensions.ts +0 -55
  64. package/src/index.ts +0 -90
  65. package/src/lottie-merge-path.ts +0 -204
  66. package/src/lottie.ts +0 -3073
  67. package/src/native3d/Animation3DError.ts +0 -20
  68. package/src/native3d/Animation3DParser.ts +0 -964
  69. package/src/native3d/Animation3DTypes.ts +0 -322
  70. package/src/native3d/index.ts +0 -14
  71. package/src/native3d.ts +0 -2
  72. package/src/parser.ts +0 -41
  73. package/src/state-machine.ts +0 -645
  74. package/src/text-selector.ts +0 -7
  75. package/src/types.ts +0 -483
  76. package/src/validation.ts +0 -1286
  77. package/test/fixtures/basic-lottie.json +0 -31
@@ -1,964 +0,0 @@
1
- import { AnimationExtensionRegistry } from '../extensions';
2
- import type { AnimationExtensionHandler } from '../extensions';
3
- import { parseAnimation } from '../parser';
4
- import type { AnimationParseOptions, AnimationResource, ParsedAnimation } from '../types';
5
- import { Native3DAnimationFormatError } from './Animation3DError';
6
- import {
7
- NATIVE_3D_ANIMATION_EXTENSION_ID,
8
- NATIVE_3D_ANIMATION_FORMAT,
9
- NATIVE_3D_CLIP_FORMAT,
10
- NATIVE_3D_STATE_MACHINE_FORMAT,
11
- type Native3DAnimationParseOptions,
12
- type Native3DAnimationPayload,
13
- type Native3DAnimationSource,
14
- type Native3DBinding,
15
- type Native3DBindingTarget,
16
- type Native3DCameraProjection,
17
- type Native3DClip,
18
- type Native3DComponent,
19
- type Native3DCoordinateSystem,
20
- type Native3DEvent,
21
- type Native3DMaterial,
22
- type Native3DNode,
23
- type Native3DParticleDescriptor,
24
- type Native3DScalarRange,
25
- type Native3DStateMachine,
26
- type Native3DStateMachineCondition,
27
- type Native3DStateMachineLayer,
28
- type Native3DStateMachineMotion,
29
- type Native3DStateMachineParameter,
30
- type Native3DStateMachineState,
31
- type Native3DStateMachineTransition,
32
- type Native3DTrack,
33
- type Native3DTransform,
34
- type Native3DVec2,
35
- type Native3DVec3,
36
- type Native3DVec4,
37
- type Native3DViewport,
38
- type ParsedNative3DAnimation,
39
- } from './Animation3DTypes';
40
-
41
- const EXTENSION_PATH = `$.extensions.${NATIVE_3D_ANIMATION_EXTENSION_ID}`;
42
- const MODEL_MIME_TYPES = new Set(['model/gltf-binary', 'model/gltf+json']);
43
- const FORBIDDEN_URI_SCHEMES = new Set(['blob', 'file', 'javascript']);
44
- const DEFAULT_LIMITS = Object.freeze({
45
- maxMaterials: 10_000,
46
- maxNodes: 100_000,
47
- maxComponents: 200_000,
48
- maxClips: 10_000,
49
- maxTracks: 200_000,
50
- maxKeyframes: 5_000_000,
51
- maxParticleCapacity: 2_000_000,
52
- maxStateMachineDepth: 64,
53
- });
54
-
55
- interface Limits {
56
- readonly maxMaterials: number;
57
- readonly maxNodes: number;
58
- readonly maxComponents: number;
59
- readonly maxClips: number;
60
- readonly maxTracks: number;
61
- readonly maxKeyframes: number;
62
- readonly maxParticleCapacity: number;
63
- readonly maxStateMachineDepth: number;
64
- }
65
-
66
- export function createNative3DAnimationExtensionHandler(
67
- options: Native3DAnimationParseOptions = {},
68
- onValidated?: (payload: Native3DAnimationPayload) => void,
69
- ): AnimationExtensionHandler {
70
- return Object.freeze({
71
- id: NATIVE_3D_ANIMATION_EXTENSION_ID,
72
- validateDocument(value: unknown): void {
73
- onValidated?.(parseNative3DAnimationPayload(value, options));
74
- },
75
- });
76
- }
77
-
78
- /** Parses the required 3D extension and rejects mixed 2D/3D carriers. */
79
- export function parseNative3DAnimation(
80
- source: Native3DAnimationSource,
81
- options: Native3DAnimationParseOptions = {},
82
- ): ParsedNative3DAnimation {
83
- const extensions = new AnimationExtensionRegistry();
84
- let payload: Native3DAnimationPayload | undefined;
85
- extensions.register(createNative3DAnimationExtensionHandler(options, value => { payload = value; }));
86
- const coreOptions: AnimationParseOptions = {
87
- ...pickCoreLimits(options),
88
- extensions,
89
- ...(options.copyFloatData === undefined ? {} : { copyFloatData: options.copyFloatData }),
90
- };
91
- const document = parseAnimation(source, coreOptions);
92
- if (!payload) {
93
- throw new Native3DAnimationFormatError(
94
- 'E_ANIMATION_3D_INVALID_PAYLOAD',
95
- `Required extension "${NATIVE_3D_ANIMATION_EXTENSION_ID}" has no document payload.`,
96
- EXTENSION_PATH,
97
- );
98
- }
99
- validateCarrier(document, payload);
100
- validateResourceReferences(document.resources, payload);
101
- return Object.freeze({ document, payload, resources: document.resources });
102
- }
103
-
104
- /** Validates and canonicalizes the extension before any runtime allocation. */
105
- export function parseNative3DAnimationPayload(
106
- value: unknown,
107
- options: Native3DAnimationParseOptions = {},
108
- ): Native3DAnimationPayload {
109
- const limits = resolveLimits(options);
110
- const root = object(value, EXTENSION_PATH, [
111
- 'format', 'mode', 'coordinateSystem', 'viewport', 'materials', 'nodes', 'clips',
112
- ], ['format', 'mode', 'coordinateSystem', 'viewport', 'materials', 'nodes', 'clips', 'stateMachine']);
113
- exact(root.format, NATIVE_3D_ANIMATION_FORMAT, `${EXTENSION_PATH}.format`);
114
- exact(root.mode, 'native-3d', `${EXTENSION_PATH}.mode`);
115
- const coordinateSystem = parseCoordinateSystem(root.coordinateSystem, `${EXTENSION_PATH}.coordinateSystem`);
116
- const viewport = parseViewport(root.viewport, `${EXTENSION_PATH}.viewport`);
117
-
118
- const materialValues = array(root.materials, `${EXTENSION_PATH}.materials`);
119
- budget(materialValues.length, limits.maxMaterials, 'materials', `${EXTENSION_PATH}.materials`);
120
- const materialIds = new Set<string>();
121
- const materials = materialValues.map((entry, index) => {
122
- const material = parseMaterial(entry, `${EXTENSION_PATH}.materials[${index}]`);
123
- unique(materialIds, material.id, `${EXTENSION_PATH}.materials[${index}].id`, 'material');
124
- return material;
125
- });
126
-
127
- const nodeValues = array(root.nodes, `${EXTENSION_PATH}.nodes`);
128
- budget(nodeValues.length, limits.maxNodes, 'nodes', `${EXTENSION_PATH}.nodes`);
129
- const nodeIds = new Set<string>();
130
- const componentIds = new Set<string>();
131
- let componentCount = 0;
132
- let particleCapacity = 0;
133
- const nodes = nodeValues.map((entry, index) => {
134
- const path = `${EXTENSION_PATH}.nodes[${index}]`;
135
- const node = parseNode(entry, path);
136
- unique(nodeIds, node.id, `${path}.id`, 'node');
137
- for (let componentIndex = 0; componentIndex < node.components.length; componentIndex++) {
138
- const component = node.components[componentIndex]!;
139
- unique(componentIds, component.id, `${path}.components[${componentIndex}].id`, 'component');
140
- componentCount++;
141
- if (component.kind === 'particle3d') particleCapacity += component.descriptor.maxParticles;
142
- }
143
- budget(componentCount, limits.maxComponents, 'components', `${path}.components`);
144
- budget(particleCapacity, limits.maxParticleCapacity, 'particle capacity', `${path}.components`);
145
- return node;
146
- });
147
- validateNodeSemantics(nodes, nodeIds, materialIds);
148
-
149
- const clipValues = array(root.clips, `${EXTENSION_PATH}.clips`);
150
- budget(clipValues.length, limits.maxClips, 'clips', `${EXTENSION_PATH}.clips`);
151
- const clipIds = new Set<string>();
152
- const bindingIds = new Set<string>();
153
- let trackCount = 0;
154
- let keyframeCount = 0;
155
- const clips = clipValues.map((entry, index) => {
156
- const path = `${EXTENSION_PATH}.clips[${index}]`;
157
- const clip = parseClip(entry, path);
158
- unique(clipIds, clip.id, `${path}.id`, 'clip');
159
- trackCount += clip.tracks.length;
160
- keyframeCount += clip.tracks.reduce((sum, track) => sum + track.times.length, 0);
161
- budget(trackCount, limits.maxTracks, 'tracks', `${path}.tracks`);
162
- budget(keyframeCount, limits.maxKeyframes, 'keyframes', `${path}.tracks`);
163
- const clipBindingIds = new Set<string>();
164
- for (let trackIndex = 0; trackIndex < clip.tracks.length; trackIndex++) {
165
- const track = clip.tracks[trackIndex]!;
166
- unique(clipBindingIds, track.binding.id, `${path}.tracks[${trackIndex}].binding.id`, 'binding');
167
- bindingIds.add(track.binding.id);
168
- validateBindingTarget(track.binding, nodes, materialIds, `${path}.tracks[${trackIndex}].binding`);
169
- }
170
- return clip;
171
- });
172
-
173
- const stateMachine = root.stateMachine === undefined || root.stateMachine === null
174
- ? root.stateMachine as undefined | null
175
- : parseStateMachine(root.stateMachine, `${EXTENSION_PATH}.stateMachine`, limits.maxStateMachineDepth);
176
- if (stateMachine) validateStateMachineReferences(stateMachine, clipIds, bindingIds, `${EXTENSION_PATH}.stateMachine`);
177
-
178
- return deepFreeze({
179
- format: NATIVE_3D_ANIMATION_FORMAT,
180
- mode: 'native-3d',
181
- coordinateSystem,
182
- viewport,
183
- materials,
184
- nodes,
185
- clips,
186
- ...(root.stateMachine === undefined ? {} : { stateMachine: stateMachine ?? null }),
187
- });
188
- }
189
-
190
- function parseCoordinateSystem(value: unknown, path: string): Native3DCoordinateSystem {
191
- const item = object(value, path,
192
- ['handedness', 'upAxis', 'forwardAxis', 'unit', 'angles', 'rotationStorage'],
193
- ['handedness', 'upAxis', 'forwardAxis', 'unit', 'angles', 'rotationStorage']);
194
- exact(item.handedness, 'right', `${path}.handedness`);
195
- exact(item.upAxis, '+y', `${path}.upAxis`);
196
- exact(item.forwardAxis, '-z', `${path}.forwardAxis`);
197
- exact(item.unit, 'meter', `${path}.unit`);
198
- exact(item.angles, 'radian', `${path}.angles`);
199
- exact(item.rotationStorage, 'normalized-xyzw-quaternion', `${path}.rotationStorage`);
200
- return Object.freeze({
201
- handedness: 'right', upAxis: '+y', forwardAxis: '-z', unit: 'meter', angles: 'radian',
202
- rotationStorage: 'normalized-xyzw-quaternion',
203
- });
204
- }
205
-
206
- function parseViewport(value: unknown, path: string): Native3DViewport {
207
- const item = object(value, path, ['width', 'height'], ['width', 'height']);
208
- return Object.freeze({ width: positive(item.width, `${path}.width`), height: positive(item.height, `${path}.height`) });
209
- }
210
-
211
- function parseMaterial(value: unknown, path: string): Native3DMaterial {
212
- const item = object(value, path,
213
- ['id', 'name', 'baseColorFactor', 'metallicFactor', 'roughnessFactor', 'emissiveFactor', 'alphaMode', 'doubleSided'],
214
- ['id', 'name', 'baseColorFactor', 'metallicFactor', 'roughnessFactor', 'emissiveFactor', 'alphaMode', 'alphaCutoff', 'doubleSided', 'baseColorTexture', 'normalTexture', 'metallicRoughnessTexture', 'emissiveTexture']);
215
- return Object.freeze({
216
- id: nonEmpty(item.id, `${path}.id`),
217
- name: string(item.name, `${path}.name`),
218
- baseColorFactor: vec4(item.baseColorFactor, `${path}.baseColorFactor`, 0, 1),
219
- metallicFactor: bounded(item.metallicFactor, `${path}.metallicFactor`, 0, 1),
220
- roughnessFactor: bounded(item.roughnessFactor, `${path}.roughnessFactor`, 0, 1),
221
- emissiveFactor: vec3(item.emissiveFactor, `${path}.emissiveFactor`, 0),
222
- alphaMode: enumeration(item.alphaMode, ['opaque', 'mask', 'blend'] as const, `${path}.alphaMode`),
223
- ...(item.alphaCutoff === undefined ? {} : { alphaCutoff: bounded(item.alphaCutoff, `${path}.alphaCutoff`, 0, 1) }),
224
- doubleSided: boolean(item.doubleSided, `${path}.doubleSided`),
225
- ...optionalStrings(item, path, ['baseColorTexture', 'normalTexture', 'metallicRoughnessTexture', 'emissiveTexture']),
226
- });
227
- }
228
-
229
- function parseNode(value: unknown, path: string): Native3DNode {
230
- const item = object(value, path, ['id', 'name', 'transform', 'components'],
231
- ['id', 'name', 'parent', 'start', 'duration', 'transform', 'components']);
232
- const components = array(item.components, `${path}.components`).map((entry, index) => (
233
- parseComponent(entry, `${path}.components[${index}]`)
234
- ));
235
- return Object.freeze({
236
- id: nonEmpty(item.id, `${path}.id`),
237
- name: string(item.name, `${path}.name`),
238
- ...(item.parent === undefined ? {} : { parent: nonEmpty(item.parent, `${path}.parent`) }),
239
- ...(item.start === undefined ? {} : { start: nonNegative(item.start, `${path}.start`) }),
240
- ...(item.duration === undefined ? {} : { duration: positive(item.duration, `${path}.duration`) }),
241
- transform: parseTransform(item.transform, `${path}.transform`),
242
- components: Object.freeze(components),
243
- });
244
- }
245
-
246
- function parseTransform(value: unknown, path: string): Native3DTransform {
247
- const item = object(value, path, ['translation', 'rotation', 'scale'], ['translation', 'rotation', 'scale']);
248
- const rotation = vec4(item.rotation, `${path}.rotation`);
249
- assertNormalizedQuaternion(rotation, `${path}.rotation`);
250
- return Object.freeze({
251
- translation: vec3(item.translation, `${path}.translation`),
252
- rotation,
253
- scale: vec3(item.scale, `${path}.scale`),
254
- });
255
- }
256
-
257
- function parseComponent(value: unknown, path: string): Native3DComponent {
258
- const kind = object(value, path).kind;
259
- if (kind === 'camera3d') {
260
- const item = object(value, path, ['id', 'kind', 'projection'], ['id', 'kind', 'projection']);
261
- return Object.freeze({ id: nonEmpty(item.id, `${path}.id`), kind, projection: parseCamera(item.projection, `${path}.projection`) });
262
- }
263
- if (kind === 'primitive3d') {
264
- const item = object(value, path, ['id', 'kind', 'primitive', 'materialId'], ['id', 'kind', 'primitive', 'materialId']);
265
- return Object.freeze({
266
- id: nonEmpty(item.id, `${path}.id`), kind,
267
- primitive: enumeration(item.primitive, ['box', 'sphere', 'plane', 'cylinder', 'cone'] as const, `${path}.primitive`),
268
- materialId: nonEmpty(item.materialId, `${path}.materialId`),
269
- });
270
- }
271
- if (kind === 'model3d') {
272
- const item = object(value, path, ['id', 'kind', 'resource'], ['id', 'kind', 'resource', 'materialOverrides']);
273
- const materialOverrides = item.materialOverrides === undefined ? undefined : array(item.materialOverrides, `${path}.materialOverrides`).map((entry, index) => {
274
- const overridePath = `${path}.materialOverrides[${index}]`;
275
- const override = object(entry, overridePath, ['slot', 'materialId'], ['slot', 'materialId']);
276
- return Object.freeze({ slot: nonEmpty(override.slot, `${overridePath}.slot`), materialId: nonEmpty(override.materialId, `${overridePath}.materialId`) });
277
- });
278
- return Object.freeze({
279
- id: nonEmpty(item.id, `${path}.id`), kind, resource: nonEmpty(item.resource, `${path}.resource`),
280
- ...(materialOverrides ? { materialOverrides: Object.freeze(materialOverrides) } : {}),
281
- });
282
- }
283
- if (kind === 'particle3d') {
284
- const item = object(value, path, ['id', 'kind', 'descriptor'], ['id', 'kind', 'descriptor']);
285
- return Object.freeze({
286
- id: nonEmpty(item.id, `${path}.id`), kind,
287
- descriptor: parseParticle(item.descriptor, `${path}.descriptor`),
288
- });
289
- }
290
- invalid(`Unsupported component kind "${String(kind)}".`, `${path}.kind`, 'E_ANIMATION_3D_UNSUPPORTED_FEATURE');
291
- }
292
-
293
- function parseCamera(value: unknown, path: string): Native3DCameraProjection {
294
- const kind = object(value, path).kind;
295
- if (kind === 'perspective') {
296
- const item = object(value, path, ['kind', 'fovYRadians', 'near', 'far'], ['kind', 'fovYRadians', 'near', 'far']);
297
- const near = positive(item.near, `${path}.near`);
298
- const far = positive(item.far, `${path}.far`);
299
- if (far <= near) invalid('Camera far must be greater than near.', `${path}.far`);
300
- return Object.freeze({
301
- kind, fovYRadians: bounded(item.fovYRadians, `${path}.fovYRadians`, Number.MIN_VALUE, Math.PI, false), near, far,
302
- });
303
- }
304
- if (kind === 'orthographic') {
305
- const item = object(value, path, ['kind', 'orthoHeight', 'near', 'far'], ['kind', 'orthoHeight', 'near', 'far']);
306
- const near = nonNegative(item.near, `${path}.near`);
307
- const far = positive(item.far, `${path}.far`);
308
- if (far <= near) invalid('Camera far must be greater than near.', `${path}.far`);
309
- return Object.freeze({ kind, orthoHeight: positive(item.orthoHeight, `${path}.orthoHeight`), near, far });
310
- }
311
- invalid(`Unsupported camera projection "${String(kind)}".`, `${path}.kind`, 'E_ANIMATION_3D_UNSUPPORTED_FEATURE');
312
- }
313
-
314
- function parseParticle(value: unknown, path: string): Native3DParticleDescriptor {
315
- const required = ['maxParticles', 'emissionRate', 'burst', 'duration', 'loop', 'seed', 'lifetime', 'speed', 'direction', 'spread', 'gravity', 'startSize', 'endSize', 'rotation', 'angularVelocity', 'startColor', 'endColor', 'shape', 'blendMode', 'radial', 'opacity', 'depthTest', 'depthWrite', 'sortMode'];
316
- const item = object(value, path, required, [...required, 'shapeSize', 'shapeRadius', 'textureResource']);
317
- return Object.freeze({
318
- maxParticles: integer(item.maxParticles, `${path}.maxParticles`, 1, 1_000_000),
319
- emissionRate: nonNegative(item.emissionRate, `${path}.emissionRate`),
320
- burst: integer(item.burst, `${path}.burst`, 0, 1_000_000),
321
- duration: positive(item.duration, `${path}.duration`),
322
- loop: boolean(item.loop, `${path}.loop`),
323
- seed: integer(item.seed, `${path}.seed`, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER),
324
- lifetime: range(item.lifetime, `${path}.lifetime`, 0),
325
- speed: range(item.speed, `${path}.speed`),
326
- direction: vec3(item.direction, `${path}.direction`),
327
- spread: bounded(item.spread, `${path}.spread`, 0, Math.PI),
328
- gravity: vec3(item.gravity, `${path}.gravity`),
329
- startSize: range(item.startSize, `${path}.startSize`, 0),
330
- endSize: range(item.endSize, `${path}.endSize`, 0),
331
- rotation: range(item.rotation, `${path}.rotation`),
332
- angularVelocity: range(item.angularVelocity, `${path}.angularVelocity`),
333
- startColor: vec4(item.startColor, `${path}.startColor`, 0, 1),
334
- endColor: vec4(item.endColor, `${path}.endColor`, 0, 1),
335
- shape: enumeration(item.shape, ['point', 'box', 'sphere'] as const, `${path}.shape`),
336
- ...(item.shapeSize === undefined ? {} : { shapeSize: vec3(item.shapeSize, `${path}.shapeSize`, 0) }),
337
- ...(item.shapeRadius === undefined ? {} : { shapeRadius: nonNegative(item.shapeRadius, `${path}.shapeRadius`) }),
338
- blendMode: enumeration(item.blendMode, ['normal', 'additive'] as const, `${path}.blendMode`),
339
- ...(item.textureResource === undefined ? {} : { textureResource: nonEmpty(item.textureResource, `${path}.textureResource`) }),
340
- radial: boolean(item.radial, `${path}.radial`),
341
- opacity: bounded(item.opacity, `${path}.opacity`, 0, 1),
342
- depthTest: boolean(item.depthTest, `${path}.depthTest`),
343
- depthWrite: boolean(item.depthWrite, `${path}.depthWrite`),
344
- sortMode: enumeration(item.sortMode, ['none', 'back-to-front'] as const, `${path}.sortMode`),
345
- });
346
- }
347
-
348
- function parseClip(value: unknown, path: string): Native3DClip {
349
- const item = object(value, path, ['format', 'id', 'name', 'duration', 'tracks', 'events'], ['format', 'id', 'name', 'duration', 'tracks', 'events']);
350
- exact(item.format, NATIVE_3D_CLIP_FORMAT, `${path}.format`);
351
- const duration = positive(item.duration, `${path}.duration`);
352
- const trackIds = new Set<string>();
353
- const tracks = array(item.tracks, `${path}.tracks`).map((entry, index) => {
354
- const trackPath = `${path}.tracks[${index}]`;
355
- const track = parseTrack(entry, trackPath, duration);
356
- unique(trackIds, track.id, `${trackPath}.id`, 'track');
357
- return track;
358
- });
359
- const eventIds = new Set<string>();
360
- const events = array(item.events, `${path}.events`).map((entry, index) => {
361
- const eventPath = `${path}.events[${index}]`;
362
- const event = parseEvent(entry, eventPath, duration);
363
- unique(eventIds, event.id, `${eventPath}.id`, 'event');
364
- return event;
365
- });
366
- return Object.freeze({
367
- format: NATIVE_3D_CLIP_FORMAT,
368
- id: nonEmpty(item.id, `${path}.id`),
369
- name: string(item.name, `${path}.name`),
370
- duration,
371
- tracks: Object.freeze(tracks),
372
- events: Object.freeze(events),
373
- });
374
- }
375
-
376
- function parseTrack(value: unknown, path: string, duration: number): Native3DTrack {
377
- const item = object(value, path, ['id', 'binding', 'interpolation', 'times', 'values'], ['id', 'binding', 'interpolation', 'times', 'values']);
378
- const binding = parseBinding(item.binding, `${path}.binding`);
379
- const interpolation = enumeration(item.interpolation, ['step', 'linear', 'cubic-spline'] as const, `${path}.interpolation`);
380
- const times = numericArray(item.times, `${path}.times`, 1);
381
- for (let index = 0; index < times.length; index++) {
382
- const time = times[index]!;
383
- if (time < 0 || time > duration) invalid('Track time must lie within clip duration.', `${path}.times[${index}]`, 'E_ANIMATION_3D_BINDING_MISMATCH');
384
- if (index > 0 && time <= times[index - 1]!) invalid('Track times must be strictly increasing.', `${path}.times[${index}]`, 'E_ANIMATION_3D_BINDING_MISMATCH');
385
- }
386
- const values = numericArray(item.values, `${path}.values`, 1);
387
- const expected = times.length * binding.valueSize * (interpolation === 'cubic-spline' ? 3 : 1);
388
- if (values.length !== expected) {
389
- invalid(`Track values length ${values.length} does not match expected ${expected}.`, `${path}.values`, 'E_ANIMATION_3D_BINDING_MISMATCH');
390
- }
391
- if (binding.path === 'transform.rotation') validateTrackQuaternions(values, times.length, interpolation, `${path}.values`);
392
- return Object.freeze({ id: nonEmpty(item.id, `${path}.id`), binding, interpolation, times, values });
393
- }
394
-
395
- function parseBinding(value: unknown, path: string): Native3DBinding {
396
- const base = object(value, path);
397
- const target = parseBindingTarget(base.target, `${path}.target`);
398
- const id = nonEmpty(base.id, `${path}.id`);
399
- if (base.path === 'transform.translation' || base.path === 'transform.scale') {
400
- const item = object(value, path, ['id', 'target', 'path', 'valueType', 'valueSize'], ['id', 'target', 'path', 'valueType', 'valueSize']);
401
- exact(item.valueType, 'vec3', `${path}.valueType`);
402
- exact(item.valueSize, 3, `${path}.valueSize`, 'E_ANIMATION_3D_BINDING_MISMATCH');
403
- return Object.freeze({ id, target, path: base.path, valueType: 'vec3', valueSize: 3 });
404
- }
405
- if (base.path === 'transform.rotation') {
406
- const item = object(value, path, ['id', 'target', 'path', 'valueType', 'valueSize'], ['id', 'target', 'path', 'valueType', 'valueSize']);
407
- exact(item.valueType, 'quaternion', `${path}.valueType`);
408
- exact(item.valueSize, 4, `${path}.valueSize`, 'E_ANIMATION_3D_BINDING_MISMATCH');
409
- return Object.freeze({ id, target, path: base.path, valueType: 'quaternion', valueSize: 4 });
410
- }
411
- if (base.path === 'morph.weights') {
412
- const item = object(value, path, ['id', 'target', 'path', 'valueType', 'valueSize'], ['id', 'target', 'path', 'valueType', 'valueSize']);
413
- exact(item.valueType, 'weights', `${path}.valueType`);
414
- return Object.freeze({ id, target, path: base.path, valueType: 'weights', valueSize: integer(item.valueSize, `${path}.valueSize`, 1, 65_536) });
415
- }
416
- if (base.path === 'property') {
417
- const item = object(value, path, ['id', 'target', 'path', 'component', 'property', 'valueType', 'valueSize'], ['id', 'target', 'path', 'component', 'property', 'valueType', 'valueSize']);
418
- const component = enumeration(item.component, ['material3d', 'camera3d'] as const, `${path}.component`);
419
- const property = enumeration(item.property, ['baseColorFactor', 'metallicFactor', 'roughnessFactor', 'emissiveFactor', 'alphaCutoff', 'fovYRadians', 'near', 'far', 'orthoHeight'] as const, `${path}.property`);
420
- const contract = propertyContract(component, property, `${path}.property`);
421
- exact(item.valueType, contract.valueType, `${path}.valueType`, 'E_ANIMATION_3D_BINDING_MISMATCH');
422
- exact(item.valueSize, contract.valueSize, `${path}.valueSize`, 'E_ANIMATION_3D_BINDING_MISMATCH');
423
- return Object.freeze({ id, target, path: 'property', component, property, ...contract });
424
- }
425
- invalid(`Unsupported binding path "${String(base.path)}".`, `${path}.path`, 'E_ANIMATION_3D_UNSUPPORTED_FEATURE');
426
- }
427
-
428
- function parseBindingTarget(value: unknown, path: string): Native3DBindingTarget {
429
- const kind = object(value, path).kind;
430
- if (kind === 'node-id') {
431
- const item = object(value, path, ['kind', 'nodeId'], ['kind', 'nodeId']);
432
- return Object.freeze({ kind, nodeId: nonEmpty(item.nodeId, `${path}.nodeId`) });
433
- }
434
- if (kind === 'node-path') {
435
- const item = object(value, path, ['kind', 'segments'], ['kind', 'segments']);
436
- const segments = array(item.segments, `${path}.segments`);
437
- if (segments.length === 0) invalid('Node path must contain at least one segment.', `${path}.segments`);
438
- return Object.freeze({ kind, segments: Object.freeze(segments.map((segment, index) => nonEmpty(segment, `${path}.segments[${index}]`))) });
439
- }
440
- if (kind === 'slot') {
441
- const item = object(value, path, ['kind', 'slot'], ['kind', 'slot']);
442
- return Object.freeze({ kind, slot: nonEmpty(item.slot, `${path}.slot`) });
443
- }
444
- invalid(`Unsupported binding target "${String(kind)}".`, `${path}.kind`, 'E_ANIMATION_3D_UNSUPPORTED_FEATURE');
445
- }
446
-
447
- function parseEvent(value: unknown, path: string, duration: number): Native3DEvent {
448
- const item = object(value, path, ['id', 'time', 'name'], ['id', 'time', 'name', 'payload']);
449
- const time = nonNegative(item.time, `${path}.time`);
450
- if (time > duration) invalid('Event time must lie within clip duration.', `${path}.time`);
451
- return Object.freeze({
452
- id: nonEmpty(item.id, `${path}.id`), time, name: nonEmpty(item.name, `${path}.name`),
453
- ...(item.payload === undefined ? {} : { payload: parseJsonObject(item.payload, `${path}.payload`) }),
454
- });
455
- }
456
-
457
- function parseStateMachine(value: unknown, path: string, maxDepth: number): Native3DStateMachine {
458
- const item = object(value, path, ['format', 'id', 'name', 'parameters', 'layers'], ['format', 'id', 'name', 'parameters', 'layers']);
459
- exact(item.format, NATIVE_3D_STATE_MACHINE_FORMAT, `${path}.format`);
460
- const parameterNames = new Set<string>();
461
- const parameters = array(item.parameters, `${path}.parameters`).map((entry, index) => {
462
- const parameterPath = `${path}.parameters[${index}]`;
463
- const parameter = parseParameter(entry, parameterPath);
464
- unique(parameterNames, parameter.name, `${parameterPath}.name`, 'state-machine parameter');
465
- return parameter;
466
- });
467
- const layerIds = new Set<string>();
468
- const layers = array(item.layers, `${path}.layers`).map((entry, index) => {
469
- const layerPath = `${path}.layers[${index}]`;
470
- const layer = parseLayer(entry, layerPath, maxDepth);
471
- unique(layerIds, layer.id, `${layerPath}.id`, 'state-machine layer');
472
- return layer;
473
- });
474
- return Object.freeze({
475
- format: NATIVE_3D_STATE_MACHINE_FORMAT,
476
- id: nonEmpty(item.id, `${path}.id`), name: string(item.name, `${path}.name`),
477
- parameters: Object.freeze(parameters), layers: Object.freeze(layers),
478
- });
479
- }
480
-
481
- function parseParameter(value: unknown, path: string): Native3DStateMachineParameter {
482
- const base = object(value, path);
483
- const name = nonEmpty(base.name, `${path}.name`);
484
- if (base.type === 'trigger') {
485
- object(value, path, ['name', 'type'], ['name', 'type']);
486
- return Object.freeze({ name, type: 'trigger' });
487
- }
488
- object(value, path, ['name', 'type', 'defaultValue'], ['name', 'type', 'defaultValue']);
489
- if (base.type === 'float') return Object.freeze({ name, type: 'float', defaultValue: finite(base.defaultValue, `${path}.defaultValue`) });
490
- if (base.type === 'integer') return Object.freeze({ name, type: 'integer', defaultValue: integer(base.defaultValue, `${path}.defaultValue`, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER) });
491
- if (base.type === 'boolean') return Object.freeze({ name, type: 'boolean', defaultValue: boolean(base.defaultValue, `${path}.defaultValue`) });
492
- invalid(`Unsupported parameter type "${String(base.type)}".`, `${path}.type`, 'E_ANIMATION_3D_UNSUPPORTED_FEATURE');
493
- }
494
-
495
- function parseLayer(value: unknown, path: string, maxDepth: number): Native3DStateMachineLayer {
496
- const item = object(value, path, ['id', 'name', 'initialStateId', 'states', 'transitions'],
497
- ['id', 'name', 'initialStateId', 'states', 'transitions', 'blendMode', 'weight', 'mask']);
498
- const stateIds = new Set<string>();
499
- const states = array(item.states, `${path}.states`).map((entry, index) => {
500
- const statePath = `${path}.states[${index}]`;
501
- const state = parseState(entry, statePath, maxDepth);
502
- unique(stateIds, state.id, `${statePath}.id`, 'state');
503
- return state;
504
- });
505
- const transitionIds = new Set<string>();
506
- const transitions = array(item.transitions, `${path}.transitions`).map((entry, index) => {
507
- const transitionPath = `${path}.transitions[${index}]`;
508
- const transition = parseTransition(entry, transitionPath);
509
- unique(transitionIds, transition.id, `${transitionPath}.id`, 'transition');
510
- return transition;
511
- });
512
- const mask = item.mask === undefined ? undefined : parseMask(item.mask, `${path}.mask`);
513
- return Object.freeze({
514
- id: nonEmpty(item.id, `${path}.id`), name: string(item.name, `${path}.name`),
515
- initialStateId: nonEmpty(item.initialStateId, `${path}.initialStateId`),
516
- states: Object.freeze(states), transitions: Object.freeze(transitions),
517
- ...(item.blendMode === undefined ? {} : { blendMode: enumeration(item.blendMode, ['override', 'additive'] as const, `${path}.blendMode`) }),
518
- ...(item.weight === undefined ? {} : { weight: bounded(item.weight, `${path}.weight`, 0, 1) }),
519
- ...(mask ? { mask } : {}),
520
- });
521
- }
522
-
523
- function parseState(value: unknown, path: string, maxDepth: number): Native3DStateMachineState {
524
- const item = object(value, path, ['id', 'name', 'motion'], ['id', 'name', 'motion', 'speed', 'speedParameter', 'loop']);
525
- return Object.freeze({
526
- id: nonEmpty(item.id, `${path}.id`), name: string(item.name, `${path}.name`),
527
- motion: parseMotion(item.motion, `${path}.motion`, 0, maxDepth),
528
- ...(item.speed === undefined ? {} : { speed: finite(item.speed, `${path}.speed`) }),
529
- ...(item.speedParameter === undefined ? {} : { speedParameter: nonEmpty(item.speedParameter, `${path}.speedParameter`) }),
530
- ...(item.loop === undefined ? {} : { loop: enumeration(item.loop, ['once', 'repeat', 'ping-pong'] as const, `${path}.loop`) }),
531
- });
532
- }
533
-
534
- function parseMotion(value: unknown, path: string, depth: number, maxDepth: number): Native3DStateMachineMotion {
535
- if (depth >= maxDepth) budget(depth + 1, maxDepth, 'state-machine motion depth', path);
536
- const base = object(value, path);
537
- if (base.kind === 'clip') {
538
- const item = object(value, path, ['kind', 'clipId'], ['kind', 'clipId']);
539
- return Object.freeze({ kind: 'clip', clipId: nonEmpty(item.clipId, `${path}.clipId`) });
540
- }
541
- if (base.kind === 'blend-1d') {
542
- const item = object(value, path, ['kind', 'parameter', 'children'], ['kind', 'parameter', 'children']);
543
- const children = nonEmptyArray(item.children, `${path}.children`).map((entry, index) => {
544
- const childPath = `${path}.children[${index}]`;
545
- const child = object(entry, childPath, ['threshold', 'motion'], ['threshold', 'motion']);
546
- return Object.freeze({ threshold: finite(child.threshold, `${childPath}.threshold`), motion: parseMotion(child.motion, `${childPath}.motion`, depth + 1, maxDepth) });
547
- });
548
- return Object.freeze({ kind: 'blend-1d', parameter: nonEmpty(item.parameter, `${path}.parameter`), children: Object.freeze(children) });
549
- }
550
- if (base.kind === 'blend-2d') {
551
- const item = object(value, path, ['kind', 'algorithm', 'parameterX', 'parameterY', 'children'], ['kind', 'algorithm', 'parameterX', 'parameterY', 'children']);
552
- const children = nonEmptyArray(item.children, `${path}.children`).map((entry, index) => {
553
- const childPath = `${path}.children[${index}]`;
554
- const child = object(entry, childPath, ['position', 'motion'], ['position', 'motion']);
555
- return Object.freeze({ position: vec2(child.position, `${childPath}.position`), motion: parseMotion(child.motion, `${childPath}.motion`, depth + 1, maxDepth) });
556
- });
557
- return Object.freeze({
558
- kind: 'blend-2d', algorithm: enumeration(item.algorithm, ['cartesian', 'directional'] as const, `${path}.algorithm`),
559
- parameterX: nonEmpty(item.parameterX, `${path}.parameterX`), parameterY: nonEmpty(item.parameterY, `${path}.parameterY`),
560
- children: Object.freeze(children),
561
- });
562
- }
563
- invalid(`Unsupported motion kind "${String(base.kind)}".`, `${path}.kind`, 'E_ANIMATION_3D_UNSUPPORTED_FEATURE');
564
- }
565
-
566
- function parseTransition(value: unknown, path: string): Native3DStateMachineTransition {
567
- const item = object(value, path, ['id', 'from', 'to', 'conditions', 'duration'],
568
- ['id', 'from', 'to', 'conditions', 'duration', 'hasExitTime', 'exitTime', 'destinationOffset', 'interruption']);
569
- const conditions = array(item.conditions, `${path}.conditions`).map((entry, index) => parseCondition(entry, `${path}.conditions[${index}]`));
570
- return Object.freeze({
571
- id: nonEmpty(item.id, `${path}.id`), from: nonEmpty(item.from, `${path}.from`), to: nonEmpty(item.to, `${path}.to`),
572
- conditions: Object.freeze(conditions), duration: nonNegative(item.duration, `${path}.duration`),
573
- ...(item.hasExitTime === undefined ? {} : { hasExitTime: boolean(item.hasExitTime, `${path}.hasExitTime`) }),
574
- ...(item.exitTime === undefined ? {} : { exitTime: nonNegative(item.exitTime, `${path}.exitTime`) }),
575
- ...(item.destinationOffset === undefined ? {} : { destinationOffset: nonNegative(item.destinationOffset, `${path}.destinationOffset`) }),
576
- ...(item.interruption === undefined ? {} : { interruption: enumeration(item.interruption, ['none', 'source', 'destination', 'source-then-destination', 'destination-then-source'] as const, `${path}.interruption`) }),
577
- });
578
- }
579
-
580
- function parseCondition(value: unknown, path: string): Native3DStateMachineCondition {
581
- const item = object(value, path, ['parameter', 'operator'], ['parameter', 'operator', 'value']);
582
- const operator = enumeration(item.operator, ['greater', 'greater-or-equal', 'less', 'less-or-equal', 'equal', 'not-equal', 'is-true', 'is-false', 'triggered'] as const, `${path}.operator`);
583
- return Object.freeze({
584
- parameter: nonEmpty(item.parameter, `${path}.parameter`), operator,
585
- ...(item.value === undefined ? {} : { value: typeof item.value === 'boolean' ? item.value : finite(item.value, `${path}.value`) }),
586
- });
587
- }
588
-
589
- function parseMask(value: unknown, path: string): Readonly<{ include?: readonly string[]; exclude?: readonly string[] }> {
590
- const item = object(value, path, [], ['include', 'exclude']);
591
- const parseList = (entry: unknown, entryPath: string): readonly string[] => {
592
- const seen = new Set<string>();
593
- return Object.freeze(array(entry, entryPath).map((value, index) => {
594
- const result = nonEmpty(value, `${entryPath}[${index}]`);
595
- unique(seen, result, `${entryPath}[${index}]`, 'mask binding');
596
- return result;
597
- }));
598
- };
599
- return Object.freeze({
600
- ...(item.include === undefined ? {} : { include: parseList(item.include, `${path}.include`) }),
601
- ...(item.exclude === undefined ? {} : { exclude: parseList(item.exclude, `${path}.exclude`) }),
602
- });
603
- }
604
-
605
- function validateCarrier(document: ParsedAnimation, payload: Native3DAnimationPayload): void {
606
- if (document.extensionsUsed.length !== 1 || document.extensionsUsed[0] !== NATIVE_3D_ANIMATION_EXTENSION_ID
607
- || document.extensionsRequired.length !== 1 || document.extensionsRequired[0] !== NATIVE_3D_ANIMATION_EXTENSION_ID) {
608
- invalid(`Native 3D carrier must use and require only "${NATIVE_3D_ANIMATION_EXTENSION_ID}".`, '$.extensionsRequired');
609
- }
610
- if (document.nodes.length > 0) {
611
- invalid('Native 3D carrier cannot contain core 2D nodes.', '$.nodes', 'E_ANIMATION_3D_MIXED_DIMENSIONS');
612
- }
613
- if (document.tracks.length > 0) {
614
- invalid('Native 3D carrier cannot contain core 2D tracks.', '$.tracks', 'E_ANIMATION_3D_MIXED_DIMENSIONS');
615
- }
616
- if (document.canvas.width !== payload.viewport.width || document.canvas.height !== payload.viewport.height) {
617
- invalid('Core canvas and native 3D viewport dimensions must match.', `${EXTENSION_PATH}.viewport`);
618
- }
619
- for (let index = 0; index < payload.nodes.length; index++) {
620
- const node = payload.nodes[index]!;
621
- const start = node.start ?? 0;
622
- if (start > document.duration || start + (node.duration ?? document.duration - start) > document.duration + 1e-6) {
623
- invalid('Node time range must fit inside composition duration.', `${EXTENSION_PATH}.nodes[${index}]`);
624
- }
625
- }
626
- for (let index = 0; index < payload.clips.length; index++) {
627
- if (payload.clips[index]!.duration > document.duration + 1e-6) {
628
- invalid('Clip duration must fit inside composition duration.', `${EXTENSION_PATH}.clips[${index}].duration`);
629
- }
630
- }
631
- }
632
-
633
- function validateNodeSemantics(nodes: readonly Native3DNode[], nodeIds: Set<string>, materialIds: Set<string>): void {
634
- const byId = new Map(nodes.map(node => [node.id, node]));
635
- for (let index = 0; index < nodes.length; index++) {
636
- const node = nodes[index]!;
637
- if (node.parent !== undefined && !nodeIds.has(node.parent)) {
638
- invalid(`Node parent "${node.parent}" does not exist.`, `${EXTENSION_PATH}.nodes[${index}].parent`, 'E_ANIMATION_3D_BINDING_MISMATCH');
639
- }
640
- if (node.parent === node.id) invalid('Node cannot parent itself.', `${EXTENSION_PATH}.nodes[${index}].parent`, 'E_ANIMATION_3D_BINDING_MISMATCH');
641
- for (let componentIndex = 0; componentIndex < node.components.length; componentIndex++) {
642
- const component = node.components[componentIndex]!;
643
- const path = `${EXTENSION_PATH}.nodes[${index}].components[${componentIndex}]`;
644
- if (component.kind === 'primitive3d' && !materialIds.has(component.materialId)) {
645
- invalid(`Primitive material "${component.materialId}" does not exist.`, `${path}.materialId`, 'E_ANIMATION_3D_UNKNOWN_RESOURCE');
646
- }
647
- if (component.kind === 'model3d') {
648
- for (let overrideIndex = 0; overrideIndex < (component.materialOverrides?.length ?? 0); overrideIndex++) {
649
- const materialId = component.materialOverrides![overrideIndex]!.materialId;
650
- if (!materialIds.has(materialId)) invalid(`Material override "${materialId}" does not exist.`, `${path}.materialOverrides[${overrideIndex}].materialId`, 'E_ANIMATION_3D_UNKNOWN_RESOURCE');
651
- }
652
- }
653
- }
654
- }
655
- for (const node of nodes) {
656
- const visited = new Set<string>();
657
- let current: Native3DNode | undefined = node;
658
- while (current?.parent) {
659
- if (visited.has(current.id)) invalid('Node hierarchy contains a cycle.', `${EXTENSION_PATH}.nodes`, 'E_ANIMATION_3D_BINDING_MISMATCH');
660
- visited.add(current.id);
661
- current = byId.get(current.parent);
662
- }
663
- }
664
- }
665
-
666
- function validateResourceReferences(resources: readonly Readonly<AnimationResource>[], payload: Native3DAnimationPayload): void {
667
- const byId = new Map(resources.map(resource => [resource.id, resource]));
668
- for (let index = 0; index < resources.length; index++) {
669
- const resource = resources[index]!;
670
- const scheme = uriScheme(resource.uri);
671
- if (scheme && FORBIDDEN_URI_SCHEMES.has(scheme)) {
672
- invalid(`Delivery URI scheme "${scheme}:" is forbidden.`, `$.resources[${index}].uri`, 'E_ANIMATION_3D_UNKNOWN_RESOURCE');
673
- }
674
- }
675
- for (let materialIndex = 0; materialIndex < payload.materials.length; materialIndex++) {
676
- const material = payload.materials[materialIndex]!;
677
- for (const key of ['baseColorTexture', 'normalTexture', 'metallicRoughnessTexture', 'emissiveTexture'] as const) {
678
- const id = material[key];
679
- if (id === undefined) continue;
680
- const resource = byId.get(id);
681
- if (!resource || resource.type !== 'image') invalid(`Material texture "${id}" must reference an image resource.`, `${EXTENSION_PATH}.materials[${materialIndex}].${key}`, 'E_ANIMATION_3D_UNKNOWN_RESOURCE');
682
- }
683
- }
684
- for (let nodeIndex = 0; nodeIndex < payload.nodes.length; nodeIndex++) {
685
- const node = payload.nodes[nodeIndex]!;
686
- for (let componentIndex = 0; componentIndex < node.components.length; componentIndex++) {
687
- const component = node.components[componentIndex]!;
688
- const path = `${EXTENSION_PATH}.nodes[${nodeIndex}].components[${componentIndex}]`;
689
- if (component.kind === 'model3d') {
690
- const resource = byId.get(component.resource);
691
- if (!resource || resource.type !== 'binary' || !resource.mimeType || !MODEL_MIME_TYPES.has(resource.mimeType)) {
692
- invalid(`Model "${component.resource}" must reference a binary glTF/GLB resource.`, `${path}.resource`, 'E_ANIMATION_3D_UNKNOWN_RESOURCE');
693
- }
694
- }
695
- if (component.kind === 'particle3d' && component.descriptor.textureResource !== undefined) {
696
- const resource = byId.get(component.descriptor.textureResource);
697
- if (!resource || resource.type !== 'image') invalid(`Particle texture "${component.descriptor.textureResource}" must reference an image resource.`, `${path}.descriptor.textureResource`, 'E_ANIMATION_3D_UNKNOWN_RESOURCE');
698
- }
699
- }
700
- }
701
- }
702
-
703
- function validateBindingTarget(binding: Native3DBinding, nodes: readonly Native3DNode[], materialIds: Set<string>, path: string): void {
704
- const byId = new Map(nodes.map(node => [node.id, node]));
705
- const target = binding.target;
706
- if (target.kind === 'node-id' && !byId.has(target.nodeId)) {
707
- invalid(`Binding node "${target.nodeId}" does not exist.`, `${path}.target.nodeId`, 'E_ANIMATION_3D_BINDING_MISMATCH');
708
- }
709
- if (target.kind === 'node-path' && !byId.has(target.segments[0]!)) {
710
- invalid(`Binding node path root "${target.segments[0]}" does not exist.`, `${path}.target.segments[0]`, 'E_ANIMATION_3D_BINDING_MISMATCH');
711
- }
712
- if (binding.path === 'property' && binding.component === 'material3d') {
713
- if (target.kind !== 'slot' || !materialIds.has(target.slot)) invalid('Material property bindings require a material-id slot target.', `${path}.target`, 'E_ANIMATION_3D_BINDING_MISMATCH');
714
- }
715
- if (binding.path === 'property' && binding.component === 'camera3d') {
716
- if (target.kind !== 'node-id' || !byId.get(target.nodeId)?.components.some(component => component.kind === 'camera3d')) {
717
- invalid('Camera property bindings require a node-id target with Camera3D.', `${path}.target`, 'E_ANIMATION_3D_BINDING_MISMATCH');
718
- }
719
- }
720
- }
721
-
722
- function validateStateMachineReferences(machine: Native3DStateMachine, clipIds: Set<string>, bindingIds: Set<string>, path: string): void {
723
- const parameterNames = new Set(machine.parameters.map(parameter => parameter.name));
724
- const visitMotion = (motion: Native3DStateMachineMotion, motionPath: string): void => {
725
- if (motion.kind === 'clip') {
726
- if (!clipIds.has(motion.clipId)) invalid(`Motion clip "${motion.clipId}" does not exist.`, `${motionPath}.clipId`, 'E_ANIMATION_3D_BINDING_MISMATCH');
727
- return;
728
- }
729
- for (let index = 0; index < motion.children.length; index++) visitMotion(motion.children[index]!.motion, `${motionPath}.children[${index}].motion`);
730
- };
731
- for (let layerIndex = 0; layerIndex < machine.layers.length; layerIndex++) {
732
- const layer = machine.layers[layerIndex]!;
733
- const layerPath = `${path}.layers[${layerIndex}]`;
734
- const stateIds = new Set(layer.states.map(state => state.id));
735
- if (!stateIds.has(layer.initialStateId)) invalid(`Initial state "${layer.initialStateId}" does not exist.`, `${layerPath}.initialStateId`, 'E_ANIMATION_3D_BINDING_MISMATCH');
736
- for (let stateIndex = 0; stateIndex < layer.states.length; stateIndex++) {
737
- const state = layer.states[stateIndex]!;
738
- visitMotion(state.motion, `${layerPath}.states[${stateIndex}].motion`);
739
- if (state.speedParameter && !parameterNames.has(state.speedParameter)) invalid(`Speed parameter "${state.speedParameter}" does not exist.`, `${layerPath}.states[${stateIndex}].speedParameter`, 'E_ANIMATION_3D_BINDING_MISMATCH');
740
- }
741
- for (let transitionIndex = 0; transitionIndex < layer.transitions.length; transitionIndex++) {
742
- const transition = layer.transitions[transitionIndex]!;
743
- const transitionPath = `${layerPath}.transitions[${transitionIndex}]`;
744
- if (transition.from !== '*' && !stateIds.has(transition.from)) invalid(`Transition source "${transition.from}" does not exist.`, `${transitionPath}.from`, 'E_ANIMATION_3D_BINDING_MISMATCH');
745
- if (!stateIds.has(transition.to)) invalid(`Transition destination "${transition.to}" does not exist.`, `${transitionPath}.to`, 'E_ANIMATION_3D_BINDING_MISMATCH');
746
- for (let conditionIndex = 0; conditionIndex < transition.conditions.length; conditionIndex++) {
747
- if (!parameterNames.has(transition.conditions[conditionIndex]!.parameter)) invalid(`Condition parameter "${transition.conditions[conditionIndex]!.parameter}" does not exist.`, `${transitionPath}.conditions[${conditionIndex}].parameter`, 'E_ANIMATION_3D_BINDING_MISMATCH');
748
- }
749
- }
750
- for (const [kind, values] of [['include', layer.mask?.include], ['exclude', layer.mask?.exclude]] as const) {
751
- for (let index = 0; index < (values?.length ?? 0); index++) {
752
- if (!bindingIds.has(values![index]!)) invalid(`Mask binding "${values![index]}" does not exist.`, `${layerPath}.mask.${kind}[${index}]`, 'E_ANIMATION_3D_BINDING_MISMATCH');
753
- }
754
- }
755
- }
756
- }
757
-
758
- function propertyContract(component: 'material3d' | 'camera3d', property: string, path: string): { valueType: 'scalar' | 'vec3' | 'vec4'; valueSize: 1 | 3 | 4 } {
759
- const material = { baseColorFactor: ['vec4', 4], metallicFactor: ['scalar', 1], roughnessFactor: ['scalar', 1], emissiveFactor: ['vec3', 3], alphaCutoff: ['scalar', 1] } as const;
760
- const camera = { fovYRadians: ['scalar', 1], near: ['scalar', 1], far: ['scalar', 1], orthoHeight: ['scalar', 1] } as const;
761
- const contract = component === 'material3d'
762
- ? material[property as keyof typeof material]
763
- : camera[property as keyof typeof camera];
764
- if (!contract) invalid(`Property "${property}" is not valid for ${component}.`, path, 'E_ANIMATION_3D_BINDING_MISMATCH');
765
- return { valueType: contract[0], valueSize: contract[1] };
766
- }
767
-
768
- function validateTrackQuaternions(values: readonly number[], keyCount: number, interpolation: Native3DTrack['interpolation'], path: string): void {
769
- const stride = interpolation === 'cubic-spline' ? 12 : 4;
770
- const valueOffset = interpolation === 'cubic-spline' ? 4 : 0;
771
- for (let index = 0; index < keyCount; index++) {
772
- assertNormalizedQuaternion(values.slice(index * stride + valueOffset, index * stride + valueOffset + 4) as unknown as Native3DVec4, `${path}[${index * stride + valueOffset}]`);
773
- }
774
- }
775
-
776
- function assertNormalizedQuaternion(value: Native3DVec4, path: string): void {
777
- const length = Math.hypot(...value);
778
- if (Math.abs(length - 1) > 1e-4) invalid('Quaternion must be normalized XYZW.', path, 'E_ANIMATION_3D_BINDING_MISMATCH');
779
- }
780
-
781
- function pickCoreLimits(options: Native3DAnimationParseOptions): AnimationParseOptions {
782
- const keys = ['maxInputBytes', 'maxMetadataBytes', 'maxNodes', 'maxComponents', 'maxTracks', 'maxKeyframes', 'maxResources', 'maxPathValues', 'maxTextCharacters', 'maxParticleCapacity'] as const;
783
- const result: Record<string, number> = {};
784
- for (const key of keys) if (options[key] !== undefined) result[key] = options[key]!;
785
- return result;
786
- }
787
-
788
- function resolveLimits(options: Native3DAnimationParseOptions): Limits {
789
- return Object.freeze({
790
- maxMaterials: positiveLimit(options.maxMaterials, DEFAULT_LIMITS.maxMaterials, 'maxMaterials'),
791
- maxNodes: positiveLimit(options.maxNodes, DEFAULT_LIMITS.maxNodes, 'maxNodes'),
792
- maxComponents: positiveLimit(options.maxComponents, DEFAULT_LIMITS.maxComponents, 'maxComponents'),
793
- maxClips: positiveLimit(options.maxClips, DEFAULT_LIMITS.maxClips, 'maxClips'),
794
- maxTracks: positiveLimit(options.maxTracks, DEFAULT_LIMITS.maxTracks, 'maxTracks'),
795
- maxKeyframes: positiveLimit(options.maxKeyframes, DEFAULT_LIMITS.maxKeyframes, 'maxKeyframes'),
796
- maxParticleCapacity: positiveLimit(options.maxParticleCapacity, DEFAULT_LIMITS.maxParticleCapacity, 'maxParticleCapacity'),
797
- maxStateMachineDepth: positiveLimit(options.maxStateMachineDepth, DEFAULT_LIMITS.maxStateMachineDepth, 'maxStateMachineDepth'),
798
- });
799
- }
800
-
801
- function positiveLimit(value: number | undefined, fallback: number, name: string): number {
802
- if (value === undefined) return fallback;
803
- if (!Number.isSafeInteger(value) || value <= 0) throw new RangeError(`${name} must be a positive safe integer.`);
804
- return value;
805
- }
806
-
807
- function object(value: unknown, path: string, required: readonly string[] = [], allowed?: readonly string[]): Record<string, unknown> {
808
- if (!value || typeof value !== 'object' || Array.isArray(value)) invalid('Expected an object.', path);
809
- const result = value as Record<string, unknown>;
810
- for (const key of required) if (!(key in result)) invalid(`Missing required property "${key}".`, `${path}.${key}`);
811
- if (allowed) {
812
- const allowedSet = new Set(allowed);
813
- for (const key of Object.keys(result)) if (!allowedSet.has(key)) invalid(`Unknown property "${key}".`, `${path}.${key}`, 'E_ANIMATION_3D_UNSUPPORTED_FEATURE');
814
- }
815
- return result;
816
- }
817
-
818
- function array(value: unknown, path: string): unknown[] {
819
- if (!Array.isArray(value)) invalid('Expected an array.', path);
820
- return value;
821
- }
822
-
823
- function nonEmptyArray(value: unknown, path: string): unknown[] {
824
- const result = array(value, path);
825
- if (result.length === 0) invalid('Expected at least one item.', path);
826
- return result;
827
- }
828
-
829
- function numericArray(value: unknown, path: string, minimumLength = 0): readonly number[] {
830
- const result = array(value, path);
831
- if (result.length < minimumLength) invalid(`Expected at least ${minimumLength} numeric value(s).`, path);
832
- return Object.freeze(result.map((entry, index) => finite(entry, `${path}[${index}]`)));
833
- }
834
-
835
- function vec2(value: unknown, path: string): Native3DVec2 {
836
- return tuple(value, path, 2) as Native3DVec2;
837
- }
838
-
839
- function vec3(value: unknown, path: string, minimum = -Number.MAX_VALUE, maximum = Number.MAX_VALUE): Native3DVec3 {
840
- return tuple(value, path, 3, minimum, maximum) as Native3DVec3;
841
- }
842
-
843
- function vec4(value: unknown, path: string, minimum = -Number.MAX_VALUE, maximum = Number.MAX_VALUE): Native3DVec4 {
844
- return tuple(value, path, 4, minimum, maximum) as Native3DVec4;
845
- }
846
-
847
- function tuple(value: unknown, path: string, size: number, minimum = -Number.MAX_VALUE, maximum = Number.MAX_VALUE): readonly number[] {
848
- const result = array(value, path);
849
- if (result.length !== size) invalid(`Expected exactly ${size} numbers.`, path);
850
- return Object.freeze(result.map((entry, index) => bounded(entry, `${path}[${index}]`, minimum, maximum)));
851
- }
852
-
853
- function range(value: unknown, path: string, minimum = -Number.MAX_VALUE): Native3DScalarRange {
854
- if (Array.isArray(value)) {
855
- const result = tuple(value, path, 2, minimum) as readonly [number, number];
856
- if (result[0] > result[1]) invalid('Range minimum cannot exceed maximum.', path);
857
- return result;
858
- }
859
- return bounded(value, path, minimum);
860
- }
861
-
862
- function finite(value: unknown, path: string): number {
863
- if (typeof value !== 'number' || !Number.isFinite(value)) invalid('Expected a finite number.', path);
864
- return value;
865
- }
866
-
867
- function positive(value: unknown, path: string): number {
868
- const result = finite(value, path);
869
- if (result <= 0) invalid('Expected a positive number.', path);
870
- return result;
871
- }
872
-
873
- function nonNegative(value: unknown, path: string): number {
874
- const result = finite(value, path);
875
- if (result < 0) invalid('Expected a non-negative number.', path);
876
- return result;
877
- }
878
-
879
- function bounded(value: unknown, path: string, minimum: number, maximum = Number.MAX_VALUE, inclusiveMaximum = true): number {
880
- const result = finite(value, path);
881
- if (result < minimum || (inclusiveMaximum ? result > maximum : result >= maximum)) invalid(`Expected a number in ${inclusiveMaximum ? '[' : '('}${minimum}, ${maximum}${inclusiveMaximum ? ']' : ')'}.`, path);
882
- return result;
883
- }
884
-
885
- function integer(value: unknown, path: string, minimum: number, maximum: number): number {
886
- if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < minimum || value > maximum) invalid(`Expected a safe integer in [${minimum}, ${maximum}].`, path);
887
- return value;
888
- }
889
-
890
- function string(value: unknown, path: string): string {
891
- if (typeof value !== 'string') invalid('Expected a string.', path);
892
- return value;
893
- }
894
-
895
- function nonEmpty(value: unknown, path: string): string {
896
- const result = string(value, path);
897
- if (result.length === 0) invalid('Expected a non-empty string.', path);
898
- return result;
899
- }
900
-
901
- function boolean(value: unknown, path: string): boolean {
902
- if (typeof value !== 'boolean') invalid('Expected a boolean.', path);
903
- return value;
904
- }
905
-
906
- function enumeration<T extends string>(value: unknown, values: readonly T[], path: string): T {
907
- if (typeof value !== 'string' || !values.includes(value as T)) invalid(`Expected one of ${values.join(', ')}.`, path);
908
- return value as T;
909
- }
910
-
911
- function exact(value: unknown, expected: unknown, path: string, code: ConstructorParameters<typeof Native3DAnimationFormatError>[0] = 'E_ANIMATION_3D_INVALID_PAYLOAD'): void {
912
- if (value !== expected) invalid(`Expected ${JSON.stringify(expected)}.`, path, code);
913
- }
914
-
915
- function unique(seen: Set<string>, value: string, path: string, label: string): void {
916
- if (seen.has(value)) invalid(`Duplicate ${label} id "${value}".`, path, 'E_ANIMATION_3D_BINDING_MISMATCH');
917
- seen.add(value);
918
- }
919
-
920
- function budget(actual: number, maximum: number, label: string, path: string): void {
921
- if (actual > maximum) invalid(`${label} count ${actual} exceeds limit ${maximum}.`, path, 'E_ANIMATION_3D_LIMIT_EXCEEDED');
922
- }
923
-
924
- function optionalStrings(item: Record<string, unknown>, path: string, keys: readonly string[]): Record<string, string> {
925
- const result: Record<string, string> = {};
926
- for (const key of keys) if (item[key] !== undefined) result[key] = nonEmpty(item[key], `${path}.${key}`);
927
- return result;
928
- }
929
-
930
- function parseJsonObject(value: unknown, path: string, depth = 0): Readonly<Record<string, unknown>> {
931
- if (depth > 64) budget(depth, 64, 'event payload depth', path);
932
- const item = object(value, path);
933
- const result: Record<string, unknown> = {};
934
- for (const [key, child] of Object.entries(item)) result[key] = parseJsonValue(child, `${path}.${key}`, depth + 1);
935
- return Object.freeze(result);
936
- }
937
-
938
- function parseJsonValue(value: unknown, path: string, depth: number): unknown {
939
- if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;
940
- if (typeof value === 'number') return finite(value, path);
941
- if (Array.isArray(value)) return Object.freeze(value.map((child, index) => parseJsonValue(child, `${path}[${index}]`, depth + 1)));
942
- return parseJsonObject(value, path, depth);
943
- }
944
-
945
- function uriScheme(uri: string): string | null {
946
- const match = /^([a-z][a-z0-9+.-]*):/i.exec(uri);
947
- return match?.[1]?.toLowerCase() ?? null;
948
- }
949
-
950
- function deepFreeze<T>(value: T): T {
951
- if (value && typeof value === 'object' && !Object.isFrozen(value)) {
952
- for (const child of Object.values(value as Record<string, unknown>)) deepFreeze(child);
953
- Object.freeze(value);
954
- }
955
- return value;
956
- }
957
-
958
- function invalid(
959
- message: string,
960
- path: string,
961
- code: ConstructorParameters<typeof Native3DAnimationFormatError>[0] = 'E_ANIMATION_3D_INVALID_PAYLOAD',
962
- ): never {
963
- throw new Native3DAnimationFormatError(code, message, path);
964
- }