@tora-editor/tora 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 (73) hide show
  1. package/README.md +108 -58
  2. package/assets/free-audio/arcade-pop/audio/loss.wav +0 -0
  3. package/assets/free-audio/arcade-pop/audio/reward.wav +0 -0
  4. package/assets/free-audio/arcade-pop/audio/win.wav +0 -0
  5. package/assets/free-audio/arcade-pop/source/INFO.txt +11 -11
  6. package/assets/kenney-food-starter/License.txt +28 -0
  7. package/assets/kenney-food-starter/burger.glb +0 -0
  8. package/assets/kenney-food-starter/frying-pan.glb +0 -0
  9. package/assets/kenney-food-starter/plan.json +61 -0
  10. package/assets/kenney-food-starter/plate.glb +0 -0
  11. package/assets/kenney-food-starter/pot.glb +0 -0
  12. package/assets/kenney-harvest/audio/victory.wav +0 -0
  13. package/assets/kenney-harvest/source/music-jingles/OGG/jingles_NES/jingles_NES03.ogg +0 -0
  14. package/assets/kenney-harvest/source/music-jingles/OGG/jingles_PIZZA/jingles_PIZZA03.ogg +0 -0
  15. package/assets/kenney-harvest/source/music-jingles/license.txt +14 -0
  16. package/bin/tora.mjs +77 -9
  17. package/crates/packer/trusted/native-3d-meta.json +3 -2
  18. package/crates/packer/trusted/native-3d.js +181 -181
  19. package/crates/packer/trusted/native-meta.json +2 -2
  20. package/crates/packer/trusted/native.js +5 -5
  21. package/crates/packer/trusted/release-manifest.json +17 -17
  22. package/crates/packer/trusted/review-runtime-meta.json +3 -2
  23. package/crates/packer/trusted/review-runtime.js +182 -182
  24. package/docs/TORA_AGENT_SETUP.md +24 -13
  25. package/docs/TORA_CREATION_API.md +29 -12
  26. package/docs/reference/CORE_AUTHORING.md +2 -1
  27. package/docs/reference/PLAYABLE_STARTERS.md +20 -0
  28. package/docs/reference/packs/3d.md +9 -3
  29. package/network-rules/mintegral-appgrowth-single-html.json +10 -10
  30. package/package.json +6 -6
  31. package/packages/creative-project/project-v21.schema.json +264 -8
  32. package/scripts/lean/editor/review-editor.css +10 -0
  33. package/scripts/lean/editor/review-editor.js +117 -1
  34. package/scripts/lean/native/agent-tools.mjs +7 -7
  35. package/scripts/lean/native/api.mjs +16 -5
  36. package/scripts/lean/native/asset-catalog.mjs +7 -6
  37. package/scripts/lean/native/asset-lineage.mjs +54 -0
  38. package/scripts/lean/native/asset-prep.mjs +173 -40
  39. package/scripts/lean/native/assets.mjs +107 -11
  40. package/scripts/lean/native/author-expansion-proofs.mjs +2 -99
  41. package/scripts/lean/native/author-fps.mjs +545 -0
  42. package/scripts/lean/native/author-primitive-proofs.mjs +5 -4
  43. package/scripts/lean/native/build-cache.mjs +2 -2
  44. package/scripts/lean/native/cc0-inputs.mjs +24 -0
  45. package/scripts/lean/native/cc0-staging.mjs +28 -8
  46. package/scripts/lean/native/check-harvest-outcome-audio.mjs +7 -8
  47. package/scripts/lean/native/check-salvage.mjs +8 -5
  48. package/scripts/lean/native/compiler.mjs +9 -3
  49. package/scripts/lean/native/contracts.mjs +11 -8
  50. package/scripts/lean/native/creative-qa.mjs +305 -122
  51. package/scripts/lean/native/demos.mjs +47 -3
  52. package/scripts/lean/native/document.mjs +36 -10
  53. package/scripts/lean/native/export-budget.mjs +75 -0
  54. package/scripts/lean/native/glb-loader.mjs +468 -0
  55. package/scripts/lean/native/intake-creator-tools.mjs +83 -30
  56. package/scripts/lean/native/local-bundle.mjs +5 -3
  57. package/scripts/lean/native/mcp-server.mjs +33 -46
  58. package/scripts/lean/native/media-validate.mjs +124 -0
  59. package/scripts/lean/native/native-bin.mjs +3 -3
  60. package/scripts/lean/native/outcome-playthrough.mjs +97 -0
  61. package/scripts/lean/native/prepare-fps-assets.mjs +330 -0
  62. package/scripts/lean/native/project-bundle.mjs +3 -3
  63. package/scripts/lean/native/remote-cc0-fetcher.mjs +403 -197
  64. package/scripts/lean/native/review-agent-tools.mjs +2 -2
  65. package/scripts/lean/native/review.mjs +3 -0
  66. package/scripts/lean/native/runtime.mjs +242 -56
  67. package/scripts/lean/native/schema.mjs +7 -5
  68. package/scripts/lean/native/service.mjs +159 -32
  69. package/scripts/lean/native/stage-3d.mjs +343 -40
  70. package/scripts/lean/native/starters.mjs +436 -0
  71. package/scripts/lean/native/verify.mjs +1 -1
  72. package/scripts/lean/native/win-cues.mjs +96 -0
  73. package/skills/tora-playables/SKILL.md +1 -1
