@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.
- package/README.md +108 -58
- package/assets/free-audio/arcade-pop/audio/loss.wav +0 -0
- package/assets/free-audio/arcade-pop/audio/reward.wav +0 -0
- package/assets/free-audio/arcade-pop/audio/win.wav +0 -0
- package/assets/free-audio/arcade-pop/source/INFO.txt +11 -11
- package/assets/kenney-food-starter/License.txt +28 -0
- package/assets/kenney-food-starter/burger.glb +0 -0
- package/assets/kenney-food-starter/frying-pan.glb +0 -0
- package/assets/kenney-food-starter/plan.json +61 -0
- package/assets/kenney-food-starter/plate.glb +0 -0
- package/assets/kenney-food-starter/pot.glb +0 -0
- package/assets/kenney-harvest/audio/victory.wav +0 -0
- package/assets/kenney-harvest/source/music-jingles/OGG/jingles_NES/jingles_NES03.ogg +0 -0
- package/assets/kenney-harvest/source/music-jingles/OGG/jingles_PIZZA/jingles_PIZZA03.ogg +0 -0
- package/assets/kenney-harvest/source/music-jingles/license.txt +14 -0
- package/bin/tora.mjs +77 -9
- package/crates/packer/trusted/native-3d-meta.json +3 -2
- package/crates/packer/trusted/native-3d.js +181 -181
- package/crates/packer/trusted/native-meta.json +2 -2
- package/crates/packer/trusted/native.js +5 -5
- package/crates/packer/trusted/release-manifest.json +17 -17
- package/crates/packer/trusted/review-runtime-meta.json +3 -2
- package/crates/packer/trusted/review-runtime.js +182 -182
- package/docs/TORA_AGENT_SETUP.md +24 -13
- package/docs/TORA_CREATION_API.md +29 -12
- package/docs/reference/CORE_AUTHORING.md +2 -1
- package/docs/reference/PLAYABLE_STARTERS.md +20 -0
- package/docs/reference/packs/3d.md +9 -3
- package/network-rules/mintegral-appgrowth-single-html.json +10 -10
- package/package.json +6 -6
- package/packages/creative-project/project-v21.schema.json +264 -8
- package/scripts/lean/editor/review-editor.css +10 -0
- package/scripts/lean/editor/review-editor.js +117 -1
- package/scripts/lean/native/agent-tools.mjs +7 -7
- package/scripts/lean/native/api.mjs +16 -5
- package/scripts/lean/native/asset-catalog.mjs +7 -6
- package/scripts/lean/native/asset-lineage.mjs +54 -0
- package/scripts/lean/native/asset-prep.mjs +173 -40
- package/scripts/lean/native/assets.mjs +107 -11
- package/scripts/lean/native/author-expansion-proofs.mjs +2 -99
- package/scripts/lean/native/author-fps.mjs +545 -0
- package/scripts/lean/native/author-primitive-proofs.mjs +5 -4
- package/scripts/lean/native/build-cache.mjs +2 -2
- package/scripts/lean/native/cc0-inputs.mjs +24 -0
- package/scripts/lean/native/cc0-staging.mjs +28 -8
- package/scripts/lean/native/check-harvest-outcome-audio.mjs +7 -8
- package/scripts/lean/native/check-salvage.mjs +8 -5
- package/scripts/lean/native/compiler.mjs +9 -3
- package/scripts/lean/native/contracts.mjs +11 -8
- package/scripts/lean/native/creative-qa.mjs +305 -122
- package/scripts/lean/native/demos.mjs +47 -3
- package/scripts/lean/native/document.mjs +36 -10
- package/scripts/lean/native/export-budget.mjs +75 -0
- package/scripts/lean/native/glb-loader.mjs +468 -0
- package/scripts/lean/native/intake-creator-tools.mjs +83 -30
- package/scripts/lean/native/local-bundle.mjs +5 -3
- package/scripts/lean/native/mcp-server.mjs +33 -46
- package/scripts/lean/native/media-validate.mjs +124 -0
- package/scripts/lean/native/native-bin.mjs +3 -3
- package/scripts/lean/native/outcome-playthrough.mjs +97 -0
- package/scripts/lean/native/prepare-fps-assets.mjs +330 -0
- package/scripts/lean/native/project-bundle.mjs +3 -3
- package/scripts/lean/native/remote-cc0-fetcher.mjs +403 -197
- package/scripts/lean/native/review-agent-tools.mjs +2 -2
- package/scripts/lean/native/review.mjs +3 -0
- package/scripts/lean/native/runtime.mjs +242 -56
- package/scripts/lean/native/schema.mjs +7 -5
- package/scripts/lean/native/service.mjs +159 -32
- package/scripts/lean/native/stage-3d.mjs +343 -40
- package/scripts/lean/native/starters.mjs +436 -0
- package/scripts/lean/native/verify.mjs +1 -1
- package/scripts/lean/native/win-cues.mjs +96 -0
- package/skills/tora-playables/SKILL.md +1 -1
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
import {multiplyMatrix,inverseMatrix,identityMatrix} from '../scene-document.mjs';
|
|
3
3
|
import {createMatchBoard} from './match-board.mjs';
|
|
4
4
|
import {createDropOccupancy,resolveDropZone,classifySwipe,createHoldCharge,createGestureTweens,computeJoystickVector} from './interaction-gestures.mjs';
|
|
5
|
-
import {createInstanceSteering,seedFromText,findNearestByTeam,turnToward} from './instance-steering.mjs';
|
|
5
|
+
import {createInstanceSteering,createRng,seedFromText,findNearestByTeam,turnToward} from './instance-steering.mjs';
|
|
6
6
|
import {createEraseMask} from './erase-mask.mjs';
|
|
7
7
|
import {createStrokeStore,strokeWalls,segmentHitsPolygon,segmentsIntersect} from './draw-stroke.mjs';
|
|
8
8
|
import {stepPhysics,predictTrajectory} from './physics-2d.mjs';
|
|
9
9
|
/* 3d:start */
|
|
10
10
|
import {stepPhysics3d,predictTrajectory3d,ground3d,resolveWallSlide3d} from './physics-3d.mjs';
|
|
11
|
-
import {createStage3dManager} from './stage-3d.mjs';
|
|
11
|
+
import {contactOrigin3d,createStage3dManager} from './stage-3d.mjs';
|
|
12
12
|
/* 3d:end */
|
|
13
13
|
import {createPathNetwork} from './path-network.mjs';
|
|
14
14
|
import {drawPixelText,measurePixelText} from './pixel-text.mjs';
|
|
@@ -32,12 +32,13 @@ export function createNetworkBridge(network){
|
|
|
32
32
|
throw Error('E_NATIVE_TARGET');
|
|
33
33
|
}
|
|
34
34
|
export function computeSafeArea(stage){
|
|
35
|
+
const l=stage.left??0,t=stage.top??0,r=stage.right??(l+stage.width),b=stage.bottom??(t+stage.height);
|
|
35
36
|
const zones=[
|
|
36
|
-
{id:'sdk-top-left',left:
|
|
37
|
-
{id:'sdk-top-right',left:Math.max(
|
|
38
|
-
{id:'sdk-bottom-left',left:
|
|
37
|
+
{id:'sdk-top-left',left:l,top:t,right:Math.min(l+48,r),bottom:Math.min(t+48,b)},
|
|
38
|
+
{id:'sdk-top-right',left:Math.max(l,r-56),top:t,right:r,bottom:Math.min(t+56,b)},
|
|
39
|
+
{id:'sdk-bottom-left',left:l,top:Math.max(t,b-28),right:Math.min(l+48,r),bottom:b},
|
|
39
40
|
];
|
|
40
|
-
return {left:Math.min(48,
|
|
41
|
+
return {left:Math.min(l+48,r),top:Math.min(t+56,b),right:Math.max(l,r-56),bottom:Math.max(t,b-28),zones};
|
|
41
42
|
}
|
|
42
43
|
function measuredTextWidth(ctx,value){const width=ctx.measureText?.(value)?.width,size=/(\d+(?:\.\d+)?)px/.exec(ctx.font||'');return Number.isFinite(width)?width:[...value].length*(size?Number(size[1]):16)*.6;}
|
|
43
44
|
function standardTextLines(ctx,text,p,fontSize){
|
|
@@ -99,12 +100,12 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
99
100
|
if(paintedLandscape!==viewport().landscape){cancelInput();render();}
|
|
100
101
|
}
|
|
101
102
|
for(const a of project.assets)if(a.mime.startsWith('image/')){const img=new Image();img.src='data:'+a.mime+';base64,'+a.data;images.set(a.id,img);}
|
|
102
|
-
let scene=sceneId,variables={},instances=[],particles=[],animations=[],queue=[],contacts=new Set(),contactPairs=new Map(),time=0,ambientTime=0,serial=0,acc=0,last=0,paused=false,frameEvents=0,frameActions=0,halted=false,diagnostics=[],audio,audioUnlock,drag,hover,pressed,pressPointerId,raf,transition,selected,paint=[],pendingStore,floatingTexts=[],screenFlashes=[],shake,tutorialInputAt=0,tutorialHadInput=false,activeTutorialHands=0,started=network==='standalone',networkReady=network==='standalone',networkVisible=network==='standalone',closed=false,destroyed=false;
|
|
103
|
-
const overrides=new Map(),timers=new Map(),runtimeNodes=new Map(),spriteMotion=new Map(),audioSources=new Set(),decodedAudio=new Map(),loopingAudio=new Set(),pendingLoopAudio=new Map(),audioVoices=new Map(),audioCooldowns=new Map(),audioPitchCounts=new Map(),pressStates=new Map(),matchCells=new Map();let audioEpoch=0,blockedAudio=0,matchSelected,matchGesture,hostVolume=1,lastEndScene;
|
|
103
|
+
let scene=sceneId,variables={},instances=[],particles=[],animations=[],queue=[],contacts=new Set(),contactPairs=new Map(),time=0,ambientTime=0,serial=0,acc=0,last=0,paused=false,frameEvents=0,frameActions=0,halted=false,diagnostics=[],audio,audioUnlock,drag,hover,pressed,pressPointerId,raf,transition,delayedScene,selected,paint=[],pendingStore,floatingTexts=[],screenFlashes=[],shake,tutorialInputAt=0,tutorialHadInput=false,activeTutorialHands=0,started=network==='standalone',networkReady=network==='standalone',networkVisible=network==='standalone',closed=false,destroyed=false;
|
|
104
|
+
const overrides=new Map(),timers=new Map(),runtimeNodes=new Map(),spriteMotion=new Map(),audioSources=new Set(),decodedAudio=new Map(),decodedLoopAudio=new Map(),loopingAudio=new Set(),pendingLoopAudio=new Map(),audioVoices=new Map(),audioCooldowns=new Map(),audioPitchCounts=new Map(),pressStates=new Map(),matchCells=new Map();let audioEpoch=0,blockedAudio=0,matchSelected,matchGesture,hostVolume=1,lastEndScene;
|
|
104
105
|
const matchBoards=new Map(),matchArtwork=new Map(),physicsBodies=new Map(),pathNetworks=new Map(),oscillations=new Map(),meterStates=new Map(),cameraStates=new Map(),dropOccupancy=createDropOccupancy(),gestureTweens=createGestureTweens(),dragOrigins=new Map(),swipeCooldowns=new Map(),instanceEngine=createInstanceSteering(seedFromText(project.projectId)),maskStates=new Map(),strokeStates=new Map(),pathFollowers=new Map(),brokenJoints=new Set(),joysticks=new Map();let aiming,currentRenderScale=1,currentRenderDpr=1,gestureInput,hoverDrop,lastPointer={x:0,y:0},continuousInput,strokeWallBodies=[],activeJoints=[];
|
|
105
106
|
/* 3d:start */
|
|
106
|
-
const bodies3d=new Map(),oscillations3d=new Map(),projected3d=new Map(),fpsStates=new Map();let aiming3d,activeLook,stage3dMgr;
|
|
107
|
-
if(project.components.some(c=>c.contract==='native.stage3d.v1'))stage3dMgr=createStage3dManager(project,assets,()=>{if(!destroyed)Promise.resolve().then(()=>{if(!destroyed)render();});});
|
|
107
|
+
const bodies3d=new Map(),oscillations3d=new Map(),projected3d=new Map(),fpsStates=new Map(),fullBleed3dIds=new Set();let aiming3d,activeLook,stage3dMgr;
|
|
108
|
+
if(project.components.some(c=>c.contract==='native.stage3d.v1'))stage3dMgr=createStage3dManager(project,assets,()=>{if(!destroyed)Promise.resolve().then(()=>{if(!destroyed)render();});},overrides);
|
|
108
109
|
/* 3d:end */
|
|
109
110
|
const object=id=>runtimeNodes.get(id)??byId.get(id),behaviorOn=(kind,id)=>project.gameplay.find(b=>b.kind===kind&&b.componentId===id);
|
|
110
111
|
const stopAudio=()=>{audioEpoch++;loopingAudio.clear();pendingLoopAudio.clear();audioCooldowns.clear();audioPitchCounts.clear();for(const source of audioSources)try{source.stop();}catch{/* A completed voice may already be stopped. */}audioSources.clear();audioVoices.clear();};
|
|
@@ -119,7 +120,7 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
119
120
|
const finishPointer=e=>{if(pendingStore?.pointerId===e.pointerId)pendingStore=undefined;for(const press of pressStates.values())if(press.pointerId===e.pointerId&&press.held){press.held=false;press.releasedAt=time;}const owned=cancelDrag(e.pointerId);if(pressPointerId===e.pointerId){pressed=undefined;pressPointerId=undefined;return true;}return owned;};
|
|
120
121
|
const despawn=id=>{if(!id)return;if(drag&&runtimeNodes.get(drag.targetId)?.instanceId===id)cancelDrag(undefined,false);if(aiming&&runtimeNodes.get(aiming.targetId)?.instanceId===id)cancelAim();const removed=[];dropOccupancy.release(id);gestureTweens.cancel(id);maskStates.delete(id);pathFollowers.delete(id);instanceEngine.remove(id);instances=instances.filter(i=>i.id!==id);for(const [key,c]of runtimeNodes)if(c.instanceId===id){removed.push(key);dropOccupancy.release(key);gestureTweens.cancel(key);runtimeNodes.delete(key);overrides.delete(key);spriteMotion.delete(key);physicsBodies.delete(key);oscillations.delete(key);meterStates.delete(key);for(const network of pathNetworks.values())network.removeAgent(key);for(const timerKey of timers.keys())if(timerKey.endsWith(':'+key))timers.delete(timerKey);}animations=animations.filter(a=>!removed.includes(a.targetId));};
|
|
121
122
|
const prototypeOwner=c=>{while(c){if(c.prototype)return c.id;c=object(c.parentId);}return undefined;};
|
|
122
|
-
const state=()=>({viewport:viewport(),components:Object.fromEntries([...overrides].map(([id,value])=>[id,{...value,parameters:{...value.parameters}}])),mode:edit?'edit':'play',scene,variables:{...variables},time,instances:instances.map(i=>({id:i.id,prototypeId:i.prototypeId,x:i.transform[4],y:i.transform[5],...instanceEngine.snapshot(i.id)})),particles:particles.length,animations:animations.length,contacts:contacts.size,spriteFrames:Object.fromEntries([...spriteMotion].map(([key,value])=>[key,value.frame??0])),input:{dragging:Boolean(drag),pointerId:drag?.pointerId??gestureInput?.pointerId??null,pressed:pressed??null,holding:Boolean(gestureInput?.holds.length),occupancy:dropOccupancy.snapshot(),joysticks:Object.fromEntries([...joysticks].map(([id,j])=>[id,{active:j.pointerId!==null,x:j.nx,y:j.ny,magnitude:j.magnitude,angle:j.angle}]))},feedback:{presses:pressStates.size,floatingTexts:floatingTexts.length,flashes:screenFlashes.length,shaking:Boolean(shake),tutorialHands:activeTutorialHands},match:{boards:Object.fromEntries([...matchBoards].map(([id,board])=>[id,board.snapshot()])),selected:matchSelected??null,cells:[...matchCells].map(([id,cell])=>({id,...cell}))},physics:physicsSnapshot(),/* 3d:start */physics3d:physics3dSnapshot(),/* 3d:end */paths:Object.fromEntries([...pathNetworks].map(([id,network])=>[id,network.snapshot()])),canvas:{masks:Object.fromEntries([...maskStates].map(([id,mask])=>[id,{progress:mask.progress}])),strokes:Object.fromEntries([...strokeStates].map(([id,store])=>[id,store.strokes.length])),walls:strokeWallBodies.length,joints:activeJoints.filter(joint=>!joint.broken).length},audio:{state:audio?.state??'locked',voices:audioSources.size,blocked:blockedAudio},network:{target:network,ready:networkReady,visible:networkVisible,started,closed,hostVolume},diagnostics:[...diagnostics]});
|
|
123
|
+
const state=()=>({viewport:viewport(),components:Object.fromEntries([...overrides].map(([id,value])=>[id,{...value,parameters:{...value.parameters}}])),mode:edit?'edit':'play',scene,variables:{...variables},time,instances:instances.map(i=>({id:i.id,prototypeId:i.prototypeId,x:i.transform[4],y:i.transform[5],...instanceEngine.snapshot(i.id)})),particles:particles.length,animations:animations.length,contacts:contacts.size,spriteFrames:Object.fromEntries([...spriteMotion].map(([key,value])=>[key,value.frame??0])),input:{dragging:Boolean(drag),pointerId:drag?.pointerId??gestureInput?.pointerId??null,pressed:pressed??null,holding:Boolean(gestureInput?.holds.length),occupancy:dropOccupancy.snapshot(),joysticks:Object.fromEntries([...joysticks].map(([id,j])=>[id,{active:j.pointerId!==null,x:j.nx,y:j.ny,magnitude:j.magnitude,angle:j.angle}]))},feedback:{presses:pressStates.size,floatingTexts:floatingTexts.length,flashes:screenFlashes.length,shaking:Boolean(shake),tutorialHands:activeTutorialHands},match:{boards:Object.fromEntries([...matchBoards].map(([id,board])=>[id,board.snapshot()])),selected:matchSelected??null,cells:[...matchCells].map(([id,cell])=>({id,...cell}))},physics:physicsSnapshot(),/* 3d:start */physics3d:physics3dSnapshot(),model3d:stage3dMgr?.modelStatus(),/* 3d:end */paths:Object.fromEntries([...pathNetworks].map(([id,network])=>[id,network.snapshot()])),canvas:{masks:Object.fromEntries([...maskStates].map(([id,mask])=>[id,{progress:mask.progress}])),strokes:Object.fromEntries([...strokeStates].map(([id,store])=>[id,store.strokes.length])),walls:strokeWallBodies.length,joints:activeJoints.filter(joint=>!joint.broken).length},audio:{state:audio?.state??'locked',voices:audioSources.size,blocked:blockedAudio},network:{target:network,ready:networkReady,visible:networkVisible,started,closed,hostVolume},diagnostics:[...diagnostics]});
|
|
123
124
|
const running=()=>!edit&&!paused&&!document.hidden&&networkReady&&networkVisible&&started&&!closed;
|
|
124
125
|
const cancelInput=()=>{pendingStore=undefined;cancelAim();/* 3d:start */cancelAim3d();cancelLook3d();/* 3d:end */cancelJoysticks();cancelDrag();gestureInput=undefined;hoverDrop=undefined;continuousInput=undefined;for(const store of strokeStates.values())store.cancel();gestureTweens.clear();matchGesture=undefined;for(const board of matchBoards.values())board.cancelSelection();if(matchBoards.size)matchSelected=undefined;pressed=undefined;pressPointerId=undefined;pressStates.clear();};
|
|
125
126
|
const diagnose=message=>{halted=true;diagnostics.push(message);diagnostics=diagnostics.slice(-16);queue=[];};
|
|
@@ -133,6 +134,14 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
133
134
|
for(let axis=0;axis<4;axis++)result[axis]*=scale;
|
|
134
135
|
return result;
|
|
135
136
|
}
|
|
137
|
+
function anchorBounds(stage){
|
|
138
|
+
/* 3d:start */
|
|
139
|
+
if(stage3dMgr&&fullBleed3dIds.size>0&&renderBleed){
|
|
140
|
+
return {left:renderBleed.x,top:renderBleed.y,right:renderBleed.x+renderBleed.w,bottom:renderBleed.y+renderBleed.h,width:renderBleed.w,height:renderBleed.h};
|
|
141
|
+
}
|
|
142
|
+
/* 3d:end */
|
|
143
|
+
return {left:0,top:0,right:stage.width,bottom:stage.height,width:stage.width,height:stage.height};
|
|
144
|
+
}
|
|
136
145
|
function transform(c){
|
|
137
146
|
const authored=c.transform,current=overrides.get(c.runtimeId??c.id)?.transform??authored;
|
|
138
147
|
const layout=responsiveLayouts.get(c.prototypeId??c.id);
|
|
@@ -148,7 +157,7 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
148
157
|
}
|
|
149
158
|
const anchor=layout.anchor??'none';
|
|
150
159
|
if(anchor==='none'&&!layout.respectSafeArea)return pressTransform(c,result);
|
|
151
|
-
const safe=layout.respectSafeArea?computeSafeArea(
|
|
160
|
+
const bounds=anchorBounds(stage),safe=layout.respectSafeArea?computeSafeArea(bounds):bounds,p=props(c),mx=layout.marginX??0,my=layout.marginY??0;
|
|
152
161
|
const width=Math.abs(result[0])*p.width+Math.abs(result[2])*p.height,height=Math.abs(result[1])*p.width+Math.abs(result[3])*p.height;
|
|
153
162
|
if(anchor!=='none'){
|
|
154
163
|
result[4]=anchor.endsWith('left')?safe.left+mx:anchor.endsWith('right')?safe.right-width-mx:(safe.left+safe.right-width)/2;
|
|
@@ -369,7 +378,17 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
369
378
|
function body3dState(c,behavior){
|
|
370
379
|
let body=bodies3d.get(c.id);if(body)return body;
|
|
371
380
|
const p=props(c),stageComp=findStage3dOf(c);
|
|
372
|
-
|
|
381
|
+
const fitted={};
|
|
382
|
+
if(behavior.parameters.fitColliderFromModel&&stageComp&&stage3dMgr){
|
|
383
|
+
stage3dMgr.getStage(stageComp);
|
|
384
|
+
const mb=stage3dMgr.modelBoundsFor(c.id);
|
|
385
|
+
if(mb){
|
|
386
|
+
const hx=Math.max(.02,mb.width*Math.abs(p.sx??1)*.5);
|
|
387
|
+
const hz=Math.max(.02,mb.depth*Math.abs(p.sz??1)*.5);
|
|
388
|
+
fitted.hx=hx;fitted.hz=hz;fitted.radius=Math.max(.02,Math.max(hx,hz));
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
body={id:c.id,sourceId:behavior.componentId,stageId:stageComp?.id,x:p.x??0,y:p.y??0,z:p.z??0,vx:0,vy:0,vz:0,spin:0,atRest:true,captured:false,captureElapsed:0,airborne:false,restElapsed:0,movingTime:0,lastSafe:{x:p.x??0,y:p.y??0,z:p.z??0},...behavior.parameters,...fitted};
|
|
373
392
|
bodies3d.set(c.id,body);return body;
|
|
374
393
|
}
|
|
375
394
|
function collect3d(){
|
|
@@ -405,6 +424,9 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
405
424
|
}});
|
|
406
425
|
for(const body of bodies)if(body.captured)body.captureElapsed=(body.captureElapsed??0)+dt;
|
|
407
426
|
tickFps3d(dt,walls);
|
|
427
|
+
stage3dMgr.stepAnimations(dt,(compId,sourceId,clipName)=>{
|
|
428
|
+
emit({kind:'modelAnimationEnd',componentId:sourceId,...(compId!==sourceId?{selfInstanceId:compId,instanceId:compId}:{}),clipName});
|
|
429
|
+
});
|
|
408
430
|
}
|
|
409
431
|
function ensureFpsState(behavior){
|
|
410
432
|
let st=fpsStates.get(behavior.componentId);
|
|
@@ -459,20 +481,60 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
459
481
|
for(const c of targetsFor(source)){
|
|
460
482
|
if(!visible(c))continue;
|
|
461
483
|
const stageComp=findStage3dOf(c),fps=stageComp?fpsStates.get(stageComp.id):undefined;if(!fps)continue;
|
|
462
|
-
const mp=props(c),cx=mp.x??0,cz=mp.z??0,dx=fps.x-cx,dz=fps.z-cz,dist=Math.hypot(dx,dz),stop=p.stopDistance??2.5;
|
|
463
|
-
let nx=cx,nz=cz;
|
|
464
|
-
|
|
484
|
+
const mp=props(c),cx=mp.x??0,cy=mp.y??0,cz=mp.z??0,dx=fps.x-cx,dz=fps.z-cz,dist=Math.hypot(dx,dz),stop=p.stopDistance??2.5;
|
|
485
|
+
let nx=cx,ny=cy,nz=cz;
|
|
486
|
+
const homingBolt=p.mode==='chase-camera'&&stop<=.5;
|
|
487
|
+
if(p.mode==='chase-camera'&&dist>stop&&dist>1e-4){const step=Math.min(dist-stop,p.speed*dt);nx+=dx/dist*step;nz+=dz/dist*step;if(homingBolt)ny+=(fps.y-.14-cy)*(step/dist);}
|
|
465
488
|
else if(p.mode==='strafe-camera'&&dist>1e-4){const tx=-dz/dist,tz=dx/dist;nx+=tx*p.speed*dt;nz+=tz*p.speed*dt;}
|
|
466
489
|
else if(p.mode==='patrol'){nx+=Math.cos(time*1.5)*p.speed*dt;}
|
|
467
|
-
const stageWalls=walls.filter(w=>w.stageId===stageComp.id&&w.id!==c.id);
|
|
468
|
-
const resolved=resolveWallSlide3d(nx,nz,.45,stageWalls,p.boundsX??12,p.boundsZ??12);
|
|
490
|
+
const stageWalls=homingBolt?[]:walls.filter(w=>w.stageId===stageComp.id&&w.id!==c.id);
|
|
491
|
+
const resolved=homingBolt?{x:nx,z:nz}:resolveWallSlide3d(nx,nz,.45,stageWalls,p.boundsX??12,p.boundsZ??12);
|
|
469
492
|
const o=overrides.get(c.id)??{transform:[...c.transform],parameters:{}};
|
|
470
|
-
o.parameters.x=resolved.x;o.parameters.z=resolved.z;
|
|
493
|
+
o.parameters.x=resolved.x;if(homingBolt)o.parameters.y=ny;o.parameters.z=resolved.z;
|
|
471
494
|
if(p.faceCamera!==false)o.parameters.ry=Math.atan2(fps.x-resolved.x,fps.z-resolved.z);
|
|
472
495
|
overrides.set(c.id,o);
|
|
473
496
|
}
|
|
474
497
|
}
|
|
475
498
|
}
|
|
499
|
+
function worldPose3d(c){
|
|
500
|
+
const chain=[];for(let cur=c;cur&&cur.contract==='native.mesh3d.v1';cur=object(cur.parentId))chain.push(cur);
|
|
501
|
+
let x=0,y=0,z=0,ry=0;
|
|
502
|
+
for(let i=chain.length-1;i>=0;i--){
|
|
503
|
+
const n=chain[i],b=bodies3d.get(n.id),mp=props(n);
|
|
504
|
+
const lx=b?b.x:(mp.x??0),ly=b?(b.y??mp.y??0):(mp.y??0),lz=b?b.z:(mp.z??0);
|
|
505
|
+
const co=Math.cos(ry),si=Math.sin(ry);
|
|
506
|
+
x+=lx*co+lz*si;y+=ly;z+=-lx*si+lz*co;ry+=mp.ry??0;
|
|
507
|
+
}
|
|
508
|
+
return {x,y,z,ry};
|
|
509
|
+
}
|
|
510
|
+
let emitter3dCursor=0;
|
|
511
|
+
function spawnAction3d(a){
|
|
512
|
+
const count=Math.max(1,Math.min(16,Math.floor(a.count??1)));
|
|
513
|
+
if(a.fromComponentId!==undefined||a.fromTeam!==undefined){
|
|
514
|
+
let emitters=[];
|
|
515
|
+
if(a.fromComponentId!==undefined){
|
|
516
|
+
const src=byId.get(a.fromComponentId);
|
|
517
|
+
if(src&&src.sceneId===scene)emitters=targetsFor(src).filter(n=>visible(n)&&(instanceState(n)?.hp??1)>0);
|
|
518
|
+
}else{
|
|
519
|
+
const seen=new Set();
|
|
520
|
+
for(const n of [...project.components,...instances]){
|
|
521
|
+
if(n.contract!=='native.mesh3d.v1'||n.sceneId!==scene||n.prototype||seen.has(n.id)||!visible(n))continue;
|
|
522
|
+
const st=instanceState(n);
|
|
523
|
+
if(st&&st.hp>0&&(a.fromTeam==='any'||st.team===a.fromTeam)){seen.add(n.id);emitters.push(n);}
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
if(!emitters.length)return;
|
|
527
|
+
const ox=a.offsetX??0,oy=a.offsetY??0,oz=a.offsetZ??0;
|
|
528
|
+
for(let i=0;i<count;i++){
|
|
529
|
+
const em=emitters[(emitter3dCursor++)%emitters.length],pose=worldPose3d(em);
|
|
530
|
+
const co=Math.cos(pose.ry),si=Math.sin(pose.ry);
|
|
531
|
+
const jx=a.jitterX?(instanceEngine.rng.next()*2-1)*a.jitterX:0,jz=a.jitterZ?(instanceEngine.rng.next()*2-1)*a.jitterZ:0;
|
|
532
|
+
spawnPrototype3d(a.prototypeId,pose.x+ox*co+oz*si+jx,pose.y+oy,pose.z-ox*si+oz*co+jz);
|
|
533
|
+
}
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
for(let index=0;index<count;index++){const jx=a.jitterX?(instanceEngine.rng.next()*2-1)*a.jitterX:0,jz=a.jitterZ?(instanceEngine.rng.next()*2-1)*a.jitterZ:0;spawnPrototype3d(a.prototypeId,a.x+jx,a.y,a.z+jz);}
|
|
537
|
+
}
|
|
476
538
|
function spawnPrototype3d(prototypeId,x,y,z){
|
|
477
539
|
if(instances.length>=128){diagnose('Instance budget exhausted');return;}
|
|
478
540
|
const proto=byId.get(prototypeId),size=id=>1+project.components.filter(c=>c.parentId===id).reduce((sum,c)=>sum+size(c.id),0);
|
|
@@ -484,12 +546,19 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
484
546
|
function performRaycast3d(a){
|
|
485
547
|
if(!stage3dMgr)return;
|
|
486
548
|
const stageComp=byId.get(a.stageId);if(!stageComp||stageComp.sceneId!==scene)return;
|
|
549
|
+
stage3dMgr.triggerRecoil?.(stageComp.id);
|
|
487
550
|
const p=props(stageComp),m=world(stageComp),sx=Math.hypot(m[0],m[1]),sy=Math.hypot(m[2],m[3]);
|
|
488
|
-
const
|
|
551
|
+
const prev=stage3dMgr.getStage(stageComp),useBleed=Boolean(prev?.isFullBleed&&prev.lastWidth>0&&prev.lastHeight>0);
|
|
552
|
+
const {entry}=stage3dMgr.syncStage(stageComp,{time,ambientTime,propsOf:props,bodies3d,fpsPose:fpsStates.get(stageComp.id),instances3d:live3dInstances(stageComp.id),aimLocked:Boolean(aiming3d),groundFn:ground3d,worldWidth:useBleed?prev.lastWidth:p.width*sx,worldHeight:useBleed?prev.lastHeight:p.height*sy,designHeight:useBleed?prev.lastDesignH:p.height*sy});
|
|
489
553
|
let ndcX=0,ndcY=0;
|
|
490
554
|
if(a.mode==='pointer'){
|
|
491
|
-
|
|
492
|
-
|
|
555
|
+
if(useBleed){
|
|
556
|
+
ndcX=(lastPointer.x-prev.lastX)/Math.max(1,prev.lastWidth)*2-1;
|
|
557
|
+
ndcY=1-(lastPointer.y-prev.lastY)/Math.max(1,prev.lastHeight)*2;
|
|
558
|
+
}else{
|
|
559
|
+
const local=point(inverseMatrix(m),lastPointer.x,lastPointer.y);
|
|
560
|
+
ndcX=local.x/Math.max(1,p.width)*2-1;ndcY=1-local.y/Math.max(1,p.height)*2;
|
|
561
|
+
}
|
|
493
562
|
}
|
|
494
563
|
const occluders=new Set(project.gameplay.filter(b=>b.kind==='physics-3d'&&b.parameters.mode!=='dynamic').map(b=>b.componentId));
|
|
495
564
|
const team=a.targetTeam??'any';
|
|
@@ -509,14 +578,20 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
509
578
|
const entry=stage3dMgr.getStage(stageComp);if(!entry||!entry.lastWidth||!entry.lastHeight)return null;
|
|
510
579
|
const body=bodies3d.get(c.id),p=props(c);
|
|
511
580
|
const local=entry.project({x:body?body.x:(p.x??0),y:body?body.y:(p.y??0),z:body?body.z:(p.z??0)},entry.lastWidth,entry.lastHeight);
|
|
512
|
-
return point(world(stageComp),local.x,local.y);
|
|
581
|
+
return entry.isFullBleed?{x:entry.lastX+local.x,y:entry.lastY+local.y}:point(world(stageComp),local.x,local.y);
|
|
513
582
|
}
|
|
514
583
|
function aim3dVelocity(){
|
|
515
584
|
if(!aiming3d||!stage3dMgr)return {vx:0,vz:0,power:0,pull:0};
|
|
516
585
|
const stageComp=byId.get(aiming3d.stageId),entry=stage3dMgr.getStage(stageComp),body=bodies3d.get(aiming3d.targetId),bp=aiming3d.behavior.parameters;
|
|
517
586
|
if(!entry||!body||!entry.lastWidth||!entry.lastHeight)return {vx:0,vz:0,power:0,pull:0};
|
|
518
|
-
|
|
519
|
-
|
|
587
|
+
let sLocal,cLocal;
|
|
588
|
+
if(entry.isFullBleed){
|
|
589
|
+
sLocal={x:aiming3d.start.x-entry.lastX,y:aiming3d.start.y-entry.lastY};
|
|
590
|
+
cLocal={x:aiming3d.current.x-entry.lastX,y:aiming3d.current.y-entry.lastY};
|
|
591
|
+
}else{
|
|
592
|
+
const inv=inverseMatrix(world(stageComp));
|
|
593
|
+
sLocal=point(inv,aiming3d.start.x,aiming3d.start.y);cLocal=point(inv,aiming3d.current.x,aiming3d.current.y);
|
|
594
|
+
}
|
|
520
595
|
const pull=Math.hypot(aiming3d.current.x-aiming3d.start.x,aiming3d.current.y-aiming3d.start.y);
|
|
521
596
|
const a=entry.unproject(sLocal.x,sLocal.y,entry.lastWidth,entry.lastHeight,body.y);
|
|
522
597
|
const b=entry.unproject(cLocal.x,cLocal.y,entry.lastWidth,entry.lastHeight,body.y);
|
|
@@ -547,7 +622,7 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
547
622
|
};
|
|
548
623
|
}
|
|
549
624
|
/* 3d:end */
|
|
550
|
-
function reset(){lastEndScene=undefined;cancelInput();joysticks.clear();dropOccupancy.clear();dragOrigins.clear();swipeCooldowns.clear();instanceEngine.reset();maskStates.clear();strokeStates.clear();strokeWallBodies=[];activeJoints=[];pathFollowers.clear();brokenJoints.clear();ctaAppearances.clear();floatingTexts=[];screenFlashes=[];shake=undefined;tutorialInputAt=0;tutorialHadInput=false;activeTutorialHands=0;variables=Object.fromEntries(project.variables.map(v=>[v.id,v.initial]));stopAudio();blockedAudio=0;runtimeNodes.clear();spriteMotion.clear();physicsBodies.clear();oscillations.clear();/* 3d:start */bodies3d.clear();oscillations3d.clear();projected3d.clear();fpsStates.clear();stage3dMgr?.reset();/* 3d:end */meterStates.clear();cameraStates.clear();aiming=undefined;instances=[];particles=[];animations=[];overrides.clear();resetMatch();timers.clear();contacts.clear();contactPairs.clear();queue=[];time=0;ambientTime=0;serial=0;halted=false;acc=0;scene=project.base.startScene;pressed=undefined;pressPointerId=undefined;hover=undefined;transition=undefined;if(!edit){initializeInstanceStates();resetBoards();initializePathNetworks();/* 3d:start */collect3d();initFpsControllers();/* 3d:end */syncPaths(0,false);initializeDropOccupancy();tickMetersAndCamera(0);emit({kind:'sceneEnter',sceneId:scene});}}
|
|
625
|
+
function reset(){delayedScene=undefined;lastEndScene=undefined;cancelInput();joysticks.clear();dropOccupancy.clear();dragOrigins.clear();swipeCooldowns.clear();instanceEngine.reset();maskStates.clear();strokeStates.clear();strokeWallBodies=[];activeJoints=[];pathFollowers.clear();brokenJoints.clear();ctaAppearances.clear();floatingTexts=[];screenFlashes=[];shake=undefined;tutorialInputAt=0;tutorialHadInput=false;activeTutorialHands=0;variables=Object.fromEntries(project.variables.map(v=>[v.id,v.initial]));stopAudio();blockedAudio=0;runtimeNodes.clear();spriteMotion.clear();physicsBodies.clear();oscillations.clear();/* 3d:start */bodies3d.clear();oscillations3d.clear();projected3d.clear();fpsStates.clear();emitter3dCursor=0;stage3dMgr?.reset();/* 3d:end */meterStates.clear();cameraStates.clear();aiming=undefined;instances=[];particles=[];animations=[];overrides.clear();resetMatch();timers.clear();contacts.clear();contactPairs.clear();queue=[];time=0;ambientTime=0;serial=0;halted=false;acc=0;scene=project.base.startScene;pressed=undefined;pressPointerId=undefined;hover=undefined;transition=undefined;if(!edit){initializeInstanceStates();resetBoards();initializePathNetworks();/* 3d:start */collect3d();initFpsControllers();/* 3d:end */syncPaths(0,false);initializeDropOccupancy();tickMetersAndCamera(0);emit({kind:'sceneEnter',sceneId:scene});}}
|
|
551
626
|
function flushPendingMusic(){
|
|
552
627
|
if(!audio||audio.state!=='running'||!pendingLoopAudio.size)return;
|
|
553
628
|
const queued=[...pendingLoopAudio.values()];
|
|
@@ -556,30 +631,57 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
556
631
|
}
|
|
557
632
|
function unlockAudio(fromGesture=false){if(!audio)return Promise.resolve(undefined);if(audio.state==='running'){Promise.resolve().then(flushPendingMusic);return Promise.resolve(audio);}if(!audioUnlock||fromGesture){const context=audio,attempt=Promise.resolve().then(()=>context.resume()).then(()=>{if(context.state==='running'){flushPendingMusic();return context;}return undefined;}).catch(()=>undefined).finally(()=>{if(audioUnlock===attempt)audioUnlock=undefined;});audioUnlock=attempt;}return audioUnlock;}
|
|
558
633
|
function updateAudioMix(){const voices=[...audioVoices.values()],speaking=voices.some(voice=>voice.bus==='voice'),stinger=voices.some(voice=>voice.bus==='stinger'),duck=stinger?.2:speaking?.25:1;for(const voice of voices){const volume=voice.volume*hostVolume*(voice.bus==='music'?duck:1);if(voice.gain.gain.setTargetAtTime)voice.gain.gain.setTargetAtTime(volume,audio.currentTime,.04);else voice.gain.gain.value=volume;}}
|
|
634
|
+
function buildSeamlessLoopBuffer(context,buffer){
|
|
635
|
+
if(!buffer||typeof context.createBuffer!=='function'||typeof buffer.getChannelData!=='function'||!buffer.numberOfChannels)return buffer;
|
|
636
|
+
const sr=buffer.sampleRate||44100,len=buffer.length;
|
|
637
|
+
if(len<Math.round(sr*.2))return buffer;
|
|
638
|
+
const channels=buffer.numberOfChannels,thresh=.002;
|
|
639
|
+
let first=len,last=0;
|
|
640
|
+
for(let c=0;c<channels;c++){
|
|
641
|
+
const data=buffer.getChannelData(c);
|
|
642
|
+
for(let i=0;i<first;i++)if(Math.abs(data[i])>thresh){first=i;break;}
|
|
643
|
+
for(let i=len-1;i>last;i--)if(Math.abs(data[i])>thresh){last=i;break;}
|
|
644
|
+
}
|
|
645
|
+
if(first>=last)return buffer;
|
|
646
|
+
const activeLen=last-first+1;
|
|
647
|
+
if(activeLen<Math.round(sr*.15))return buffer;
|
|
648
|
+
const fadeLen=Math.min(Math.round(sr*.06),Math.floor(activeLen*.1)),outLen=activeLen-fadeLen;
|
|
649
|
+
if(fadeLen<8||outLen<Math.round(sr*.1))return buffer;
|
|
650
|
+
const out=context.createBuffer(channels,outLen,sr);
|
|
651
|
+
for(let c=0;c<channels;c++){
|
|
652
|
+
const src=buffer.getChannelData(c),dst=out.getChannelData(c);
|
|
653
|
+
for(let i=0;i<fadeLen;i++){const t=i/fadeLen;dst[i]=src[first+i]*Math.sin(t*Math.PI*.5)+src[first+outLen+i]*Math.cos(t*Math.PI*.5);}
|
|
654
|
+
for(let i=fadeLen;i<outLen;i++)dst[i]=src[first+i];
|
|
655
|
+
}
|
|
656
|
+
return out;
|
|
657
|
+
}
|
|
559
658
|
function connectVoice(source,gain,b){const bus=b.parameters.bus??'sfx';source.connect(gain);gain.connect(audio.destination);audioSources.add(source);audioVoices.set(source,{gain,bus,volume:b.parameters.volume});source.onended=()=>{audioSources.delete(source);audioVoices.delete(source);if(b.parameters.loop)loopingAudio.delete(b.id);updateAudioMix();};updateAudioMix();}
|
|
560
659
|
async function sound(b){
|
|
561
660
|
if(audioSources.size>=32)return;
|
|
562
|
-
|
|
661
|
+
const shouldLoop=Boolean(b.parameters.loop);
|
|
662
|
+
if(!audio){if(shouldLoop)pendingLoopAudio.set(b.id,b);return;}
|
|
563
663
|
const context=audio,epoch=audioEpoch,cooldown=b.parameters.cooldownMs??45,now=context.currentTime;
|
|
564
664
|
if(cooldown>0&&now-(audioCooldowns.get(b.id)??-Infinity)<cooldown/1000)return;
|
|
565
|
-
if(
|
|
665
|
+
if(shouldLoop&&loopingAudio.has(b.id))return;
|
|
566
666
|
const target=byId.get(b.componentId),asset=assets.get(target?.assetSlots[0]?.assetId),isSampled=asset?.mime==='audio/wav'||asset?.mime==='audio/mpeg';
|
|
567
667
|
if(!isSampled&&b.parameters.allowSynthFallback===false){blockedAudio++;return;}
|
|
568
668
|
audioCooldowns.set(b.id,now);
|
|
569
|
-
if(context.state!=='running'&&!await unlockAudio()){if(
|
|
669
|
+
if(context.state!=='running'&&!await unlockAudio()){if(shouldLoop)pendingLoopAudio.set(b.id,b);return;}
|
|
570
670
|
if(audio!==context||context.state!=='running'||epoch!==audioEpoch||audioSources.size>=32)return;
|
|
571
671
|
const count=audioPitchCounts.get(b.id)??0,pattern=[0,-.5,.5,-1,1],jitter=(b.parameters.pitchJitter??0)*pattern[count%pattern.length],combo=Number(variables[b.parameters.pitchVariableId]??0),pitch=Math.max(-12,Math.min(12,jitter+combo*(b.parameters.pitchStep??0))),playbackRate=2**(pitch/12);
|
|
572
672
|
audioPitchCounts.set(b.id,count+1);
|
|
573
673
|
if(isSampled){
|
|
574
|
-
if(
|
|
674
|
+
if(shouldLoop)loopingAudio.add(b.id);
|
|
575
675
|
try{
|
|
576
676
|
let buffer=decodedAudio.get(asset.hash);
|
|
577
677
|
if(!buffer){const bin=atob(asset.data),raw=new Uint8Array(bin.length);for(let i=0;i<bin.length;i++)raw[i]=bin.charCodeAt(i);buffer=await new Promise((resolve,reject)=>{
|
|
578
678
|
const pending=context.decodeAudioData(raw.buffer,resolve,reject);
|
|
579
679
|
if(pending&&typeof pending.then==='function')pending.then(resolve,reject);
|
|
580
680
|
});decodedAudio.set(asset.hash,buffer);}
|
|
581
|
-
if(audio!==context||context.state!=='running'||epoch!==audioEpoch||audioSources.size>=32){if(
|
|
582
|
-
|
|
681
|
+
if(audio!==context||context.state!=='running'||epoch!==audioEpoch||audioSources.size>=32){if(shouldLoop&&epoch===audioEpoch)loopingAudio.delete(b.id);return;}
|
|
682
|
+
let playBuffer=buffer;
|
|
683
|
+
if(shouldLoop){playBuffer=decodedLoopAudio.get(asset.hash);if(!playBuffer){playBuffer=buildSeamlessLoopBuffer(context,buffer);decodedLoopAudio.set(asset.hash,playBuffer);}}
|
|
684
|
+
const source=context.createBufferSource(),gain=context.createGain();source.buffer=playBuffer;source.loop=shouldLoop;if(source.playbackRate)source.playbackRate.value=playbackRate;if(shouldLoop&&gain.gain.setValueAtTime&&gain.gain.linearRampToValueAtTime){gain.gain.setValueAtTime(.0001,context.currentTime);gain.gain.linearRampToValueAtTime(b.parameters.volume,context.currentTime+.025);}else gain.gain.value=b.parameters.volume;connectVoice(source,gain,b);source.start();
|
|
583
685
|
}catch{loopingAudio.delete(b.id);diagnose('Audio decode failed');}
|
|
584
686
|
return;
|
|
585
687
|
}
|
|
@@ -676,13 +778,20 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
676
778
|
const root=cloneNode(proto,undefined);root.transform[4]=x;root.transform[5]=y;if(path){root.pathStartNode=path.startNode;root.pathTargetNode=path.targetNode;root.parentId=project.gameplay.find(b=>b.id===path.networkBehaviorId)?.componentId;}instances.push(root);initializeInstanceState(root);initializeDropOccupancy(root);if(path)syncPaths(0,false);return root;
|
|
677
779
|
}
|
|
678
780
|
function action(a,event,bindingCondition){if(++frameActions>1024){diagnose('Action budget exhausted');return;}if(a.kind==='add'||a.kind==='set'){const old=variables[a.variableId],value=a.kind==='add'?old+a.value:a.value;if(typeof value==='number'&&(!Number.isFinite(value)||Math.abs(value)>1e12)){diagnose('Variable range exceeded');return;}variables[a.variableId]=value;if(old!==value)emit({kind:'variableChange',variableId:a.variableId,instanceId:event.instanceId});}
|
|
781
|
+
/* 3d:start */
|
|
782
|
+
else if(a.kind==='setAsset'&&object(a.componentId)?.contract==='native.mesh3d.v1'){
|
|
783
|
+
const c=object(a.componentId),o=overrides.get(c.id)??{transform:[...c.transform],parameters:{}};
|
|
784
|
+
(o.slots??={})[a.slotId??'source']=a.assetId;overrides.set(c.id,o);
|
|
785
|
+
}
|
|
786
|
+
/* 3d:end */
|
|
679
787
|
else if(a.kind==='setComponent'||a.kind==='setAsset'){const c=object(a.componentId);if(!c)return;const o=overrides.get(c.id)??{transform:[...c.transform],parameters:{}};if(a.kind==='setComponent')o.parameters[a.key]=a.valueVariableId?variables[a.valueVariableId]:a.value;else o.assetId=a.assetId;overrides.set(c.id,o);if(a.kind==='setComponent'&&a.key==='visible'&&a.value===false){dropOccupancy.release(c.id);gestureTweens.cancel(c.id);}}
|
|
680
788
|
else if(a.kind==='resetMatch'){resetMatch(a.componentId);resetBoards(a.componentId);}
|
|
681
789
|
else if(a.kind==='clearStrokes'){strokeStates.get(a.componentId)?.clear();strokeWallBodies=strokeWallBodies.filter(wall=>wall.owner!==a.componentId);}
|
|
682
790
|
else if(a.kind==='resetMask'){const c=object(a.componentId),behavior=behaviorOn('erase-mask',a.componentId);if(c&&behavior)maskState(c,behavior).reset();}
|
|
683
791
|
/* 3d:start */
|
|
684
792
|
else if(a.kind==='raycast3d'){performRaycast3d(a);}
|
|
685
|
-
else if(a.kind==='spawnAt3d'){
|
|
793
|
+
else if(a.kind==='spawnAt3d'){spawnAction3d(a);}
|
|
794
|
+
else if(a.kind==='playModelAnimation'){stage3dMgr?.playModelAnimation(a.componentId,a);}
|
|
686
795
|
/* 3d:end */
|
|
687
796
|
else if(a.kind==='copyMatchAsset'){
|
|
688
797
|
const last=matchBoards.get(a.boardId)?.snapshot().lastMatch,target=byId.get(a.componentId),sample=last&&matchArtwork.get(a.boardId)?.get(last.group)?.children.find(child=>child.contract==='native.image.v1');
|
|
@@ -741,7 +850,11 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
741
850
|
if(a.round)value=Math.round(value);if(!Number.isFinite(value)||Math.abs(value)>1e12){diagnose('Variable range exceeded');return;}const old=variables[a.variableId];variables[a.variableId]=value;if(old!==value)emit({kind:'variableChange',variableId:a.variableId,instanceId:event.instanceId});
|
|
742
851
|
}
|
|
743
852
|
else if(a.kind==='despawn'){const self=event.selfInstanceId??event.instanceId;if(a.target==='other')despawn(event.otherInstanceId);else if(a.target==='both'){despawn(self);despawn(event.otherInstanceId);}else despawn(self);}
|
|
744
|
-
else if(a.kind==='changeScene')
|
|
853
|
+
else if(a.kind==='changeScene'){
|
|
854
|
+
if(a.delaySeconds>0){
|
|
855
|
+
if(a.sceneId!==scene)delayedScene??={sceneId:a.sceneId,at:time+a.delaySeconds};
|
|
856
|
+
}else transition=a.sceneId;
|
|
857
|
+
}
|
|
745
858
|
else if(a.kind==='restart'){bridge?.notifyGameRetry?.();transition='__restart';}
|
|
746
859
|
else if(a.kind==='cameraShake'){if(!reducedMotion?.matches)shake={intensity:a.intensity,seconds:a.seconds,elapsed:0};}
|
|
747
860
|
else if(a.kind==='screenFlash'){screenFlashes.push({color:a.color,opacity:a.opacity,seconds:a.seconds,elapsed:0});if(screenFlashes.length>8)screenFlashes.shift();}
|
|
@@ -772,6 +885,30 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
772
885
|
if(isVectorConfetti&&p.coverage==='screen'){particles.push(...screenVectorConfetti(p));return;}
|
|
773
886
|
const source=byId.get(behavior.componentId);
|
|
774
887
|
const c=event.instanceId?[...runtimeNodes.values()].find(node=>node.instanceId===event.instanceId&&node.prototypeId===source.id)??source:source;
|
|
888
|
+
/* 3d:start */
|
|
889
|
+
if(p.origin==='contact-3d'){
|
|
890
|
+
if(reducedMotion?.matches)return;
|
|
891
|
+
const stage=findStage3dOf(c);
|
|
892
|
+
if(!stage)return;
|
|
893
|
+
const origin=contactOrigin3d(c,object,props,bodies3d);
|
|
894
|
+
const colors=[p.color,p.color2,p.color3].filter(Boolean);
|
|
895
|
+
const rng=createRng(seedFromText(c.id+':'+time.toFixed(3)));
|
|
896
|
+
const spread=(p.spread??360)*Math.PI/180,heading=(p.direction??-90)*Math.PI/180;
|
|
897
|
+
for(let n=0;n<p.count;n++){
|
|
898
|
+
const angle=heading+spread*(rng.next()-.5);
|
|
899
|
+
// This emitter uses the existing speed/gravity controls at 100 px per world unit.
|
|
900
|
+
const speed=p.speed/100*rng.between(.42,1.1);
|
|
901
|
+
particles.push({
|
|
902
|
+
...origin,stageId:stage.id,shape:'contact-3d',confetti:isVectorConfetti,age:0,
|
|
903
|
+
vx:Math.cos(angle)*speed,vy:rng.between(.55,.95)*speed,vz:Math.sin(angle)*speed,
|
|
904
|
+
life:(p.lifetime??.5)*rng.between(.7,1),gravity:(p.gravity??300)/100,
|
|
905
|
+
color:colors[n%colors.length],size:rng.between(.024,.058),
|
|
906
|
+
spinX:rng.between(-13,13),spinZ:rng.between(-17,17),
|
|
907
|
+
});
|
|
908
|
+
}
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
/* 3d:end */
|
|
775
912
|
let matrix=transform(c),clipId;
|
|
776
913
|
for(let parent=object(c.parentId);parent;parent=object(parent.parentId)){
|
|
777
914
|
if(isConfetti&&parent.contract==='native.group.v1'&&props(parent).clip){clipId=parent.id;break;}
|
|
@@ -783,13 +920,20 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
783
920
|
{x:matrix[4]+c.parameters.width/2,y:matrix[5]+c.parameters.height/2};
|
|
784
921
|
if(isPixelConfetti){particles.push(...pixelConfetti(p,position,clipId));return;}
|
|
785
922
|
if(isVectorConfetti){particles.push(...vectorConfetti(p,position,clipId));return;}
|
|
923
|
+
const rng=createRng(seedFromText(c.id+':'+time.toFixed(3)));
|
|
786
924
|
for(let n=0;n<p.count;n++){
|
|
787
|
-
const angle
|
|
788
|
-
const speed=p.speed*(.5
|
|
925
|
+
const angle=-Math.PI/2+((n+rng.next())/p.count-.5)*(p.spread??360)*Math.PI/180;
|
|
926
|
+
const speed=p.speed*rng.between(.5,.95);
|
|
789
927
|
particles.push({...position,vx:Math.cos(angle)*speed,vy:Math.sin(angle)*speed,life:p.lifetime??.7,gravity:p.gravity??250,color:p.color,shape:p.shape??'circle'});
|
|
790
928
|
}
|
|
791
929
|
}
|
|
792
|
-
function
|
|
930
|
+
function enterScene(next){
|
|
931
|
+
if(next==='__restart'){reset();return;}
|
|
932
|
+
if(next===scene)return;
|
|
933
|
+
delayedScene=undefined;
|
|
934
|
+
const previous=scene;stopAudio();scene=next;joysticks.clear();dropOccupancy.clear();dragOrigins.clear();swipeCooldowns.clear();maskStates.clear();strokeStates.clear();strokeWallBodies=[];activeJoints=[];pathFollowers.clear();brokenJoints.clear();matchSelected=undefined;instances=[];particles=[];floatingTexts=[];screenFlashes=[];shake=undefined;tutorialHadInput=false;activeTutorialHands=0;runtimeNodes.clear();physicsBodies.clear();oscillations.clear();/* 3d:start */bodies3d.clear();oscillations3d.clear();projected3d.clear();fpsStates.clear();emitter3dCursor=0;stage3dMgr?.reset();/* 3d:end */meterStates.clear();cameraStates.clear();aiming=undefined;initializePathNetworks();queue=queue.filter(e=>e.kind==='variableChange');overrides.clear();matchGesture=undefined;for(const board of matchBoards.values())board.reset();contacts.clear();contactPairs.clear();timers.clear();animations=[];cancelInput();ctaAppearances.clear();pressed=undefined;pressPointerId=undefined;/* 3d:start */collect3d();initFpsControllers();/* 3d:end */syncPaths(0,false);initializeDropOccupancy();tickMetersAndCamera(0);emit({kind:'sceneExit',sceneId:previous});emit({kind:'sceneEnter',sceneId:scene});
|
|
935
|
+
}
|
|
936
|
+
function process(){while(queue.length&&!halted&&frameEvents<256&&frameActions<1024){const e=queue.shift();frameEvents++;const alive=id=>id===undefined||Boolean(object(id))||[...runtimeNodes.values()].some(node=>node.instanceId===id);if(!alive(e.selfInstanceId)||!alive(e.otherInstanceId))continue;if(['contactBegin','boundaryExit'].includes(e.kind)&&e.instanceId&&!runtimeNodes.has(e.instanceId))continue;for(const b of project.eventBindings){if(Object.entries(eventDefinitions.get(b.eventId)).every(([k,v])=>k==='id'||e[k]===v)&&condition(b.condition,e)){for(const a of b.actions){if(frameActions>=1024||halted)break;action(a,e,b.condition);}if(transition)break;}}if(transition){const next=transition;transition=undefined;enterScene(next);}}if(queue.length)diagnose('Event/action budget exhausted');}
|
|
793
937
|
function world(c){return multiplyMatrix(c.parentId?world(object(c.parentId)):identityMatrix(),transform(c));}
|
|
794
938
|
const point=(m,x,y)=>({x:m[0]*x+m[2]*y+m[4],y:m[1]*x+m[3]*y+m[5]});
|
|
795
939
|
function geometry(c,m){const p=props(c),corners=[[0,0],[p.width,0],[p.width,p.height],[0,p.height]].map(([x,y])=>point(m,x,y));return {left:Math.min(...corners.map(p=>p.x)),right:Math.max(...corners.map(p=>p.x)),top:Math.min(...corners.map(p=>p.y)),bottom:Math.max(...corners.map(p=>p.y))};}
|
|
@@ -814,12 +958,14 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
814
958
|
if(p.orientToMove)setComponentHeading(target,Math.atan2(j.ny,j.nx));
|
|
815
959
|
}
|
|
816
960
|
}
|
|
817
|
-
function tick(dt){const stage=viewport();time+=dt;
|
|
961
|
+
function tick(dt){const stage=viewport();time+=dt;
|
|
962
|
+
if(delayedScene&&time>=delayedScene.at)enterScene(delayedScene.sceneId);
|
|
963
|
+
tickCanvas(dt);tickGestureInput(dt);tickJoysticks(dt);tickSteering(dt);tickOscillations();
|
|
818
964
|
for(const [id,press]of pressStates)if(!press.held&&time-(press.releasedAt??time)>=press.behavior.springBackSeconds)pressStates.delete(id);
|
|
819
965
|
if(shake){shake.elapsed+=dt;if(shake.elapsed>=shake.seconds)shake=undefined;}
|
|
820
966
|
for(const flash of screenFlashes)flash.elapsed+=dt;screenFlashes=screenFlashes.filter(flash=>flash.elapsed<flash.seconds);
|
|
821
967
|
for(const floating of floatingTexts)floating.elapsed+=dt;floatingTexts=floatingTexts.filter(floating=>floating.elapsed<floating.seconds);
|
|
822
|
-
for(const [id,board]of matchBoards)if(byId.get(id).sceneId===scene&&visible(byId.get(id)))board.tick(dt);for(const b of project.gameplay){const source=byId.get(b.componentId);if(source.sceneId!==scene)continue;const targets=prototypeOwner(source)?[...runtimeNodes.values()].filter(i=>i.prototypeId===source.id):[source];for(const c of targets){const key=b.id+':'+c.id;if(b.kind==='motion'){const old=overrides.get(c.id)??{transform:[...c.transform],parameters:{}},v=old.velocity??{x:b.parameters.vx,y:b.parameters.vy};v.y+=b.parameters.gravity*dt;old.transform[4]+=v.x*dt;old.transform[5]+=v.y*dt;old.velocity=v;overrides.set(c.id,old);if(c.prototypeId)c.transform=old.transform;const location=world(c);if(location[5]>stage.height||location[4]<-300||location[4]>stage.width+300){if(!old.exited){old.exited=true;emit({kind:'boundaryExit',componentId:source.id,instanceId:c.instanceId});}}}else if(b.kind==='timer'){const t=(timers.get(key)??0)+dt;timers.set(key,t);if(t>=b.parameters.seconds&&t-dt<b.parameters.seconds){emit({kind:'timer',behaviorId:b.id,componentId:source.id});if(b.parameters.repeat)timers.set(key,t-b.parameters.seconds);}}}}
|
|
968
|
+
for(const [id,board]of matchBoards)if(byId.get(id).sceneId===scene&&visible(byId.get(id)))board.tick(dt);for(const b of project.gameplay){const source=byId.get(b.componentId);if(source.sceneId!==scene)continue;const targets=prototypeOwner(source)?[...runtimeNodes.values()].filter(i=>i.prototypeId===source.id):[source];for(const c of targets){const key=b.id+':'+c.id;if(b.kind==='motion'){const old=overrides.get(c.id)??{transform:[...c.transform],parameters:{}},v=old.velocity??{x:b.parameters.vx,y:b.parameters.vy};v.y+=b.parameters.gravity*dt;old.transform[4]+=v.x*dt;old.transform[5]+=v.y*dt;old.velocity=v;overrides.set(c.id,old);if(c.prototypeId)c.transform=old.transform;const location=world(c);if(location[5]>stage.height||location[4]<-300||location[4]>stage.width+300){if(!old.exited){old.exited=true;emit({kind:'boundaryExit',componentId:source.id,instanceId:c.instanceId});}}}else if(b.kind==='timer'){const t=(timers.get(key)??0)+dt;timers.set(key,t);if(t>=b.parameters.seconds&&t-dt<b.parameters.seconds){emit({kind:'timer',behaviorId:b.id,componentId:source.id,...(c.instanceId?{instanceId:c.instanceId,selfInstanceId:c.instanceId}:{})});if(b.parameters.repeat)timers.set(key,t-b.parameters.seconds);}}}}
|
|
823
969
|
tickPhysics(dt);/* 3d:start */tick3d(dt);/* 3d:end */syncPaths(dt);tickMetersAndCamera(dt);
|
|
824
970
|
const colliders=[];for(const b of project.gameplay.filter(b=>b.kind==='collider')){const c=byId.get(b.componentId);if(c.sceneId!==scene)continue;for(const target of prototypeOwner(c)?[...runtimeNodes.values()].filter(i=>i.prototypeId===c.id):[c])if(visible(target)){if(colliders.length>=256){diagnose('Collider budget exhausted');break;}colliders.push({b,c:target,box:geometry(target,world(target)),polygon:collisionPolygon(target,b.parameters.shape)});}}
|
|
825
971
|
const next=new Set(),nextPairs=new Map(),contactEvent=(kind,x,y)=>{if((x.c.prototypeId??x.c.id)===(y.c.prototypeId??y.c.id)&&x.c.id>y.c.id)return;emit({...instanceEvent(kind,x.c,y.c),instanceId:x.c.instanceId??y.c.instanceId});};let pairCount=0;collisionLoop:for(let a=0;a<colliders.length;a++)for(let b=a+1;b<colliders.length;b++){const x=colliders[a],y=colliders[b];if(x.c.instanceId&&x.c.instanceId===y.c.instanceId)continue;const A=x.box,B=y.box;let overlap=A.left<B.right&&A.right>B.left&&A.top<B.bottom&&A.bottom>B.top;if(overlap){if(++pairCount>4096){diagnose('Collision budget exhausted');break collisionLoop;}overlap=polygonsOverlap(x.polygon,y.polygon);}if(!overlap)continue;const key=[x.c.id,y.c.id].sort().join('|');next.add(key);nextPairs.set(key,[x,y]);if(!contacts.has(key))for(const [first,other]of [[x,y],[y,x]])contactEvent('contactBegin',first,other);}for(const [key,[x,y]]of contactPairs)if(!next.has(key))for(const [first,other]of [[x,y],[y,x]])contactEvent('contactEnd',first,other);contacts=next;contactPairs=nextPairs;
|
|
@@ -852,7 +998,7 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
852
998
|
}
|
|
853
999
|
animations=animations.filter(a=>object(a.targetId??a.componentId)&&(a.elapsed<a.parameters.seconds+(a.parameters.delay??0)||a.parameters.loop));
|
|
854
1000
|
for(const p of particles){
|
|
855
|
-
if(p.
|
|
1001
|
+
if(p.age!==undefined){p.age+=dt;continue;}
|
|
856
1002
|
p.life-=dt;p.x+=p.vx*dt;p.y+=p.vy*dt;p.vy+=p.gravity*dt;
|
|
857
1003
|
}
|
|
858
1004
|
particles=particles.filter(p=>p.life>(p.age??0));process();}
|
|
@@ -869,7 +1015,37 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
869
1015
|
}
|
|
870
1016
|
}}
|
|
871
1017
|
function spriteFrame(c,p,m){const pathFrame=overrides.get(c.id)?.pathFrame;if(pathFrame!==undefined)return Math.min(p.frameCount-1,pathFrame);if(edit||!p.frameRate)return 0;if(c.contract!=='native.walk-sprite.v1')return Math.floor(Math.max(0,time-(c.spawnTime??0))*p.frameRate)%p.frameCount;const key=c.runtimeId??c.id,prior=spriteMotion.get(key);if(!prior){spriteMotion.set(key,{x:m[4],y:m[5],phase:0,lastMove:-Infinity,frame:0});return 0;}const moved=Math.hypot(m[4]-prior.x,m[5]-prior.y)>.3;if(moved){const gap=time-prior.lastMove;prior.phase=Number.isFinite(gap)&&gap<.25?prior.phase+Math.min(gap,.12)*p.frameRate:0;prior.lastMove=time;}prior.x=m[4];prior.y=m[5];if(time-prior.lastMove>.11)prior.phase=0;prior.frame=Math.floor(prior.phase)%p.frameCount;return prior.frame;}
|
|
872
|
-
|
|
1018
|
+
let stageClipped=false,stageClipRect={width:390,height:700};
|
|
1019
|
+
/* 3d:start */
|
|
1020
|
+
let renderBleed,fullBleedAncestors=new Set();
|
|
1021
|
+
/* 3d:end */
|
|
1022
|
+
function clipStage(on){
|
|
1023
|
+
if(on===stageClipped)return;
|
|
1024
|
+
if(on){ctx.save();ctx.beginPath();ctx.rect(stageClipRect.left??0,stageClipRect.top??0,stageClipRect.width,stageClipRect.height);ctx.clip();stageClipped=true;}
|
|
1025
|
+
else{ctx.restore();stageClipped=false;}
|
|
1026
|
+
}
|
|
1027
|
+
function drawObject(c,parent=identityMatrix(),clips=[],instance,unstacked=false){if(c.contract==='native.mesh3d.v1')return;const p=props(c),maskBehavior=behaviorOn('erase-mask',c.prototypeId??c.id);if(!p.visible||p.opacity<=0)return;const m=multiplyMatrix(parent,transform(c));
|
|
1028
|
+
/* 3d:start */
|
|
1029
|
+
if(fullBleedAncestors.has(c.id)){
|
|
1030
|
+
paint.push({c,m,clips,instance:instance??c.prototypeId});
|
|
1031
|
+
for(const child of children(c.id))drawObject(child,m,clips,instance??c.prototypeId,true);
|
|
1032
|
+
return;
|
|
1033
|
+
}
|
|
1034
|
+
if(c.contract==='native.stage3d.v1'&&stage3dMgr&&renderBleed&&fullBleed3dIds.has(c.id)){
|
|
1035
|
+
clipStage(false);
|
|
1036
|
+
// Keep the authored camera framing as the clip region expands to the physical canvas.
|
|
1037
|
+
const entry=stage3dMgr.renderStage(c,ctx,renderBleed.pw,renderBleed.ph,renderBleed.w,renderBleed.h,{time,ambientTime,propsOf:props,bodies3d,fpsPose:fpsStates.get(c.id),instances3d:live3dInstances(c.id),contactParticles:reducedMotion?.matches?[]:particles.filter(p=>p.stageId===c.id),aimLocked:Boolean(aiming3d),groundFn:ground3d,worldWidth:renderBleed.w,worldHeight:renderBleed.h,designHeight:viewport().height,drawX:renderBleed.x,drawY:renderBleed.y,fullBleed:true});
|
|
1038
|
+
for(const [bid,body]of bodies3d)if(body.stageId===c.id&&body.mode==='dynamic'){
|
|
1039
|
+
const local=entry.project({x:body.x,y:body.y,z:body.z},renderBleed.w,renderBleed.h);
|
|
1040
|
+
projected3d.set(bid,{x:renderBleed.x+local.x,y:renderBleed.y+local.y});
|
|
1041
|
+
}
|
|
1042
|
+
paint.push({c,m,clips,instance:instance??c.prototypeId});
|
|
1043
|
+
for(const child of children(c.id))drawObject(child,m,clips,instance??c.prototypeId,true);
|
|
1044
|
+
return;
|
|
1045
|
+
}
|
|
1046
|
+
/* 3d:end */
|
|
1047
|
+
if(!stageClipped)clipStage(true);
|
|
1048
|
+
ctx.save();ctx.transform(...(unstacked?m:transform(c)));ctx.globalAlpha*=p.opacity;const press=pressStates.get(c.id);if(press?.behavior.liftShadow){ctx.shadowColor='#00000055';ctx.shadowBlur=8;ctx.shadowOffsetY=4;}let nextClips=clips;if(c.contract==='native.group.v1'&&p.clip){ctx.beginPath();ctx.rect(0,0,p.width,p.height);ctx.clip();nextClips=[...clips,{matrix:m,width:p.width,height:p.height}];}
|
|
873
1049
|
let maskRendered=false;
|
|
874
1050
|
if(!['native.group.v1','native.text.v1','native.image.v1','native.sprite.v1','native.walk-sprite.v1','native.stage3d.v1','native.mesh3d.v1'].includes(c.contract)){
|
|
875
1051
|
const button=c.contract==='native.button.v1',isPressed=pressed===c.id;
|
|
@@ -901,9 +1077,9 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
901
1077
|
if(['native.image.v1','native.sprite.v1','native.walk-sprite.v1'].includes(c.contract)&&!maskBehavior){const img=images.get(overrides.get(c.id)?.assetId??c.assetSlots[0]?.assetId);if(img?.complete&&img.naturalWidth){ctx.save();ctx.beginPath();ctx.rect(0,0,p.width,p.height);ctx.clip();const sprite=c.contract!=='native.image.v1',columns=sprite?Math.min(p.frameColumns,p.frameCount):1,rows=sprite?Math.ceil(p.frameCount/columns):1,sw=img.width/columns,sh=img.height/rows,frame=sprite?spriteFrame(c,p,m):0,sx=frame%columns*sw,sy=Math.floor(frame/columns)*sh,scale=p.fit==='cover'?Math.max(p.width/sw,p.height/sh):Math.min(p.width/sw,p.height/sh),w=p.fit==='stretch'?p.width:sw*scale,h=p.fit==='stretch'?p.height:sh*scale;ctx.imageSmoothingEnabled=p.smoothing??true;ctx.drawImage(img,sx,sy,sw,sh,(p.width-w)/2,(p.height-h)/2,w,h);ctx.restore();}}
|
|
902
1078
|
if(maskBehavior&&!maskRendered)maskState(c,maskBehavior).render(ctx);
|
|
903
1079
|
/* 3d:start */
|
|
904
|
-
if(c.contract==='native.stage3d.v1'&&stage3dMgr){
|
|
1080
|
+
if(c.contract==='native.stage3d.v1'&&stage3dMgr&&!fullBleed3dIds.has(c.id)){
|
|
905
1081
|
const sx=Math.hypot(m[0],m[1]),sy=Math.hypot(m[2],m[3]);
|
|
906
|
-
const entry=stage3dMgr.renderStage(c,ctx,p.width*sx*currentRenderScale*currentRenderDpr,p.height*sy*currentRenderScale*currentRenderDpr,p.width,p.height,{time,ambientTime,propsOf:props,bodies3d,fpsPose:fpsStates.get(c.id),instances3d:live3dInstances(c.id),aimLocked:Boolean(aiming3d),groundFn:ground3d,worldWidth:p.width*sx,worldHeight:p.height*sy});
|
|
1082
|
+
const entry=stage3dMgr.renderStage(c,ctx,p.width*sx*currentRenderScale*currentRenderDpr,p.height*sy*currentRenderScale*currentRenderDpr,p.width,p.height,{time,ambientTime,propsOf:props,bodies3d,fpsPose:fpsStates.get(c.id),instances3d:live3dInstances(c.id),contactParticles:reducedMotion?.matches?[]:particles.filter(p=>p.stageId===c.id),aimLocked:Boolean(aiming3d),groundFn:ground3d,worldWidth:p.width*sx,worldHeight:p.height*sy});
|
|
907
1083
|
for(const [bid,body]of bodies3d)if(body.stageId===c.id&&body.mode==='dynamic'){
|
|
908
1084
|
const local=entry.project({x:body.x,y:body.y,z:body.z},p.width,p.height);
|
|
909
1085
|
projected3d.set(bid,point(m,local.x,local.y));
|
|
@@ -988,18 +1164,18 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
988
1164
|
if(hoverDrop&&visible(hoverDrop.c)){const c=hoverDrop.c,p=props(c);ctx.save();ctx.transform(...world(c));ctx.strokeStyle=hoverDrop.highlightColor??'#ffffff';ctx.lineWidth=4;ctx.globalAlpha=.85;ctx.strokeRect(-4,-4,p.width+8,p.height+8);ctx.restore();}
|
|
989
1165
|
if(drag?.b.parameters.bringToFront){const c=object(drag.targetId);if(c)drawObject(c,c.parentId?world(object(c.parentId)):identityMatrix(),[],c.prototypeId);}
|
|
990
1166
|
}
|
|
991
|
-
function render(){previousCtaAppearances=ctaAppearances;ctaAppearances=new Map();const stage=viewport();if(paintedLandscape!==undefined&&paintedLandscape!==stage.landscape)cancelInput();paintedLandscape=stage.landscape;const dpr=Math.min(devicePixelRatio||1,2),w=canvas.clientWidth,h=canvas.clientHeight;if(canvas.width!==Math.round(w*dpr)||canvas.height!==Math.round(h*dpr)){canvas.width=Math.round(w*dpr);canvas.height=Math.round(h*dpr);}ctx.setTransform(dpr,0,0,dpr,0,0);ctx.fillStyle=stageBackdropColor(stage);ctx.fillRect(0,0,w,h);const scale=Math.min(w/stage.width,h/stage.height),ox=(w-stage.width*scale)/2,oy=(h-stage.height*scale)/2;currentRenderScale=scale||1;currentRenderDpr=dpr;ctx.translate(ox,oy);ctx.scale(scale,scale);if(shake){const progress=Math.min(1,shake.elapsed/shake.seconds),strength=shake.intensity*(1-progress);ctx.translate(Math.sin(shake.elapsed*95)*strength,Math.cos(shake.elapsed*113)*strength);}
|
|
1167
|
+
function render(){previousCtaAppearances=ctaAppearances;ctaAppearances=new Map();const stage=viewport();if(paintedLandscape!==undefined&&paintedLandscape!==stage.landscape)cancelInput();paintedLandscape=stage.landscape;const dpr=Math.min(devicePixelRatio||1,2),w=canvas.clientWidth,h=canvas.clientHeight;if(canvas.width!==Math.round(w*dpr)||canvas.height!==Math.round(h*dpr)){canvas.width=Math.round(w*dpr);canvas.height=Math.round(h*dpr);}ctx.setTransform(dpr,0,0,dpr,0,0);ctx.fillStyle=stageBackdropColor(stage);ctx.fillRect(0,0,w,h);const scale=Math.min(w/stage.width,h/stage.height),ox=(w-stage.width*scale)/2,oy=(h-stage.height*scale)/2;currentRenderScale=scale||1;currentRenderDpr=dpr;ctx.translate(ox,oy);ctx.scale(scale,scale);if(shake){const progress=Math.min(1,shake.elapsed/shake.seconds),strength=shake.intensity*(1-progress);ctx.translate(Math.sin(shake.elapsed*95)*strength,Math.cos(shake.elapsed*113)*strength);}stageClipRect=stage;stageClipped=false;/* 3d:start */renderBleed=undefined;fullBleedAncestors.clear();fullBleed3dIds.clear();if(stage3dMgr&&scale>0&&w>=2&&h>=2){renderBleed={x:-ox/scale,y:-oy/scale,w:w/scale,h:h/scale,pw:w*dpr,ph:h*dpr};for(const c of project.components){if(c.contract!=='native.stage3d.v1'||c.sceneId!==scene||c.prototype||!visible(c))continue;let ok=true;const anc=[];for(let cur=c.parentId?object(c.parentId):undefined;cur;cur=cur.parentId?object(cur.parentId):undefined){const cp=props(cur);if(cur.contract!=='native.group.v1'||cp.clip||cp.opacity<1){ok=false;break;}anc.push(cur.id);}if(!ok)continue;const m=world(c),p=props(c);if(Math.abs(m[1])>.001||Math.abs(m[2])>.001)continue;const sx=Math.hypot(m[0],m[1]),sy=Math.hypot(m[2],m[3]);if(m[4]>1||m[5]>1||m[4]+p.width*sx<stage.width-1||m[5]+p.height*sy<stage.height-1)continue;fullBleed3dIds.add(c.id);for(const id of anc)fullBleedAncestors.add(id);}}/* 3d:end */stageClipRect=anchorBounds(stage);paint=[];for(const c of roots())drawObject(c);clipStage(true);for(const c of instances)if(!c.parentId)drawObject(c,identityMatrix(),[],c.prototypeId);drawDropFeedback();drawAim();if(edit&&selected){let prototype=byId.get(selected);while(prototype?.parentId)prototype=byId.get(prototype.parentId);if(prototype?.prototype)drawObject(prototype);}drawConfetti();ctx.save();for(const p of particles){if(p.age!==undefined)continue;const fade=Math.min(1,p.life*2),radius=1.5+2.5*fade;ctx.globalAlpha=fade;ctx.globalCompositeOperation=p.shape==='square'?'source-over':'lighter';ctx.fillStyle=p.color;if(p.shape==='square'){const size=Math.max(2,Math.round(radius*1.6));ctx.fillRect(Math.round(p.x-size/2),Math.round(p.y-size/2),size,size);continue;}ctx.globalCompositeOperation='lighter';ctx.shadowColor=p.color;ctx.shadowBlur=particles.length<=16?6:0;ctx.strokeStyle=p.color;ctx.lineWidth=1.5+fade;ctx.beginPath();ctx.moveTo(p.x-p.vx*.025,p.y-p.vy*.025);ctx.lineTo(p.x,p.y);ctx.stroke();ctx.beginPath();ctx.arc(p.x,p.y,radius,0,Math.PI*2);ctx.fill();}ctx.restore();drawGameFeedback();if(edit&&selected){const rows=paint.filter(r=>r.c.contract!=='native.group.v1'&&(r.c.id===selected||isDescendant(r.c,selected)));if(rows.length){const boxes=rows.map(r=>geometry(r.c,r.m)),l=Math.min(...boxes.map(b=>b.left)),t=Math.min(...boxes.map(b=>b.top));ctx.strokeStyle='#55e6ef';ctx.lineWidth=2/scale;ctx.strokeRect(l,t,Math.max(...boxes.map(b=>b.right))-l,Math.max(...boxes.map(b=>b.bottom))-t);}}clipStage(false);if(scale>0)drawConfetti(undefined,{x:-ox/scale,y:-oy/scale,width:w/scale,height:h/scale});}
|
|
992
1168
|
function auditViewport(ids){
|
|
993
1169
|
const required=Array.isArray(ids)?[...new Set(ids)]:undefined;
|
|
994
1170
|
render();
|
|
995
|
-
const stage=viewport(),found=new Set(),issues=[];
|
|
1171
|
+
const stage=viewport(),boundsRect=anchorBounds(stage),found=new Set(),issues=[];
|
|
996
1172
|
for(const row of paint){
|
|
997
1173
|
const id=row.c.prototypeId??row.c.id;
|
|
998
1174
|
if(row.c.contract==='native.group.v1'||(required&&!required.includes(id)))continue;
|
|
999
1175
|
found.add(id);
|
|
1000
1176
|
const bounds=geometry(row.c,row.m),stroke=(props(row.c).strokeWidth??0)/2;
|
|
1001
1177
|
bounds.left-=stroke;bounds.right+=stroke;bounds.top-=stroke;bounds.bottom+=stroke;
|
|
1002
|
-
const overflow={left:Math.max(0
|
|
1178
|
+
const overflow={left:Math.max(0,boundsRect.left-bounds.left),right:Math.max(0,bounds.right-boundsRect.right),top:Math.max(0,boundsRect.top-bounds.top),bottom:Math.max(0,bounds.bottom-boundsRect.bottom)};
|
|
1003
1179
|
if(Object.values(overflow).some(value=>value>.01))issues.push({id,contract:row.c.contract,bounds,overflow});
|
|
1004
1180
|
}
|
|
1005
1181
|
const missing=required?required.filter(id=>!found.has(id)):[];
|
|
@@ -1008,11 +1184,11 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
1008
1184
|
function auditSceneLayout({ids,interactiveIds,network='standalone',minTouchPx=44}={}){
|
|
1009
1185
|
const required=Array.isArray(ids)?[...new Set(ids)]:undefined;
|
|
1010
1186
|
render();
|
|
1011
|
-
const stage=viewport(),scale=Math.min(canvas.clientWidth/stage.width,canvas.clientHeight/stage.height),safe=computeSafeArea(
|
|
1187
|
+
const stage=viewport(),boundsRect=anchorBounds(stage),scale=Math.min(canvas.clientWidth/stage.width,canvas.clientHeight/stage.height),safe=computeSafeArea(boundsRect,network),defects=[],found=new Set();
|
|
1012
1188
|
const selected=row=>!required||required.includes(row.c.prototypeId??row.c.id);
|
|
1013
1189
|
const rows=paint.filter(selected),automatic=new Set(project.events.filter(event=>event.kind==='click').map(event=>event.componentId));
|
|
1014
1190
|
for(const behavior of project.gameplay)if(['drag','match-tile','aim-launch','aim-launch-3d','swipe-input','hold-charge','virtual-joystick','draw-stroke','erase-mask'].includes(behavior.kind))automatic.add(behavior.componentId);
|
|
1015
|
-
const interactive=new Set(interactiveIds??automatic),anywhereAim=new Set(project.gameplay.filter(b=>['aim-launch','aim-launch-3d','swipe-input','hold-charge','draw-stroke','virtual-joystick'].includes(b.kind)&&(b.parameters.dragMode==='anywhere'||b.kind==='draw-stroke'||(b.kind==='virtual-joystick'&&b.parameters.mode==='floating'))).map(b=>b.componentId)),isInteractive=row=>interactive.has(row.c.prototypeId??row.c.id);
|
|
1191
|
+
const interactive=new Set(interactiveIds??automatic),anywhereAim=new Set([...project.gameplay.filter(b=>['aim-launch','aim-launch-3d','swipe-input','hold-charge','draw-stroke','virtual-joystick'].includes(b.kind)&&(b.parameters.dragMode==='anywhere'||b.kind==='draw-stroke'||(b.kind==='virtual-joystick'&&b.parameters.mode==='floating'))).map(b=>b.componentId),...project.components.filter(c=>c.contract==='native.stage3d.v1').map(c=>c.id)]),isInteractive=row=>interactive.has(row.c.prototypeId??row.c.id);
|
|
1016
1192
|
const add=(kind,severity,id,detail,metrics,otherId)=>defects.push({kind,severity,id,...(otherId?{otherId}:{}),detail,metrics});
|
|
1017
1193
|
const clippedBounds=clip=>{const corners=[[0,0],[clip.width,0],[clip.width,clip.height],[0,clip.height]].map(([x,y])=>point(clip.matrix,x,y));return {left:Math.min(...corners.map(p=>p.x)),right:Math.max(...corners.map(p=>p.x)),top:Math.min(...corners.map(p=>p.y)),bottom:Math.max(...corners.map(p=>p.y))};};
|
|
1018
1194
|
for(const row of rows){
|
|
@@ -1023,7 +1199,7 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
1023
1199
|
const isFullBleedBackdrop=(row.c.contract==='native.image.v1'&&row.clips.length===0&&props(row.c).fit==='cover'&&bounds.left<=0&&bounds.top<=0&&bounds.right>=stage.width&&bounds.bottom>=stage.height)||(row.c.contract==='native.stage3d.v1'&&bounds.left<=0&&bounds.top<=0&&bounds.right>=stage.width&&bounds.bottom>=stage.height);
|
|
1024
1200
|
const fullBleed=(row.c.contract==='native.rectangle.v1'&&stroke===0&&bounds.left<=0&&bounds.top<=0&&bounds.right>=stage.width&&bounds.bottom>=stage.height)||isFullBleedBackdrop;
|
|
1025
1201
|
if(!structural){
|
|
1026
|
-
const overflow={left:Math.max(0
|
|
1202
|
+
const overflow={left:Math.max(0,boundsRect.left-bounds.left),right:Math.max(0,bounds.right-boundsRect.right),top:Math.max(0,boundsRect.top-bounds.top),bottom:Math.max(0,bounds.bottom-boundsRect.bottom)};
|
|
1027
1203
|
if(!fullBleed&&!inCameraWorld(row.c)&&Object.values(overflow).some(value=>value>.01))add('stage-overflow','blocker',id,'Component extends beyond the active stage.',{bounds,overflow});
|
|
1028
1204
|
if(row.c.contract==='native.image.v1'&&row.clips.length===0){
|
|
1029
1205
|
const bw=bounds.right-bounds.left,bh=bounds.bottom-bounds.top;
|
|
@@ -1057,7 +1233,7 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
1057
1233
|
if(width>.01&&height>.01)add('sdk-safe-area-collision','blocker',id,'Component intersects a reserved ad-SDK overlay zone.',{bounds,zone,intersection:{width,height},network});
|
|
1058
1234
|
}
|
|
1059
1235
|
}
|
|
1060
|
-
const interactiveRows=rows.filter(row=>isInteractive(row)&&row.c.contract!=='native.group.v1');
|
|
1236
|
+
const interactiveRows=rows.filter(row=>isInteractive(row)&&row.c.contract!=='native.group.v1'&&row.c.contract!=='native.stage3d.v1');
|
|
1061
1237
|
for(let first=0;first<interactiveRows.length;first++)for(let second=first+1;second<interactiveRows.length;second++){
|
|
1062
1238
|
const a=interactiveRows[first],b=interactiveRows[second],aid=a.c.prototypeId??a.c.id,bid=b.c.prototypeId??b.c.id;
|
|
1063
1239
|
if(aid===bid||isDescendant(a.c,b.c.id)||isDescendant(b.c,a.c.id))continue;
|
|
@@ -1195,7 +1371,7 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
1195
1371
|
const stage=viewport(),r=canvas.getBoundingClientRect(),scale=Math.min(r.width/stage.width,r.height/stage.height);
|
|
1196
1372
|
return {x:(e.clientX-r.left-(r.width-stage.width*scale)/2)/scale,y:(e.clientY-r.top-(r.height-stage.height*scale)/2)/scale};
|
|
1197
1373
|
}
|
|
1198
|
-
function inside(row,p){try{for(const clip of row.clips){const q=point(inverseMatrix(clip.matrix),p.x,p.y);if(q.x<0||q.y<0||q.x>clip.width||q.y>clip.height)return false;}const q=point(inverseMatrix(row.m),p.x,p.y),v=props(row.c);if(row.c.contract==='native.path.v1'){const path=new Path2D();for(const [cmd,...args]of v.commands)({M:()=>path.moveTo(...args),L:()=>path.lineTo(...args),C:()=>path.bezierCurveTo(...args),Q:()=>path.quadraticCurveTo(...args),Z:()=>path.closePath()})[cmd]();ctx.save();ctx.setTransform(1,0,0,1,0,0);ctx.lineWidth=v.strokeWidth;const hit=ctx.isPointInPath(path,q.x,q.y)||(v.strokeWidth>0&&ctx.isPointInStroke(path,q.x,q.y));ctx.restore();return hit;}if(row.c.contract==='native.ellipse.v1')return ((q.x-v.width/2)/(v.width/2))**2+((q.y-v.height/2)/(v.height/2))**2<=1;return q.x>=0&&q.y>=0&&q.x<=v.width&&q.y<=v.height;}catch{return false;}}
|
|
1374
|
+
function inside(row,p){try{/* 3d:start */if(row.c.contract==='native.stage3d.v1'&&fullBleed3dIds.has(row.c.id)&&renderBleed)return p.x>=renderBleed.x&&p.y>=renderBleed.y&&p.x<=renderBleed.x+renderBleed.w&&p.y<=renderBleed.y+renderBleed.h;/* 3d:end */for(const clip of row.clips){const q=point(inverseMatrix(clip.matrix),p.x,p.y);if(q.x<0||q.y<0||q.x>clip.width||q.y>clip.height)return false;}const q=point(inverseMatrix(row.m),p.x,p.y),v=props(row.c);if(row.c.contract==='native.path.v1'){const path=new Path2D();for(const [cmd,...args]of v.commands)({M:()=>path.moveTo(...args),L:()=>path.lineTo(...args),C:()=>path.bezierCurveTo(...args),Q:()=>path.quadraticCurveTo(...args),Z:()=>path.closePath()})[cmd]();ctx.save();ctx.setTransform(1,0,0,1,0,0);ctx.lineWidth=v.strokeWidth;const hit=ctx.isPointInPath(path,q.x,q.y)||(v.strokeWidth>0&&ctx.isPointInStroke(path,q.x,q.y));ctx.restore();return hit;}if(row.c.contract==='native.ellipse.v1')return ((q.x-v.width/2)/(v.width/2))**2+((q.y-v.height/2)/(v.height/2))**2<=1;return q.x>=0&&q.y>=0&&q.x<=v.width&&q.y<=v.height;}catch{return false;}}
|
|
1199
1375
|
function hit(p){return [...paint].reverse().find(r=>r.c.contract!=='native.group.v1'&&r.c.sceneId===scene&&object(r.c.id)&&visible(r.c)&&inside(r,p));}
|
|
1200
1376
|
function ancestors(c){const a=[];while(c){a.push(c);c=object(c.parentId);}return a;}
|
|
1201
1377
|
function aimVelocity(){
|
|
@@ -1291,13 +1467,23 @@ export function mountNative(project,canvas,{edit=false,sceneId=project.base.star
|
|
|
1291
1467
|
updateAim3d(p);canvas.setPointerCapture?.(e.pointerId);return;
|
|
1292
1468
|
}
|
|
1293
1469
|
}
|
|
1294
|
-
const
|
|
1295
|
-
|
|
1296
|
-
|
|
1470
|
+
const hasButton=chain.some(c=>c.contract==='native.button.v1'&&props(c).enabled);
|
|
1471
|
+
const hasClickTarget=hasButton||chain.some(c=>project.events.some(event=>event.kind==='click'&&event.componentId===(c.prototypeId??c.id)));
|
|
1472
|
+
if(stage3dMgr&&!hasButton){
|
|
1473
|
+
const fpsBeh=project.gameplay.find(b=>b.kind==='fps-controller-3d'&&byId.get(b.componentId)?.sceneId===scene);
|
|
1297
1474
|
if(fpsBeh){
|
|
1298
1475
|
const stageComp=byId.get(fpsBeh.componentId),local=point(inverseMatrix(world(stageComp)),p.x,p.y),sp=props(stageComp);
|
|
1299
|
-
if(local.x>=0&&local.y>=0&&local.x<=sp.width&&local.y<=sp.height){
|
|
1300
|
-
|
|
1476
|
+
if(fullBleed3dIds.has(stageComp.id)||(local.x>=0&&local.y>=0&&local.x<=sp.width&&local.y<=sp.height)){
|
|
1477
|
+
const stageClick=project.events.some(event=>event.kind==='click'&&event.componentId===stageComp.id);
|
|
1478
|
+
if(!activeLook&&fpsBeh.parameters.lookMode!=='none'){
|
|
1479
|
+
ensureFpsState(fpsBeh);activeLook={pointerId:e.pointerId,stageId:stageComp.id,behavior:fpsBeh,last:p};canvas.setPointerCapture?.(e.pointerId);
|
|
1480
|
+
}
|
|
1481
|
+
if(stageClick){
|
|
1482
|
+
frameEvents=frameActions=0;halted=false;
|
|
1483
|
+
emit({kind:'click',componentId:stageComp.id,targetId:stageComp.id,pointerId:e.pointerId});
|
|
1484
|
+
process();render();return;
|
|
1485
|
+
}
|
|
1486
|
+
if(!hasClickTarget)return;
|
|
1301
1487
|
}
|
|
1302
1488
|
}
|
|
1303
1489
|
}
|