@zylem/game-lib 0.8.3 → 0.8.4
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/dist/actions.d.ts +5 -5
- package/dist/api/game-lib.api.json +454 -195
- package/dist/api/game-lib.api.md +28 -12
- package/dist/api/game-lib.d.ts +66 -3
- package/dist/api/game-lib.typedoc.json +29076 -28454
- package/dist/bridge.d.ts +18 -4
- package/dist/bridge.js +1 -1
- package/dist/{chunk-WVSYUWTT.js → chunk-4CHZUWLF.js} +1 -1
- package/dist/{chunk-Q27ULMXY.js → chunk-6B5JP7T5.js} +2 -2
- package/dist/chunk-D3JO4HW2.js +1 -0
- package/dist/{chunk-CV75NSES.js → chunk-OAWK2UUY.js} +1 -1
- package/dist/chunk-PNLNC3FA.js +1 -0
- package/dist/chunk-VIPINV7V.js +19 -0
- package/dist/{chunk-YAOXFYOD.js → chunk-WBQ5TNRZ.js} +1 -1
- package/dist/{collision-builder-B_tm8OVy.d.ts → collision-builder-4TVDzXsp.d.ts} +1 -1
- package/dist/core.d.ts +11 -11
- package/dist/core.js +1 -1
- package/dist/{debug-state-Dp9CQQZ4.d.ts → debug-state-s0s-qndj.d.ts} +1 -1
- package/dist/debug.d.ts +11 -5
- package/dist/debug.js +1 -1
- package/dist/{entity-BGEq1yfC.d.ts → entity-BI7cSlK8.d.ts} +3 -3
- package/dist/{entity-B9yZeBm4.d.ts → entity-DDks47JB.d.ts} +1 -1
- package/dist/{entity-type-map-CW6RHQkx.d.ts → entity-type-map-COHu4fkW.d.ts} +41 -7
- package/dist/entity.d.ts +7 -7
- package/dist/entity.js +1 -1
- package/dist/{game-NHkubIfI.d.ts → game-4fsy55uN.d.ts} +6 -6
- package/dist/{game-default-5TB3T5N7.js → game-default-4PPYYGAR.js} +1 -1
- package/dist/graphics.d.ts +5 -5
- package/dist/{material-DbSuZBbP.d.ts → material-BKPYeBC6.d.ts} +1 -1
- package/dist/public.d.ts +9 -9
- package/dist/public.js +1 -1
- package/dist/runtime.d.ts +3 -3
- package/dist/runtime.js +1 -1
- package/dist/{vector-DN6zlPoE.d.ts → vector-DPbwlzgG.d.ts} +10 -2
- package/dist/web-components.d.ts +9 -9
- package/dist/{zylem-camera-Du2UPW9O.d.ts → zylem-camera-B73ZNcgs.d.ts} +1 -1
- package/package.json +16 -15
- package/LICENSE +0 -21
- package/dist/chunk-2VSVOPQN.js +0 -19
- package/dist/chunk-GKHAJ3MW.js +0 -1
- package/dist/chunk-LGS5N5M4.js +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zylem/game-lib",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.4",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "A powerful and easy-to-use framework for creating simple 3D digital interactive applications using TypeScript.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -101,11 +101,24 @@
|
|
|
101
101
|
"files": [
|
|
102
102
|
"dist"
|
|
103
103
|
],
|
|
104
|
+
"scripts": {
|
|
105
|
+
"build": "tsup && pnpm api:extract && pnpm api:typedoc && pnpm schema:emit",
|
|
106
|
+
"dev": "tsup --watch",
|
|
107
|
+
"api:extract": "mkdir -p dist/api temp && api-extractor run --local --verbose",
|
|
108
|
+
"api:typedoc": "mkdir -p dist/api && typedoc --options typedoc.json",
|
|
109
|
+
"schema:emit": "node --experimental-strip-types ./scripts/emit-json-schemas.ts",
|
|
110
|
+
"prepublishOnly": "NODE_ENV=production pnpm build",
|
|
111
|
+
"lint": "biome check .",
|
|
112
|
+
"typecheck": "tsgo --noEmit",
|
|
113
|
+
"test": "vitest --reporter=verbose",
|
|
114
|
+
"coverage": "vitest run --coverage"
|
|
115
|
+
},
|
|
104
116
|
"dependencies": {
|
|
105
117
|
"@dgreenheck/three-pinata": "^2.0.1",
|
|
106
118
|
"@sinclair/typebox": "^0.34.41",
|
|
107
119
|
"@types/howler": "^2.2.12",
|
|
108
120
|
"@zylem/behaviors": "^0.5.8",
|
|
121
|
+
"@zylem/bridge": "workspace:*",
|
|
109
122
|
"comlink": "^4.4.2",
|
|
110
123
|
"howler": "^2.2.4",
|
|
111
124
|
"idb-keyval": "^6.2.2",
|
|
@@ -114,8 +127,7 @@
|
|
|
114
127
|
"stats.js": "^0.17.0",
|
|
115
128
|
"three": "^0.185.0",
|
|
116
129
|
"typescript-fsm": "^1.6.0",
|
|
117
|
-
"valtio": "^2.1.7"
|
|
118
|
-
"@zylem/bridge": "0.1.1"
|
|
130
|
+
"valtio": "^2.1.7"
|
|
119
131
|
},
|
|
120
132
|
"peerDependencies": {
|
|
121
133
|
"howler": "^2.2.4",
|
|
@@ -137,16 +149,5 @@
|
|
|
137
149
|
"typescript": "6.0.3",
|
|
138
150
|
"vite-plugin-solid": "^2.11.8",
|
|
139
151
|
"vitest": "^4.0.9"
|
|
140
|
-
},
|
|
141
|
-
"scripts": {
|
|
142
|
-
"build": "tsup && pnpm api:extract && pnpm api:typedoc && pnpm schema:emit",
|
|
143
|
-
"dev": "tsup --watch",
|
|
144
|
-
"api:extract": "mkdir -p dist/api temp && api-extractor run --local --verbose",
|
|
145
|
-
"api:typedoc": "mkdir -p dist/api && typedoc --options typedoc.json",
|
|
146
|
-
"schema:emit": "node --experimental-strip-types ./scripts/emit-json-schemas.ts",
|
|
147
|
-
"lint": "biome check .",
|
|
148
|
-
"typecheck": "tsgo --noEmit",
|
|
149
|
-
"test": "vitest --reporter=verbose",
|
|
150
|
-
"coverage": "vitest run --coverage"
|
|
151
152
|
}
|
|
152
|
-
}
|
|
153
|
+
}
|
package/LICENSE
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2023 Timothy Cool
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
package/dist/chunk-2VSVOPQN.js
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import{a as y}from"./chunk-C5NEGC3S.js";import{AmbientLight as R,Object3D as U,PerspectiveCamera as T,RenderTarget as O,Scene as C,Color as P,LinearFilter as w,SpotLight as W,Vector3 as E}from"three";function d(a,e,t,n={}){let s=e*4,i=new Uint8ClampedArray(t*s),r=null;if(n.srgb){r=new Uint8Array(256);for(let o=0;o<256;o+=1){let c=o/255,u=c<=.0031308?c*12.92:1.055*Math.pow(c,1/2.4)-.055;r[o]=Math.round(Math.max(0,Math.min(1,u))*255)}}for(let o=0;o<t;o+=1){let c=(n.flipY?t-1-o:o)*s,u=o*s;if(r===null){i.set(a.subarray(c,c+s),u);continue}for(let l=0;l<s;l+=4)i[u+l]=r[a[c+l]],i[u+l+1]=r[a[c+l+1]],i[u+l+2]=r[a[c+l+2]],i[u+l+3]=a[c+l+3]}return i}var x=`
|
|
2
|
-
const encodeReadbackPixels = ${d.toString()};
|
|
3
|
-
|
|
4
|
-
self.onmessage = async (event) => {
|
|
5
|
-
const { id, buffer, width, height, options } = event.data;
|
|
6
|
-
try {
|
|
7
|
-
const src = new Uint8ClampedArray(buffer);
|
|
8
|
-
const pixels = encodeReadbackPixels(src, width, height, options);
|
|
9
|
-
const canvas = new OffscreenCanvas(width, height);
|
|
10
|
-
const ctx = canvas.getContext('2d');
|
|
11
|
-
if (!ctx) throw new Error('OffscreenCanvas 2d context unavailable');
|
|
12
|
-
ctx.putImageData(new ImageData(pixels, width, height), 0, 0);
|
|
13
|
-
const blob = await canvas.convertToBlob({ type: 'image/png' });
|
|
14
|
-
self.postMessage({ id, blob });
|
|
15
|
-
} catch (error) {
|
|
16
|
-
self.postMessage({ id, error: String(error) });
|
|
17
|
-
}
|
|
18
|
-
};
|
|
19
|
-
`,h=class{worker=null;workerFailed=!1;nextId=1;pending=new Map;isSupported(){return!this.workerFailed&&typeof Worker<"u"&&typeof OffscreenCanvas<"u"&&typeof URL<"u"&&typeof Blob<"u"}async encodeThumbnail(e,t,n,s={}){if(!this.isSupported())return null;let i=this.ensureWorker();if(!i)return null;let r=new Uint8Array(e.byteLength);r.set(e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength));let o=this.nextId++;try{let c=await new Promise((u,l)=>{this.pending.set(o,{resolve:u,reject:l}),i.postMessage({id:o,buffer:r.buffer,width:t,height:n,options:s},[r.buffer])});return URL.createObjectURL(c)}catch{return null}}dispose(){this.worker&&(this.worker.terminate(),this.worker=null);for(let{reject:e}of this.pending.values())e(new Error("EntityPayloadWorker disposed"));this.pending.clear()}ensureWorker(){if(this.worker)return this.worker;try{let e=new Blob([x],{type:"text/javascript"}),t=URL.createObjectURL(e),n=new Worker(t,{type:"module"});return URL.revokeObjectURL(t),n.onmessage=s=>{let{id:i}=s.data,r=this.pending.get(i);r&&(this.pending.delete(i),"blob"in s.data?r.resolve(s.data.blob):r.reject(new Error(s.data.error)))},n.onerror=()=>{this.workerFailed=!0,this.dispose()},this.worker=n,n}catch{return this.workerFailed=!0,null}}},v=new h;var S=128,L=256,M=1,k=32,p=class{cache=new Map;inFlight=new Map;renderer=null;size;maxEntries;queue=[];activeRenders=0;constructor(e=S,t=L){this.size=e,this.maxEntries=t}setRenderer(e){this.renderer=e}get(e){let t=this.cache.get(e);return t?(this.touch(e,t),t):null}invalidate(e){let t=this.cache.get(e);t&&f(t.dataUrl),this.cache.delete(e),this.inFlight.delete(e),this.queue=this.queue.filter(n=>n.uuid!==e?!0:(n.resolve(null),!1))}clear(){this.cache.forEach(e=>f(e.dataUrl)),this.cache.clear(),this.inFlight.clear();for(let e of this.queue)e.resolve(null);this.queue=[]}get cacheSize(){return this.cache.size}get pendingCount(){return this.queue.length}async ensure(e,t){let n=this.cache.get(e);if(n)return this.touch(e,n),n;let s=this.inFlight.get(e);if(s)return s;if(!t||!this.renderer)return null;let i=new Promise(r=>{if(this.queue.push({uuid:e,object:t,resolve:r}),this.queue.length>k){let o=this.queue.splice(0,this.queue.length-k);for(let c of o)this.inFlight.delete(c.uuid),c.resolve(null)}this.drainQueue()});return this.inFlight.set(e,i),i}drainQueue(){for(;this.activeRenders<M&&this.queue.length>0;){let e=this.queue.shift();if(!e)return;this.activeRenders+=1,this.render(e.uuid,e.object).then(t=>{t&&(this.cache.set(e.uuid,t),this.evictOverflow()),e.resolve(t)}).catch(t=>{console.warn("EntityThumbnailCache: failed to render thumbnail",e.uuid,t),e.resolve(null)}).finally(()=>{this.activeRenders-=1,this.inFlight.delete(e.uuid),this.drainQueue()})}}touch(e,t){this.cache.delete(e),this.cache.set(e,t)}evictOverflow(){for(;this.cache.size>this.maxEntries;){let e=this.cache.keys().next();if(e.done)return;let t=this.cache.get(e.value);t&&f(t.dataUrl),this.cache.delete(e.value)}}async render(e,t){let n=this.renderer;if(!n)return null;let s=new C;s.background=new P(3815994);let i=t.clone(!0);i.position.set(0,0,0),i.rotation.set(0,0,0),i.updateMatrixWorld(!0),s.add(i);let r=new T(50,1,.1,100),o=y(i,r);F(s,r,o);let c=new O(this.size,this.size,{minFilter:w,magFilter:w}),u=n.getRenderTarget(),l=n.getScissorTest();try{n.setScissorTest(!1),n.setRenderTarget(c),n.render(s,r)}finally{n.setRenderTarget(u),n.setScissorTest(l)}let b=await n.readRenderTargetPixelsAsync(c,0,0,this.size,this.size);c.dispose(),s.remove(i);let m={flipY:A(n),srgb:!0},g=await v.encodeThumbnail(b,this.size,this.size,m)??D(b,this.size,this.size,m);return g?{uuid:e,dataUrl:g,bounds:{width:o.width,height:o.height,depth:o.depth}}:null}},N=new p;function f(a){a.startsWith("blob:")&&typeof URL<"u"&&URL.revokeObjectURL(a)}function A(a){return a?.backend?.isWebGLBackend===!0}function F(a,e,t){a.add(new R(16777215,.7)),e.updateMatrixWorld(!0);let n=new E().setFromMatrixColumn(e.matrixWorld,0),s=new E().setFromMatrixColumn(e.matrixWorld,1),i=e.position.distanceTo(t.center)||1,r=new W(16777215,5);r.position.copy(e.position).addScaledVector(n,i*.35).addScaledVector(s,i*.45),r.decay=0,r.distance=0,r.penumbra=.5,r.angle=j(Math.atan(t.maxDim/i)+.25,.4,Math.PI/3),r.castShadow=!1;let o=new U;o.position.copy(t.center),a.add(o),r.target=o,a.add(r)}function j(a,e,t){return Math.min(t,Math.max(e,a))}function D(a,e,t,n={}){if(typeof document>"u")return null;let s=document.createElement("canvas");s.width=e,s.height=t;let i=s.getContext("2d");if(!i)return null;let r=a instanceof Uint8Array?a:new Uint8Array(a.buffer,a.byteOffset,a.byteLength),o=i.createImageData(e,t);return o.data.set(d(r,e,t,n)),i.putImageData(o,0,0),s.toDataURL("image/png")}export{p as a,N as b};
|
package/dist/chunk-GKHAJ3MW.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as c}from"./chunk-LKFF6XJC.js";import{a as n,e as l,g as r,i as h}from"./chunk-W5SXED5T.js";import{subscribe as p}from"valtio/vanilla";import{announceBridgeReady as m,getZylemBridge as b}from"@zylem/bridge";function g(i){return(i?.group??i?.mesh)?.scale}function w(i){let e=i?.scale??g(i)??{};return{x:e.x??1,y:e.y??1,z:e.z??1}}function v(i,e){if(typeof i?.setScale=="function"){i.setScale(e.x,e.y,e.z);return}g(i)?.set?.(e.x,e.y,e.z)}function G(i,e){b().channel.send("game:notice",{level:i,message:e})}var y=class{channel;unsubscribes=[];host=null;editorKnown={};constructor(){this.channel=b().channel}connect(e,a){this.disconnect(),this.host=e,this.unsubscribes.push(this.channel.on("debug:set",({enabled:t})=>{this.editorKnown.debug=t,n.enabled=t}),this.channel.on("tool:set",({tool:t})=>{r(t)}),this.channel.on("playback:set",({paused:t})=>{this.editorKnown.paused=t,l(t)}),this.channel.on("entity:select",({uuid:t})=>{this.editorKnown.selectedUuid=t,h(t)}),this.channel.on("entity:focus",({uuid:t})=>{c(t)}),this.channel.on("entity:transform",({uuid:t,position:o,rotation:d,scale:u})=>{let s=this.host?.resolveEntity(t);s&&(o&&typeof s.setPosition=="function"&&s.setPosition(o.x,o.y,o.z),d&&(s.setRotationX?.(d.x),s.setRotationY?.(d.y),s.setRotationZ?.(d.z)),u&&v(s,u))}),this.channel.on("stage:variable:set",({key:t,value:o})=>{this.host?.setStageVariable?.(t,o)}),p(n,()=>this.publishDebugStateChanges())),this.publishDebugStateChanges(),m(a)}disconnect(){for(let e of this.unsubscribes)e();this.unsubscribes=[],this.host=null,this.editorKnown={}}publishDebugStateChanges(){let e={};n.paused!==this.editorKnown.paused&&(this.editorKnown.paused=n.paused,e.paused=n.paused),n.enabled!==this.editorKnown.debug&&(this.editorKnown.debug=n.enabled,e.debug=n.enabled),(e.paused!==void 0||e.debug!==void 0)&&this.publishStatus(e),(n.selectedEntityId!==this.editorKnown.selectedUuid||n.hoveredEntityId!==this.editorKnown.hoveredUuid)&&(this.editorKnown.selectedUuid=n.selectedEntityId,this.editorKnown.hoveredUuid=n.hoveredEntityId,this.channel.queue("entity:selection",{selectedUuid:n.selectedEntityId,hoveredUuid:n.hoveredEntityId}))}wantsEntityUpdates(){return this.channel.hasSubscribers("entity:upsert")||this.channel.hasSubscribers("stage:snapshot")}wantsThumbnails(){return this.channel.hasSubscribers("entity:thumbnail")}onEditorAttached(e){return this.channel.onSubscriberAdded(a=>{(a==="entity:upsert"||a==="entity:thumbnail")&&e()})}publishConfig(e){this.channel.send("game:config",e)}publishLoading(e){this.channel.send("game:loading",e)}publishStatus(e){this.channel.queue("game:status",e)}publishVariable(e){this.channel.queue("game:variable",e)}publishNotice(e,a){this.channel.send("game:notice",{level:e,message:a})}publishStageSnapshot(e){this.channel.send("stage:snapshot",e)}queueEntityUpsert(e){e.length&&this.channel.queue("entity:upsert",e)}queueEntityRemoved(e){e.length&&this.channel.queue("entity:removed",{uuids:e})}queueThumbnails(e){e.length&&this.channel.queue("entity:thumbnail",e)}};export{w as a,G as b,y as c};
|
package/dist/chunk-LGS5N5M4.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as d,p as v,q as V,r as y,t as D,u as S,v as B,x as b}from"./chunk-3I537JFL.js";import{c as k}from"./chunk-CM5YRNBJ.js";import{c as h,d as _,h as u,i as T,j as C}from"./chunk-7WRQ2UAN.js";import{Color as $,Group as nt,Sprite as st,SpriteMaterial as rt,CanvasTexture as U,LinearFilter as E,Vector2 as ot,ClampToEdgeWrapping as H}from"three";import{MeshStandardMaterial as K,MeshBasicMaterial as tt,MeshPhongMaterial as et}from"three";function it(i){return i&&typeof i.getDebugInfo=="function"}var c=class{entity;constructor(t){this.entity=t}getPositionString(){if(this.entity.mesh){let{x:r,y:s,z:o}=this.entity.mesh.position;return`${r.toFixed(2)}, ${s.toFixed(2)}, ${o.toFixed(2)}`}let{x:t,y:e,z:n}=this.entity.options.position||{x:0,y:0,z:0};return`${t.toFixed(2)}, ${e.toFixed(2)}, ${n.toFixed(2)}`}getRotationString(){if(this.entity.mesh){let{x:s,y:o,z:a}=this.entity.mesh.rotation,p=l=>(l*180/Math.PI).toFixed(1);return`${p(s)}\xB0, ${p(o)}\xB0, ${p(a)}\xB0`}let{x:t,y:e,z:n}=this.entity.options.rotation||{x:0,y:0,z:0},r=s=>(s*180/Math.PI).toFixed(1);return`${r(t)}\xB0, ${r(e)}\xB0, ${r(n)}\xB0`}getMaterialInfo(){if(!this.entity.mesh||!this.entity.mesh.material)return{type:"none"};let t=Array.isArray(this.entity.mesh.material)?this.entity.mesh.material[0]:this.entity.mesh.material,e={type:t.type};return(t instanceof K||t instanceof tt||t instanceof et)&&(e.color=`#${t.color.getHexString()}`,e.opacity=t.opacity,e.transparent=t.transparent),"roughness"in t&&(e.roughness=t.roughness),"metalness"in t&&(e.metalness=t.metalness),e}getPhysicsInfo(){if(!this.entity.body)return null;let t={type:this.entity.body.bodyType(),mass:this.entity.body.mass(),isEnabled:this.entity.body.isEnabled(),isSleeping:this.entity.body.isSleeping()},e=this.entity.body.linvel();return t.velocity=`${e.x.toFixed(2)}, ${e.y.toFixed(2)}, ${e.z.toFixed(2)}`,t}buildDebugInfo(){let t={name:this.entity.name||this.entity.uuid,uuid:this.entity.uuid,position:this.getPositionString(),rotation:this.getRotationString(),material:this.getMaterialInfo()},e=this.getPhysicsInfo();if(e&&(t.physics=e),it(this.entity)){let n=this.entity.getDebugInfo();return{...t,...n}}return t}};var f={position:void 0,text:"",fontFamily:'Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',fontSize:18,fontColor:"#FFFFFF",backgroundColor:null,padding:4,stickToViewport:!0,screenPosition:new ot(24,24),zDistance:1},O=class extends b{createEntity(t){return new g(t)}},at=Symbol("Text"),g=class i extends y{static type=at;_sprite=null;_texture=null;_canvas=null;_ctx=null;_cameraRef=null;_lastCanvasW=0;_lastCanvasH=0;constructor(t){super(),this.options=d(f,t),this.options.screenPosition=T(this.options.screenPosition,f.screenPosition),this.prependSetup(this.textSetup.bind(this)),this.prependUpdate(this.textUpdate.bind(this)),this.onCleanup(this.textDestroy.bind(this))}create(){return this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._lastCanvasW=0,this._lastCanvasH=0,this.group=new nt,this.createSprite(),super.create()}createSprite(){this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),this._texture=new U(this._canvas),this._texture.minFilter=E,this._texture.magFilter=E;let t=new rt({map:this._texture,transparent:!0,depthTest:!1,depthWrite:!1,alphaTest:.5});this._sprite=new st(t),this.group?.add(this._sprite),this.redrawText(this.options.text??"")}measureAndResizeCanvas(t,e,n,r){if(!this._canvas||!this._ctx)return{sizeChanged:!1};this._ctx.font=`${e}px ${n}`;let s=this._ctx.measureText(t),o=Math.ceil(s.width),a=Math.ceil(e*1.4),p=Math.max(2,o+r*2),l=Math.max(2,a+r*2),w=p!==this._lastCanvasW||l!==this._lastCanvasH;return this._canvas.width=p,this._canvas.height=l,this._lastCanvasW=p,this._lastCanvasH=l,{sizeChanged:w}}drawCenteredText(t,e,n){!this._canvas||!this._ctx||(this._ctx.font=`${e}px ${n}`,this._ctx.textAlign="center",this._ctx.textBaseline="middle",this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this.options.backgroundColor&&(this._ctx.fillStyle=this.toCssColor(this.options.backgroundColor),this._ctx.fillRect(0,0,this._canvas.width,this._canvas.height)),this._ctx.fillStyle=this.toCssColor(this.options.fontColor??"#FFFFFF"),this._ctx.fillText(t,this._canvas.width/2,this._canvas.height/2))}updateTexture(t){!this._texture||!this._canvas||(t&&(this._texture.dispose(),this._texture=new U(this._canvas),this._texture.minFilter=E,this._texture.magFilter=E,this._texture.wrapS=H,this._texture.wrapT=H),this._texture.image=this._canvas,this._texture.needsUpdate=!0,this._sprite&&this._sprite.material&&(this._sprite.material.map=this._texture,this._sprite.material.needsUpdate=!0))}redrawText(t){if(!this._canvas||!this._ctx)return;let e=this.options.fontSize??18,n=this.options.fontFamily??f.fontFamily,r=this.options.padding??4,{sizeChanged:s}=this.measureAndResizeCanvas(t,e,n,r);this.drawCenteredText(t,e,n),this.updateTexture(!!s),this.options.stickToViewport&&this._cameraRef?this.updateStickyTransform():this.updateWorldSpriteScale()}toCssColor(t){return typeof t=="string"?t:`#${(t instanceof $?t:new $(t)).getHexString()}`}textSetup(t){this._cameraRef=t.camera,this.options.stickToViewport&&this._cameraRef&&(this._cameraRef.camera.add(this.group),this.updateStickyTransform())}textUpdate(t){this._sprite&&this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}getResolution(){return{width:this._cameraRef?.screenResolution.x??1,height:this._cameraRef?.screenResolution.y??1}}getScreenPixels(t,e,n){let r=t.x>=0&&t.x<=1,s=t.y>=0&&t.y<=1;return{px:r?t.x*e:t.x,py:s?t.y*n:t.y}}computeWorldExtents(t,e){let n=1,r=1;if(t.isPerspectiveCamera){let s=t,o=Math.tan(s.fov*Math.PI/180/2)*e;n=o*s.aspect,r=o}else if(t.isOrthographicCamera){let s=t;n=(s.right-s.left)/2,r=(s.top-s.bottom)/2}return{worldHalfW:n,worldHalfH:r}}updateSpriteScale(t,e){if(!this._canvas||!this._sprite)return;let r=t*2/e,s=this._canvas.height,o=Math.max(1e-4,s*r),a=this._canvas.width/this._canvas.height,p=o*a;this._sprite.scale.set(p,o,1)}updateWorldSpriteScale(){if(!this._canvas||!this._sprite)return;let t=this._canvas.width/Math.max(1,this._canvas.height),e=Math.max(1,this.options.fontSize??18),n=Math.max(.25,e/32),r=n*t;this._sprite.scale.set(r,n,1)}updateStickyTransform(){if(!this._sprite||!this._cameraRef)return;let t=this._cameraRef.camera,{width:e,height:n}=this.getResolution(),r=T(this.options.screenPosition,f.screenPosition),{px:s,py:o}=this.getScreenPixels(r,e,n),a=Math.max(.001,this.options.zDistance??1),{worldHalfW:p,worldHalfH:l}=this.computeWorldExtents(t,a),w=s/e*2-1,Q=1-o/n*2,q=w*p,J=Q*l;this.group?.position.set(q,J,-a),this.updateSpriteScale(l,n)}updateText(t){this.options.text=t,this.redrawText(t),this.options.stickToViewport&&this._cameraRef&&this.updateStickyTransform()}buildInfo(){return{...new c(this).buildDebugInfo(),type:String(i.type),text:this.options.text??"",sticky:this.options.stickToViewport}}textDestroy(){this._texture?.dispose(),this._sprite?.material&&this._sprite.material.dispose(),this._sprite&&this._sprite.removeFromParent(),this.group?.removeFromParent(),this._sprite=null,this._texture=null,this._canvas=null,this._ctx=null,this._cameraRef=null}};function I(...i){return S({args:i,defaultConfig:{...f},EntityClass:g,BuilderClass:O,entityType:g.type,cloneFactory:t=>I(t??{})})}import{Euler as pt,Group as lt,Quaternion as ct,Vector3 as mt}from"three";import{TextureLoader as ht,SpriteMaterial as ut,Sprite as dt,SRGBColorSpace as yt}from"three";var W={...v,size:new mt(1,1,1),images:[],animations:[]},R=class extends B{collider(t){let e=C(t.collisionSize,t.size??_);return{shape:{type:"box",halfExtents:[e.x/2,e.y/2,e.z/2]}}}},F=class extends b{createEntity(t){return new x(t)}},ft=Symbol("Sprite"),x=class i extends y{static type=ft;sprites=[];spriteMap=new Map;currentSpriteIndex=0;animations=new Map;currentAnimation=null;currentAnimationFrame="";currentAnimationIndex=0;currentAnimationTime=0;constructor(t){super(),this.options=d(W,t),this.prependSetup(this.spriteSetup.bind(this)),this.prependUpdate(this.spriteUpdate.bind(this)),this.onCleanup(this.spriteDestroy.bind(this))}create(){return this.sprites=[],this.spriteMap.clear(),this.animations.clear(),this.currentAnimation=null,this.currentAnimationFrame="",this.currentAnimationIndex=0,this.currentAnimationTime=0,this.group=void 0,this.createSpritesFromImages(this.options?.images||[]),this.createAnimations(this.options?.animations||[]),super.create()}createSpritesFromImages(t){let e=new ht,n=C(this.options.size,_);t.forEach((r,s)=>{let o=e.load(r.file);o.colorSpace=yt,o.anisotropy=k;let a=new ut({map:o,transparent:!0}),p=new dt(a);p.position.normalize(),p.scale.set(n.x,n.y,n.z),p.visible=s===0,this.sprites.push(p),this.spriteMap.set(r.name,s)}),this.group=new lt,this.group.add(...this.sprites)}createAnimations(t){t.forEach(e=>{let{name:n,frames:r,loop:s=!1,speed:o=1}=e,a={frames:r.map((p,l)=>({key:p,index:l,time:(typeof o=="number"?o:o[l])*(l+1),duration:typeof o=="number"?o:o[l]})),loop:s};this.animations.set(n,a)})}setSprite(t){let n=this.spriteMap.get(t)??0;this.currentSpriteIndex=n,this.sprites.forEach((r,s)=>{r.visible=this.currentSpriteIndex===s})}setAnimation(t,e){let n=this.animations.get(t);if(!n)return;let{loop:r,frames:s}=n,o=s[this.currentAnimationIndex];t===this.currentAnimation?(this.currentAnimationFrame=o.key,this.currentAnimationTime+=e,this.setSprite(this.currentAnimationFrame)):this.currentAnimation=t,this.currentAnimationTime>o.time&&this.currentAnimationIndex++,this.currentAnimationIndex>=s.length&&(r?(this.currentAnimationIndex=0,this.currentAnimationTime=0):this.currentAnimationTime=s[this.currentAnimationIndex].time)}getCurrentRotationQuaternion(){return this.transformStore?.dirty.rotation?this.transformStore.rotation:this.body?.rotation?.()??null}syncSpriteMaterials(){let t=this.getCurrentRotationQuaternion();this.sprites.forEach(e=>{if(e.material&&t){let r=new ct(t.x,t.y,t.z,t.w),s=new pt().setFromQuaternion(r,"XYZ");e.material.rotation=s.z}let n=C(this.options.size,_);e.scale.set(n.x,n.y,n.z)})}spriteSetup(t){this.syncSpriteMaterials()}spriteUpdate(t){this.syncSpriteMaterials()}spriteDestroy(t){this.sprites.forEach(e=>{e.removeFromParent()}),this.group?.remove(...this.sprites),this.group?.removeFromParent()}buildInfo(){return{...new c(this).buildDebugInfo(),type:String(i.type)}}};function P(...i){return S({args:i,defaultConfig:W,EntityClass:x,BuilderClass:F,CollisionBuilderClass:R,entityType:x.type,cloneFactory:t=>P(t??{})})}import{Color as X,Group as xt}from"three";import{Line2NodeMaterial as _t}from"three/webgpu";import{Line2 as Ct}from"three/addons/lines/webgpu/Line2.js";import{Color as N}from"three";import{LineGeometry as gt}from"three/addons/lines/LineGeometry.js";function z(i){let t=[];for(let e of i){let{x:n,y:r,z:s}=u(e,h);t.push(n,r,s)}return t}function L(i,t,e){if(!i||i.length===0)return;let n=[],r=new N(e);for(let s=0;s<t;s++){let o=i[s]??i[i.length-1]??e,a=new N(o??r);n.push(a.r,a.g,a.b)}return n}function Y(i){let t=new gt,e=z(i.points);t.setPositions(e);let n=L(i.colors,i.points.length,"#ffffff");return n&&t.setColors(n),t}var m={...v,points:[{x:0,y:0,z:0},{x:1,y:0,z:0}],linewidth:1,worldUnits:!0,alphaToCoverage:!1,opacity:1,transparent:!1,dashed:!1,dashSize:1,gapSize:1,pickThreshold:0},vt=Symbol("Line");function M(i,t){if(!i||i.length<2)throw new Error(`${t}: at least two points are required`);return i}function j(i){return i instanceof X?i.clone():new X(i??"#ffffff")}function St(i){let t=!!i.colors?.length,e=new _t({color:j(i.color).getHex(),linewidth:i.linewidth??m.linewidth,worldUnits:i.worldUnits??m.worldUnits,vertexColors:t,dashed:i.dashed??!1,dashSize:i.dashSize??m.dashSize,gapSize:i.gapSize??m.gapSize,transparent:i.transparent??!1,opacity:i.opacity??1});return e.alphaToCoverage=i.alphaToCoverage??!1,e}function bt(i){return!i.point||!i.pointOnLine||i.faceIndex==null?null:{point:i.point.clone(),pointOnLine:i.pointOnLine.clone(),faceIndex:i.faceIndex,distance:i.distance}}function Et(i,t,e={}){let n=t.getLineObject();if(!n)return null;let r=e.threshold??t.options.pickThreshold??0,s=i.params.Line2??{threshold:0};s.threshold=r,i.params.Line2=s;let a=i.intersectObject(n,!1)[0];return a?bt(a):null}var Z=class i extends y{static type=vt;_line=null;_geometry=null;_material=null;constructor(t){super();let e=d(m,t);e.points=M(e.points,"ZylemLine").map(n=>u(n,h)),this.options=e}create(){return this.disposeLineResources(),this.group=new xt,this.rebuildLine(),this.applyGroupPosition(),super.create()}setPoints(t,e){if(M(t,"setPoints"),this.options.points=t.map(r=>u(r,h)),e&&(this.options.colors=e),!this._line||!this._geometry||!this._material)return this;this._geometry.setPositions(z(this.options.points));let n=L(this.options.colors,this.options.points.length,j(this.options.color));return n&&this._geometry.setColors(n),this._material.vertexColors=!!this.options.colors?.length,this.options.dashed&&this._line.computeLineDistances(),this._geometry.computeBoundingBox(),this._geometry.computeBoundingSphere(),this}getLineObject(){return this._line}pickFromRaycaster(t,e={}){return Et(t,this,e)}buildInfo(){return{...new c(this).buildDebugInfo(),type:String(i.type),points:this.options.points.length,linewidth:this.options.linewidth??m.linewidth,worldUnits:this.options.worldUnits??m.worldUnits}}rebuildLine(){this._geometry=Y({points:this.options.points,colors:this.options.colors}),this._material=St(this.options),this._line=new Ct(this._geometry,this._material),this.options.dashed&&this._line.computeLineDistances(),this.group?.add(this._line)}applyGroupPosition(){if(!this.group)return;let t=u(this.options.position,h);this.group.position.set(t.x,t.y,t.z)}_cleanup(t){this.disposeLineResources(),super._cleanup(t)}disposeLineResources(){this._line?.removeFromParent(),this._geometry?.dispose(),this._material?.dispose(),this._line=null,this._geometry=null,this._material=null}};function G(...i){let t=V(i,m);M(t.points,"createLine");let e=new Z(t);return D(e,n=>G(n??{}))}var A={registry:new Map,register(i,t){this.registry.set(i,t)},createFromBlueprint(i){let t=this.registry.get(i.type);if(!t)throw new Error(`Unknown entity type: ${i.type}`);let e={...i.data,position:i.position?{x:i.position[0],y:i.position[1],z:0}:void 0,name:i.id};return t(e)}};A.register("text",i=>I(i));A.register("sprite",i=>P(i));A.register("line",i=>G(i));function Ce(i){return{template:i,generate(t){let e=[];for(let n=0;n<t;n++)e.push(i.clone());return e}}}export{c as a,at as b,g as c,I as d,ft as e,x as f,P as g,vt as h,Et as i,Z as j,G as k,A as l,Ce as m};
|