mirror of
https://github.com/billsonnn/nitro-renderer.git
synced 2025-02-07 14:22:36 +01:00
281 lines
69 KiB
JavaScript
281 lines
69 KiB
JavaScript
"use strict";const i=require("./index-H-H0n5qT.cjs");class Z{static init(e){Object.defineProperty(this,"resizeTo",{set(t){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=t,t&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let t,r;if(this._resizeTo===globalThis.window)t=globalThis.innerWidth,r=globalThis.innerHeight;else{const{clientWidth:s,clientHeight:a}=this._resizeTo;t=s,r=a}this.renderer.resize(t,r),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}Z.extension=i.ExtensionType.Application;class ee{static init(e){e=Object.assign({autoStart:!0,sharedTicker:!1},e),Object.defineProperty(this,"ticker",{set(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this,i.UPDATE_PRIORITY.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?i.Ticker.shared:new i.Ticker,e.autoStart&&this.start()}static destroy(){if(this._ticker){const e=this._ticker;this.ticker=null,e.destroy()}}}ee.extension=i.ExtensionType.Application;class te{constructor(e){this._renderer=e}push(e,t,r){this._renderer.renderPipes.batch.break(r),r.add({renderPipeId:"filter",canBundle:!1,action:"pushFilter",container:t,filterEffect:e})}pop(e,t,r){this._renderer.renderPipes.batch.break(r),r.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}execute(e){e.action==="pushFilter"?this._renderer.filter.push(e):e.action==="popFilter"&&this._renderer.filter.pop()}destroy(){this._renderer=null}}te.extension={type:[i.ExtensionType.WebGLPipes,i.ExtensionType.WebGPUPipes,i.ExtensionType.CanvasPipes],name:"filter"};const Re=new i.Matrix;function Ue(n,e){return e.clear(),re(n,e),e.isValid||e.set(0,0,0,0),n.renderGroup?e.applyMatrix(n.renderGroup.localTransform):e.applyMatrix(n.parentRenderGroup.worldTransform),e}function re(n,e){if(n.localDisplayStatus!==7||!n.measurable)return;const t=!!n.effects.length;let r=e;if((n.renderGroup||t)&&(r=i.boundsPool.get().clear()),n.boundsArea)e.addRect(n.boundsArea,n.worldTransform);else{if(n.renderPipeId){const a=n.bounds;r.addFrame(a.minX,a.minY,a.maxX,a.maxY,n.groupTransform)}const s=n.children;for(let a=0;a<s.length;a++)re(s[a],r)}if(t){let s=!1;for(let a=0;a<n.effects.length;a++)n.effects[a].addBounds&&(s||(s=!0,r.applyMatrix(n.parentRenderGroup.worldTransform)),n.effects[a].addBounds(r,!0));s&&(r.applyMatrix(n.parentRenderGroup.worldTransform.copyTo(Re).invert()),e.addBounds(r,n.relativeGroupTransform)),e.addBounds(r),i.boundsPool.return(r)}else n.renderGroup&&(e.addBounds(r,n.relativeGroupTransform),i.boundsPool.return(r))}function Ge(n,e){e.clear();const t=e.matrix;for(let r=0;r<n.length;r++){const s=n[r];s.globalDisplayStatus<7||(e.matrix=s.worldTransform,s.addBounds(e))}return e.matrix=t,e}const Fe=new i.Geometry({attributes:{aPosition:{buffer:new Float32Array([0,0,1,0,1,1,0,1]),format:"float32x2",stride:2*4,offset:0}},indexBuffer:new Uint32Array([0,1,2,0,2,3])});class ie{constructor(e){this._filterStackIndex=0,this._filterStack=[],this._filterGlobalUniforms=new i.UniformGroup({uInputSize:{value:new Float32Array(4),type:"vec4<f32>"},uInputPixel:{value:new Float32Array(4),type:"vec4<f32>"},uInputClamp:{value:new Float32Array(4),type:"vec4<f32>"},uOutputFrame:{value:new Float32Array(4),type:"vec4<f32>"},uGlobalFrame:{value:new Float32Array(4),type:"vec4<f32>"},uOutputTexture:{value:new Float32Array(4),type:"vec4<f32>"}}),this._globalFilterBindGroup=new i.BindGroup({}),this.renderer=e}get activeBackTexture(){var e;return(e=this._activeFilterData)==null?void 0:e.backTexture}push(e){var g;const t=this.renderer,r=e.filterEffect.filters;this._filterStack[this._filterStackIndex]||(this._filterStack[this._filterStackIndex]=this._getFilterData());const s=this._filterStack[this._filterStackIndex];if(this._filterStackIndex++,r.length===0){s.skip=!0;return}const a=s.bounds;e.renderables?Ge(e.renderables,a):e.filterEffect.filterArea?(a.clear(),a.addRect(e.filterEffect.filterArea),a.applyMatrix(e.container.worldTransform)):Ue(e.container,a);const o=t.renderTarget.renderTarget.colorTexture.source;let l=1/0,d=0,c=!0,h=!1,u=!1,f=!0;for(let x=0;x<r.length;x++){const p=r[x];if(l=Math.min(l,p.resolution==="inherit"?o._resolution:p.resolution),d+=p.padding,p.antialias==="off"?c=!1:p.antialias==="inherit"&&c&&(c=o.antialias),p.clipToViewport||(f=!1),!!!(p.compatibleRenderers&t.type)){u=!1;break}if(p.blendRequired&&!(((g=t.backBuffer)==null?void 0:g.useBackBuffer)??!0)){i.warn("Blend filter requires backBuffer on WebGL renderer to be enabled. Set `useBackBuffer: true` in the renderer options."),u=!1;break}u=p.enabled||u,h=h||p.blendRequired}if(!u){s.skip=!0;return}if(a.scale(l),f){const x=t.renderTarget.rootViewPort;a.fitBounds(0,x.width,0,x.height)}if(a.ceil().scale(1/l).pad(d|0),!a.isPositive){s.skip=!0;return}s.skip=!1,s.bounds=a,s.blendRequired=h,s.container=e.container,s.filterEffect=e.filterEffect,s.previousRenderSurface=t.renderTarget.renderSurface,s.inputTexture=i.TexturePool.getOptimalTexture(a.width,a.height,l,c),t.renderTarget.bind(s.inputTexture,!0),t.globalUniforms.push({offset:a})}pop(){const e=this.renderer;this._filterStackIndex--;const t=this._filterStack[this._filterStackIndex];if(t.skip)return;this._activeFilterData=t;const r=t.inputTexture,s=t.bounds;let a=i.Texture.EMPTY;if(e.renderTarget.finishRenderPass(),t.blendRequired){const l=this._filterStackIndex>0?this._filterStack[this._filterStackIndex-1].bounds:null,d=e.renderTarget.getRenderTarget(t.previousRenderSurface);a=this.getBackTexture(d,s,l)}t.backTexture=a;const o=t.filterEffect.filters;if(this._globalFilterBindGroup.setResource(r.source.style,2),this._globalFilterBindGroup.setResource(a.source,3),e.globalUniforms.pop(),o.length===1)o[0].apply(this,r,t.previousRenderSurface,!1),i.TexturePool.returnTexture(r);else{let l=t.inputTexture,d=i.TexturePool.getOptimalTexture(s.width,s.height,l.source._resolution,!1),c=0;for(c=0;c<o.length-1;++c){o[c].apply(this,l,d,!0);const u=l;l=d,d=u}o[c].apply(this,l,t.previousRenderSurface,!1),i.TexturePool.returnTexture(l),i.TexturePool.returnTexture(d)}t.blendRequired&&i.TexturePool.returnTexture(a)}getBackTexture(e,t,r){const s=e.colorTexture.source._resolution,a=i.TexturePool.getOptimalTexture(t.width,t.height,s,!1);let o=t.minX,l=t.minY;r&&(o-=r.minX,l-=r.minY),o=Math.floor(o*s),l=Math.floor(l*s);const d=Math.ceil(t.width*s),c=Math.ceil(t.height*s);return this.renderer.renderTarget.copyToTexture(e,a,{x:o,y:l},{width:d,height:c},{x:0,y:0}),a}applyFilter(e,t,r,s){const a=this.renderer,o=this._filterStack[this._filterStackIndex],l=o.bounds,d=i.Point.shared,h=o.previousRenderSurface===r;let u=this.renderer.renderTarget.rootRenderTarget.colorTexture.source._resolution,f=this._filterStackIndex-1;for(;f>0&&this._filterStack[f].skip;)--f;f>0&&(u=this._filterStack[f].inputTexture.source._resolution);const g=this._filterGlobalUniforms,x=g.uniforms,p=x.uOutputFrame,m=x.uInputSize,_=x.uInputPixel,v=x.uInputClamp,b=x.uGlobalFrame,S=x.uOutputTexture;if(h){let w=this._filterStackIndex;for(;w>0;){w--;const C=this._filterStack[this._filterStackIndex-1];if(!C.skip){d.x=C.bounds.minX,d.y=C.bounds.minY;break}}p[0]=l.minX-d.x,p[1]=l.minY-d.y}else p[0]=0,p[1]=0;p[2]=t.frame.width,p[3]=t.frame.height,m[0]=t.source.width,m[1]=t.source.height,m[2]=1/m[0],m[3]=1/m[1],_[0]=t.source.pixelWidth,_[1]=t.source.pixelHeight,_[2]=1/_[0],_[3]=1/_[1],v[0]=.5*_[2],v[1]=.5*_[3],v[2]=t.frame.width*m[2]-.5*_[2],v[3]=t.frame.height*m[3]-.5*_[3];const B=this.renderer.renderTarget.rootRenderTarget.colorTexture;b[0]=d.x*u,b[1]=d.y*u,b[2]=B.source.width*u,b[3]=B.source.height*u;const T=this.renderer.renderTarget.getRenderTarget(r);if(a.renderTarget.bind(r,!!s),r instanceof i.Texture?(S[0]=r.frame.width,S[1]=r.frame.height):(S[0]=T.width,S[1]=T.height),S[2]=T.isRoot?-1:1,g.update(),a.renderPipes.uniformBatch){const w=a.renderPipes.uniformBatch.getUboResource(g);this._globalFilterBindGroup.setResource(w,0)}else this._globalFilterBindGroup.setResource(g,0);this._globalFilterBindGroup.setResource(t.source,1),this._globalFilterBindGroup.setResource(t.source.style,2),e.groups[0]=this._globalFilterBindGroup,a.encoder.draw({geometry:Fe,shader:e,state:e._state,topology:"triangle-list"}),a.type===i.RendererType.WEBGL&&a.renderTarget.finishRenderPass()}_getFilterData(){return{skip:!1,inputTexture:null,bounds:new i.Bounds,container:null,filterEffect:null,blendRequired:!1,previousRenderSurface:null}}calculateSpriteMatrix(e,t){const r=this._activeFilterData,s=e.set(r.inputTexture._source.width,0,0,r.inputTexture._source.height,r.bounds.minX,r.bounds.minY),a=t.worldTransform.copyTo(i.Matrix.shared);return a.invert(),s.prepend(a),s.scale(1/t.texture.frame.width,1/t.texture.frame.height),s.translate(t.anchor.x,t.anchor.y),s}}ie.extension={type:[i.ExtensionType.WebGLSystem,i.ExtensionType.WebGPUSystem],name:"filter"};class R extends i.ViewContainer{constructor(e){e instanceof i.GraphicsContext&&(e={context:e});const{context:t,roundPixels:r,...s}=e||{};super({label:"Graphics",...s}),this.renderPipeId="graphics",t?this._context=t:this._context=this._ownedContext=new i.GraphicsContext,this._context.on("update",this.onViewUpdate,this),this.allowChildren=!1,this.roundPixels=r??!1}set context(e){e!==this._context&&(this._context.off("update",this.onViewUpdate,this),this._context=e,this._context.on("update",this.onViewUpdate,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}addBounds(e){e.addBounds(this._context.bounds)}containsPoint(e){return this._context.containsPoint(e)}destroy(e){this._ownedContext&&!e?this._ownedContext.destroy(e):(e===!0||(e==null?void 0:e.context)===!0)&&this._context.destroy(e),this._ownedContext=null,this._context=null,super.destroy(e)}_callContextMethod(e,t){return this.context[e](...t),this}setFillStyle(...e){return this._callContextMethod("setFillStyle",e)}setStrokeStyle(...e){return this._callContextMethod("setStrokeStyle",e)}fill(...e){return this._callContextMethod("fill",e)}stroke(...e){return this._callContextMethod("stroke",e)}texture(...e){return this._callContextMethod("texture",e)}beginPath(){return this._callContextMethod("beginPath",[])}cut(){return this._callContextMethod("cut",[])}arc(...e){return this._callContextMethod("arc",e)}arcTo(...e){return this._callContextMethod("arcTo",e)}arcToSvg(...e){return this._callContextMethod("arcToSvg",e)}bezierCurveTo(...e){return this._callContextMethod("bezierCurveTo",e)}closePath(){return this._callContextMethod("closePath",[])}ellipse(...e){return this._callContextMethod("ellipse",e)}circle(...e){return this._callContextMethod("circle",e)}path(...e){return this._callContextMethod("path",e)}lineTo(...e){return this._callContextMethod("lineTo",e)}moveTo(...e){return this._callContextMethod("moveTo",e)}quadraticCurveTo(...e){return this._callContextMethod("quadraticCurveTo",e)}rect(...e){return this._callContextMethod("rect",e)}roundRect(...e){return this._callContextMethod("roundRect",e)}poly(...e){return this._callContextMethod("poly",e)}regularPoly(...e){return this._callContextMethod("regularPoly",e)}roundPoly(...e){return this._callContextMethod("roundPoly",e)}roundShape(...e){return this._callContextMethod("roundShape",e)}filletRect(...e){return this._callContextMethod("filletRect",e)}chamferRect(...e){return this._callContextMethod("chamferRect",e)}star(...e){return this._callContextMethod("star",e)}svg(...e){return this._callContextMethod("svg",e)}restore(...e){return this._callContextMethod("restore",e)}save(){return this._callContextMethod("save",[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod("resetTransform",[])}rotateTransform(...e){return this._callContextMethod("rotate",e)}scaleTransform(...e){return this._callContextMethod("scale",e)}setTransform(...e){return this._callContextMethod("setTransform",e)}transform(...e){return this._callContextMethod("transform",e)}translateTransform(...e){return this._callContextMethod("translate",e)}clear(){return this._callContextMethod("clear",[])}get fillStyle(){return this._context.fillStyle}set fillStyle(e){this._context.fillStyle=e}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(e){this._context.strokeStyle=e}clone(e=!1){return e?new R(this._context.clone()):(this._ownedContext=null,new R(this._context))}lineStyle(e,t,r){i.deprecation(i.v8_0_0,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");const s={};return e&&(s.width=e),t&&(s.color=t),r&&(s.alpha=r),this.context.strokeStyle=s,this}beginFill(e,t){i.deprecation(i.v8_0_0,"Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.");const r={};return e&&(r.color=e),t&&(r.alpha=t),this.context.fillStyle=r,this}endFill(){i.deprecation(i.v8_0_0,"Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style."),this.context.fill();const e=this.context.strokeStyle;return(e.width!==i.GraphicsContext.defaultStrokeStyle.width||e.color!==i.GraphicsContext.defaultStrokeStyle.color||e.alpha!==i.GraphicsContext.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...e){return i.deprecation(i.v8_0_0,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",e)}drawEllipse(...e){return i.deprecation(i.v8_0_0,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",e)}drawPolygon(...e){return i.deprecation(i.v8_0_0,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",e)}drawRect(...e){return i.deprecation(i.v8_0_0,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",e)}drawRoundedRect(...e){return i.deprecation(i.v8_0_0,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",e)}drawStar(...e){return i.deprecation(i.v8_0_0,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",e)}}const se=class ne extends i.Geometry{constructor(...e){let t=e[0]??{};t instanceof Float32Array&&(i.deprecation(i.v8_0_0,"use new MeshGeometry({ positions, uvs, indices }) instead"),t={positions:t,uvs:e[1],indices:e[2]}),t={...ne.defaultOptions,...t};const r=t.positions||new Float32Array([0,0,1,0,1,1,0,1]),s=t.uvs||new Float32Array([0,0,1,0,1,1,0,1]),a=t.indices||new Uint32Array([0,1,2,0,2,3]),o=t.shrinkBuffersToFit,l=new i.Buffer({data:r,label:"attribute-mesh-positions",shrinkToFit:o,usage:i.BufferUsage.VERTEX|i.BufferUsage.COPY_DST}),d=new i.Buffer({data:s,label:"attribute-mesh-uvs",shrinkToFit:o,usage:i.BufferUsage.VERTEX|i.BufferUsage.COPY_DST}),c=new i.Buffer({data:a,label:"index-mesh-buffer",shrinkToFit:o,usage:i.BufferUsage.INDEX|i.BufferUsage.COPY_DST});super({attributes:{aPosition:{buffer:l,format:"float32x2",stride:2*4,offset:0},aUV:{buffer:d,format:"float32x2",stride:2*4,offset:0}},indexBuffer:c,topology:t.topology}),this.batchMode="auto"}get positions(){return this.attributes.aPosition.buffer.data}set positions(e){this.attributes.aPosition.buffer.data=e}get uvs(){return this.attributes.aUV.buffer.data}set uvs(e){this.attributes.aUV.buffer.data=e}get indices(){return this.indexBuffer.data}set indices(e){this.indexBuffer.data=e}};se.defaultOptions={topology:"triangle-list",shrinkBuffersToFit:!1};let A=se;function ke(n){const e=n._stroke,t=n._fill,s=[`div { ${[`color: ${i.Color.shared.setValue(t.color).toHex()}`,`font-size: ${n.fontSize}px`,`font-family: ${n.fontFamily}`,`font-weight: ${n.fontWeight}`,`font-style: ${n.fontStyle}`,`font-variant: ${n.fontVariant}`,`letter-spacing: ${n.letterSpacing}px`,`text-align: ${n.align}`,`padding: ${n.padding}px`,`white-space: ${n.whiteSpace==="pre"&&n.wordWrap?"pre-wrap":n.whiteSpace}`,...n.lineHeight?[`line-height: ${n.lineHeight}px`]:[],...n.wordWrap?[`word-wrap: ${n.breakWords?"break-all":"break-word"}`,`max-width: ${n.wordWrapWidth}px`]:[],...e?[oe(e)]:[],...n.dropShadow?[ae(n.dropShadow)]:[],...n.cssOverrides].join(";")} }`];return Ae(n.tagStyles,s),s.join(" ")}function ae(n){const e=i.Color.shared.setValue(n.color).setAlpha(n.alpha).toHexa(),t=Math.round(Math.cos(n.angle)*n.distance),r=Math.round(Math.sin(n.angle)*n.distance),s=`${t}px ${r}px`;return n.blur>0?`text-shadow: ${s} ${n.blur}px ${e}`:`text-shadow: ${s} ${e}`}function oe(n){return[`-webkit-text-stroke-width: ${n.width}px`,`-webkit-text-stroke-color: ${i.Color.shared.setValue(n.color).toHex()}`,`text-stroke-width: ${n.width}px`,`text-stroke-color: ${i.Color.shared.setValue(n.color).toHex()}`,"paint-order: stroke"].join(";")}const O={fontSize:"font-size: {{VALUE}}px",fontFamily:"font-family: {{VALUE}}",fontWeight:"font-weight: {{VALUE}}",fontStyle:"font-style: {{VALUE}}",fontVariant:"font-variant: {{VALUE}}",letterSpacing:"letter-spacing: {{VALUE}}px",align:"text-align: {{VALUE}}",padding:"padding: {{VALUE}}px",whiteSpace:"white-space: {{VALUE}}",lineHeight:"line-height: {{VALUE}}px",wordWrapWidth:"max-width: {{VALUE}}px"},I={fill:n=>`color: ${i.Color.shared.setValue(n).toHex()}`,breakWords:n=>`word-wrap: ${n?"break-all":"break-word"}`,stroke:oe,dropShadow:ae};function Ae(n,e){for(const t in n){const r=n[t],s=[];for(const a in r)I[a]?s.push(I[a](r[a])):O[a]&&s.push(O[a].replace("{{VALUE}}",r[a]));e.push(`${t} { ${s.join(";")} }`)}}class H extends i.TextStyle{constructor(e={}){super(e),this._cssOverrides=[],this.cssOverrides??(this.cssOverrides=e.cssOverrides),this.tagStyles=e.tagStyles??{}}set cssOverrides(e){this._cssOverrides=e instanceof Array?e:[e],this.update()}get cssOverrides(){return this._cssOverrides}_generateKey(){return this._styleKey=i.generateTextStyleKey(this)+this._cssOverrides.join("-"),this._styleKey}update(){this._cssStyle=null,super.update()}clone(){return new H({align:this.align,breakWords:this.breakWords,dropShadow:this.dropShadow?{...this.dropShadow}:null,fill:this._fill,fontFamily:this.fontFamily,fontSize:this.fontSize,fontStyle:this.fontStyle,fontVariant:this.fontVariant,fontWeight:this.fontWeight,letterSpacing:this.letterSpacing,lineHeight:this.lineHeight,padding:this.padding,stroke:this._stroke,whiteSpace:this.whiteSpace,wordWrap:this.wordWrap,wordWrapWidth:this.wordWrapWidth,cssOverrides:this.cssOverrides})}get cssStyle(){return this._cssStyle||(this._cssStyle=ke(this)),this._cssStyle}addOverride(...e){const t=e.filter(r=>!this.cssOverrides.includes(r));t.length>0&&(this.cssOverrides.push(...t),this.update())}removeOverride(...e){const t=e.filter(r=>this.cssOverrides.includes(r));t.length>0&&(this.cssOverrides=this.cssOverrides.filter(r=>!t.includes(r)),this.update())}set fill(e){typeof e!="string"&&typeof e!="number"&&i.warn("[HTMLTextStyle] only color fill is not supported by HTMLText"),super.fill=e}set stroke(e){e&&typeof e!="string"&&typeof e!="number"&&i.warn("[HTMLTextStyle] only color stroke is not supported by HTMLText"),super.stroke=e}}const L="http://www.w3.org/2000/svg",$="http://www.w3.org/1999/xhtml";class le{constructor(){this.svgRoot=document.createElementNS(L,"svg"),this.foreignObject=document.createElementNS(L,"foreignObject"),this.domElement=document.createElementNS($,"div"),this.styleElement=document.createElementNS($,"style"),this.image=new Image;const{foreignObject:e,svgRoot:t,styleElement:r,domElement:s}=this;e.setAttribute("width","10000"),e.setAttribute("height","10000"),e.style.overflow="hidden",t.appendChild(e),e.appendChild(r),e.appendChild(s)}}let Y;function He(n,e,t,r){r=r||Y||(Y=new le);const{domElement:s,styleElement:a,svgRoot:o}=r;s.innerHTML=`<style>${e.cssStyle};</style><div style='padding:0'>${n}</div>`,s.setAttribute("style","transform-origin: top left; display: inline-block"),t&&(a.textContent=t),document.body.appendChild(o);const l=s.getBoundingClientRect();o.remove();const d=i.CanvasTextMetrics.measureFont(e.fontStyle).descent,c=e.padding*2;return{width:l.width-c,height:l.height+d-c}}class de{constructor(e,t){this.state=i.State.for2d(),this._graphicsBatchesHash=Object.create(null),this._destroyRenderableBound=this.destroyRenderable.bind(this),this.renderer=e,this._adaptor=t,this._adaptor.init(),this.renderer.renderableGC.addManagedHash(this,"_graphicsBatchesHash")}validateRenderable(e){const t=e.context,r=!!this._graphicsBatchesHash[e.uid],s=this.renderer.graphicsContext.updateGpuContext(t);return!!(s.isBatchable||r!==s.isBatchable)}addRenderable(e,t){const r=this.renderer.graphicsContext.updateGpuContext(e.context);e.didViewUpdate&&this._rebuild(e),r.isBatchable?this._addToBatcher(e,t):(this.renderer.renderPipes.batch.break(t),t.add(e))}updateRenderable(e){const t=this._graphicsBatchesHash[e.uid];if(t)for(let r=0;r<t.length;r++){const s=t[r];s._batcher.updateElement(s)}}destroyRenderable(e){this._graphicsBatchesHash[e.uid]&&this._removeBatchForRenderable(e.uid),e.off("destroyed",this._destroyRenderableBound)}execute(e){if(!e.isRenderable)return;const t=this.renderer,r=e.context;if(!t.graphicsContext.getGpuContext(r).batches.length)return;const a=r.customShader||this._adaptor.shader;this.state.blendMode=e.groupBlendMode;const o=a.resources.localUniforms.uniforms;o.uTransformMatrix=e.groupTransform,o.uRound=t._roundPixels|e._roundPixels,i.color32BitToUniform(e.groupColorAlpha,o.uColor,0),this._adaptor.execute(this,e)}_rebuild(e){const t=!!this._graphicsBatchesHash[e.uid],r=this.renderer.graphicsContext.updateGpuContext(e.context);t&&this._removeBatchForRenderable(e.uid),r.isBatchable&&this._initBatchesForRenderable(e),e.batched=r.isBatchable}_addToBatcher(e,t){const r=this.renderer.renderPipes.batch,s=this._getBatchesForRenderable(e);for(let a=0;a<s.length;a++){const o=s[a];r.addToBatch(o,t)}}_getBatchesForRenderable(e){return this._graphicsBatchesHash[e.uid]||this._initBatchesForRenderable(e)}_initBatchesForRenderable(e){const t=e.context,r=this.renderer.graphicsContext.getGpuContext(t),s=this.renderer._roundPixels|e._roundPixels,a=r.batches.map(o=>{const l=i.BigPool.get(i.BatchableGraphics);return o.copyTo(l),l.renderable=e,l.roundPixels=s,l});return this._graphicsBatchesHash[e.uid]===void 0&&e.on("destroyed",this._destroyRenderableBound),this._graphicsBatchesHash[e.uid]=a,a}_removeBatchForRenderable(e){this._graphicsBatchesHash[e].forEach(t=>{i.BigPool.return(t)}),this._graphicsBatchesHash[e]=null}destroy(){this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null;for(const e in this._graphicsBatchesHash)this._removeBatchForRenderable(e);this._graphicsBatchesHash=null}}de.extension={type:[i.ExtensionType.WebGLPipes,i.ExtensionType.WebGPUPipes,i.ExtensionType.CanvasPipes],name:"graphics"};const ue=class ce extends A{constructor(...e){super({});let t=e[0]??{};typeof t=="number"&&(i.deprecation(i.v8_0_0,"PlaneGeometry constructor changed please use { width, height, verticesX, verticesY } instead"),t={width:t,height:e[1],verticesX:e[2],verticesY:e[3]}),this.build(t)}build(e){e={...ce.defaultOptions,...e},this.verticesX=this.verticesX??e.verticesX,this.verticesY=this.verticesY??e.verticesY,this.width=this.width??e.width,this.height=this.height??e.height;const t=this.verticesX*this.verticesY,r=[],s=[],a=[],o=this.verticesX-1,l=this.verticesY-1,d=this.width/o,c=this.height/l;for(let u=0;u<t;u++){const f=u%this.verticesX,g=u/this.verticesX|0;r.push(f*d,g*c),s.push(f/o,g/l)}const h=o*l;for(let u=0;u<h;u++){const f=u%o,g=u/o|0,x=g*this.verticesX+f,p=g*this.verticesX+f+1,m=(g+1)*this.verticesX+f,_=(g+1)*this.verticesX+f+1;a.push(x,p,m,p,_,m)}this.buffers[0].data=new Float32Array(r),this.buffers[1].data=new Float32Array(s),this.indexBuffer.data=new Uint32Array(a),this.buffers[0].update(),this.buffers[1].update(),this.indexBuffer.update()}};ue.defaultOptions={width:100,height:100,verticesX:10,verticesY:10};let Ee=ue;class E{constructor(){this.batcherName="default",this.packAsQuad=!1,this.indexOffset=0,this.attributeOffset=0,this.roundPixels=0,this._batcher=null,this._batch=null,this._uvUpdateId=-1,this._textureMatrixUpdateId=-1}get blendMode(){return this.renderable.groupBlendMode}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.geometry=null,this._uvUpdateId=-1,this._textureMatrixUpdateId=-1}get uvs(){const t=this.geometry.getBuffer("aUV"),r=t.data;let s=r;const a=this.texture.textureMatrix;return a.isSimple||(s=this._transformedUvs,(this._textureMatrixUpdateId!==a._updateID||this._uvUpdateId!==t._updateID)&&((!s||s.length<r.length)&&(s=this._transformedUvs=new Float32Array(r.length)),this._textureMatrixUpdateId=a._updateID,this._uvUpdateId=t._updateID,a.multiplyUvs(r,s))),s}get positions(){return this.geometry.positions}get indices(){return this.geometry.indices}get color(){return this.renderable.groupColorAlpha}get groupTransform(){return this.renderable.groupTransform}get attributeSize(){return this.geometry.positions.length/2}get indexSize(){return this.geometry.indices.length}}class he{constructor(e,t){this.localUniforms=new i.UniformGroup({uTransformMatrix:{value:new i.Matrix,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),this.localUniformsBindGroup=new i.BindGroup({0:this.localUniforms}),this._meshDataHash=Object.create(null),this._gpuBatchableMeshHash=Object.create(null),this._destroyRenderableBound=this.destroyRenderable.bind(this),this.renderer=e,this._adaptor=t,this._adaptor.init(),e.renderableGC.addManagedHash(this,"_gpuBatchableMeshHash"),e.renderableGC.addManagedHash(this,"_meshDataHash")}validateRenderable(e){const t=this._getMeshData(e),r=t.batched,s=e.batched;if(t.batched=s,r!==s)return!0;if(s){const a=e._geometry;if(a.indices.length!==t.indexSize||a.positions.length!==t.vertexSize)return t.indexSize=a.indices.length,t.vertexSize=a.positions.length,!0;const o=this._getBatchableMesh(e),l=e.texture;if(o.texture._source!==l._source&&o.texture._source!==l._source)return!o._batcher.checkAndUpdateTexture(o,l)}return!1}addRenderable(e,t){const r=this.renderer.renderPipes.batch,{batched:s}=this._getMeshData(e);if(s){const a=this._getBatchableMesh(e);a.texture=e._texture,a.geometry=e._geometry,r.addToBatch(a,t)}else r.break(t),t.add(e)}updateRenderable(e){if(e.batched){const t=this._gpuBatchableMeshHash[e.uid];t.texture=e._texture,t.geometry=e._geometry,t._batcher.updateElement(t)}}destroyRenderable(e){this._meshDataHash[e.uid]=null;const t=this._gpuBatchableMeshHash[e.uid];t&&(i.BigPool.return(t),this._gpuBatchableMeshHash[e.uid]=null),e.off("destroyed",this._destroyRenderableBound)}execute(e){if(!e.isRenderable)return;e.state.blendMode=i.getAdjustedBlendModeBlend(e.groupBlendMode,e.texture._source);const t=this.localUniforms;t.uniforms.uTransformMatrix=e.groupTransform,t.uniforms.uRound=this.renderer._roundPixels|e._roundPixels,t.update(),i.color32BitToUniform(e.groupColorAlpha,t.uniforms.uColor,0),this._adaptor.execute(this,e)}_getMeshData(e){return this._meshDataHash[e.uid]||this._initMeshData(e)}_initMeshData(e){var t,r;return this._meshDataHash[e.uid]={batched:e.batched,indexSize:(t=e._geometry.indices)==null?void 0:t.length,vertexSize:(r=e._geometry.positions)==null?void 0:r.length},e.on("destroyed",this._destroyRenderableBound),this._meshDataHash[e.uid]}_getBatchableMesh(e){return this._gpuBatchableMeshHash[e.uid]||this._initBatchableMesh(e)}_initBatchableMesh(e){const t=i.BigPool.get(E);return t.renderable=e,t.texture=e._texture,t.transform=e.groupTransform,t.roundPixels=this.renderer._roundPixels|e._roundPixels,this._gpuBatchableMeshHash[e.uid]=t,t}destroy(){for(const e in this._gpuBatchableMeshHash)this._gpuBatchableMeshHash[e]&&i.BigPool.return(this._gpuBatchableMeshHash[e]);this._gpuBatchableMeshHash=null,this._meshDataHash=null,this.localUniforms=null,this.localUniformsBindGroup=null,this._adaptor.destroy(),this._adaptor=null,this.renderer=null}}he.extension={type:[i.ExtensionType.WebGLPipes,i.ExtensionType.WebGPUPipes,i.ExtensionType.CanvasPipes],name:"mesh"};class De{execute(e,t){const r=e.state,s=e.renderer,a=t.shader||e.defaultShader;a.resources.uTexture=t.texture._source,a.resources.uniforms=e.localUniforms;const o=s.gl,l=e.getBuffers(t);s.shader.bind(a),s.state.set(r),s.geometry.bind(l.geometry,a.glProgram);const c=l.geometry.indexBuffer.data.BYTES_PER_ELEMENT===2?o.UNSIGNED_SHORT:o.UNSIGNED_INT;o.drawElements(o.TRIANGLES,t.particleChildren.length*6,c,0)}}class ze{execute(e,t){const r=e.renderer,s=t.shader||e.defaultShader;s.groups[0]=r.renderPipes.uniformBatch.getUniformBindGroup(e.localUniforms,!0),s.groups[1]=r.texture.getTextureBindGroup(t.texture);const a=e.state,o=e.getBuffers(t);r.encoder.draw({geometry:o.geometry,shader:t.shader||e.defaultShader,state:a,size:t.particleChildren.length*6})}}function X(n,e=null){const t=n*6;if(t>65535?e=e||new Uint32Array(t):e=e||new Uint16Array(t),e.length!==t)throw new Error(`Out buffer length is incorrect, got ${e.length} and expected ${t}`);for(let r=0,s=0;r<t;r+=6,s+=4)e[r+0]=s+0,e[r+1]=s+1,e[r+2]=s+2,e[r+3]=s+0,e[r+4]=s+2,e[r+5]=s+3;return e}function We(n){return{dynamicUpdate:j(n,!0),staticUpdate:j(n,!1)}}function j(n,e){const t=[];t.push(`
|
|
|
|
var index = 0;
|
|
|
|
for (let i = 0; i < ps.length; ++i)
|
|
{
|
|
const p = ps[i];
|
|
|
|
`);let r=0;for(const a in n){const o=n[a];if(e!==o.dynamic)continue;t.push(`offset = index + ${r}`),t.push(o.code);const l=i.getAttributeInfoFromFormat(o.format);r+=l.stride/4}t.push(`
|
|
index += stride * 4;
|
|
}
|
|
`),t.unshift(`
|
|
var stride = ${r};
|
|
`);const s=t.join(`
|
|
`);return new Function("ps","f32v","u32v",s)}class Ve{constructor(e){this._size=0,this._generateParticleUpdateCache={};const t=this._size=e.size??1e3,r=e.properties;let s=0,a=0;for(const h in r){const u=r[h],f=i.getAttributeInfoFromFormat(u.format);u.dynamic?a+=f.stride:s+=f.stride}this._dynamicStride=a/4,this._staticStride=s/4,this.staticAttributeBuffer=new i.ViewableBuffer(t*4*s),this.dynamicAttributeBuffer=new i.ViewableBuffer(t*4*a),this.indexBuffer=X(t);const o=new i.Geometry;let l=0,d=0;this._staticBuffer=new i.Buffer({data:new Float32Array(1),label:"static-particle-buffer",shrinkToFit:!1,usage:i.BufferUsage.VERTEX|i.BufferUsage.COPY_DST}),this._dynamicBuffer=new i.Buffer({data:new Float32Array(1),label:"dynamic-particle-buffer",shrinkToFit:!1,usage:i.BufferUsage.VERTEX|i.BufferUsage.COPY_DST});for(const h in r){const u=r[h],f=i.getAttributeInfoFromFormat(u.format);u.dynamic?(o.addAttribute(u.attributeName,{buffer:this._dynamicBuffer,stride:this._dynamicStride*4,offset:l*4,format:u.format}),l+=f.size):(o.addAttribute(u.attributeName,{buffer:this._staticBuffer,stride:this._staticStride*4,offset:d*4,format:u.format}),d+=f.size)}o.addIndex(this.indexBuffer);const c=this.getParticleUpdate(r);this._dynamicUpload=c.dynamicUpdate,this._staticUpload=c.staticUpdate,this.geometry=o}getParticleUpdate(e){const t=Oe(e);return this._generateParticleUpdateCache[t]?this._generateParticleUpdateCache[t]:(this._generateParticleUpdateCache[t]=this.generateParticleUpdate(e),this._generateParticleUpdateCache[t])}generateParticleUpdate(e){return We(e)}update(e,t){e.length>this._size&&(t=!0,this._size=Math.max(e.length,this._size*1.5|0),this.staticAttributeBuffer=new i.ViewableBuffer(this._size*this._staticStride*4*4),this.dynamicAttributeBuffer=new i.ViewableBuffer(this._size*this._dynamicStride*4*4),this.indexBuffer=X(this._size),this.geometry.indexBuffer.setDataWithSize(this.indexBuffer,this.indexBuffer.byteLength,!0));const r=this.dynamicAttributeBuffer;if(this._dynamicUpload(e,r.float32View,r.uint32View),this._dynamicBuffer.setDataWithSize(this.dynamicAttributeBuffer.float32View,e.length*this._dynamicStride*4,!0),t){const s=this.staticAttributeBuffer;this._staticUpload(e,s.float32View,s.uint32View),this._staticBuffer.setDataWithSize(s.float32View,e.length*this._staticStride*4,!0)}}destroy(){this._staticBuffer.destroy(),this._dynamicBuffer.destroy(),this.geometry.destroy()}}function Oe(n){const e=[];for(const t in n){const r=n[t];e.push(t,r.code,r.dynamic?"d":"s")}return e.join("_")}var Ie=`varying vec2 vUV;
|
|
varying vec4 vColor;
|
|
|
|
uniform sampler2D uTexture;
|
|
|
|
void main(void){
|
|
vec4 color = texture2D(uTexture, vUV) * vColor;
|
|
gl_FragColor = color;
|
|
}`,Le=`attribute vec2 aVertex;
|
|
attribute vec2 aUV;
|
|
attribute vec4 aColor;
|
|
|
|
attribute vec2 aPosition;
|
|
attribute float aRotation;
|
|
|
|
uniform mat3 uTranslationMatrix;
|
|
uniform float uRound;
|
|
uniform vec2 uResolution;
|
|
uniform vec4 uColor;
|
|
|
|
varying vec2 vUV;
|
|
varying vec4 vColor;
|
|
|
|
vec2 roundPixels(vec2 position, vec2 targetSize)
|
|
{
|
|
return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
|
|
}
|
|
|
|
void main(void){
|
|
float cosRotation = cos(aRotation);
|
|
float sinRotation = sin(aRotation);
|
|
float x = aVertex.x * cosRotation - aVertex.y * sinRotation;
|
|
float y = aVertex.x * sinRotation + aVertex.y * cosRotation;
|
|
|
|
vec2 v = vec2(x, y);
|
|
v = v + aPosition;
|
|
|
|
gl_Position = vec4((uTranslationMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);
|
|
|
|
if(uRound == 1.0)
|
|
{
|
|
gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
|
|
}
|
|
|
|
vUV = aUV;
|
|
vColor = aColor * uColor;
|
|
}
|
|
`,K=`
|
|
struct ParticleUniforms {
|
|
uProjectionMatrix:mat3x3<f32>,
|
|
uResolution:vec2<f32>,
|
|
uRoundPixels:f32,
|
|
};
|
|
|
|
@group(0) @binding(0) var<uniform> uniforms: ParticleUniforms;
|
|
|
|
@group(1) @binding(0) var uTexture: texture_2d<f32>;
|
|
@group(1) @binding(1) var uSampler : sampler;
|
|
|
|
struct VSOutput {
|
|
@builtin(position) position: vec4<f32>,
|
|
@location(0) uv : vec2<f32>,
|
|
@location(1) color : vec4<f32>,
|
|
};
|
|
@vertex
|
|
fn mainVertex(
|
|
@location(0) aVertex: vec2<f32>,
|
|
@location(1) aPosition: vec2<f32>,
|
|
@location(2) aUV: vec2<f32>,
|
|
@location(3) aColor: vec4<f32>,
|
|
@location(4) aRotation: f32,
|
|
) -> VSOutput {
|
|
|
|
let v = vec2(
|
|
aVertex.x * cos(aRotation) - aVertex.y * sin(aRotation),
|
|
aVertex.x * sin(aRotation) + aVertex.y * cos(aRotation)
|
|
) + aPosition;
|
|
|
|
let position = vec4((uniforms.uProjectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);
|
|
|
|
return VSOutput(
|
|
position,
|
|
aUV,
|
|
aColor,
|
|
);
|
|
}
|
|
|
|
@fragment
|
|
fn mainFragment(
|
|
@location(0) uv: vec2<f32>,
|
|
@location(1) color: vec4<f32>,
|
|
@builtin(position) position: vec4<f32>,
|
|
) -> @location(0) vec4<f32> {
|
|
|
|
var sample = textureSample(uTexture, uSampler, uv) * color;
|
|
|
|
return sample;
|
|
}`;class $e extends i.Shader{constructor(){const e=i.GlProgram.from({vertex:Le,fragment:Ie}),t=i.GpuProgram.from({fragment:{source:K,entryPoint:"mainFragment"},vertex:{source:K,entryPoint:"mainVertex"}});super({glProgram:e,gpuProgram:t,resources:{uTexture:i.Texture.WHITE.source,uSampler:new i.TextureStyle({}),uniforms:{uTranslationMatrix:{value:new i.Matrix,type:"mat3x3<f32>"},uColor:{value:new i.Color(16777215),type:"vec4<f32>"},uRound:{value:1,type:"f32"},uResolution:{value:[0,0],type:"vec2<f32>"}}}})}}class fe{constructor(e,t){this.state=i.State.for2d(),this._gpuBufferHash=Object.create(null),this._destroyRenderableBound=this.destroyRenderable.bind(this),this.localUniforms=new i.UniformGroup({uTranslationMatrix:{value:new i.Matrix,type:"mat3x3<f32>"},uColor:{value:new Float32Array(4),type:"vec4<f32>"},uRound:{value:1,type:"f32"},uResolution:{value:[0,0],type:"vec2<f32>"}}),this.renderer=e,this.adaptor=t,this.defaultShader=new $e,this.state=i.State.for2d()}validateRenderable(e){return!1}addRenderable(e,t){this.renderer.renderPipes.batch.break(t),t.add(e)}getBuffers(e){return this._gpuBufferHash[e.uid]||this._initBuffer(e)}_initBuffer(e){return this._gpuBufferHash[e.uid]=new Ve({size:e.particleChildren.length,properties:e._properties}),e.on("destroyed",this._destroyRenderableBound),this._gpuBufferHash[e.uid]}updateRenderable(e){}destroyRenderable(e){this._gpuBufferHash[e.uid].destroy(),this._gpuBufferHash[e.uid]=null,e.off("destroyed",this._destroyRenderableBound)}execute(e){const t=e.particleChildren;if(t.length===0)return;const r=this.renderer,s=this.getBuffers(e);e.texture||(e.texture=t[0].texture);const a=this.state;s.update(t,e._childrenDirty),e._childrenDirty=!1,a.blendMode=i.getAdjustedBlendModeBlend(e.blendMode,e.texture._source);const o=this.localUniforms.uniforms,l=o.uTranslationMatrix;e.worldTransform.copyTo(l),l.prepend(r.globalUniforms.globalUniformData.projectionMatrix),o.uResolution=r.globalUniforms.globalUniformData.resolution,o.uRound=r._roundPixels|e._roundPixels,i.color32BitToUniform(e.groupColorAlpha,o.uColor,0),this.adaptor.execute(this,e)}destroy(){this.defaultShader&&(this.defaultShader.destroy(),this.defaultShader=null)}}class pe extends fe{constructor(e){super(e,new De)}}pe.extension={type:[i.ExtensionType.WebGLPipes],name:"particle"};class ge extends fe{constructor(e){super(e,new ze)}}ge.extension={type:[i.ExtensionType.WebGPUPipes],name:"particle"};const xe=class me extends Ee{constructor(e={}){e={...me.defaultOptions,...e},super({width:e.width,height:e.height,verticesX:4,verticesY:4}),this.update(e)}update(e){this.width=e.width??this.width,this.height=e.height??this.height,this._originalWidth=e.originalWidth??this._originalWidth,this._originalHeight=e.originalHeight??this._originalHeight,this._leftWidth=e.leftWidth??this._leftWidth,this._rightWidth=e.rightWidth??this._rightWidth,this._topHeight=e.topHeight??this._topHeight,this._bottomHeight=e.bottomHeight??this._bottomHeight,this.updateUvs(),this.updatePositions()}updatePositions(){const e=this.positions,t=this._leftWidth+this._rightWidth,r=this.width>t?1:this.width/t,s=this._topHeight+this._bottomHeight,a=this.height>s?1:this.height/s,o=Math.min(r,a);e[9]=e[11]=e[13]=e[15]=this._topHeight*o,e[17]=e[19]=e[21]=e[23]=this.height-this._bottomHeight*o,e[25]=e[27]=e[29]=e[31]=this.height,e[2]=e[10]=e[18]=e[26]=this._leftWidth*o,e[4]=e[12]=e[20]=e[28]=this.width-this._rightWidth*o,e[6]=e[14]=e[22]=e[30]=this.width,this.getBuffer("aPosition").update()}updateUvs(){const e=this.uvs;e[0]=e[8]=e[16]=e[24]=0,e[1]=e[3]=e[5]=e[7]=0,e[6]=e[14]=e[22]=e[30]=1,e[25]=e[27]=e[29]=e[31]=1;const t=1/this._originalWidth,r=1/this._originalHeight;e[2]=e[10]=e[18]=e[26]=t*this._leftWidth,e[9]=e[11]=e[13]=e[15]=r*this._topHeight,e[4]=e[12]=e[20]=e[28]=1-t*this._rightWidth,e[17]=e[19]=e[21]=e[23]=1-r*this._bottomHeight,this.getBuffer("aUV").update()}};xe.defaultOptions={width:100,height:100,leftWidth:10,topHeight:10,rightWidth:10,bottomHeight:10,originalWidth:100,originalHeight:100};let Ye=xe;class _e{constructor(e){this._gpuSpriteHash=Object.create(null),this._destroyRenderableBound=this.destroyRenderable.bind(this),this._renderer=e,this._renderer.renderableGC.addManagedHash(this,"_gpuSpriteHash")}addRenderable(e,t){const r=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,r),this._renderer.renderPipes.batch.addToBatch(r,t)}updateRenderable(e){const t=this._gpuSpriteHash[e.uid];e.didViewUpdate&&this._updateBatchableSprite(e,t),t._batcher.updateElement(t)}validateRenderable(e){const t=e._texture,r=this._getGpuSprite(e);return r.texture._source!==t._source?!r._batcher.checkAndUpdateTexture(r,t):!1}destroyRenderable(e){const t=this._gpuSpriteHash[e.uid];i.BigPool.return(t.geometry),i.BigPool.return(t),this._gpuSpriteHash[e.uid]=null,e.off("destroyed",this._destroyRenderableBound)}_updateBatchableSprite(e,t){t.geometry.update(e),t.texture=e._texture}_getGpuSprite(e){return this._gpuSpriteHash[e.uid]||this._initGPUSprite(e)}_initGPUSprite(e){const t=i.BigPool.get(E);return t.geometry=i.BigPool.get(Ye),t.renderable=e,t.transform=e.groupTransform,t.texture=e._texture,t.roundPixels=this._renderer._roundPixels|e._roundPixels,this._gpuSpriteHash[e.uid]=t,e.on("destroyed",this._destroyRenderableBound),t}destroy(){for(const e in this._gpuSpriteHash)this._gpuSpriteHash[e].geometry.destroy();this._gpuSpriteHash=null,this._renderer=null}}_e.extension={type:[i.ExtensionType.WebGLPipes,i.ExtensionType.WebGPUPipes,i.ExtensionType.CanvasPipes],name:"nineSliceSprite"};const Xe={name:"tiling-bit",vertex:{header:`
|
|
struct TilingUniforms {
|
|
uMapCoord:mat3x3<f32>,
|
|
uClampFrame:vec4<f32>,
|
|
uClampOffset:vec2<f32>,
|
|
uTextureTransform:mat3x3<f32>,
|
|
uSizeAnchor:vec4<f32>
|
|
};
|
|
|
|
@group(2) @binding(0) var<uniform> tilingUniforms: TilingUniforms;
|
|
@group(2) @binding(1) var uTexture: texture_2d<f32>;
|
|
@group(2) @binding(2) var uSampler: sampler;
|
|
`,main:`
|
|
uv = (tilingUniforms.uTextureTransform * vec3(uv, 1.0)).xy;
|
|
|
|
position = (position - tilingUniforms.uSizeAnchor.zw) * tilingUniforms.uSizeAnchor.xy;
|
|
`},fragment:{header:`
|
|
struct TilingUniforms {
|
|
uMapCoord:mat3x3<f32>,
|
|
uClampFrame:vec4<f32>,
|
|
uClampOffset:vec2<f32>,
|
|
uTextureTransform:mat3x3<f32>,
|
|
uSizeAnchor:vec4<f32>
|
|
};
|
|
|
|
@group(2) @binding(0) var<uniform> tilingUniforms: TilingUniforms;
|
|
@group(2) @binding(1) var uTexture: texture_2d<f32>;
|
|
@group(2) @binding(2) var uSampler: sampler;
|
|
`,main:`
|
|
|
|
var coord = vUV + ceil(tilingUniforms.uClampOffset - vUV);
|
|
coord = (tilingUniforms.uMapCoord * vec3(coord, 1.0)).xy;
|
|
var unclamped = coord;
|
|
coord = clamp(coord, tilingUniforms.uClampFrame.xy, tilingUniforms.uClampFrame.zw);
|
|
|
|
var bias = 0.;
|
|
|
|
if(unclamped.x == coord.x && unclamped.y == coord.y)
|
|
{
|
|
bias = -32.;
|
|
}
|
|
|
|
outColor = textureSampleBias(uTexture, uSampler, coord, bias);
|
|
`}},je={name:"tiling-bit",vertex:{header:`
|
|
uniform mat3 uTextureTransform;
|
|
uniform vec4 uSizeAnchor;
|
|
|
|
`,main:`
|
|
uv = (uTextureTransform * vec3(aUV, 1.0)).xy;
|
|
|
|
position = (position - uSizeAnchor.zw) * uSizeAnchor.xy;
|
|
`},fragment:{header:`
|
|
uniform sampler2D uTexture;
|
|
uniform mat3 uMapCoord;
|
|
uniform vec4 uClampFrame;
|
|
uniform vec2 uClampOffset;
|
|
`,main:`
|
|
|
|
vec2 coord = vUV + ceil(uClampOffset - vUV);
|
|
coord = (uMapCoord * vec3(coord, 1.0)).xy;
|
|
vec2 unclamped = coord;
|
|
coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);
|
|
|
|
outColor = texture(uTexture, coord, unclamped == coord ? 0.0 : -32.0);// lod-bias very negative to force lod 0
|
|
|
|
`}};let U,G;class Ke extends i.Shader{constructor(){U??(U=i.compileHighShaderGpuProgram({name:"tiling-sprite-shader",bits:[i.localUniformBit,Xe,i.roundPixelsBit]})),G??(G=i.compileHighShaderGlProgram({name:"tiling-sprite-shader",bits:[i.localUniformBitGl,je,i.roundPixelsBitGl]}));const e=new i.UniformGroup({uMapCoord:{value:new i.Matrix,type:"mat3x3<f32>"},uClampFrame:{value:new Float32Array([0,0,1,1]),type:"vec4<f32>"},uClampOffset:{value:new Float32Array([0,0]),type:"vec2<f32>"},uTextureTransform:{value:new i.Matrix,type:"mat3x3<f32>"},uSizeAnchor:{value:new Float32Array([100,100,.5,.5]),type:"vec4<f32>"}});super({glProgram:G,gpuProgram:U,resources:{localUniforms:new i.UniformGroup({uTransformMatrix:{value:new i.Matrix,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),tilingUniforms:e,uTexture:i.Texture.EMPTY.source,uSampler:i.Texture.EMPTY.source.style}})}updateUniforms(e,t,r,s,a,o){const l=this.resources.tilingUniforms,d=o.width,c=o.height,h=o.textureMatrix,u=l.uniforms.uTextureTransform;u.set(r.a*d/e,r.b*d/t,r.c*c/e,r.d*c/t,r.tx/e,r.ty/t),u.invert(),l.uniforms.uMapCoord=h.mapCoord,l.uniforms.uClampFrame=h.uClampFrame,l.uniforms.uClampOffset=h.uClampOffset,l.uniforms.uTextureTransform=u,l.uniforms.uSizeAnchor[0]=e,l.uniforms.uSizeAnchor[1]=t,l.uniforms.uSizeAnchor[2]=s,l.uniforms.uSizeAnchor[3]=a,o&&(this.resources.uTexture=o.source,this.resources.uSampler=o.source.style)}}class Ne extends A{constructor(){super({positions:new Float32Array([0,0,1,0,1,1,0,1]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),indices:new Uint32Array([0,1,2,0,2,3])})}}function qe(n,e){const t=n.anchor.x,r=n.anchor.y;e[0]=-t*n.width,e[1]=-r*n.height,e[2]=(1-t)*n.width,e[3]=-r*n.height,e[4]=(1-t)*n.width,e[5]=(1-r)*n.height,e[6]=-t*n.width,e[7]=(1-r)*n.height}function Qe(n,e,t,r){let s=0;const a=n.length/e,o=r.a,l=r.b,d=r.c,c=r.d,h=r.tx,u=r.ty;for(t*=e;s<a;){const f=n[t],g=n[t+1];n[t]=o*f+d*g+h,n[t+1]=l*f+c*g+u,t+=e,s++}}function Je(n,e){const t=n.texture,r=t.frame.width,s=t.frame.height;let a=0,o=0;n._applyAnchorToTexture&&(a=n.anchor.x,o=n.anchor.y),e[0]=e[6]=-a,e[2]=e[4]=1-a,e[1]=e[3]=-o,e[5]=e[7]=1-o;const l=i.Matrix.shared;l.copyFrom(n._tileTransform.matrix),l.tx/=n.width,l.ty/=n.height,l.invert(),l.scale(n.width/r,n.height/s),Qe(e,2,0,l)}const P=new Ne;class be{constructor(e){this._state=i.State.default2d,this._tilingSpriteDataHash=Object.create(null),this._destroyRenderableBound=this.destroyRenderable.bind(this),this._renderer=e,this._renderer.renderableGC.addManagedHash(this,"_tilingSpriteDataHash")}validateRenderable(e){const t=this._getTilingSpriteData(e),r=t.canBatch;this._updateCanBatch(e);const s=t.canBatch;if(s&&s===r){const{batchableMesh:a}=t;if(a&&a.texture._source!==e.texture._source)return!a._batcher.checkAndUpdateTexture(a,e.texture)}return r!==s}addRenderable(e,t){const r=this._renderer.renderPipes.batch;this._updateCanBatch(e);const s=this._getTilingSpriteData(e),{geometry:a,canBatch:o}=s;if(o){s.batchableMesh||(s.batchableMesh=new E);const l=s.batchableMesh;e.didViewUpdate&&(this._updateBatchableMesh(e),l.geometry=a,l.renderable=e,l.transform=e.groupTransform,l.texture=e._texture),l.roundPixels=this._renderer._roundPixels|e._roundPixels,r.addToBatch(l,t)}else r.break(t),s.shader||(s.shader=new Ke),this.updateRenderable(e),t.add(e)}execute(e){const{shader:t}=this._tilingSpriteDataHash[e.uid];t.groups[0]=this._renderer.globalUniforms.bindGroup;const r=t.resources.localUniforms.uniforms;r.uTransformMatrix=e.groupTransform,r.uRound=this._renderer._roundPixels|e._roundPixels,i.color32BitToUniform(e.groupColorAlpha,r.uColor,0),this._state.blendMode=i.getAdjustedBlendModeBlend(e.groupBlendMode,e.texture._source),this._renderer.encoder.draw({geometry:P,shader:t,state:this._state})}updateRenderable(e){const t=this._getTilingSpriteData(e),{canBatch:r}=t;if(r){const{batchableMesh:s}=t;e.didViewUpdate&&this._updateBatchableMesh(e),s._batcher.updateElement(s)}else if(e.didViewUpdate){const{shader:s}=t;s.updateUniforms(e.width,e.height,e._tileTransform.matrix,e.anchor.x,e.anchor.y,e.texture)}}destroyRenderable(e){var r;const t=this._getTilingSpriteData(e);t.batchableMesh=null,(r=t.shader)==null||r.destroy(),this._tilingSpriteDataHash[e.uid]=null,e.off("destroyed",this._destroyRenderableBound)}_getTilingSpriteData(e){return this._tilingSpriteDataHash[e.uid]||this._initTilingSpriteData(e)}_initTilingSpriteData(e){const t=new A({indices:P.indices,positions:P.positions.slice(),uvs:P.uvs.slice()});return this._tilingSpriteDataHash[e.uid]={canBatch:!0,renderable:e,geometry:t},e.on("destroyed",this._destroyRenderableBound),this._tilingSpriteDataHash[e.uid]}_updateBatchableMesh(e){const t=this._getTilingSpriteData(e),{geometry:r}=t,s=e.texture.source.style;s.addressMode!=="repeat"&&(s.addressMode="repeat",s.update()),Je(e,r.uvs),qe(e,r.positions)}destroy(){for(const e in this._tilingSpriteDataHash)this.destroyRenderable(this._tilingSpriteDataHash[e].renderable);this._tilingSpriteDataHash=null,this._renderer=null}_updateCanBatch(e){const t=this._getTilingSpriteData(e),r=e.texture;let s=!0;return this._renderer.type===i.RendererType.WEBGL&&(s=this._renderer.context.supports.nonPowOf2wrapping),t.canBatch=r.textureMatrix.isSimple&&(s||r.source.isPowerOfTwo),t.canBatch}}be.extension={type:[i.ExtensionType.WebGLPipes,i.ExtensionType.WebGPUPipes,i.ExtensionType.CanvasPipes],name:"tilingSprite"};const Ze={name:"local-uniform-msdf-bit",vertex:{header:`
|
|
struct LocalUniforms {
|
|
uColor:vec4<f32>,
|
|
uTransformMatrix:mat3x3<f32>,
|
|
uDistance: f32,
|
|
uRound:f32,
|
|
}
|
|
|
|
@group(2) @binding(0) var<uniform> localUniforms : LocalUniforms;
|
|
`,main:`
|
|
vColor *= localUniforms.uColor;
|
|
modelMatrix *= localUniforms.uTransformMatrix;
|
|
`,end:`
|
|
if(localUniforms.uRound == 1)
|
|
{
|
|
vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw);
|
|
}
|
|
`},fragment:{header:`
|
|
struct LocalUniforms {
|
|
uColor:vec4<f32>,
|
|
uTransformMatrix:mat3x3<f32>,
|
|
uDistance: f32
|
|
}
|
|
|
|
@group(2) @binding(0) var<uniform> localUniforms : LocalUniforms;
|
|
`,main:`
|
|
outColor = vec4<f32>(calculateMSDFAlpha(outColor, localUniforms.uColor, localUniforms.uDistance));
|
|
`}},et={name:"local-uniform-msdf-bit",vertex:{header:`
|
|
uniform mat3 uTransformMatrix;
|
|
uniform vec4 uColor;
|
|
uniform float uRound;
|
|
`,main:`
|
|
vColor *= uColor;
|
|
modelMatrix *= uTransformMatrix;
|
|
`,end:`
|
|
if(uRound == 1.)
|
|
{
|
|
gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
|
|
}
|
|
`},fragment:{header:`
|
|
uniform float uDistance;
|
|
`,main:`
|
|
outColor = vec4(calculateMSDFAlpha(outColor, vColor, uDistance));
|
|
`}},tt={name:"msdf-bit",fragment:{header:`
|
|
fn calculateMSDFAlpha(msdfColor:vec4<f32>, shapeColor:vec4<f32>, distance:f32) -> f32 {
|
|
|
|
// MSDF
|
|
var median = msdfColor.r + msdfColor.g + msdfColor.b -
|
|
min(msdfColor.r, min(msdfColor.g, msdfColor.b)) -
|
|
max(msdfColor.r, max(msdfColor.g, msdfColor.b));
|
|
|
|
// SDF
|
|
median = min(median, msdfColor.a);
|
|
|
|
var screenPxDistance = distance * (median - 0.5);
|
|
var alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0);
|
|
if (median < 0.01) {
|
|
alpha = 0.0;
|
|
} else if (median > 0.99) {
|
|
alpha = 1.0;
|
|
}
|
|
|
|
// Gamma correction for coverage-like alpha
|
|
var luma: f32 = dot(shapeColor.rgb, vec3<f32>(0.299, 0.587, 0.114));
|
|
var gamma: f32 = mix(1.0, 1.0 / 2.2, luma);
|
|
var coverage: f32 = pow(shapeColor.a * alpha, gamma);
|
|
|
|
return coverage;
|
|
|
|
}
|
|
`}},rt={name:"msdf-bit",fragment:{header:`
|
|
float calculateMSDFAlpha(vec4 msdfColor, vec4 shapeColor, float distance) {
|
|
|
|
// MSDF
|
|
float median = msdfColor.r + msdfColor.g + msdfColor.b -
|
|
min(msdfColor.r, min(msdfColor.g, msdfColor.b)) -
|
|
max(msdfColor.r, max(msdfColor.g, msdfColor.b));
|
|
|
|
// SDF
|
|
median = min(median, msdfColor.a);
|
|
|
|
float screenPxDistance = distance * (median - 0.5);
|
|
float alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0);
|
|
|
|
if (median < 0.01) {
|
|
alpha = 0.0;
|
|
} else if (median > 0.99) {
|
|
alpha = 1.0;
|
|
}
|
|
|
|
// Gamma correction for coverage-like alpha
|
|
float luma = dot(shapeColor.rgb, vec3(0.299, 0.587, 0.114));
|
|
float gamma = mix(1.0, 1.0 / 2.2, luma);
|
|
float coverage = pow(shapeColor.a * alpha, gamma);
|
|
|
|
return coverage;
|
|
}
|
|
`}};let F,k;class it extends i.Shader{constructor(){const e=new i.UniformGroup({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new i.Matrix,type:"mat3x3<f32>"},uDistance:{value:4,type:"f32"},uRound:{value:0,type:"f32"}}),t=i.getMaxTexturesPerBatch();F??(F=i.compileHighShaderGpuProgram({name:"sdf-shader",bits:[i.colorBit,i.generateTextureBatchBit(t),Ze,tt,i.roundPixelsBit]})),k??(k=i.compileHighShaderGlProgram({name:"sdf-shader",bits:[i.colorBitGl,i.generateTextureBatchBitGl(t),et,rt,i.roundPixelsBitGl]})),super({glProgram:k,gpuProgram:F,resources:{localUniforms:e,batchSamplers:i.getBatchSamplersUniformGroup(t)}})}}class ye{constructor(e){this._gpuBitmapText={},this._destroyRenderableBound=this.destroyRenderable.bind(this),this._renderer=e,this._renderer.renderableGC.addManagedHash(this,"_gpuBitmapText")}validateRenderable(e){const t=this._getGpuBitmapText(e);return e._didTextUpdate&&(e._didTextUpdate=!1,this._updateContext(e,t)),this._renderer.renderPipes.graphics.validateRenderable(t)}addRenderable(e,t){const r=this._getGpuBitmapText(e);N(e,r),e._didTextUpdate&&(e._didTextUpdate=!1,this._updateContext(e,r)),this._renderer.renderPipes.graphics.addRenderable(r,t),r.context.customShader&&this._updateDistanceField(e)}destroyRenderable(e){e.off("destroyed",this._destroyRenderableBound),this._destroyRenderableByUid(e.uid)}_destroyRenderableByUid(e){const t=this._gpuBitmapText[e].context;t.customShader&&(i.BigPool.return(t.customShader),t.customShader=null),i.BigPool.return(this._gpuBitmapText[e]),this._gpuBitmapText[e]=null}updateRenderable(e){const t=this._getGpuBitmapText(e);N(e,t),this._renderer.renderPipes.graphics.updateRenderable(t),t.context.customShader&&this._updateDistanceField(e)}_updateContext(e,t){const{context:r}=t,s=i.BitmapFontManager.getFont(e.text,e._style);r.clear(),s.distanceField.type!=="none"&&(r.customShader||(r.customShader=i.BigPool.get(it)));const a=Array.from(e.text),o=e._style;let l=s.baseLineOffset;const d=i.getBitmapTextLayout(a,o,s,!0);let c=0;const h=o.padding,u=d.scale;let f=d.width,g=d.height+d.offsetY;o._stroke&&(f+=o._stroke.width/u,g+=o._stroke.width/u),r.translate(-e._anchor._x*f-h,-e._anchor._y*g-h).scale(u,u);const x=s.applyFillAsTint?o._fill.color:16777215;for(let p=0;p<d.lines.length;p++){const m=d.lines[p];for(let _=0;_<m.charPositions.length;_++){const v=a[c++],b=s.chars[v];b!=null&&b.texture&&r.texture(b.texture,x||"black",Math.round(m.charPositions[_]+b.xOffset),Math.round(l+b.yOffset))}l+=s.lineHeight}}_getGpuBitmapText(e){return this._gpuBitmapText[e.uid]||this.initGpuText(e)}initGpuText(e){const t=i.BigPool.get(R);return this._gpuBitmapText[e.uid]=t,this._updateContext(e,t),e.on("destroyed",this._destroyRenderableBound),this._gpuBitmapText[e.uid]}_updateDistanceField(e){const t=this._getGpuBitmapText(e).context,r=e._style.fontFamily,s=i.Cache.get(`${r}-bitmap`),{a,b:o,c:l,d}=e.groupTransform,c=Math.sqrt(a*a+o*o),h=Math.sqrt(l*l+d*d),u=(Math.abs(c)+Math.abs(h))/2,f=s.baseRenderedFontSize/e._style.fontSize,g=u*s.distanceField.range*(1/f);t.customShader.resources.localUniforms.uniforms.uDistance=g}destroy(){for(const e in this._gpuBitmapText)this._destroyRenderableByUid(e);this._gpuBitmapText=null,this._renderer=null}}ye.extension={type:[i.ExtensionType.WebGLPipes,i.ExtensionType.WebGPUPipes,i.ExtensionType.CanvasPipes],name:"bitmapText"};function N(n,e){e.groupTransform=n.groupTransform,e.groupColorAlpha=n.groupColorAlpha,e.groupColor=n.groupColor,e.groupBlendMode=n.groupBlendMode,e.globalDisplayStatus=n.globalDisplayStatus,e.groupTransform=n.groupTransform,e.localDisplayStatus=n.localDisplayStatus,e.groupAlpha=n.groupAlpha,e._roundPixels=n._roundPixels}class Te{constructor(e){this._gpuText=Object.create(null),this._destroyRenderableBound=this.destroyRenderable.bind(this),this._renderer=e,this._renderer.runners.resolutionChange.add(this),this._renderer.renderableGC.addManagedHash(this,"_gpuText")}resolutionChange(){for(const e in this._gpuText){const t=this._gpuText[e];if(!t)continue;const r=t.batchableSprite.renderable;r._autoResolution&&(r._resolution=this._renderer.resolution,r.onViewUpdate())}}validateRenderable(e){const t=this._getGpuText(e),r=e._getKey();return t.textureNeedsUploading?(t.textureNeedsUploading=!1,!0):t.currentKey!==r}addRenderable(e,t){const s=this._getGpuText(e).batchableSprite;e._didTextUpdate&&this._updateText(e),this._renderer.renderPipes.batch.addToBatch(s,t)}updateRenderable(e){const r=this._getGpuText(e).batchableSprite;e._didTextUpdate&&this._updateText(e),r._batcher.updateElement(r)}destroyRenderable(e){e.off("destroyed",this._destroyRenderableBound),this._destroyRenderableById(e.uid)}_destroyRenderableById(e){const t=this._gpuText[e];this._renderer.htmlText.decreaseReferenceCount(t.currentKey),i.BigPool.return(t.batchableSprite),this._gpuText[e]=null}_updateText(e){const t=e._getKey(),r=this._getGpuText(e),s=r.batchableSprite;r.currentKey!==t&&this._updateGpuText(e).catch(o=>{console.error(o)}),e._didTextUpdate=!1;const a=e._style.padding;i.updateQuadBounds(s.bounds,e._anchor,s.texture,a)}async _updateGpuText(e){e._didTextUpdate=!1;const t=this._getGpuText(e);if(t.generatingTexture)return;const r=e._getKey();this._renderer.htmlText.decreaseReferenceCount(t.currentKey),t.generatingTexture=!0,t.currentKey=r;const s=e.resolution??this._renderer.resolution,a=await this._renderer.htmlText.getManagedTexture(e.text,s,e._style,e._getKey()),o=t.batchableSprite;o.texture=t.texture=a,t.generatingTexture=!1,t.textureNeedsUploading=!0,e.onViewUpdate();const l=e._style.padding;i.updateQuadBounds(o.bounds,e._anchor,o.texture,l)}_getGpuText(e){return this._gpuText[e.uid]||this.initGpuText(e)}initGpuText(e){const t={texture:i.Texture.EMPTY,currentKey:"--",batchableSprite:i.BigPool.get(i.BatchableSprite),textureNeedsUploading:!1,generatingTexture:!1},r=t.batchableSprite;return r.renderable=e,r.transform=e.groupTransform,r.texture=i.Texture.EMPTY,r.bounds={minX:0,maxX:1,minY:0,maxY:0},r.roundPixels=this._renderer._roundPixels|e._roundPixels,e._resolution=e._autoResolution?this._renderer.resolution:e.resolution,this._gpuText[e.uid]=t,e.on("destroyed",this._destroyRenderableBound),t}destroy(){for(const e in this._gpuText)this._destroyRenderableById(e);this._gpuText=null,this._renderer=null}}Te.extension={type:[i.ExtensionType.WebGLPipes,i.ExtensionType.WebGPUPipes,i.ExtensionType.CanvasPipes],name:"htmlText"};function st(){const{userAgent:n}=i.DOMAdapter.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(n)}const nt=new i.Bounds;function ve(n,e,t,r){const s=nt;s.minX=0,s.minY=0,s.maxX=n.width/r|0,s.maxY=n.height/r|0;const a=i.TexturePool.getOptimalTexture(s.width,s.height,r,!1);return a.source.uploadMethodId="image",a.source.resource=n,a.source.alphaMode="premultiply-alpha-on-upload",a.frame.width=e/r,a.frame.height=t/r,a.source.emit("update",a.source),a.updateUvs(),a}function at(n,e){const t=e.fontFamily,r=[],s={},a=/font-family:([^;"\s]+)/g,o=n.match(a);function l(d){s[d]||(r.push(d),s[d]=!0)}if(Array.isArray(t))for(let d=0;d<t.length;d++)l(t[d]);else l(t);o&&o.forEach(d=>{const c=d.split(":")[1].trim();l(c)});for(const d in e.tagStyles){const c=e.tagStyles[d].fontFamily;l(c)}return r}async function ot(n){const t=await(await i.DOMAdapter.get().fetch(n)).blob(),r=new FileReader;return await new Promise((a,o)=>{r.onloadend=()=>a(r.result),r.onerror=o,r.readAsDataURL(t)})}async function q(n,e){const t=await ot(e);return`@font-face {
|
|
font-family: "${n.fontFamily}";
|
|
src: url('${t}');
|
|
font-weight: ${n.fontWeight};
|
|
font-style: ${n.fontStyle};
|
|
}`}const M=new Map;async function lt(n,e,t){const r=n.filter(s=>i.Cache.has(`${s}-and-url`)).map((s,a)=>{if(!M.has(s)){const{url:o}=i.Cache.get(`${s}-and-url`);a===0?M.set(s,q({fontWeight:e.fontWeight,fontStyle:e.fontStyle,fontFamily:s},o)):M.set(s,q({fontWeight:t.fontWeight,fontStyle:t.fontStyle,fontFamily:s},o))}return M.get(s)});return(await Promise.all(r)).join(`
|
|
`)}function dt(n,e,t,r,s){const{domElement:a,styleElement:o,svgRoot:l}=s;a.innerHTML=`<style>${e.cssStyle}</style><div style='padding:0;'>${n}</div>`,a.setAttribute("style",`transform: scale(${t});transform-origin: top left; display: inline-block`),o.textContent=r;const{width:d,height:c}=s.image;return l.setAttribute("width",d.toString()),l.setAttribute("height",c.toString()),new XMLSerializer().serializeToString(l)}function ut(n,e){const t=i.CanvasPool.getOptimalCanvasAndContext(n.width,n.height,e),{context:r}=t;return r.clearRect(0,0,n.width,n.height),r.drawImage(n,0,0),t}function ct(n,e,t){return new Promise(async r=>{t&&await new Promise(s=>setTimeout(s,100)),n.onload=()=>{r()},n.src=`data:image/svg+xml;charset=utf8,${encodeURIComponent(e)}`,n.crossOrigin="anonymous"})}class D{constructor(e){this._activeTextures={},this._renderer=e,this._createCanvas=e.type===i.RendererType.WEBGPU}getTexture(e){return this._buildTexturePromise(e.text,e.resolution,e.style)}getManagedTexture(e,t,r,s){if(this._activeTextures[s])return this._increaseReferenceCount(s),this._activeTextures[s].promise;const a=this._buildTexturePromise(e,t,r).then(o=>(this._activeTextures[s].texture=o,o));return this._activeTextures[s]={texture:null,promise:a,usageCount:1},a}async _buildTexturePromise(e,t,r){const s=i.BigPool.get(le),a=at(e,r),o=await lt(a,r,H.defaultTextStyle),l=He(e,r,o,s),d=Math.ceil(Math.ceil(Math.max(1,l.width)+r.padding*2)*t),c=Math.ceil(Math.ceil(Math.max(1,l.height)+r.padding*2)*t),h=s.image,u=2;h.width=(d|0)+u,h.height=(c|0)+u;const f=dt(e,r,t,o,s);await ct(h,f,st()&&a.length>0);const g=h;let x;this._createCanvas&&(x=ut(h,t));const p=ve(x?x.canvas:g,h.width-u,h.height-u,t);return this._createCanvas&&(this._renderer.texture.initSource(p.source),i.CanvasPool.returnCanvasAndContext(x)),i.BigPool.return(s),p}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}decreaseReferenceCount(e){const t=this._activeTextures[e];t&&(t.usageCount--,t.usageCount===0&&(t.texture?this._cleanUp(t):t.promise.then(r=>{t.texture=r,this._cleanUp(t)}).catch(()=>{i.warn("HTMLTextSystem: Failed to clean texture")}),this._activeTextures[e]=null))}_cleanUp(e){i.TexturePool.returnTexture(e.texture),e.texture.source.resource=null,e.texture.source.uploadMethodId="unknown"}getReferenceCount(e){return this._activeTextures[e].usageCount}destroy(){this._activeTextures=null}}D.extension={type:[i.ExtensionType.WebGLSystem,i.ExtensionType.WebGPUSystem,i.ExtensionType.CanvasSystem],name:"htmlText"};D.defaultFontOptions={fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal"};class Se{constructor(e){this._gpuText=Object.create(null),this._destroyRenderableBound=this.destroyRenderable.bind(this),this._renderer=e,this._renderer.runners.resolutionChange.add(this),this._renderer.renderableGC.addManagedHash(this,"_gpuText")}resolutionChange(){for(const e in this._gpuText){const t=this._gpuText[e];if(!t)continue;const r=t.batchableSprite.renderable;r._autoResolution&&(r._resolution=this._renderer.resolution,r.onViewUpdate())}}validateRenderable(e){const t=this._getGpuText(e),r=e._getKey();return t.currentKey!==r}addRenderable(e,t){const s=this._getGpuText(e).batchableSprite;e._didTextUpdate&&this._updateText(e),this._renderer.renderPipes.batch.addToBatch(s,t)}updateRenderable(e){const r=this._getGpuText(e).batchableSprite;e._didTextUpdate&&this._updateText(e),r._batcher.updateElement(r)}destroyRenderable(e){e.off("destroyed",this._destroyRenderableBound),this._destroyRenderableById(e.uid)}_destroyRenderableById(e){const t=this._gpuText[e];this._renderer.canvasText.decreaseReferenceCount(t.currentKey),i.BigPool.return(t.batchableSprite),this._gpuText[e]=null}_updateText(e){const t=e._getKey(),r=this._getGpuText(e),s=r.batchableSprite;r.currentKey!==t&&this._updateGpuText(e),e._didTextUpdate=!1;const a=e._style.padding;i.updateQuadBounds(s.bounds,e._anchor,s.texture,a)}_updateGpuText(e){const t=this._getGpuText(e),r=t.batchableSprite;t.texture&&this._renderer.canvasText.decreaseReferenceCount(t.currentKey),t.texture=r.texture=this._renderer.canvasText.getManagedTexture(e),t.currentKey=e._getKey(),r.texture=t.texture}_getGpuText(e){return this._gpuText[e.uid]||this.initGpuText(e)}initGpuText(e){const t={texture:null,currentKey:"--",batchableSprite:i.BigPool.get(i.BatchableSprite)};return t.batchableSprite.renderable=e,t.batchableSprite.transform=e.groupTransform,t.batchableSprite.bounds={minX:0,maxX:1,minY:0,maxY:0},t.batchableSprite.roundPixels=this._renderer._roundPixels|e._roundPixels,this._gpuText[e.uid]=t,e._resolution=e._autoResolution?this._renderer.resolution:e.resolution,this._updateText(e),e.on("destroyed",this._destroyRenderableBound),t}destroy(){for(const e in this._gpuText)this._destroyRenderableById(e);this._gpuText=null,this._renderer=null}}Se.extension={type:[i.ExtensionType.WebGLPipes,i.ExtensionType.WebGPUPipes,i.ExtensionType.CanvasPipes],name:"text"};function Q(n,e,t){for(let r=0,s=4*t*e;r<e;++r,s+=4)if(n[s+3]!==0)return!1;return!0}function J(n,e,t,r,s){const a=4*e;for(let o=r,l=r*a+4*t;o<=s;++o,l+=a)if(n[l+3]!==0)return!1;return!0}function ht(n,e=1){const{width:t,height:r}=n,s=n.getContext("2d",{willReadFrequently:!0});if(s===null)throw new TypeError("Failed to get canvas 2D context");const o=s.getImageData(0,0,t,r).data;let l=0,d=0,c=t-1,h=r-1;for(;d<r&&Q(o,t,d);)++d;if(d===r)return i.Rectangle.EMPTY;for(;Q(o,t,h);)--h;for(;J(o,t,l,d,h);)++l;for(;J(o,t,c,d,h);)--c;return++c,++h,new i.Rectangle(l/e,d/e,(c-l)/e,(h-d)/e)}class we{constructor(e){this._activeTextures={},this._renderer=e}getTextureSize(e,t,r){const s=i.CanvasTextMetrics.measureText(e||" ",r);let a=Math.ceil(Math.ceil(Math.max(1,s.width)+r.padding*2)*t),o=Math.ceil(Math.ceil(Math.max(1,s.height)+r.padding*2)*t);return a=Math.ceil(a-1e-6),o=Math.ceil(o-1e-6),a=i.nextPow2(a),o=i.nextPow2(o),{width:a,height:o}}getTexture(e,t,r,s){typeof e=="string"&&(i.deprecation("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),e={text:e,style:r,resolution:t}),e.style instanceof i.TextStyle||(e.style=new i.TextStyle(e.style));const{texture:a,canvasAndContext:o}=this.createTextureAndCanvas(e);return this._renderer.texture.initSource(a._source),i.CanvasPool.returnCanvasAndContext(o),a}createTextureAndCanvas(e){const{text:t,style:r}=e,s=e.resolution??this._renderer.resolution,a=i.CanvasTextMetrics.measureText(t||" ",r),o=Math.ceil(Math.ceil(Math.max(1,a.width)+r.padding*2)*s),l=Math.ceil(Math.ceil(Math.max(1,a.height)+r.padding*2)*s),d=i.CanvasPool.getOptimalCanvasAndContext(o,l),{canvas:c}=d;this.renderTextToCanvas(t,r,s,d);const h=ve(c,o,l,s);if(r.trim){const u=ht(c,s);h.frame.copyFrom(u),h.updateUvs()}return{texture:h,canvasAndContext:d}}getManagedTexture(e){e._resolution=e._autoResolution?this._renderer.resolution:e.resolution;const t=e._getKey();if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].texture;const{texture:r,canvasAndContext:s}=this.createTextureAndCanvas(e);return this._activeTextures[t]={canvasAndContext:s,texture:r,usageCount:1},r}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}decreaseReferenceCount(e){const t=this._activeTextures[e];if(t.usageCount--,t.usageCount===0){i.CanvasPool.returnCanvasAndContext(t.canvasAndContext),i.TexturePool.returnTexture(t.texture);const r=t.texture.source;r.resource=null,r.uploadMethodId="unknown",r.alphaMode="no-premultiply-alpha",this._activeTextures[e]=null}}getReferenceCount(e){return this._activeTextures[e].usageCount}renderTextToCanvas(e,t,r,s){var v,b,S,B;const{canvas:a,context:o}=s,l=i.fontStringFromTextStyle(t),d=i.CanvasTextMetrics.measureText(e||" ",t),c=d.lines,h=d.lineHeight,u=d.lineWidths,f=d.maxLineWidth,g=d.fontProperties,x=a.height;if(o.resetTransform(),o.scale(r,r),o.textBaseline=t.textBaseline,(v=t._stroke)!=null&&v.width){const T=t._stroke;o.lineWidth=T.width,o.miterLimit=T.miterLimit,o.lineJoin=T.join,o.lineCap=T.cap}o.font=l;let p,m;const _=t.dropShadow?2:1;for(let T=0;T<_;++T){const w=t.dropShadow&&T===0,C=w?Math.ceil(Math.max(1,x)+t.padding*2):0,Ce=C*r;if(w){o.fillStyle="black",o.strokeStyle="black";const y=t.dropShadow,Be=y.color,Pe=y.alpha;o.shadowColor=i.Color.shared.setValue(Be).setAlpha(Pe).toRgbaString();const Me=y.blur*r,V=y.distance*r;o.shadowBlur=Me,o.shadowOffsetX=Math.cos(y.angle)*V,o.shadowOffsetY=Math.sin(y.angle)*V+Ce}else o.fillStyle=t._fill?i.getCanvasFillStyle(t._fill,o):null,(b=t._stroke)!=null&&b.width&&(o.strokeStyle=i.getCanvasFillStyle(t._stroke,o)),o.shadowColor="black";let z=(h-g.fontSize)/2;h-g.fontSize<0&&(z=0);const W=((S=t._stroke)==null?void 0:S.width)??0;for(let y=0;y<c.length;y++)p=W/2,m=W/2+y*h+g.ascent+z,t.align==="right"?p+=f-u[y]:t.align==="center"&&(p+=(f-u[y])/2),(B=t._stroke)!=null&&B.width&&this._drawLetterSpacing(c[y],t,s,p+t.padding,m+t.padding-C,!0),t._fill!==void 0&&this._drawLetterSpacing(c[y],t,s,p+t.padding,m+t.padding-C)}}_drawLetterSpacing(e,t,r,s,a,o=!1){const{context:l}=r,d=t.letterSpacing;let c=!1;if(i.CanvasTextMetrics.experimentalLetterSpacingSupported&&(i.CanvasTextMetrics.experimentalLetterSpacing?(l.letterSpacing=`${d}px`,l.textLetterSpacing=`${d}px`,c=!0):(l.letterSpacing="0px",l.textLetterSpacing="0px")),d===0||c){o?l.strokeText(e,s,a):l.fillText(e,s,a);return}let h=s;const u=i.CanvasTextMetrics.graphemeSegmenter(e);let f=l.measureText(e).width,g=0;for(let x=0;x<u.length;++x){const p=u[x];o?l.strokeText(p,h,a):l.fillText(p,h,a);let m="";for(let _=x+1;_<u.length;++_)m+=u[_];g=l.measureText(m).width,h+=f-g+d,f=g}}destroy(){this._activeTextures=null}}we.extension={type:[i.ExtensionType.WebGLSystem,i.ExtensionType.WebGPUSystem,i.ExtensionType.CanvasSystem],name:"canvasText"};i.extensions.add(Z);i.extensions.add(ee);i.extensions.add(de);i.extensions.add(i.GraphicsContextSystem);i.extensions.add(he);i.extensions.add(pe);i.extensions.add(ge);i.extensions.add(we);i.extensions.add(Se);i.extensions.add(ye);i.extensions.add(D);i.extensions.add(Te);i.extensions.add(be);i.extensions.add(_e);i.extensions.add(ie);i.extensions.add(te);
|