modern-canvas 0.0.1 → 0.0.3

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 CHANGED
@@ -17,3 +17,62 @@
17
17
  <img src="https://img.shields.io/npm/l/modern-canvas.svg" alt="License">
18
18
  </a>
19
19
  </p>
20
+
21
+
22
+ ## 📦 Install
23
+
24
+ ```shell
25
+ npm i modern-canvas
26
+ ```
27
+
28
+ ## 🦄 Usage
29
+
30
+ ```ts
31
+ import { createApp, plugins } from 'modern-canvas'
32
+
33
+ const app = createApp({
34
+ view: document.querySelector('canvas'),
35
+ children: [
36
+ {
37
+ type: 'image',
38
+ style: {
39
+ left: 0,
40
+ top: 0,
41
+ width: 130,
42
+ height: 130,
43
+ rotation: 30,
44
+ },
45
+ src: '/example.jpg',
46
+ },
47
+ {
48
+ type: 'text',
49
+ style: {
50
+ left: 60,
51
+ top: 60,
52
+ width: 240,
53
+ height: 240,
54
+ rotation: 0,
55
+ fontSize: 40,
56
+ color: 'red',
57
+ },
58
+ content: 'TEXT',
59
+ },
60
+ {
61
+ type: 'video',
62
+ style: {
63
+ left: 60,
64
+ top: 60,
65
+ width: 30,
66
+ height: 30,
67
+ rotation: 30,
68
+ },
69
+ src: 'example.mp4',
70
+ },
71
+ ],
72
+ plugins,
73
+ })
74
+
75
+ await app.load()
76
+
77
+ app.start()
78
+ ```
package/dist/index.cjs CHANGED
@@ -1 +1,17 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=1;exports.one=e;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function w(o){return typeof o=="function"?o():o}class x extends Float32Array{static identity(){return new x([1,0,0,0,1,0,0,0,1])}static translation(r,c){return new x([1,0,0,0,1,0,r,c,1])}static rotation(r){const c=Math.cos(r),t=Math.sin(r);return new x([c,-t,0,t,c,0,0,0,1])}static scaling(r,c){return new x([r,0,0,0,c,0,0,0,1])}multiply(r){const c=this[0],t=this[1],n=this[2],d=this[3],m=this[4],a=this[5],s=this[6],e=this[7],i=this[8],u=r[0],f=r[1],h=r[2],E=r[3],T=r[4],l=r[5],g=r[6],R=r[7],A=r[8];return this[0]=u*c+f*d+h*s,this[1]=u*t+f*m+h*e,this[2]=u*n+f*a+h*i,this[3]=E*c+T*d+l*s,this[4]=E*t+T*m+l*e,this[5]=E*n+T*a+l*i,this[6]=g*c+R*d+A*s,this[7]=g*t+R*m+A*e,this[8]=g*n+R*a+A*i,this}}function L(o){const r=[];for(let c=o.length,t=0;t<c;t++){const n=o[t],d=~~(n/16);for(let m=0;m<=d;m++)m in r||(r[m]=0);r[d]|=1<<n%16}return r}function B(o){const r=document.createElement("video");return r.playsInline=!0,r.muted=!0,r.loop=!0,r.src=o,r}function O(o){const r=new Image;return r.decoding="sync",r.loading="eager",r.crossOrigin="anonymous",r.src=o,r}let b;const y=new Map;function X(){var o;return b||(b=document.createElement("iframe"),b.id=`__SANDBOX__${Math.random()}`,b.width="0",b.height="0",b.style.visibility="hidden",b.style.position="fixed",document.body.appendChild(b),(o=b.contentWindow)==null||o.document.write('<!DOCTYPE html><meta charset="UTF-8"><title></title><body>')),b}function P(o){switch(!0){case(o.startsWith("#")&&o.length===7):return o=o.substring(1),[parseInt(`${o[0]}${o[1]}`,16)/255,parseInt(`${o[2]}${o[3]}`,16)/255,parseInt(`${o[4]}${o[5]}`,16)/255,1];case(o.startsWith("#")&&o.length===9):return o=o.substring(1),[parseInt(`${o[0]}${o[1]}`,16)/255,parseInt(`${o[2]}${o[3]}`,16)/255,parseInt(`${o[4]}${o[5]}`,16)/255,parseInt(`${o[6]}${o[7]}`,16)/255];case o.startsWith("rgb("):return[...o.replace(/rgb\((.+?)\)/,"$1").split(",").slice(0,3).map(r=>Number(r.trim())/255),1];case o.startsWith("rgba("):return o.replace(/rgba\((.+?)\)/,"$1").split(",").slice(0,4).map(r=>Number(r.trim())/255)}}function G(o,r=[0,0,0,0]){if(y.has(o))return y.get(o);let c=P(o);if(!c){const t=X();if(t){const n=t.contentWindow;if(n){const d=n.document,m=d.createElement("div");d.body.appendChild(m),m.textContent=" ",m.style.color=o,c=P(n.getComputedStyle(m).color),d.body.removeChild(m)}}}return c&&y.set(o,c),c??r}const $=w({name:"renderer2d",register(o){o.registerShape("rectangle",{type:"2d",mode:"triangles",buffer:new Float32Array([-1,1,-1,-1,1,-1,1,-1,1,1,-1,1])}),o.registerMaterial("material2d",{vertexShader:`attribute vec2 aPosition;
2
+ varying vec2 vTextureCoord;
3
+ uniform mat3 uModelMatrix;
4
+ void main() {
5
+ vTextureCoord = step(0.0, aPosition);
6
+ vec2 position = aPosition;
7
+ gl_Position = vec4((uModelMatrix * vec3(position, 1)).xy, 0, 1);
8
+ }`,fragmentShader:`uniform sampler2D uSampler;
9
+ varying vec2 vTextureCoord;
10
+ uniform vec4 uBackgroundColor;
11
+ void main() {
12
+ vec4 color = texture2D(uSampler, vTextureCoord);
13
+ gl_FragColor = mix(uBackgroundColor, color, color.a);
14
+ }`});const r=document.createElement("canvas").getContext("2d");o.registerSystem({update(c=0){var d;const{textures:t}=o,n=o.query("type");for(let m=n.length,a=0;a<m;a++){const s=n[a],{type:e}=s;if(e==="image"&&s.src)t.has(s.id)||o.registerTexture(s.id,O(s.src));else if(e==="video")if(!t.has(s.id))o.registerTexture(s.id,B(s.src));else{const i=(d=t.get(s.id))==null?void 0:d.source;i.duration&&(i.currentTime=c%i.duration)}else if(e==="text"){const{width:i,height:u,color:f="black",fontSize:h=14,fontWeight:E=400,direction:T="inherit",fontFamily:l="monospace",fontKerning:g="normal",textAlign:R="center",textBaseline:A="middle"}=s.style??{};if(!t.has(s.id)){const _=`${E} ${h}px ${l}`;r.font=_;const p=r.measureText(s.content),I=u??p.actualBoundingBoxAscent+p.actualBoundingBoxDescent,v=i??p.width;s.style.width=v,s.style.height=I,r.canvas.width=v,r.canvas.height=I,r.fillStyle=f,r.direction=T,r.font=_,r.fontKerning=g,r.textAlign=R,r.textBaseline=A,r.clearRect(0,0,v,I),r.fillText(s.content,v/2,I/2),o.registerTexture(s.id,r.canvas)}}}}}),o.registerSystem({update(){var m;const{width:c,height:t,textures:n}=o,d=o.query();for(let a=d.length,s=0;s<a;s++){const e=d[s],{shape:i="rectangle",material:u="material2d",filters:f=[]}=e,{left:h=0,top:E=0,width:T=0,height:l=0,rotation:g=0,background:R}=e.style??{},A=h/c,_=E/t,p=T/c,I=l/t,v=g/180*Math.PI,D=R!=null&&R.color?G(R.color):[0,0,0,0];o.renderNode({shape:i,material:u,uniforms:{uSampler:(m=n.get(e.id))==null?void 0:m.value,uBackgroundColor:D,uModelMatrix:x.identity().multiply(x.translation(2*A-(1-p),1-I-2*_)).multiply(x.scaling(p,I)).multiply(x.rotation(v))},extraRenderers:f==null?void 0:f.map(N=>{const{shape:C,material:M,type:S,...F}=N;return{shape:C??i,material:M??S??u,uniforms:F}})})}}})}});function W(o,r){const{width:c,height:t,context:n,shapes:d,materials:m,framebuffers:a,lastState:s}=o,{extraRenderers:e=[]}=r,i=[r,...e].filter(u=>d.has(u.shape)&&m.has(u.material));for(let u=i.length,f=0;f<u;f++){const h=i[f],{shape:E,material:T,uniforms:l}=h,g=d.get(E),R=m.get(T);(s==null?void 0:s.material)!==T&&(s==null?void 0:s.shape)!==E&&R.setupAttributes({aPosition:g.buffer});const A=f<u-1?a[f%2]:null;n.bindFramebuffer(n.FRAMEBUFFER,(A==null?void 0:A.buffer)??null),n.viewport(0,0,c,t),A&&n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),(s==null?void 0:s.material)!==T&&n.useProgram(R.program),l&&R.setupUniforms(l),n.drawArrays(g.mode,0,g.count),A&&n.bindTexture(n.TEXTURE_2D,A.texture),o.lastState={material:T,shape:E}}}function U(o,r=0){var d,m;const{context:c,systems:t,framebuffers:n}=o;n.forEach(a=>a.resize()),c.clear(c.COLOR_BUFFER_BIT|c.DEPTH_BUFFER_BIT);for(let a=t.length,s=0;s<a;s++)(m=(d=t[s]).update)==null||m.call(d,r);c.flush()}function V(){const o=new Map,r=new Map;function c(a){if(o.has(a))return o.get(a);if(r.has(a)){const{value:s,shared:e}=r.get(a),i=s();return e&&n(a,i),i}}function t(a){return o.has(a)||r.has(a)}function n(a,s){o.set(a,s)}function d(a,s){m(a,s,!0)}function m(a,s,e=!1){r.set(a,{value:s,shared:e})}return new Proxy({instances:o,bindings:r,get:c,has:t,set:n,bind:m,singleton:d},{get(a,s,e){return typeof s=="symbol"||s in a?Reflect.get(a,s,e):a.get(s)},has(a,s){return typeof s=="symbol"||s in a?Reflect.has(a,s):a.has(s)},set(a,s,e,i){return typeof s=="symbol"||s in a?Reflect.set(a,s,e,i):(a.set(s,e),!0)}})}function H(o,r,c){const{context:t,materials:n,slTypes:d}=o,{vertexShader:m,fragmentShader:a,uniforms:s}=c;if(n.has(r))return;const e=[{type:t.VERTEX_SHADER,source:m},{type:t.FRAGMENT_SHADER,source:a.includes("precision")?a:`precision mediump float;
15
+ ${a}`}].map(({type:E,source:T})=>{const l=t.createShader(E);if(!l)throw new Error("failed to create shader");if(t.shaderSource(l,T),t.compileShader(l),!t.getShaderParameter(l,t.COMPILE_STATUS))throw new Error(`failed to compiling shader:
16
+ ${T}
17
+ ${t.getShaderInfoLog(l)}`);return l}),i=t.createProgram();if(!i)throw new Error("failed to create program");if(e.forEach(E=>t.attachShader(i,E)),t.linkProgram(i),e.forEach(E=>t.deleteShader(E)),!t.getProgramParameter(i,t.LINK_STATUS))throw new Error(`failed to initing program: ${t.getProgramInfoLog(i)}`);const u={};for(let E=t.getProgramParameter(i,t.ACTIVE_ATTRIBUTES),T=0;T<E;T++){const l=t.getActiveAttrib(i,T);if(!l)continue;const g=l.name.replace(/\[.*?]$/,"");u[g]={type:d[l.type],isArray:g!==l.name,location:t.getAttribLocation(i,g)}}const f={};for(let E=t.getProgramParameter(i,t.ACTIVE_UNIFORMS),T=0;T<E;T++){const l=t.getActiveUniform(i,T);if(!l)continue;const g=l.name.replace(/\[.*?]$/,"");f[g]={type:d[l.type],isArray:g!==l.name,location:t.getUniformLocation(i,g)}}const h={...c,program:i,attributes:u,uniforms:f,setupAttributes(E){for(const[T,l]of Object.entries(E)){const g=u[T];if(!g)continue;const{type:R,isArray:A,location:_}=g;if(l instanceof WebGLBuffer){t.bindBuffer(t.ARRAY_BUFFER,l);const p=t.getAttribLocation(i,T);switch(R){case"vec2":t.vertexAttribPointer(p,2,t.FLOAT,!1,0,0),t.enableVertexAttribArray(p);break;case"vec3":t.vertexAttribPointer(p,3,t.FLOAT,!1,0,0),t.enableVertexAttribArray(p);break}}else switch(R){case"float":A?t.vertexAttrib1fv(_,l):t.vertexAttrib1f(_,l);break;case"vec2":t.vertexAttrib2fv(_,l);break;case"vec3":t.vertexAttrib3fv(_,l);break;case"vec4":t.vertexAttrib4fv(_,l);break}}},setupUniforms(E){for(const[T,l]of Object.entries(E)){const g=f[T];if(!g)continue;const{type:R,isArray:A,location:_}=g;switch(R){case"float":A?t.uniform1fv(_,l):t.uniform1f(_,l);break;case"bool":case"int":A?t.uniform1iv(_,l):t.uniform1i(_,l);break;case"vec2":t.uniform2fv(_,l);break;case"vec3":t.uniform3fv(_,l);break;case"vec4":t.uniform4fv(_,l);break;case"mat2":t.uniformMatrix2fv(_,!1,l);break;case"mat3":t.uniformMatrix3fv(_,!1,l);break;case"mat4":t.uniformMatrix4fv(_,!1,l);break;case"sampler2D":t.bindTexture(t.TEXTURE_2D,l??o.defaultTexture),t.uniform1i(_,0);break}}}};s&&h.setupUniforms(s),n.set(r,h)}function Y(o,r,c){const{context:t,shapes:n,drawModes:d}=o,{type:m="2d",mode:a="triangles",buffer:s=new Float32Array([])}=c,e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,s,t.STATIC_DRAW),n.set(r,{mode:d[a],count:s.byteLength/s.BYTES_PER_ELEMENT/(m==="2d"?2:3),buffer:e})}function k(o){const{entities:r,children:c,components:t,archetypes:n}=o;r.clear(),t.clear(),n.clear();const d=function(){let e=0;return()=>++e}(),m=function(){let e=0;return()=>++e}();function a(e,i){var R,A;e.id||(e.id=d());const u=e.id,f=[];for(const _ in e){let p=t.get(_);p||(p=m(),t.set(_,p)),f.push(p)}const h=L(f),E=h.map(_=>String.fromCharCode(_)).join(""),T=r.get(u);T&&((A=(R=n.get(T.archetypeId))==null?void 0:R.entityIds)==null||A.delete(u));const l=n.get(E);let g=l==null?void 0:l.entityIds;l||(g=new Set,n.set(E,{entityIds:g,codePoints:h})),g.add(u),r.set(u,{path:i,archetypeId:E})}function s(e,i){for(let u=e.length,f=0;f<u;f++){const h=e[f],E=[...i,f];a(h,E),h.children&&s(h.children,E)}}s(c,[])}function q(o,r){const{entities:c,components:t,children:n,archetypes:d}=o;if(!r)return n.flatMap(function i(u){var f;return[u,(f=u.children)==null?void 0:f.flatMap(i)].filter(Boolean)});const m=typeof r=="string"?[r]:r,a=[];for(let i=m.length,u=0;u<i;u++){const f=t.get(m[u]);f&&a.push(f)}const s=L(a),e=[];for(const[,{entityIds:i,codePoints:u}]of d.entries())if(u.some(f=>s.some(h=>h&f)))for(const[f]of i.entries()){const{path:h}=c.get(f);if(!h||!h.length)continue;let E=n[h[0]];for(let T=h.length,l=1;l<T;l++)E=E[l];e.push(E)}return e}function K(o,r,c){const{context:t,textures:n}=o,d={loading:!0,value:null,source:c};return n.set(r,d),new Promise(m=>{c instanceof HTMLImageElement?c.addEventListener("load",a,{once:!0}):c instanceof HTMLVideoElement?(c.addEventListener("canplay",a,{once:!0}),c.addEventListener("timeupdate",()=>{t.bindTexture(t.TEXTURE_2D,d.value),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,c)})):a();function a(){d.value=t.createTexture(),d.value&&(t.bindTexture(t.TEXTURE_2D,d.value),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,c)),d.loading=!1,c instanceof HTMLVideoElement&&(c.currentTime=.01),m()}})}function j(o,r){const{systems:c}=o;c.push(r)}function z(o={}){var a,s;const{view:r=document.createElement("canvas"),children:c=[],plugins:t=[]}=o,n=V();n.view=r,n.singleton("context",()=>{const{view:e}=n,i=e.getContext("webgl",o)||e.getContext("experimental-webgl",o);if(!i)throw new Error("failed to getContext for webgl");const u=i.drawingBufferWidth,f=i.drawingBufferHeight;return i.viewport(0,0,u,f),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,!0),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),i.clearColor(0,0,0,0),i.enable(i.DEPTH_TEST),i.enable(i.CULL_FACE),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.depthMask(!1),i}),n.singleton("defaultTexture",()=>{const{context:e,width:i,height:u}=n,f=e.createTexture();return e.bindTexture(e.TEXTURE_2D,f),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,i,u,0,e.RGBA,e.UNSIGNED_BYTE,null),f}),n.singleton("framebuffers",()=>{const{context:e}=n;return Array.from({length:2},()=>{const i=e.createTexture(),u=e.createFramebuffer(),f=e.createRenderbuffer();function h(){const{width:E,height:T}=n;e.bindTexture(e.TEXTURE_2D,i),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,E,T,0,e.RGBA,e.UNSIGNED_BYTE,null),e.bindRenderbuffer(e.RENDERBUFFER,f),e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_COMPONENT16,E,T)}return h(),e.bindTexture(e.TEXTURE_2D,i),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindFramebuffer(e.FRAMEBUFFER,u),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,i,0),e.bindRenderbuffer(e.RENDERBUFFER,f),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,f),{buffer:u,depthBuffer:f,texture:i,resize:h}})}),n.singleton("drawModes",()=>{const{context:e}=n;return{points:e.POINTS,linear:e.LINEAR,triangles:e.TRIANGLES,triangleStrip:e.TRIANGLE_STRIP,triangleFan:e.TRIANGLE_FAN}}),n.singleton("slTypes",()=>{const{context:e}=n;return{[e.FLOAT]:"float",[e.FLOAT_VEC2]:"vec2",[e.FLOAT_VEC3]:"vec3",[e.FLOAT_VEC4]:"vec4",[e.INT]:"int",[e.INT_VEC2]:"ivec2",[e.INT_VEC3]:"ivec3",[e.INT_VEC4]:"ivec4",[e.UNSIGNED_INT]:"uint",[e.UNSIGNED_INT_VEC2??-1]:"uvec2",[e.UNSIGNED_INT_VEC3??-1]:"uvec3",[e.UNSIGNED_INT_VEC4??-1]:"uvec4",[e.BOOL]:"bool",[e.BOOL_VEC2]:"bvec2",[e.BOOL_VEC3]:"bvec3",[e.BOOL_VEC4]:"bvec4",[e.FLOAT_MAT2]:"mat2",[e.FLOAT_MAT3]:"mat3",[e.FLOAT_MAT4]:"mat4",[e.SAMPLER_2D]:"sampler2D",[e.INT_SAMPLER_2D??-1]:"sampler2D",[e.UNSIGNED_INT_SAMPLER_2D??-1]:"sampler2D",[e.SAMPLER_CUBE]:"samplerCube",[e.INT_SAMPLER_CUBE??-1]:"samplerCube",[e.UNSIGNED_INT_SAMPLER_CUBE??-1]:"samplerCube",[e.SAMPLER_2D_ARRAY??-1]:"sampler2DArray",[e.INT_SAMPLER_2D_ARRAY??-1]:"sampler2DArray",[e.UNSIGNED_INT_SAMPLER_2D_ARRAY??-1]:"sampler2DArray"}}),n.singleton("extensions",()=>({loseContext:n.context.getExtension("WEBGL_lose_context")})),n.bind("width",()=>n.context.drawingBufferWidth),n.bind("height",()=>n.context.drawingBufferHeight),n.plugins=new Map,n.children=c,n.shapes=new Map,n.registerShape=(e,i)=>Y(n,e,i),n.materials=new Map,n.registerMaterial=(e,i)=>H(n,e,i),n.textures=new Map,n.registerTexture=(e,i)=>K(n,e,i),n.entities=new Map,n.components=new Map,n.archetypes=new Map,n.systems=[],n.registerSystem=e=>j(n,e),n.query=e=>q(n,e),n.setup=()=>k(n),n.load=async()=>{var u,f;const{systems:e,textures:i}=n;for(let h=e.length,E=0;E<h;E++)(f=(u=e[E]).update)==null||f.call(u,0);for(;Array.from(i.values()).some(h=>h.loading);)await new Promise(h=>setTimeout(h,100))},n.renderNode=e=>W(n,e),n.render=e=>U(n,e),n.start=()=>{let e=0,i=0;u(0);function u(f){requestAnimationFrame(u),U(n,i),f*=.001,i+=f-e,e=f}};function d(e){e.preventDefault(),setTimeout(()=>{var i;n.context.isContextLost()&&((i=n.extensions.loseContext)==null||i.restoreContext())},0)}function m(){}return(a=r.addEventListener)==null||a.call(r,"webglcontextlost",d,!1),(s=r.addEventListener)==null||s.call(r,"webglcontextrestored",m,!1),n.destroy=()=>{var e,i,u;(e=r.removeEventListener)==null||e.call(r,"webglcontextlost",d),(i=r.removeEventListener)==null||i.call(r,"webglcontextrestored",m),n.context.useProgram(null),(u=n.extensions.loseContext)==null||u.loseContext()},t.forEach(e=>{var i;(i=e.register)==null||i.call(e,n),n.plugins.set(e.name,e)}),n.setup(),n}exports.Renderer2d=$;exports.createApp=z;
package/dist/index.js CHANGED
@@ -1 +1,17 @@
1
- (function(e,n){typeof exports=="object"&&typeof module<"u"?n(exports):typeof define=="function"&&define.amd?define(["exports"],n):(e=typeof globalThis<"u"?globalThis:e||self,n(e.modernCanvas={}))})(this,function(e){"use strict";e.one=1,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
1
+ (function(I,P){typeof exports=="object"&&typeof module<"u"?P(exports):typeof define=="function"&&define.amd?define(["exports"],P):(I=typeof globalThis<"u"?globalThis:I||self,P(I.modernCanvas={}))})(this,function(I){"use strict";function P(o){return typeof o=="function"?o():o}class x extends Float32Array{static identity(){return new x([1,0,0,0,1,0,0,0,1])}static translation(r,c){return new x([1,0,0,0,1,0,r,c,1])}static rotation(r){const c=Math.cos(r),t=Math.sin(r);return new x([c,-t,0,t,c,0,0,0,1])}static scaling(r,c){return new x([r,0,0,0,c,0,0,0,1])}multiply(r){const c=this[0],t=this[1],n=this[2],d=this[3],m=this[4],a=this[5],s=this[6],e=this[7],i=this[8],u=r[0],l=r[1],h=r[2],E=r[3],T=r[4],f=r[5],g=r[6],R=r[7],p=r[8];return this[0]=u*c+l*d+h*s,this[1]=u*t+l*m+h*e,this[2]=u*n+l*a+h*i,this[3]=E*c+T*d+f*s,this[4]=E*t+T*m+f*e,this[5]=E*n+T*a+f*i,this[6]=g*c+R*d+p*s,this[7]=g*t+R*m+p*e,this[8]=g*n+R*a+p*i,this}}function L(o){const r=[];for(let c=o.length,t=0;t<c;t++){const n=o[t],d=~~(n/16);for(let m=0;m<=d;m++)m in r||(r[m]=0);r[d]|=1<<n%16}return r}function C(o){const r=document.createElement("video");return r.playsInline=!0,r.muted=!0,r.loop=!0,r.src=o,r}function M(o){const r=new Image;return r.decoding="sync",r.loading="eager",r.crossOrigin="anonymous",r.src=o,r}let b;const U=new Map;function S(){var o;return b||(b=document.createElement("iframe"),b.id=`__SANDBOX__${Math.random()}`,b.width="0",b.height="0",b.style.visibility="hidden",b.style.position="fixed",document.body.appendChild(b),(o=b.contentWindow)==null||o.document.write('<!DOCTYPE html><meta charset="UTF-8"><title></title><body>')),b}function D(o){switch(!0){case(o.startsWith("#")&&o.length===7):return o=o.substring(1),[parseInt(`${o[0]}${o[1]}`,16)/255,parseInt(`${o[2]}${o[3]}`,16)/255,parseInt(`${o[4]}${o[5]}`,16)/255,1];case(o.startsWith("#")&&o.length===9):return o=o.substring(1),[parseInt(`${o[0]}${o[1]}`,16)/255,parseInt(`${o[2]}${o[3]}`,16)/255,parseInt(`${o[4]}${o[5]}`,16)/255,parseInt(`${o[6]}${o[7]}`,16)/255];case o.startsWith("rgb("):return[...o.replace(/rgb\((.+?)\)/,"$1").split(",").slice(0,3).map(r=>Number(r.trim())/255),1];case o.startsWith("rgba("):return o.replace(/rgba\((.+?)\)/,"$1").split(",").slice(0,4).map(r=>Number(r.trim())/255)}}function F(o,r=[0,0,0,0]){if(U.has(o))return U.get(o);let c=D(o);if(!c){const t=S();if(t){const n=t.contentWindow;if(n){const d=n.document,m=d.createElement("div");d.body.appendChild(m),m.textContent=" ",m.style.color=o,c=D(n.getComputedStyle(m).color),d.body.removeChild(m)}}}return c&&U.set(o,c),c??r}const w=P({name:"renderer2d",register(o){o.registerShape("rectangle",{type:"2d",mode:"triangles",buffer:new Float32Array([-1,1,-1,-1,1,-1,1,-1,1,1,-1,1])}),o.registerMaterial("material2d",{vertexShader:`attribute vec2 aPosition;
2
+ varying vec2 vTextureCoord;
3
+ uniform mat3 uModelMatrix;
4
+ void main() {
5
+ vTextureCoord = step(0.0, aPosition);
6
+ vec2 position = aPosition;
7
+ gl_Position = vec4((uModelMatrix * vec3(position, 1)).xy, 0, 1);
8
+ }`,fragmentShader:`uniform sampler2D uSampler;
9
+ varying vec2 vTextureCoord;
10
+ uniform vec4 uBackgroundColor;
11
+ void main() {
12
+ vec4 color = texture2D(uSampler, vTextureCoord);
13
+ gl_FragColor = mix(uBackgroundColor, color, color.a);
14
+ }`});const r=document.createElement("canvas").getContext("2d");o.registerSystem({update(c=0){var d;const{textures:t}=o,n=o.query("type");for(let m=n.length,a=0;a<m;a++){const s=n[a],{type:e}=s;if(e==="image"&&s.src)t.has(s.id)||o.registerTexture(s.id,M(s.src));else if(e==="video")if(!t.has(s.id))o.registerTexture(s.id,C(s.src));else{const i=(d=t.get(s.id))==null?void 0:d.source;i.duration&&(i.currentTime=c%i.duration)}else if(e==="text"){const{width:i,height:u,color:l="black",fontSize:h=14,fontWeight:E=400,direction:T="inherit",fontFamily:f="monospace",fontKerning:g="normal",textAlign:R="center",textBaseline:p="middle"}=s.style??{};if(!t.has(s.id)){const _=`${E} ${h}px ${f}`;r.font=_;const A=r.measureText(s.content),v=u??A.actualBoundingBoxAscent+A.actualBoundingBoxDescent,y=i??A.width;s.style.width=y,s.style.height=v,r.canvas.width=y,r.canvas.height=v,r.fillStyle=l,r.direction=T,r.font=_,r.fontKerning=g,r.textAlign=R,r.textBaseline=p,r.clearRect(0,0,y,v),r.fillText(s.content,y/2,v/2),o.registerTexture(s.id,r.canvas)}}}}}),o.registerSystem({update(){var m;const{width:c,height:t,textures:n}=o,d=o.query();for(let a=d.length,s=0;s<a;s++){const e=d[s],{shape:i="rectangle",material:u="material2d",filters:l=[]}=e,{left:h=0,top:E=0,width:T=0,height:f=0,rotation:g=0,background:R}=e.style??{},p=h/c,_=E/t,A=T/c,v=f/t,y=g/180*Math.PI,k=R!=null&&R.color?F(R.color):[0,0,0,0];o.renderNode({shape:i,material:u,uniforms:{uSampler:(m=n.get(e.id))==null?void 0:m.value,uBackgroundColor:k,uModelMatrix:x.identity().multiply(x.translation(2*p-(1-A),1-v-2*_)).multiply(x.scaling(A,v)).multiply(x.rotation(y))},extraRenderers:l==null?void 0:l.map(j=>{const{shape:q,material:K,type:z,...J}=j;return{shape:q??i,material:K??z??u,uniforms:J}})})}}})}});function B(o,r){const{width:c,height:t,context:n,shapes:d,materials:m,framebuffers:a,lastState:s}=o,{extraRenderers:e=[]}=r,i=[r,...e].filter(u=>d.has(u.shape)&&m.has(u.material));for(let u=i.length,l=0;l<u;l++){const h=i[l],{shape:E,material:T,uniforms:f}=h,g=d.get(E),R=m.get(T);(s==null?void 0:s.material)!==T&&(s==null?void 0:s.shape)!==E&&R.setupAttributes({aPosition:g.buffer});const p=l<u-1?a[l%2]:null;n.bindFramebuffer(n.FRAMEBUFFER,(p==null?void 0:p.buffer)??null),n.viewport(0,0,c,t),p&&n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),(s==null?void 0:s.material)!==T&&n.useProgram(R.program),f&&R.setupUniforms(f),n.drawArrays(g.mode,0,g.count),p&&n.bindTexture(n.TEXTURE_2D,p.texture),o.lastState={material:T,shape:E}}}function N(o,r=0){var d,m;const{context:c,systems:t,framebuffers:n}=o;n.forEach(a=>a.resize()),c.clear(c.COLOR_BUFFER_BIT|c.DEPTH_BUFFER_BIT);for(let a=t.length,s=0;s<a;s++)(m=(d=t[s]).update)==null||m.call(d,r);c.flush()}function O(){const o=new Map,r=new Map;function c(a){if(o.has(a))return o.get(a);if(r.has(a)){const{value:s,shared:e}=r.get(a),i=s();return e&&n(a,i),i}}function t(a){return o.has(a)||r.has(a)}function n(a,s){o.set(a,s)}function d(a,s){m(a,s,!0)}function m(a,s,e=!1){r.set(a,{value:s,shared:e})}return new Proxy({instances:o,bindings:r,get:c,has:t,set:n,bind:m,singleton:d},{get(a,s,e){return typeof s=="symbol"||s in a?Reflect.get(a,s,e):a.get(s)},has(a,s){return typeof s=="symbol"||s in a?Reflect.has(a,s):a.has(s)},set(a,s,e,i){return typeof s=="symbol"||s in a?Reflect.set(a,s,e,i):(a.set(s,e),!0)}})}function X(o,r,c){const{context:t,materials:n,slTypes:d}=o,{vertexShader:m,fragmentShader:a,uniforms:s}=c;if(n.has(r))return;const e=[{type:t.VERTEX_SHADER,source:m},{type:t.FRAGMENT_SHADER,source:a.includes("precision")?a:`precision mediump float;
15
+ ${a}`}].map(({type:E,source:T})=>{const f=t.createShader(E);if(!f)throw new Error("failed to create shader");if(t.shaderSource(f,T),t.compileShader(f),!t.getShaderParameter(f,t.COMPILE_STATUS))throw new Error(`failed to compiling shader:
16
+ ${T}
17
+ ${t.getShaderInfoLog(f)}`);return f}),i=t.createProgram();if(!i)throw new Error("failed to create program");if(e.forEach(E=>t.attachShader(i,E)),t.linkProgram(i),e.forEach(E=>t.deleteShader(E)),!t.getProgramParameter(i,t.LINK_STATUS))throw new Error(`failed to initing program: ${t.getProgramInfoLog(i)}`);const u={};for(let E=t.getProgramParameter(i,t.ACTIVE_ATTRIBUTES),T=0;T<E;T++){const f=t.getActiveAttrib(i,T);if(!f)continue;const g=f.name.replace(/\[.*?]$/,"");u[g]={type:d[f.type],isArray:g!==f.name,location:t.getAttribLocation(i,g)}}const l={};for(let E=t.getProgramParameter(i,t.ACTIVE_UNIFORMS),T=0;T<E;T++){const f=t.getActiveUniform(i,T);if(!f)continue;const g=f.name.replace(/\[.*?]$/,"");l[g]={type:d[f.type],isArray:g!==f.name,location:t.getUniformLocation(i,g)}}const h={...c,program:i,attributes:u,uniforms:l,setupAttributes(E){for(const[T,f]of Object.entries(E)){const g=u[T];if(!g)continue;const{type:R,isArray:p,location:_}=g;if(f instanceof WebGLBuffer){t.bindBuffer(t.ARRAY_BUFFER,f);const A=t.getAttribLocation(i,T);switch(R){case"vec2":t.vertexAttribPointer(A,2,t.FLOAT,!1,0,0),t.enableVertexAttribArray(A);break;case"vec3":t.vertexAttribPointer(A,3,t.FLOAT,!1,0,0),t.enableVertexAttribArray(A);break}}else switch(R){case"float":p?t.vertexAttrib1fv(_,f):t.vertexAttrib1f(_,f);break;case"vec2":t.vertexAttrib2fv(_,f);break;case"vec3":t.vertexAttrib3fv(_,f);break;case"vec4":t.vertexAttrib4fv(_,f);break}}},setupUniforms(E){for(const[T,f]of Object.entries(E)){const g=l[T];if(!g)continue;const{type:R,isArray:p,location:_}=g;switch(R){case"float":p?t.uniform1fv(_,f):t.uniform1f(_,f);break;case"bool":case"int":p?t.uniform1iv(_,f):t.uniform1i(_,f);break;case"vec2":t.uniform2fv(_,f);break;case"vec3":t.uniform3fv(_,f);break;case"vec4":t.uniform4fv(_,f);break;case"mat2":t.uniformMatrix2fv(_,!1,f);break;case"mat3":t.uniformMatrix3fv(_,!1,f);break;case"mat4":t.uniformMatrix4fv(_,!1,f);break;case"sampler2D":t.bindTexture(t.TEXTURE_2D,f??o.defaultTexture),t.uniform1i(_,0);break}}}};s&&h.setupUniforms(s),n.set(r,h)}function G(o,r,c){const{context:t,shapes:n,drawModes:d}=o,{type:m="2d",mode:a="triangles",buffer:s=new Float32Array([])}=c,e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,s,t.STATIC_DRAW),n.set(r,{mode:d[a],count:s.byteLength/s.BYTES_PER_ELEMENT/(m==="2d"?2:3),buffer:e})}function $(o){const{entities:r,children:c,components:t,archetypes:n}=o;r.clear(),t.clear(),n.clear();const d=function(){let e=0;return()=>++e}(),m=function(){let e=0;return()=>++e}();function a(e,i){var R,p;e.id||(e.id=d());const u=e.id,l=[];for(const _ in e){let A=t.get(_);A||(A=m(),t.set(_,A)),l.push(A)}const h=L(l),E=h.map(_=>String.fromCharCode(_)).join(""),T=r.get(u);T&&((p=(R=n.get(T.archetypeId))==null?void 0:R.entityIds)==null||p.delete(u));const f=n.get(E);let g=f==null?void 0:f.entityIds;f||(g=new Set,n.set(E,{entityIds:g,codePoints:h})),g.add(u),r.set(u,{path:i,archetypeId:E})}function s(e,i){for(let u=e.length,l=0;l<u;l++){const h=e[l],E=[...i,l];a(h,E),h.children&&s(h.children,E)}}s(c,[])}function W(o,r){const{entities:c,components:t,children:n,archetypes:d}=o;if(!r)return n.flatMap(function i(u){var l;return[u,(l=u.children)==null?void 0:l.flatMap(i)].filter(Boolean)});const m=typeof r=="string"?[r]:r,a=[];for(let i=m.length,u=0;u<i;u++){const l=t.get(m[u]);l&&a.push(l)}const s=L(a),e=[];for(const[,{entityIds:i,codePoints:u}]of d.entries())if(u.some(l=>s.some(h=>h&l)))for(const[l]of i.entries()){const{path:h}=c.get(l);if(!h||!h.length)continue;let E=n[h[0]];for(let T=h.length,f=1;f<T;f++)E=E[f];e.push(E)}return e}function V(o,r,c){const{context:t,textures:n}=o,d={loading:!0,value:null,source:c};return n.set(r,d),new Promise(m=>{c instanceof HTMLImageElement?c.addEventListener("load",a,{once:!0}):c instanceof HTMLVideoElement?(c.addEventListener("canplay",a,{once:!0}),c.addEventListener("timeupdate",()=>{t.bindTexture(t.TEXTURE_2D,d.value),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,c)})):a();function a(){d.value=t.createTexture(),d.value&&(t.bindTexture(t.TEXTURE_2D,d.value),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,c)),d.loading=!1,c instanceof HTMLVideoElement&&(c.currentTime=.01),m()}})}function H(o,r){const{systems:c}=o;c.push(r)}function Y(o={}){var a,s;const{view:r=document.createElement("canvas"),children:c=[],plugins:t=[]}=o,n=O();n.view=r,n.singleton("context",()=>{const{view:e}=n,i=e.getContext("webgl",o)||e.getContext("experimental-webgl",o);if(!i)throw new Error("failed to getContext for webgl");const u=i.drawingBufferWidth,l=i.drawingBufferHeight;return i.viewport(0,0,u,l),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,!0),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),i.clearColor(0,0,0,0),i.enable(i.DEPTH_TEST),i.enable(i.CULL_FACE),i.enable(i.BLEND),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA),i.depthMask(!1),i}),n.singleton("defaultTexture",()=>{const{context:e,width:i,height:u}=n,l=e.createTexture();return e.bindTexture(e.TEXTURE_2D,l),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,i,u,0,e.RGBA,e.UNSIGNED_BYTE,null),l}),n.singleton("framebuffers",()=>{const{context:e}=n;return Array.from({length:2},()=>{const i=e.createTexture(),u=e.createFramebuffer(),l=e.createRenderbuffer();function h(){const{width:E,height:T}=n;e.bindTexture(e.TEXTURE_2D,i),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,E,T,0,e.RGBA,e.UNSIGNED_BYTE,null),e.bindRenderbuffer(e.RENDERBUFFER,l),e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_COMPONENT16,E,T)}return h(),e.bindTexture(e.TEXTURE_2D,i),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindFramebuffer(e.FRAMEBUFFER,u),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,i,0),e.bindRenderbuffer(e.RENDERBUFFER,l),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,l),{buffer:u,depthBuffer:l,texture:i,resize:h}})}),n.singleton("drawModes",()=>{const{context:e}=n;return{points:e.POINTS,linear:e.LINEAR,triangles:e.TRIANGLES,triangleStrip:e.TRIANGLE_STRIP,triangleFan:e.TRIANGLE_FAN}}),n.singleton("slTypes",()=>{const{context:e}=n;return{[e.FLOAT]:"float",[e.FLOAT_VEC2]:"vec2",[e.FLOAT_VEC3]:"vec3",[e.FLOAT_VEC4]:"vec4",[e.INT]:"int",[e.INT_VEC2]:"ivec2",[e.INT_VEC3]:"ivec3",[e.INT_VEC4]:"ivec4",[e.UNSIGNED_INT]:"uint",[e.UNSIGNED_INT_VEC2??-1]:"uvec2",[e.UNSIGNED_INT_VEC3??-1]:"uvec3",[e.UNSIGNED_INT_VEC4??-1]:"uvec4",[e.BOOL]:"bool",[e.BOOL_VEC2]:"bvec2",[e.BOOL_VEC3]:"bvec3",[e.BOOL_VEC4]:"bvec4",[e.FLOAT_MAT2]:"mat2",[e.FLOAT_MAT3]:"mat3",[e.FLOAT_MAT4]:"mat4",[e.SAMPLER_2D]:"sampler2D",[e.INT_SAMPLER_2D??-1]:"sampler2D",[e.UNSIGNED_INT_SAMPLER_2D??-1]:"sampler2D",[e.SAMPLER_CUBE]:"samplerCube",[e.INT_SAMPLER_CUBE??-1]:"samplerCube",[e.UNSIGNED_INT_SAMPLER_CUBE??-1]:"samplerCube",[e.SAMPLER_2D_ARRAY??-1]:"sampler2DArray",[e.INT_SAMPLER_2D_ARRAY??-1]:"sampler2DArray",[e.UNSIGNED_INT_SAMPLER_2D_ARRAY??-1]:"sampler2DArray"}}),n.singleton("extensions",()=>({loseContext:n.context.getExtension("WEBGL_lose_context")})),n.bind("width",()=>n.context.drawingBufferWidth),n.bind("height",()=>n.context.drawingBufferHeight),n.plugins=new Map,n.children=c,n.shapes=new Map,n.registerShape=(e,i)=>G(n,e,i),n.materials=new Map,n.registerMaterial=(e,i)=>X(n,e,i),n.textures=new Map,n.registerTexture=(e,i)=>V(n,e,i),n.entities=new Map,n.components=new Map,n.archetypes=new Map,n.systems=[],n.registerSystem=e=>H(n,e),n.query=e=>W(n,e),n.setup=()=>$(n),n.load=async()=>{var u,l;const{systems:e,textures:i}=n;for(let h=e.length,E=0;E<h;E++)(l=(u=e[E]).update)==null||l.call(u,0);for(;Array.from(i.values()).some(h=>h.loading);)await new Promise(h=>setTimeout(h,100))},n.renderNode=e=>B(n,e),n.render=e=>N(n,e),n.start=()=>{let e=0,i=0;u(0);function u(l){requestAnimationFrame(u),N(n,i),l*=.001,i+=l-e,e=l}};function d(e){e.preventDefault(),setTimeout(()=>{var i;n.context.isContextLost()&&((i=n.extensions.loseContext)==null||i.restoreContext())},0)}function m(){}return(a=r.addEventListener)==null||a.call(r,"webglcontextlost",d,!1),(s=r.addEventListener)==null||s.call(r,"webglcontextrestored",m,!1),n.destroy=()=>{var e,i,u;(e=r.removeEventListener)==null||e.call(r,"webglcontextlost",d),(i=r.removeEventListener)==null||i.call(r,"webglcontextrestored",m),n.context.useProgram(null),(u=n.extensions.loseContext)==null||u.loseContext()},t.forEach(e=>{var i;(i=e.register)==null||i.call(e,n),n.plugins.set(e.name,e)}),n.setup(),n}I.Renderer2d=w,I.createApp=Y,Object.defineProperty(I,Symbol.toStringTag,{value:"Module"})});
package/dist/index.mjs CHANGED
@@ -1,4 +1,647 @@
1
- const o = 1;
1
+ function w(o) {
2
+ return typeof o == "function" ? o() : o;
3
+ }
4
+ class x extends Float32Array {
5
+ static identity() {
6
+ return new x([
7
+ 1,
8
+ 0,
9
+ 0,
10
+ 0,
11
+ 1,
12
+ 0,
13
+ 0,
14
+ 0,
15
+ 1
16
+ ]);
17
+ }
18
+ static translation(r, c) {
19
+ return new x([
20
+ 1,
21
+ 0,
22
+ 0,
23
+ 0,
24
+ 1,
25
+ 0,
26
+ r,
27
+ c,
28
+ 1
29
+ ]);
30
+ }
31
+ static rotation(r) {
32
+ const c = Math.cos(r), t = Math.sin(r);
33
+ return new x([
34
+ c,
35
+ -t,
36
+ 0,
37
+ t,
38
+ c,
39
+ 0,
40
+ 0,
41
+ 0,
42
+ 1
43
+ ]);
44
+ }
45
+ static scaling(r, c) {
46
+ return new x([
47
+ r,
48
+ 0,
49
+ 0,
50
+ 0,
51
+ c,
52
+ 0,
53
+ 0,
54
+ 0,
55
+ 1
56
+ ]);
57
+ }
58
+ multiply(r) {
59
+ const c = this[0], t = this[1], n = this[2], d = this[3], m = this[4], a = this[5], s = this[6], e = this[7], i = this[8], u = r[0], f = r[1], h = r[2], E = r[3], T = r[4], l = r[5], g = r[6], R = r[7], A = r[8];
60
+ return this[0] = u * c + f * d + h * s, this[1] = u * t + f * m + h * e, this[2] = u * n + f * a + h * i, this[3] = E * c + T * d + l * s, this[4] = E * t + T * m + l * e, this[5] = E * n + T * a + l * i, this[6] = g * c + R * d + A * s, this[7] = g * t + R * m + A * e, this[8] = g * n + R * a + A * i, this;
61
+ }
62
+ }
63
+ function P(o) {
64
+ const r = [];
65
+ for (let c = o.length, t = 0; t < c; t++) {
66
+ const n = o[t], d = ~~(n / 16);
67
+ for (let m = 0; m <= d; m++)
68
+ m in r || (r[m] = 0);
69
+ r[d] |= 1 << n % 16;
70
+ }
71
+ return r;
72
+ }
73
+ function B(o) {
74
+ const r = document.createElement("video");
75
+ return r.playsInline = !0, r.muted = !0, r.loop = !0, r.src = o, r;
76
+ }
77
+ function O(o) {
78
+ const r = new Image();
79
+ return r.decoding = "sync", r.loading = "eager", r.crossOrigin = "anonymous", r.src = o, r;
80
+ }
81
+ let b;
82
+ const y = /* @__PURE__ */ new Map();
83
+ function X() {
84
+ var o;
85
+ return b || (b = document.createElement("iframe"), b.id = `__SANDBOX__${Math.random()}`, b.width = "0", b.height = "0", b.style.visibility = "hidden", b.style.position = "fixed", document.body.appendChild(b), (o = b.contentWindow) == null || o.document.write('<!DOCTYPE html><meta charset="UTF-8"><title></title><body>')), b;
86
+ }
87
+ function U(o) {
88
+ switch (!0) {
89
+ case (o.startsWith("#") && o.length === 7):
90
+ return o = o.substring(1), [
91
+ parseInt(`${o[0]}${o[1]}`, 16) / 255,
92
+ parseInt(`${o[2]}${o[3]}`, 16) / 255,
93
+ parseInt(`${o[4]}${o[5]}`, 16) / 255,
94
+ 1
95
+ ];
96
+ case (o.startsWith("#") && o.length === 9):
97
+ return o = o.substring(1), [
98
+ parseInt(`${o[0]}${o[1]}`, 16) / 255,
99
+ parseInt(`${o[2]}${o[3]}`, 16) / 255,
100
+ parseInt(`${o[4]}${o[5]}`, 16) / 255,
101
+ parseInt(`${o[6]}${o[7]}`, 16) / 255
102
+ ];
103
+ case o.startsWith("rgb("):
104
+ return [
105
+ ...o.replace(/rgb\((.+?)\)/, "$1").split(",").slice(0, 3).map((r) => Number(r.trim()) / 255),
106
+ 1
107
+ ];
108
+ case o.startsWith("rgba("):
109
+ return o.replace(/rgba\((.+?)\)/, "$1").split(",").slice(0, 4).map((r) => Number(r.trim()) / 255);
110
+ }
111
+ }
112
+ function G(o, r = [0, 0, 0, 0]) {
113
+ if (y.has(o))
114
+ return y.get(o);
115
+ let c = U(o);
116
+ if (!c) {
117
+ const t = X();
118
+ if (t) {
119
+ const n = t.contentWindow;
120
+ if (n) {
121
+ const d = n.document, m = d.createElement("div");
122
+ d.body.appendChild(m), m.textContent = " ", m.style.color = o, c = U(n.getComputedStyle(m).color), d.body.removeChild(m);
123
+ }
124
+ }
125
+ }
126
+ return c && y.set(o, c), c ?? r;
127
+ }
128
+ const j = w({
129
+ name: "renderer2d",
130
+ register(o) {
131
+ o.registerShape("rectangle", {
132
+ type: "2d",
133
+ mode: "triangles",
134
+ buffer: new Float32Array([
135
+ -1,
136
+ 1,
137
+ -1,
138
+ -1,
139
+ 1,
140
+ -1,
141
+ 1,
142
+ -1,
143
+ 1,
144
+ 1,
145
+ -1,
146
+ 1
147
+ ])
148
+ }), o.registerMaterial("material2d", {
149
+ vertexShader: `attribute vec2 aPosition;
150
+ varying vec2 vTextureCoord;
151
+ uniform mat3 uModelMatrix;
152
+ void main() {
153
+ vTextureCoord = step(0.0, aPosition);
154
+ vec2 position = aPosition;
155
+ gl_Position = vec4((uModelMatrix * vec3(position, 1)).xy, 0, 1);
156
+ }`,
157
+ fragmentShader: `uniform sampler2D uSampler;
158
+ varying vec2 vTextureCoord;
159
+ uniform vec4 uBackgroundColor;
160
+ void main() {
161
+ vec4 color = texture2D(uSampler, vTextureCoord);
162
+ gl_FragColor = mix(uBackgroundColor, color, color.a);
163
+ }`
164
+ });
165
+ const r = document.createElement("canvas").getContext("2d");
166
+ o.registerSystem({
167
+ update(c = 0) {
168
+ var d;
169
+ const { textures: t } = o, n = o.query("type");
170
+ for (let m = n.length, a = 0; a < m; a++) {
171
+ const s = n[a], { type: e } = s;
172
+ if (e === "image" && s.src)
173
+ t.has(s.id) || o.registerTexture(s.id, O(s.src));
174
+ else if (e === "video")
175
+ if (!t.has(s.id))
176
+ o.registerTexture(s.id, B(s.src));
177
+ else {
178
+ const i = (d = t.get(s.id)) == null ? void 0 : d.source;
179
+ i.duration && (i.currentTime = c % i.duration);
180
+ }
181
+ else if (e === "text") {
182
+ const {
183
+ width: i,
184
+ height: u,
185
+ color: f = "black",
186
+ fontSize: h = 14,
187
+ fontWeight: E = 400,
188
+ direction: T = "inherit",
189
+ fontFamily: l = "monospace",
190
+ fontKerning: g = "normal",
191
+ textAlign: R = "center",
192
+ textBaseline: A = "middle"
193
+ } = s.style ?? {};
194
+ if (!t.has(s.id)) {
195
+ const _ = `${E} ${h}px ${l}`;
196
+ r.font = _;
197
+ const p = r.measureText(s.content), I = u ?? p.actualBoundingBoxAscent + p.actualBoundingBoxDescent, v = i ?? p.width;
198
+ s.style.width = v, s.style.height = I, r.canvas.width = v, r.canvas.height = I, r.fillStyle = f, r.direction = T, r.font = _, r.fontKerning = g, r.textAlign = R, r.textBaseline = A, r.clearRect(0, 0, v, I), r.fillText(s.content, v / 2, I / 2), o.registerTexture(s.id, r.canvas);
199
+ }
200
+ }
201
+ }
202
+ }
203
+ }), o.registerSystem({
204
+ update() {
205
+ var m;
206
+ const {
207
+ width: c,
208
+ height: t,
209
+ textures: n
210
+ } = o, d = o.query();
211
+ for (let a = d.length, s = 0; s < a; s++) {
212
+ const e = d[s], {
213
+ shape: i = "rectangle",
214
+ material: u = "material2d",
215
+ filters: f = []
216
+ } = e, {
217
+ left: h = 0,
218
+ top: E = 0,
219
+ width: T = 0,
220
+ height: l = 0,
221
+ rotation: g = 0,
222
+ background: R
223
+ } = e.style ?? {}, A = h / c, _ = E / t, p = T / c, I = l / t, v = g / 180 * Math.PI, D = R != null && R.color ? G(R.color) : [0, 0, 0, 0];
224
+ o.renderNode({
225
+ shape: i,
226
+ material: u,
227
+ uniforms: {
228
+ uSampler: (m = n.get(e.id)) == null ? void 0 : m.value,
229
+ uBackgroundColor: D,
230
+ uModelMatrix: x.identity().multiply(x.translation(2 * A - (1 - p), 1 - I - 2 * _)).multiply(x.scaling(p, I)).multiply(x.rotation(v))
231
+ },
232
+ extraRenderers: f == null ? void 0 : f.map((N) => {
233
+ const {
234
+ shape: C,
235
+ material: M,
236
+ type: S,
237
+ ...F
238
+ } = N;
239
+ return {
240
+ shape: C ?? i,
241
+ material: M ?? S ?? u,
242
+ uniforms: F
243
+ };
244
+ })
245
+ });
246
+ }
247
+ }
248
+ });
249
+ }
250
+ });
251
+ function $(o, r) {
252
+ const { width: c, height: t, context: n, shapes: d, materials: m, framebuffers: a, lastState: s } = o, { extraRenderers: e = [] } = r, i = [
253
+ r,
254
+ ...e
255
+ ].filter((u) => d.has(u.shape) && m.has(u.material));
256
+ for (let u = i.length, f = 0; f < u; f++) {
257
+ const h = i[f], {
258
+ shape: E,
259
+ material: T,
260
+ uniforms: l
261
+ } = h, g = d.get(E), R = m.get(T);
262
+ (s == null ? void 0 : s.material) !== T && (s == null ? void 0 : s.shape) !== E && R.setupAttributes({ aPosition: g.buffer });
263
+ const A = f < u - 1 ? a[f % 2] : null;
264
+ n.bindFramebuffer(n.FRAMEBUFFER, (A == null ? void 0 : A.buffer) ?? null), n.viewport(0, 0, c, t), A && n.clear(n.COLOR_BUFFER_BIT | n.DEPTH_BUFFER_BIT), (s == null ? void 0 : s.material) !== T && n.useProgram(R.program), l && R.setupUniforms(l), n.drawArrays(g.mode, 0, g.count), A && n.bindTexture(n.TEXTURE_2D, A.texture), o.lastState = {
265
+ material: T,
266
+ shape: E
267
+ };
268
+ }
269
+ }
270
+ function L(o, r = 0) {
271
+ var d, m;
272
+ const { context: c, systems: t, framebuffers: n } = o;
273
+ n.forEach((a) => a.resize()), c.clear(c.COLOR_BUFFER_BIT | c.DEPTH_BUFFER_BIT);
274
+ for (let a = t.length, s = 0; s < a; s++)
275
+ (m = (d = t[s]).update) == null || m.call(d, r);
276
+ c.flush();
277
+ }
278
+ function W() {
279
+ const o = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map();
280
+ function c(a) {
281
+ if (o.has(a))
282
+ return o.get(a);
283
+ if (r.has(a)) {
284
+ const { value: s, shared: e } = r.get(a), i = s();
285
+ return e && n(a, i), i;
286
+ }
287
+ }
288
+ function t(a) {
289
+ return o.has(a) || r.has(a);
290
+ }
291
+ function n(a, s) {
292
+ o.set(a, s);
293
+ }
294
+ function d(a, s) {
295
+ m(a, s, !0);
296
+ }
297
+ function m(a, s, e = !1) {
298
+ r.set(a, { value: s, shared: e });
299
+ }
300
+ return new Proxy(
301
+ { instances: o, bindings: r, get: c, has: t, set: n, bind: m, singleton: d },
302
+ {
303
+ get(a, s, e) {
304
+ return typeof s == "symbol" || s in a ? Reflect.get(a, s, e) : a.get(s);
305
+ },
306
+ has(a, s) {
307
+ return typeof s == "symbol" || s in a ? Reflect.has(a, s) : a.has(s);
308
+ },
309
+ set(a, s, e, i) {
310
+ return typeof s == "symbol" || s in a ? Reflect.set(a, s, e, i) : (a.set(s, e), !0);
311
+ }
312
+ }
313
+ );
314
+ }
315
+ function V(o, r, c) {
316
+ const { context: t, materials: n, slTypes: d } = o, {
317
+ vertexShader: m,
318
+ fragmentShader: a,
319
+ uniforms: s
320
+ } = c;
321
+ if (n.has(r))
322
+ return;
323
+ const e = [
324
+ { type: t.VERTEX_SHADER, source: m },
325
+ { type: t.FRAGMENT_SHADER, source: a.includes("precision") ? a : `precision mediump float;
326
+ ${a}` }
327
+ ].map(({ type: E, source: T }) => {
328
+ const l = t.createShader(E);
329
+ if (!l)
330
+ throw new Error("failed to create shader");
331
+ if (t.shaderSource(l, T), t.compileShader(l), !t.getShaderParameter(l, t.COMPILE_STATUS))
332
+ throw new Error(`failed to compiling shader:
333
+ ${T}
334
+ ${t.getShaderInfoLog(l)}`);
335
+ return l;
336
+ }), i = t.createProgram();
337
+ if (!i)
338
+ throw new Error("failed to create program");
339
+ if (e.forEach((E) => t.attachShader(i, E)), t.linkProgram(i), e.forEach((E) => t.deleteShader(E)), !t.getProgramParameter(i, t.LINK_STATUS))
340
+ throw new Error(`failed to initing program: ${t.getProgramInfoLog(i)}`);
341
+ const u = {};
342
+ for (let E = t.getProgramParameter(i, t.ACTIVE_ATTRIBUTES), T = 0; T < E; T++) {
343
+ const l = t.getActiveAttrib(i, T);
344
+ if (!l)
345
+ continue;
346
+ const g = l.name.replace(/\[.*?]$/, "");
347
+ u[g] = {
348
+ type: d[l.type],
349
+ isArray: g !== l.name,
350
+ location: t.getAttribLocation(i, g)
351
+ };
352
+ }
353
+ const f = {};
354
+ for (let E = t.getProgramParameter(i, t.ACTIVE_UNIFORMS), T = 0; T < E; T++) {
355
+ const l = t.getActiveUniform(i, T);
356
+ if (!l)
357
+ continue;
358
+ const g = l.name.replace(/\[.*?]$/, "");
359
+ f[g] = {
360
+ type: d[l.type],
361
+ isArray: g !== l.name,
362
+ location: t.getUniformLocation(i, g)
363
+ };
364
+ }
365
+ const h = {
366
+ ...c,
367
+ program: i,
368
+ attributes: u,
369
+ uniforms: f,
370
+ setupAttributes(E) {
371
+ for (const [T, l] of Object.entries(E)) {
372
+ const g = u[T];
373
+ if (!g)
374
+ continue;
375
+ const { type: R, isArray: A, location: _ } = g;
376
+ if (l instanceof WebGLBuffer) {
377
+ t.bindBuffer(t.ARRAY_BUFFER, l);
378
+ const p = t.getAttribLocation(i, T);
379
+ switch (R) {
380
+ case "vec2":
381
+ t.vertexAttribPointer(p, 2, t.FLOAT, !1, 0, 0), t.enableVertexAttribArray(p);
382
+ break;
383
+ case "vec3":
384
+ t.vertexAttribPointer(p, 3, t.FLOAT, !1, 0, 0), t.enableVertexAttribArray(p);
385
+ break;
386
+ }
387
+ } else
388
+ switch (R) {
389
+ case "float":
390
+ A ? t.vertexAttrib1fv(_, l) : t.vertexAttrib1f(_, l);
391
+ break;
392
+ case "vec2":
393
+ t.vertexAttrib2fv(_, l);
394
+ break;
395
+ case "vec3":
396
+ t.vertexAttrib3fv(_, l);
397
+ break;
398
+ case "vec4":
399
+ t.vertexAttrib4fv(_, l);
400
+ break;
401
+ }
402
+ }
403
+ },
404
+ setupUniforms(E) {
405
+ for (const [T, l] of Object.entries(E)) {
406
+ const g = f[T];
407
+ if (!g)
408
+ continue;
409
+ const { type: R, isArray: A, location: _ } = g;
410
+ switch (R) {
411
+ case "float":
412
+ A ? t.uniform1fv(_, l) : t.uniform1f(_, l);
413
+ break;
414
+ case "bool":
415
+ case "int":
416
+ A ? t.uniform1iv(_, l) : t.uniform1i(_, l);
417
+ break;
418
+ case "vec2":
419
+ t.uniform2fv(_, l);
420
+ break;
421
+ case "vec3":
422
+ t.uniform3fv(_, l);
423
+ break;
424
+ case "vec4":
425
+ t.uniform4fv(_, l);
426
+ break;
427
+ case "mat2":
428
+ t.uniformMatrix2fv(_, !1, l);
429
+ break;
430
+ case "mat3":
431
+ t.uniformMatrix3fv(_, !1, l);
432
+ break;
433
+ case "mat4":
434
+ t.uniformMatrix4fv(_, !1, l);
435
+ break;
436
+ case "sampler2D":
437
+ t.bindTexture(
438
+ t.TEXTURE_2D,
439
+ l ?? o.defaultTexture
440
+ ), t.uniform1i(_, 0);
441
+ break;
442
+ }
443
+ }
444
+ }
445
+ };
446
+ s && h.setupUniforms(s), n.set(r, h);
447
+ }
448
+ function H(o, r, c) {
449
+ const { context: t, shapes: n, drawModes: d } = o, {
450
+ type: m = "2d",
451
+ mode: a = "triangles",
452
+ buffer: s = new Float32Array([])
453
+ } = c, e = t.createBuffer();
454
+ t.bindBuffer(t.ARRAY_BUFFER, e), t.bufferData(t.ARRAY_BUFFER, s, t.STATIC_DRAW), n.set(r, {
455
+ mode: d[a],
456
+ count: s.byteLength / s.BYTES_PER_ELEMENT / (m === "2d" ? 2 : 3),
457
+ buffer: e
458
+ });
459
+ }
460
+ function Y(o) {
461
+ const { entities: r, children: c, components: t, archetypes: n } = o;
462
+ r.clear(), t.clear(), n.clear();
463
+ const d = function() {
464
+ let e = 0;
465
+ return () => ++e;
466
+ }(), m = function() {
467
+ let e = 0;
468
+ return () => ++e;
469
+ }();
470
+ function a(e, i) {
471
+ var R, A;
472
+ e.id || (e.id = d());
473
+ const u = e.id, f = [];
474
+ for (const _ in e) {
475
+ let p = t.get(_);
476
+ p || (p = m(), t.set(_, p)), f.push(p);
477
+ }
478
+ const h = P(f), E = h.map((_) => String.fromCharCode(_)).join(""), T = r.get(u);
479
+ T && ((A = (R = n.get(T.archetypeId)) == null ? void 0 : R.entityIds) == null || A.delete(u));
480
+ const l = n.get(E);
481
+ let g = l == null ? void 0 : l.entityIds;
482
+ l || (g = /* @__PURE__ */ new Set(), n.set(E, {
483
+ entityIds: g,
484
+ codePoints: h
485
+ })), g.add(u), r.set(u, { path: i, archetypeId: E });
486
+ }
487
+ function s(e, i) {
488
+ for (let u = e.length, f = 0; f < u; f++) {
489
+ const h = e[f], E = [...i, f];
490
+ a(h, E), h.children && s(h.children, E);
491
+ }
492
+ }
493
+ s(c, []);
494
+ }
495
+ function k(o, r) {
496
+ const { entities: c, components: t, children: n, archetypes: d } = o;
497
+ if (!r)
498
+ return n.flatMap(function i(u) {
499
+ var f;
500
+ return [u, (f = u.children) == null ? void 0 : f.flatMap(i)].filter(Boolean);
501
+ });
502
+ const m = typeof r == "string" ? [r] : r, a = [];
503
+ for (let i = m.length, u = 0; u < i; u++) {
504
+ const f = t.get(m[u]);
505
+ f && a.push(f);
506
+ }
507
+ const s = P(a), e = [];
508
+ for (const [, { entityIds: i, codePoints: u }] of d.entries())
509
+ if (u.some((f) => s.some((h) => h & f)))
510
+ for (const [f] of i.entries()) {
511
+ const { path: h } = c.get(f);
512
+ if (!h || !h.length)
513
+ continue;
514
+ let E = n[h[0]];
515
+ for (let T = h.length, l = 1; l < T; l++)
516
+ E = E[l];
517
+ e.push(E);
518
+ }
519
+ return e;
520
+ }
521
+ function q(o, r, c) {
522
+ const { context: t, textures: n } = o, d = {
523
+ loading: !0,
524
+ value: null,
525
+ source: c
526
+ };
527
+ return n.set(r, d), new Promise((m) => {
528
+ c instanceof HTMLImageElement ? c.addEventListener("load", a, { once: !0 }) : c instanceof HTMLVideoElement ? (c.addEventListener("canplay", a, { once: !0 }), c.addEventListener("timeupdate", () => {
529
+ t.bindTexture(t.TEXTURE_2D, d.value), t.texImage2D(t.TEXTURE_2D, 0, t.RGBA, t.RGBA, t.UNSIGNED_BYTE, c);
530
+ })) : a();
531
+ function a() {
532
+ d.value = t.createTexture(), d.value && (t.bindTexture(t.TEXTURE_2D, d.value), t.texParameteri(t.TEXTURE_2D, t.TEXTURE_MIN_FILTER, t.LINEAR), t.texParameteri(t.TEXTURE_2D, t.TEXTURE_MAG_FILTER, t.LINEAR), t.texParameteri(t.TEXTURE_2D, t.TEXTURE_WRAP_S, t.CLAMP_TO_EDGE), t.texParameteri(t.TEXTURE_2D, t.TEXTURE_WRAP_T, t.CLAMP_TO_EDGE), t.texImage2D(t.TEXTURE_2D, 0, t.RGBA, t.RGBA, t.UNSIGNED_BYTE, c)), d.loading = !1, c instanceof HTMLVideoElement && (c.currentTime = 0.01), m();
533
+ }
534
+ });
535
+ }
536
+ function K(o, r) {
537
+ const { systems: c } = o;
538
+ c.push(r);
539
+ }
540
+ function z(o = {}) {
541
+ var a, s;
542
+ const {
543
+ view: r = document.createElement("canvas"),
544
+ children: c = [],
545
+ plugins: t = []
546
+ } = o, n = W();
547
+ n.view = r, n.singleton("context", () => {
548
+ const { view: e } = n, i = e.getContext("webgl", o) || e.getContext("experimental-webgl", o);
549
+ if (!i)
550
+ throw new Error("failed to getContext for webgl");
551
+ const u = i.drawingBufferWidth, f = i.drawingBufferHeight;
552
+ return i.viewport(0, 0, u, f), i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL, !0), i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL, !0), i.clearColor(0, 0, 0, 0), i.enable(i.DEPTH_TEST), i.enable(i.CULL_FACE), i.enable(i.BLEND), i.blendFunc(i.ONE, i.ONE_MINUS_SRC_ALPHA), i.depthMask(!1), i;
553
+ }), n.singleton("defaultTexture", () => {
554
+ const { context: e, width: i, height: u } = n, f = e.createTexture();
555
+ return e.bindTexture(e.TEXTURE_2D, f), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MIN_FILTER, e.LINEAR), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MAG_FILTER, e.LINEAR), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_S, e.CLAMP_TO_EDGE), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_T, e.CLAMP_TO_EDGE), e.texImage2D(e.TEXTURE_2D, 0, e.RGBA, i, u, 0, e.RGBA, e.UNSIGNED_BYTE, null), f;
556
+ }), n.singleton("framebuffers", () => {
557
+ const { context: e } = n;
558
+ return Array.from({ length: 2 }, () => {
559
+ const i = e.createTexture(), u = e.createFramebuffer(), f = e.createRenderbuffer();
560
+ function h() {
561
+ const { width: E, height: T } = n;
562
+ e.bindTexture(e.TEXTURE_2D, i), e.texImage2D(e.TEXTURE_2D, 0, e.RGBA, E, T, 0, e.RGBA, e.UNSIGNED_BYTE, null), e.bindRenderbuffer(e.RENDERBUFFER, f), e.renderbufferStorage(e.RENDERBUFFER, e.DEPTH_COMPONENT16, E, T);
563
+ }
564
+ return h(), e.bindTexture(e.TEXTURE_2D, i), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MIN_FILTER, e.LINEAR), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_MAG_FILTER, e.LINEAR), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_S, e.CLAMP_TO_EDGE), e.texParameteri(e.TEXTURE_2D, e.TEXTURE_WRAP_T, e.CLAMP_TO_EDGE), e.bindFramebuffer(e.FRAMEBUFFER, u), e.framebufferTexture2D(e.FRAMEBUFFER, e.COLOR_ATTACHMENT0, e.TEXTURE_2D, i, 0), e.bindRenderbuffer(e.RENDERBUFFER, f), e.framebufferRenderbuffer(e.FRAMEBUFFER, e.DEPTH_ATTACHMENT, e.RENDERBUFFER, f), {
565
+ buffer: u,
566
+ depthBuffer: f,
567
+ texture: i,
568
+ resize: h
569
+ };
570
+ });
571
+ }), n.singleton("drawModes", () => {
572
+ const { context: e } = n;
573
+ return {
574
+ points: e.POINTS,
575
+ linear: e.LINEAR,
576
+ triangles: e.TRIANGLES,
577
+ triangleStrip: e.TRIANGLE_STRIP,
578
+ triangleFan: e.TRIANGLE_FAN
579
+ };
580
+ }), n.singleton("slTypes", () => {
581
+ const { context: e } = n;
582
+ return {
583
+ [e.FLOAT]: "float",
584
+ [e.FLOAT_VEC2]: "vec2",
585
+ [e.FLOAT_VEC3]: "vec3",
586
+ [e.FLOAT_VEC4]: "vec4",
587
+ [e.INT]: "int",
588
+ [e.INT_VEC2]: "ivec2",
589
+ [e.INT_VEC3]: "ivec3",
590
+ [e.INT_VEC4]: "ivec4",
591
+ [e.UNSIGNED_INT]: "uint",
592
+ [e.UNSIGNED_INT_VEC2 ?? -1]: "uvec2",
593
+ [e.UNSIGNED_INT_VEC3 ?? -1]: "uvec3",
594
+ [e.UNSIGNED_INT_VEC4 ?? -1]: "uvec4",
595
+ [e.BOOL]: "bool",
596
+ [e.BOOL_VEC2]: "bvec2",
597
+ [e.BOOL_VEC3]: "bvec3",
598
+ [e.BOOL_VEC4]: "bvec4",
599
+ [e.FLOAT_MAT2]: "mat2",
600
+ [e.FLOAT_MAT3]: "mat3",
601
+ [e.FLOAT_MAT4]: "mat4",
602
+ [e.SAMPLER_2D]: "sampler2D",
603
+ [e.INT_SAMPLER_2D ?? -1]: "sampler2D",
604
+ [e.UNSIGNED_INT_SAMPLER_2D ?? -1]: "sampler2D",
605
+ [e.SAMPLER_CUBE]: "samplerCube",
606
+ [e.INT_SAMPLER_CUBE ?? -1]: "samplerCube",
607
+ [e.UNSIGNED_INT_SAMPLER_CUBE ?? -1]: "samplerCube",
608
+ [e.SAMPLER_2D_ARRAY ?? -1]: "sampler2DArray",
609
+ [e.INT_SAMPLER_2D_ARRAY ?? -1]: "sampler2DArray",
610
+ [e.UNSIGNED_INT_SAMPLER_2D_ARRAY ?? -1]: "sampler2DArray"
611
+ };
612
+ }), n.singleton("extensions", () => ({
613
+ loseContext: n.context.getExtension("WEBGL_lose_context")
614
+ })), n.bind("width", () => n.context.drawingBufferWidth), n.bind("height", () => n.context.drawingBufferHeight), n.plugins = /* @__PURE__ */ new Map(), n.children = c, n.shapes = /* @__PURE__ */ new Map(), n.registerShape = (e, i) => H(n, e, i), n.materials = /* @__PURE__ */ new Map(), n.registerMaterial = (e, i) => V(n, e, i), n.textures = /* @__PURE__ */ new Map(), n.registerTexture = (e, i) => q(n, e, i), n.entities = /* @__PURE__ */ new Map(), n.components = /* @__PURE__ */ new Map(), n.archetypes = /* @__PURE__ */ new Map(), n.systems = [], n.registerSystem = (e) => K(n, e), n.query = (e) => k(n, e), n.setup = () => Y(n), n.load = async () => {
615
+ var u, f;
616
+ const { systems: e, textures: i } = n;
617
+ for (let h = e.length, E = 0; E < h; E++)
618
+ (f = (u = e[E]).update) == null || f.call(u, 0);
619
+ for (; Array.from(i.values()).some((h) => h.loading); )
620
+ await new Promise((h) => setTimeout(h, 100));
621
+ }, n.renderNode = (e) => $(n, e), n.render = (e) => L(n, e), n.start = () => {
622
+ let e = 0, i = 0;
623
+ u(0);
624
+ function u(f) {
625
+ requestAnimationFrame(u), L(n, i), f *= 1e-3, i += f - e, e = f;
626
+ }
627
+ };
628
+ function d(e) {
629
+ e.preventDefault(), setTimeout(() => {
630
+ var i;
631
+ n.context.isContextLost() && ((i = n.extensions.loseContext) == null || i.restoreContext());
632
+ }, 0);
633
+ }
634
+ function m() {
635
+ }
636
+ return (a = r.addEventListener) == null || a.call(r, "webglcontextlost", d, !1), (s = r.addEventListener) == null || s.call(r, "webglcontextrestored", m, !1), n.destroy = () => {
637
+ var e, i, u;
638
+ (e = r.removeEventListener) == null || e.call(r, "webglcontextlost", d), (i = r.removeEventListener) == null || i.call(r, "webglcontextrestored", m), n.context.useProgram(null), (u = n.extensions.loseContext) == null || u.loseContext();
639
+ }, t.forEach((e) => {
640
+ var i;
641
+ (i = e.register) == null || i.call(e, n), n.plugins.set(e.name, e);
642
+ }), n.setup(), n;
643
+ }
2
644
  export {
3
- o as one
645
+ j as Renderer2d,
646
+ z as createApp
4
647
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "modern-canvas",
3
3
  "type": "module",
4
- "version": "0.0.1",
4
+ "version": "0.0.3",
5
5
  "packageManager": "pnpm@7.26.2",
6
6
  "description": "A data driven modern canvas library",
7
7
  "author": "wxm",
@@ -45,21 +45,24 @@
45
45
  "types"
46
46
  ],