@@ -1,11 +1,43 @@
1
1
  /* global atob,document,Image */
2
+ import {parseGlb, cloneModelTemplate, createModelAnimator} from './glb-loader.mjs';
2
3
  import {
3
4
  Scene, Color, PerspectiveCamera, WebGLRenderer, BufferGeometry, Float32BufferAttribute,
4
5
  Mesh, InstancedMesh, Matrix4, MeshLambertMaterial, MeshBasicMaterial, DirectionalLight, HemisphereLight, Group,
5
6
  BoxGeometry, CylinderGeometry, SphereGeometry, RingGeometry, CircleGeometry, Shape, Path,
6
7
  ShapeGeometry, Texture, SRGBColorSpace, Vector3, Vector2, Plane, Raycaster, PCFSoftShadowMap, DoubleSide,
8
+ NoColorSpace, NoToneMapping, ACESFilmicToneMapping, NeutralToneMapping, DataTexture,
9
+ EquirectangularReflectionMapping, PMREMGenerator, RepeatWrapping, Euler, Object3D,
7
10
  } from 'three';
8
11
 
12
+ export function contactOrigin3d(component, object, props, bodies){
13
+ const origin = new Vector3();
14
+ const local = new Vector3();
15
+ const rotation = new Euler();
16
+ for(let mesh = component; mesh?.contract === 'native.mesh3d.v1'; mesh = object(mesh.parentId)){
17
+ const p = props(mesh);
18
+ const body = bodies.get(mesh.id);
19
+ const dynamic = body?.mode === 'dynamic';
20
+ const captured = dynamic && body.captured;
21
+ const progress = captured ? Math.min(1, (body.captureElapsed ?? 0) / .55) : 0;
22
+ const target = body?.captureTarget;
23
+ const scale = 1 - progress * .65;
24
+ local.set(p.sx * scale, p.sy * scale, p.sz * scale);
25
+ rotation.set(
26
+ dynamic ? -(body.spin ?? 0) : p.rx,
27
+ body?.mode === 'kinematic' ? -(body.angle ?? p.ry) : p.ry,
28
+ dynamic ? (body.spin ?? 0) * .22 : p.rz,
29
+ );
30
+ origin.multiply(local).applyEuler(rotation);
31
+ local.set(
32
+ (body?.x ?? p.x) + (captured && target ? (target.x - body.x) * progress : 0),
33
+ (body?.y ?? p.y) - progress * .45,
34
+ (body?.z ?? p.z) + (captured && target ? (target.z - body.z) * progress : 0),
35
+ );
36
+ origin.add(local);
37
+ }
38
+ return {x:origin.x,y:origin.y,z:origin.z};
39
+ }
40
+
9
41
  function decodeToraMesh(base64) {
10
42
  const bin = atob(base64);
11
43
  const bytes = new Uint8Array(bin.length);
@@ -225,10 +257,63 @@ function waveFlagGeometry(geometry, rest, time) {
225
257
  geometry.computeVertexNormals();
226
258
  }
227
259
 
260
+ function studioEnvironment(renderer) {
261
+ const w = 64, h = 32, pixels = new Uint8Array(w * h * 4);
262
+ for (let y = 0; y < h; y++) {
263
+ const elevation = y / (h - 1);
264
+ for (let x = 0; x < w; x++) {
265
+ const u = x / w, i = (y * w + x) * 4;
266
+ const key = Math.exp(-((u - 0.35) ** 2 / 0.012 + (elevation - 0.7) ** 2 / 0.018));
267
+ const rim = Math.exp(-((u - 0.79) ** 2 / 0.004 + (elevation - 0.58) ** 2 / 0.055));
268
+ pixels[i] = Math.min(255, 21 + elevation * 90 + key * 180 + rim * 125);
269
+ pixels[i + 1] = Math.min(255, 22 + elevation * 105 + key * 158 + rim * 145);
270
+ pixels[i + 2] = Math.min(255, 24 + elevation * 127 + key * 128 + rim * 180);
271
+ pixels[i + 3] = 255;
272
+ }
273
+ }
274
+ const texture = new DataTexture(pixels, w, h);
275
+ texture.mapping = EquirectangularReflectionMapping;
276
+ texture.needsUpdate = true;
277
+ const generator = new PMREMGenerator(renderer);
278
+ try { return generator.fromEquirectangular(texture); }
279
+ finally { generator.dispose(); texture.dispose(); }
280
+ }
281
+
228
282
  /** Manages one Three.js WebGL2 offscreen canvas per active native.stage3d.v1 component. */
229
- export function createStage3dManager(project, assetsMap, onTextureReady) {
283
+ export function createStage3dManager(project, assetsMap, onTextureReady, overrides = new Map()) {
230
284
  const meshCache = new Map();
231
- const textureCache = new Map();
285
+ const textureCache = new Map(), modelCache = new Map();
286
+ const sharedGeometry = new Set(), sharedMaterials = new Set();
287
+ let environment;
288
+
289
+ function dirtyTextures() {
290
+ for (const stage of stages.values()) stage.textureDirty = true;
291
+ onTextureReady?.();
292
+ }
293
+
294
+ function getModel(asset) {
295
+ if (!modelCache.has(asset.hash ?? asset.id)) {
296
+ const bytes = Uint8Array.from(atob(asset.data), char => char.charCodeAt(0));
297
+ const model = parseGlb(bytes, dirtyTextures);
298
+ for (const geometry of model.geometries) sharedGeometry.add(geometry);
299
+ for (const material of model.materials) sharedMaterials.add(material);
300
+ modelCache.set(asset.hash ?? asset.id, model);
301
+ }
302
+ return modelCache.get(asset.hash ?? asset.id);
303
+ }
304
+
305
+ function disposeTree(root) {
306
+ const geometry = new Set(), materials = new Set();
307
+ root.traverse(obj => {
308
+ if (obj.geometry && !sharedGeometry.has(obj.geometry)) geometry.add(obj.geometry);
309
+ if (obj.material) for (const mat of Array.isArray(obj.material) ? obj.material : [obj.material]) {
310
+ if (!sharedMaterials.has(mat)) materials.add(mat);
311
+ }
312
+ });
313
+ for (const geo of geometry) geo.dispose();
314
+ for (const mat of materials) mat.dispose();
315
+ }
316
+
232
317
  const stages = new Map();
233
318
  let sharedGlCanvas, sharedRenderer, sharedCacheCanvas, sharedCacheCtx, sharedStageId;
234
319
 
@@ -270,17 +355,23 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
270
355
  if (!asset || asset.mime !== 'model/tora-mesh' || !asset.data) return undefined;
271
356
  const geo = decodeToraMesh(asset.data);
272
357
  meshCache.set(assetId, geo);
358
+ sharedGeometry.add(geo);
273
359
  return geo;
274
360
  }
275
361
 
276
- function getTexture(assetId) {
362
+ function getTexture(assetId, usage) {
277
363
  if (!assetId) return undefined;
278
- if (textureCache.has(assetId)) return textureCache.get(assetId);
364
+ const key = (usage ?? 'stage') + ':' + assetId;
365
+ if (textureCache.has(key)) return textureCache.get(key);
279
366
  const asset = assetsMap.get(assetId);
280
367
  if (!asset || !asset.mime.startsWith('image/') || !asset.data) return undefined;
281
368
  const img = new Image();
282
369
  const tex = new Texture(img);
283
- tex.colorSpace = SRGBColorSpace;
370
+ tex.colorSpace = usage === 'normalMap' ? NoColorSpace : SRGBColorSpace;
371
+ if (usage) {
372
+ tex.flipY = false;
373
+ tex.wrapS = tex.wrapT = RepeatWrapping;
374
+ }
284
375
  const markLoaded = notify => {
285
376
  tex.needsUpdate = true;
286
377
  for (const entry of stages.values()) {
@@ -299,7 +390,7 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
299
390
  }
300
391
  if (notify) onTextureReady?.();
301
392
  };
302
- textureCache.set(assetId, tex);
393
+ textureCache.set(key, tex);
303
394
  img.onload = () => markLoaded(true);
304
395
  img.src = 'data:' + asset.mime + ';base64,' + asset.data;
305
396
  if (img.complete && img.naturalWidth) markLoaded(false);
@@ -319,11 +410,17 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
319
410
  sun.position.set(p.sunX ?? -9, p.sunY ?? 18, p.sunZ ?? 8);
320
411
  scene.add(sun);
321
412
 
413
+ sun.shadow.camera.left = sun.shadow.camera.bottom = -16;
414
+ sun.shadow.camera.right = sun.shadow.camera.top = 16;
415
+ sun.shadow.camera.far = 100;
416
+ sun.shadow.camera.updateProjectionMatrix();
417
+
322
418
  const sharedTex = getTexture(stageComp.assetSlots?.[0]?.assetId);
323
419
  const nodes = new Map();
324
420
  const dynamicNodes = new Map();
325
421
  const wavingFlags = [];
326
422
  const confettiSystems = [];
423
+ const modelBindings = new Map();
327
424
 
328
425
  function tagSubtree(rootObj, rootId, sourceId, cameraAttached) {
329
426
  rootObj.traverse(node => {
@@ -347,7 +444,59 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
347
444
  if (mp.useTexture && sharedTex && !texReady) mat.userData.pendingTex = {tex: sharedTex, color: '#ffffff'};
348
445
  return mat;
349
446
  };
350
- if (mp.primitive === 'group') {
447
+ if (mp.primitive === 'model' || (mp.primitive === 'mesh' && !mp.waveFlag)) {
448
+ obj = new Group();
449
+ let child, cachedSlots, cachedParams;
450
+ const animBehavior = (project.gameplay ?? []).find(b => b.kind === 'animate-3d' && b.componentId === (comp.prototypeId ?? comp.id));
451
+ const binding = {
452
+ sourceId,
453
+ animator: null,
454
+ modelBounds: null,
455
+ startDefaultAnimation() {
456
+ if (!binding.animator || !animBehavior) return;
457
+ const ap = animBehavior.parameters;
458
+ if (ap.autoplay !== false) {
459
+ binding.animator.play(ap.clipName || '', {loop: ap.loop ?? 'repeat', speed: ap.speed ?? 1, fadeSeconds: 0, restart: true, startTime: ap.startTime ?? 0});
460
+ }
461
+ },
462
+ update(params) {
463
+ const runtime = overrides.get(comp.id)?.slots, prototype = overrides.get(comp.prototypeId)?.slots;
464
+ const slot = id => runtime?.[id] ?? prototype?.[id] ?? comp.assetSlots?.find(s => s.slotId === id)?.assetId;
465
+ const slots = ['source', 'texture', 'normalMap', 'emissiveMap'].map(slot);
466
+ const fields = ['subNode','materialMode','overrideMaterialName','opacity','tintColor','roughnessScale',
467
+ 'metalnessScale','castShadow','receiveShadow','normalizeSize','pivotMode','color','useTexture'];
468
+ if (cachedSlots && slots.every((id, i) => id === cachedSlots[i]) &&
469
+ fields.every(key => params[key] === cachedParams[key])) return false;
470
+ const asset = assetsMap.get(slots[0]);
471
+ if (child) { obj.remove(child); disposeTree(child); }
472
+ binding.animator = null;
473
+ binding.modelBounds = null;
474
+ if (asset?.mime === 'model/gltf-binary') {
475
+ const external = {};
476
+ for (const [i, key] of ['texture','normalMap','emissiveMap'].entries()) {
477
+ if (slots[i + 1]) external[key] = getTexture(slots[i + 1], key);
478
+ }
479
+ child = cloneModelTemplate(getModel(asset), params, external);
480
+ binding.modelBounds = child.userData?.modelBounds ?? null;
481
+ binding.animator = createModelAnimator(child);
482
+ binding.startDefaultAnimation();
483
+ } else {
484
+ child = new Mesh(getMeshGeometry(slots[0]) ?? new BoxGeometry(1, 1, 1), makeMat());
485
+ child.castShadow = !!params.castShadow;
486
+ child.receiveShadow = !!params.receiveShadow;
487
+ if (slots[1]) child.material.map = getTexture(slots[1]);
488
+ else if (params.color && !params.useTexture) child.material.color.set(params.color);
489
+ }
490
+ obj.add(child);
491
+ tagSubtree(child, rootId, sourceId, cameraAttached);
492
+ cachedSlots = slots;
493
+ cachedParams = {...params};
494
+ return true;
495
+ },
496
+ };
497
+ binding.update(mp);
498
+ modelBindings.set(comp.id, binding);
499
+ } else if (mp.primitive === 'group') {
351
500
  obj = new Group();
352
501
  } else if (mp.primitive === 'fairway') {
353
502
  obj = buildFairwayGroup(mp, sharedTex, getMeshGeometry(comp.assetSlots?.[0]?.assetId));
@@ -454,6 +603,8 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
454
603
  dynamicNodes,
455
604
  nodeEntries,
456
605
  createMeshObject,
606
+ modelBindings,
607
+ sun,
457
608
  wavingFlags,
458
609
  confettiSystems,
459
610
  guideGroup,
@@ -461,6 +612,7 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
461
612
  compiled: false,
462
613
  lastRenderMs: 0,
463
614
  textureDirty: true,
615
+ animDirty: false,
464
616
  skyColor: p.skyColor || '#b8e2ed',
465
617
  lastWaveAt: -1,
466
618
  lastRenderedTime: -1,
@@ -510,7 +662,18 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
510
662
  raycaster.near = 0.05;
511
663
  raycaster.far = maxDistance;
512
664
  raycaster.setFromCamera(ndc, camera);
513
- const hits = raycaster.intersectObjects(scene.children, true);
665
+ const candidates = [];
666
+ for (const obj of entry.nodes.values()) {
667
+ if (!obj.visible || obj.userData?.cameraAttached) continue;
668
+ const rid = obj.userData?.toraRootId, sid = obj.userData?.toraSourceId;
669
+ if (rid && (isTarget(rid, sid) || isOccluder(rid, sid))) candidates.push(obj);
670
+ }
671
+ for (const obj of entry.dynamicNodes.values()) {
672
+ if (!obj.visible || obj.userData?.cameraAttached) continue;
673
+ const rid = obj.userData?.toraRootId, sid = obj.userData?.toraSourceId;
674
+ if (rid && (isTarget(rid, sid) || isOccluder(rid, sid))) candidates.push(obj);
675
+ }
676
+ const hits = raycaster.intersectObjects(candidates.length ? candidates : scene.children, true);
514
677
  const seen = new Set();
515
678
  for (const hit of hits) {
516
679
  let hidden = false;
@@ -546,7 +709,41 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
546
709
  return stages.get(stageComp.id) ?? buildStage(stageComp);
547
710
  }
548
711
 
549
- function syncStage(stageComp, {time = 0, ambientTime, propsOf, bodies3d, fpsPose, instances3d = [], aimLocked = false, groundFn, worldWidth = 390, worldHeight = 700}) {
712
+ function syncContactParticles(entry, particles) {
713
+ if (!particles.length && !entry.contactBatches) return false;
714
+ if (!entry.contactBatches) {
715
+ entry.contactBatches = [new SphereGeometry(1, 6, 4), new BoxGeometry(1, 0.2, 1.6)].map(geometry => {
716
+ const mesh = new InstancedMesh(geometry, new MeshBasicMaterial({toneMapped: false}), 256);
717
+ mesh.userData.isConfetti = true;
718
+ mesh.frustumCulled = false;
719
+ mesh.count = 0;
720
+ entry.scene.add(mesh);
721
+ return mesh;
722
+ });
723
+ entry.contactPose = new Object3D();
724
+ entry.contactColor = new Color();
725
+ }
726
+ const prior = entry.contactBatches.some(mesh => mesh.count > 0);
727
+ for (const mesh of entry.contactBatches) mesh.count = 0;
728
+ const {contactBatches, contactPose, contactColor} = entry;
729
+ for (const p of particles) {
730
+ const mesh = contactBatches[Number(p.confetti)], age = p.age;
731
+ contactPose.position.set(p.x + p.vx * age, p.y + p.vy * age - p.gravity * age * age / 2, p.z + p.vz * age);
732
+ contactPose.rotation.set(p.spinX * age, p.spinZ * age / 2, p.spinZ * age);
733
+ contactPose.scale.setScalar(p.size * Math.min(1, (p.life - age) * 7));
734
+ contactPose.updateMatrix();
735
+ mesh.setMatrixAt(mesh.count, contactPose.matrix);
736
+ mesh.setColorAt(mesh.count, contactColor.set(p.color));
737
+ mesh.count++;
738
+ }
739
+ for (const mesh of contactBatches) {
740
+ mesh.instanceMatrix.needsUpdate = true;
741
+ if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
742
+ }
743
+ return prior || particles.length > 0;
744
+ }
745
+
746
+ function syncStage(stageComp, {time = 0, ambientTime, propsOf, bodies3d, fpsPose, instances3d = [], aimLocked = false, groundFn, worldWidth = 390, worldHeight = 700, designHeight}) {
550
747
  const entry = getStage(stageComp);
551
748
  const waveTime = ambientTime ?? time;
552
749
  const p = propsOf(stageComp);
@@ -561,6 +758,8 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
561
758
  for (const [dynId, dynObj] of entry.dynamicNodes) {
562
759
  if (!liveIds.has(dynId)) {
563
760
  dynObj.parent?.remove(dynObj);
761
+ disposeTree(dynObj);
762
+ entry.modelBindings.delete(dynId);
564
763
  entry.dynamicNodes.delete(dynId);
565
764
  }
566
765
  }
@@ -576,6 +775,21 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
576
775
  entry.dynamicNodes.set(comp.id, obj);
577
776
  }
578
777
 
778
+ const portrait = worldHeight >= worldWidth;
779
+ const dt = entry.lastTime < 0 || waveTime < entry.lastTime ? 0 : Math.min(0.05, waveTime - entry.lastTime);
780
+ const heightExpand = Math.max(1, worldHeight / Math.max(1, designHeight ?? worldHeight));
781
+ const expandFov = baseFov => heightExpand > 1.001
782
+ ? Math.min(135, 2 * Math.atan(Math.tan((baseFov * Math.PI) / 360) * heightExpand) * (180 / Math.PI))
783
+ : baseFov;
784
+ const camAspect = worldWidth / Math.max(1, worldHeight);
785
+ const camFov = fpsPose
786
+ ? expandFov(portrait ? (p.cameraFov ?? 68) : (p.landscapeCameraFov ?? 54))
787
+ : expandFov(portrait ? (p.cameraFov ?? 39) : (p.landscapeCameraFov ?? 22.6199));
788
+ if (entry.recoil > 0) {
789
+ entry.recoil = dt > 0 ? (entry.recoil * Math.exp(-10 * dt)) : entry.recoil;
790
+ if (entry.recoil < 0.002) entry.recoil = 0;
791
+ }
792
+
579
793
  // Sync mesh3d node transforms, visibility & colors from live parameters + 3D physics + drop shadows
580
794
  const allNodes = [
581
795
  ...entry.nodeEntries,
@@ -585,6 +799,10 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
585
799
  for (const {id, obj, comp} of allNodes) {
586
800
  const mp = propsOf(comp);
587
801
  obj.visible = mp.visible !== false;
802
+ if (entry.modelBindings.get(id)?.update(mp)) {
803
+ entry.textureDirty = true;
804
+ entry.compiled = false;
805
+ }
588
806
  if (!mp.useTexture && obj.isMesh && obj.material?.color && mp.color) {
589
807
  obj.material.color.set(mp.color);
590
808
  }
@@ -610,13 +828,20 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
610
828
  const s = 1 + lift * 0.4;
611
829
  obj.scale.set(s, s, s);
612
830
  obj.visible = !target.captured && mp.visible !== false;
831
+ } else if (mp.attachToCamera) {
832
+ const refTan = Math.tan(((p.cameraFov ?? 68) * Math.PI) / 360), curTan = Math.tan((camFov * Math.PI) / 360);
833
+ const r = curTan / Math.max(0.05, refTan), s = Math.min(1, r), sy = Math.min(1.15, r) * (camAspect > 1.3 ? 1.12 : 1);
834
+ const sx = sy * Math.min(3.55, camAspect / (390 / 700)), rec = entry.recoil ?? 0;
835
+ obj.position.set((mp.x ?? 0) * sx, (mp.y ?? 0) * sy + rec * 0.085 * s, (mp.z ?? 0) + rec * 0.3 * s);
836
+ obj.rotation.set((mp.rx ?? 0) + rec * 0.34, (mp.ry ?? 0) + (camAspect > 1.1 ? 0.1 : 0), (mp.rz ?? 0) - rec * 0.09);
837
+ obj.scale.set((mp.sx ?? 1) * s, (mp.sy ?? 1) * s, (mp.sz ?? 1) * s);
613
838
  } else {
614
839
  obj.position.set(mp.x ?? 0, mp.y ?? 0, mp.z ?? 0);
615
840
  obj.rotation.set(mp.rx ?? 0, mp.ry ?? 0, mp.rz ?? 0);
616
841
  obj.scale.set(mp.sx ?? 1, mp.sy ?? 1, mp.sz ?? 1);
617
842
  }
618
843
  if (fpsPose || entry.dynamicNodes.size > 0) {
619
- poseParts += `${id}:${obj.visible ? 1 : 0},${obj.position.x.toFixed(3)},${obj.position.y.toFixed(3)},${obj.position.z.toFixed(3)},${obj.rotation.y.toFixed(3)},${mp.color ?? ''}|`;
844
+ poseParts += `${id}:${+obj.visible},${obj.position.x * 1e2 | 0},${obj.position.y * 1e2 | 0},${obj.position.z * 1e2 | 0},${obj.rotation.x * 1e2 | 0},${obj.rotation.y * 1e2 | 0}|`;
620
845
  }
621
846
  }
622
847
 
@@ -647,17 +872,15 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
647
872
  }
648
873
 
649
874
  // Camera pose: first-person FPS controller or smooth tracking / golf framing
650
- const portrait = worldHeight >= worldWidth;
651
- const dt = entry.lastTime < 0 || waveTime < entry.lastTime ? 0 : Math.min(0.05, waveTime - entry.lastTime);
652
- entry.camera.aspect = worldWidth / Math.max(1, worldHeight);
875
+ entry.camera.aspect = camAspect;
653
876
  let victorySway = false;
654
877
  if (fpsPose) {
655
878
  entry.lastTime = waveTime;
656
879
  entry.camera.rotation.order = 'YXZ';
657
880
  entry.camera.position.set(fpsPose.x, fpsPose.y + (fpsPose.bob ?? 0), fpsPose.z);
658
881
  entry.camera.rotation.set(fpsPose.pitch, fpsPose.yaw, 0);
659
- entry.camera.fov = portrait ? (p.cameraFov ?? 68) : (p.landscapeCameraFov ?? 54);
660
- poseParts += `cam:${entry.camera.position.x.toFixed(3)},${entry.camera.position.y.toFixed(3)},${entry.camera.position.z.toFixed(3)},${fpsPose.yaw.toFixed(4)},${fpsPose.pitch.toFixed(4)},${entry.camera.fov.toFixed(2)}`;
882
+ entry.camera.fov = camFov;
883
+ poseParts += `c:${entry.camera.position.x * 1e2 | 0},${entry.camera.position.y * 1e2 | 0},${entry.camera.position.z * 1e2 | 0},${fpsPose.yaw * 1e3 | 0},${fpsPose.pitch * 1e3 | 0},${camFov * 1e2 | 0},${camAspect * 1e3 | 0},${(entry.recoil ?? 0) * 1e3 | 0}`;
661
884
  } else {
662
885
  const followBody = p.followTargetId ? bodies3d?.get(p.followTargetId) : undefined;
663
886
  const targetZ = followBody ? followBody.z * (p.followZFactor ?? 0.12) : (p.lookAtZ ?? 0);
@@ -674,9 +897,10 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
674
897
  const baseZ = (portrait ? (p.cameraZ ?? 21) : (p.landscapeCameraZ ?? 18)) + swayZ;
675
898
  const y = dt === 0 ? baseY : entry.camera.position.y + (baseY - entry.camera.position.y) * (1 - Math.exp(-6 * dt));
676
899
  entry.camera.position.set(baseX, y, baseZ + entry.focusZ);
677
- entry.camera.fov = portrait ? (p.cameraFov ?? 39) : (p.landscapeCameraFov ?? 22.6199);
900
+ entry.camera.fov = camFov;
678
901
  entry.camera.lookAt(p.lookAtX ?? 0, p.lookAtY ?? 0.15, entry.focusZ);
679
902
  }
903
+ poseParts += `a:${camAspect * 1e3 | 0},${camFov * 1e2 | 0}`;
680
904
  }
681
905
  entry.camera.updateProjectionMatrix();
682
906
  entry.camera.updateMatrixWorld(true);
@@ -689,22 +913,38 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
689
913
  worldWidth: options.worldWidth ?? stageWidth,
690
914
  worldHeight: options.worldHeight ?? stageHeight,
691
915
  });
692
- const {bodies3d} = options;
693
-
694
- // Render into offscreen WebGL2 buffer & composite onto main Canvas2D stage
695
- if (pixelWidth < 2 || pixelHeight < 2) {
696
- ctx2d.fillStyle = entry.skyColor;
697
- ctx2d.fillRect(0, 0, stageWidth, stageHeight);
698
- return entry;
699
- }
700
- const renderer = ensureRenderer();
916
+ const {bodies3d} = options, drawX = options.drawX ?? 0, drawY = options.drawY ?? 0;
917
+ const contactDirty = syncContactParticles(entry, options.contactParticles ?? []);
918
+ Object.assign(entry, {lastX: drawX, lastY: drawY, lastWidth: stageWidth, lastHeight: stageHeight, lastDesignH: options.designHeight ?? stageHeight, isFullBleed: Boolean(options.fullBleed)});
919
+ const renderer = pixelWidth >= 2 && pixelHeight >= 2 ? ensureRenderer() : null;
701
920
  if (!renderer || renderer.getContext?.()?.isContextLost?.()) {
702
921
  ctx2d.fillStyle = entry.skyColor;
703
- ctx2d.fillRect(0, 0, stageWidth, stageHeight);
922
+ ctx2d.fillRect(drawX, drawY, stageWidth, stageHeight);
704
923
  return entry;
705
924
  }
706
925
  const maxDim = Math.max(pixelWidth, pixelHeight, 1);
707
- const maxTarget = 520;
926
+ const p = options.propsOf(stageComp);
927
+ const toneMapping = {none: NoToneMapping, neutral: NeutralToneMapping, aces: ACESFilmicToneMapping}[p.toneMapping] ?? NoToneMapping;
928
+ renderer.toneMapping = toneMapping;
929
+ const shadows = !!p.shadowsEnabled, size = Number(p.shadowMapSize ?? 512);
930
+ renderer.shadowMap.enabled = shadows;
931
+ entry.sun.castShadow = shadows;
932
+ if (entry.sun.shadow.mapSize.x !== size) {
933
+ entry.sun.shadow.mapSize.set(size, size);
934
+ entry.sun.shadow.map?.dispose();
935
+ entry.sun.shadow.map = null;
936
+ }
937
+ const intensity = p.envIntensity ?? 0.8;
938
+ if (entry.textureDirty || !entry.compiled) {
939
+ entry.usesPbr = false;
940
+ entry.scene.traverse(o => { if (o.material?.isMeshStandardMaterial) entry.usesPbr = true; });
941
+ }
942
+ if (entry.usesPbr && intensity > 0) environment ??= studioEnvironment(renderer);
943
+ entry.scene.environment = entry.usesPbr && intensity > 0 ? environment?.texture : null;
944
+ entry.scene.environmentIntensity = intensity;
945
+ const lightingKey = [toneMapping, shadows, size, intensity].join('/');
946
+ if (entry.lightingKey !== lightingKey) { entry.textureDirty = true; entry.lightingKey = lightingKey; }
947
+ const maxTarget = p.renderMaxDim ?? 520;
708
948
  const cap = maxDim > maxTarget ? maxTarget / maxDim : 1;
709
949
  const rw = Math.max(2, Math.round(pixelWidth * cap));
710
950
  const rh = Math.max(2, Math.round(pixelHeight * cap));
@@ -750,7 +990,7 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
750
990
  const swayDirty = victorySway && Math.abs(waveTime - entry.lastRenderedTime) >= 0.032;
751
991
  const bodyDirty = hasMovingBody && entry.lastRenderedTime !== waveTime;
752
992
  const poseDirty = poseParts !== entry.lastPoseSig;
753
- const didRender = resized || sharedStageId !== stageComp.id || entry.guideDirty || entry.textureDirty || entry.lastRenderedTime < 0 || entry.lastRenderedW !== rw || entry.lastRenderedH !== rh || flagDirty || swayDirty || bodyDirty || poseDirty;
993
+ const didRender = resized || sharedStageId !== stageComp.id || entry.guideDirty || entry.textureDirty || entry.animDirty || entry.lastRenderedTime < 0 || entry.lastRenderedW !== rw || entry.lastRenderedH !== rh || flagDirty || swayDirty || bodyDirty || poseDirty || contactDirty;
754
994
  if (didRender) {
755
995
  if (entry.wavingFlags.length > 0 && entry.lastFlagStep !== flagStep) {
756
996
  for (const flag of entry.wavingFlags) waveFlagGeometry(flag.geo, flag.rest, flagStep / 20);
@@ -768,19 +1008,27 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
768
1008
  entry.lastPoseSig = poseParts;
769
1009
  entry.guideDirty = false;
770
1010
  entry.textureDirty = false;
1011
+ entry.animDirty = false;
771
1012
  }
772
- entry.lastWidth = stageWidth;
773
- entry.lastHeight = stageHeight;
774
1013
  if (sharedCacheCanvas.width > 0 && sharedCacheCanvas.height > 0) {
775
- ctx2d.drawImage(sharedCacheCanvas, 0, 0, stageWidth, stageHeight);
1014
+ ctx2d.drawImage(sharedCacheCanvas, drawX, drawY, stageWidth, stageHeight);
776
1015
  }
777
1016
  return entry;
778
1017
  }
779
1018
 
780
1019
  function reset() {
781
1020
  for (const entry of stages.values()) {
782
- for (const dynObj of entry.dynamicNodes.values()) dynObj.parent?.remove(dynObj);
1021
+ for (const [id, dynObj] of entry.dynamicNodes) {
1022
+ dynObj.parent?.remove(dynObj);
1023
+ disposeTree(dynObj);
1024
+ entry.modelBindings.delete(id);
1025
+ }
783
1026
  entry.dynamicNodes.clear();
1027
+ for (const binding of entry.modelBindings.values()) {
1028
+ binding.animator?.reset();
1029
+ binding.startDefaultAnimation();
1030
+ }
1031
+ entry.animDirty = true;
784
1032
  entry.focusZ = 0;
785
1033
  entry.lastTime = -1;
786
1034
  entry.lastRenderedTime = -1;
@@ -793,15 +1041,19 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
793
1041
 
794
1042
  function dispose() {
795
1043
  for (const entry of stages.values()) {
796
- entry.scene.traverse(o => {
797
- if (o.isMesh) {
798
- if (o.geometry && !Array.from(meshCache.values()).includes(o.geometry)) o.geometry.dispose();
799
- if (o.material) for (const m of Array.isArray(o.material) ? o.material : [o.material]) m.dispose();
800
- }
801
- });
1044
+ for (const mesh of entry.contactBatches ?? []) mesh.dispose();
1045
+ disposeTree(entry.scene);
1046
+ entry.sun.shadow.dispose();
802
1047
  }
803
- for (const geo of meshCache.values()) geo.dispose();
1048
+ for (const geo of sharedGeometry) geo.dispose();
1049
+ for (const mat of sharedMaterials) mat.dispose();
804
1050
  for (const tex of textureCache.values()) tex.dispose();
1051
+ for (const model of modelCache.values()) for (const tex of model.textures.values()) tex.dispose();
1052
+ sharedMaterials.clear();
1053
+ sharedGeometry.clear();
1054
+ modelCache.clear();
1055
+ environment?.dispose();
1056
+ environment = undefined;
805
1057
  stages.clear();
806
1058
  meshCache.clear();
807
1059
  textureCache.clear();
@@ -814,5 +1066,56 @@ export function createStage3dManager(project, assetsMap, onTextureReady) {
814
1066
  sharedStageId = undefined;
815
1067
  }
816
1068
 
817
- return {getStage, syncStage, renderStage, reset, dispose};
1069
+ function stepAnimations(dt, onAnimEnd) {
1070
+ for (const entry of stages.values()) {
1071
+ for (const [id, binding] of entry.modelBindings) {
1072
+ if (!binding.animator) continue;
1073
+ if (binding.animator.step(dt, clipName => onAnimEnd?.(id, binding.sourceId ?? id, clipName))) {
1074
+ entry.animDirty = true;
1075
+ }
1076
+ }
1077
+ }
1078
+ }
1079
+
1080
+ function playModelAnimation(componentId, opts = {}) {
1081
+ let matched = false;
1082
+ for (const entry of stages.values()) {
1083
+ for (const [id, binding] of entry.modelBindings) {
1084
+ if (id !== componentId && binding.sourceId !== componentId) continue;
1085
+ if (binding.animator?.play(opts.clipName || '', opts)) {
1086
+ entry.animDirty = true;
1087
+ matched = true;
1088
+ }
1089
+ }
1090
+ }
1091
+ return matched;
1092
+ }
1093
+
1094
+ function modelBoundsFor(componentId) {
1095
+ for (const entry of stages.values()) {
1096
+ const binding = entry.modelBindings.get(componentId);
1097
+ if (binding?.modelBounds) return binding.modelBounds;
1098
+ }
1099
+ return null;
1100
+ }
1101
+
1102
+ function modelStatus() {
1103
+ const total = {texturesPending: 0, textureErrors: 0, animations: {}};
1104
+ for (const model of modelCache.values()) {
1105
+ const status = model.imageStatus();
1106
+ total.texturesPending += status.texturesPending;
1107
+ total.textureErrors += status.textureErrors;
1108
+ }
1109
+ for (const entry of stages.values()) {
1110
+ for (const [id, binding] of entry.modelBindings) {
1111
+ if (binding.animator) total.animations[id] = binding.animator.snapshot();
1112
+ }
1113
+ }
1114
+ return total;
1115
+ }
1116
+ function triggerRecoil(stageId) {
1117
+ const entry = stages.get(stageId);
1118
+ if (entry) entry.recoil = 1;
1119
+ }
1120
+ return {getStage, syncStage, renderStage, reset, dispose, stepAnimations, playModelAnimation, modelBoundsFor, modelStatus, triggerRecoil};
818
1121
  }