@call-me-sensei/toonlab 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/AGENTS.md +127 -4
  2. package/ATTRIBUTION.md +41 -3
  3. package/README.md +231 -34
  4. package/docs/characters.md +144 -0
  5. package/docs/debug-panel.md +126 -0
  6. package/docs/docs.css +589 -0
  7. package/docs/environment.md +186 -0
  8. package/docs/getting-started.md +180 -0
  9. package/docs/index.html +14 -0
  10. package/docs/lab-architecture.md +100 -0
  11. package/docs/lighting.md +825 -0
  12. package/docs/main.jsx +752 -0
  13. package/docs/mcp.md +97 -0
  14. package/docs/post-processing.md +98 -0
  15. package/docs/settings-reference.md +1878 -0
  16. package/docs/shader-constants.md +77 -0
  17. package/docs/sky.md +182 -0
  18. package/docs/style-labs.md +309 -0
  19. package/docs/texture-lab.md +135 -0
  20. package/docs/toon-shading.md +183 -0
  21. package/docs/tsl-conventions.md +167 -0
  22. package/docs/vegetation-sky.md +275 -0
  23. package/docs/water.md +430 -0
  24. package/docs/weather.md +200 -0
  25. package/docs/world-scale.md +111 -0
  26. package/mcp/server.mjs +610 -0
  27. package/mcp/style-lab-tools.mjs +371 -0
  28. package/mcp/vite-plugin.mjs +174 -0
  29. package/mcp/workspace.mjs +397 -0
  30. package/package.json +64 -5
  31. package/src/ambientfx/INTEGRATION.md +164 -0
  32. package/src/ambientfx/ambientFxPresets.js +83 -0
  33. package/src/ambientfx/ambientFxSettings.js +368 -0
  34. package/src/ambientfx/emitters.js +169 -0
  35. package/src/ambientfx/index.js +5 -0
  36. package/src/ambientfx/particleBackbone.js +493 -0
  37. package/src/ambientfx/stylizedAmbientFx.js +450 -0
  38. package/src/assetlib/ambientcg.js +117 -0
  39. package/src/assetlib/assetRef.js +91 -0
  40. package/src/assetlib/importedEntry.js +40 -0
  41. package/src/assetlib/index.js +23 -0
  42. package/src/assetlib/kaykit.js +192 -0
  43. package/src/assetlib/kaykitStaticIndex.js +700 -0
  44. package/src/assetlib/loadImported.js +143 -0
  45. package/src/assetlib/opensource3d.js +113 -0
  46. package/src/assetlib/polyhaven.js +182 -0
  47. package/src/assetlib/polypizza.js +115 -0
  48. package/src/assetlib/smithsonian.js +214 -0
  49. package/src/assetlib/sources.js +279 -0
  50. package/src/assetlib/zip.js +58 -0
  51. package/src/biome/biomeGenerator.js +385 -0
  52. package/src/biome/biomeRuntime.js +299 -0
  53. package/src/biome/index.js +2 -0
  54. package/src/buildinggen/buildingAsset.js +44 -0
  55. package/src/buildinggen/buildingGrammar.js +311 -0
  56. package/src/buildinggen/buildingMesh.js +451 -0
  57. package/src/buildinggen/buildingPresets.js +46 -0
  58. package/src/buildinggen/buildingRecipe.js +100 -0
  59. package/src/buildinggen/buildingSettings.js +238 -0
  60. package/src/buildinggen/index.js +6 -0
  61. package/src/camera/cameraDirector.js +157 -0
  62. package/src/camera/cameraGenerator.js +367 -0
  63. package/src/camera/cameraRig.js +570 -0
  64. package/src/camera/cameraSettings.js +236 -0
  65. package/src/camera/index.js +7 -0
  66. package/src/catalog/builtinEntries.js +245 -0
  67. package/src/catalog/catalog.js +210 -0
  68. package/src/catalog/index.js +3 -0
  69. package/src/catalog/manifest.js +84 -0
  70. package/src/core/generation.js +529 -0
  71. package/src/environment/environmentRigs.js +21 -1
  72. package/src/environment/environmentSettings.js +4 -0
  73. package/src/environment/environmentSunShadowPass.js +8 -0
  74. package/src/fauna/INTEGRATION.md +174 -0
  75. package/src/fauna/boids.js +861 -0
  76. package/src/fauna/faunaBodies.js +492 -0
  77. package/src/fauna/faunaPresets.js +52 -0
  78. package/src/fauna/faunaSettings.js +525 -0
  79. package/src/fauna/index.js +5 -0
  80. package/src/fauna/stylizedFauna.js +395 -0
  81. package/src/game-feel/gameFeelGenerator.js +402 -0
  82. package/src/game-feel/gameFeelRuntime.js +549 -0
  83. package/src/game-feel/index.js +2 -0
  84. package/src/index.js +17 -6
  85. package/src/lighting/colorIntensity.js +177 -0
  86. package/src/lighting/index.js +161 -0
  87. package/src/lighting/lightDescriptors.js +249 -0
  88. package/src/lighting/lightingCapabilities.js +79 -0
  89. package/src/lighting/lightingDocuments.js +247 -0
  90. package/src/lighting/lightingFixtures.js +446 -0
  91. package/src/lighting/lightingGenerator.js +449 -0
  92. package/src/lighting/lightingPresets.js +319 -0
  93. package/src/lighting/lightingRuntime.js +723 -0
  94. package/src/lighting/lightingStyle.js +386 -0
  95. package/src/lighting/lightingSystem.js +774 -0
  96. package/src/lighting/unrealExport.js +186 -0
  97. package/src/lighting/utils.js +87 -0
  98. package/src/motion/index.js +5 -0
  99. package/src/motion/motionClip.js +441 -0
  100. package/src/motion/motionController.js +628 -0
  101. package/src/motion/motionDocuments.js +225 -0
  102. package/src/motion/motionGraph.js +307 -0
  103. package/src/motion/motionSettings.js +222 -0
  104. package/src/pathgen/index.js +7 -0
  105. package/src/pathgen/pathBridge.js +232 -0
  106. package/src/pathgen/pathPresets.js +35 -0
  107. package/src/pathgen/pathRibbon.js +410 -0
  108. package/src/pathgen/pathRouter.js +380 -0
  109. package/src/pathgen/pathSettings.js +335 -0
  110. package/src/pathgen/pathTextures.js +123 -0
  111. package/src/pathgen/stylizedPaths.js +453 -0
  112. package/src/post/index.js +1 -0
  113. package/src/post/postGenerator.js +177 -0
  114. package/src/post/postProcessing.js +41 -0
  115. package/src/propgen/generatorsWave1.js +379 -0
  116. package/src/propgen/generatorsWave2.js +462 -0
  117. package/src/propgen/index.js +5 -0
  118. package/src/propgen/propAsset.js +323 -0
  119. package/src/propgen/propParts.js +170 -0
  120. package/src/propgen/propPlacement.js +459 -0
  121. package/src/propgen/propPresets.js +82 -0
  122. package/src/propgen/propSettings.js +395 -0
  123. package/src/shaders-tsl/chunks/projected-water-caustics.js +242 -0
  124. package/src/shaders-tsl/chunks/vegetation-style.js +360 -0
  125. package/src/shaders-tsl/chunks/water-shore-state.js +31 -0
  126. package/src/shaders-tsl/chunks/water-waves.js +90 -11
  127. package/src/shaders-tsl/environment.js +15 -1
  128. package/src/shaders-tsl/flower.js +279 -30
  129. package/src/shaders-tsl/grass.js +60 -33
  130. package/src/shaders-tsl/sky.js +125 -31
  131. package/src/shaders-tsl/tree-leaf.js +61 -25
  132. package/src/shaders-tsl/water-breaker.js +7 -4
  133. package/src/shaders-tsl/water-shore-state-simulation.js +523 -0
  134. package/src/shaders-tsl/water.js +439 -49
  135. package/src/shaders-tsl/woody-surface.js +154 -0
  136. package/src/sky/sceneOverrideLayers.js +10 -0
  137. package/src/sky/skyQuality.js +26 -0
  138. package/src/sky/stylizedSky.js +753 -45
  139. package/src/soundscape/index.js +4 -0
  140. package/src/soundscape/soundscapeGenerator.js +179 -0
  141. package/src/soundscape/soundscapeRuntime.js +806 -0
  142. package/src/soundscape/soundscapeSettings.js +292 -0
  143. package/src/styles/index.js +13 -0
  144. package/src/styles/styleBundle.js +325 -0
  145. package/src/stylizedTerrain.js +32 -2
  146. package/src/stylizedWorld.js +423 -20
  147. package/src/texgen/evaluateTexture.js +675 -0
  148. package/src/texgen/index.js +60 -0
  149. package/src/texgen/noise2.js +210 -0
  150. package/src/texgen/textureAi.js +436 -0
  151. package/src/texgen/textureGenerators.js +516 -0
  152. package/src/texgen/texturePresets.js +490 -0
  153. package/src/texgen/textureSettings.js +342 -0
  154. package/src/texgen/textureThree.js +59 -0
  155. package/src/vegetation/flowerSpecies.js +15 -3
  156. package/src/vegetation/grassPalettes.js +153 -0
  157. package/src/vegetation/index.js +6 -0
  158. package/src/vegetation/stylizedBush.js +2 -0
  159. package/src/vegetation/stylizedFlower.js +82 -0
  160. package/src/vegetation/stylizedFlowers.js +48 -7
  161. package/src/vegetation/stylizedForest.js +29 -1
  162. package/src/vegetation/stylizedGrass.js +291 -56
  163. package/src/vegetation/stylizedTree.js +38 -2
  164. package/src/vegetation/stylizedTreeFoliage.js +2 -1
  165. package/src/vegetation/vegetationShaders.js +1110 -0
  166. package/src/vfxgen/INTEGRATION.md +145 -0
  167. package/src/vfxgen/core/burstBackbone.js +380 -0
  168. package/src/vfxgen/core/projectileCore.js +92 -0
  169. package/src/vfxgen/core/spriteShapes.js +98 -0
  170. package/src/vfxgen/core/trailRibbon.js +272 -0
  171. package/src/vfxgen/core/vfxRandom.js +29 -0
  172. package/src/vfxgen/effects/emitHelpers.js +37 -0
  173. package/src/vfxgen/effects/magicEffects.js +162 -0
  174. package/src/vfxgen/effects/movementEffects.js +87 -0
  175. package/src/vfxgen/effects/weaponEffects.js +118 -0
  176. package/src/vfxgen/index.js +18 -0
  177. package/src/vfxgen/moves/moveController.js +146 -0
  178. package/src/vfxgen/moves/moveLibrary.js +335 -0
  179. package/src/vfxgen/vfxPresets.js +98 -0
  180. package/src/vfxgen/vfxSettings.js +384 -0
  181. package/src/vfxgen/vfxSystem.js +449 -0
  182. package/src/vfxgen/weapons/stylizedWeapons.js +137 -0
  183. package/src/villagegen/index.js +4 -0
  184. package/src/villagegen/stylizedVillage.js +490 -0
  185. package/src/villagegen/villageArchetypes.js +160 -0
  186. package/src/villagegen/villageNames.js +40 -0
  187. package/src/villagegen/villageSites.js +105 -0
  188. package/src/water/sceneOverrideLayers.js +23 -0
  189. package/src/water/water.js +5 -0
  190. package/src/water/waterBreakerSystem.js +15 -1
  191. package/src/water/waterCurrentField.js +447 -0
  192. package/src/water/waterMaterial.js +12 -0
  193. package/src/water/waterNearshorePhase.js +320 -0
  194. package/src/water/waterScenePasses.js +83 -30
  195. package/src/water/waterSettings.js +325 -13
  196. package/src/water/waterShoreMaterial.js +322 -0
  197. package/src/water/waterShoreStateField.js +605 -0
  198. package/src/water/waterSurface.js +797 -28
  199. package/src/weather/index.js +6 -0
  200. package/src/weather/weatherPrecipitation.js +221 -0
  201. package/src/weather/weatherPresets.js +258 -0
  202. package/src/weather/weatherSettings.js +269 -0
  203. package/src/weather/weatherSystem.js +871 -0
  204. package/src/worldMinimap.js +62 -0
  205. package/src/worldPresets.js +4 -1