47
47
  "scripts": {
48
- "dev": "vite",
48
+ "dev": "vite docs",
49
49
  "lint": "eslint src",
50
50
  "test": "vitest --no-threads --no-isolate",
51
51
  "build": "vite build && tsc --project tsconfig.build.json",
52
+ "build:docs": "vite build docs",
52
53
  "version": "conventional-changelog -p angular -i CHANGELOG.md -s && git add CHANGELOG.md",
53
54
  "release": "bumpp package.json --commit \"release: v%s\" --push --all --tag"
54
55
  },
55
56
  "devDependencies": {
56
57
  "@qq15725/eslint-config": "^1.1.0",
57
58
  "@types/node": "^18.14.0",
59
+ "@vitejs/plugin-vue": "^4.1.0",
58
60
  "bumpp": "^8.2.1",
59
61
  "conventional-changelog-cli": "^2.2.2",
60
62
  "eslint": "^8.34.0",
61
63
  "typescript": "^4.9.5",
62
64
  "vite": "^4.1.2",
63
- "vitest": "^0.28.5"
65
+ "vitest": "^0.28.5",
66
+ "vue": "^3.2.47"
64
67
  }
65
68
  }
package/types/app.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ import type { QueryOptions } from './query';
2
+ import type { RenderNodeOptions } from './render';
3
+ import type { System } from './system';
4
+ import type { Texture } from './texture';
5
+ import type { Shape, UserShape } from './shape';
6
+ import type { Node } from './node';
7
+ import type { Material, UserMaterial } from './material';
8
+ import type { Plugin } from './plugin';
9
+ import type { Container } from './container';
10
+ export interface App extends Container {
11
+ view: HTMLCanvasElement;
12
+ children: Node[];
13
+ context: WebGLRenderingContext;
14
+ defaultTexture: WebGLTexture;
15
+ framebuffers: {
16
+ buffer: WebGLFramebuffer | null;
17
+ depthBuffer: WebGLRenderbuffer | null;
18
+ texture: WebGLTexture | null;
19
+ resize(): void;
20
+ }[];
21
+ drawModes: {
22
+ points: GLenum;
23
+ linear: GLenum;
24
+ triangles: GLenum;
25
+ triangleStrip: GLenum;
26
+ triangleFan: GLenum;
27
+ };
28
+ slTypes: Record<number, 'float' | 'vec2' | 'vec3' | 'vec4' | 'int' | 'ivec2' | 'ivec3' | 'ivec4' | 'uint' | 'uvec2' | 'uvec3' | 'uvec4' | 'bool' | 'bvec2' | 'bvec3' | 'bvec4' | 'mat2' | 'mat3' | 'mat4' | 'sampler2D' | 'samplerCube' | 'sampler2DArray'>;
29
+ extensions: {
30
+ loseContext: WEBGL_lose_context | null;
31
+ };
32
+ width: number;
33
+ height: number;
34
+ plugins: Map<string, Plugin>;
35
+ shapes: Map<string, Shape>;
36
+ registerShape(name: string, shape: UserShape): void;
37
+ materials: Map<string, Material>;
38
+ registerMaterial(name: string, material: UserMaterial): void;
39
+ textures: Map<number, Texture>;
40
+ registerTexture(id: number, source: TexImageSource): Promise<void>;
41
+ lastState?: {
42
+ material: string;
43
+ shape: string;
44
+ };
45
+ entities: Map<number, {
46
+ path: number[];
47
+ archetypeId: string;
48
+ }>;
49
+ components: Map<string, number>;
50
+ archetypes: Map<string, {
51
+ entityIds: Set<number>;
52
+ codePoints: number[];
53
+ }>;
54
+ systems: System[];
55
+ registerSystem(system: System): void;
56
+ query(where?: QueryOptions): Node;
57
+ setup(): void;
58
+ load(): Promise<void>;
59
+ renderNode(options: RenderNodeOptions): void;
60
+ render(time?: number): void;
61
+ start(): void;
62
+ destroy(): void;
63
+ }
@@ -0,0 +1,13 @@
1
+ export interface Container {
2
+ instances: Map<string, any>;
3
+ bindings: Map<string, {
4
+ value: () => any;
5
+ shared: boolean;
6
+ }>;
7
+ get<T = any>(key: string): T;
8
+ has(key: string): boolean;
9
+ set<T = any>(key: string, value: T): void;
10
+ bind<T = any>(key: string, value: () => T, shared?: boolean): void;
11
+ singleton<T = any>(key: string, value: () => T): void;
12
+ }
13
+ export declare function createContainer(): Container;
@@ -0,0 +1,3 @@
1
+ import type { Options } from './options';
2
+ import type { App } from './app';
3
+ export declare function createApp(options?: Options): App;
package/types/index.d.ts CHANGED
@@ -1 +1,4 @@
1
- export declare const one = 1;
1
+ export * from './plugins';
2
+ export * from './app';
3
+ export * from './create-app';
4
+ export type { Node } from './node';
@@ -0,0 +1,24 @@
1
+ import type { App } from './app';
2
+ export interface UserMaterial {
3
+ vertexShader: string;
4
+ fragmentShader: string;
5
+ uniforms?: Record<string, any>;
6
+ }
7
+ export type Material = UserMaterial & {
8
+ program: WebGLProgram;
9
+ attributes: Record<string, MaterialAttribute>;
10
+ uniforms: Record<string, MaterialUniform>;
11
+ setupAttributes(attributes: Record<string, any>): void;
12
+ setupUniforms(uniforms: Record<string, any>): void;
13
+ };
14
+ export interface MaterialAttribute {
15
+ type: App['slTypes'][keyof App['slTypes']];
16
+ isArray: boolean;
17
+ location: GLint;
18
+ }
19
+ export interface MaterialUniform {
20
+ type: App['slTypes'][keyof App['slTypes']];
21
+ isArray: boolean;
22
+ location: WebGLUniformLocation | null;
23
+ }
24
+ export declare function registerMaterial(app: App, name: string, userMaterial: UserMaterial): void;
@@ -0,0 +1,4 @@
1
+ export interface Node {
2
+ [key: string]: any;
3
+ children?: Node[];
4
+ }
@@ -0,0 +1,7 @@
1
+ import type { Node } from './node';
2
+ import type { Plugin } from './plugin';
3
+ export interface Options extends WebGLContextAttributes {
4
+ view?: HTMLCanvasElement;
5
+ children?: Node[];
6
+ plugins?: Plugin[];
7
+ }
@@ -0,0 +1,6 @@
1
+ import type { App } from './app';
2
+ export interface Plugin {
3
+ name: string;
4
+ register?(app: App): void;
5
+ }
6
+ export declare function definePlugin(plugin: Plugin | (() => Plugin)): Plugin;
@@ -0,0 +1 @@
1
+ export * from './renderer2d';
@@ -0,0 +1 @@
1
+ export declare const Renderer2d: import("../plugin").Plugin;
@@ -0,0 +1,4 @@
1
+ import type { App } from './app';
2
+ import type { Node } from './node';
3
+ export type QueryOptions = string | string[];
4
+ export declare function query(app: App, options?: QueryOptions): Node[];
@@ -0,0 +1,13 @@
1
+ import type { App } from './app';
2
+ export interface RenderNodeOptions {
3
+ shape: string;
4
+ material: string;
5
+ uniforms?: Record<string, any>;
6
+ extraRenderers?: {
7
+ shape: string;
8
+ material: string;
9
+ uniforms?: Record<string, any>;
10
+ }[];
11
+ }
12
+ export declare function renderNode(app: App, options: RenderNodeOptions): void;
13
+ export declare function render(app: App, time?: number): void;
@@ -0,0 +1,2 @@
1
+ import type { App } from './app';
2
+ export declare function setup(app: App): void;
@@ -0,0 +1,12 @@
1
+ import type { App } from './app';
2
+ export interface UserShape {
3
+ type?: '2d' | '3d';
4
+ mode?: keyof App['drawModes'];
5
+ buffer?: Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | BigUint64Array | BigInt64Array | Float32Array | Float64Array;
6
+ }
7
+ export interface Shape {
8
+ mode: GLenum;
9
+ count: number;
10
+ buffer: WebGLBuffer | null;
11
+ }
12
+ export declare function registerShape(app: App, name: string, userShape: UserShape): void;
@@ -0,0 +1,5 @@
1
+ import type { App } from './app';
2
+ export interface System {
3
+ update?(time?: number): void;
4
+ }
5
+ export declare function registerSystem(app: App, system: System): void;
@@ -0,0 +1,7 @@
1
+ import type { App } from './app';
2
+ export interface Texture {
3
+ loading: boolean;
4
+ value: WebGLTexture | null;
5
+ source: TexImageSource;
6
+ }
7
+ export declare function registerTexture(app: App, name: number, source: TexImageSource): Promise<void>;
@@ -0,0 +1,11 @@
1
+ export declare class Matrix3 extends Float32Array {
2
+ static identity(): Matrix3;
3
+ static translation(tx: number, ty: number): Matrix3;
4
+ static rotation(radians: number): Matrix3;
5
+ static scaling(sx: number, sy: number): Matrix3;
6
+ multiply(matrix3: Matrix3): this;
7
+ }
8
+ export declare function getArchetypeIdCodePoints(componentIds: number[]): number[];
9
+ export declare function createVideo(url: string): HTMLVideoElement;
10
+ export declare function createImage(url: string): HTMLImageElement;
11
+ export declare function resolveColor(value: string, defaultValue?: number[]): [number, number, number, number];