@tora-editor/tora 0.2.0 → 0.3.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 +5 -6
- package/bin/tora.mjs +255 -29
- package/crates/packer/trusted/native-3d-meta.json +3 -3
- package/crates/packer/trusted/native-3d.js +180 -180
- package/crates/packer/trusted/native-meta.json +3 -3
- 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 -3
- package/crates/packer/trusted/review-runtime.js +182 -182
- package/docs/MIGRATION_0_3.md +39 -0
- package/docs/NATIVE_AGENT_TOOLS.md +12 -363
- package/docs/TORA_AGENT_SETUP.md +24 -106
- package/docs/TORA_CREATION_API.md +63 -365
- package/docs/reference/CORE_AUTHORING.md +8 -2
- package/docs/reference/PLAYABLE_STARTERS.md +1 -1
- package/docs/reference/packs/3d.md +2 -0
- package/package.json +6 -6
- package/packages/creative-project/project-v21.schema.json +108 -1
- package/scripts/lean/editor/entry.js +11 -6
- package/scripts/lean/editor/project-launcher.js +116 -0
- package/scripts/lean/editor/quick-edit-panel.js +479 -0
- package/scripts/lean/editor/review-editor.css +246 -68
- package/scripts/lean/editor/review-editor.js +1731 -1099
- package/scripts/lean/editor-state.mjs +6 -0
- package/scripts/lean/editor.mjs +6 -3
- package/scripts/lean/matrix.mjs +5 -0
- package/scripts/lean/native/agent-tools.mjs +35 -58
- package/scripts/lean/native/api.mjs +148 -134
- package/scripts/lean/native/audio-assets.mjs +30 -0
- package/scripts/lean/native/browser-pool.mjs +34 -0
- package/scripts/lean/native/build-cache.mjs +36 -5
- package/scripts/lean/native/contracts.mjs +8 -6
- package/scripts/lean/native/creative-qa.mjs +66 -12
- package/scripts/lean/native/demos.mjs +11 -20
- package/scripts/lean/native/document.mjs +14 -2
- package/scripts/lean/native/local-bundle.mjs +4 -2
- package/scripts/lean/native/mcp-server.mjs +16 -35
- package/scripts/lean/native/modules/harvest-restore.mjs +3 -284
- package/scripts/lean/native/modules/sort-puzzle.mjs +51 -0
- package/scripts/lean/native/modules/star-salvage.mjs +3 -368
- package/scripts/lean/native/project-bundle.mjs +3 -2
- package/scripts/lean/native/project-index.mjs +0 -2
- package/scripts/lean/native/qa-adapters.mjs +10 -0
- package/scripts/lean/native/quick-edit.mjs +328 -0
- package/scripts/lean/native/review.mjs +203 -572
- package/scripts/lean/native/schema-vocabulary.mjs +10 -0
- package/scripts/lean/native/schema.mjs +1 -1
- package/scripts/lean/native/scope.mjs +45 -0
- package/scripts/lean/native/service.mjs +242 -70
- package/scripts/lean/native/starters.mjs +135 -8
- package/scripts/lean/native/variant-adapters.mjs +8 -0
- package/scripts/lean/native/variants-core.mjs +186 -0
- package/scripts/lean/native/variants.mjs +63 -0
- package/scripts/lean/native/win-cues.mjs +1 -1
- package/skills/tora-playables/SKILL.md +1 -1
- package/scripts/lean/editor/review-intake.js +0 -837
- package/scripts/lean/model-client.mjs +0 -119
- package/scripts/lean/native/author-expansion-proofs.mjs +0 -143
- package/scripts/lean/native/author-fps.mjs +0 -545
- package/scripts/lean/native/author-games.mjs +0 -160
- package/scripts/lean/native/author-harvest.mjs +0 -74
- package/scripts/lean/native/author-primitive-proofs.mjs +0 -875
- package/scripts/lean/native/author-salvage.mjs +0 -71
- package/scripts/lean/native/chat-compose.mjs +0 -287
- package/scripts/lean/native/check-harvest-outcome-audio.mjs +0 -190
- package/scripts/lean/native/check-salvage.mjs +0 -200
- package/scripts/lean/native/compatibility.mjs +0 -34
- package/scripts/lean/native/concept.mjs +0 -633
- package/scripts/lean/native/draw-stroke.mjs +0 -26
- package/scripts/lean/native/erase-mask.mjs +0 -18
- package/scripts/lean/native/glb-loader.mjs +0 -468
- package/scripts/lean/native/harvest-recipe.mjs +0 -21
- package/scripts/lean/native/instance-steering.mjs +0 -24
- package/scripts/lean/native/intake-creator-agent.mjs +0 -98
- package/scripts/lean/native/intake-creator-tools.mjs +0 -218
- package/scripts/lean/native/interaction-gestures.mjs +0 -45
- package/scripts/lean/native/match-board.mjs +0 -138
- package/scripts/lean/native/modules/index.mjs +0 -54
- package/scripts/lean/native/modules/tap-collect.mjs +0 -54
- package/scripts/lean/native/path-network.mjs +0 -132
- package/scripts/lean/native/physics-2d.mjs +0 -154
- package/scripts/lean/native/physics-3d.mjs +0 -259
- package/scripts/lean/native/prepare-audio-collections.mjs +0 -112
- package/scripts/lean/native/prepare-fps-assets.mjs +0 -330
- package/scripts/lean/native/prepare-game-audio.mjs +0 -372
- package/scripts/lean/native/prepare-golf-3d-assets.py +0 -177
- package/scripts/lean/native/prepare-golf-assets.py +0 -211
- package/scripts/lean/native/prepare-harvest-audio.mjs +0 -83
- package/scripts/lean/native/prepare-harvest-images.mjs +0 -31
- package/scripts/lean/native/prepare-primitive-images.py +0 -25
- package/scripts/lean/native/prepare-space-salvage-images.mjs +0 -89
- package/scripts/lean/native/prepare-traffic-assets.py +0 -329
- package/scripts/lean/native/presentation.mjs +0 -335
- package/scripts/lean/native/review-agent-tools.mjs +0 -561
- package/scripts/lean/native/review-connection.mjs +0 -303
- package/scripts/lean/native/review-fields.mjs +0 -24
- package/scripts/lean/native/review-intake.mjs +0 -385
- package/scripts/lean/native/review-intents.mjs +0 -217
- package/scripts/lean/native/review-provider.mjs +0 -580
- package/scripts/lean/native/review-receipts.mjs +0 -76
- package/scripts/lean/native/review-resolver.mjs +0 -429
- package/scripts/lean/native/review-targets.mjs +0 -35
- package/scripts/lean/native/runtime.mjs +0 -1809
- package/scripts/lean/native/salvage-recipe.mjs +0 -20
- package/scripts/lean/native/stage-3d.mjs +0 -1121
- package/scripts/lean/native/verify.mjs +0 -4
- package/scripts/lean/scene-document.mjs +0 -48
|
@@ -1,1809 +0,0 @@
|
|
|
1
|
-
/* global Image,atob,navigator,window,document,devicePixelRatio,requestAnimationFrame,cancelAnimationFrame,Path2D */
|
|
2
|
-
import {multiplyMatrix,inverseMatrix,identityMatrix} from '../scene-document.mjs';
|
|
3
|
-
import {createMatchBoard} from './match-board.mjs';
|
|
4
|
-
import {createDropOccupancy,resolveDropZone,classifySwipe,createHoldCharge,createGestureTweens,computeJoystickVector} from './interaction-gestures.mjs';
|
|
5
|
-
import {createInstanceSteering,createRng,seedFromText,findNearestByTeam,turnToward} from './instance-steering.mjs';
|
|
6
|
-
import {createEraseMask} from './erase-mask.mjs';
|
|
7
|
-
import {createStrokeStore,strokeWalls,segmentHitsPolygon,segmentsIntersect} from './draw-stroke.mjs';
|
|
8
|
-
import {stepPhysics,predictTrajectory} from './physics-2d.mjs';
|
|
9
|
-
/* 3d:start */
|
|
10
|
-
import {stepPhysics3d,predictTrajectory3d,ground3d,resolveWallSlide3d} from './physics-3d.mjs';
|
|
11
|
-
import {contactOrigin3d,createStage3dManager} from './stage-3d.mjs';
|
|
12
|
-
/* 3d:end */
|
|
13
|
-
import {createPathNetwork} from './path-network.mjs';
|
|
14
|
-
import {drawPixelText,measurePixelText} from './pixel-text.mjs';
|
|
15
|
-
import {drawPixelConfetti,drawPixelCta,drawShinyCta,drawVectorConfetti,pixelConfetti,screenConfetti,screenVectorConfetti,vectorConfetti} from './presentation.mjs';
|
|
16
|
-
import {createUnityAdsBridge} from '../../../packages/adapters/src/unity.ts';
|
|
17
|
-
import {createAppLovinBridge} from '../../../packages/adapters/src/applovin.ts';
|
|
18
|
-
import {createIronSourceBridge} from '../../../packages/adapters/src/ironsource.ts';
|
|
19
|
-
import {createMetaBridge} from '../../../packages/adapters/src/meta.ts';
|
|
20
|
-
import {createGoogleAdsBridge} from '../../../packages/adapters/src/google.ts';
|
|
21
|
-
import {createMintegralBridge} from '../../../packages/adapters/src/mintegral.ts';
|
|
22
|
-
import {createTikTokBridge} from '../../../packages/adapters/src/tiktok.ts';
|
|
23
|
-
export function createNetworkBridge(network){
|
|
24
|
-
if(network==='standalone')return undefined;
|
|
25
|
-
if(network==='unity-ads-ua-playable')return createUnityAdsBridge();
|
|
26
|
-
if(network==='applovin-growth-playable')return createAppLovinBridge();
|
|
27
|
-
if(network==='ironsource-levelplay-playable')return createIronSourceBridge();
|
|
28
|
-
if(network==='meta-audience-playable')return createMetaBridge();
|
|
29
|
-
if(network==='google-ads-app-playable')return createGoogleAdsBridge();
|
|
30
|
-
if(network==='mintegral-appgrowth-zip')return createMintegralBridge();
|
|
31
|
-
if(network==='tiktok-ads-playable')return createTikTokBridge();
|
|
32
|
-
throw Error('E_NATIVE_TARGET');
|
|
33
|
-
}
|
|
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);
|
|
36
|
-
const zones=[
|
|
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},
|
|
40
|
-
];
|
|
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};
|
|
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;}
|
|
44
|
-
function standardTextLines(ctx,text,p,fontSize){
|
|
45
|
-
ctx.font=p.fontWeight+' '+fontSize+'px '+p.fontFamily;
|
|
46
|
-
const availableWidth=Math.max(0,p.width-2*(p.padding??4)),lines=[];
|
|
47
|
-
for(const paragraph of String(text).split('\n')){
|
|
48
|
-
if(p.wrap===false){lines.push(paragraph);continue;}
|
|
49
|
-
const words=paragraph.trim()?paragraph.trim().split(/\s+/):[''];
|
|
50
|
-
let line;
|
|
51
|
-
for(const word of words){
|
|
52
|
-
const candidate=line?line+' '+word:word;
|
|
53
|
-
if(measuredTextWidth(ctx,candidate)<=availableWidth){line=candidate;continue;}
|
|
54
|
-
if(line)lines.push(line);
|
|
55
|
-
if(measuredTextWidth(ctx,word)<=availableWidth){line=word;continue;}
|
|
56
|
-
let part='';
|
|
57
|
-
for(const char of word){
|
|
58
|
-
if(part&&measuredTextWidth(ctx,part+char)>availableWidth){lines.push(part);part=char;}
|
|
59
|
-
else part+=char;
|
|
60
|
-
}
|
|
61
|
-
line=part;
|
|
62
|
-
}
|
|
63
|
-
lines.push(line);
|
|
64
|
-
}
|
|
65
|
-
return lines;
|
|
66
|
-
}
|
|
67
|
-
export function layoutStandardText(ctx,text,p){
|
|
68
|
-
const padding=p.padding??4,availableWidth=Math.max(0,p.width-2*padding),availableHeight=Math.max(0,p.height-2*padding),minimum=Math.min(p.fontSize,p.minFontSize??12);
|
|
69
|
-
let fontSize=p.fontSize,lines=standardTextLines(ctx,text,p,fontSize),measure;
|
|
70
|
-
const calculate=()=>{
|
|
71
|
-
ctx.font=p.fontWeight+' '+fontSize+'px '+p.fontFamily;
|
|
72
|
-
const renderedWidth=Math.max(0,...lines.map(line=>measuredTextWidth(ctx,line))),lineBox=fontSize*(p.lineHeight??1.2),truncated=lines.length>16;
|
|
73
|
-
if(truncated)lines=lines.slice(0,16);
|
|
74
|
-
const renderedHeight=lines.length*lineBox;
|
|
75
|
-
return {lines,fontSize,scale:fontSize/p.fontSize,renderedWidth,renderedHeight,availableWidth,availableHeight,padding,lineHeight:lineBox,overflowsWidth:renderedWidth>availableWidth+.01,overflowsHeight:truncated||renderedHeight>availableHeight+.01,unsupportedChars:[]};
|
|
76
|
-
};
|
|
77
|
-
measure=calculate();
|
|
78
|
-
if(p.autoFit!==false)while((measure.overflowsWidth||measure.overflowsHeight)&&fontSize>minimum){fontSize=Math.max(minimum,fontSize-1);lines=standardTextLines(ctx,text,p,fontSize);measure=calculate();}
|
|
79
|
-
return measure;
|
|
80
|
-
}
|
|
81
|
-
function drawStandardText(ctx,text,p){
|
|
82
|
-
const metrics=layoutStandardText(ctx,text,p),padding=metrics.padding;
|
|
83
|
-
ctx.fillStyle=p.color;ctx.font=p.fontWeight+' '+metrics.fontSize+'px '+p.fontFamily;ctx.textAlign=p.align;ctx.textBaseline='middle';
|
|
84
|
-
const x=p.align==='left'?padding:p.align==='right'?p.width-padding:p.width/2,top=(p.height-metrics.renderedHeight)/2;
|
|
85
|
-
metrics.lines.forEach((line,index)=>ctx.fillText(line,x,top+(index+.5)*metrics.lineHeight));
|
|
86
|
-
return metrics;
|
|
87
|
-
}
|
|
88
|
-
/** One runtime for all native projects. Author data never supplies executable functions. */
|
|
89
|
-
export function mountNative(project,canvas,{edit=false,sceneId=project.base.startScene,onSelect=()=>{},network='standalone'/* review:start */,review=false/* review:end */}={}){
|
|
90
|
-
const bridge=createNetworkBridge(network);
|
|
91
|
-
const ctx=canvas.getContext('2d'),byId=new Map(project.components.map(c=>[c.id,c])),assets=new Map(project.assets.map(a=>[a.id,a])),images=new Map(),eventDefinitions=new Map(project.events.map(e=>[e.id,e]));
|
|
92
|
-
const responsiveLayouts=new Map(project.gameplay.filter(behavior=>behavior.kind==='responsive-layout').map(behavior=>[behavior.componentId,behavior.parameters]));
|
|
93
|
-
const reducedMotion=globalThis.matchMedia?.('(prefers-reduced-motion: reduce)');
|
|
94
|
-
let paintedLandscape,ctaAppearances=new Map(),previousCtaAppearances=ctaAppearances;
|
|
95
|
-
function viewport(){
|
|
96
|
-
const landscape=responsiveLayouts.size>0&&canvas.clientWidth>canvas.clientHeight;
|
|
97
|
-
return {width:landscape?Math.max(project.base.width,project.base.height):project.base.width,height:landscape?Math.min(project.base.width,project.base.height):project.base.height,landscape};
|
|
98
|
-
}
|
|
99
|
-
function refreshOrientation(){
|
|
100
|
-
if(paintedLandscape!==viewport().landscape){cancelInput();render();}
|
|
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);}
|
|
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;
|
|
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=[];
|
|
106
|
-
/* 3d:start */
|
|
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);
|
|
109
|
-
/* 3d:end */
|
|
110
|
-
const object=id=>runtimeNodes.get(id)??byId.get(id),behaviorOn=(kind,id)=>project.gameplay.find(b=>b.kind===kind&&b.componentId===id);
|
|
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();};
|
|
112
|
-
const cancelAim=pointerId=>{if(!aiming||(pointerId!==undefined&&aiming.pointerId!==pointerId))return false;const id=aiming.pointerId;if(aiming.behavior.parameters.powerVariableId)variables[aiming.behavior.parameters.powerVariableId]=0;aiming=undefined;try{if(canvas.hasPointerCapture?.(id))canvas.releasePointerCapture?.(id);}catch{/* Capture may already have been released by the host. */}return true;};
|
|
113
|
-
/* 3d:start */
|
|
114
|
-
const cancelAim3d=pointerId=>{if(!aiming3d||(pointerId!==undefined&&aiming3d.pointerId!==pointerId))return false;const id=aiming3d.pointerId;if(aiming3d.behavior.parameters.powerVariableId)variables[aiming3d.behavior.parameters.powerVariableId]=0;stage3dMgr?.getStage(byId.get(aiming3d.stageId))?.setGuide([]);aiming3d=undefined;try{if(canvas.hasPointerCapture?.(id))canvas.releasePointerCapture?.(id);}catch{/* Capture may already have been released by the host. */}return true;};
|
|
115
|
-
const cancelLook3d=pointerId=>{if(!activeLook||(pointerId!==undefined&&activeLook.pointerId!==pointerId))return false;const id=activeLook.pointerId;activeLook=undefined;try{if(canvas.hasPointerCapture?.(id))canvas.releasePointerCapture?.(id);}catch{/* Capture may already have been released by the host. */}return true;};
|
|
116
|
-
/* 3d:end */
|
|
117
|
-
const writeJoystickVars=j=>{const p=j.behavior.parameters;if(p.axisXVariableId)variables[p.axisXVariableId]=j.nx;if(p.axisYVariableId)variables[p.axisYVariableId]=j.ny;if(p.magnitudeVariableId)variables[p.magnitudeVariableId]=j.magnitude;if(p.angleVariableId&&j.magnitude>0)variables[p.angleVariableId]=j.angle;};
|
|
118
|
-
const cancelJoysticks=(pointerId,emitEnd=false)=>{for(const j of joysticks.values()){if(j.pointerId===null||(pointerId!==undefined&&j.pointerId!==pointerId))continue;const id=j.pointerId;j.pointerId=null;j.nx=0;j.ny=0;j.magnitude=0;j.knobX=j.origin.x;j.knobY=j.origin.y;writeJoystickVars(j);try{if(canvas.hasPointerCapture?.(id))canvas.releasePointerCapture?.(id);}catch{/* Capture may already have been released by the host. */}if(emitEnd)emit(instanceEvent('joystickEnd',j.c));}};
|
|
119
|
-
const cancelDrag=(pointerId,restore=true)=>{if(!drag||(pointerId!==undefined&&drag.pointerId!==pointerId))return false;const current=drag,id=current.pointerId;drag=undefined;hoverDrop=undefined;if(restore){const c=object(current.targetId);if(c&¤t.b.parameters.snapBack){setWorldCenter(c,current.origin.x,current.origin.y);if(current.originZone)dropOccupancy.place(c.id,current.originZone);}}try{if(canvas.hasPointerCapture?.(id))canvas.releasePointerCapture?.(id);}catch{/* Capture may already have been released by the host. */}return true;};
|
|
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;};
|
|
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));};
|
|
122
|
-
const prototypeOwner=c=>{while(c){if(c.prototype)return c.id;c=object(c.parentId);}return undefined;};
|
|
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]});
|
|
124
|
-
const running=()=>!edit&&!paused&&!document.hidden&&networkReady&&networkVisible&&started&&!closed;
|
|
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();};
|
|
126
|
-
const diagnose=message=>{halted=true;diagnostics.push(message);diagnostics=diagnostics.slice(-16);queue=[];};
|
|
127
|
-
const props=c=>({...c.parameters,...(c.prototypeId?overrides.get(c.prototypeId)?.parameters:{}),...overrides.get(c.runtimeId??c.id)?.parameters});
|
|
128
|
-
function pressTransform(c,matrix){
|
|
129
|
-
const press=pressStates.get(c.id);
|
|
130
|
-
if(!press||reducedMotion?.matches)return matrix;
|
|
131
|
-
const result=[...matrix],elapsed=press.held?0:time-(press.releasedAt??time),progress=press.held?0:Math.min(1,elapsed/press.behavior.springBackSeconds),scale=press.held?press.behavior.scaleDown:press.behavior.scaleDown+(1-press.behavior.scaleDown)*(1-(1-progress)**3),p=props(c);
|
|
132
|
-
result[4]+=(1-scale)*(result[0]*p.width+result[2]*p.height)/2;
|
|
133
|
-
result[5]+=(1-scale)*(result[1]*p.width+result[3]*p.height)/2;
|
|
134
|
-
for(let axis=0;axis<4;axis++)result[axis]*=scale;
|
|
135
|
-
return result;
|
|
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
|
-
}
|
|
145
|
-
function transform(c){
|
|
146
|
-
const authored=c.transform,current=overrides.get(c.runtimeId??c.id)?.transform??authored;
|
|
147
|
-
const layout=responsiveLayouts.get(c.prototypeId??c.id);
|
|
148
|
-
if(!layout)return pressTransform(c,current);
|
|
149
|
-
const stage=viewport(),result=[...current];
|
|
150
|
-
if(stage.landscape){
|
|
151
|
-
result[4]+=layout.x-authored[4];
|
|
152
|
-
result[5]+=layout.y-authored[5];
|
|
153
|
-
result[0]*=layout.scaleX;
|
|
154
|
-
result[1]*=layout.scaleX;
|
|
155
|
-
result[2]*=layout.scaleY;
|
|
156
|
-
result[3]*=layout.scaleY;
|
|
157
|
-
}
|
|
158
|
-
const anchor=layout.anchor??'none';
|
|
159
|
-
if(anchor==='none'&&!layout.respectSafeArea)return pressTransform(c,result);
|
|
160
|
-
const bounds=anchorBounds(stage),safe=layout.respectSafeArea?computeSafeArea(bounds):bounds,p=props(c),mx=layout.marginX??0,my=layout.marginY??0;
|
|
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;
|
|
162
|
-
if(anchor!=='none'){
|
|
163
|
-
result[4]=anchor.endsWith('left')?safe.left+mx:anchor.endsWith('right')?safe.right-width-mx:(safe.left+safe.right-width)/2;
|
|
164
|
-
result[5]=anchor.startsWith('top')?safe.top+my:anchor.startsWith('bottom')?safe.bottom-height-my:(safe.top+safe.bottom-height)/2;
|
|
165
|
-
}else{
|
|
166
|
-
result[4]=Math.max(safe.left+mx,Math.min(safe.right-width-mx,result[4]));
|
|
167
|
-
result[5]=Math.max(safe.top+my,Math.min(safe.bottom-height-my,result[5]));
|
|
168
|
-
}
|
|
169
|
-
return pressTransform(c,result);
|
|
170
|
-
}
|
|
171
|
-
const children=id=>(runtimeNodes.has(id)?[...runtimeNodes.values()]:[...project.components,...instances]).filter(c=>c.parentId===id&&!c.prototype).sort((a,b)=>a.order-b.order||(a.id<b.id?-1:a.id>b.id?1:0));
|
|
172
|
-
const roots=()=>project.components.filter(c=>c.sceneId===scene&&!c.parentId&&!c.prototype).sort((a,b)=>a.order-b.order||(a.id<b.id?-1:a.id>b.id?1:0));
|
|
173
|
-
const emit=e=>{if(e.kind==='sceneEnter'&&project.scenes.find(item=>item.id===e.sceneId)?.role==='end-card'&&lastEndScene!==e.sceneId){lastEndScene=e.sceneId;bridge?.notifyGameEnd?.();}if(queue.length>=256){diagnose('Event queue budget exhausted');return;}queue.push(e);};
|
|
174
|
-
const instanceEvent=(kind,c,other,extra={})=>({kind,componentId:c.prototypeId??c.id,selfInstanceId:c.instanceId??c.id,instanceId:c.instanceId,...(other?{otherId:other.prototypeId??other.id,otherInstanceId:other.instanceId??other.id}:{}),...extra});
|
|
175
|
-
function instanceState(c){for(let current=c;current;current=object(current.parentId)){const state=instanceEngine.states.get(current.instanceId??current.id);if(state)return state;}return undefined;}
|
|
176
|
-
function initializeInstanceState(c){const behavior=behaviorOn('instance-state',c.prototypeId??c.id);return behavior?instanceEngine.initialize(c.instanceId??c.id,behavior.parameters):undefined;}
|
|
177
|
-
function initializeInstanceStates(){for(const behavior of project.gameplay.filter(b=>b.kind==='instance-state'))for(const c of targetsFor(byId.get(behavior.componentId)))initializeInstanceState(c);}
|
|
178
|
-
function modifyInstance(c,field,op,value){
|
|
179
|
-
const state=instanceState(c);if(!state)return;const previous=state.hp;if(field==='tag')state.tag=op==='set'?String(value):state.tag;else{const numeric=Number(value);state[field]=op==='add'?state[field]+numeric:op==='sub'?state[field]-numeric:numeric;if(!Number.isFinite(state[field])){diagnose('Instance state range exceeded');return;}if(field==='hp')state.hp=Math.max(0,Math.min(state.maxHp,state.hp));}
|
|
180
|
-
if(previous>0&&state.hp<=0){emit(instanceEvent('instanceDepleted',c));}
|
|
181
|
-
}
|
|
182
|
-
function condition(c,event){if(!c)return true;if(c.all)return c.all.every(item=>condition(item,event));if(c.any)return c.any.some(item=>condition(item,event));const instanceId=c.instanceTarget==='other'?event?.otherInstanceId:event?.selfInstanceId??event?.instanceId,target=c.instanceField?object(instanceId)??[...runtimeNodes.values()].find(node=>node.instanceId===instanceId):undefined,a=c.instanceField?instanceState(target)?.[c.instanceField]:variables[c.variableId],b=c.compareVariableId?variables[c.compareVariableId]:c.value;return {eq:()=>a===b,ne:()=>a!==b,lt:()=>a<b,lte:()=>a<=b,gt:()=>a>b,gte:()=>a>=b}[c.op]();}
|
|
183
|
-
function resetMatch(componentId){matchSelected=undefined;matchGesture=undefined;if(!componentId)matchCells.clear();for(const b of project.gameplay)if(b.kind==='match-tile'){const c=byId.get(b.componentId);if(componentId&&c.id!==componentId&&!isDescendant(c,componentId))continue;overrides.delete(c.id);matchCells.set(c.id,{row:b.parameters.row,column:b.parameters.column,group:b.parameters.group,sceneId:c.sceneId,boardId:c.parentId??c.sceneId});}}
|
|
184
|
-
function initializeMatchBoards(){
|
|
185
|
-
for(const behavior of project.gameplay.filter(item=>item.kind==='match-board')){
|
|
186
|
-
if(matchBoards.has(behavior.componentId))continue;
|
|
187
|
-
const boardId=behavior.componentId,parameters=behavior.parameters;
|
|
188
|
-
const slots=project.gameplay.filter(item=>item.kind==='match-tile'&&byId.get(item.componentId).parentId===boardId).sort((a,b)=>a.parameters.row-b.parameters.row||a.parameters.column-b.parameters.column).map(item=>({id:item.componentId,...item.parameters}));
|
|
189
|
-
const palette=new Map();
|
|
190
|
-
for(const slot of slots)if(!palette.has(slot.group)){
|
|
191
|
-
const component=byId.get(slot.id);
|
|
192
|
-
palette.set(slot.group,{fill:component.parameters.fill,children:children(slot.id).filter(child=>['native.image.v1','native.text.v1'].includes(child.contract))});
|
|
193
|
-
}
|
|
194
|
-
matchArtwork.set(boardId,palette);
|
|
195
|
-
const rowHeight=byId.get(slots[parameters.columns].id).transform[5]-byId.get(slots[0].id).transform[5];
|
|
196
|
-
const paintSlot=(index,group,{from=index,progress=0,offsetRows=0,scale=1,opacity=1})=>{
|
|
197
|
-
const slot=slots[index],component=byId.get(slot.id),source=byId.get(slots[from].id),art=palette.get(group),matrix=[...component.transform];
|
|
198
|
-
matrix[4]+=(source.transform[4]-component.transform[4])*progress;
|
|
199
|
-
matrix[5]+=(source.transform[5]-component.transform[5]+offsetRows*rowHeight)*progress;
|
|
200
|
-
matrix[4]+=(1-scale)*(matrix[0]*component.parameters.width+matrix[2]*component.parameters.height)/2;
|
|
201
|
-
matrix[5]+=(1-scale)*(matrix[1]*component.parameters.width+matrix[3]*component.parameters.height)/2;
|
|
202
|
-
for(let axis=0;axis<4;axis++)matrix[axis]*=scale;
|
|
203
|
-
overrides.set(slot.id,{...overrides.get(slot.id),transform:matrix,parameters:{...overrides.get(slot.id)?.parameters,fill:art.fill,opacity}});
|
|
204
|
-
matchCells.get(slot.id).group=group;
|
|
205
|
-
const targets=children(slot.id).filter(child=>['native.image.v1','native.text.v1'].includes(child.contract));
|
|
206
|
-
targets.forEach((child,childIndex)=>{
|
|
207
|
-
const sample=art.children[childIndex];
|
|
208
|
-
if(!sample||sample.contract!==child.contract)return;
|
|
209
|
-
const previous=overrides.get(child.id)??{transform:[...child.transform],parameters:{}};
|
|
210
|
-
if(child.contract==='native.image.v1')previous.assetId=sample.assetSlots[0]?.assetId;
|
|
211
|
-
else previous.parameters.text=sample.parameters.text;
|
|
212
|
-
overrides.set(child.id,previous);
|
|
213
|
-
});
|
|
214
|
-
};
|
|
215
|
-
const board=createMatchBoard({...parameters,slots,paint:paintSlot,onEvent:kind=>{matchSelected=undefined;emit({kind,componentId:boardId});}});
|
|
216
|
-
matchBoards.set(boardId,board);
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
function resetBoards(componentId){
|
|
220
|
-
initializeMatchBoards();
|
|
221
|
-
for(const [boardId,board]of matchBoards)if(!componentId||componentId===boardId||isDescendant(byId.get(boardId),componentId))board.reset();
|
|
222
|
-
}
|
|
223
|
-
function targetsFor(source){return prototypeOwner(source)?[...runtimeNodes.values()].filter(i=>i.prototypeId===source.id):[source];}
|
|
224
|
-
function centerOf(c){const p=props(c);return point(world(c),p.width/2,p.height/2);}
|
|
225
|
-
function eventTarget(componentId,event,which='self'){
|
|
226
|
-
const source=byId.get(componentId),id=which==='other'?event.otherInstanceId:event.selfInstanceId??event.instanceId,isProto=Boolean(source&&prototypeOwner(source));
|
|
227
|
-
if(id!==undefined){
|
|
228
|
-
if(componentId){const target=[...runtimeNodes.values()].find(node=>node.prototypeId===componentId&&(node.instanceId===id||node.id===id));if(target)return target;}
|
|
229
|
-
if(which==='other'||!componentId)return object(id);
|
|
230
|
-
if(isProto&&typeof id==='string'&&id.startsWith('instance.'))return undefined;
|
|
231
|
-
}
|
|
232
|
-
return source?(isProto?targetsFor(source)[0]:object(componentId)):undefined;
|
|
233
|
-
}
|
|
234
|
-
function setWorldCenter(c,x,y){
|
|
235
|
-
const p=props(c),current=overrides.get(c.id)??{transform:[...c.transform],parameters:{}},matrix=[...current.transform],parent=c.parentId?world(object(c.parentId)):identityMatrix(),local=point(inverseMatrix(parent),x,y);
|
|
236
|
-
matrix[4]=local.x-(matrix[0]*p.width+matrix[2]*p.height)/2;matrix[5]=local.y-(matrix[1]*p.width+matrix[3]*p.height)/2;
|
|
237
|
-
overrides.set(c.id,{...current,transform:matrix});if(c.prototypeId)c.transform=[...matrix];
|
|
238
|
-
}
|
|
239
|
-
function setComponentHeading(c,angle,flip=false){
|
|
240
|
-
const current=overrides.get(c.id)??{transform:[...c.transform],parameters:{}},authored=byId.get(c.prototypeId??c.id)?.transform??c.transform;
|
|
241
|
-
const sx=Math.hypot(authored[0],authored[1])*(flip?-1:1),sy=Math.hypot(authored[2],authored[3]);
|
|
242
|
-
const total=angle+(flip?0:Math.atan2(authored[1],authored[0])),cos=Math.cos(total),sin=Math.sin(total),matrix=[...current.transform];
|
|
243
|
-
matrix[0]=cos*sx;matrix[1]=sin*sx;matrix[2]=-sin*sy;matrix[3]=cos*sy;overrides.set(c.id,{...current,transform:matrix});
|
|
244
|
-
}
|
|
245
|
-
function physicsState(c,behavior){
|
|
246
|
-
let body=physicsBodies.get(c.id);if(body)return body;
|
|
247
|
-
const matrix=world(c),p=props(c),center=point(matrix,p.width/2,p.height/2);
|
|
248
|
-
body={id:c.id,sourceId:behavior.componentId,instanceId:c.instanceId,x:center.x,y:center.y,vx:0,vy:0,width:Math.hypot(matrix[0],matrix[1])*p.width,height:Math.hypot(matrix[2],matrix[3])*p.height,angle:Math.atan2(matrix[1],matrix[0]),restElapsed:0,atRest:true,...behavior.parameters};
|
|
249
|
-
physicsBodies.set(c.id,body);return body;
|
|
250
|
-
}
|
|
251
|
-
function maskState(c,behavior){
|
|
252
|
-
let mask=maskStates.get(c.id);if(mask)return mask;const p=props(c),config=behavior.parameters;
|
|
253
|
-
mask=createEraseMask(config,{width:p.width,height:p.height,source:c.contract==='native.image.v1'?images.get(c.assetSlots[0]?.assetId):undefined,onProgress:percent=>{if(config.progressVariableId)variables[config.progressVariableId]=percent;emit(instanceEvent('maskProgress',c));},onComplete:()=>emit(instanceEvent('maskComplete',c))});maskStates.set(c.id,mask);return mask;
|
|
254
|
-
}
|
|
255
|
-
function strokeState(behavior){let store=strokeStates.get(behavior.componentId);if(!store){store=createStrokeStore(behavior.parameters);strokeStates.set(behavior.componentId,store);}return store;}
|
|
256
|
-
function collectPhysics(){
|
|
257
|
-
const active=new Set(),bodies=[];
|
|
258
|
-
for(const behavior of project.gameplay.filter(item=>item.kind==='physics-body')){
|
|
259
|
-
const source=byId.get(behavior.componentId);if(source.sceneId!==scene)continue;
|
|
260
|
-
for(const c of targetsFor(source)){
|
|
261
|
-
if(!visible(c))continue;if(bodies.length>=64){diagnose('Physics body budget exhausted');break;}
|
|
262
|
-
const body=physicsState(c,behavior),matrix=world(c),p=props(c),center=point(matrix,p.width/2,p.height/2);
|
|
263
|
-
active.add(c.id);
|
|
264
|
-
body.width=Math.hypot(matrix[0],matrix[1])*p.width;body.height=Math.hypot(matrix[2],matrix[3])*p.height;
|
|
265
|
-
if(body.mode!=='dynamic'){
|
|
266
|
-
const velocity=oscillations.get(c.id),parent=c.parentId?world(object(c.parentId)):identityMatrix(),lvx=velocity?.vx??0,lvy=velocity?.vy??0;
|
|
267
|
-
body.x=center.x;body.y=center.y;body.angle=Math.atan2(matrix[1],matrix[0]);
|
|
268
|
-
body.vx=parent[0]*lvx+parent[2]*lvy;body.vy=parent[1]*lvx+parent[3]*lvy;
|
|
269
|
-
}else if(body.atRest){
|
|
270
|
-
body.x=center.x;body.y=center.y;
|
|
271
|
-
}
|
|
272
|
-
bodies.push(body);
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
for(const id of physicsBodies.keys())if(!active.has(id)&&!runtimeNodes.has(id))physicsBodies.delete(id);
|
|
276
|
-
const zones=[];
|
|
277
|
-
for(const behavior of project.gameplay.filter(item=>item.kind==='capture-zone')){
|
|
278
|
-
const source=byId.get(behavior.componentId);if(source.sceneId!==scene)continue;
|
|
279
|
-
for(const c of targetsFor(source))if(visible(c)){const matrix=world(c),p=props(c),center=point(matrix,p.width/2,p.height/2),scale=Math.max(.1,Math.min(Math.hypot(matrix[0],matrix[1]),Math.hypot(matrix[2],matrix[3])));zones.push({id:c.id,sourceId:source.id,instanceId:c.instanceId,x:center.x,y:center.y,...behavior.parameters,radius:behavior.parameters.radius*scale});}
|
|
280
|
-
}
|
|
281
|
-
return {bodies:[...bodies,...strokeWallBodies],zones};
|
|
282
|
-
}
|
|
283
|
-
function tickPhysics(dt){
|
|
284
|
-
const {bodies,zones}=collectPhysics(),stage=viewport();activeJoints=[];
|
|
285
|
-
for(const behavior of project.gameplay.filter(item=>item.kind==='physics-joint')){
|
|
286
|
-
const source=byId.get(behavior.componentId);if(source.sceneId!==scene)continue;const anchor=object(behavior.parameters.anchorComponentId),bodyBehavior=behaviorOn('physics-body',source.id);if(!anchor||!bodyBehavior)continue;
|
|
287
|
-
for(const c of targetsFor(source)){physicsState(c,bodyBehavior);const center=centerOf(anchor),key=behavior.id+':'+c.id;activeJoints.push({...behavior.parameters,id:behavior.id,key,componentId:source.id,bodyId:c.id,anchorId:anchor.id,x:center.x,y:center.y,broken:brokenJoints.has(key)});}
|
|
288
|
-
}
|
|
289
|
-
stepPhysics({bodies,zones,joints:activeJoints,bounds:{left:0,top:0,right:stage.width,bottom:stage.height},dt,onEvent:(kind,body,other)=>{
|
|
290
|
-
if(kind==='bodyBounce'&&other&&body.sourceId===other.sourceId&&body.id>other.id)return;
|
|
291
|
-
const selfInstanceId=body.instanceId??body.id,otherInstanceId=other?(other.instanceId??other.id):undefined,payload={kind,componentId:body.sourceId,selfInstanceId,...(otherInstanceId?{otherInstanceId}:{}),instanceId:body.instanceId??other?.instanceId};if(other)payload.otherId=other.sourceId;emit(payload);
|
|
292
|
-
if(kind==='zoneCapture'){
|
|
293
|
-
const target=object(body.id),zone=byId.get(other.sourceId);
|
|
294
|
-
if(other.hideCaptured&&target){const current=overrides.get(target.id)??{transform:[...target.transform],parameters:{}};current.parameters.visible=false;overrides.set(target.id,current);}
|
|
295
|
-
if(other.stopBody&&zone&&target)setWorldCenter(target,other.x,other.y);
|
|
296
|
-
}
|
|
297
|
-
}});
|
|
298
|
-
for(const body of bodies){
|
|
299
|
-
const c=object(body.id);if(!c||body.mode!=='dynamic')continue;
|
|
300
|
-
if(body.spinToRotation)setComponentHeading(c,body.angle??0);
|
|
301
|
-
setWorldCenter(c,body.x,body.y);
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
function tickOscillations(){
|
|
305
|
-
for(const behavior of project.gameplay.filter(item=>item.kind==='oscillate')){
|
|
306
|
-
const source=byId.get(behavior.componentId);if(source.sceneId!==scene)continue;
|
|
307
|
-
for(const c of targetsFor(source)){
|
|
308
|
-
let state=oscillations.get(c.id);if(!state){state={base:[...transform(c)],vx:0,vy:0};oscillations.set(c.id,state);}
|
|
309
|
-
const p=behavior.parameters,angle=(time/p.periodSeconds+p.phase)*Math.PI*2,offset=Math.sin(angle)*p.amplitude,velocity=Math.cos(angle)*p.amplitude*Math.PI*2/p.periodSeconds,current=overrides.get(c.id)??{parameters:{}},matrix=[...state.base];
|
|
310
|
-
if(p.axis==='x'){matrix[4]+=offset;state.vx=velocity;state.vy=0;}else{matrix[5]+=offset;state.vy=velocity;state.vx=0;}
|
|
311
|
-
overrides.set(c.id,{...current,transform:matrix});oscillations.set(c.id,state);
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
function initializePathNetworks(){
|
|
316
|
-
pathNetworks.clear();
|
|
317
|
-
for(const behavior of project.gameplay.filter(item=>item.kind==='path-network')){
|
|
318
|
-
const gates=project.gameplay.filter(item=>item.kind==='path-gate'&&item.parameters.networkBehaviorId===behavior.id);
|
|
319
|
-
const network=createPathNetwork({id:behavior.id,nodes:behavior.parameters.nodes,edges:behavior.parameters.edges,gates,onEvent:(kind,event)=>{
|
|
320
|
-
const c=object(event.componentId),source=c?.prototypeId??event.componentId;emit({kind,componentId:source,instanceId:c?.instanceId,...(event.nodeId?{nodeId:event.nodeId}:{})});
|
|
321
|
-
}});
|
|
322
|
-
pathNetworks.set(behavior.id,network);
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
function syncPaths(dt,step=true){
|
|
326
|
-
let count=0;
|
|
327
|
-
for(const behavior of project.gameplay.filter(item=>item.kind==='path-agent')){
|
|
328
|
-
const source=byId.get(behavior.componentId),network=pathNetworks.get(behavior.parameters.networkBehaviorId);if(source.sceneId!==scene||!network)continue;
|
|
329
|
-
for(const c of targetsFor(source)){
|
|
330
|
-
if(++count>64){diagnose('Path agent budget exhausted');break;}
|
|
331
|
-
let agent=network.getAgent(c.id);
|
|
332
|
-
if(!agent)agent=network.addAgent({...behavior.parameters,id:c.id,startNode:c.pathStartNode??behavior.parameters.startNode,targetNode:c.pathTargetNode??behavior.parameters.targetNode});
|
|
333
|
-
agent.speedMultiplier=Math.max(0,Number(behavior.parameters.speedMultiplierVariableId?variables[behavior.parameters.speedMultiplierVariableId]:1));
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
if(step)for(const [behaviorId,network]of pathNetworks){const owner=project.gameplay.find(b=>b.id===behaviorId);if(byId.get(owner.componentId).sceneId===scene)network.tick(dt);}
|
|
337
|
-
for(const behavior of project.gameplay.filter(item=>item.kind==='path-agent')){
|
|
338
|
-
const source=byId.get(behavior.componentId),network=pathNetworks.get(behavior.parameters.networkBehaviorId);if(source.sceneId!==scene||!network)continue;
|
|
339
|
-
for(const c of targetsFor(source)){
|
|
340
|
-
const agent=network.getAgent(c.id);if(!agent)continue;
|
|
341
|
-
if(agent.orientToPath==='rotate')setComponentHeading(c,agent.heading);
|
|
342
|
-
else if(agent.orientToPath==='flip-x')setComponentHeading(c,0,agent.flipX);
|
|
343
|
-
else if(agent.orientToPath==='iso-4'){const current=overrides.get(c.id)??{transform:[...c.transform],parameters:{}};current.pathFrame=agent.frame;overrides.set(c.id,current);}
|
|
344
|
-
const worldPoint=c.parentId?point(world(object(c.parentId)),agent.x,agent.y):agent;
|
|
345
|
-
setWorldCenter(c,worldPoint.x,worldPoint.y);
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
function tickMetersAndCamera(dt){
|
|
350
|
-
const activeMeters=new Set();
|
|
351
|
-
for(const behavior of project.gameplay.filter(item=>item.kind==='value-meter')){
|
|
352
|
-
const source=byId.get(behavior.componentId);if(source.sceneId!==scene)continue;
|
|
353
|
-
for(const c of targetsFor(source)){
|
|
354
|
-
const p=behavior.parameters,instance=p.instanceField?instanceState(c):undefined,initialRaw=p.instanceField==='hp'&&instance?instance.hp/instance.maxHp*(p.max-p.min)+p.min:p.instanceField==='value'&&instance?instance.value:Number(variables[p.variableId]);
|
|
355
|
-
let state=meterStates.get(c.id);if(!state){state={base:[...transform(c)],value:Number.isFinite(initialRaw)?Math.max(p.min,Math.min(p.max,initialRaw)):p.min};meterStates.set(c.id,state);}activeMeters.add(c.id);
|
|
356
|
-
const target=Math.max(p.min,Math.min(p.max,initialRaw)),blend=p.smoothingSeconds?1-Math.exp(-dt/p.smoothingSeconds):1;
|
|
357
|
-
state.value+=((Number.isFinite(target)?target:p.min)-state.value)*blend;
|
|
358
|
-
const ratio=Math.max(0,Math.min(1,(state.value-p.min)/(p.max-p.min))),matrix=[...state.base],current=overrides.get(c.id)??{parameters:{}},size=p.axis==='x'?props(c).width:props(c).height;
|
|
359
|
-
if(p.axis==='x'){matrix[0]*=ratio;matrix[1]*=ratio;}else{matrix[2]*=ratio;matrix[3]*=ratio;}
|
|
360
|
-
if(p.direction==='negative'){const shift=size*(1-ratio);if(p.axis==='x'){matrix[4]+=state.base[0]*shift;matrix[5]+=state.base[1]*shift;}else{matrix[4]+=state.base[2]*shift;matrix[5]+=state.base[3]*shift;}}
|
|
361
|
-
overrides.set(c.id,{...current,transform:matrix});
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
for(const id of meterStates.keys())if(!activeMeters.has(id))meterStates.delete(id);
|
|
365
|
-
for(const behavior of project.gameplay.filter(item=>item.kind==='camera-follow')){
|
|
366
|
-
const owner=byId.get(behavior.componentId),target=object(behavior.parameters.targetId);if(owner.sceneId!==scene||!target)continue;
|
|
367
|
-
let state=cameraStates.get(owner.id);if(!state){state={base:[...owner.transform],x:behavior.parameters.minX,y:behavior.parameters.minY};cameraStates.set(owner.id,state);}
|
|
368
|
-
const relative=(c,root)=>{const chain=[];for(let current=c;current&¤t.id!==root.id;current=object(current.parentId))chain.unshift(current);return chain.reduce((matrix,item)=>multiplyMatrix(matrix,transform(item)),identityMatrix());};
|
|
369
|
-
const matrix=isDescendant(target,owner.id)?relative(target,owner):world(target),p=props(target),center=point(matrix,p.width/2,p.height/2),stage=viewport(),config=behavior.parameters;
|
|
370
|
-
const maxX=Math.max(config.minX,config.maxX-stage.width/config.zoom),maxY=Math.max(config.minY,config.maxY-stage.height/config.zoom),tx=Math.max(config.minX,Math.min(maxX,center.x-stage.width/(2*config.zoom))),ty=Math.max(config.minY,Math.min(maxY,center.y-stage.height/(2*config.zoom))),blend=1-Math.exp(-config.smoothing*dt);
|
|
371
|
-
state.x+=(tx-state.x)*blend;state.y+=(ty-state.y)*blend;
|
|
372
|
-
const current=overrides.get(owner.id)??{parameters:{}},next=[...state.base];next[0]*=config.zoom;next[1]*=config.zoom;next[2]*=config.zoom;next[3]*=config.zoom;next[4]-=state.x*config.zoom;next[5]-=state.y*config.zoom;overrides.set(owner.id,{...current,transform:next});
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
function physicsSnapshot(){return {bodies:[...physicsBodies.values()].map(body=>({id:body.id,sourceId:body.sourceId,x:body.x,y:body.y,vx:body.vx,vy:body.vy,atRest:Boolean(body.atRest),captured:Boolean(body.captured)})),aiming:aiming?{componentId:aiming.sourceId,pointerId:aiming.pointerId,power:aiming.power}:null};}
|
|
376
|
-
/* 3d:start */
|
|
377
|
-
function findStage3dOf(c){let cur=c;while(cur){if(cur.contract==='native.stage3d.v1')return cur;cur=cur.parentId?object(cur.parentId):undefined;}return undefined;}
|
|
378
|
-
function body3dState(c,behavior){
|
|
379
|
-
let body=bodies3d.get(c.id);if(body)return body;
|
|
380
|
-
const p=props(c),stageComp=findStage3dOf(c);
|
|
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};
|
|
392
|
-
bodies3d.set(c.id,body);return body;
|
|
393
|
-
}
|
|
394
|
-
function collect3d(){
|
|
395
|
-
const bodies=[],walls=[],zones=[];
|
|
396
|
-
if(!stage3dMgr)return {bodies,walls,zones};
|
|
397
|
-
for(const behavior of project.gameplay.filter(item=>item.kind==='physics-3d')){
|
|
398
|
-
const source=byId.get(behavior.componentId);if(!source||source.sceneId!==scene||!visible(source))continue;
|
|
399
|
-
const body=body3dState(source,behavior);
|
|
400
|
-
if(body.mode==='dynamic')bodies.push(body);
|
|
401
|
-
else walls.push(body);
|
|
402
|
-
}
|
|
403
|
-
for(const behavior of project.gameplay.filter(item=>item.kind==='capture-zone-3d')){
|
|
404
|
-
const source=byId.get(behavior.componentId);if(!source||source.sceneId!==scene||!visible(source))continue;
|
|
405
|
-
const p=props(source);
|
|
406
|
-
zones.push({id:source.id,sourceId:source.id,x:p.x??0,y:p.y??0,z:p.z??0,...behavior.parameters});
|
|
407
|
-
}
|
|
408
|
-
return {bodies,walls,zones};
|
|
409
|
-
}
|
|
410
|
-
function tick3d(dt){
|
|
411
|
-
if(!stage3dMgr)return;
|
|
412
|
-
for(const behavior of project.gameplay.filter(item=>item.kind==='oscillate-3d')){
|
|
413
|
-
const source=byId.get(behavior.componentId);if(!source||source.sceneId!==scene)continue;
|
|
414
|
-
let st=oscillations3d.get(source.id);if(!st){const p=props(source);st={x:p.x??0,y:p.y??0,z:p.z??0};oscillations3d.set(source.id,st);}
|
|
415
|
-
const bp=behavior.parameters,arg=time*bp.angularSpeed+bp.phase,offset=Math.sin(arg)*bp.amplitude,vel=Math.cos(arg)*bp.amplitude*bp.angularSpeed;
|
|
416
|
-
const body=bodies3d.get(source.id)??(behaviorOn('physics-3d',source.id)?body3dState(source,behaviorOn('physics-3d',source.id)):undefined);
|
|
417
|
-
const nx=st.x+(bp.axis==='x'?offset:0),ny=st.y+(bp.axis==='y'?offset:0),nz=st.z+(bp.axis==='z'?offset:0);
|
|
418
|
-
if(body){body.x=nx;body.y=ny;body.z=nz;body.vx=bp.axis==='x'?vel:0;body.vy=bp.axis==='y'?vel:0;body.vz=bp.axis==='z'?vel:0;}
|
|
419
|
-
else{const o=overrides.get(source.id)??{transform:[...source.transform],parameters:{}};o.parameters.x=nx;o.parameters.y=ny;o.parameters.z=nz;overrides.set(source.id,o);}
|
|
420
|
-
}
|
|
421
|
-
const {bodies,walls,zones}=collect3d();
|
|
422
|
-
stepPhysics3d({bodies,walls,zones,dt,onEvent:(kind,body,other)=>{
|
|
423
|
-
const payload={kind,componentId:body.sourceId};if(other)payload.otherId=other.sourceId;emit(payload);
|
|
424
|
-
}});
|
|
425
|
-
for(const body of bodies)if(body.captured)body.captureElapsed=(body.captureElapsed??0)+dt;
|
|
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
|
-
});
|
|
430
|
-
}
|
|
431
|
-
function ensureFpsState(behavior){
|
|
432
|
-
let st=fpsStates.get(behavior.componentId);
|
|
433
|
-
if(!st){const p=behavior.parameters;st={behavior,x:p.x,y:p.y,z:p.z,yaw:p.yaw,pitch:p.pitch,bobPhase:0,bob:0};fpsStates.set(behavior.componentId,st);}
|
|
434
|
-
return st;
|
|
435
|
-
}
|
|
436
|
-
function initFpsControllers(){
|
|
437
|
-
for(const behavior of project.gameplay.filter(b=>b.kind==='fps-controller-3d'&&byId.get(b.componentId)?.sceneId===scene))ensureFpsState(behavior);
|
|
438
|
-
}
|
|
439
|
-
function live3dInstances(stageId){
|
|
440
|
-
const list=[];
|
|
441
|
-
for(const node of runtimeNodes.values())if(node.contract==='native.mesh3d.v1'&&findStage3dOf(node)?.id===stageId)list.push(node);
|
|
442
|
-
return list;
|
|
443
|
-
}
|
|
444
|
-
function applyFpsLookDelta(behavior,dx,dy){
|
|
445
|
-
const fps=ensureFpsState(behavior),fp=behavior.parameters,sens=fp.lookSensitivity,inv=fp.invertAimY?-1:1;
|
|
446
|
-
let yaw=fps.yaw-dx*sens;
|
|
447
|
-
if(fp.minYaw!==undefined&&fp.maxYaw!==undefined)yaw=Math.max(fp.minYaw,Math.min(fp.maxYaw,yaw));
|
|
448
|
-
fps.yaw=yaw;
|
|
449
|
-
fps.pitch=Math.max(fp.minPitch??-.75,Math.min(fp.maxPitch??.75,fps.pitch-dy*sens*inv));
|
|
450
|
-
}
|
|
451
|
-
function tickFps3d(dt,walls){
|
|
452
|
-
for(const behavior of project.gameplay.filter(b=>b.kind==='fps-controller-3d')){
|
|
453
|
-
const stageComp=byId.get(behavior.componentId);if(!stageComp||stageComp.sceneId!==scene)continue;
|
|
454
|
-
const fps=ensureFpsState(behavior),p=behavior.parameters;
|
|
455
|
-
const aimJoy=p.aimJoystickBehaviorId?joysticks.get(p.aimJoystickBehaviorId):undefined;
|
|
456
|
-
if(aimJoy&&p.aimMode==='rate'&&aimJoy.magnitude>1e-4&&dt>0){
|
|
457
|
-
const turn=p.aimTurnSpeed??1.8,invert=p.invertAimY?-1:1;
|
|
458
|
-
let yaw=fps.yaw-aimJoy.nx*turn*dt;
|
|
459
|
-
if(p.minYaw!==undefined&&p.maxYaw!==undefined)yaw=Math.max(p.minYaw,Math.min(p.maxYaw,yaw));
|
|
460
|
-
fps.yaw=yaw;
|
|
461
|
-
fps.pitch=Math.max(p.minPitch??-.75,Math.min(p.maxPitch??.75,fps.pitch-aimJoy.ny*turn*invert*dt));
|
|
462
|
-
}
|
|
463
|
-
const joy=p.joystickBehaviorId?joysticks.get(p.joystickBehaviorId):undefined;
|
|
464
|
-
const mx=joy?joy.nx:Number(p.moveXVariableId?variables[p.moveXVariableId]:0);
|
|
465
|
-
const my=joy?joy.ny:Number(p.moveYVariableId?variables[p.moveYVariableId]:0);
|
|
466
|
-
const mag=Math.min(1,Math.hypot(mx,my));
|
|
467
|
-
if(mag>1e-4&&p.moveSpeed>0&&dt>0){
|
|
468
|
-
const forward=-my,right=mx,fx=-Math.sin(fps.yaw),fz=-Math.cos(fps.yaw),rx=Math.cos(fps.yaw),rz=-Math.sin(fps.yaw);
|
|
469
|
-
const step=p.moveSpeed*dt,stageWalls=walls.filter(w=>w.stageId===stageComp.id);
|
|
470
|
-
const next=resolveWallSlide3d(fps.x+(fx*forward+rx*right)*step,fps.z+(fz*forward+rz*right)*step,p.playerRadius??.45,stageWalls,p.boundsX??12,p.boundsZ??12);
|
|
471
|
-
fps.x=next.x;fps.z=next.z;
|
|
472
|
-
fps.bobPhase+=dt*10*mag;
|
|
473
|
-
fps.bob=reducedMotion?.matches?0:Math.sin(fps.bobPhase)*(p.bobAmplitude??.04)*mag;
|
|
474
|
-
}else{
|
|
475
|
-
fps.bob*=Math.max(0,1-12*dt);
|
|
476
|
-
}
|
|
477
|
-
}
|
|
478
|
-
for(const behavior of project.gameplay.filter(b=>b.kind==='steer-3d')){
|
|
479
|
-
const source=byId.get(behavior.componentId);if(!source||source.sceneId!==scene)continue;
|
|
480
|
-
const p=behavior.parameters;
|
|
481
|
-
for(const c of targetsFor(source)){
|
|
482
|
-
if(!visible(c))continue;
|
|
483
|
-
const stageComp=findStage3dOf(c),fps=stageComp?fpsStates.get(stageComp.id):undefined;if(!fps)continue;
|
|
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);}
|
|
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;}
|
|
489
|
-
else if(p.mode==='patrol'){nx+=Math.cos(time*1.5)*p.speed*dt;}
|
|
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);
|
|
492
|
-
const o=overrides.get(c.id)??{transform:[...c.transform],parameters:{}};
|
|
493
|
-
o.parameters.x=resolved.x;if(homingBolt)o.parameters.y=ny;o.parameters.z=resolved.z;
|
|
494
|
-
if(p.faceCamera!==false)o.parameters.ry=Math.atan2(fps.x-resolved.x,fps.z-resolved.z);
|
|
495
|
-
overrides.set(c.id,o);
|
|
496
|
-
}
|
|
497
|
-
}
|
|
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
|
-
}
|
|
538
|
-
function spawnPrototype3d(prototypeId,x,y,z){
|
|
539
|
-
if(instances.length>=128){diagnose('Instance budget exhausted');return;}
|
|
540
|
-
const proto=byId.get(prototypeId),size=id=>1+project.components.filter(c=>c.parentId===id).reduce((sum,c)=>sum+size(c.id),0);
|
|
541
|
-
if(runtimeNodes.size+size(proto.id)>4096){diagnose('Runtime node budget exhausted');return;}
|
|
542
|
-
const rootId='instance.'+(++serial);
|
|
543
|
-
function cloneNode(source,parentId){const id=source.id===proto.id?rootId:rootId+':'+source.id,node={...source,id,runtimeId:id,instanceId:rootId,prototypeId:source.id,prototype:false,parentId,transform:[...source.transform],parameters:{...source.parameters},spawnTime:time};runtimeNodes.set(id,node);for(const child of project.components.filter(c=>c.parentId===source.id))cloneNode(child,id);return node;}
|
|
544
|
-
const root=cloneNode(proto,proto.parentId);root.parameters.x=x;root.parameters.y=y;root.parameters.z=z;instances.push(root);initializeInstanceState(root);return root;
|
|
545
|
-
}
|
|
546
|
-
function performRaycast3d(a){
|
|
547
|
-
if(!stage3dMgr)return;
|
|
548
|
-
const stageComp=byId.get(a.stageId);if(!stageComp||stageComp.sceneId!==scene)return;
|
|
549
|
-
stage3dMgr.triggerRecoil?.(stageComp.id);
|
|
550
|
-
const p=props(stageComp),m=world(stageComp),sx=Math.hypot(m[0],m[1]),sy=Math.hypot(m[2],m[3]);
|
|
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});
|
|
553
|
-
let ndcX=0,ndcY=0;
|
|
554
|
-
if(a.mode==='pointer'){
|
|
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
|
-
}
|
|
562
|
-
}
|
|
563
|
-
const occluders=new Set(project.gameplay.filter(b=>b.kind==='physics-3d'&&b.parameters.mode!=='dynamic').map(b=>b.componentId));
|
|
564
|
-
const team=a.targetTeam??'any';
|
|
565
|
-
const isTarget=id=>{
|
|
566
|
-
const c=object(id);if(!c||!visible(c))return false;
|
|
567
|
-
if(team!=='any')return instanceState(c)?.team===team;
|
|
568
|
-
return Boolean(instanceState(c))||!occluders.has(c.prototypeId??c.id);
|
|
569
|
-
};
|
|
570
|
-
const hitResult=entry.raycast(ndcX,ndcY,a.maxDistance??80,{isTarget,isOccluder:id=>occluders.has(id)});
|
|
571
|
-
if(hitResult){const target=object(hitResult.id);if(target)emit(instanceEvent('raycastHit3d',target,stageComp));}
|
|
572
|
-
else emit({kind:'raycastMiss3d',componentId:stageComp.id});
|
|
573
|
-
}
|
|
574
|
-
function project3dToStage(compId){
|
|
575
|
-
if(!stage3dMgr)return null;
|
|
576
|
-
const c=object(compId);if(!c||c.contract!=='native.mesh3d.v1')return null;
|
|
577
|
-
const stageComp=findStage3dOf(c);if(!stageComp)return null;
|
|
578
|
-
const entry=stage3dMgr.getStage(stageComp);if(!entry||!entry.lastWidth||!entry.lastHeight)return null;
|
|
579
|
-
const body=bodies3d.get(c.id),p=props(c);
|
|
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);
|
|
581
|
-
return entry.isFullBleed?{x:entry.lastX+local.x,y:entry.lastY+local.y}:point(world(stageComp),local.x,local.y);
|
|
582
|
-
}
|
|
583
|
-
function aim3dVelocity(){
|
|
584
|
-
if(!aiming3d||!stage3dMgr)return {vx:0,vz:0,power:0,pull:0};
|
|
585
|
-
const stageComp=byId.get(aiming3d.stageId),entry=stage3dMgr.getStage(stageComp),body=bodies3d.get(aiming3d.targetId),bp=aiming3d.behavior.parameters;
|
|
586
|
-
if(!entry||!body||!entry.lastWidth||!entry.lastHeight)return {vx:0,vz:0,power:0,pull:0};
|
|
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
|
-
}
|
|
595
|
-
const pull=Math.hypot(aiming3d.current.x-aiming3d.start.x,aiming3d.current.y-aiming3d.start.y);
|
|
596
|
-
const a=entry.unproject(sLocal.x,sLocal.y,entry.lastWidth,entry.lastHeight,body.y);
|
|
597
|
-
const b=entry.unproject(cLocal.x,cLocal.y,entry.lastWidth,entry.lastHeight,body.y);
|
|
598
|
-
if(!a||!b)return {vx:0,vz:0,power:0,pull};
|
|
599
|
-
let vx=(a.x-b.x)*bp.dragScale,vz=(a.z-b.z)*bp.dragScale;
|
|
600
|
-
const speed=Math.hypot(vx,vz);
|
|
601
|
-
if(speed>bp.maxSpeed){vx*=bp.maxSpeed/speed;vz*=bp.maxSpeed/speed;}
|
|
602
|
-
return {vx,vz,power:Math.min(1,Math.hypot(vx,vz)/Math.max(.001,bp.maxSpeed)),pull};
|
|
603
|
-
}
|
|
604
|
-
function updateAim3d(p){
|
|
605
|
-
if(!aiming3d||!stage3dMgr)return;
|
|
606
|
-
aiming3d.current=p;
|
|
607
|
-
const launch=aim3dVelocity(),bp=aiming3d.behavior.parameters;
|
|
608
|
-
aiming3d.power=launch.power;
|
|
609
|
-
if(bp.powerVariableId)variables[bp.powerVariableId]=launch.power;
|
|
610
|
-
const stageComp=byId.get(aiming3d.stageId),entry=stage3dMgr.getStage(stageComp),body=bodies3d.get(aiming3d.targetId);
|
|
611
|
-
if(entry&&body&&bp.showTrajectory&&launch.pull>=bp.minPullPx){
|
|
612
|
-
const {walls,zones}=collect3d();
|
|
613
|
-
entry.setGuide(predictTrajectory3d({body,walls,zones,vx:launch.vx,vz:launch.vz,dots:bp.trajectoryDots}));
|
|
614
|
-
}else entry?.setGuide([]);
|
|
615
|
-
}
|
|
616
|
-
function physics3dSnapshot(){
|
|
617
|
-
return {
|
|
618
|
-
bodies:[...bodies3d.values()].map(b=>({id:b.id,sourceId:b.sourceId,x:b.x,y:b.y,z:b.z,vx:b.vx,vy:b.vy,vz:b.vz,atRest:Boolean(b.atRest),captured:Boolean(b.captured),airborne:Boolean(b.airborne)})),
|
|
619
|
-
aiming:aiming3d?{componentId:aiming3d.sourceId,pointerId:aiming3d.pointerId,power:aiming3d.power}:null,
|
|
620
|
-
projected:Object.fromEntries(projected3d),
|
|
621
|
-
fps:Object.fromEntries([...fpsStates].map(([id,s])=>[id,{x:s.x,y:s.y,z:s.z,yaw:s.yaw,pitch:s.pitch}])),
|
|
622
|
-
};
|
|
623
|
-
}
|
|
624
|
-
/* 3d:end */
|
|
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});}}
|
|
626
|
-
function flushPendingMusic(){
|
|
627
|
-
if(!audio||audio.state!=='running'||!pendingLoopAudio.size)return;
|
|
628
|
-
const queued=[...pendingLoopAudio.values()];
|
|
629
|
-
pendingLoopAudio.clear();
|
|
630
|
-
for(const b of queued)void sound(b);
|
|
631
|
-
}
|
|
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;}
|
|
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
|
-
}
|
|
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();}
|
|
659
|
-
async function sound(b){
|
|
660
|
-
if(audioSources.size>=32)return;
|
|
661
|
-
const shouldLoop=Boolean(b.parameters.loop);
|
|
662
|
-
if(!audio){if(shouldLoop)pendingLoopAudio.set(b.id,b);return;}
|
|
663
|
-
const context=audio,epoch=audioEpoch,cooldown=b.parameters.cooldownMs??45,now=context.currentTime;
|
|
664
|
-
if(cooldown>0&&now-(audioCooldowns.get(b.id)??-Infinity)<cooldown/1000)return;
|
|
665
|
-
if(shouldLoop&&loopingAudio.has(b.id))return;
|
|
666
|
-
const target=byId.get(b.componentId),asset=assets.get(target?.assetSlots[0]?.assetId),isSampled=asset?.mime==='audio/wav'||asset?.mime==='audio/mpeg';
|
|
667
|
-
if(!isSampled&&b.parameters.allowSynthFallback===false){blockedAudio++;return;}
|
|
668
|
-
audioCooldowns.set(b.id,now);
|
|
669
|
-
if(context.state!=='running'&&!await unlockAudio()){if(shouldLoop)pendingLoopAudio.set(b.id,b);return;}
|
|
670
|
-
if(audio!==context||context.state!=='running'||epoch!==audioEpoch||audioSources.size>=32)return;
|
|
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);
|
|
672
|
-
audioPitchCounts.set(b.id,count+1);
|
|
673
|
-
if(isSampled){
|
|
674
|
-
if(shouldLoop)loopingAudio.add(b.id);
|
|
675
|
-
try{
|
|
676
|
-
let buffer=decodedAudio.get(asset.hash);
|
|
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)=>{
|
|
678
|
-
const pending=context.decodeAudioData(raw.buffer,resolve,reject);
|
|
679
|
-
if(pending&&typeof pending.then==='function')pending.then(resolve,reject);
|
|
680
|
-
});decodedAudio.set(asset.hash,buffer);}
|
|
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();
|
|
685
|
-
}catch{loopingAudio.delete(b.id);diagnose('Audio decode failed');}
|
|
686
|
-
return;
|
|
687
|
-
}
|
|
688
|
-
const o=context.createOscillator(),g=context.createGain();o.frequency.value=b.parameters.frequency*playbackRate;o.type='sine';g.gain.setValueAtTime(b.parameters.volume,context.currentTime);g.gain.exponentialRampToValueAtTime(.001,context.currentTime+b.parameters.seconds);connectVoice(o,g,b);o.start();o.stop(context.currentTime+b.parameters.seconds);
|
|
689
|
-
}
|
|
690
|
-
function hasMatch(boardId,changed){const cells=[...matchCells.values()].filter(cell=>cell.boardId===boardId),at=(row,column)=>cells.find(cell=>cell.row===row&&cell.column===column)?.group;for(let row=0;row<16;row++)for(let column=0;column<14;column++){const group=at(row,column);if(group&&group===at(row,column+1)&&group===at(row,column+2)&&changed.some(c=>c.row===row&&c.column>=column&&c.column<=column+2))return true;}for(let column=0;column<16;column++)for(let row=0;row<14;row++){const group=at(row,column);if(group&&group===at(row+1,column)&&group===at(row+2,column)&&changed.some(c=>c.column===column&&c.row>=row&&c.row<=row+2))return true;}return false;}
|
|
691
|
-
function selectMatchTile(c){const cell=matchCells.get(c.id);if(!cell||cell.sceneId!==scene||!props(c).enabled||!visible(c))return;const board=matchBoards.get(c.parentId);if(board){matchSelected=board.select(c.id);return;}if(matchSelected===c.id){matchSelected=undefined;return;}const prior=matchCells.get(matchSelected);if(!prior||prior.sceneId!==scene||prior.boardId!==cell.boardId){matchSelected=c.id;return;}const first=byId.get(matchSelected);if(Math.abs(prior.row-cell.row)+Math.abs(prior.column-cell.column)!==1){matchSelected=c.id;return;}if(prior.group===cell.group){matchSelected=undefined;emit({kind:'invalidMatch',componentId:c.parentId??c.id});return;}const row=prior.row,column=prior.column,otherRow=cell.row,otherColumn=cell.column,firstTransform=[...transform(first)],secondTransform=[...transform(c)];prior.row=otherRow;prior.column=otherColumn;cell.row=row;cell.column=column;if(hasMatch(cell.boardId,[prior,cell])){const move=(target,position)=>{const current=overrides.get(target.id)??{transform:[...transform(target)],parameters:{}};current.transform=[...current.transform];current.transform[4]=position[4];current.transform[5]=position[5];overrides.set(target.id,current);};move(first,secondTransform);move(c,firstTransform);matchSelected=undefined;emit({kind:'validMatch',componentId:c.parentId??c.id});}else{prior.row=row;prior.column=column;cell.row=otherRow;cell.column=otherColumn;matchSelected=undefined;emit({kind:'invalidMatch',componentId:c.parentId??c.id});}}
|
|
692
|
-
|
|
693
|
-
function dropZonesFor(item){
|
|
694
|
-
const zones=[],itemBounds=geometry(item,world(item)),itemCenter=centerOf(item),dragBehavior=behaviorOn('drag',item.prototypeId??item.id);
|
|
695
|
-
for(const behavior of project.gameplay.filter(b=>b.kind==='drop-zone')){
|
|
696
|
-
const source=byId.get(behavior.componentId),config=behavior.parameters;if(source.sceneId!==scene)continue;
|
|
697
|
-
for(const candidate of targetsFor(source)){
|
|
698
|
-
if(candidate.id===item.id||isDescendant(candidate,item.id)||!visible(candidate))continue;
|
|
699
|
-
const bounds=geometry(candidate,world(candidate)),center=centerOf(candidate),distance=Math.hypot(center.x-itemCenter.x,center.y-itemCenter.y),overlap=config.radiusPx>0?distance<=config.radiusPx:itemBounds.left<bounds.right&&itemBounds.right>bounds.left&&itemBounds.top<bounds.bottom&&itemBounds.bottom>bounds.top;
|
|
700
|
-
if(!overlap)continue;
|
|
701
|
-
zones.push({id:candidate.id,c:candidate,sourceId:source.id,paintOrder:paint.findIndex(row=>row.c.id===candidate.id),distance,itemTarget:project.gameplay.some(b=>b.kind==='drag'&&b.componentId===source.id),...config});
|
|
702
|
-
}
|
|
703
|
-
}
|
|
704
|
-
return {zones,tag:dragBehavior?.parameters.tag??''};
|
|
705
|
-
}
|
|
706
|
-
function initializeDropOccupancy(item){
|
|
707
|
-
const sources=item?[item]:project.gameplay.filter(b=>b.kind==='drag').flatMap(b=>targetsFor(byId.get(b.componentId)));
|
|
708
|
-
for(const c of sources){
|
|
709
|
-
if(!c||!visible(c)||dropOccupancy.zoneOf(c.id))continue;
|
|
710
|
-
const {zones,tag}=dropZonesFor(c),result=resolveDropZone({itemId:c.id,tag,zones:zones.filter(zone=>!zone.itemTarget),occupancy:dropOccupancy});if(result?.kind==='accept')dropOccupancy.place(c.id,result.zone.id);
|
|
711
|
-
}
|
|
712
|
-
}
|
|
713
|
-
function tweenCenter(c,target,seconds=.18){if(!c)return;gestureTweens.to(c.id,centerOf(c),target,seconds);}
|
|
714
|
-
function dropEvent(kind,c,zone,occupant){
|
|
715
|
-
const other=occupant??zone?.c;emit({...instanceEvent(kind,c,other,{...(zone?{otherId:zone.sourceId}:{})}),instanceId:c.instanceId??zone?.c?.instanceId});
|
|
716
|
-
}
|
|
717
|
-
function finishDrag(p){
|
|
718
|
-
if(!drag||drag.pointerId!==p.pointerId)return false;
|
|
719
|
-
const current=drag,c=object(current.targetId),config=current.b.parameters;drag=undefined;hoverDrop=undefined;
|
|
720
|
-
try{if(canvas.hasPointerCapture?.(p.pointerId))canvas.releasePointerCapture?.(p.pointerId);}catch{/* Capture may already have been released by the host. */}
|
|
721
|
-
if(!c)return true;
|
|
722
|
-
const {zones,tag}=dropZonesFor(c),result=resolveDropZone({itemId:c.id,tag,zones,occupancy:dropOccupancy}),origin=current.origin,originZone=current.originZone;
|
|
723
|
-
if(!result){
|
|
724
|
-
dropEvent('dragReject',c,undefined,undefined);
|
|
725
|
-
if(config.snapBack){if(originZone)dropOccupancy.place(c.id,originZone);tweenCenter(c,origin,config.snapBackSeconds??.18);}
|
|
726
|
-
return true;
|
|
727
|
-
}
|
|
728
|
-
const {zone}=result,occupant=result.occupantId?object(result.occupantId):undefined;
|
|
729
|
-
if(result.kind==='reject'){
|
|
730
|
-
dropEvent('dragReject',c,zone,occupant);
|
|
731
|
-
if(config.snapBack){if(originZone)dropOccupancy.place(c.id,originZone);tweenCenter(c,origin,config.snapBackSeconds??.18);}
|
|
732
|
-
return true;
|
|
733
|
-
}
|
|
734
|
-
if(result.kind==='accept'){
|
|
735
|
-
dropOccupancy.place(c.id,zone.id);if(zone.snapMode==='center')tweenCenter(c,centerOf(zone.c),config.snapBackSeconds??.18);
|
|
736
|
-
}else if(result.kind==='swap'&&occupant){
|
|
737
|
-
dropOccupancy.place(c.id,zone.id);if(originZone)dropOccupancy.place(occupant.id,originZone);else dropOccupancy.release(occupant.id);
|
|
738
|
-
tweenCenter(c,centerOf(zone.c),config.snapBackSeconds??.18);tweenCenter(occupant,origin,config.snapBackSeconds??.18);
|
|
739
|
-
}
|
|
740
|
-
dropEvent('dragDrop',c,zone,result.kind==='accept'?zone.c:occupant);return true;
|
|
741
|
-
}
|
|
742
|
-
function tickGestureInput(dt){
|
|
743
|
-
gestureTweens.tick(dt,(id,position)=>{const c=object(id);if(c)setWorldCenter(c,position.x,position.y);});
|
|
744
|
-
for(const id of [...dropOccupancy.itemZone.keys()]){const c=object(id);if(!c||!visible(c))dropOccupancy.release(id);}
|
|
745
|
-
if(!gestureInput)return;
|
|
746
|
-
for(const hold of gestureInput.holds){
|
|
747
|
-
const value=hold.charge.tick(dt);if(value===variables[hold.behavior.parameters.variableId])continue;
|
|
748
|
-
variables[hold.behavior.parameters.variableId]=value;emit({kind:'variableChange',variableId:hold.behavior.parameters.variableId,instanceId:hold.c.instanceId,selfInstanceId:hold.c.instanceId??hold.c.id});
|
|
749
|
-
}
|
|
750
|
-
}
|
|
751
|
-
function targetForMode(c,parameters){
|
|
752
|
-
const mode=parameters.targetMode;if(mode==='pointer')return {...lastPointer};
|
|
753
|
-
if(mode==='component'){const target=object(parameters.targetComponentId);return target?centerOf(target):undefined;}
|
|
754
|
-
if(mode==='nearest-team'){
|
|
755
|
-
const origin=centerOf(c),nodes=[],team=parameters.team,range=parameters.maxRangePx??0;for(const [id,state]of instanceEngine.states){const target=object(id);if(target&&visible(target))nodes.push({id,...centerOf(target),team:state.team});}
|
|
756
|
-
return findNearestByTeam(origin,nodes,team,range,c.instanceId??c.id);
|
|
757
|
-
}
|
|
758
|
-
return undefined;
|
|
759
|
-
}
|
|
760
|
-
function tickSteering(dt){
|
|
761
|
-
for(const behavior of project.gameplay.filter(b=>b.kind==='steer')){
|
|
762
|
-
const source=byId.get(behavior.componentId),p=behavior.parameters;if(source.sceneId!==scene)continue;
|
|
763
|
-
for(const c of targetsFor(source)){
|
|
764
|
-
if(!visible(c))continue;const target=targetForMode(c,p);if(!target)continue;
|
|
765
|
-
const center=centerOf(c),dx=target.x-center.x,dy=target.y-center.y;if(p.maxRangePx>0&&Math.hypot(dx,dy)>p.maxRangePx)continue;
|
|
766
|
-
let desired=Math.atan2(dy,dx);if(p.mode==='flee')desired+=Math.PI;else if(p.mode==='orbit')desired+=Math.PI/2;
|
|
767
|
-
const previous=instanceEngine.headings.get(c.id)??desired,heading=turnToward(previous,desired,p.turnRateDegPerSec*Math.PI/180*dt);instanceEngine.headings.set(c.id,heading);
|
|
768
|
-
setWorldCenter(c,center.x+Math.cos(heading)*p.speed*dt,center.y+Math.sin(heading)*p.speed*dt);if(p.orientToVelocity!==false)setComponentHeading(c,heading);
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
}
|
|
772
|
-
function spawnPrototype(prototypeId,x,y,path){
|
|
773
|
-
if(instances.length>=128){diagnose('Instance budget exhausted');return;}
|
|
774
|
-
const proto=byId.get(prototypeId),size=id=>1+project.components.filter(c=>c.parentId===id).reduce((sum,c)=>sum+size(c.id),0);
|
|
775
|
-
if(runtimeNodes.size+size(proto.id)>4096){diagnose('Runtime node budget exhausted');return;}
|
|
776
|
-
const rootId='instance.'+(++serial);
|
|
777
|
-
function cloneNode(source,parentId){const id=source.id===proto.id?rootId:rootId+':'+source.id,node={...source,id,runtimeId:id,instanceId:rootId,prototypeId:source.id,prototype:false,parentId,transform:[...source.transform],spawnTime:time};runtimeNodes.set(id,node);for(const child of project.components.filter(c=>c.parentId===source.id))cloneNode(child,id);return node;}
|
|
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;
|
|
779
|
-
}
|
|
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 */
|
|
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);}}
|
|
788
|
-
else if(a.kind==='resetMatch'){resetMatch(a.componentId);resetBoards(a.componentId);}
|
|
789
|
-
else if(a.kind==='clearStrokes'){strokeStates.get(a.componentId)?.clear();strokeWallBodies=strokeWallBodies.filter(wall=>wall.owner!==a.componentId);}
|
|
790
|
-
else if(a.kind==='resetMask'){const c=object(a.componentId),behavior=behaviorOn('erase-mask',a.componentId);if(c&&behavior)maskState(c,behavior).reset();}
|
|
791
|
-
/* 3d:start */
|
|
792
|
-
else if(a.kind==='raycast3d'){performRaycast3d(a);}
|
|
793
|
-
else if(a.kind==='spawnAt3d'){spawnAction3d(a);}
|
|
794
|
-
else if(a.kind==='playModelAnimation'){stage3dMgr?.playModelAnimation(a.componentId,a);}
|
|
795
|
-
/* 3d:end */
|
|
796
|
-
else if(a.kind==='copyMatchAsset'){
|
|
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');
|
|
798
|
-
if(last&&sample){
|
|
799
|
-
const source=byId.get(last.from),center=point(world(source),source.parameters.width/2,source.parameters.height/2),parent=target.parentId?world(byId.get(target.parentId)):identityMatrix(),position=point(inverseMatrix(parent),center.x,center.y);
|
|
800
|
-
const current=overrides.get(target.id)??{transform:[...target.transform],parameters:{}};
|
|
801
|
-
current.transform=[...current.transform];current.transform[4]=position.x-target.parameters.width/2;current.transform[5]=position.y-target.parameters.height/2;current.assetId=sample.assetSlots[0]?.assetId;
|
|
802
|
-
overrides.set(target.id,current);
|
|
803
|
-
}
|
|
804
|
-
}
|
|
805
|
-
else if(a.kind==='hintMatch'){matchSelected=undefined;matchBoards.get(a.componentId)?.showHint();}
|
|
806
|
-
else if(a.kind==='spawn')spawnPrototype(a.prototypeId,a.x,a.y);
|
|
807
|
-
else if(a.kind==='spawnAt'){
|
|
808
|
-
const self=a.at==='self'||a.at==='midpoint'?(event.selfInstanceId!==undefined||event.instanceId!==undefined?object(event.selfInstanceId??event.instanceId):eventTarget(a.targetComponentId,event,'self')):eventTarget(a.targetComponentId,event,'self');
|
|
809
|
-
const other=a.at==='other'||a.at==='midpoint'?(event.otherInstanceId!==undefined?object(event.otherInstanceId):undefined):undefined,target=a.at==='other'?other:self;
|
|
810
|
-
if(a.at==='pointer'||(a.at==='midpoint'?self&&other:target)){
|
|
811
|
-
const first=self?centerOf(self):undefined,second=other?centerOf(other):undefined,center=a.at==='pointer'?lastPointer:a.at==='midpoint'?{x:(first.x+second.x)/2,y:(first.y+second.y)/2}:centerOf(target),proto=byId.get(a.prototypeId);
|
|
812
|
-
const count=Math.max(0,Math.min(16,Math.floor(a.countVariableId?Number(variables[a.countVariableId]):a.count??1)));
|
|
813
|
-
for(let index=0;index<count;index++){const jitterX=a.jitterX?(instanceEngine.rng.next()*2-1)*a.jitterX:0,jitterY=a.jitterY?(instanceEngine.rng.next()*2-1)*a.jitterY:0;spawnPrototype(a.prototypeId,center.x+a.offsetX+jitterX-proto.parameters.width/2,center.y+a.offsetY+jitterY-proto.parameters.height/2);}
|
|
814
|
-
}
|
|
815
|
-
}
|
|
816
|
-
else if(a.kind==='random'){
|
|
817
|
-
const old=variables[a.variableId],value=instanceEngine.rng.between(a.min,a.max,a.integer===true);variables[a.variableId]=value;if(old!==value)emit({kind:'variableChange',variableId:a.variableId,instanceId:event.instanceId});
|
|
818
|
-
}
|
|
819
|
-
else if(a.kind==='modifyInstanceState'){
|
|
820
|
-
const c=a.target==='component'?object(a.componentId):eventTarget(a.componentId,event,a.target);if(c)modifyInstance(c,a.field,a.op,a.variableId?variables[a.variableId]:a.value);
|
|
821
|
-
}
|
|
822
|
-
else if(a.kind==='launchToward'){
|
|
823
|
-
const source=byId.get(a.componentId),list=targetsFor(source),eid=event.selfInstanceId??event.instanceId,c=source.prototype?(list.find(node=>node.instanceId===eid||node.id===eid)??list[list.length-1]):eventTarget(a.componentId,event,'self')??object(a.componentId),behavior=behaviorOn('physics-body',a.componentId),body=c&&physicsState(c,behavior);if(!body)return;
|
|
824
|
-
let angle;if(a.targetMode==='angle-variable')angle=Number(variables[a.angleVariableId])*Math.PI/180;else{const target=targetForMode(c,a);if(!target)return;const center=centerOf(c);angle=Math.atan2(target.y-center.y,target.x-center.x);}
|
|
825
|
-
const speed=Number(a.speedVariableId?variables[a.speedVariableId]:a.speed);if(!Number.isFinite(speed)){diagnose('Launch speed invalid');return;}body.vx=Math.cos(angle)*speed;body.vy=Math.sin(angle)*speed;body.atRest=false;body.restElapsed=0;body.captured=false;body.exited=false;if(a.orientToVelocity!==false)setComponentHeading(c,angle);emit(instanceEvent('launch',c));
|
|
826
|
-
}
|
|
827
|
-
else if(a.kind==='moveToComponent'){
|
|
828
|
-
const destSource=byId.get(a.targetComponentId),c=eventTarget(a.componentId,event,a.target??'self'),target=destSource&&prototypeOwner(destSource)?eventTarget(a.targetComponentId,event,a.target==='other'?'self':'other')??targetsFor(destSource)[0]:object(a.targetComponentId);if(c&&target)tweenCenter(c,centerOf(target),a.seconds);
|
|
829
|
-
}
|
|
830
|
-
else if(a.kind==='returnToOrigin'){
|
|
831
|
-
const c=eventTarget(a.componentId,event,'self'),origin=c&&dragOrigins.get(c.id);if(c&&origin)tweenCenter(c,origin,a.seconds);
|
|
832
|
-
}
|
|
833
|
-
else if(a.kind==='spawnOnPath')spawnPrototype(a.prototypeId,0,0,{startNode:a.startNode,targetNode:a.targetNode,networkBehaviorId:a.networkBehaviorId});
|
|
834
|
-
else if(['setVelocity','applyImpulse','stopBody'].includes(a.kind)){
|
|
835
|
-
const source=byId.get(a.componentId),targets=event.instanceId?[...runtimeNodes.values()].filter(c=>c.instanceId===event.instanceId&&c.prototypeId===source.id):targetsFor(source),behavior=behaviorOn('physics-body',source.id);
|
|
836
|
-
for(const c of targets){const body=physicsState(c,behavior);if(a.kind==='setVelocity'){body.vx=a.vxVariableId?variables[a.vxVariableId]:a.vx;body.vy=a.vyVariableId?variables[a.vyVariableId]:a.vy;}else if(a.kind==='applyImpulse'){body.vx+=a.vxVariableId?variables[a.vxVariableId]:a.ix;body.vy+=a.vyVariableId?variables[a.vyVariableId]:a.iy;}else{body.vx=0;body.vy=0;body.atRest=true;}body.captured=false;body.exited=false;body.restElapsed=0;if(a.kind!=='stopBody')body.atRest=false;}
|
|
837
|
-
}
|
|
838
|
-
else if(a.kind==='setPosition'){
|
|
839
|
-
const source=byId.get(a.componentId),targets=event.instanceId?[...runtimeNodes.values()].filter(c=>c.instanceId===event.instanceId&&c.prototypeId===source.id):targetsFor(source),behavior=behaviorOn('physics-body',source.id);
|
|
840
|
-
for(const c of targets){const body=physicsState(c,behavior);body.x=a.xVariableId?variables[a.xVariableId]:a.x;body.y=a.yVariableId?variables[a.yVariableId]:a.y;body.vx=0;body.vy=0;body.captured=false;body.exited=false;body.atRest=true;setWorldCenter(c,body.x,body.y);}
|
|
841
|
-
}
|
|
842
|
-
else if(a.kind==='setPathEdge')pathNetworks.get(a.behaviorId)?.setEdge(a.edgeId,a.enabled,a.cost);
|
|
843
|
-
else if(a.kind==='setPathGate')pathNetworks.get(project.gameplay.find(b=>b.id===a.behaviorId)?.parameters.networkBehaviorId)?.setGate(a.behaviorId,a.mode,a.holdSeconds);
|
|
844
|
-
else if(a.kind==='setPathTarget'){
|
|
845
|
-
const source=byId.get(a.componentId),behavior=behaviorOn('path-agent',source.id),network=pathNetworks.get(behavior.parameters.networkBehaviorId);
|
|
846
|
-
for(const c of event.instanceId?[...runtimeNodes.values()].filter(c=>c.instanceId===event.instanceId&&c.prototypeId===source.id):targetsFor(source)){c.pathTargetNode=a.targetNode;network?.setTarget(c.id,a.targetNode);}
|
|
847
|
-
}
|
|
848
|
-
else if(a.kind==='compute'){
|
|
849
|
-
const left=Number(variables[a.variableId]),right=a.operandVariableId!==undefined?Number(variables[a.operandVariableId]):a.value;if(['div','mod'].includes(a.op)&&right===0){diagnose('Division by zero');return;}let value=({add:()=>left+right,sub:()=>left-right,mul:()=>left*right,div:()=>right===0?left:left/right,mod:()=>right===0?left:left%right,min:()=>Math.min(left,right),max:()=>Math.max(left,right),set:()=>right,floor:()=>Math.floor(left),ceil:()=>Math.ceil(left),abs:()=>Math.abs(left),clamp:()=>Math.max(a.min,Math.min(a.max,left))})[a.op]();
|
|
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});
|
|
851
|
-
}
|
|
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);}
|
|
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
|
-
}
|
|
858
|
-
else if(a.kind==='restart'){bridge?.notifyGameRetry?.();transition='__restart';}
|
|
859
|
-
else if(a.kind==='cameraShake'){if(!reducedMotion?.matches)shake={intensity:a.intensity,seconds:a.seconds,elapsed:0};}
|
|
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();}
|
|
861
|
-
else if(a.kind==='floatingText'){
|
|
862
|
-
const authored=byId.get(a.componentId),source=event.instanceId?[...runtimeNodes.values()].find(node=>node.instanceId===event.instanceId&&node.prototypeId===a.componentId)??authored:object(a.componentId)??authored,target=source?.sceneId===scene?source:authored;
|
|
863
|
-
if(target){
|
|
864
|
-
let center;
|
|
865
|
-
/* 3d:start */
|
|
866
|
-
if(target.contract==='native.mesh3d.v1')center=project3dToStage(target.id);
|
|
867
|
-
/* 3d:end */
|
|
868
|
-
if(!center){const p=props(target);center=point(world(target),p.width/2,p.height/2);}
|
|
869
|
-
floatingTexts.push({x:center.x,y:center.y,text:a.text.replace(/\{\{([a-z0-9_.-]+)\}\}/g,(_,id)=>String(variables[id]??'')),color:a.color,fontSize:a.fontSize,risePx:a.risePx,seconds:a.seconds,elapsed:0});if(floatingTexts.length>32)floatingTexts.shift();
|
|
870
|
-
}
|
|
871
|
-
}
|
|
872
|
-
else if(a.kind==='store'){
|
|
873
|
-
if(event.kind==='click'&&event.pointerId!==undefined&&!pendingStore){
|
|
874
|
-
pendingStore={pointerId:event.pointerId,targetId:event.targetId,condition:bindingCondition};
|
|
875
|
-
canvas.setPointerCapture?.(event.pointerId);
|
|
876
|
-
}
|
|
877
|
-
}
|
|
878
|
-
else if(a.behaviorId){const b=project.gameplay.find(b=>b.id===a.behaviorId);if(a.kind==='playAudio')void sound(b);else if(a.kind==='animate'){const source=byId.get(b.componentId),targets=prototypeOwner(source)?[...runtimeNodes.values()].filter(c=>c.prototypeId===source.id&&(!event.instanceId||c.instanceId===event.instanceId)):[source];for(const target of targets){const key=b.id+':'+target.id;animations=animations.filter(x=>x.id!==key);const parameters={...b.parameters};if(parameters.fromCurrent)parameters.from=parameters.property==='opacity'?props(target).opacity:transform(target)[parameters.property==='x'?4:5];animations.push({...b,parameters,id:key,behaviorId:b.id,targetId:target.id,elapsed:0,baseTransform:[...target.transform]});}}else if(a.kind==='stopAnimation')animations=animations.filter(x=>x.behaviorId!==b.id);else if(a.kind==='emit')emitParticles(b,event);}
|
|
879
|
-
}
|
|
880
|
-
function emitParticles(behavior,event){
|
|
881
|
-
const p=behavior.parameters,isPixelConfetti=p.shape==='pixel-confetti',isVectorConfetti=p.shape==='confetti',isConfetti=isPixelConfetti||isVectorConfetti;
|
|
882
|
-
if(isConfetti&&reducedMotion?.matches)return;
|
|
883
|
-
if(particles.length+p.count>256){diagnose('Particle budget exhausted');return;}
|
|
884
|
-
if(isPixelConfetti&&p.coverage==='screen'){particles.push(...screenConfetti(p));return;}
|
|
885
|
-
if(isVectorConfetti&&p.coverage==='screen'){particles.push(...screenVectorConfetti(p));return;}
|
|
886
|
-
const source=byId.get(behavior.componentId);
|
|
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 */
|
|
912
|
-
let matrix=transform(c),clipId;
|
|
913
|
-
for(let parent=object(c.parentId);parent;parent=object(parent.parentId)){
|
|
914
|
-
if(isConfetti&&parent.contract==='native.group.v1'&&props(parent).clip){clipId=parent.id;break;}
|
|
915
|
-
matrix=multiplyMatrix(transform(parent),matrix);
|
|
916
|
-
}
|
|
917
|
-
const dimensions=props(c);
|
|
918
|
-
const position=p.origin==='anchor'?point(matrix,0,0):
|
|
919
|
-
isConfetti||p.origin==='center'?point(matrix,dimensions.width/2,dimensions.height/2):
|
|
920
|
-
{x:matrix[4]+c.parameters.width/2,y:matrix[5]+c.parameters.height/2};
|
|
921
|
-
if(isPixelConfetti){particles.push(...pixelConfetti(p,position,clipId));return;}
|
|
922
|
-
if(isVectorConfetti){particles.push(...vectorConfetti(p,position,clipId));return;}
|
|
923
|
-
const rng=createRng(seedFromText(c.id+':'+time.toFixed(3)));
|
|
924
|
-
for(let n=0;n<p.count;n++){
|
|
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);
|
|
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'});
|
|
928
|
-
}
|
|
929
|
-
}
|
|
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');}
|
|
937
|
-
function world(c){return multiplyMatrix(c.parentId?world(object(c.parentId)):identityMatrix(),transform(c));}
|
|
938
|
-
const point=(m,x,y)=>({x:m[0]*x+m[2]*y+m[4],y:m[1]*x+m[3]*y+m[5]});
|
|
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))};}
|
|
940
|
-
function visible(c){return props(c).visible&&props(c).opacity>0&&(!c.parentId||visible(object(c.parentId)));}
|
|
941
|
-
function collisionPolygon(c,shape){const p=props(c),m=world(c),radius=Math.min(p.width,p.height)/2;let polygon=shape==='circle'?Array.from({length:32},(_,i)=>point(m,p.width/2+Math.cos(i*Math.PI/16)*radius,p.height/2+Math.sin(i*Math.PI/16)*radius)):[[0,0],[p.width,0],[p.width,p.height],[0,p.height]].map(([x,y])=>point(m,x,y));let ancestor=c.parentId?object(c.parentId):undefined;while(ancestor){const v=props(ancestor);if(ancestor.contract==='native.group.v1'&&v.clip){const cm=world(ancestor),clip=[[0,0],[v.width,0],[v.width,v.height],[0,v.height]].map(([x,y])=>point(cm,x,y));let area=0;for(let i=0;i<4;i++)area+=clip[i].x*clip[(i+1)%4].y-clip[(i+1)%4].x*clip[i].y;const sign=area>=0?1:-1;for(let i=0;i<4&&polygon.length;i++){const a=clip[i],b=clip[(i+1)%4],side=p=>sign*((b.x-a.x)*(p.y-a.y)-(b.y-a.y)*(p.x-a.x)),input=polygon;polygon=[];let previous=input[input.length-1],pd=side(previous);for(const current of input){const d=side(current);if((d>=0)!==(pd>=0)){const t=pd/(pd-d);polygon.push({x:previous.x+(current.x-previous.x)*t,y:previous.y+(current.y-previous.y)*t});}if(d>=0)polygon.push(current);previous=current;pd=d;}}}ancestor=ancestor.parentId?object(ancestor.parentId):undefined;}return polygon;}
|
|
942
|
-
function polygonsOverlap(a,b){if(a.length<3||b.length<3)return false;for(const polygon of [a,b])for(let i=0;i<polygon.length;i++){const p=polygon[i],q=polygon[(i+1)%polygon.length],nx=p.y-q.y,ny=q.x-p.x;let amin=Infinity,amax=-Infinity,bmin=Infinity,bmax=-Infinity;for(const v of a){const n=v.x*nx+v.y*ny;amin=Math.min(amin,n);amax=Math.max(amax,n);}for(const v of b){const n=v.x*nx+v.y*ny;bmin=Math.min(bmin,n);bmax=Math.max(bmax,n);}if(amax<bmin||bmax<amin)return false;}return true;}
|
|
943
|
-
function tickJoysticks(dt){
|
|
944
|
-
const stage=viewport();
|
|
945
|
-
for(const j of joysticks.values()){
|
|
946
|
-
const p=j.behavior.parameters;
|
|
947
|
-
if(!p.moveComponentId||j.magnitude<=0)continue;
|
|
948
|
-
const target=object(p.moveComponentId);if(!target||!visible(target))continue;
|
|
949
|
-
const speed=p.moveSpeed??220,phys=behaviorOn('physics-body',target.prototypeId??target.id);
|
|
950
|
-
if(phys&&phys.parameters.mode==='dynamic'){
|
|
951
|
-
const body=physicsState(target,phys);body.vx=j.nx*speed;body.vy=j.ny*speed;body.atRest=false;body.restElapsed=0;
|
|
952
|
-
}else{
|
|
953
|
-
const c=centerOf(target),tp=props(target);
|
|
954
|
-
let nx=c.x+j.nx*speed*dt,ny=c.y+j.ny*speed*dt;
|
|
955
|
-
if(!inCameraWorld(target)){nx=Math.max(tp.width/2,Math.min(stage.width-tp.width/2,nx));ny=Math.max(tp.height/2,Math.min(stage.height-tp.height/2,ny));}
|
|
956
|
-
setWorldCenter(target,nx,ny);
|
|
957
|
-
}
|
|
958
|
-
if(p.orientToMove)setComponentHeading(target,Math.atan2(j.ny,j.nx));
|
|
959
|
-
}
|
|
960
|
-
}
|
|
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();
|
|
964
|
-
for(const [id,press]of pressStates)if(!press.held&&time-(press.releasedAt??time)>=press.behavior.springBackSeconds)pressStates.delete(id);
|
|
965
|
-
if(shake){shake.elapsed+=dt;if(shake.elapsed>=shake.seconds)shake=undefined;}
|
|
966
|
-
for(const flash of screenFlashes)flash.elapsed+=dt;screenFlashes=screenFlashes.filter(flash=>flash.elapsed<flash.seconds);
|
|
967
|
-
for(const floating of floatingTexts)floating.elapsed+=dt;floatingTexts=floatingTexts.filter(floating=>floating.elapsed<floating.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);}}}}
|
|
969
|
-
tickPhysics(dt);/* 3d:start */tick3d(dt);/* 3d:end */syncPaths(dt);tickMetersAndCamera(dt);
|
|
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)});}}
|
|
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;
|
|
972
|
-
for(const a of animations){
|
|
973
|
-
a.elapsed+=dt;
|
|
974
|
-
const p=a.parameters,delay=p.delay??0,elapsed=a.elapsed-delay;
|
|
975
|
-
if(elapsed<0)continue;
|
|
976
|
-
const rawT=elapsed/p.seconds,t=p.loop?(rawT%1):Math.min(1,rawT),easing=p.easing??'ease-out';
|
|
977
|
-
let progress=t;
|
|
978
|
-
if(p.loop&&easing==='ease-in-out')progress=.5-.5*Math.cos(t*Math.PI*2);
|
|
979
|
-
else if(easing==='ease-out')progress=1-(1-t)**3;
|
|
980
|
-
else if(easing==='ease-in')progress=t**3;
|
|
981
|
-
else if(easing==='ease-in-out')progress=t<.5?4*t**3:1-(-2*t+2)**3/2;
|
|
982
|
-
else if(easing==='back-out')progress=1+2.70158*(t-1)**3+1.70158*(t-1)**2;
|
|
983
|
-
const v=p.from+(p.to-p.from)*progress,c=object(a.targetId??a.componentId);
|
|
984
|
-
if(!c)continue;
|
|
985
|
-
const o=overrides.get(c.id)??{transform:[...c.transform],parameters:{}},base=a.baseTransform??c.transform;
|
|
986
|
-
if(p.property==='opacity')o.parameters.opacity=Math.max(0,Math.min(1,v));
|
|
987
|
-
else if(['scale','scaleX','scaleY','rotation'].includes(p.property)){
|
|
988
|
-
o.animationAxes??={scale:1,scaleX:1,scaleY:1,rotation:0};
|
|
989
|
-
o.animationAxes[p.property]=v;
|
|
990
|
-
const axes=o.animationAxes,radians=axes.rotation*Math.PI/180,cos=Math.cos(radians),sin=Math.sin(radians),sx=axes.scale*axes.scaleX,sy=axes.scale*axes.scaleY;
|
|
991
|
-
o.transform[0]=(base[0]*cos+base[2]*sin)*sx;
|
|
992
|
-
o.transform[1]=(base[1]*cos+base[3]*sin)*sx;
|
|
993
|
-
o.transform[2]=(-base[0]*sin+base[2]*cos)*sy;
|
|
994
|
-
o.transform[3]=(-base[1]*sin+base[3]*cos)*sy;
|
|
995
|
-
}else o.transform[p.property==='x'?4:5]=v;
|
|
996
|
-
overrides.set(c.id,o);
|
|
997
|
-
if(p.loop&&elapsed>=p.seconds)a.elapsed=delay+(elapsed%p.seconds);
|
|
998
|
-
}
|
|
999
|
-
animations=animations.filter(a=>object(a.targetId??a.componentId)&&(a.elapsed<a.parameters.seconds+(a.parameters.delay??0)||a.parameters.loop));
|
|
1000
|
-
for(const p of particles){
|
|
1001
|
-
if(p.age!==undefined){p.age+=dt;continue;}
|
|
1002
|
-
p.life-=dt;p.x+=p.vx*dt;p.y+=p.vy*dt;p.vy+=p.gravity*dt;
|
|
1003
|
-
}
|
|
1004
|
-
particles=particles.filter(p=>p.life>(p.age??0));process();}
|
|
1005
|
-
function path(c,p){ctx.beginPath();if(c.contract==='native.ellipse.v1')ctx.ellipse(p.width/2,p.height/2,p.width/2,p.height/2,0,0,Math.PI*2);else if(c.contract==='native.path.v1'){for(const [command,...v]of p.commands)({M:()=>ctx.moveTo(...v),L:()=>ctx.lineTo(...v),C:()=>ctx.bezierCurveTo(...v),Q:()=>ctx.quadraticCurveTo(...v),Z:()=>ctx.closePath()})[command]();}else{
|
|
1006
|
-
const radius=Math.min(p.radius??0,p.width/2,p.height/2);
|
|
1007
|
-
if(typeof ctx.roundRect==='function')ctx.roundRect(0,0,p.width,p.height,radius);
|
|
1008
|
-
else{
|
|
1009
|
-
ctx.moveTo(radius,0);
|
|
1010
|
-
ctx.arcTo(p.width,0,p.width,p.height,radius);
|
|
1011
|
-
ctx.arcTo(p.width,p.height,0,p.height,radius);
|
|
1012
|
-
ctx.arcTo(0,p.height,0,0,radius);
|
|
1013
|
-
ctx.arcTo(0,0,p.width,0,radius);
|
|
1014
|
-
ctx.closePath();
|
|
1015
|
-
}
|
|
1016
|
-
}}
|
|
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;}
|
|
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}];}
|
|
1049
|
-
let maskRendered=false;
|
|
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)){
|
|
1051
|
-
const button=c.contract==='native.button.v1',isPressed=pressed===c.id;
|
|
1052
|
-
const fill=button?(!p.enabled?p.disabledFill:isPressed?p.pressedFill:hover===c.id?p.hoverFill:p.fill):p.fill;
|
|
1053
|
-
if(button&&(p.presentation==='pixel-cta'||p.presentation==='shiny-cta')){
|
|
1054
|
-
const appeared=previousCtaAppearances.get(c.id)??ambientTime;
|
|
1055
|
-
ctaAppearances.set(c.id,appeared);
|
|
1056
|
-
const age=!edit&&!reducedMotion?.matches?ambientTime-appeared:-1;
|
|
1057
|
-
if(p.presentation==='shiny-cta')drawShinyCta(ctx,p,fill,isPressed,age);
|
|
1058
|
-
else drawPixelCta(ctx,p,fill,isPressed,age);
|
|
1059
|
-
}else{
|
|
1060
|
-
if(p.pixelFrame){ctx.save();ctx.translate(3,4);path(c,p);ctx.fillStyle='#3c293366';ctx.fill();ctx.restore();}
|
|
1061
|
-
path(c,p);
|
|
1062
|
-
if(maskBehavior){ctx.save();ctx.clip();maskState(c,maskBehavior).render(ctx);ctx.restore();maskRendered=true;path(c,p);}
|
|
1063
|
-
else{ctx.fillStyle=fill;ctx.fill();}
|
|
1064
|
-
if(p.pixelFrame&&!(p.radius>0)){ctx.fillStyle='#ffffff22';ctx.fillRect(2,2,Math.max(0,p.width-4),2);ctx.fillRect(2,2,2,Math.max(0,p.height-4));}
|
|
1065
|
-
if(p.strokeWidth){ctx.strokeStyle=p.stroke;ctx.lineWidth=p.strokeWidth;ctx.stroke();}
|
|
1066
|
-
}
|
|
1067
|
-
if(matchSelected===c.id){path(c,p);ctx.strokeStyle='#ffffff';ctx.lineWidth=5;ctx.stroke();}
|
|
1068
|
-
}
|
|
1069
|
-
let textMetrics;
|
|
1070
|
-
if(c.contract==='native.text.v1'){
|
|
1071
|
-
const text=p.text.replace(/\{\{([a-z0-9_.-]+)\}\}/g,(_,id)=>String(variables[id]??''));
|
|
1072
|
-
if(p.pixelPanel){ctx.fillStyle='#3c293366';ctx.fillRect(3,4,p.width,p.height);ctx.fillStyle=p.panelFill;ctx.fillRect(0,0,p.width,p.height);ctx.strokeStyle=p.panelStroke??p.color;ctx.lineWidth=2;ctx.strokeRect(1,1,p.width-2,p.height-2);ctx.fillStyle='#ffffff22';ctx.fillRect(3,3,Math.max(0,p.width-6),2);}
|
|
1073
|
-
const pixelMetrics=p.fontFamily==='pixel'?measurePixelText(text,p):undefined;
|
|
1074
|
-
if(pixelMetrics&&!pixelMetrics.unsupportedChars.length)textMetrics=drawPixelText(ctx,text,p);
|
|
1075
|
-
else textMetrics=drawStandardText(ctx,text,pixelMetrics?{...p,fontFamily:'sans-serif',fontWeight:'700'}:p);
|
|
1076
|
-
}
|
|
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();}}
|
|
1078
|
-
if(maskBehavior&&!maskRendered)maskState(c,maskBehavior).render(ctx);
|
|
1079
|
-
/* 3d:start */
|
|
1080
|
-
if(c.contract==='native.stage3d.v1'&&stage3dMgr&&!fullBleed3dIds.has(c.id)){
|
|
1081
|
-
const sx=Math.hypot(m[0],m[1]),sy=Math.hypot(m[2],m[3]);
|
|
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});
|
|
1083
|
-
for(const [bid,body]of bodies3d)if(body.stageId===c.id&&body.mode==='dynamic'){
|
|
1084
|
-
const local=entry.project({x:body.x,y:body.y,z:body.z},p.width,p.height);
|
|
1085
|
-
projected3d.set(bid,point(m,local.x,local.y));
|
|
1086
|
-
}
|
|
1087
|
-
}
|
|
1088
|
-
/* 3d:end */
|
|
1089
|
-
paint.push({c,m,clips:nextClips,instance:instance??c.prototypeId,textMetrics});for(const child of children(c.id))drawObject(child,m,nextClips,instance??c.prototypeId);if(p.clip&&c.contract==='native.group.v1')drawConfetti(c.id);ctx.restore();}
|
|
1090
|
-
function drawConfetti(clipId,screen){
|
|
1091
|
-
if(reducedMotion?.matches)return;
|
|
1092
|
-
for(const particle of particles){
|
|
1093
|
-
if((particle.shape!=='pixel-confetti'&&particle.shape!=='confetti')||particle.clipId!==clipId||Boolean(particle.screen)!==Boolean(screen))continue;
|
|
1094
|
-
ctx.save();
|
|
1095
|
-
if(particle.shape==='confetti')drawVectorConfetti(ctx,particle,screen);
|
|
1096
|
-
else drawPixelConfetti(ctx,particle,screen);
|
|
1097
|
-
ctx.restore();
|
|
1098
|
-
}
|
|
1099
|
-
}
|
|
1100
|
-
function drawTutorialHand(x,y,mode,phase){
|
|
1101
|
-
ctx.save();ctx.translate(x,y);ctx.globalAlpha=.92;ctx.lineWidth=2;ctx.lineJoin='round';
|
|
1102
|
-
if(mode==='tap'){ctx.strokeStyle='#fff0bd';ctx.globalAlpha=.7*(1-phase);ctx.beginPath();ctx.arc(0,0,12+phase*12,0,Math.PI*2);ctx.stroke();ctx.globalAlpha=.92;}
|
|
1103
|
-
ctx.fillStyle='#fff0bd';ctx.strokeStyle='#193b46';ctx.beginPath();ctx.moveTo(-7,10);ctx.lineTo(-9,-1);ctx.quadraticCurveTo(-9,-5,-5,-5);ctx.lineTo(-3,-3);ctx.lineTo(-3,-17);ctx.quadraticCurveTo(-3,-22,1,-22);ctx.quadraticCurveTo(5,-22,5,-17);ctx.lineTo(5,-6);ctx.quadraticCurveTo(9,-9,11,-5);ctx.quadraticCurveTo(15,-7,16,-2);ctx.lineTo(14,9);ctx.quadraticCurveTo(12,18,3,18);ctx.lineTo(-1,18);ctx.quadraticCurveTo(-5,17,-7,10);ctx.closePath();ctx.fill();ctx.stroke();ctx.restore();
|
|
1104
|
-
}
|
|
1105
|
-
function drawGameFeedback(){
|
|
1106
|
-
activeTutorialHands=0;
|
|
1107
|
-
if(!edit)for(const behavior of project.gameplay.filter(item=>item.kind==='tutorial-hand')){
|
|
1108
|
-
const owner=byId.get(behavior.componentId),target=object(behavior.parameters.targetId);
|
|
1109
|
-
if(!owner||owner.sceneId!==scene||!target||target.sceneId!==scene||!visible(target))continue;
|
|
1110
|
-
if(behavior.parameters.hideOnFirstInput&&tutorialHadInput)continue;
|
|
1111
|
-
const hintClock=started?time:ambientTime;
|
|
1112
|
-
if(hintClock-tutorialInputAt<behavior.parameters.idleDelaySeconds)continue;
|
|
1113
|
-
activeTutorialHands++;
|
|
1114
|
-
const destination=behavior.parameters.destinationId?object(behavior.parameters.destinationId):undefined,p=props(target);
|
|
1115
|
-
let start;
|
|
1116
|
-
/* 3d:start */
|
|
1117
|
-
if(target.contract==='native.mesh3d.v1')start=project3dToStage(target.id);
|
|
1118
|
-
/* 3d:end */
|
|
1119
|
-
if(!start)start=point(world(target),p.width/2,p.height/2);
|
|
1120
|
-
const cycle=(hintClock%1.2)/1.2,phase=reducedMotion?.matches?0:cycle*cycle*(3-2*cycle);
|
|
1121
|
-
let x=start.x,y=start.y;
|
|
1122
|
-
if(behavior.parameters.mode!=='tap'){
|
|
1123
|
-
const end=destination?point(world(destination),props(destination).width/2,props(destination).height/2):{x:start.x-36,y:start.y+48};x=start.x+(end.x-start.x)*phase;y=start.y+(end.y-start.y)*phase;
|
|
1124
|
-
}
|
|
1125
|
-
drawTutorialHand(x+8,y+22,behavior.parameters.mode,phase);
|
|
1126
|
-
}
|
|
1127
|
-
for(const [componentId,store]of strokeStates){const config=behaviorOn('draw-stroke',componentId).parameters;for(const stroke of store.strokes){if(stroke.points.length<2)continue;ctx.save();ctx.globalAlpha=config.mode==='slice-blade'?Math.max(0,1-stroke.age/.18):1;ctx.strokeStyle=config.color;ctx.lineWidth=config.strokeWidth;ctx.lineCap='round';ctx.lineJoin='round';ctx.beginPath();ctx.moveTo(stroke.points[0].x,stroke.points[0].y);for(const point of stroke.points.slice(1))ctx.lineTo(point.x,point.y);ctx.stroke();ctx.restore();}}
|
|
1128
|
-
for(const joint of activeJoints){if(joint.broken||!joint.drawRope)continue;const body=physicsBodies.get(joint.bodyId),anchor=object(joint.anchorId);if(!body||!anchor)continue;const center=centerOf(anchor);ctx.save();ctx.strokeStyle=joint.ropeColor;ctx.lineWidth=joint.ropeWidth;ctx.beginPath();ctx.moveTo(center.x,center.y);ctx.lineTo(body.x,body.y);ctx.stroke();ctx.restore();}
|
|
1129
|
-
for(const behavior of project.gameplay.filter(b=>b.kind==='virtual-joystick'&&byId.get(b.componentId)?.sceneId===scene)){
|
|
1130
|
-
const c=object(behavior.componentId),p=behavior.parameters;if(!c||!visible(c)||p.drawControl===false)continue;
|
|
1131
|
-
const j=joysticks.get(behavior.id),origin=j&&j.pointerId!==null?j.origin:centerOf(c),kx=j&&j.pointerId!==null?j.knobX:origin.x,ky=j&&j.pointerId!==null?j.knobY:origin.y,r=p.radiusPx??56;
|
|
1132
|
-
ctx.save();ctx.fillStyle=p.baseColor??'#ffffff44';ctx.strokeStyle='#ffffffaa';ctx.lineWidth=2.5;ctx.beginPath();ctx.arc(origin.x,origin.y,r,0,Math.PI*2);ctx.fill();ctx.stroke();
|
|
1133
|
-
ctx.fillStyle=p.knobColor??'#fff0bdee';ctx.strokeStyle='#193b46aa';ctx.lineWidth=2;ctx.beginPath();ctx.arc(kx,ky,r*.42,0,Math.PI*2);ctx.fill();ctx.stroke();ctx.restore();
|
|
1134
|
-
}
|
|
1135
|
-
for(const floating of floatingTexts){
|
|
1136
|
-
const progress=Math.min(1,floating.elapsed/floating.seconds);ctx.save();ctx.globalAlpha=1-progress;ctx.fillStyle=floating.color;ctx.strokeStyle='#193b46';ctx.lineWidth=3;ctx.font='900 '+floating.fontSize+'px sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';const y=floating.y-(reducedMotion?.matches?0:floating.risePx*progress);ctx.strokeText(floating.text,floating.x,y);ctx.fillText(floating.text,floating.x,y);ctx.restore();
|
|
1137
|
-
}
|
|
1138
|
-
for(const flash of screenFlashes){const progress=Math.min(1,flash.elapsed/flash.seconds),stage=viewport();ctx.save();ctx.globalAlpha=flash.opacity*(1-progress);ctx.fillStyle=flash.color;ctx.fillRect(0,0,stage.width,stage.height);ctx.restore();}
|
|
1139
|
-
}
|
|
1140
|
-
function drawAim(){
|
|
1141
|
-
if(!aiming)return;const body=physicsBodies.get(aiming.targetId),p=aiming.behavior.parameters;if(!body)return;
|
|
1142
|
-
const dx=aiming.current.x-aiming.start.x,dy=aiming.current.y-aiming.start.y,pull=Math.hypot(dx,dy),clamped=Math.min(p.maxPullPx,pull),scale=pull>.001?clamped/pull:0;
|
|
1143
|
-
ctx.save();ctx.lineCap='round';
|
|
1144
|
-
const ringR=Math.max(12,Math.min(body.width,body.height)*.62);
|
|
1145
|
-
ctx.strokeStyle='#173a2f66';ctx.lineWidth=3.5;ctx.beginPath();ctx.arc(body.x,body.y,ringR,0,Math.PI*2);ctx.stroke();
|
|
1146
|
-
ctx.strokeStyle=p.trajectoryColor;ctx.lineWidth=2;ctx.beginPath();ctx.arc(body.x,body.y,ringR,0,Math.PI*2);ctx.stroke();
|
|
1147
|
-
if(p.showTrajectory&&pull>=p.minPullPx){const launch=aimVelocity(),{bodies,zones}=collectPhysics(),stage=viewport(),points=predictTrajectory({body:{...body,vx:launch.vx,vy:launch.vy,atRest:false},bodies,zones,bounds:{left:0,top:0,right:stage.width,bottom:stage.height},dots:p.trajectoryDots,bounces:p.trajectoryBounces});points.forEach((dot,index)=>{const alpha=.96-.52*(index/Math.max(1,points.length)),r=Math.max(2.2,4.5-index*.22);ctx.globalAlpha=alpha;ctx.fillStyle='#173a2f88';ctx.beginPath();ctx.arc(dot.x,dot.y,r+1.3,0,Math.PI*2);ctx.fill();ctx.fillStyle=p.trajectoryColor;ctx.beginPath();ctx.arc(dot.x,dot.y,r,0,Math.PI*2);ctx.fill();});}
|
|
1148
|
-
if(pull>=4){const tx=body.x+dx*scale,ty=body.y+dy*scale;ctx.globalAlpha=.9;ctx.strokeStyle='#173a2f66';ctx.lineWidth=5;ctx.beginPath();ctx.moveTo(body.x,body.y);ctx.lineTo(tx,ty);ctx.stroke();ctx.strokeStyle=p.trajectoryColor;ctx.lineWidth=2.6;ctx.beginPath();ctx.moveTo(body.x,body.y);ctx.lineTo(tx,ty);ctx.stroke();ctx.fillStyle='#173a2f88';ctx.beginPath();ctx.arc(tx,ty,5.2,0,Math.PI*2);ctx.fill();ctx.fillStyle=p.trajectoryColor;ctx.beginPath();ctx.arc(tx,ty,3.6,0,Math.PI*2);ctx.fill();}ctx.restore();
|
|
1149
|
-
}
|
|
1150
|
-
function stageBackdropColor(stage){
|
|
1151
|
-
for(const root of roots()){
|
|
1152
|
-
const list=root.contract==='native.group.v1'?children(root.id):[root];
|
|
1153
|
-
for(const c of list){
|
|
1154
|
-
if(c.contract==='native.stage3d.v1'&&visible(c)&&props(c).skyColor)return props(c).skyColor;
|
|
1155
|
-
if(c.contract!=='native.rectangle.v1'||!visible(c))continue;
|
|
1156
|
-
const p=props(c);
|
|
1157
|
-
if(p.opacity<.95||!p.fill||p.fill==='transparent')continue;
|
|
1158
|
-
if(/(?:^|\.)(background|backdrop|bg)(?:\.fill)?$/.test(c.id)||(p.width>=stage.width*.9&&p.height>=stage.height*.9))return p.fill;
|
|
1159
|
-
}
|
|
1160
|
-
}
|
|
1161
|
-
return '#102a34';
|
|
1162
|
-
}
|
|
1163
|
-
function drawDropFeedback(){
|
|
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();}
|
|
1165
|
-
if(drag?.b.parameters.bringToFront){const c=object(drag.targetId);if(c)drawObject(c,c.parentId?world(object(c.parentId)):identityMatrix(),[],c.prototypeId);}
|
|
1166
|
-
}
|
|
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});}
|
|
1168
|
-
function auditViewport(ids){
|
|
1169
|
-
const required=Array.isArray(ids)?[...new Set(ids)]:undefined;
|
|
1170
|
-
render();
|
|
1171
|
-
const stage=viewport(),boundsRect=anchorBounds(stage),found=new Set(),issues=[];
|
|
1172
|
-
for(const row of paint){
|
|
1173
|
-
const id=row.c.prototypeId??row.c.id;
|
|
1174
|
-
if(row.c.contract==='native.group.v1'||(required&&!required.includes(id)))continue;
|
|
1175
|
-
found.add(id);
|
|
1176
|
-
const bounds=geometry(row.c,row.m),stroke=(props(row.c).strokeWidth??0)/2;
|
|
1177
|
-
bounds.left-=stroke;bounds.right+=stroke;bounds.top-=stroke;bounds.bottom+=stroke;
|
|
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)};
|
|
1179
|
-
if(Object.values(overflow).some(value=>value>.01))issues.push({id,contract:row.c.contract,bounds,overflow});
|
|
1180
|
-
}
|
|
1181
|
-
const missing=required?required.filter(id=>!found.has(id)):[];
|
|
1182
|
-
return {ok:issues.length===0&&missing.length===0,viewport:{...stage,canvasWidth:canvas.clientWidth,canvasHeight:canvas.clientHeight},issues,missing};
|
|
1183
|
-
}
|
|
1184
|
-
function auditSceneLayout({ids,interactiveIds,network='standalone',minTouchPx=44}={}){
|
|
1185
|
-
const required=Array.isArray(ids)?[...new Set(ids)]:undefined;
|
|
1186
|
-
render();
|
|
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();
|
|
1188
|
-
const selected=row=>!required||required.includes(row.c.prototypeId??row.c.id);
|
|
1189
|
-
const rows=paint.filter(selected),automatic=new Set(project.events.filter(event=>event.kind==='click').map(event=>event.componentId));
|
|
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);
|
|
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);
|
|
1192
|
-
const add=(kind,severity,id,detail,metrics,otherId)=>defects.push({kind,severity,id,...(otherId?{otherId}:{}),detail,metrics});
|
|
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))};};
|
|
1194
|
-
for(const row of rows){
|
|
1195
|
-
const id=row.c.prototypeId??row.c.id;found.add(id);
|
|
1196
|
-
const bounds=geometry(row.c,row.m),stroke=(props(row.c).strokeWidth??0)/2;
|
|
1197
|
-
bounds.left-=stroke;bounds.right+=stroke;bounds.top-=stroke;bounds.bottom+=stroke;
|
|
1198
|
-
const structural=row.c.contract==='native.group.v1'&&!props(row.c).clip;
|
|
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);
|
|
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;
|
|
1201
|
-
if(!structural){
|
|
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)};
|
|
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});
|
|
1204
|
-
if(row.c.contract==='native.image.v1'&&row.clips.length===0){
|
|
1205
|
-
const bw=bounds.right-bounds.left,bh=bounds.bottom-bounds.top;
|
|
1206
|
-
const backdropRole=/(?:^|\.)(backdrop|background|bg)$/.test(id)||(props(row.c).fit==='cover'&&!row.c.parentId&&bounds.left<=1&&bounds.top<=1&&(bw>=stage.width*.4||bh>=stage.height*.4));
|
|
1207
|
-
if(backdropRole&&(bounds.left>.5||bounds.top>.5||bounds.right<stage.width-.5||bounds.bottom<stage.height-.5)){
|
|
1208
|
-
add('backdrop-incomplete','blocker',id,'Backdrop image does not cover the full active stage, leaving a visible seam.',{bounds,stage:{width:stage.width,height:stage.height}});
|
|
1209
|
-
}
|
|
1210
|
-
}
|
|
1211
|
-
for(const clip of row.clips){
|
|
1212
|
-
const boundary=clippedBounds(clip),crop={left:Math.max(0,boundary.left-bounds.left),right:Math.max(0,bounds.right-boundary.right),top:Math.max(0,boundary.top-bounds.top),bottom:Math.max(0,bounds.bottom-boundary.bottom)};
|
|
1213
|
-
if(Object.values(crop).some(value=>value>.01))add('parent-clip-crop','blocker',id,'Component is cropped by an ancestor clipping group.',{bounds,clip:boundary,crop});
|
|
1214
|
-
}
|
|
1215
|
-
}
|
|
1216
|
-
if(row.textMetrics){
|
|
1217
|
-
const metrics=row.textMetrics;
|
|
1218
|
-
if(metrics.overflowsWidth||metrics.overflowsHeight)add('text-overflow','blocker',id,'Text does not fit its component after wrapping and auto-fit.',metrics);
|
|
1219
|
-
const renderedFontSize=metrics.fontSize??metrics.scale*8;
|
|
1220
|
-
if(renderedFontSize<12)add('text-illegible',renderedFontSize<8?'blocker':'warning',id,'Rendered text is below the recommended legible size.',{renderedFontSize,...metrics});
|
|
1221
|
-
const textProps=props(row.c);
|
|
1222
|
-
if(textProps.pixelPanel&&textProps.align!=='center'){
|
|
1223
|
-
const innerWidth=Math.max(0,textProps.width-2*(textProps.padding===undefined?8:textProps.padding));
|
|
1224
|
-
if(innerWidth-(metrics.renderedWidth??0)>12)add('panel-off-center','blocker',id,'Text inside a framed pixel panel is not horizontally centered.',{align:textProps.align,innerWidth,renderedWidth:metrics.renderedWidth??0});
|
|
1225
|
-
}
|
|
1226
|
-
}
|
|
1227
|
-
if(isInteractive(row)&&!anywhereAim.has(id)&&(row.c.contract!=='native.group.v1'||bounds.right>bounds.left&&bounds.bottom>bounds.top)){
|
|
1228
|
-
const width=(bounds.right-bounds.left)*scale,height=(bounds.bottom-bounds.top)*scale;
|
|
1229
|
-
if(width<minTouchPx-.01||height<minTouchPx-.01)add('touch-target-small','blocker',id,'Interactive target is smaller than the required physical touch size.',{width,height,minTouchPx,scale});
|
|
1230
|
-
}
|
|
1231
|
-
if((isInteractive(row)&&!anywhereAim.has(id))||row.c.contract==='native.text.v1')for(const zone of safe.zones){
|
|
1232
|
-
const width=Math.min(bounds.right,zone.right)-Math.max(bounds.left,zone.left),height=Math.min(bounds.bottom,zone.bottom)-Math.max(bounds.top,zone.top);
|
|
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});
|
|
1234
|
-
}
|
|
1235
|
-
}
|
|
1236
|
-
const interactiveRows=rows.filter(row=>isInteractive(row)&&row.c.contract!=='native.group.v1'&&row.c.contract!=='native.stage3d.v1');
|
|
1237
|
-
for(let first=0;first<interactiveRows.length;first++)for(let second=first+1;second<interactiveRows.length;second++){
|
|
1238
|
-
const a=interactiveRows[first],b=interactiveRows[second],aid=a.c.prototypeId??a.c.id,bid=b.c.prototypeId??b.c.id;
|
|
1239
|
-
if(aid===bid||isDescendant(a.c,b.c.id)||isDescendant(b.c,a.c.id))continue;
|
|
1240
|
-
const A=geometry(a.c,a.m),B=geometry(b.c,b.m),width=Math.min(A.right,B.right)-Math.max(A.left,B.left),height=Math.min(A.bottom,B.bottom)-Math.max(A.top,B.top);
|
|
1241
|
-
if(width>1&&height>1)add('interactive-overlap','blocker',aid,'Interactive targets overlap.',{intersection:{width,height},first:A,second:B},bid);
|
|
1242
|
-
}
|
|
1243
|
-
const isOpaqueFill=fill=>{
|
|
1244
|
-
if(!fill||fill==='transparent')return false;
|
|
1245
|
-
const hex=/^#([0-9a-f]{4}|[0-9a-f]{8})$/i.exec(fill);
|
|
1246
|
-
if(hex)return hex[1].length===4?hex[1][3].toLowerCase()==='f':hex[1].slice(6).toLowerCase()==='ff';
|
|
1247
|
-
const rgba=/^rgba\([^,]+,[^,]+,[^,]+,\s*([0-9.]+)\s*\)$/i.exec(fill);
|
|
1248
|
-
return rgba?Number(rgba[1])>=.95:true;
|
|
1249
|
-
};
|
|
1250
|
-
const occluders=[];
|
|
1251
|
-
rows.forEach((row,rowIndex)=>{
|
|
1252
|
-
if(row.c.contract==='native.rectangle.v1'&&!isInteractive(row)&&(props(row.c).opacity??1)>=.95&&isOpaqueFill(props(row.c).fill)){
|
|
1253
|
-
occluders.push({rowIndex,row,order:row.c.order??0,bounds:geometry(row.c,row.m)});
|
|
1254
|
-
}
|
|
1255
|
-
});
|
|
1256
|
-
const visibleRows=rows.filter((row,rowIndex)=>{
|
|
1257
|
-
const b=geometry(row.c,row.m),ord=row.c.order??0;
|
|
1258
|
-
return !occluders.some(occ=>occ.rowIndex>rowIndex&&occ.order>ord&&occ.row.c.id!==row.c.id&&!isDescendant(occ.row.c,row.c.id)&&!isDescendant(row.c,occ.row.c.id)&&occ.bounds.left<=b.left+1&&occ.bounds.right>=b.right-1&&occ.bounds.top<=b.top+1&&occ.bounds.bottom>=b.bottom-1);
|
|
1259
|
-
});
|
|
1260
|
-
const panels=visibleRows.map((row,rowIndex)=>({row,rowIndex})).filter(({row})=>{
|
|
1261
|
-
if(row.c.contract!=='native.rectangle.v1')return false;
|
|
1262
|
-
const b=geometry(row.c,row.m),pw=b.right-b.left,ph=b.bottom-b.top;
|
|
1263
|
-
const fullWidthBg=(props(row.c).strokeWidth??0)===0&&b.left<=0&&b.right>=stage.width;
|
|
1264
|
-
return !fullWidthBg&&pw>=180&&ph>=140&&!isInteractive(row);
|
|
1265
|
-
}).map(({row,rowIndex})=>({id:row.c.prototypeId??row.c.id,row,rowIndex,bounds:geometry(row.c,row.m)}));
|
|
1266
|
-
const enclosingPanel=(row,rowIndex,b,requireAfter=false)=>{
|
|
1267
|
-
const id=row.c.prototypeId??row.c.id,cx=(b.left+b.right)/2,cy=(b.top+b.bottom)/2,ord=row.c.order??0;
|
|
1268
|
-
return panels.filter(p=>p.id!==id&&(!requireAfter||p.rowIndex<rowIndex||(p.row.c.order??0)===ord)&&b.right-b.left<=p.bounds.right-p.bounds.left+4&&b.bottom-b.top<=p.bounds.bottom-p.bounds.top+4&&cx>=p.bounds.left&&cx<=p.bounds.right&&cy>=p.bounds.top&&cy<=p.bounds.bottom)
|
|
1269
|
-
.sort((a,c)=>((a.bounds.right-a.bounds.left)*(a.bounds.bottom-a.bounds.top))-((c.bounds.right-c.bounds.left)*(c.bounds.bottom-c.bounds.top))||(c.rowIndex-a.rowIndex))[0];
|
|
1270
|
-
};
|
|
1271
|
-
const byPanel=new Map(),contentByPanel=new Map();
|
|
1272
|
-
if(panels.length){
|
|
1273
|
-
visibleRows.forEach((row,rowIndex)=>{
|
|
1274
|
-
const id=row.c.prototypeId??row.c.id,b=geometry(row.c,row.m),cx=(b.left+b.right)/2,cy=(b.top+b.bottom)/2;
|
|
1275
|
-
const isBtn=row.c.contract==='native.button.v1'&&!matchCells.has(row.c.id);
|
|
1276
|
-
const parent=row.c.parentId?object(row.c.parentId):undefined;
|
|
1277
|
-
const isCenteredText=row.c.contract==='native.text.v1'&&props(row.c).align==='center'&&parent?.contract!=='native.button.v1';
|
|
1278
|
-
if(isBtn||isCenteredText){
|
|
1279
|
-
const enclosing=enclosingPanel(row,rowIndex,b,false);
|
|
1280
|
-
if(enclosing){
|
|
1281
|
-
if(!byPanel.has(enclosing.id))byPanel.set(enclosing.id,{panel:enclosing,items:[]});
|
|
1282
|
-
byPanel.get(enclosing.id).items.push({id,bounds:b,cx,cy,isBtn});
|
|
1283
|
-
}
|
|
1284
|
-
}
|
|
1285
|
-
if(['native.text.v1','native.image.v1','native.button.v1'].includes(row.c.contract)&&parent?.contract!=='native.button.v1'){
|
|
1286
|
-
const enclosing=enclosingPanel(row,rowIndex,b,true);
|
|
1287
|
-
if(enclosing){
|
|
1288
|
-
if(!contentByPanel.has(enclosing.id))contentByPanel.set(enclosing.id,{panel:enclosing,content:[]});
|
|
1289
|
-
contentByPanel.get(enclosing.id).content.push({row,id,bounds:b});
|
|
1290
|
-
}
|
|
1291
|
-
}
|
|
1292
|
-
});
|
|
1293
|
-
for(const {panel,items}of byPanel.values()){
|
|
1294
|
-
if(!items.some(item=>item.isBtn))continue;
|
|
1295
|
-
const pb=panel.bounds,panelCx=(pb.left+pb.right)/2;
|
|
1296
|
-
for(const item of items){
|
|
1297
|
-
const margins={left:item.bounds.left-pb.left,right:pb.right-item.bounds.right,top:item.bounds.top-pb.top,bottom:pb.bottom-item.bounds.bottom};
|
|
1298
|
-
const minMargin=Math.min(margins.left,margins.right,margins.top,margins.bottom);
|
|
1299
|
-
if(minMargin<10||minMargin*scale<8)add('panel-edge-cramped','blocker',item.id,'Element sits too close to its enclosing panel edge.',{panelId:panel.id,margins,scale,minStagePx:10,minCssPx:8},panel.id);
|
|
1300
|
-
}
|
|
1301
|
-
const grouped=[];
|
|
1302
|
-
for(const item of items){
|
|
1303
|
-
const rowGroup=grouped.find(g=>Math.abs(g.cy-item.cy)<=16&&g.isBtn===item.isBtn);
|
|
1304
|
-
if(rowGroup)rowGroup.items.push(item);else grouped.push({cy:item.cy,isBtn:item.isBtn,items:[item]});
|
|
1305
|
-
}
|
|
1306
|
-
for(const group of grouped){
|
|
1307
|
-
const left=Math.min(...group.items.map(i=>i.bounds.left)),right=Math.max(...group.items.map(i=>i.bounds.right));
|
|
1308
|
-
const groupCx=(left+right)/2,offsetX=groupCx-panelCx;
|
|
1309
|
-
if(Math.abs(offsetX)>3)add('panel-off-center','blocker',group.items[0].id,'Element is not horizontally centered inside its enclosing panel.',{panelId:panel.id,offsetX,groupCenterX:groupCx,panelCenterX:panelCx,scale},panel.id);
|
|
1310
|
-
}
|
|
1311
|
-
}
|
|
1312
|
-
for(const {panel,content}of contentByPanel.values()){
|
|
1313
|
-
const hasUi=byPanel.has(panel.id);
|
|
1314
|
-
for(let first=0;first<content.length;first++)for(let second=first+1;second<content.length;second++){
|
|
1315
|
-
const a=content[first],b=content[second];
|
|
1316
|
-
if(a.id===b.id||isDescendant(a.row.c,b.row.c.id)||isDescendant(b.row.c,a.row.c.id))continue;
|
|
1317
|
-
const bothImages=a.row.c.contract==='native.image.v1'&&b.row.c.contract==='native.image.v1';
|
|
1318
|
-
if(bothImages&&(!hasUi||(a.row.c.parentId&&a.row.c.parentId===b.row.c.parentId)))continue;
|
|
1319
|
-
const width=Math.min(a.bounds.right,b.bounds.right)-Math.max(a.bounds.left,b.bounds.left),height=Math.min(a.bounds.bottom,b.bounds.bottom)-Math.max(a.bounds.top,b.bounds.top);
|
|
1320
|
-
if(width>2&&height>2)add('panel-content-overlap','blocker',a.id,'Panel elements overlap each other.',{panelId:panel.id,intersection:{width,height},first:a.bounds,second:b.bounds},b.id);
|
|
1321
|
-
}
|
|
1322
|
-
}
|
|
1323
|
-
}
|
|
1324
|
-
const visibleTexts=visibleRows.filter(row=>{
|
|
1325
|
-
if(row.c.contract!=='native.text.v1')return false;
|
|
1326
|
-
const parent=row.c.parentId?object(row.c.parentId):undefined;
|
|
1327
|
-
return parent?.contract!=='native.button.v1';
|
|
1328
|
-
}).map(row=>{
|
|
1329
|
-
const raw=String(props(row.c).text??'').replace(/\{\{([a-z0-9_.-]+)\}\}/g,(_,key)=>String(variables[key]??'')).trim();
|
|
1330
|
-
return {row,id:row.c.prototypeId??row.c.id,bounds:geometry(row.c,row.m),raw,norm:raw.toLowerCase().replace(/[^a-z0-9]+/g,' ').trim()};
|
|
1331
|
-
}).filter(item=>item.raw.length>0);
|
|
1332
|
-
const uiPanels=panels.filter(panel=>byPanel.get(panel.id)?.items.some(item=>item.isBtn)||contentByPanel.get(panel.id)?.content.some(item=>item.row.c.contract==='native.button.v1'));
|
|
1333
|
-
for(const panel of uiPanels){
|
|
1334
|
-
const pb=panel.bounds,panelCx=(pb.left+pb.right)/2,panelW=pb.right-pb.left;
|
|
1335
|
-
for(const t of visibleTexts){
|
|
1336
|
-
if(props(t.row.c).align!=='center')continue;
|
|
1337
|
-
if(t.bounds.bottom>pb.top+6||pb.top-t.bounds.bottom>48)continue;
|
|
1338
|
-
const tw=t.bounds.right-t.bounds.left,tcx=(t.bounds.left+t.bounds.right)/2;
|
|
1339
|
-
const overlap=Math.min(t.bounds.right,pb.right)-Math.max(t.bounds.left,pb.left);
|
|
1340
|
-
if(((tcx>=pb.left&&tcx<=pb.right)||overlap>=tw*.6)&&tw<=panelW+60&&Math.abs(tcx-panelCx)>4){
|
|
1341
|
-
add('header-off-center','blocker',t.id,'Centered text above a panel is not horizontally aligned with the panel below it.',{panelId:panel.id,offsetX:tcx-panelCx,textCenterX:tcx,panelCenterX:panelCx,scale},panel.id);
|
|
1342
|
-
}
|
|
1343
|
-
}
|
|
1344
|
-
}
|
|
1345
|
-
for(let first=0;first<visibleTexts.length;first++)for(let second=first+1;second<visibleTexts.length;second++){
|
|
1346
|
-
const a=visibleTexts[first],b=visibleTexts[second];
|
|
1347
|
-
if(a.id===b.id||isDescendant(a.row.c,b.row.c.id)||isDescendant(b.row.c,a.row.c.id))continue;
|
|
1348
|
-
const width=Math.min(a.bounds.right,b.bounds.right)-Math.max(a.bounds.left,b.bounds.left),height=Math.min(a.bounds.bottom,b.bounds.bottom)-Math.max(a.bounds.top,b.bounds.top);
|
|
1349
|
-
if(width>2&&height>2)add('panel-content-overlap','blocker',a.id,'Visible text elements overlap.',{intersection:{width,height},first:a.bounds,second:b.bounds},b.id);
|
|
1350
|
-
if(a.norm&&b.norm){
|
|
1351
|
-
const [shortText,longText]=a.norm.length<=b.norm.length?[a.norm,b.norm]:[b.norm,a.norm];
|
|
1352
|
-
if((shortText===longText&&shortText.length>=6)||(shortText.length>=12&&longText.includes(shortText))){
|
|
1353
|
-
add('duplicate-visible-copy','blocker',a.id,'Duplicate visible copy appears in multiple text elements simultaneously.',{first:a.raw,second:b.raw},b.id);
|
|
1354
|
-
}
|
|
1355
|
-
}
|
|
1356
|
-
}
|
|
1357
|
-
const copyTexts=visibleTexts.filter(item=>!/^[\d\s/.,:%+\-x]+$/i.test(item.raw));
|
|
1358
|
-
const wordCount=copyTexts.reduce((sum,item)=>sum+(item.norm?item.norm.split(' ').filter(Boolean).length:0),0);
|
|
1359
|
-
const charCount=copyTexts.reduce((sum,item)=>sum+item.raw.replace(/\s+/g,' ').length,0);
|
|
1360
|
-
if(wordCount>20||charCount>130||copyTexts.length>5){
|
|
1361
|
-
add('text-clutter-heavy','blocker',copyTexts[0]?.id??null,'Too much visible copy on one screen; keep playable ads visual and concise.',{blocks:copyTexts.length,wordCount,charCount,texts:copyTexts.map(item=>item.raw)});
|
|
1362
|
-
}else if(wordCount>12||copyTexts.length>4){
|
|
1363
|
-
add('text-clutter-heavy','warning',copyTexts[0]?.id??null,'Screen copy is getting dense; consider trimming narration so gameplay carries the experience.',{blocks:copyTexts.length,wordCount,charCount,texts:copyTexts.map(item=>item.raw)});
|
|
1364
|
-
}
|
|
1365
|
-
const missing=required?required.filter(id=>{if(found.has(id))return false;const component=object(id);if(component?.contract==='native.mesh3d.v1')return false;return !component||visible(component);}):[];
|
|
1366
|
-
return {ok:!defects.some(defect=>defect.severity==='blocker')&&missing.length===0,viewport:{...stage,canvasWidth:canvas.clientWidth,canvasHeight:canvas.clientHeight,scale},defects,missing,interactive:interactiveRows.map(row=>({id:row.c.prototypeId??row.c.id,bounds:geometry(row.c,row.m)})),safeArea:safe};
|
|
1367
|
-
}
|
|
1368
|
-
function isDescendant(c,id){while(c.parentId){if(c.parentId===id)return true;c=object(c.parentId);}return false;}
|
|
1369
|
-
function inCameraWorld(c){for(let current=c;current;current=current.parentId?object(current.parentId):undefined)if(project.gameplay.some(b=>b.kind==='camera-follow'&&b.componentId===(current.prototypeId??current.id)))return true;return false;}
|
|
1370
|
-
function locate(e){
|
|
1371
|
-
const stage=viewport(),r=canvas.getBoundingClientRect(),scale=Math.min(r.width/stage.width,r.height/stage.height);
|
|
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};
|
|
1373
|
-
}
|
|
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;}}
|
|
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));}
|
|
1376
|
-
function ancestors(c){const a=[];while(c){a.push(c);c=object(c.parentId);}return a;}
|
|
1377
|
-
function aimVelocity(){
|
|
1378
|
-
if(!aiming)return {vx:0,vy:0,power:0,pull:0};const p=aiming.behavior.parameters,dx=aiming.current.x-aiming.start.x,dy=aiming.current.y-aiming.start.y,pull=Math.hypot(dx,dy),power=Math.max(0,Math.min(1,(pull-p.minPullPx)/Math.max(1,p.maxPullPx-p.minPullPx))),speed=p.minSpeed+(p.maxSpeed-p.minSpeed)*power,direction=p.invert?-1:1;
|
|
1379
|
-
return {vx:pull?dx/pull*speed*direction:0,vy:pull?dy/pull*speed*direction:0,power,pull};
|
|
1380
|
-
}
|
|
1381
|
-
function updateAim(p){if(!aiming)return;aiming.current=p;const launch=aimVelocity();aiming.power=launch.power;if(aiming.behavior.parameters.powerVariableId)variables[aiming.behavior.parameters.powerVariableId]=launch.power;}
|
|
1382
|
-
function ensureAudio(fromGesture=false){try{const Audio=globalThis.AudioContext??globalThis.webkitAudioContext;if(Audio&&!audio){audio=new Audio();audio.addEventListener?.('statechange',()=>{if(audio?.state==='running')flushPendingMusic();});}void unlockAudio(fromGesture);}catch{/* Muted interaction remains playable when audio is unavailable. */}}
|
|
1383
|
-
function beginContinuous(e,p,chain){
|
|
1384
|
-
for(const behavior of project.gameplay.filter(item=>item.kind==='erase-mask'&&byId.get(item.componentId)?.sceneId===scene)){
|
|
1385
|
-
const c=chain.find(target=>(target.prototypeId??target.id)===behavior.componentId);if(!c)continue;const local=point(inverseMatrix(world(c)),p.x,p.y),mask=maskState(c,behavior);mask.stampSegment(local,local);continuousInput={kind:'mask',pointerId:e.pointerId,c,behavior,last:local};canvas.setPointerCapture?.(e.pointerId);return true;
|
|
1386
|
-
}
|
|
1387
|
-
if(chain.some(c=>c.contract==='native.button.v1'||project.events.some(event=>event.kind==='click'&&event.componentId===(c.prototypeId??c.id))))return false;
|
|
1388
|
-
for(const behavior of project.gameplay.filter(item=>item.kind==='draw-stroke'&&byId.get(item.componentId)?.sceneId===scene)){
|
|
1389
|
-
const c=byId.get(behavior.componentId),inverse=inverseMatrix(world(c)),local=point(inverse,p.x,p.y),padded=props(c);if(local.x<0||local.y<0||local.x>padded.width||local.y>padded.height)continue;
|
|
1390
|
-
const store=strokeState(behavior);store.begin(p);continuousInput={kind:'stroke',pointerId:e.pointerId,c,behavior,store,last:p};emit({kind:'strokeStart',componentId:c.id});canvas.setPointerCapture?.(e.pointerId);return true;
|
|
1391
|
-
}
|
|
1392
|
-
return false;
|
|
1393
|
-
}
|
|
1394
|
-
function sliceSegment(a,b,input){
|
|
1395
|
-
const active=input.store.active;if(!active)return;
|
|
1396
|
-
for(const collider of project.gameplay.filter(item=>item.kind==='collider'&&byId.get(item.componentId)?.sceneId===scene)){
|
|
1397
|
-
const source=byId.get(collider.componentId);for(const c of targetsFor(source)){if(!visible(c)||active.hitIds.has(c.id))continue;if(segmentHitsPolygon(a,b,collisionPolygon(c,collider.parameters.shape))){active.hitIds.add(c.id);emit(instanceEvent('sliceHit',c));}}
|
|
1398
|
-
}
|
|
1399
|
-
for(const joint of activeJoints){if(joint.broken||!joint.breakable||active.hitIds.has(joint.key))continue;const body=physicsBodies.get(joint.bodyId),anchor=object(joint.anchorId);if(!body||!anchor)continue;const center=centerOf(anchor);if(segmentsIntersect(a,b,{x:center.x,y:center.y},{x:body.x,y:body.y})){active.hitIds.add(joint.key);joint.broken=true;brokenJoints.add(joint.key);emit({kind:'jointBreak',behaviorId:joint.id,componentId:joint.componentId,selfInstanceId:joint.bodyId,instanceId:object(joint.bodyId)?.instanceId});}}
|
|
1400
|
-
}
|
|
1401
|
-
function addStrokePoint(point,input){
|
|
1402
|
-
const previous=input.last,config=input.behavior.parameters;if(config.inkVariableId){const id=config.inkVariableId,cost=Math.hypot(point.x-previous.x,point.y-previous.y);if((variables[id]??0)<cost)return;variables[id]-=cost;}
|
|
1403
|
-
if(!input.store.add(point))return;if(config.mode==='slice-blade')sliceSegment(previous,point,input);input.last=point;
|
|
1404
|
-
}
|
|
1405
|
-
function endContinuous(e){
|
|
1406
|
-
if(!continuousInput||continuousInput.pointerId!==e.pointerId)return;const input=continuousInput;continuousInput=undefined;
|
|
1407
|
-
try{if(canvas.hasPointerCapture?.(e.pointerId))canvas.releasePointerCapture?.(e.pointerId);}catch{/* Capture may already have been released by the host. */}
|
|
1408
|
-
if(input.kind==='stroke'){
|
|
1409
|
-
const stroke=input.store.end(),config=input.behavior.parameters;if(stroke){if(config.mode==='physics-wall'){const live=new Set(input.store.strokes.map(s=>s.id));strokeWallBodies=strokeWallBodies.filter(wall=>wall.owner!==input.c.id||live.has(wall.strokeId));strokeWallBodies.push(...strokeWalls(stroke,config.strokeWidth).map(wall=>({...wall,owner:input.c.id})));}else if(config.mode==='path-trace'){const follow=object(config.followComponentId);if(follow&&stroke.points.length>1)pathFollowers.set(follow.id,{points:stroke.points,index:1,speed:config.followSpeed});}}
|
|
1410
|
-
emit({kind:'strokeEnd',componentId:input.c.id});
|
|
1411
|
-
}
|
|
1412
|
-
}
|
|
1413
|
-
function tickCanvas(dt){
|
|
1414
|
-
for(const store of strokeStates.values())store.tick(dt);
|
|
1415
|
-
for(const [id,follower]of pathFollowers){const c=object(id);if(!c){pathFollowers.delete(id);continue;}const target=follower.points[follower.index];if(!target){pathFollowers.delete(id);emit(instanceEvent('pathArrive',c));continue;}const center=centerOf(c),dx=target.x-center.x,dy=target.y-center.y,distance=Math.hypot(dx,dy),step=follower.speed*dt;if(distance<=step){setWorldCenter(c,target.x,target.y);follower.index++;}else if(distance>.001)setWorldCenter(c,center.x+dx/distance*step,center.y+dy/distance*step);}
|
|
1416
|
-
}
|
|
1417
|
-
function beginGestureInput(e,p,chain){
|
|
1418
|
-
const holds=[],swipes=[];
|
|
1419
|
-
for(const behavior of project.gameplay.filter(b=>['swipe-input','hold-charge'].includes(b.kind)&&byId.get(b.componentId)?.sceneId===scene)){
|
|
1420
|
-
const source=byId.get(behavior.componentId),c=behavior.parameters.dragMode==='anywhere'?targetsFor(source).find(target=>visible(target)):chain.find(target=>(target.prototypeId??target.id)===source.id);
|
|
1421
|
-
if(!c)continue;
|
|
1422
|
-
if(behavior.kind==='swipe-input')swipes.push({behavior,c});
|
|
1423
|
-
else{
|
|
1424
|
-
const parameters=behavior.parameters,value=Math.max(parameters.min,Math.min(parameters.max,Number(variables[parameters.variableId])));variables[parameters.variableId]=value;
|
|
1425
|
-
holds.push({behavior,c,charge:createHoldCharge(parameters,value)});emit(instanceEvent('holdStart',c));
|
|
1426
|
-
}
|
|
1427
|
-
}
|
|
1428
|
-
if(holds.length||swipes.length)gestureInput={pointerId:e.pointerId,start:p,current:p,holds,swipes};
|
|
1429
|
-
}
|
|
1430
|
-
function endGestureInput(e,p){
|
|
1431
|
-
if(!gestureInput||gestureInput.pointerId!==e.pointerId)return;
|
|
1432
|
-
const input=gestureInput,pointerSources=new Set();gestureInput=undefined;
|
|
1433
|
-
for(const {behavior,c} of [...input.holds,...input.swipes])if(!pointerSources.has(behavior.componentId)){pointerSources.add(behavior.componentId);emit(instanceEvent('pointerUp',c,undefined,{targetId:c.id,pointerId:e.pointerId}));}
|
|
1434
|
-
for(const hold of input.holds){
|
|
1435
|
-
const parameters=hold.behavior.parameters;emit(instanceEvent('holdRelease',hold.c));
|
|
1436
|
-
if(parameters.resetOnRelease!==false){const old=variables[parameters.variableId];variables[parameters.variableId]=parameters.min;if(old!==parameters.min)emit({kind:'variableChange',variableId:parameters.variableId,selfInstanceId:hold.c.instanceId??hold.c.id,instanceId:hold.c.instanceId});}
|
|
1437
|
-
}
|
|
1438
|
-
for(const swipe of input.swipes){
|
|
1439
|
-
const direction=classifySwipe(input.start,p,swipe.behavior.parameters.minDistancePx,swipeCooldowns.get(swipe.behavior.id)??-Infinity,time*1000,swipe.behavior.parameters.cooldownMs);if(!direction)continue;
|
|
1440
|
-
swipeCooldowns.set(swipe.behavior.id,time*1000);emit(instanceEvent('swipe',swipe.c,undefined,{direction}));
|
|
1441
|
-
}
|
|
1442
|
-
return pointerSources;
|
|
1443
|
-
}
|
|
1444
|
-
function beginJoystick(e,p,chain){
|
|
1445
|
-
if(chain.some(c=>c.contract==='native.button.v1'&&props(c).enabled))return false;
|
|
1446
|
-
for(const behavior of project.gameplay.filter(b=>b.kind==='virtual-joystick'&&byId.get(b.componentId)?.sceneId===scene)){
|
|
1447
|
-
const c=byId.get(behavior.componentId);if(!visible(c))continue;
|
|
1448
|
-
let j=joysticks.get(behavior.id);if(j&&j.pointerId!==null)continue;
|
|
1449
|
-
const local=point(inverseMatrix(world(c)),p.x,p.y),cp=props(c);
|
|
1450
|
-
if(local.x<0||local.y<0||local.x>cp.width||local.y>cp.height)continue;
|
|
1451
|
-
const origin=behavior.parameters.mode==='floating'?{...p}:centerOf(c),vec=computeJoystickVector(origin,p,behavior.parameters.radiusPx,behavior.parameters.deadZone);
|
|
1452
|
-
j={behavior,c,pointerId:e.pointerId,origin,current:p,...vec};joysticks.set(behavior.id,j);writeJoystickVars(j);
|
|
1453
|
-
emit(instanceEvent('joystickStart',c));canvas.setPointerCapture?.(e.pointerId);return true;
|
|
1454
|
-
}
|
|
1455
|
-
return false;
|
|
1456
|
-
}
|
|
1457
|
-
const down=e=>{refreshOrientation();const p=locate(e),row=hit(p);lastPointer=p;if(!row&&edit)return;if(edit){if(row){selected=row.c.id;onSelect(row.c.prototypeId??row.c.id);}return;}const multiTouch=project.gameplay.some(b=>b.kind==='virtual-joystick'||b.kind==='fps-controller-3d');if(!e.isTrusted||(e.button!==undefined&&e.button!==0)||(!multiTouch&&e.isPrimary===false)||paused||closed||(!multiTouch&&((drag&&drag.pointerId!==e.pointerId)||(gestureInput&&gestureInput.pointerId!==e.pointerId)||(aiming&&aiming.pointerId!==e.pointerId)/* 3d:start */||(aiming3d&&aiming3d.pointerId!==e.pointerId)/* 3d:end */))||(bridge&&(!networkReady||!networkVisible)))return;const firstStart=!started;tutorialInputAt=time;tutorialHadInput=true;started=true;ensureAudio(true);if(firstStart&&!halted){frameEvents=frameActions=0;process();}const chain=row?ancestors(row.c):[];if(beginJoystick(e,p,chain)){frameEvents=frameActions=0;halted=false;process();render();return;}if(beginContinuous(e,p,chain)){process();render();return;}beginGestureInput(e,p,chain);
|
|
1458
|
-
/* 3d:start */
|
|
1459
|
-
const aim3d=stage3dMgr&&!chain.some(c=>c.contract==='native.button.v1')?project.gameplay.find(b=>b.kind==='aim-launch-3d'&&byId.get(b.componentId)?.sceneId===scene):undefined;
|
|
1460
|
-
if(aim3d){
|
|
1461
|
-
const source=byId.get(aim3d.componentId),phys=behaviorOn('physics-3d',source.id);
|
|
1462
|
-
const body=phys?body3dState(source,phys):undefined;
|
|
1463
|
-
const proj=project3dToStage(source.id);
|
|
1464
|
-
const nearBall=aim3d.parameters.dragMode==='anywhere'||(proj&&Math.hypot(p.x-proj.x,p.y-proj.y)<=aim3d.parameters.hitRadiusPx);
|
|
1465
|
-
if(body&&body.atRest&&!body.captured&&nearBall){
|
|
1466
|
-
aiming3d={behavior:aim3d,targetId:source.id,sourceId:source.id,stageId:aim3d.parameters.stageId,pointerId:e.pointerId,start:p,current:p,power:0};
|
|
1467
|
-
updateAim3d(p);canvas.setPointerCapture?.(e.pointerId);return;
|
|
1468
|
-
}
|
|
1469
|
-
}
|
|
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);
|
|
1474
|
-
if(fpsBeh){
|
|
1475
|
-
const stageComp=byId.get(fpsBeh.componentId),local=point(inverseMatrix(world(stageComp)),p.x,p.y),sp=props(stageComp);
|
|
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;
|
|
1487
|
-
}
|
|
1488
|
-
}
|
|
1489
|
-
}
|
|
1490
|
-
/* 3d:end */
|
|
1491
|
-
const aimBehavior=project.gameplay.find(b=>b.kind==='aim-launch'&&byId.get(b.componentId).sceneId===scene&&(b.parameters.dragMode==='anywhere'&&!chain.some(c=>c.contract==='native.button.v1')||chain.some(c=>(c.prototypeId??c.id)===b.componentId)));
|
|
1492
|
-
if(aimBehavior){
|
|
1493
|
-
const source=byId.get(aimBehavior.componentId),target=chain.find(c=>(c.prototypeId??c.id)===source.id)??targetsFor(source).find(c=>visible(c)),body=target&&physicsState(target,behaviorOn('physics-body',source.id));
|
|
1494
|
-
if(body&&(!aimBehavior.parameters.onlyWhenAtRest||body.atRest)){aiming={behavior:aimBehavior,targetId:target.id,sourceId:source.id,pointerId:e.pointerId,start:p,current:p,power:0};updateAim(p);canvas.setPointerCapture?.(e.pointerId);render();return;}
|
|
1495
|
-
}
|
|
1496
|
-
for(const c of chain){const feedback=behaviorOn('press-feedback',c.prototypeId??c.id);if(feedback&&(c.contract!=='native.button.v1'||props(c).enabled))pressStates.set(c.id,{behavior:feedback.parameters,pointerId:e.pointerId,held:true});}const matchTile=chain.find(c=>matchCells.get(c.id)?.sceneId===scene);if(matchTile){
|
|
1497
|
-
const board=matchBoards.get(matchTile.parentId);
|
|
1498
|
-
if(board?.snapshot().busy)return;
|
|
1499
|
-
selectMatchTile(matchTile);
|
|
1500
|
-
if(board&&!board.snapshot().busy){
|
|
1501
|
-
matchGesture={pointerId:e.pointerId,boardId:matchTile.parentId,tileId:matchTile.id,start:p};
|
|
1502
|
-
canvas.setPointerCapture?.(e.pointerId);
|
|
1503
|
-
}
|
|
1504
|
-
}pressed=chain.find(c=>c.contract==='native.button.v1'&&props(c).enabled)?.id;pressPointerId=pressed?e.pointerId:undefined;const b=project.gameplay.find(b=>b.kind==='drag'&&chain.some(c=>(c.prototypeId??c.id)===b.componentId));if(b){const c=chain.find(c=>(c.prototypeId??c.id)===b.componentId);const origin=centerOf(c),originZone=dropOccupancy.zoneOf(c.id);dragOrigins.set(c.id,origin);dropOccupancy.release(c.id);drag={b,targetId:c.id,start:p,current:p,origin,originZone,m:[...transform(c)],pointerId:e.pointerId};emit(instanceEvent('dragStart',c));canvas.setPointerCapture(e.pointerId);}frameEvents=frameActions=0;halted=false;for(const c of chain)if(c.contract!=='native.button.v1'||props(c).enabled)emit({kind:'click',componentId:c.prototypeId??c.id,instanceId:c.instanceId,targetId:c.id,pointerId:e.pointerId});process();render();};
|
|
1505
|
-
function swipeMatch(e,p){
|
|
1506
|
-
if(!matchGesture||matchGesture.pointerId!==e.pointerId)return false;
|
|
1507
|
-
if(!e.isTrusted||!running())return true;
|
|
1508
|
-
const gesture=matchGesture,board=matchBoards.get(gesture.boardId);
|
|
1509
|
-
if(board.snapshot().busy){matchGesture=undefined;return true;}
|
|
1510
|
-
const inverse=inverseMatrix(world(byId.get(gesture.boardId))),start=point(inverse,gesture.start.x,gesture.start.y),current=point(inverse,p.x,p.y);
|
|
1511
|
-
const dx=current.x-start.x,dy=current.y-start.y,tile=byId.get(gesture.tileId);
|
|
1512
|
-
if(Math.max(Math.abs(dx),Math.abs(dy))<Math.min(tile.parameters.width,tile.parameters.height)*.35)return true;
|
|
1513
|
-
const cell=matchCells.get(tile.id),horizontal=Math.abs(dx)>Math.abs(dy);
|
|
1514
|
-
const row=cell.row+(horizontal?0:Math.sign(dy)),column=cell.column+(horizontal?Math.sign(dx):0);
|
|
1515
|
-
const destination=[...matchCells].find(([,value])=>value.boardId===gesture.boardId&&value.row===row&&value.column===column);
|
|
1516
|
-
if(destination&&board.swap(tile.id,destination[0])){matchSelected=undefined;render();}
|
|
1517
|
-
matchGesture=undefined;
|
|
1518
|
-
return true;
|
|
1519
|
-
}
|
|
1520
|
-
const move=e=>{
|
|
1521
|
-
if(paused)return;
|
|
1522
|
-
refreshOrientation();
|
|
1523
|
-
const stage=viewport(),p=locate(e);lastPointer=p;if(gestureInput?.pointerId===e.pointerId)gestureInput.current=p;
|
|
1524
|
-
for(const j of joysticks.values())if(j.pointerId===e.pointerId){
|
|
1525
|
-
const dx=p.x-j.current.x,dy=p.y-j.current.y;
|
|
1526
|
-
/* 3d:start */
|
|
1527
|
-
if(e.isTrusted&&running())for(const fpsBeh of project.gameplay.filter(b=>b.kind==='fps-controller-3d'&&b.parameters.aimJoystickBehaviorId===j.behavior.id&&(b.parameters.aimMode??'delta')==='delta'&&byId.get(b.componentId)?.sceneId===scene))applyFpsLookDelta(fpsBeh,dx,dy);
|
|
1528
|
-
/* 3d:end */
|
|
1529
|
-
Object.assign(j,{current:p},computeJoystickVector(j.origin,p,j.behavior.parameters.radiusPx,j.behavior.parameters.deadZone));writeJoystickVars(j);render();return;
|
|
1530
|
-
}
|
|
1531
|
-
if(continuousInput?.pointerId===e.pointerId){if(continuousInput.kind==='mask'){const input=continuousInput,local=point(inverseMatrix(world(input.c)),p.x,p.y);maskState(input.c,input.behavior).stampSegment(input.last,local);input.last=local;}else addStrokePoint(p,continuousInput);process();render();return;}
|
|
1532
|
-
/* 3d:start */
|
|
1533
|
-
if(activeLook?.pointerId===e.pointerId){if(e.isTrusted&&running()){applyFpsLookDelta(activeLook.behavior,p.x-activeLook.last.x,p.y-activeLook.last.y);activeLook.last=p;render();}return;}
|
|
1534
|
-
if(aiming3d?.pointerId===e.pointerId){if(e.isTrusted&&running())updateAim3d(p);return;}
|
|
1535
|
-
/* 3d:end */
|
|
1536
|
-
if(aiming?.pointerId===e.pointerId){if(e.isTrusted&&running())updateAim(p);render();return;}
|
|
1537
|
-
const row=hit(p);
|
|
1538
|
-
hover=row?ancestors(row.c).find(c=>c.contract==='native.button.v1')?.id:undefined;
|
|
1539
|
-
if(swipeMatch(e,p))return;
|
|
1540
|
-
if(!drag||drag.pointerId!==e.pointerId)return;
|
|
1541
|
-
const c=object(drag.targetId);
|
|
1542
|
-
if(!c){cancelDrag();return;}
|
|
1543
|
-
const parent=c.parentId?world(object(c.parentId)):identityMatrix(),inverse=inverseMatrix(parent);
|
|
1544
|
-
const start=point(inverse,drag.start.x,drag.start.y),now=point(inverse,p.x,p.y);
|
|
1545
|
-
const matrix=[...drag.m],axis=drag.b.parameters.axis;
|
|
1546
|
-
if(axis!=='y'){
|
|
1547
|
-
let x=drag.m[4]+now.x-start.x;
|
|
1548
|
-
if(Number.isFinite(drag.b.parameters.minX))x=Math.max(drag.b.parameters.minX,x);
|
|
1549
|
-
if(Number.isFinite(drag.b.parameters.maxX))x=Math.min(drag.b.parameters.maxX,x);
|
|
1550
|
-
matrix[4]=x;
|
|
1551
|
-
}
|
|
1552
|
-
if(axis!=='x'){
|
|
1553
|
-
let y=drag.m[5]+now.y-start.y;
|
|
1554
|
-
if(Number.isFinite(drag.b.parameters.minY))y=Math.max(drag.b.parameters.minY,y);
|
|
1555
|
-
if(Number.isFinite(drag.b.parameters.maxY))y=Math.min(drag.b.parameters.maxY,y);
|
|
1556
|
-
matrix[5]=y;
|
|
1557
|
-
}
|
|
1558
|
-
if(!c.parentId){
|
|
1559
|
-
if(axis!=='y')matrix[4]=Math.max(0,Math.min(stage.width-c.parameters.width,matrix[4]));
|
|
1560
|
-
}else{
|
|
1561
|
-
const bounds=geometry(c,multiplyMatrix(parent,matrix));
|
|
1562
|
-
let correction=0;
|
|
1563
|
-
if(bounds.left<0||bounds.right-bounds.left>stage.width)correction=-bounds.left;
|
|
1564
|
-
else if(bounds.right>stage.width)correction=stage.width-bounds.right;
|
|
1565
|
-
const xInfluence=axis==='y'?0:parent[0],yInfluence=axis==='x'?0:parent[2];
|
|
1566
|
-
if(Math.abs(xInfluence)>=Math.abs(yInfluence)&&Math.abs(xInfluence)>1e-8)matrix[4]+=correction/xInfluence;
|
|
1567
|
-
else if(Math.abs(yInfluence)>1e-8)matrix[5]+=correction/yInfluence;
|
|
1568
|
-
}
|
|
1569
|
-
const previous=overrides.get(c.id)??{parameters:{}};
|
|
1570
|
-
overrides.set(c.id,{...previous,transform:matrix});drag.current=p;
|
|
1571
|
-
const {zones,tag}=dropZonesFor(c),resolved=resolveDropZone({itemId:c.id,tag,zones,occupancy:dropOccupancy});hoverDrop=resolved&&resolved.kind!=='reject'?resolved.zone:undefined;
|
|
1572
|
-
};
|
|
1573
|
-
|
|
1574
|
-
const up=e=>{
|
|
1575
|
-
refreshOrientation();
|
|
1576
|
-
const p=locate(e),store=pendingStore;lastPointer=p;cancelJoysticks(e.pointerId,true);/* 3d:start */cancelLook3d(e.pointerId);/* 3d:end */endContinuous(e);const gesturePointerSources=endGestureInput(e,p)??new Set();finishDrag(e);
|
|
1577
|
-
if(e.isTrusted&&running()){const released=hit(p);for(const c of released?ancestors(released.c):[])if(!gesturePointerSources.has(c.prototypeId??c.id)&&(c.contract!=='native.button.v1'||props(c).enabled))emit(instanceEvent('pointerUp',c,undefined,{targetId:c.id,pointerId:e.pointerId}));}
|
|
1578
|
-
process();render();
|
|
1579
|
-
/* 3d:start */
|
|
1580
|
-
if(aiming3d?.pointerId===e.pointerId){
|
|
1581
|
-
const gesture=aiming3d,launch=aim3dVelocity(),body=bodies3d.get(gesture.targetId);
|
|
1582
|
-
stage3dMgr?.getStage(byId.get(gesture.stageId))?.setGuide([]);
|
|
1583
|
-
aiming3d=undefined;
|
|
1584
|
-
if(gesture.behavior.parameters.powerVariableId)variables[gesture.behavior.parameters.powerVariableId]=0;
|
|
1585
|
-
const speed=Math.hypot(launch.vx,launch.vz);
|
|
1586
|
-
if(e.isTrusted)ensureAudio(true);
|
|
1587
|
-
if(body&&e.isTrusted&&running()&&launch.pull>=gesture.behavior.parameters.minPullPx&&speed>=gesture.behavior.parameters.minSpeed){
|
|
1588
|
-
body.vx=launch.vx;body.vy=0;body.vz=launch.vz;body.atRest=false;body.restElapsed=0;body.movingTime=0;body.captured=false;body.lastSafe={x:body.x,y:body.y,z:body.z};
|
|
1589
|
-
emit({kind:'launch',componentId:gesture.sourceId});
|
|
1590
|
-
}
|
|
1591
|
-
finishPointer(e);process();return;
|
|
1592
|
-
}
|
|
1593
|
-
/* 3d:end */
|
|
1594
|
-
if(aiming?.pointerId===e.pointerId){
|
|
1595
|
-
const gesture=aiming,launch=aimVelocity(),body=physicsBodies.get(gesture.targetId);aiming=undefined;
|
|
1596
|
-
if(gesture.behavior.parameters.powerVariableId)variables[gesture.behavior.parameters.powerVariableId]=0;
|
|
1597
|
-
if(body&&e.isTrusted&&running()&&launch.pull>=gesture.behavior.parameters.minPullPx){body.vx=launch.vx;body.vy=launch.vy;body.atRest=false;body.restElapsed=0;body.captured=false;body.exited=false;emit({kind:'launch',componentId:gesture.sourceId,instanceId:body.instanceId});}
|
|
1598
|
-
finishPointer(e);process();render();return;
|
|
1599
|
-
}
|
|
1600
|
-
swipeMatch(e,p);
|
|
1601
|
-
if(matchGesture?.pointerId===e.pointerId)matchGesture=undefined;
|
|
1602
|
-
finishPointer(e);
|
|
1603
|
-
if(/* review:start */review||/* review:end */store?.pointerId!==e.pointerId||!e.isTrusted||!running()||
|
|
1604
|
-
(navigator.userActivation&&navigator.userActivation.isActive!==true)||!condition(store.condition))return;
|
|
1605
|
-
const row=hit(p);
|
|
1606
|
-
if(!row||!ancestors(row.c).some(c=>c.id===store.targetId&&(c.contract!=='native.button.v1'||props(c).enabled)))return;
|
|
1607
|
-
if(bridge)bridge.openStore(project.base.storeUrl);
|
|
1608
|
-
else window.open(project.base.storeUrl,'_blank','noopener');
|
|
1609
|
-
};
|
|
1610
|
-
const cancelPointer=e=>{/* 3d:start */if(aiming3d?.pointerId===e.pointerId)cancelAim3d(e.pointerId);if(activeLook?.pointerId===e.pointerId)cancelLook3d(e.pointerId);/* 3d:end */cancelJoysticks(e.pointerId,true);if(aiming?.pointerId===e.pointerId){if(aiming.behavior.parameters.powerVariableId)variables[aiming.behavior.parameters.powerVariableId]=0;aiming=undefined;}if(matchGesture?.pointerId===e.pointerId)matchGesture=undefined;if(continuousInput?.pointerId===e.pointerId){if(continuousInput.kind==='stroke')continuousInput.store.cancel();continuousInput=undefined;}if(gestureInput?.pointerId===e.pointerId){for(const hold of gestureInput.holds)if(hold.behavior.parameters.resetOnRelease!==false)variables[hold.behavior.parameters.variableId]=hold.behavior.parameters.min;gestureInput=undefined;}finishPointer(e);};
|
|
1611
|
-
const onClickUnlock=e=>{if(e?.isTrusted&&!edit&&!paused&&!closed)ensureAudio(true);};
|
|
1612
|
-
const onResize=()=>{if(!destroyed)render();};
|
|
1613
|
-
const resizeObserver=typeof globalThis.ResizeObserver==='function'?new globalThis.ResizeObserver(onResize):undefined;
|
|
1614
|
-
try{resizeObserver?.observe?.(canvas);}catch{/* Non-Element canvas mocks in unit tests do not support ResizeObserver. */}
|
|
1615
|
-
const visibility=()=>{acc=0;last=0;if(document.hidden)cancelInput();if(audio){if(document.hidden)void audio.suspend().catch(()=>{});else if(!paused&&started)void unlockAudio();}};document.addEventListener('visibilitychange',visibility);globalThis.addEventListener?.('resize',onResize);canvas.addEventListener('pointerdown',down);canvas.addEventListener('pointermove',move);canvas.addEventListener('pointerup',up);canvas.addEventListener('pointercancel',cancelPointer);canvas.addEventListener('lostpointercapture',cancelPointer);canvas.addEventListener('click',onClickUnlock);
|
|
1616
|
-
const unsubscribeVisibility=bridge?.onVisibilityChanged(value=>{networkVisible=value;acc=0;last=0;if(!value)cancelInput();if(audio){if(!value)void audio.suspend().catch(()=>{});else if(!paused&&started)void unlockAudio();}});
|
|
1617
|
-
const unsubscribeClosed=bridge?.onClosed(()=>{closed=true;acc=0;last=0;cancelInput();stopAudio();});
|
|
1618
|
-
const unsubscribeVolume=bridge?.onVolumeChanged?.(value=>{if(typeof value==='number'&&Number.isFinite(value)&&value>=0){hostVolume=Math.min(1,value>1?value/100:value);updateAudioMix();}});
|
|
1619
|
-
/* review:start */
|
|
1620
|
-
let reviewStop,reviewTick;
|
|
1621
|
-
/* review:end */
|
|
1622
|
-
function frame(now){const liveVisual=!edit&&!paused&&!document.hidden&&networkReady&&networkVisible&&!closed;if(liveVisual&&last)ambientTime+=Math.min((now-last)/1000,5/60);if(running()){frameEvents=frameActions=0;halted=false;if(last)acc+=Math.min((now-last)/1000,5/60);for(let n=0;n<5&&acc>=1/60;n++){/* review:start */reviewTick?.();/* review:end */tick(1/60);acc-=1/60;}process();
|
|
1623
|
-
/* review:start */
|
|
1624
|
-
if(reviewStop?.()){
|
|
1625
|
-
paused=true;reviewStop=undefined;reviewTick=undefined;
|
|
1626
|
-
}
|
|
1627
|
-
/* review:end */
|
|
1628
|
-
}else acc=0;last=now;render();raf=requestAnimationFrame(frame);}reset();if(edit)scene=sceneId;render();raf=requestAnimationFrame(frame);
|
|
1629
|
-
if(bridge)void bridge.init().then(()=>{if(destroyed)return;networkReady=true;networkVisible=bridge.isVisible();acc=0;last=0;}).catch(()=>{if(destroyed)return;closed=true;cancelInput();stopAudio();});
|
|
1630
|
-
/* review:start */
|
|
1631
|
-
// Only the local editor bundle includes synthetic replay and hit testing.
|
|
1632
|
-
const reviewTools=review?{
|
|
1633
|
-
freezeReview(){
|
|
1634
|
-
paused=true;reviewStop=undefined;reviewTick=undefined;acc=0;last=0;cancelAim();cancelDrag();matchGesture=undefined;void audio?.suspend().catch(()=>{});render();
|
|
1635
|
-
},
|
|
1636
|
-
seekReview(moment,{motion=false,trustedEvent}={}){
|
|
1637
|
-
paused=true;reviewStop=undefined;reviewTick=undefined;reset();
|
|
1638
|
-
const board=matchBoards.get('harvest.board');
|
|
1639
|
-
const audition=motion&&trustedEvent instanceof globalThis.Event&&trustedEvent.isTrusted;
|
|
1640
|
-
const step=()=>{
|
|
1641
|
-
const context=audio;
|
|
1642
|
-
audio=undefined;
|
|
1643
|
-
try{frameEvents=frameActions=0;halted=false;tick(1/60);process();}finally{audio=context;}
|
|
1644
|
-
};
|
|
1645
|
-
const play=()=>{
|
|
1646
|
-
if(audition){
|
|
1647
|
-
try{
|
|
1648
|
-
const Audio=globalThis.AudioContext??globalThis.webkitAudioContext;
|
|
1649
|
-
if(Audio)audio??=new Audio();
|
|
1650
|
-
void unlockAudio();
|
|
1651
|
-
}catch{/* The review can still play when audio is unavailable. */}
|
|
1652
|
-
}
|
|
1653
|
-
acc=0;last=0;paused=false;render();
|
|
1654
|
-
};
|
|
1655
|
-
if(byId.has('salvage.ship')&&Object.hasOwn(variables,'salvage.phase')){
|
|
1656
|
-
if(!['opening','first-catch','end-card','timeout'].includes(moment))throw Error('Review moment unavailable');
|
|
1657
|
-
const ship=byId.get('salvage.ship');
|
|
1658
|
-
const align=visible=>{
|
|
1659
|
-
const core=instances.filter(instance=>instance.prototypeId.startsWith('salvage.core')).sort((a,b)=>b.transform[5]-a.transform[5])[0];
|
|
1660
|
-
const previous=overrides.get(ship.id),matrix=[...(previous?.transform??ship.transform)];
|
|
1661
|
-
matrix[4]=visible&&core?Math.max(20,Math.min(306,core.transform[4]-8)):20;
|
|
1662
|
-
overrides.set(ship.id,{...previous,transform:matrix,parameters:{...previous?.parameters,visible}});
|
|
1663
|
-
};
|
|
1664
|
-
let salvageCtaAt,caughtAt;
|
|
1665
|
-
const salvageCtaSettled=()=>{
|
|
1666
|
-
if(variables['salvage.phase']!=='cta')return false;
|
|
1667
|
-
salvageCtaAt??=time;return time-salvageCtaAt>=.65;
|
|
1668
|
-
};
|
|
1669
|
-
if(moment==='opening'){
|
|
1670
|
-
if(motion){reviewStop=()=>time>=4;play();return;}
|
|
1671
|
-
render();return;
|
|
1672
|
-
}
|
|
1673
|
-
if(moment==='timeout'){
|
|
1674
|
-
const deadline=project.gameplay.find(behavior=>behavior.id==='salvage.deadline')?.parameters.seconds;
|
|
1675
|
-
if(!Number.isFinite(deadline))throw Error('Timeout replay unavailable');
|
|
1676
|
-
align(false);
|
|
1677
|
-
if(motion){
|
|
1678
|
-
while(time<deadline-.25&&variables['salvage.phase']!=='cta'){align(false);step();}
|
|
1679
|
-
if(variables['salvage.phase']==='cta')throw Error('Timeout replay unavailable');
|
|
1680
|
-
reviewTick=()=>{if(variables['salvage.phase']!=='cta')align(false);};
|
|
1681
|
-
reviewStop=()=>salvageCtaSettled()||time>=deadline+1;play();return;
|
|
1682
|
-
}
|
|
1683
|
-
for(let n=0;variables['salvage.phase']!=='cta'&&n<3600;n++){align(false);step();}
|
|
1684
|
-
if(variables['salvage.phase']!=='cta')throw Error('Timeout card unavailable');
|
|
1685
|
-
render();return;
|
|
1686
|
-
}
|
|
1687
|
-
const target=moment==='first-catch'?1:3;
|
|
1688
|
-
if(motion){
|
|
1689
|
-
for(let n=0;variables['salvage.catches']<target-1&&n<3600;n++){align(true);step();}
|
|
1690
|
-
if(variables['salvage.catches']!==target-1)throw Error('Review replay unavailable');
|
|
1691
|
-
reviewTick=()=>{if(variables['salvage.catches']<target)align(true);};
|
|
1692
|
-
reviewStop=()=>{
|
|
1693
|
-
if(target===1&&variables['salvage.catches']>=1){caughtAt??=time;return time-caughtAt>=1;}
|
|
1694
|
-
return target===3&&salvageCtaSettled()||time>=20;
|
|
1695
|
-
};
|
|
1696
|
-
play();return;
|
|
1697
|
-
}
|
|
1698
|
-
for(let n=0;variables['salvage.catches']<target&&n<3600;n++){align(true);step();}
|
|
1699
|
-
if(variables['salvage.catches']!==target)throw Error('Review catch unavailable');
|
|
1700
|
-
if(target===1)for(let n=0;n<84;n++)step();
|
|
1701
|
-
else{
|
|
1702
|
-
for(let n=0;variables['salvage.phase']!=='cta'&&n<300;n++)step();
|
|
1703
|
-
if(variables['salvage.phase']!=='cta')throw Error('End card unavailable');
|
|
1704
|
-
}
|
|
1705
|
-
render();return;
|
|
1706
|
-
}
|
|
1707
|
-
if(!board){
|
|
1708
|
-
if(!['opening','first-input','end-card','timeout'].includes(moment))throw Error('Review moment unavailable');
|
|
1709
|
-
if(moment==='opening'){if(motion){reviewStop=()=>time>=4;play();}else render();return;}
|
|
1710
|
-
const aim=project.gameplay.find(behavior=>behavior.kind==='aim-launch'&&byId.get(behavior.componentId).sceneId===scene);
|
|
1711
|
-
/* 3d:start */
|
|
1712
|
-
const aim3dReview=project.gameplay.find(behavior=>behavior.kind==='aim-launch-3d'&&byId.get(behavior.componentId).sceneId===scene);
|
|
1713
|
-
/* 3d:end */
|
|
1714
|
-
const primary=project.events.find(event=>event.kind==='click'&&byId.get(event.componentId)?.sceneId===scene&&project.eventBindings.some(binding=>binding.eventId===event.id));
|
|
1715
|
-
const firstInput=()=>{
|
|
1716
|
-
/* 3d:start */
|
|
1717
|
-
if(aim3dReview){
|
|
1718
|
-
const source=byId.get(aim3dReview.componentId),phys=behaviorOn('physics-3d',source.id),body=body3dState(source,phys),zone=project.gameplay.find(b=>b.kind==='capture-zone-3d'&&byId.get(b.componentId).sceneId===scene);
|
|
1719
|
-
let vx=0,vz=-aim3dReview.parameters.maxSpeed*.45;
|
|
1720
|
-
if(zone){const zc=byId.get(zone.componentId),zp=props(zc),dx=(zp.x??0)-body.x,dz=(zp.z??0)-body.z,len=Math.hypot(dx,dz)||1;vx=dx/len*aim3dReview.parameters.maxSpeed*.55;vz=dz/len*aim3dReview.parameters.maxSpeed*.55;}
|
|
1721
|
-
body.vx=vx;body.vy=0;body.vz=vz;body.atRest=false;body.restElapsed=0;body.movingTime=0;body.lastSafe={x:body.x,y:body.y,z:body.z};emit({kind:'launch',componentId:source.id});
|
|
1722
|
-
process();return;
|
|
1723
|
-
}
|
|
1724
|
-
/* 3d:end */
|
|
1725
|
-
if(aim){
|
|
1726
|
-
const source=byId.get(aim.componentId),target=targetsFor(source)[0],body=physicsState(target,behaviorOn('physics-body',source.id)),zone=project.gameplay.find(b=>b.kind==='capture-zone'&&byId.get(b.componentId).sceneId===scene);
|
|
1727
|
-
let vx=aim.parameters.maxSpeed*.45,vy=0;
|
|
1728
|
-
if(zone){const zc=byId.get(zone.componentId),center=point(world(zc),props(zc).width/2,props(zc).height/2),dx=center.x-body.x,dy=center.y-body.y,length=Math.hypot(dx,dy)||1;vx=dx/length*aim.parameters.maxSpeed*.45;vy=dy/length*aim.parameters.maxSpeed*.45;}
|
|
1729
|
-
body.vx=vx;body.vy=vy;body.atRest=false;body.restElapsed=0;emit({kind:'launch',componentId:source.id,instanceId:target.instanceId});
|
|
1730
|
-
}else if(primary)emit({kind:'click',componentId:primary.componentId,targetId:primary.componentId});
|
|
1731
|
-
else throw Error('Review primary input unavailable');
|
|
1732
|
-
process();
|
|
1733
|
-
};
|
|
1734
|
-
if(moment==='first-input'){firstInput();if(motion){reviewStop=()=>time>=2;play();}else{for(let n=0;n<60;n++)step();render();}return;}
|
|
1735
|
-
if(moment==='end-card')firstInput();
|
|
1736
|
-
const deadline=moment==='timeout'?Math.min(60,Math.max(1,project.gameplay.find(b=>b.kind==='timer')?.parameters.seconds??10)):60;
|
|
1737
|
-
const endScene=()=>project.scenes.find(item=>item.id===scene)?.role==='end-card';
|
|
1738
|
-
const preferredEnd=()=>moment==='timeout'
|
|
1739
|
-
?(project.scenes.find(item=>item.role==='end-card'&&/fail|loss|timeout/i.test(item.id))??project.scenes.find(item=>item.role==='end-card'))
|
|
1740
|
-
:(project.scenes.find(item=>item.role==='end-card'&&!/fail|loss|timeout/i.test(item.id))??project.scenes.find(item=>item.role==='end-card'));
|
|
1741
|
-
if(motion){
|
|
1742
|
-
reviewStop=()=>endScene()&&time>=1||time>=deadline+1;play();return;
|
|
1743
|
-
}
|
|
1744
|
-
for(let n=0;n<deadline*60&&!endScene();n++)step();
|
|
1745
|
-
if(!endScene()||(moment==='timeout'&&!/fail|loss|timeout/i.test(scene))||(moment==='end-card'&&/fail|loss|timeout/i.test(scene))){
|
|
1746
|
-
const fallback=preferredEnd();if(!fallback)throw Error('End card unavailable');scene=fallback.id;aiming=undefined;cancelInput();emit({kind:'sceneEnter',sceneId:scene});process();
|
|
1747
|
-
}
|
|
1748
|
-
for(let n=0;n<45;n++)step();render();return;
|
|
1749
|
-
}
|
|
1750
|
-
let ctaAt;
|
|
1751
|
-
const ctaRevealSettled=()=>{
|
|
1752
|
-
if(variables['harvest.phase']!=='cta')return false;
|
|
1753
|
-
ctaAt??=time;
|
|
1754
|
-
return time-ctaAt>=.65;
|
|
1755
|
-
};
|
|
1756
|
-
if(moment==='opening'&&motion){
|
|
1757
|
-
reviewStop=()=>time>=7;
|
|
1758
|
-
acc=0;last=0;paused=false;
|
|
1759
|
-
}
|
|
1760
|
-
if(moment==='timeout'){
|
|
1761
|
-
if(!board)throw Error('Review moment unavailable');
|
|
1762
|
-
if(motion){
|
|
1763
|
-
const deadline=project.gameplay.find(behavior=>behavior.id==='harvest.deadline')?.parameters.seconds;
|
|
1764
|
-
if(!Number.isFinite(deadline))throw Error('Timeout replay unavailable');
|
|
1765
|
-
while(time<deadline-.25&&variables['harvest.phase']!=='cta')step();
|
|
1766
|
-
if(variables['harvest.phase']==='cta')throw Error('Timeout replay unavailable');
|
|
1767
|
-
reviewStop=()=>ctaRevealSettled()||time>=deadline+1;
|
|
1768
|
-
play();return;
|
|
1769
|
-
}
|
|
1770
|
-
for(let n=0;variables['harvest.phase']!=='cta'&&n<3600;n++)step();
|
|
1771
|
-
if(variables['harvest.phase']!=='cta')throw Error('Timeout card unavailable');
|
|
1772
|
-
}else if(moment!=='opening'){
|
|
1773
|
-
if(!board||!['first-harvest','end-card'].includes(moment))throw Error('Review moment unavailable');
|
|
1774
|
-
const count=moment==='first-harvest'?1:3;
|
|
1775
|
-
for(let match=0;match<count;match++){
|
|
1776
|
-
const move=board.snapshot().legalMoves[0];
|
|
1777
|
-
if(!move||!board.swap(move.from,move.to))throw Error('Review move unavailable');
|
|
1778
|
-
if(motion&&match===count-1){
|
|
1779
|
-
const until=time+(count===1?3:8);
|
|
1780
|
-
reviewStop=()=>time>=until||(count===3&&ctaRevealSettled());
|
|
1781
|
-
play();return;
|
|
1782
|
-
}
|
|
1783
|
-
for(let frames=0;board.snapshot().busy&&frames<240;frames++)step();
|
|
1784
|
-
if(board.snapshot().busy)throw Error('Review replay did not settle');
|
|
1785
|
-
}
|
|
1786
|
-
if(count===1){for(let n=0;n<84;n++)step();}
|
|
1787
|
-
else{
|
|
1788
|
-
for(let n=0;variables['harvest.phase']!=='cta'&&n<300;n++)step();
|
|
1789
|
-
if(variables['harvest.phase']!=='cta')throw Error('End card unavailable');
|
|
1790
|
-
}
|
|
1791
|
-
}
|
|
1792
|
-
render();
|
|
1793
|
-
},
|
|
1794
|
-
pickReview(clientX,clientY){
|
|
1795
|
-
const row=hit(locate({clientX,clientY}));
|
|
1796
|
-
return row?ancestors(row.c).map(c=>c.prototypeId??c.id):[];
|
|
1797
|
-
},
|
|
1798
|
-
reviewBounds(ids){
|
|
1799
|
-
const stage=viewport(),w=canvas.clientWidth,h=canvas.clientHeight;
|
|
1800
|
-
const scale=Math.min(w/stage.width,h/stage.height);
|
|
1801
|
-
return paint.filter(row=>ids.includes(row.c.id)).map(row=>{
|
|
1802
|
-
const b=geometry(row.c,row.m);
|
|
1803
|
-
return {left:(w-stage.width*scale)/2+b.left*scale,top:(h-stage.height*scale)/2+b.top*scale,width:(b.right-b.left)*scale,height:(b.bottom-b.top)*scale};
|
|
1804
|
-
});
|
|
1805
|
-
},
|
|
1806
|
-
}:undefined;
|
|
1807
|
-
/* review:end */
|
|
1808
|
-
return {/* review:start */...reviewTools,/* review:end */state,auditViewport,auditSceneLayout,restart:()=>{/* review:start */reviewStop=undefined;reviewTick=undefined;/* review:end */bridge?.notifyGameRetry?.();reset();render();},select:id=>{selected=id;},inspectScene:id=>{if(edit&&project.scenes.some(s=>s.id===id)){scene=id;selected=undefined;}},pause:value=>{paused=value;acc=0;last=0;if(value)cancelInput();if(audio){if(value)void audio.suspend().catch(()=>{});else if(started)void unlockAudio();}},destroy:()=>{destroyed=true;cancelAnimationFrame(raf);cancelInput();stopAudio();/* 3d:start */stage3dMgr?.dispose();/* 3d:end */unsubscribeVisibility?.();unsubscribeClosed?.();unsubscribeVolume?.();bridge?.destroy();resizeObserver?.disconnect?.();document.removeEventListener('visibilitychange',visibility);globalThis.removeEventListener?.('resize',onResize);canvas.removeEventListener('pointerdown',down);canvas.removeEventListener('pointermove',move);canvas.removeEventListener('pointerup',up);canvas.removeEventListener('pointercancel',cancelPointer);canvas.removeEventListener('lostpointercapture',cancelPointer);canvas.removeEventListener('click',onClickUnlock);void audio?.close().catch(()=>{});}};
|
|
1809
|
-
}
|