@@ -0,0 +1,225 @@
1
+ import { parsePresetDocument } from '../core/presetDocuments.js';
2
+ import {
3
+ createGeneratorRecipeDocument,
4
+ deepMerge,
5
+ generateDomainValues,
6
+ hashSeed,
7
+ hashValue,
8
+ parseGeneratorRecipeDocument,
9
+ stableStringify,
10
+ validateGeneratorRecipeDocument,
11
+ } from '../core/generation.js';
12
+ import {
13
+ DEFAULT_MOTION_CLIP_SLOTS,
14
+ DEFAULT_MOTION_GRAPH,
15
+ createMotionClipSlots,
16
+ createMotionGraph,
17
+ validateMotionGraph,
18
+ } from './motionGraph.js';
19
+ import { createMotionSettings } from './motionSettings.js';
20
+
21
+ export const MOTION_PRESET_DOCUMENT_TYPE = 'toonlab/motion-preset';
22
+ export const MOTION_PRESET_SCHEMA_VERSION = 1;
23
+ export const MOTION_GENERATOR_DOCUMENT_TYPE = 'toonlab/motion-generator';
24
+
25
+ const plain = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
26
+ const cleanId = (value) => String(value ?? '').trim().replace(/[^a-zA-Z0-9._/-]+/g, '_');
27
+
28
+ /** Complete portable configuration shared by presets, recipes, Labs, and MCP. */
29
+ export function createMotionConfiguration(options = {}) {
30
+ const source = plain(options?.configuration) ? options.configuration : (plain(options) ? options : {});
31
+ return {
32
+ settings: createMotionSettings(source.settings),
33
+ graph: createMotionGraph(source.graph),
34
+ clipSlots: createMotionClipSlots(source.clipSlots),
35
+ };
36
+ }
37
+
38
+ export function validateMotionPresetDocument(input) {
39
+ const errors = [];
40
+ const warnings = [];
41
+ if (!plain(input)) return { errors: ['Motion preset must be a JSON object.'], ok: false, value: null, warnings };
42
+ if (input.type !== MOTION_PRESET_DOCUMENT_TYPE) errors.push(`Motion preset type must be "${MOTION_PRESET_DOCUMENT_TYPE}".`);
43
+ const version = Number(input.version ?? 1);
44
+ if (!Number.isInteger(version) || version < 1) errors.push('Motion preset version must be a positive integer.');
45
+ if (version > MOTION_PRESET_SCHEMA_VERSION) errors.push(`Motion preset version ${version} is newer than supported version ${MOTION_PRESET_SCHEMA_VERSION}.`);
46
+ const id = cleanId(input.id);
47
+ if (!id) errors.push('Motion preset id is required.');
48
+ const source = plain(input.configuration)
49
+ ? input.configuration
50
+ : { settings: input.settings, graph: input.graph, clipSlots: input.clipSlots };
51
+ const configuration = createMotionConfiguration(source);
52
+ const graphResult = validateMotionGraph(configuration.graph, { clipSlots: configuration.clipSlots });
53
+ errors.push(...graphResult.errors);
54
+ warnings.push(...graphResult.warnings);
55
+ return {
56
+ errors,
57
+ ok: errors.length === 0,
58
+ value: errors.length ? null : {
59
+ type: MOTION_PRESET_DOCUMENT_TYPE,
60
+ version: MOTION_PRESET_SCHEMA_VERSION,
61
+ id,
62
+ label: String(input.label || id),
63
+ description: String(input.description ?? ''),
64
+ configuration,
65
+ ...(plain(input.generation) ? { generation: {
66
+ recipeId: cleanId(input.generation.recipeId),
67
+ seed: hashSeed(input.generation.seed ?? 1),
68
+ signature: String(input.generation.signature ?? ''),
69
+ } } : {}),
70
+ },
71
+ warnings: [...new Set(warnings)],
72
+ };
73
+ }
74
+
75
+ export function createMotionPresetDocument(id, definition = {}) {
76
+ const source = plain(definition) ? definition : {};
77
+ const result = validateMotionPresetDocument({
78
+ type: MOTION_PRESET_DOCUMENT_TYPE,
79
+ version: MOTION_PRESET_SCHEMA_VERSION,
80
+ id: id ?? source.id,
81
+ label: source.label ?? source.name ?? id,
82
+ description: source.description ?? '',
83
+ configuration: createMotionConfiguration(source.configuration ?? source),
84
+ ...(source.generation ? { generation: source.generation } : {}),
85
+ });
86
+ if (!result.ok) throw new Error(result.errors.join(' '));
87
+ return result.value;
88
+ }
89
+
90
+ export function parseMotionPresetDocument(input) {
91
+ return parsePresetDocument(input, validateMotionPresetDocument, { invalidJsonLabel: 'motion preset' });
92
+ }
93
+
94
+ export function serializeMotionPresetDocument(idOrDocument, definition = {}, { pretty = true } = {}) {
95
+ const document = plain(idOrDocument)
96
+ ? createMotionPresetDocument(idOrDocument.id, idOrDocument)
97
+ : createMotionPresetDocument(idOrDocument, definition);
98
+ return stableStringify(document, pretty ? 2 : 0);
99
+ }
100
+
101
+ /** Wrapper around the shared generator schema with motion-specific sanitation. */
102
+ export function validateMotionGeneratorRecipeDocument(input) {
103
+ const result = validateGeneratorRecipeDocument(input, {
104
+ domain: 'motion',
105
+ sanitizeConfiguration: createMotionConfiguration,
106
+ });
107
+ if (!result.ok) return result;
108
+ const graphResult = validateMotionGraph(result.value.configuration.graph, {
109
+ clipSlots: result.value.configuration.clipSlots,
110
+ });
111
+ return {
112
+ ...result,
113
+ errors: [...result.errors, ...graphResult.errors],
114
+ ok: result.ok && graphResult.ok,
115
+ value: graphResult.ok ? result.value : null,
116
+ warnings: [...new Set([...result.warnings, ...graphResult.warnings])],
117
+ };
118
+ }
119
+
120
+ export function createMotionGeneratorRecipeDocument(id, definition = {}) {
121
+ const document = createGeneratorRecipeDocument('motion', id, {
122
+ ...definition,
123
+ configuration: createMotionConfiguration(definition.configuration ?? definition),
124
+ }, { sanitizeConfiguration: createMotionConfiguration });
125
+ const result = validateMotionGeneratorRecipeDocument(document);
126
+ if (!result.ok) throw new Error(result.errors.join(' '));
127
+ return result.value;
128
+ }
129
+
130
+ export function parseMotionGeneratorRecipeDocument(input) {
131
+ const parsed = parseGeneratorRecipeDocument(input, {
132
+ domain: 'motion',
133
+ sanitizeConfiguration: createMotionConfiguration,
134
+ });
135
+ return parsed.ok ? validateMotionGeneratorRecipeDocument(parsed.value) : parsed;
136
+ }
137
+
138
+ export function serializeMotionGeneratorRecipeDocument(idOrDocument, definition = {}, { pretty = true } = {}) {
139
+ const document = plain(idOrDocument)
140
+ ? createMotionGeneratorRecipeDocument(idOrDocument.id, idOrDocument)
141
+ : createMotionGeneratorRecipeDocument(idOrDocument, definition);
142
+ return stableStringify(document, pretty ? 2 : 0);
143
+ }
144
+
145
+ export const DEFAULT_MOTION_GENERATOR_DOMAINS = Object.freeze({
146
+ settings: Object.freeze({
147
+ playback: Object.freeze({
148
+ cadence: Object.freeze({ $type: 'choice', options: Object.freeze([
149
+ Object.freeze({ value: 'smooth', weight: 3 }),
150
+ Object.freeze({ value: 'stepped', weight: 2 }),
151
+ ]) }),
152
+ sampleRate: Object.freeze({ $type: 'range', min: 10, max: 30, integer: true }),
153
+ speed: Object.freeze({ $type: 'range', min: 0.88, max: 1.16, step: 0.01 }),
154
+ }),
155
+ transitions: Object.freeze({
156
+ duration: Object.freeze({ $type: 'range', min: 0.08, max: 0.32, step: 0.01 }),
157
+ }),
158
+ lean: Object.freeze({
159
+ maxAngle: Object.freeze({ $type: 'range', min: 0.08, max: 0.32, step: 0.01 }),
160
+ response: Object.freeze({ $type: 'range', min: 6, max: 18, step: 0.5 }),
161
+ }),
162
+ bob: Object.freeze({
163
+ amplitude: Object.freeze({ $type: 'range', min: 0.012, max: 0.075, step: 0.001 }),
164
+ frequency: Object.freeze({ $type: 'range', min: 1.2, max: 2.8, step: 0.05 }),
165
+ lateral: Object.freeze({ $type: 'range', min: 0, max: 0.035, step: 0.001 }),
166
+ }),
167
+ squash: Object.freeze({
168
+ amount: Object.freeze({ $type: 'range', min: 0.02, max: 0.16, step: 0.005 }),
169
+ response: Object.freeze({ $type: 'range', min: 8, max: 24, step: 0.5 }),
170
+ }),
171
+ }),
172
+ });
173
+
174
+ export function createDefaultMotionGeneratorRecipe(options = {}) {
175
+ return createMotionGeneratorRecipeDocument(options.id ?? 'motion-family', {
176
+ label: options.label ?? 'Generative Motion Family',
177
+ description: options.description ?? 'An unrestricted motion graph with generated timing and presentation style.',
178
+ seed: options.seed ?? 2027,
179
+ configuration: {
180
+ settings: options.settings,
181
+ graph: options.graph ?? DEFAULT_MOTION_GRAPH,
182
+ clipSlots: options.clipSlots ?? DEFAULT_MOTION_CLIP_SLOTS,
183
+ },
184
+ domains: options.domains ?? DEFAULT_MOTION_GENERATOR_DOMAINS,
185
+ locks: options.locks ?? [],
186
+ });
187
+ }
188
+
189
+ /** Resolves one deterministic seed from an unlimited recipe family. */
190
+ export function resolveMotionGeneratorRecipe(input, {
191
+ seed = undefined,
192
+ current = undefined,
193
+ baseConfiguration = undefined,
194
+ resolveBasePreset = null,
195
+ presetId = undefined,
196
+ label = undefined,
197
+ } = {}) {
198
+ const validation = validateMotionGeneratorRecipeDocument(input);
199
+ if (!validation.ok) throw new Error(validation.errors.join(' '));
200
+ const recipe = validation.value;
201
+ const resolvedSeed = hashSeed(seed ?? recipe.seed);
202
+ let inherited = baseConfiguration ? createMotionConfiguration(baseConfiguration) : createMotionConfiguration();
203
+ if (recipe.basePreset && typeof resolveBasePreset === 'function') {
204
+ const base = resolveBasePreset(recipe.basePreset);
205
+ if (base) inherited = createMotionConfiguration(base.configuration ?? base);
206
+ }
207
+ const existing = createMotionConfiguration(current ?? recipe.configuration);
208
+ const generated = generateDomainValues(recipe.domains, {
209
+ current: existing,
210
+ locks: recipe.locks,
211
+ seed: resolvedSeed,
212
+ });
213
+ const configuration = createMotionConfiguration(deepMerge(inherited, recipe.configuration, generated));
214
+ const signature = hashValue(configuration);
215
+ return createMotionPresetDocument(presetId ?? `${recipe.id}-${resolvedSeed}`, {
216
+ label: label ?? `${recipe.label} · ${resolvedSeed}`,
217
+ description: recipe.description,
218
+ configuration,
219
+ generation: { recipeId: recipe.id, seed: resolvedSeed, signature },
220
+ });
221
+ }
222
+
223
+ export function motionConfigurationSignature(configuration) {
224
+ return hashValue(createMotionConfiguration(configuration));
225
+ }
@@ -0,0 +1,307 @@
1
+ import { cloneSerializable } from '../core/generation.js';
2
+
3
+ export const MOTION_BLEND_NODE_TYPES = Object.freeze(['clip', 'blend1d', 'blend2d', 'weighted']);
4
+ export const MOTION_LAYER_MODES = Object.freeze(['additive', 'override']);
5
+ export const MOTION_PARAMETER_TYPES = Object.freeze(['number', 'boolean', 'trigger']);
6
+ export const MOTION_CONDITION_OPERATORS = Object.freeze(['>', '>=', '<', '<=', '==', '!=', 'truthy', 'falsy', 'triggered']);
7
+
8
+ const plain = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
9
+ const finite = (value, fallback) => Number.isFinite(Number(value)) ? Number(value) : fallback;
10
+ const cleanId = (value, fallback = '') => String(value ?? fallback).trim();
11
+
12
+ export const DEFAULT_MOTION_CLIP_SLOTS = Object.freeze({
13
+ idle: Object.freeze({ source: 'preview/idle', loop: true, speed: 1, events: Object.freeze([]) }),
14
+ walk: Object.freeze({ source: 'preview/walk', loop: true, speed: 1, events: Object.freeze([
15
+ Object.freeze({ time: 0.1, name: 'footstep', payload: Object.freeze({ foot: 'left' }) }),
16
+ Object.freeze({ time: 0.6, name: 'footstep', payload: Object.freeze({ foot: 'right' }) }),
17
+ ]) }),
18
+ run: Object.freeze({ source: 'preview/run', loop: true, speed: 1, events: Object.freeze([
19
+ Object.freeze({ time: 0.05, name: 'footstep', payload: Object.freeze({ foot: 'left' }) }),
20
+ Object.freeze({ time: 0.38, name: 'footstep', payload: Object.freeze({ foot: 'right' }) }),
21
+ ]) }),
22
+ airborne: Object.freeze({ source: 'preview/airborne', loop: true, speed: 1, events: Object.freeze([]) }),
23
+ breathe: Object.freeze({ source: 'preview/breathe', loop: true, speed: 1, events: Object.freeze([]) }),
24
+ });
25
+
26
+ export const DEFAULT_MOTION_GRAPH = Object.freeze({
27
+ id: 'responsive-locomotion',
28
+ initial: 'locomotion',
29
+ parameters: Object.freeze({
30
+ speed: Object.freeze({ type: 'number', default: 0 }),
31
+ turn: Object.freeze({ type: 'number', default: 0 }),
32
+ verticalSpeed: Object.freeze({ type: 'number', default: 0 }),
33
+ grounded: Object.freeze({ type: 'boolean', default: true }),
34
+ }),
35
+ states: Object.freeze({
36
+ locomotion: Object.freeze({
37
+ node: Object.freeze({
38
+ type: 'blend1d',
39
+ parameter: 'speed',
40
+ children: Object.freeze([
41
+ Object.freeze({ threshold: 0, slot: 'idle' }),
42
+ Object.freeze({ threshold: 0.45, slot: 'walk' }),
43
+ Object.freeze({ threshold: 1, slot: 'run' }),
44
+ ]),
45
+ }),
46
+ layers: Object.freeze([
47
+ Object.freeze({ id: 'breathing', mode: 'additive', node: Object.freeze({ type: 'clip', slot: 'breathe' }), weight: 0.3, mask: Object.freeze(['spine', 'chest', 'head']) }),
48
+ ]),
49
+ transitions: Object.freeze([
50
+ Object.freeze({ to: 'air', conditions: Object.freeze([{ parameter: 'grounded', op: 'falsy' }]), duration: 0.1 }),
51
+ ]),
52
+ }),
53
+ air: Object.freeze({
54
+ node: Object.freeze({ type: 'clip', slot: 'airborne' }),
55
+ transitions: Object.freeze([
56
+ Object.freeze({ to: 'locomotion', conditions: Object.freeze([{ parameter: 'grounded', op: 'truthy' }]), duration: 0.12 }),
57
+ ]),
58
+ layers: Object.freeze([]),
59
+ }),
60
+ }),
61
+ });
62
+
63
+ function normalizeParameter(value) {
64
+ const source = plain(value) ? value : { default: value };
65
+ const inferredType = typeof source.default === 'boolean' ? 'boolean' : 'number';
66
+ const type = MOTION_PARAMETER_TYPES.includes(source.type) ? source.type : inferredType;
67
+ const fallback = type === 'boolean' || type === 'trigger' ? false : 0;
68
+ return {
69
+ type,
70
+ default: type === 'boolean' || type === 'trigger'
71
+ ? Boolean(source.default ?? fallback)
72
+ : finite(source.default, fallback),
73
+ ...(Number.isFinite(Number(source.min)) ? { min: Number(source.min) } : {}),
74
+ ...(Number.isFinite(Number(source.max)) ? { max: Number(source.max) } : {}),
75
+ };
76
+ }
77
+
78
+ function childNode(source) {
79
+ if (plain(source?.node)) return normalizeBlendNode(source.node);
80
+ if (source?.slot !== undefined) return normalizeBlendNode({ type: 'clip', slot: source.slot });
81
+ return normalizeBlendNode({ type: 'clip', slot: '' });
82
+ }
83
+
84
+ /** Normalizes an arbitrary recursive clip/blend node. */
85
+ export function normalizeBlendNode(value = {}) {
86
+ const source = plain(value) ? value : { type: 'clip', slot: String(value ?? '') };
87
+ const type = MOTION_BLEND_NODE_TYPES.includes(source.type) ? source.type : 'clip';
88
+ if (type === 'clip') {
89
+ return {
90
+ type,
91
+ slot: cleanId(source.slot ?? source.clip),
92
+ speed: Math.max(0, finite(source.speed, 1)),
93
+ phase: finite(source.phase, 0),
94
+ };
95
+ }
96
+ if (type === 'blend1d') {
97
+ const children = (Array.isArray(source.children) ? source.children : [])
98
+ .map((entry, index) => ({
99
+ threshold: finite(entry?.threshold, index),
100
+ node: childNode(entry),
101
+ }))
102
+ .sort((a, b) => a.threshold - b.threshold);
103
+ return {
104
+ type,
105
+ parameter: cleanId(source.parameter, 'value'),
106
+ children,
107
+ };
108
+ }
109
+ if (type === 'blend2d') {
110
+ return {
111
+ type,
112
+ parameterX: cleanId(source.parameterX ?? source.parameters?.[0], 'x'),
113
+ parameterY: cleanId(source.parameterY ?? source.parameters?.[1], 'y'),
114
+ children: (Array.isArray(source.children) ? source.children : []).map((entry) => ({
115
+ x: finite(entry?.x ?? entry?.position?.[0], 0),
116
+ y: finite(entry?.y ?? entry?.position?.[1], 0),
117
+ node: childNode(entry),
118
+ })),
119
+ };
120
+ }
121
+ return {
122
+ type,
123
+ children: (Array.isArray(source.children) ? source.children : []).map((entry) => ({
124
+ node: childNode(entry),
125
+ weight: Math.max(0, finite(entry?.weight, 1)),
126
+ weightParameter: cleanId(entry?.weightParameter),
127
+ })),
128
+ };
129
+ }
130
+
131
+ function normalizeCondition(value) {
132
+ if (!plain(value)) return { parameter: cleanId(value), op: 'truthy' };
133
+ if (Array.isArray(value.all)) return { all: value.all.map(normalizeCondition) };
134
+ if (Array.isArray(value.any)) return { any: value.any.map(normalizeCondition) };
135
+ if (value.not !== undefined) return { not: normalizeCondition(value.not) };
136
+ return {
137
+ parameter: cleanId(value.parameter ?? value.param),
138
+ op: MOTION_CONDITION_OPERATORS.includes(value.op) ? value.op : 'truthy',
139
+ ...(Object.hasOwn(value, 'value') ? { value: cloneSerializable(value.value) } : {}),
140
+ };
141
+ }
142
+
143
+ function normalizeTransition(value, index) {
144
+ const source = plain(value) ? value : { to: value };
145
+ const conditions = Array.isArray(source.conditions)
146
+ ? source.conditions.map(normalizeCondition)
147
+ : source.when !== undefined
148
+ ? [normalizeCondition(source.when)]
149
+ : [];
150
+ return {
151
+ id: cleanId(source.id, `transition-${index}`),
152
+ to: cleanId(source.to),
153
+ conditions,
154
+ duration: source.duration === undefined ? -1 : Math.max(0, finite(source.duration, 0)),
155
+ priority: finite(source.priority, 0),
156
+ exitTime: source.exitTime === undefined ? null : Math.min(Math.max(finite(source.exitTime, 0), 0), 1),
157
+ interruptible: source.interruptible === undefined ? null : Boolean(source.interruptible),
158
+ syncPhase: source.syncPhase === undefined ? null : Boolean(source.syncPhase),
159
+ };
160
+ }
161
+
162
+ function normalizeLayer(value, index) {
163
+ const source = plain(value) ? value : {};
164
+ return {
165
+ id: cleanId(source.id, `layer-${index}`),
166
+ mode: MOTION_LAYER_MODES.includes(source.mode) ? source.mode : 'additive',
167
+ node: normalizeBlendNode(source.node ?? source.blend ?? source.motion ?? {}),
168
+ weight: Math.min(Math.max(finite(source.weight, 1), 0), 1),
169
+ weightParameter: cleanId(source.weightParameter),
170
+ enabledParameter: cleanId(source.enabledParameter),
171
+ mask: Array.isArray(source.mask) ? source.mask.map(String) : [],
172
+ };
173
+ }
174
+
175
+ function normalizeState(id, value) {
176
+ const source = plain(value) ? value : {};
177
+ return {
178
+ id,
179
+ node: normalizeBlendNode(source.node ?? source.blend ?? source.motion ?? source),
180
+ speed: Math.max(0, finite(source.speed, 1)),
181
+ transitions: (Array.isArray(source.transitions) ? source.transitions : [])
182
+ .map(normalizeTransition)
183
+ .sort((a, b) => b.priority - a.priority),
184
+ layers: (Array.isArray(source.layers) ? source.layers : []).map(normalizeLayer),
185
+ tags: Array.isArray(source.tags) ? source.tags.map(String) : [],
186
+ };
187
+ }
188
+
189
+ /** Creates a graph with arbitrary state ids, topology, parameters, and layers. */
190
+ export function createMotionGraph(options = DEFAULT_MOTION_GRAPH) {
191
+ const source = plain(options) ? options : {};
192
+ const rawStates = plain(source.states) ? source.states : {};
193
+ const states = Object.fromEntries(Object.entries(rawStates)
194
+ .filter(([id]) => cleanId(id))
195
+ .map(([id, state]) => [cleanId(id), normalizeState(cleanId(id), state)]));
196
+ const firstState = Object.keys(states)[0] ?? '';
197
+ return {
198
+ id: cleanId(source.id, 'motion-graph'),
199
+ initial: Object.hasOwn(states, source.initial) ? source.initial : firstState,
200
+ parameters: Object.fromEntries(Object.entries(plain(source.parameters) ? source.parameters : {})
201
+ .filter(([id]) => cleanId(id))
202
+ .map(([id, parameter]) => [cleanId(id), normalizeParameter(parameter)])),
203
+ states,
204
+ };
205
+ }
206
+
207
+ function normalizeEvent(value, index) {
208
+ const source = plain(value) ? value : { name: value };
209
+ return {
210
+ id: cleanId(source.id, `event-${index}`),
211
+ name: cleanId(source.name ?? source.type, 'event'),
212
+ time: Math.max(0, finite(source.time ?? source.at, 0)),
213
+ normalized: Boolean(source.normalized),
214
+ once: Boolean(source.once),
215
+ payload: cloneSerializable(plain(source.payload) ? source.payload : {}),
216
+ };
217
+ }
218
+
219
+ /** Creates serializable slot bindings independently from graph topology. */
220
+ export function createMotionClipSlots(options = DEFAULT_MOTION_CLIP_SLOTS) {
221
+ const source = plain(options) ? options : {};
222
+ return Object.fromEntries(Object.entries(source)
223
+ .filter(([id]) => cleanId(id))
224
+ .map(([id, value]) => {
225
+ const slot = plain(value) ? value : { source: value };
226
+ return [cleanId(id), {
227
+ source: cloneSerializable(slot.source ?? slot.clip ?? id),
228
+ loop: slot.loop === undefined ? true : Boolean(slot.loop),
229
+ speed: Math.max(0, finite(slot.speed, 1)),
230
+ phase: finite(slot.phase, 0),
231
+ events: (Array.isArray(slot.events) ? slot.events : []).map(normalizeEvent).sort((a, b) => a.time - b.time),
232
+ metadata: cloneSerializable(plain(slot.metadata) ? slot.metadata : {}),
233
+ }];
234
+ }));
235
+ }
236
+
237
+ function visitNode(node, visit) {
238
+ visit(node);
239
+ for (const child of node.children ?? []) visitNode(child.node, visit);
240
+ }
241
+
242
+ export function collectMotionGraphSlots(graph) {
243
+ const output = new Set();
244
+ const normalized = createMotionGraph(graph);
245
+ for (const state of Object.values(normalized.states)) {
246
+ visitNode(state.node, (node) => {
247
+ if (node.type === 'clip' && node.slot) output.add(node.slot);
248
+ });
249
+ for (const layer of state.layers) visitNode(layer.node, (node) => {
250
+ if (node.type === 'clip' && node.slot) output.add(node.slot);
251
+ });
252
+ }
253
+ return [...output];
254
+ }
255
+
256
+ /** Structural validation. Missing slot bindings are warnings for graceful asset loading. */
257
+ export function validateMotionGraph(input, { clipSlots = null } = {}) {
258
+ const errors = [];
259
+ const warnings = [];
260
+ if (!plain(input)) return { errors: ['Motion graph must be an object.'], ok: false, value: null, warnings };
261
+ const graph = createMotionGraph(input);
262
+ const stateIds = new Set(Object.keys(graph.states));
263
+ if (stateIds.size === 0) errors.push('Motion graph must contain at least one state.');
264
+ if (!stateIds.has(graph.initial)) errors.push(`Initial state "${graph.initial}" does not exist.`);
265
+ for (const state of Object.values(graph.states)) {
266
+ for (const transition of state.transitions) {
267
+ if (!stateIds.has(transition.to)) errors.push(`State "${state.id}" transitions to missing state "${transition.to}".`);
268
+ for (const condition of transition.conditions) {
269
+ const queue = [condition];
270
+ while (queue.length) {
271
+ const current = queue.pop();
272
+ if (current?.parameter && !Object.hasOwn(graph.parameters, current.parameter)) {
273
+ warnings.push(`Transition "${transition.id}" reads undeclared parameter "${current.parameter}".`);
274
+ }
275
+ queue.push(...(current?.all ?? []), ...(current?.any ?? []));
276
+ if (current?.not) queue.push(current.not);
277
+ }
278
+ }
279
+ }
280
+ }
281
+ if (clipSlots) {
282
+ const slots = createMotionClipSlots(clipSlots);
283
+ for (const id of collectMotionGraphSlots(graph)) {
284
+ if (!Object.hasOwn(slots, id)) warnings.push(`Graph references unbound clip slot "${id}".`);
285
+ }
286
+ }
287
+ return { errors, ok: errors.length === 0, value: errors.length ? null : graph, warnings: [...new Set(warnings)] };
288
+ }
289
+
290
+ export function evaluateMotionCondition(condition, parameters, triggers = new Set()) {
291
+ if (condition?.all) return condition.all.every((entry) => evaluateMotionCondition(entry, parameters, triggers));
292
+ if (condition?.any) return condition.any.some((entry) => evaluateMotionCondition(entry, parameters, triggers));
293
+ if (condition?.not) return !evaluateMotionCondition(condition.not, parameters, triggers);
294
+ const value = parameters?.[condition?.parameter];
295
+ switch (condition?.op) {
296
+ case '>': return Number(value) > Number(condition.value);
297
+ case '>=': return Number(value) >= Number(condition.value);
298
+ case '<': return Number(value) < Number(condition.value);
299
+ case '<=': return Number(value) <= Number(condition.value);
300
+ case '==': return value === condition.value;
301
+ case '!=': return value !== condition.value;
302
+ case 'falsy': return !value;
303
+ case 'triggered': return triggers.has(condition.parameter);
304
+ case 'truthy':
305
+ default: return Boolean(value);
306
+ }
307
+ }