mirror of
https://github.com/SoPat712/dotfiles.git
synced 2025-08-21 10:38:44 -04:00
288 lines
83 KiB
JavaScript
288 lines
83 KiB
JavaScript
import{E as b,U as Ft,T as Be,a as Ve,a3 as k,a4 as W,a0 as R,ac as E,ad as Ce,ae as Pe,af as Z,ag as pe,D as K,v as A,M as U,w as $,V as ce,ah as Mt,ai as G,aj as ne,a6 as ge,l as j,d as $e,I as H,P as kt,R as me,J as je,c as Y,B as D,F as v,ak as Ut,al as _e,N as ue,am as N,t as xe,x as Wt,G as At,an as zt,m as Ke,a7 as Ye,s as Xe,aa as Ne,q as Gt,o as Ht,p as Dt,a8 as Lt,a9 as It,ab as Ot,ao as Et,ap as fe,n as Re,e as P,aq as Vt}from"./TorrentDetail-CoyYqyCA.js";import{S as ee,c as ie,a as $t,b as jt,B as qe}from"./colorToUniform-C2GHuDhf.js";import{C as O}from"./CanvasPool-BAToQajg.js";import"./ColoredChip.vue_vue_type_script_setup_true_lang-DosC_URk.js";import"./index-BhWmfNB5.js";import"./vue-DFryKk-1.js";import"./vuetify-XtA0Y0Oj.js";class Qe{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:i,clientHeight:s}=this._resizeTo;t=i,r=s}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}}Qe.extension=b.Application;class Je{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,Ft.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?Be.shared:new Be,e.autoStart&&this.start()}static destroy(){if(this._ticker){const e=this._ticker;this.ticker=null,e.destroy()}}}Je.extension=b.Application;class Kt extends Ve{constructor(){super(...arguments),this.chars=Object.create(null),this.lineHeight=0,this.fontFamily="",this.fontMetrics={fontSize:0,ascent:0,descent:0},this.baseLineOffset=0,this.distanceField={type:"none",range:0},this.pages=[],this.applyFillAsTint=!0,this.baseMeasurementFontSize=100,this.baseRenderedFontSize=100}get font(){return k(W,"BitmapFont.font is deprecated, please use BitmapFont.fontFamily instead."),this.fontFamily}get pageTextures(){return k(W,"BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead."),this.pages}get size(){return k(W,"BitmapFont.size is deprecated, please use BitmapFont.fontMetrics.fontSize instead."),this.fontMetrics.fontSize}get distanceFieldRange(){return k(W,"BitmapFont.distanceFieldRange is deprecated, please use BitmapFont.distanceField.range instead."),this.distanceField.range}get distanceFieldType(){return k(W,"BitmapFont.distanceFieldType is deprecated, please use BitmapFont.distanceField.type instead."),this.distanceField.type}destroy(e=!1){this.emit("destroy",this),this.removeAllListeners();for(const t in this.chars)this.chars[t].texture?.destroy();this.chars=null,e&&(this.pages.forEach(t=>t.texture.destroy(!0)),this.pages=null)}}const Fe=["align","breakWords","cssOverrides","fontVariant","fontWeight","leading","letterSpacing","lineHeight","padding","textBaseline","trim","whiteSpace","wordWrap","wordWrapWidth","fontFamily","fontStyle","fontSize"];function Ze(n){const e=[];let t=0;for(let r=0;r<Fe.length;r++){const i=`_${Fe[r]}`;e[t++]=n[i]}return t=et(n._fill,e,t),t=Yt(n._stroke,e,t),t=Xt(n.dropShadow,e,t),e.join("-")}function et(n,e,t){return n&&(e[t++]=n.color,e[t++]=n.alpha,e[t++]=n.fill?.styleKey),t}function Yt(n,e,t){return n&&(t=et(n,e,t),e[t++]=n.width,e[t++]=n.alignment,e[t++]=n.cap,e[t++]=n.join,e[t++]=n.miterLimit),t}function Xt(n,e,t){return n&&(e[t++]=n.alpha,e[t++]=n.angle,e[t++]=n.blur,e[t++]=n.distance,e[t++]=R.shared.setValue(n.color).toNumber()),t}const be=class V extends Ve{constructor(e={}){super(),Nt(e);const t={...V.defaultTextStyle,...e};for(const r in t){const i=r;this[i]=t[r]}this.update()}get align(){return this._align}set align(e){this._align=e,this.update()}get breakWords(){return this._breakWords}set breakWords(e){this._breakWords=e,this.update()}get dropShadow(){return this._dropShadow}set dropShadow(e){e!==null&&typeof e=="object"?this._dropShadow=this._createProxy({...V.defaultDropShadow,...e}):this._dropShadow=e?this._createProxy({...V.defaultDropShadow}):null,this.update()}get fontFamily(){return this._fontFamily}set fontFamily(e){this._fontFamily=e,this.update()}get fontSize(){return this._fontSize}set fontSize(e){typeof e=="string"?this._fontSize=parseInt(e,10):this._fontSize=e,this.update()}get fontStyle(){return this._fontStyle}set fontStyle(e){this._fontStyle=e.toLowerCase(),this.update()}get fontVariant(){return this._fontVariant}set fontVariant(e){this._fontVariant=e,this.update()}get fontWeight(){return this._fontWeight}set fontWeight(e){this._fontWeight=e,this.update()}get leading(){return this._leading}set leading(e){this._leading=e,this.update()}get letterSpacing(){return this._letterSpacing}set letterSpacing(e){this._letterSpacing=e,this.update()}get lineHeight(){return this._lineHeight}set lineHeight(e){this._lineHeight=e,this.update()}get padding(){return this._padding}set padding(e){this._padding=e,this.update()}get trim(){return this._trim}set trim(e){this._trim=e,this.update()}get textBaseline(){return this._textBaseline}set textBaseline(e){this._textBaseline=e,this.update()}get whiteSpace(){return this._whiteSpace}set whiteSpace(e){this._whiteSpace=e,this.update()}get wordWrap(){return this._wordWrap}set wordWrap(e){this._wordWrap=e,this.update()}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(e){this._wordWrapWidth=e,this.update()}get fill(){return this._originalFill}set fill(e){e!==this._originalFill&&(this._originalFill=e,this._isFillStyle(e)&&(this._originalFill=this._createProxy({...E.defaultFillStyle,...e},()=>{this._fill=Ce({...this._originalFill},E.defaultFillStyle)})),this._fill=Ce(e===0?"black":e,E.defaultFillStyle),this.update())}get stroke(){return this._originalStroke}set stroke(e){e!==this._originalStroke&&(this._originalStroke=e,this._isFillStyle(e)&&(this._originalStroke=this._createProxy({...E.defaultStrokeStyle,...e},()=>{this._stroke=Pe({...this._originalStroke},E.defaultStrokeStyle)})),this._stroke=Pe(e,E.defaultStrokeStyle),this.update())}_generateKey(){return this._styleKey=Ze(this),this._styleKey}update(){this._styleKey=null,this.emit("update",this)}reset(){const e=V.defaultTextStyle;for(const t in e)this[t]=e[t]}get styleKey(){return this._styleKey||this._generateKey()}clone(){return new V({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,leading:this.leading,letterSpacing:this.letterSpacing,lineHeight:this.lineHeight,padding:this.padding,stroke:this._stroke,textBaseline:this.textBaseline,whiteSpace:this.whiteSpace,wordWrap:this.wordWrap,wordWrapWidth:this.wordWrapWidth})}destroy(e=!1){if(this.removeAllListeners(),typeof e=="boolean"?e:e?.texture){const r=typeof e=="boolean"?e:e?.textureSource;this._fill?.texture&&this._fill.texture.destroy(r),this._originalFill?.texture&&this._originalFill.texture.destroy(r),this._stroke?.texture&&this._stroke.texture.destroy(r),this._originalStroke?.texture&&this._originalStroke.texture.destroy(r)}this._fill=null,this._stroke=null,this.dropShadow=null,this._originalStroke=null,this._originalFill=null}_createProxy(e,t){return new Proxy(e,{set:(r,i,s)=>(r[i]=s,t?.(i,s),this.update(),!0)})}_isFillStyle(e){return(e??null)!==null&&!(R.isColorLike(e)||e instanceof Z||e instanceof pe)}};be.defaultDropShadow={alpha:1,angle:Math.PI/6,blur:0,color:"black",distance:5};be.defaultTextStyle={align:"left",breakWords:!1,dropShadow:null,fill:"black",fontFamily:"Arial",fontSize:26,fontStyle:"normal",fontVariant:"normal",fontWeight:"normal",leading:0,letterSpacing:0,lineHeight:0,padding:0,stroke:null,textBaseline:"alphabetic",trim:!1,whiteSpace:"pre",wordWrap:!1,wordWrapWidth:100};let I=be;function Nt(n){const e=n;if(typeof e.dropShadow=="boolean"&&e.dropShadow){const t=I.defaultDropShadow;n.dropShadow={alpha:e.dropShadowAlpha??t.alpha,angle:e.dropShadowAngle??t.angle,blur:e.dropShadowBlur??t.blur,color:e.dropShadowColor??t.color,distance:e.dropShadowDistance??t.distance}}if(e.strokeThickness!==void 0){k(W,"strokeThickness is now a part of stroke");const t=e.stroke;let r={};if(R.isColorLike(t))r.color=t;else if(t instanceof Z||t instanceof pe)r.fill=t;else if(Object.hasOwnProperty.call(t,"color")||Object.hasOwnProperty.call(t,"fill"))r=t;else throw new Error("Invalid stroke value.");n.stroke={...r,width:e.strokeThickness}}if(Array.isArray(e.fillGradientStops)){k(W,"gradient fill is now a fill pattern: `new FillGradient(...)`");let t;n.fontSize==null?n.fontSize=I.defaultTextStyle.fontSize:typeof n.fontSize=="string"?t=parseInt(n.fontSize,10):t=n.fontSize;const r=new Z(0,0,0,t*1.7),i=e.fillGradientStops.map(s=>R.shared.setValue(s).toNumber());i.forEach((s,a)=>{const o=a/(i.length-1);r.addColorStop(o,s)}),n.fill={fill:r}}}const qt=["serif","sans-serif","monospace","cursive","fantasy","system-ui"];function te(n){const e=typeof n.fontSize=="number"?`${n.fontSize}px`:n.fontSize;let t=n.fontFamily;Array.isArray(n.fontFamily)||(t=n.fontFamily.split(","));for(let r=t.length-1;r>=0;r--){let i=t[r].trim();!/([\"\'])[^\'\"]+\1/.test(i)&&!qt.includes(i)&&(i=`"${i}"`),t[r]=i}return`${n.fontStyle} ${n.fontVariant} ${n.fontWeight} ${e} ${t.join(",")}`}const ae={willReadFrequently:!0},z=class p{static get experimentalLetterSpacingSupported(){let e=p._experimentalLetterSpacingSupported;if(e!==void 0){const t=K.get().getCanvasRenderingContext2D().prototype;e=p._experimentalLetterSpacingSupported="letterSpacing"in t||"textLetterSpacing"in t}return e}constructor(e,t,r,i,s,a,o,l,h){this.text=e,this.style=t,this.width=r,this.height=i,this.lines=s,this.lineWidths=a,this.lineHeight=o,this.maxLineWidth=l,this.fontProperties=h}static measureText(e=" ",t,r=p._canvas,i=t.wordWrap){const s=`${e}:${t.styleKey}`;if(p._measurementCache[s])return p._measurementCache[s];const a=te(t),o=p.measureFont(a);o.fontSize===0&&(o.fontSize=t.fontSize,o.ascent=t.fontSize);const l=p.__context;l.font=a;const d=(i?p._wordWrap(e,t,r):e).split(/(?:\r\n|\r|\n)/),c=new Array(d.length);let f=0;for(let y=0;y<d.length;y++){const S=p._measureText(d[y],t.letterSpacing,l);c[y]=S,f=Math.max(f,S)}const g=t._stroke?.width||0;let u=f+g;t.dropShadow&&(u+=t.dropShadow.distance);const m=t.lineHeight||o.fontSize;let x=Math.max(m,o.fontSize+g)+(d.length-1)*(m+t.leading);return t.dropShadow&&(x+=t.dropShadow.distance),new p(e,t,u,x,d,c,m+t.leading,f,o)}static _measureText(e,t,r){let i=!1;p.experimentalLetterSpacingSupported&&(p.experimentalLetterSpacing?(r.letterSpacing=`${t}px`,r.textLetterSpacing=`${t}px`,i=!0):(r.letterSpacing="0px",r.textLetterSpacing="0px"));const s=r.measureText(e);let a=s.width;const o=-s.actualBoundingBoxLeft;let h=s.actualBoundingBoxRight-o;if(a>0)if(i)a-=t,h-=t;else{const d=(p.graphemeSegmenter(e).length-1)*t;a+=d,h+=d}return Math.max(a,h)}static _wordWrap(e,t,r=p._canvas){const i=r.getContext("2d",ae);let s=0,a="",o="";const l=Object.create(null),{letterSpacing:h,whiteSpace:d}=t,c=p._collapseSpaces(d),f=p._collapseNewlines(d);let g=!c;const u=t.wordWrapWidth+h,m=p._tokenize(e);for(let x=0;x<m.length;x++){let _=m[x];if(p._isNewline(_)){if(!f){o+=p._addLine(a),g=!c,a="",s=0;continue}_=" "}if(c){const S=p.isBreakingSpace(_),w=p.isBreakingSpace(a[a.length-1]);if(S&&w)continue}const y=p._getFromCache(_,h,l,i);if(y>u)if(a!==""&&(o+=p._addLine(a),a="",s=0),p.canBreakWords(_,t.breakWords)){const S=p.wordWrapSplit(_);for(let w=0;w<S.length;w++){let B=S[w],F=B,C=1;for(;S[w+C];){const M=S[w+C];if(!p.canBreakChars(F,M,_,w,t.breakWords))B+=M;else break;F=M,C++}w+=C-1;const T=p._getFromCache(B,h,l,i);T+s>u&&(o+=p._addLine(a),g=!1,a="",s=0),a+=B,s+=T}}else{a.length>0&&(o+=p._addLine(a),a="",s=0);const S=x===m.length-1;o+=p._addLine(_,!S),g=!1,a="",s=0}else y+s>u&&(g=!1,o+=p._addLine(a),a="",s=0),(a.length>0||!p.isBreakingSpace(_)||g)&&(a+=_,s+=y)}return o+=p._addLine(a,!1),o}static _addLine(e,t=!0){return e=p._trimRight(e),e=t?`${e}
|
|
`:e,e}static _getFromCache(e,t,r,i){let s=r[e];return typeof s!="number"&&(s=p._measureText(e,t,i)+t,r[e]=s),s}static _collapseSpaces(e){return e==="normal"||e==="pre-line"}static _collapseNewlines(e){return e==="normal"}static _trimRight(e){if(typeof e!="string")return"";for(let t=e.length-1;t>=0;t--){const r=e[t];if(!p.isBreakingSpace(r))break;e=e.slice(0,-1)}return e}static _isNewline(e){return typeof e!="string"?!1:p._newlines.includes(e.charCodeAt(0))}static isBreakingSpace(e,t){return typeof e!="string"?!1:p._breakingSpaces.includes(e.charCodeAt(0))}static _tokenize(e){const t=[];let r="";if(typeof e!="string")return t;for(let i=0;i<e.length;i++){const s=e[i],a=e[i+1];if(p.isBreakingSpace(s,a)||p._isNewline(s)){r!==""&&(t.push(r),r=""),t.push(s);continue}r+=s}return r!==""&&t.push(r),t}static canBreakWords(e,t){return t}static canBreakChars(e,t,r,i,s){return!0}static wordWrapSplit(e){return p.graphemeSegmenter(e)}static measureFont(e){if(p._fonts[e])return p._fonts[e];const t=p._context;t.font=e;const r=t.measureText(p.METRICS_STRING+p.BASELINE_SYMBOL),i={ascent:r.actualBoundingBoxAscent,descent:r.actualBoundingBoxDescent,fontSize:r.actualBoundingBoxAscent+r.actualBoundingBoxDescent};return p._fonts[e]=i,i}static clearMetrics(e=""){e?delete p._fonts[e]:p._fonts={}}static get _canvas(){if(!p.__canvas){let e;try{const t=new OffscreenCanvas(0,0);if(t.getContext("2d",ae)?.measureText)return p.__canvas=t,t;e=K.get().createCanvas()}catch{e=K.get().createCanvas()}e.width=e.height=10,p.__canvas=e}return p.__canvas}static get _context(){return p.__context||(p.__context=p._canvas.getContext("2d",ae)),p.__context}};z.METRICS_STRING="|ÉqÅ";z.BASELINE_SYMBOL="M";z.BASELINE_MULTIPLIER=1.4;z.HEIGHT_MULTIPLIER=2;z.graphemeSegmenter=(()=>{if(typeof Intl?.Segmenter=="function"){const n=new Intl.Segmenter;return e=>[...n.segment(e)].map(t=>t.segment)}return n=>[...n]})();z.experimentalLetterSpacing=!1;z._fonts={};z._newlines=[10,13];z._breakingSpaces=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288];z._measurementCache={};let L=z;function re(n,e){if(n.texture===A.WHITE&&!n.fill)return R.shared.setValue(n.color).setAlpha(n.alpha??1).toHexa();if(n.fill){if(n.fill instanceof pe){const t=n.fill,r=e.createPattern(t.texture.source.resource,"repeat"),i=t.transform.copyTo(U.shared);return i.scale(t.texture.frame.width,t.texture.frame.height),r.setTransform(i),r}else if(n.fill instanceof Z){const t=n.fill;if(t.type==="linear"){const r=e.createLinearGradient(t.x0,t.y0,t.x1,t.y1);return t.gradientStops.forEach(i=>{r.addColorStop(i.offset,R.shared.setValue(i.color).toHex())}),r}}}else{const t=e.createPattern(n.texture.source.resource,"repeat"),r=n.matrix.copyTo(U.shared);return r.scale(n.texture.frame.width,n.texture.frame.height),t.setTransform(r),t}return $("FillStyle not recognised",n),"red"}function tt(n){if(n==="")return[];typeof n=="string"&&(n=[n]);const e=[];for(let t=0,r=n.length;t<r;t++){const i=n[t];if(Array.isArray(i)){if(i.length!==2)throw new Error(`[BitmapFont]: Invalid character range length, expecting 2 got ${i.length}.`);if(i[0].length===0||i[1].length===0)throw new Error("[BitmapFont]: Invalid character delimiter.");const s=i[0].charCodeAt(0),a=i[1].charCodeAt(0);if(a<s)throw new Error("[BitmapFont]: Invalid character range.");for(let o=s,l=a;o<=l;o++)e.push(String.fromCharCode(o))}else e.push(...Array.from(i))}if(e.length===0)throw new Error("[BitmapFont]: Empty set when resolving characters.");return e}const rt=class it extends Kt{constructor(e){super(),this.resolution=1,this.pages=[],this._padding=0,this._measureCache=Object.create(null),this._currentChars=[],this._currentX=0,this._currentY=0,this._currentPageIndex=-1,this._skipKerning=!1;const t={...it.defaultOptions,...e};this._textureSize=t.textureSize,this._mipmap=t.mipmap;const r=t.style.clone();t.overrideFill&&(r._fill.color=16777215,r._fill.alpha=1,r._fill.texture=A.WHITE,r._fill.fill=null),this.applyFillAsTint=t.overrideFill;const i=r.fontSize;r.fontSize=this.baseMeasurementFontSize;const s=te(r);t.overrideSize?r._stroke&&(r._stroke.width*=this.baseRenderedFontSize/i):r.fontSize=this.baseRenderedFontSize=i,this._style=r,this._skipKerning=t.skipKerning??!1,this.resolution=t.resolution??1,this._padding=t.padding??4,this.fontMetrics=L.measureFont(s),this.lineHeight=r.lineHeight||this.fontMetrics.fontSize||r.fontSize}ensureCharacters(e){const t=tt(e).filter(x=>!this._currentChars.includes(x)).filter((x,_,y)=>y.indexOf(x)===_);if(!t.length)return;this._currentChars=[...this._currentChars,...t];let r;this._currentPageIndex===-1?r=this._nextPage():r=this.pages[this._currentPageIndex];let{canvas:i,context:s}=r.canvasAndContext,a=r.texture.source;const o=this._style;let l=this._currentX,h=this._currentY;const d=this.baseRenderedFontSize/this.baseMeasurementFontSize,c=this._padding*d;let f=0,g=!1;const u=i.width/this.resolution,m=i.height/this.resolution;for(let x=0;x<t.length;x++){const _=t[x],y=L.measureText(_,o,i,!1);y.lineHeight=y.height;const S=y.width*d,w=Math.ceil((o.fontStyle==="italic"?2:1)*S),B=y.height*d,F=w+c*2,C=B+c*2;if(g=!1,_!==`
|
|
`&&_!=="\r"&&_!==" "&&_!==" "&&(g=!0,f=Math.ceil(Math.max(C,f))),l+F>u&&(h+=f,f=C,l=0,h+f>m)){a.update();const M=this._nextPage();i=M.canvasAndContext.canvas,s=M.canvasAndContext.context,a=M.texture.source,h=0}const T=S/d-(o.dropShadow?.distance??0)-(o._stroke?.width??0);if(this.chars[_]={id:_.codePointAt(0),xOffset:-this._padding,yOffset:-this._padding,xAdvance:T,kerning:{}},g){this._drawGlyph(s,y,l+c,h+c,d,o);const M=a.width*d,X=a.height*d,se=new ce(l/M*a.width,h/X*a.height,F/M*a.width,C/X*a.height);this.chars[_].texture=new A({source:a,frame:se}),l+=Math.ceil(F)}}a.update(),this._currentX=l,this._currentY=h,this._skipKerning&&this._applyKerning(t,s)}get pageTextures(){return k(W,"BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead."),this.pages}_applyKerning(e,t){const r=this._measureCache;for(let i=0;i<e.length;i++){const s=e[i];for(let a=0;a<this._currentChars.length;a++){const o=this._currentChars[a];let l=r[s];l||(l=r[s]=t.measureText(s).width);let h=r[o];h||(h=r[o]=t.measureText(o).width);let d=t.measureText(s+o).width,c=d-(l+h);c&&(this.chars[s].kerning[o]=c),d=t.measureText(s+o).width,c=d-(l+h),c&&(this.chars[o].kerning[s]=c)}}}_nextPage(){this._currentPageIndex++;const e=this.resolution,t=O.getOptimalCanvasAndContext(this._textureSize,this._textureSize,e);this._setupContext(t.context,this._style,e);const r=e*(this.baseRenderedFontSize/this.baseMeasurementFontSize),i=new A({source:new Mt({resource:t.canvas,resolution:r,alphaMode:"premultiply-alpha-on-upload",autoGenerateMipmaps:this._mipmap})}),s={canvasAndContext:t,texture:i};return this.pages[this._currentPageIndex]=s,s}_setupContext(e,t,r){t.fontSize=this.baseRenderedFontSize,e.scale(r,r),e.font=te(t),t.fontSize=this.baseMeasurementFontSize,e.textBaseline=t.textBaseline;const i=t._stroke,s=i?.width??0;if(i&&(e.lineWidth=s,e.lineJoin=i.join,e.miterLimit=i.miterLimit,e.strokeStyle=re(i,e)),t._fill&&(e.fillStyle=re(t._fill,e)),t.dropShadow){const a=t.dropShadow,o=R.shared.setValue(a.color).toArray(),l=a.blur*r,h=a.distance*r;e.shadowColor=`rgba(${o[0]*255},${o[1]*255},${o[2]*255},${a.alpha})`,e.shadowBlur=l,e.shadowOffsetX=Math.cos(a.angle)*h,e.shadowOffsetY=Math.sin(a.angle)*h}else e.shadowColor="black",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0}_drawGlyph(e,t,r,i,s,a){const o=t.text,l=t.fontProperties,d=(a._stroke?.width??0)*s,c=r+d/2,f=i-d/2,g=l.descent*s,u=t.lineHeight*s;a.stroke&&d&&e.strokeText(o,c,f+u-g),a._fill&&e.fillText(o,c,f+u-g)}destroy(){super.destroy();for(let e=0;e<this.pages.length;e++){const{canvasAndContext:t,texture:r}=this.pages[e];O.returnCanvasAndContext(t),r.destroy(!0)}this.pages=null}};rt.defaultOptions={textureSize:512,style:new I,mipmap:!0};let Me=rt;function st(n,e,t,r){const i={width:0,height:0,offsetY:0,scale:e.fontSize/t.baseMeasurementFontSize,lines:[{width:0,charPositions:[],spaceWidth:0,spacesIndex:[],chars:[]}]};i.offsetY=t.baseLineOffset;let s=i.lines[0],a=null,o=!0;const l={spaceWord:!1,width:0,start:0,index:0,positions:[],chars:[]},h=u=>{const m=s.width;for(let x=0;x<l.index;x++){const _=u.positions[x];s.chars.push(u.chars[x]),s.charPositions.push(_+m)}s.width+=u.width,o=!1,l.width=0,l.index=0,l.chars.length=0},d=()=>{let u=s.chars.length-1;if(r){let m=s.chars[u];for(;m===" ";)s.width-=t.chars[m].xAdvance,m=s.chars[--u]}i.width=Math.max(i.width,s.width),s={width:0,charPositions:[],chars:[],spaceWidth:0,spacesIndex:[]},o=!0,i.lines.push(s),i.height+=t.lineHeight},c=t.baseMeasurementFontSize/e.fontSize,f=e.letterSpacing*c,g=e.wordWrapWidth*c;for(let u=0;u<n.length+1;u++){let m;const x=u===n.length;x||(m=n[u]);const _=t.chars[m]||t.chars[" "];if(/(?:\s)/.test(m)||m==="\r"||m===`
|
|
`||x){if(!o&&e.wordWrap&&s.width+l.width-f>g?(d(),h(l),x||s.charPositions.push(0)):(l.start=s.width,h(l),x||s.charPositions.push(0)),m==="\r"||m===`
|
|
`)s.width!==0&&d();else if(!x){const B=_.xAdvance+(_.kerning[a]||0)+f;s.width+=B,s.spaceWidth=B,s.spacesIndex.push(s.charPositions.length),s.chars.push(m)}}else{const w=_.kerning[a]||0,B=_.xAdvance+w+f;l.positions[l.index++]=l.width+w,l.chars.push(m),l.width+=B}a=m}return d(),e.align==="center"?Qt(i):e.align==="right"?Jt(i):e.align==="justify"&&Zt(i),i}function Qt(n){for(let e=0;e<n.lines.length;e++){const t=n.lines[e],r=n.width/2-t.width/2;for(let i=0;i<t.charPositions.length;i++)t.charPositions[i]+=r}}function Jt(n){for(let e=0;e<n.lines.length;e++){const t=n.lines[e],r=n.width-t.width;for(let i=0;i<t.charPositions.length;i++)t.charPositions[i]+=r}}function Zt(n){const e=n.width;for(let t=0;t<n.lines.length;t++){const r=n.lines[t];let i=0,s=r.spacesIndex[i++],a=0;const o=r.spacesIndex.length,h=(e-r.width)/o;for(let d=0;d<r.charPositions.length;d++)d===s&&(s=r.spacesIndex[i++],a+=h),r.charPositions[d]+=a}}let q=0;class er{constructor(){this.ALPHA=[["a","z"],["A","Z"]," "],this.NUMERIC=[["0","9"]],this.ALPHANUMERIC=[["a","z"],["A","Z"],["0","9"]," "],this.ASCII=[[" ","~"]],this.defaultOptions={chars:this.ALPHANUMERIC,resolution:1,padding:4,skipKerning:!1}}getFont(e,t){let r=`${t.fontFamily}-bitmap`,i=!0;if(t._fill.fill&&!t._stroke)r+=t._fill.fill.styleKey,i=!1;else if(t._stroke||t.dropShadow){let a=t.styleKey;a=a.substring(0,a.lastIndexOf("-")),r=`${a}-bitmap`,i=!1}if(!G.has(r)){const a=new Me({style:t,overrideFill:i,overrideSize:!0,...this.defaultOptions});q++,q>50&&$("BitmapText",`You have dynamically created ${q} bitmap fonts, this can be inefficient. Try pre installing your font styles using \`BitmapFont.install({name:"style1", style})\``),a.once("destroy",()=>{q--,G.remove(r)}),G.set(r,a)}const s=G.get(r);return s.ensureCharacters?.(e),s}getLayout(e,t,r=!0){const i=this.getFont(e,t);return st([...e],t,i,r)}measureText(e,t,r=!0){return this.getLayout(e,t,r)}install(...e){let t=e[0];typeof t=="string"&&(t={name:t,style:e[1],chars:e[2]?.chars,resolution:e[2]?.resolution,padding:e[2]?.padding,skipKerning:e[2]?.skipKerning},k(W,"BitmapFontManager.install(name, style, options) is deprecated, use BitmapFontManager.install({name, style, ...options})"));const r=t?.name;if(!r)throw new Error("[BitmapFontManager] Property `name` is required.");t={...this.defaultOptions,...t};const i=t.style,s=i instanceof I?i:new I(i),a=s._fill.fill!==null&&s._fill.fill!==void 0,o=new Me({style:s,overrideFill:a,skipKerning:t.skipKerning,padding:t.padding,resolution:t.resolution,overrideSize:!1}),l=tt(t.chars);return o.ensureCharacters(l.join("")),G.set(`${r}-bitmap`,o),o.once("destroy",()=>G.remove(`${r}-bitmap`)),o}uninstall(e){const t=`${e}-bitmap`,r=G.get(t);r&&r.destroy()}}const tr=new er;class nt{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}}nt.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"filter"};const rr=new U;function ir(n,e){e.clear(),at(n,e),e.isValid||e.set(0,0,0,0);const t=n.renderGroup||n.parentRenderGroup;return e.applyMatrix(t.worldTransform),e}function at(n,e){if(n.localDisplayStatus!==7||!n.measurable)return;const t=!!n.effects.length;let r=e;if((n.renderGroup||t)&&(r=ne.get().clear()),n.boundsArea)e.addRect(n.boundsArea,n.worldTransform);else{if(n.renderPipeId){const s=n.bounds;r.addFrame(s.minX,s.minY,s.maxX,s.maxY,n.groupTransform)}const i=n.children;for(let s=0;s<i.length;s++)at(i[s],r)}if(t){let i=!1;for(let s=0;s<n.effects.length;s++)n.effects[s].addBounds&&(i||(i=!0,r.applyMatrix(n.parentRenderGroup.worldTransform)),n.effects[s].addBounds(r,!0));i&&(r.applyMatrix(n.parentRenderGroup.worldTransform.copyTo(rr).invert()),e.addBounds(r,n.relativeGroupTransform)),e.addBounds(r),ne.return(r)}else n.renderGroup&&(e.addBounds(r,n.relativeGroupTransform),ne.return(r))}function sr(n,e){e.clear();const t=e.matrix;for(let r=0;r<n.length;r++){const i=n[r];i.globalDisplayStatus<7||(e.matrix=i.worldTransform,e.addBounds(i.bounds))}return e.matrix=t,e}const nr=new ge({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 ot{constructor(e){this._filterStackIndex=0,this._filterStack=[],this._filterGlobalUniforms=new j({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 $e({}),this.renderer=e}get activeBackTexture(){return this._activeFilterData?.backTexture}push(e){const t=this.renderer,r=e.filterEffect.filters;this._filterStack[this._filterStackIndex]||(this._filterStack[this._filterStackIndex]=this._getFilterData());const i=this._filterStack[this._filterStackIndex];if(this._filterStackIndex++,r.length===0){i.skip=!0;return}const s=i.bounds;if(e.renderables?sr(e.renderables,s):e.filterEffect.filterArea?(s.clear(),s.addRect(e.filterEffect.filterArea),s.applyMatrix(e.container.worldTransform)):ir(e.container,s),e.container){const u=(e.container.renderGroup||e.container.parentRenderGroup).cacheToLocalTransform;u&&s.applyMatrix(u)}const a=t.renderTarget.renderTarget.colorTexture.source;let o=1/0,l=0,h=!0,d=!1,c=!1,f=!0;for(let g=0;g<r.length;g++){const u=r[g];if(o=Math.min(o,u.resolution==="inherit"?a._resolution:u.resolution),l+=u.padding,u.antialias==="off"?h=!1:u.antialias==="inherit"&&h&&(h=a.antialias),u.clipToViewport||(f=!1),!!!(u.compatibleRenderers&t.type)){c=!1;break}if(u.blendRequired&&!(t.backBuffer?.useBackBuffer??!0)){$("Blend filter requires backBuffer on WebGL renderer to be enabled. Set `useBackBuffer: true` in the renderer options."),c=!1;break}c=u.enabled||c,d||(d=u.blendRequired)}if(!c){i.skip=!0;return}if(f){const g=t.renderTarget.rootViewPort,u=t.renderTarget.renderTarget.resolution;s.fitBounds(0,g.width/u,0,g.height/u)}if(s.scale(o).ceil().scale(1/o).pad(l|0),!s.isPositive){i.skip=!0;return}i.skip=!1,i.bounds=s,i.blendRequired=d,i.container=e.container,i.filterEffect=e.filterEffect,i.previousRenderSurface=t.renderTarget.renderSurface,i.inputTexture=H.getOptimalTexture(s.width,s.height,o,h),t.renderTarget.bind(i.inputTexture,!0),t.globalUniforms.push({offset:s})}pop(){const e=this.renderer;this._filterStackIndex--;const t=this._filterStack[this._filterStackIndex];if(t.skip)return;this._activeFilterData=t;const r=t.inputTexture,i=t.bounds;let s=A.EMPTY;if(e.renderTarget.finishRenderPass(),t.blendRequired){const o=this._filterStackIndex>0?this._filterStack[this._filterStackIndex-1].bounds:null,l=e.renderTarget.getRenderTarget(t.previousRenderSurface);s=this.getBackTexture(l,i,o)}t.backTexture=s;const a=t.filterEffect.filters;if(this._globalFilterBindGroup.setResource(r.source.style,2),this._globalFilterBindGroup.setResource(s.source,3),e.globalUniforms.pop(),a.length===1)a[0].apply(this,r,t.previousRenderSurface,!1),H.returnTexture(r);else{let o=t.inputTexture,l=H.getOptimalTexture(i.width,i.height,o.source._resolution,!1),h=0;for(h=0;h<a.length-1;++h){a[h].apply(this,o,l,!0);const c=o;o=l,l=c}a[h].apply(this,o,t.previousRenderSurface,!1),H.returnTexture(o),H.returnTexture(l)}t.blendRequired&&H.returnTexture(s)}getBackTexture(e,t,r){const i=e.colorTexture.source._resolution,s=H.getOptimalTexture(t.width,t.height,i,!1);let a=t.minX,o=t.minY;r&&(a-=r.minX,o-=r.minY),a=Math.floor(a*i),o=Math.floor(o*i);const l=Math.ceil(t.width*i),h=Math.ceil(t.height*i);return this.renderer.renderTarget.copyToTexture(e,s,{x:a,y:o},{width:l,height:h},{x:0,y:0}),s}applyFilter(e,t,r,i){const s=this.renderer,a=this._filterStack[this._filterStackIndex],o=a.bounds,l=kt.shared,d=a.previousRenderSurface===r;let c=this.renderer.renderTarget.rootRenderTarget.colorTexture.source._resolution,f=this._filterStackIndex-1;for(;f>0&&this._filterStack[f].skip;)--f;f>0&&(c=this._filterStack[f].inputTexture.source._resolution);const g=this._filterGlobalUniforms,u=g.uniforms,m=u.uOutputFrame,x=u.uInputSize,_=u.uInputPixel,y=u.uInputClamp,S=u.uGlobalFrame,w=u.uOutputTexture;if(d){let C=this._filterStackIndex;for(;C>0;){C--;const T=this._filterStack[this._filterStackIndex-1];if(!T.skip){l.x=T.bounds.minX,l.y=T.bounds.minY;break}}m[0]=o.minX-l.x,m[1]=o.minY-l.y}else m[0]=0,m[1]=0;m[2]=t.frame.width,m[3]=t.frame.height,x[0]=t.source.width,x[1]=t.source.height,x[2]=1/x[0],x[3]=1/x[1],_[0]=t.source.pixelWidth,_[1]=t.source.pixelHeight,_[2]=1/_[0],_[3]=1/_[1],y[0]=.5*_[2],y[1]=.5*_[3],y[2]=t.frame.width*x[2]-.5*_[2],y[3]=t.frame.height*x[3]-.5*_[3];const B=this.renderer.renderTarget.rootRenderTarget.colorTexture;S[0]=l.x*c,S[1]=l.y*c,S[2]=B.source.width*c,S[3]=B.source.height*c;const F=this.renderer.renderTarget.getRenderTarget(r);if(s.renderTarget.bind(r,!!i),r instanceof A?(w[0]=r.frame.width,w[1]=r.frame.height):(w[0]=F.width,w[1]=F.height),w[2]=F.isRoot?-1:1,g.update(),s.renderPipes.uniformBatch){const C=s.renderPipes.uniformBatch.getUboResource(g);this._globalFilterBindGroup.setResource(C,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,s.encoder.draw({geometry:nr,shader:e,state:e._state,topology:"triangle-list"}),s.type===me.WEBGL&&s.renderTarget.finishRenderPass()}_getFilterData(){return{skip:!1,inputTexture:null,bounds:new je,container:null,filterEffect:null,blendRequired:!1,previousRenderSurface:null}}calculateSpriteMatrix(e,t){const r=this._activeFilterData,i=e.set(r.inputTexture._source.width,0,0,r.inputTexture._source.height,r.bounds.minX,r.bounds.minY),s=t.worldTransform.copyTo(U.shared);return s.invert(),i.prepend(s),i.scale(1/t.texture.frame.width,1/t.texture.frame.height),i.translate(t.anchor.x,t.anchor.y),i}}ot.extension={type:[b.WebGLSystem,b.WebGPUSystem],name:"filter"};const lt=class dt extends ge{constructor(...e){let t=e[0]??{};t instanceof Float32Array&&(k(W,"use new MeshGeometry({ positions, uvs, indices }) instead"),t={positions:t,uvs:e[1],indices:e[2]}),t={...dt.defaultOptions,...t};const r=t.positions||new Float32Array([0,0,1,0,1,1,0,1]),i=t.uvs||new Float32Array([0,0,1,0,1,1,0,1]),s=t.indices||new Uint32Array([0,1,2,0,2,3]),a=t.shrinkBuffersToFit,o=new Y({data:r,label:"attribute-mesh-positions",shrinkToFit:a,usage:D.VERTEX|D.COPY_DST}),l=new Y({data:i,label:"attribute-mesh-uvs",shrinkToFit:a,usage:D.VERTEX|D.COPY_DST}),h=new Y({data:s,label:"index-mesh-buffer",shrinkToFit:a,usage:D.INDEX|D.COPY_DST});super({attributes:{aPosition:{buffer:o,format:"float32x2",stride:2*4,offset:0},aUV:{buffer:l,format:"float32x2",stride:2*4,offset:0}},indexBuffer:h,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}};lt.defaultOptions={topology:"triangle-list",shrinkBuffersToFit:!1};let ye=lt;function ar(n){const e=n._stroke,t=n._fill,i=[`div { ${[`color: ${R.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?[ct(e)]:[],...n.dropShadow?[ht(n.dropShadow)]:[],...n.cssOverrides].join(";")} }`];return or(n.tagStyles,i),i.join(" ")}function ht(n){const e=R.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),i=`${t}px ${r}px`;return n.blur>0?`text-shadow: ${i} ${n.blur}px ${e}`:`text-shadow: ${i} ${e}`}function ct(n){return[`-webkit-text-stroke-width: ${n.width}px`,`-webkit-text-stroke-color: ${R.shared.setValue(n.color).toHex()}`,`text-stroke-width: ${n.width}px`,`text-stroke-color: ${R.shared.setValue(n.color).toHex()}`,"paint-order: stroke"].join(";")}const ke={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"},Ue={fill:n=>`color: ${R.shared.setValue(n).toHex()}`,breakWords:n=>`word-wrap: ${n?"break-all":"break-word"}`,stroke:ct,dropShadow:ht};function or(n,e){for(const t in n){const r=n[t],i=[];for(const s in r)Ue[s]?i.push(Ue[s](r[s])):ke[s]&&i.push(ke[s].replace("{{VALUE}}",r[s]));e.push(`${t} { ${i.join(";")} }`)}}class Se extends I{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=Ze(this)+this._cssOverrides.join("-"),this._styleKey}update(){this._cssStyle=null,super.update()}clone(){return new Se({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=ar(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"&&$("[HTMLTextStyle] only color fill is not supported by HTMLText"),super.fill=e}set stroke(e){e&&typeof e!="string"&&typeof e!="number"&&$("[HTMLTextStyle] only color stroke is not supported by HTMLText"),super.stroke=e}}const We="http://www.w3.org/2000/svg",Ae="http://www.w3.org/1999/xhtml";class ut{constructor(){this.svgRoot=document.createElementNS(We,"svg"),this.foreignObject=document.createElementNS(We,"foreignObject"),this.domElement=document.createElementNS(Ae,"div"),this.styleElement=document.createElementNS(Ae,"style"),this.image=new Image;const{foreignObject:e,svgRoot:t,styleElement:r,domElement:i}=this;e.setAttribute("width","10000"),e.setAttribute("height","10000"),e.style.overflow="hidden",t.appendChild(e),e.appendChild(r),e.appendChild(i)}}let ze;function lr(n,e,t,r){r||(r=ze||(ze=new ut));const{domElement:i,styleElement:s,svgRoot:a}=r;i.innerHTML=`<style>${e.cssStyle};</style><div style='padding:0'>${n}</div>`,i.setAttribute("style","transform-origin: top left; display: inline-block"),t&&(s.textContent=t),document.body.appendChild(a);const o=i.getBoundingClientRect();a.remove();const l=e.padding*2;return{width:o.width-l,height:o.height-l}}class ft{constructor(e,t){this.state=ee.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],i=this.renderer.graphicsContext.updateGpuContext(t);return!!(i.isBatchable||r!==i.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 i=t[r];i._batcher.updateElement(i)}}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 s=r.customShader||this._adaptor.shader;this.state.blendMode=e.groupBlendMode;const a=s.resources.localUniforms.uniforms;a.uTransformMatrix=e.groupTransform,a.uRound=t._roundPixels|e._roundPixels,ie(e.groupColorAlpha,a.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,i=this._getBatchesForRenderable(e);for(let s=0;s<i.length;s++){const a=i[s];r.addToBatch(a,t)}}_getBatchesForRenderable(e){return this._graphicsBatchesHash[e.uid]||this._initBatchesForRenderable(e)}_initBatchesForRenderable(e){const t=e.context,r=this.renderer.graphicsContext.getGpuContext(t),i=this.renderer._roundPixels|e._roundPixels,s=r.batches.map(a=>{const o=v.get(Ut);return a.copyTo(o),o.renderable=e,o.roundPixels=i,o});return this._graphicsBatchesHash[e.uid]===void 0&&e.on("destroyed",this._destroyRenderableBound),this._graphicsBatchesHash[e.uid]=s,s}_removeBatchForRenderable(e){this._graphicsBatchesHash[e].forEach(t=>{v.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}}ft.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"graphics"};const pt=class gt extends ye{constructor(...e){super({});let t=e[0]??{};typeof t=="number"&&(k(W,"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={...gt.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=[],i=[],s=[],a=this.verticesX-1,o=this.verticesY-1,l=this.width/a,h=this.height/o;for(let c=0;c<t;c++){const f=c%this.verticesX,g=c/this.verticesX|0;r.push(f*l,g*h),i.push(f/a,g/o)}const d=a*o;for(let c=0;c<d;c++){const f=c%a,g=c/a|0,u=g*this.verticesX+f,m=g*this.verticesX+f+1,x=(g+1)*this.verticesX+f,_=(g+1)*this.verticesX+f+1;s.push(u,m,x,m,_,x)}this.buffers[0].data=new Float32Array(r),this.buffers[1].data=new Float32Array(i),this.indexBuffer.data=new Uint32Array(s),this.buffers[0].update(),this.buffers[1].update(),this.indexBuffer.update()}};pt.defaultOptions={width:100,height:100,verticesX:10,verticesY:10};let dr=pt;class we{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}get topology(){return this._topology||this.geometry.topology}set topology(e){this._topology=e}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 i=r;const s=this.texture.textureMatrix;return s.isSimple||(i=this._transformedUvs,(this._textureMatrixUpdateId!==s._updateID||this._uvUpdateId!==t._updateID)&&((!i||i.length<r.length)&&(i=this._transformedUvs=new Float32Array(r.length)),this._textureMatrixUpdateId=s._updateID,this._uvUpdateId=t._updateID,s.multiplyUvs(r,i))),i}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 mt{constructor(e,t){this.localUniforms=new j({uTransformMatrix:{value:new U,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),this.localUniformsBindGroup=new $e({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,i=e.batched;if(t.batched=i,r!==i)return!0;if(i){const s=e._geometry;if(s.indices.length!==t.indexSize||s.positions.length!==t.vertexSize)return t.indexSize=s.indices.length,t.vertexSize=s.positions.length,!0;const a=this._getBatchableMesh(e);return!a._batcher.checkAndUpdateTexture(a,e.texture)}return!1}addRenderable(e,t){const r=this.renderer.renderPipes.batch,{batched:i}=this._getMeshData(e);if(i){const s=this._getBatchableMesh(e);s.texture=e._texture,s.geometry=e._geometry,r.addToBatch(s,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&&(v.return(t),this._gpuBatchableMeshHash[e.uid]=null),e.off("destroyed",this._destroyRenderableBound)}execute(e){if(!e.isRenderable)return;e.state.blendMode=_e(e.groupBlendMode,e.texture._source);const t=this.localUniforms;t.uniforms.uTransformMatrix=e.groupTransform,t.uniforms.uRound=this.renderer._roundPixels|e._roundPixels,t.update(),ie(e.groupColorAlpha,t.uniforms.uColor,0),this._adaptor.execute(this,e)}_getMeshData(e){return this._meshDataHash[e.uid]||this._initMeshData(e)}_initMeshData(e){return this._meshDataHash[e.uid]={batched:e.batched,indexSize:e._geometry.indices?.length,vertexSize:e._geometry.positions?.length},e.on("destroyed",this._destroyRenderableBound),this._meshDataHash[e.uid]}_getBatchableMesh(e){return this._gpuBatchableMeshHash[e.uid]||this._initBatchableMesh(e)}_initBatchableMesh(e){const t=v.get(we);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]&&v.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}}mt.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"mesh"};class hr{execute(e,t){const r=e.state,i=e.renderer,s=t.shader||e.defaultShader;s.resources.uTexture=t.texture._source,s.resources.uniforms=e.localUniforms;const a=i.gl,o=e.getBuffers(t);i.shader.bind(s),i.state.set(r),i.geometry.bind(o.geometry,s.glProgram);const h=o.geometry.indexBuffer.data.BYTES_PER_ELEMENT===2?a.UNSIGNED_SHORT:a.UNSIGNED_INT;a.drawElements(a.TRIANGLES,t.particleChildren.length*6,h,0)}}class cr{execute(e,t){const r=e.renderer,i=t.shader||e.defaultShader;i.groups[0]=r.renderPipes.uniformBatch.getUniformBindGroup(e.localUniforms,!0),i.groups[1]=r.texture.getTextureBindGroup(t.texture);const s=e.state,a=e.getBuffers(t);r.encoder.draw({geometry:a.geometry,shader:t.shader||e.defaultShader,state:s,size:t.particleChildren.length*6})}}function Ge(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,i=0;r<t;r+=6,i+=4)e[r+0]=i+0,e[r+1]=i+1,e[r+2]=i+2,e[r+3]=i+0,e[r+4]=i+2,e[r+5]=i+3;return e}function ur(n){return{dynamicUpdate:He(n,!0),staticUpdate:He(n,!1)}}function He(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 s in n){const a=n[s];if(e!==a.dynamic)continue;t.push(`offset = index + ${r}`),t.push(a.code);const o=ue(a.format);r+=o.stride/4}t.push(`
|
|
index += stride * 4;
|
|
}
|
|
`),t.unshift(`
|
|
var stride = ${r};
|
|
`);const i=t.join(`
|
|
`);return new Function("ps","f32v","u32v",i)}class fr{constructor(e){this._size=0,this._generateParticleUpdateCache={};const t=this._size=e.size??1e3,r=e.properties;let i=0,s=0;for(const d in r){const c=r[d],f=ue(c.format);c.dynamic?s+=f.stride:i+=f.stride}this._dynamicStride=s/4,this._staticStride=i/4,this.staticAttributeBuffer=new N(t*4*i),this.dynamicAttributeBuffer=new N(t*4*s),this.indexBuffer=Ge(t);const a=new ge;let o=0,l=0;this._staticBuffer=new Y({data:new Float32Array(1),label:"static-particle-buffer",shrinkToFit:!1,usage:D.VERTEX|D.COPY_DST}),this._dynamicBuffer=new Y({data:new Float32Array(1),label:"dynamic-particle-buffer",shrinkToFit:!1,usage:D.VERTEX|D.COPY_DST});for(const d in r){const c=r[d],f=ue(c.format);c.dynamic?(a.addAttribute(c.attributeName,{buffer:this._dynamicBuffer,stride:this._dynamicStride*4,offset:o*4,format:c.format}),o+=f.size):(a.addAttribute(c.attributeName,{buffer:this._staticBuffer,stride:this._staticStride*4,offset:l*4,format:c.format}),l+=f.size)}a.addIndex(this.indexBuffer);const h=this.getParticleUpdate(r);this._dynamicUpload=h.dynamicUpdate,this._staticUpload=h.staticUpdate,this.geometry=a}getParticleUpdate(e){const t=pr(e);return this._generateParticleUpdateCache[t]?this._generateParticleUpdateCache[t]:(this._generateParticleUpdateCache[t]=this.generateParticleUpdate(e),this._generateParticleUpdateCache[t])}generateParticleUpdate(e){return ur(e)}update(e,t){e.length>this._size&&(t=!0,this._size=Math.max(e.length,this._size*1.5|0),this.staticAttributeBuffer=new N(this._size*this._staticStride*4*4),this.dynamicAttributeBuffer=new N(this._size*this._dynamicStride*4*4),this.indexBuffer=Ge(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 i=this.staticAttributeBuffer;this._staticUpload(e,i.float32View,i.uint32View),this._staticBuffer.setDataWithSize(i.float32View,e.length*this._staticStride*4,!0)}}destroy(){this._staticBuffer.destroy(),this._dynamicBuffer.destroy(),this.geometry.destroy()}}function pr(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 gr=`varying vec2 vUV;
|
|
varying vec4 vColor;
|
|
|
|
uniform sampler2D uTexture;
|
|
|
|
void main(void){
|
|
vec4 color = texture2D(uTexture, vUV) * vColor;
|
|
gl_FragColor = color;
|
|
}`,mr=`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 = vec4(aColor.rgb * aColor.a, aColor.a) * uColor;
|
|
}
|
|
`,De=`
|
|
struct ParticleUniforms {
|
|
uProjectionMatrix:mat3x3<f32>,
|
|
uColor:vec4<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);
|
|
|
|
let vColor = vec4(aColor.rgb * aColor.a, aColor.a) * uniforms.uColor;
|
|
|
|
return VSOutput(
|
|
position,
|
|
aUV,
|
|
vColor,
|
|
);
|
|
}
|
|
|
|
@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 _r extends xe{constructor(){const e=Wt.from({vertex:mr,fragment:gr}),t=At.from({fragment:{source:De,entryPoint:"mainFragment"},vertex:{source:De,entryPoint:"mainVertex"}});super({glProgram:e,gpuProgram:t,resources:{uTexture:A.WHITE.source,uSampler:new zt({}),uniforms:{uTranslationMatrix:{value:new U,type:"mat3x3<f32>"},uColor:{value:new R(16777215),type:"vec4<f32>"},uRound:{value:1,type:"f32"},uResolution:{value:[0,0],type:"vec2<f32>"}}}})}}class _t{constructor(e,t){this.state=ee.for2d(),this._gpuBufferHash=Object.create(null),this._destroyRenderableBound=this.destroyRenderable.bind(this),this.localUniforms=new j({uTranslationMatrix:{value:new U,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 _r,this.state=ee.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 fr({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,i=this.getBuffers(e);e.texture||(e.texture=t[0].texture);const s=this.state;i.update(t,e._childrenDirty),e._childrenDirty=!1,s.blendMode=_e(e.blendMode,e.texture._source);const a=this.localUniforms.uniforms,o=a.uTranslationMatrix;e.worldTransform.copyTo(o),o.prepend(r.globalUniforms.globalUniformData.projectionMatrix),a.uResolution=r.globalUniforms.globalUniformData.resolution,a.uRound=r._roundPixels|e._roundPixels,ie(e.groupColorAlpha,a.uColor,0),this.adaptor.execute(this,e)}destroy(){this.defaultShader&&(this.defaultShader.destroy(),this.defaultShader=null)}}class xt extends _t{constructor(e){super(e,new hr)}}xt.extension={type:[b.WebGLPipes],name:"particle"};class bt extends _t{constructor(e){super(e,new cr)}}bt.extension={type:[b.WebGPUPipes],name:"particle"};const yt=class St extends dr{constructor(e={}){e={...St.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,i=this._topHeight+this._bottomHeight,s=this.height>i?1:this.height/i,a=Math.min(r,s);e[9]=e[11]=e[13]=e[15]=this._topHeight*a,e[17]=e[19]=e[21]=e[23]=this.height-this._bottomHeight*a,e[25]=e[27]=e[29]=e[31]=this.height,e[2]=e[10]=e[18]=e[26]=this._leftWidth*a,e[4]=e[12]=e[20]=e[28]=this.width-this._rightWidth*a,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()}};yt.defaultOptions={width:100,height:100,leftWidth:10,topHeight:10,rightWidth:10,bottomHeight:10,originalWidth:100,originalHeight:100};let xr=yt;class wt{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=this._getGpuSprite(e);return!t._batcher.checkAndUpdateTexture(t,e._texture)}destroyRenderable(e){const t=this._gpuSpriteHash[e.uid];v.return(t.geometry),v.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=v.get(we);return t.geometry=v.get(xr),t.renderable=e,t.transform=e.groupTransform,t.texture=e._texture,t.roundPixels=this._renderer._roundPixels|e._roundPixels,this._gpuSpriteHash[e.uid]=t,e.didViewUpdate||this._updateBatchableSprite(e,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}}wt.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"nineSliceSprite"};const br={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);
|
|
`}},yr={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 oe,le;class Sr extends xe{constructor(){oe??(oe=Ke({name:"tiling-sprite-shader",bits:[$t,br,Xe]})),le??(le=Ye({name:"tiling-sprite-shader",bits:[jt,yr,Ne]}));const e=new j({uMapCoord:{value:new U,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 U,type:"mat3x3<f32>"},uSizeAnchor:{value:new Float32Array([100,100,.5,.5]),type:"vec4<f32>"}});super({glProgram:le,gpuProgram:oe,resources:{localUniforms:new j({uTransformMatrix:{value:new U,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),tilingUniforms:e,uTexture:A.EMPTY.source,uSampler:A.EMPTY.source.style}})}updateUniforms(e,t,r,i,s,a){const o=this.resources.tilingUniforms,l=a.width,h=a.height,d=a.textureMatrix,c=o.uniforms.uTextureTransform;c.set(r.a*l/e,r.b*l/t,r.c*h/e,r.d*h/t,r.tx/e,r.ty/t),c.invert(),o.uniforms.uMapCoord=d.mapCoord,o.uniforms.uClampFrame=d.uClampFrame,o.uniforms.uClampOffset=d.uClampOffset,o.uniforms.uTextureTransform=c,o.uniforms.uSizeAnchor[0]=e,o.uniforms.uSizeAnchor[1]=t,o.uniforms.uSizeAnchor[2]=i,o.uniforms.uSizeAnchor[3]=s,a&&(this.resources.uTexture=a.source,this.resources.uSampler=a.source.style)}}class wr extends ye{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 Tr(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 vr(n,e,t,r){let i=0;const s=n.length/e,a=r.a,o=r.b,l=r.c,h=r.d,d=r.tx,c=r.ty;for(t*=e;i<s;){const f=n[t],g=n[t+1];n[t]=a*f+l*g+d,n[t+1]=o*f+h*g+c,t+=e,i++}}function Br(n,e){const t=n.texture,r=t.frame.width,i=t.frame.height;let s=0,a=0;n.applyAnchorToTexture&&(s=n.anchor.x,a=n.anchor.y),e[0]=e[6]=-s,e[2]=e[4]=1-s,e[1]=e[3]=-a,e[5]=e[7]=1-a;const o=U.shared;o.copyFrom(n._tileTransform.matrix),o.tx/=n.width,o.ty/=n.height,o.invert(),o.scale(n.width/r,n.height/i),vr(e,2,0,o)}const Q=new wr;class Tt{constructor(e){this._state=ee.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 i=t.canBatch;if(i&&i===r){const{batchableMesh:s}=t;return!s._batcher.checkAndUpdateTexture(s,e.texture)}return r!==i}addRenderable(e,t){const r=this._renderer.renderPipes.batch;this._updateCanBatch(e);const i=this._getTilingSpriteData(e),{geometry:s,canBatch:a}=i;if(a){i.batchableMesh||(i.batchableMesh=new we);const o=i.batchableMesh;e.didViewUpdate&&(this._updateBatchableMesh(e),o.geometry=s,o.renderable=e,o.transform=e.groupTransform,o.texture=e._texture),o.roundPixels=this._renderer._roundPixels|e._roundPixels,r.addToBatch(o,t)}else r.break(t),i.shader||(i.shader=new Sr),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,ie(e.groupColorAlpha,r.uColor,0),this._state.blendMode=_e(e.groupBlendMode,e.texture._source),this._renderer.encoder.draw({geometry:Q,shader:t,state:this._state})}updateRenderable(e){const t=this._getTilingSpriteData(e),{canBatch:r}=t;if(r){const{batchableMesh:i}=t;e.didViewUpdate&&this._updateBatchableMesh(e),i._batcher.updateElement(i)}else if(e.didViewUpdate){const{shader:i}=t;i.updateUniforms(e.width,e.height,e._tileTransform.matrix,e.anchor.x,e.anchor.y,e.texture)}}destroyRenderable(e){const t=this._getTilingSpriteData(e);t.batchableMesh=null,t.shader?.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 ye({indices:Q.indices,positions:Q.positions.slice(),uvs:Q.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,i=e.texture.source.style;i.addressMode!=="repeat"&&(i.addressMode="repeat",i.update()),Br(e,r.uvs),Tr(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 i=!0;return this._renderer.type===me.WEBGL&&(i=this._renderer.context.supports.nonPowOf2wrapping),t.canBatch=r.textureMatrix.isSimple&&(i||r.source.isPowerOfTwo),t.canBatch}}Tt.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"tilingSprite"};const Cr={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));
|
|
`}},Pr={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));
|
|
`}},Rr={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;
|
|
|
|
}
|
|
`}},Fr={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 de,he;class Mr extends xe{constructor(){const e=new j({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new U,type:"mat3x3<f32>"},uDistance:{value:4,type:"f32"},uRound:{value:0,type:"f32"}}),t=Gt();de??(de=Ke({name:"sdf-shader",bits:[Ht,Dt(t),Cr,Rr,Xe]})),he??(he=Ye({name:"sdf-shader",bits:[Lt,It(t),Pr,Fr,Ne]})),super({glProgram:he,gpuProgram:de,resources:{localUniforms:e,batchSamplers:Ot(t)}})}}class vt{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);Le(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&&(v.return(t.customShader),t.customShader=null),v.return(this._gpuBitmapText[e]),this._gpuBitmapText[e]=null}updateRenderable(e){const t=this._getGpuBitmapText(e);Le(e,t),this._renderer.renderPipes.graphics.updateRenderable(t),t.context.customShader&&this._updateDistanceField(e)}_updateContext(e,t){const{context:r}=t,i=tr.getFont(e.text,e._style);r.clear(),i.distanceField.type!=="none"&&(r.customShader||(r.customShader=v.get(Mr)));const s=Array.from(e.text),a=e._style;let o=i.baseLineOffset;const l=st(s,a,i,!0);let h=0;const d=a.padding,c=l.scale;let f=l.width,g=l.height+l.offsetY;a._stroke&&(f+=a._stroke.width/c,g+=a._stroke.width/c),r.translate(-e._anchor._x*f-d,-e._anchor._y*g-d).scale(c,c);const u=i.applyFillAsTint?a._fill.color:16777215;for(let m=0;m<l.lines.length;m++){const x=l.lines[m];for(let _=0;_<x.charPositions.length;_++){const y=s[h++],S=i.chars[y];S?.texture&&r.texture(S.texture,u||"black",Math.round(x.charPositions[_]+S.xOffset),Math.round(o+S.yOffset))}o+=i.lineHeight}}_getGpuBitmapText(e){return this._gpuBitmapText[e.uid]||this.initGpuText(e)}initGpuText(e){const t=v.get(Et);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,i=G.get(`${r}-bitmap`),{a:s,b:a,c:o,d:l}=e.groupTransform,h=Math.sqrt(s*s+a*a),d=Math.sqrt(o*o+l*l),c=(Math.abs(h)+Math.abs(d))/2,f=i.baseRenderedFontSize/e._style.fontSize,g=c*i.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}}vt.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"bitmapText"};function Le(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 Bt{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 i=this._getGpuText(e).batchableSprite;e._didTextUpdate&&this._updateText(e),this._renderer.renderPipes.batch.addToBatch(i,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),v.return(t.batchableSprite),this._gpuText[e]=null}_updateText(e){const t=e._getKey(),r=this._getGpuText(e),i=r.batchableSprite;r.currentKey!==t&&this._updateGpuText(e).catch(a=>{console.error(a)}),e._didTextUpdate=!1;const s=e._style.padding;fe(i.bounds,e._anchor,i.texture,s)}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 i=e.resolution??this._renderer.resolution,s=await this._renderer.htmlText.getManagedTexture(e.text,i,e._style,e._getKey()),a=t.batchableSprite;a.texture=t.texture=s,t.generatingTexture=!1,t.textureNeedsUploading=!0,e.onViewUpdate();const o=e._style.padding;fe(a.bounds,e._anchor,a.texture,o)}_getGpuText(e){return this._gpuText[e.uid]||this.initGpuText(e)}initGpuText(e){const t={texture:A.EMPTY,currentKey:"--",batchableSprite:v.get(qe),textureNeedsUploading:!1,generatingTexture:!1},r=t.batchableSprite;return r.renderable=e,r.transform=e.groupTransform,r.texture=A.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}}Bt.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"htmlText"};function kr(){const{userAgent:n}=K.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(n)}const Ur=new je;function Ct(n,e,t,r){const i=Ur;i.minX=0,i.minY=0,i.maxX=n.width/r|0,i.maxY=n.height/r|0;const s=H.getOptimalTexture(i.width,i.height,r,!1);return s.source.uploadMethodId="image",s.source.resource=n,s.source.alphaMode="premultiply-alpha-on-upload",s.frame.width=e/r,s.frame.height=t/r,s.source.emit("update",s.source),s.updateUvs(),s}function Wr(n,e){const t=e.fontFamily,r=[],i={},s=/font-family:([^;"\s]+)/g,a=n.match(s);function o(l){i[l]||(r.push(l),i[l]=!0)}if(Array.isArray(t))for(let l=0;l<t.length;l++)o(t[l]);else o(t);a&&a.forEach(l=>{const h=l.split(":")[1].trim();o(h)});for(const l in e.tagStyles){const h=e.tagStyles[l].fontFamily;o(h)}return r}async function Ar(n){const t=await(await K.get().fetch(n)).blob(),r=new FileReader;return await new Promise((s,a)=>{r.onloadend=()=>s(r.result),r.onerror=a,r.readAsDataURL(t)})}async function Ie(n,e){const t=await Ar(e);return`@font-face {
|
|
font-family: "${n.fontFamily}";
|
|
src: url('${t}');
|
|
font-weight: ${n.fontWeight};
|
|
font-style: ${n.fontStyle};
|
|
}`}const J=new Map;async function zr(n,e,t){const r=n.filter(i=>G.has(`${i}-and-url`)).map((i,s)=>{if(!J.has(i)){const{url:a}=G.get(`${i}-and-url`);s===0?J.set(i,Ie({fontWeight:e.fontWeight,fontStyle:e.fontStyle,fontFamily:i},a)):J.set(i,Ie({fontWeight:t.fontWeight,fontStyle:t.fontStyle,fontFamily:i},a))}return J.get(i)});return(await Promise.all(r)).join(`
|
|
`)}function Gr(n,e,t,r,i){const{domElement:s,styleElement:a,svgRoot:o}=i;s.innerHTML=`<style>${e.cssStyle}</style><div style='padding:0;'>${n}</div>`,s.setAttribute("style",`transform: scale(${t});transform-origin: top left; display: inline-block`),a.textContent=r;const{width:l,height:h}=i.image;return o.setAttribute("width",l.toString()),o.setAttribute("height",h.toString()),new XMLSerializer().serializeToString(o)}function Hr(n,e){const t=O.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 Dr(n,e,t){return new Promise(async r=>{t&&await new Promise(i=>setTimeout(i,100)),n.onload=()=>{r()},n.src=`data:image/svg+xml;charset=utf8,${encodeURIComponent(e)}`,n.crossOrigin="anonymous"})}class Te{constructor(e){this._activeTextures={},this._renderer=e,this._createCanvas=e.type===me.WEBGPU}getTexture(e){return this._buildTexturePromise(e.text,e.resolution,e.style)}getManagedTexture(e,t,r,i){if(this._activeTextures[i])return this._increaseReferenceCount(i),this._activeTextures[i].promise;const s=this._buildTexturePromise(e,t,r).then(a=>(this._activeTextures[i].texture=a,a));return this._activeTextures[i]={texture:null,promise:s,usageCount:1},s}async _buildTexturePromise(e,t,r){const i=v.get(ut),s=Wr(e,r),a=await zr(s,r,Se.defaultTextStyle),o=lr(e,r,a,i),l=Math.ceil(Math.ceil(Math.max(1,o.width)+r.padding*2)*t),h=Math.ceil(Math.ceil(Math.max(1,o.height)+r.padding*2)*t),d=i.image,c=2;d.width=(l|0)+c,d.height=(h|0)+c;const f=Gr(e,r,t,a,i);await Dr(d,f,kr()&&s.length>0);const g=d;let u;this._createCanvas&&(u=Hr(d,t));const m=Ct(u?u.canvas:g,d.width-c,d.height-c,t);return this._createCanvas&&(this._renderer.texture.initSource(m.source),O.returnCanvasAndContext(u)),v.return(i),m}_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(()=>{$("HTMLTextSystem: Failed to clean texture")}),this._activeTextures[e]=null))}_cleanUp(e){H.returnTexture(e.texture),e.texture.source.resource=null,e.texture.source.uploadMethodId="unknown"}getReferenceCount(e){return this._activeTextures[e].usageCount}destroy(){this._activeTextures=null}}Te.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"htmlText"};Te.defaultFontOptions={fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal"};class Pt{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 i=this._getGpuText(e).batchableSprite;e._didTextUpdate&&this._updateText(e),this._renderer.renderPipes.batch.addToBatch(i,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),v.return(t.batchableSprite),this._gpuText[e]=null}_updateText(e){const t=e._getKey(),r=this._getGpuText(e),i=r.batchableSprite;r.currentKey!==t&&this._updateGpuText(e),e._didTextUpdate=!1;const s=e._style.padding;fe(i.bounds,e._anchor,i.texture,s)}_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:v.get(qe)};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}}Pt.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"text"};function Oe(n,e,t){for(let r=0,i=4*t*e;r<e;++r,i+=4)if(n[i+3]!==0)return!1;return!0}function Ee(n,e,t,r,i){const s=4*e;for(let a=r,o=r*s+4*t;a<=i;++a,o+=s)if(n[o+3]!==0)return!1;return!0}function Lr(n,e=1){const{width:t,height:r}=n,i=n.getContext("2d",{willReadFrequently:!0});if(i===null)throw new TypeError("Failed to get canvas 2D context");const a=i.getImageData(0,0,t,r).data;let o=0,l=0,h=t-1,d=r-1;for(;l<r&&Oe(a,t,l);)++l;if(l===r)return ce.EMPTY;for(;Oe(a,t,d);)--d;for(;Ee(a,t,o,l,d);)++o;for(;Ee(a,t,h,l,d);)--h;return++h,++d,new ce(o/e,l/e,(h-o)/e,(d-l)/e)}class Rt{constructor(e){this._activeTextures={},this._renderer=e}getTextureSize(e,t,r){const i=L.measureText(e||" ",r);let s=Math.ceil(Math.ceil(Math.max(1,i.width)+r.padding*2)*t),a=Math.ceil(Math.ceil(Math.max(1,i.height)+r.padding*2)*t);return s=Math.ceil(s-1e-6),a=Math.ceil(a-1e-6),s=Re(s),a=Re(a),{width:s,height:a}}getTexture(e,t,r,i){typeof e=="string"&&(k("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),e={text:e,style:r,resolution:t}),e.style instanceof I||(e.style=new I(e.style));const{texture:s,canvasAndContext:a}=this.createTextureAndCanvas(e);return this._renderer.texture.initSource(s._source),O.returnCanvasAndContext(a),s}createTextureAndCanvas(e){const{text:t,style:r}=e,i=e.resolution??this._renderer.resolution,s=L.measureText(t||" ",r),a=Math.ceil(Math.ceil(Math.max(1,s.width)+r.padding*2)*i),o=Math.ceil(Math.ceil(Math.max(1,s.height)+r.padding*2)*i),l=O.getOptimalCanvasAndContext(a,o),{canvas:h}=l;this.renderTextToCanvas(t,r,i,l);const d=Ct(h,a,o,i);if(r.trim){const c=Lr(h,i);d.frame.copyFrom(c),d.updateUvs()}return{texture:d,canvasAndContext:l}}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:i}=this.createTextureAndCanvas(e);return this._activeTextures[t]={canvasAndContext:i,texture:r,usageCount:1},r}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}decreaseReferenceCount(e){const t=this._activeTextures[e];if(t.usageCount--,t.usageCount===0){O.returnCanvasAndContext(t.canvasAndContext),H.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,i){const{canvas:s,context:a}=i,o=te(t),l=L.measureText(e||" ",t),h=l.lines,d=l.lineHeight,c=l.lineWidths,f=l.maxLineWidth,g=l.fontProperties,u=s.height;if(a.resetTransform(),a.scale(r,r),a.textBaseline=t.textBaseline,t._stroke?.width){const y=t._stroke;a.lineWidth=y.width,a.miterLimit=y.miterLimit,a.lineJoin=y.join,a.lineCap=y.cap}a.font=o;let m,x;const _=t.dropShadow?2:1;for(let y=0;y<_;++y){const S=t.dropShadow&&y===0,w=S?Math.ceil(Math.max(1,u)+t.padding*2):0,B=w*r;if(S){a.fillStyle="black",a.strokeStyle="black";const T=t.dropShadow,M=T.color,X=T.alpha;a.shadowColor=R.shared.setValue(M).setAlpha(X).toRgbaString();const se=T.blur*r,ve=T.distance*r;a.shadowBlur=se,a.shadowOffsetX=Math.cos(T.angle)*ve,a.shadowOffsetY=Math.sin(T.angle)*ve+B}else a.fillStyle=t._fill?re(t._fill,a):null,t._stroke?.width&&(a.strokeStyle=re(t._stroke,a)),a.shadowColor="black";let F=(d-g.fontSize)/2;d-g.fontSize<0&&(F=0);const C=t._stroke?.width??0;for(let T=0;T<h.length;T++)m=C/2,x=C/2+T*d+g.ascent+F,t.align==="right"?m+=f-c[T]:t.align==="center"&&(m+=(f-c[T])/2),t._stroke?.width&&this._drawLetterSpacing(h[T],t,i,m+t.padding,x+t.padding-w,!0),t._fill!==void 0&&this._drawLetterSpacing(h[T],t,i,m+t.padding,x+t.padding-w)}}_drawLetterSpacing(e,t,r,i,s,a=!1){const{context:o}=r,l=t.letterSpacing;let h=!1;if(L.experimentalLetterSpacingSupported&&(L.experimentalLetterSpacing?(o.letterSpacing=`${l}px`,o.textLetterSpacing=`${l}px`,h=!0):(o.letterSpacing="0px",o.textLetterSpacing="0px")),l===0||h){a?o.strokeText(e,i,s):o.fillText(e,i,s);return}let d=i;const c=L.graphemeSegmenter(e);let f=o.measureText(e).width,g=0;for(let u=0;u<c.length;++u){const m=c[u];a?o.strokeText(m,d,s):o.fillText(m,d,s);let x="";for(let _=u+1;_<c.length;++_)x+=c[_];g=o.measureText(x).width,d+=f-g+l,f=g}}destroy(){this._activeTextures=null}}Rt.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"canvasText"};P.add(Qe);P.add(Je);P.add(ft);P.add(Vt);P.add(mt);P.add(xt);P.add(bt);P.add(Rt);P.add(Pt);P.add(vt);P.add(Te);P.add(Bt);P.add(Tt);P.add(wt);P.add(ot);P.add(nt);
|