@therealjsmastery/jsm-hq 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +119 -2
  3. package/TRADEMARKS.md +17 -0
  4. package/bin/jsm-hq.mjs +50 -0
  5. package/dist/assets/CanvasPool-O1IaWL-9.js +1 -0
  6. package/dist/assets/CanvasRenderer-Dd4pZNIN.js +1 -0
  7. package/dist/assets/RenderTargetSystem-BccyHTeF.js +184 -0
  8. package/dist/assets/WebGLRenderer-1zkR__s9.js +156 -0
  9. package/dist/assets/WebGPURenderer-CSiZQVKf.js +75 -0
  10. package/dist/assets/browserAll-K-v47ayM.js +14 -0
  11. package/dist/assets/canvasUtils-C3DGUQjp.js +1 -0
  12. package/dist/assets/getTexelRangeRects-D8_SvULv.js +195 -0
  13. package/dist/assets/index-BHNtDgvI.css +1 -0
  14. package/dist/assets/index-DPTN0V6X.js +311 -0
  15. package/dist/assets/pixelify-sans-cyrillic-400-normal-DfOZNMlW.woff +0 -0
  16. package/dist/assets/pixelify-sans-cyrillic-600-normal-B3EuUOZG.woff +0 -0
  17. package/dist/assets/pixelify-sans-cyrillic-700-normal-BrZTw8tu.woff +0 -0
  18. package/dist/assets/pixelify-sans-latin-400-normal-DLrIX9QE.woff2 +0 -0
  19. package/dist/assets/pixelify-sans-latin-400-normal-JapMNN6Z.woff +0 -0
  20. package/dist/assets/pixelify-sans-latin-600-normal-BNlgYbDL.woff +0 -0
  21. package/dist/assets/pixelify-sans-latin-600-normal-Dd_Dy7u5.woff2 +0 -0
  22. package/dist/assets/pixelify-sans-latin-700-normal-BctWAS0u.woff +0 -0
  23. package/dist/assets/pixelify-sans-latin-700-normal-D3Xxx3QE.woff2 +0 -0
  24. package/dist/assets/pixelify-sans-latin-ext-400-normal-BkfTUL4s.woff +0 -0
  25. package/dist/assets/pixelify-sans-latin-ext-400-normal-DdH6zlBQ.woff2 +0 -0
  26. package/dist/assets/pixelify-sans-latin-ext-600-normal-CDaIumwU.woff +0 -0
  27. package/dist/assets/pixelify-sans-latin-ext-600-normal-Dha6RiOG.woff2 +0 -0
  28. package/dist/assets/pixelify-sans-latin-ext-700-normal-BadXkHzZ.woff +0 -0
  29. package/dist/assets/pixelify-sans-latin-ext-700-normal-ClyJstAh.woff2 +0 -0
  30. package/dist/assets/vt323-latin-400-normal-Dqn9ZSPj.woff +0 -0
  31. package/dist/assets/vt323-latin-400-normal-wDgJuOC9.woff2 +0 -0
  32. package/dist/assets/vt323-latin-ext-400-normal-DqOq58ri.woff +0 -0
  33. package/dist/assets/vt323-latin-ext-400-normal-iUdYUaX4.woff2 +0 -0
  34. package/dist/assets/vt323-vietnamese-400-normal-D0VnvwZ9.woff2 +0 -0
  35. package/dist/assets/vt323-vietnamese-400-normal-D_5Q7Vcv.woff +0 -0
  36. package/dist/assets/webworkerAll-wf0zq30l.js +83 -0
  37. package/dist/index.html +14 -0
  38. package/dist-server/main.mjs +2342 -0
  39. package/package.json +79 -4
  40. package/scripts/fix-node-pty.mjs +17 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 JavaScript Mastery
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,120 @@
1
- # Temporary Holding Version
1
+ # JSM HQ
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A pixel-art office where you run a team of AI coding agents on your repo. One lead plans the work and assigns tasks; each worker gets its own desk, its own copy of the repo and its own Docker Sandbox. The office shows the team's work as it happens: the plan, tasks, pull requests, reviews and deploys.
4
+
5
+ Agents can run **Claude Code** or **Codex**. Everything runs on your machine.
6
+
7
+ ## Quickstart (2 minutes)
8
+
9
+ From inside any git repo:
10
+
11
+ ```bash
12
+ cd ~/developer/my-app
13
+ npx @therealjsmastery/jsm-hq
14
+ ```
15
+
16
+ HQ opens your browser and walks you through the rest:
17
+
18
+ 1. **Welcome:** name the project, pick a lead and workers (Claude Code or Codex for each) and a review tool. HQ saves this to `.jsmhq/config.json` in your repo.
19
+ 2. **Setup checklist:** if something is missing on your machine, HQ shows what to install, with a Copy button, docs links and, for safe commands, **Run in terminal**.
20
+ 3. **Start the team** from the top bar, then message the lead from their **Messages** tab, for example: *"Plan two small tasks for Bob and assign the first one."*
21
+
22
+ Want to try it without touching a real project? Make a throwaway repo:
23
+
24
+ ```bash
25
+ mkdir hq-test && cd hq-test
26
+ git init -b main && echo "# HQ test" > README.md && git add . && git commit -m init
27
+ npx @therealjsmastery/jsm-hq
28
+ ```
29
+
30
+ Use it often? Install it once and run `jsm-hq` from any repo:
31
+
32
+ ```bash
33
+ npm install -g @therealjsmastery/jsm-hq
34
+ jsm-hq
35
+ ```
36
+
37
+ ### Options
38
+
39
+ ```
40
+ jsm-hq --repo <path> the repo to manage (default: current folder)
41
+ --port <n> HQ port (default: 7420)
42
+ --no-open don't open the browser
43
+ --version, --help
44
+ ```
45
+
46
+ ## Requirements
47
+
48
+ | What | Why | Install (macOS) |
49
+ | ------------------------ | ------------------------------------------------ | ------------------------------------------------------------------------- |
50
+ | Node.js 20+ | Runs HQ | [nodejs.org](https://nodejs.org) |
51
+ | git | Each agent works in its own clone | `xcode-select --install` |
52
+ | tmux | Agents keep running if HQ or the browser closes | `brew install tmux` |
53
+ | Docker Sandboxes (`sbx`) | Each agent runs in its own microVM | `brew trust docker/tap && brew install docker/tap/sbx`, then `sbx login` |
54
+ | GitHub CLI (`gh`) | PRs and reviews (optional) | `brew install gh`, then `gh auth login` |
55
+
56
+ Sandboxes need macOS 14+ on Apple silicon, Windows 11, or Ubuntu 24.04+. On other machines, set agents to **Local** in Settings → Team. They then run Claude Code or Codex installed on your machine, with permission prompts on.
57
+
58
+ ## How it works
59
+
60
+ - **Workspaces.** Each agent gets a full clone of your repo at `~/.jsmhq/<project>/<agent>/`. HQ writes the agent's `ROLE.md`, hooks and MCP config there and excludes them from git.
61
+ - **Sessions.** Each agent runs in a tmux session (`hq-<project>-<agent>`) inside its sandbox. Its live terminal is in the agent's drawer, and you can attach from any terminal with `tmux attach -t hq-<project>-<agent>`.
62
+ - **Team MCP.** Agents talk to each other and to HQ through an MCP server called `hq`. The lead creates boards and tasks and assigns them; anyone can send a message. HQ delivers it right away if the agent is idle, or when its current turn ends if it's busy.
63
+ - **GitHub.** HQ reads PRs, checks and review comments through your `gh` login (every ~20 seconds). It matches PRs to tasks by `[TASK-ID]` in the title, tells the author about review comments, tells the lead when a PR passes and marks the task done when you merge. **HQ never merges.**
64
+ - **Sandbox settings** (Settings → Sandbox) go straight to `sbx`: CPU and memory, allowed and blocked domains, service keys, an env file for app variables, and the upstream proxy. HQ never stores key values, never reads your env files and only removes rules it added.
65
+ - **Files in your repo.** `.jsmhq/config.json` (team and workflow) and `.jsmhq/plan.json` (boards and tasks) are safe to commit. Turn on **Settings → Project → Export plan** to also get a readable `docs/plan.md`.
66
+
67
+ ## Troubleshooting
68
+
69
+ | Problem | Fix |
70
+ | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
71
+ | Agents fail to start with a sign-in error | Your Docker sign-in expired. Run `sbx login`, then **Check again** in the setup checklist. |
72
+ | A Codex agent is stuck on "Do you trust this folder?" | Codex asks once per workspace, and again to trust HQ's hooks. Answer it in the agent's terminal. HQ never answers trust prompts for you. |
73
+ | "Port 7420 is in use" | Another HQ is running. Stop it, or use `npx @therealjsmastery/jsm-hq --port 7421`. |
74
+ | Agent state never changes / messages never arrive | The sandbox can't reach HQ. Check that `sbx policy ls` shows `localhost:<port>` and `host.docker.internal:<port>` allowed. HQ adds them on start if they're missing. |
75
+ | Windows | Run HQ inside WSL 2 (Ubuntu 24.04+). tmux isn't available on native Windows. |
76
+ | `posix_spawnp failed` when opening a terminal | Reinstall (`npx clear-npx-cache` then `npx @therealjsmastery/jsm-hq`). HQ fixes the node-pty helper's permissions on install and on start. |
77
+
78
+ **Clean up a project:** remove each agent in Settings → Team (it deletes the sandbox and, if you choose, the folder), then delete `~/.jsmhq/<project>`.
79
+
80
+ ## Develop JSM HQ
81
+
82
+ Needs Node.js 20+ and pnpm 10 or 11 (`corepack enable` gets you pnpm).
83
+
84
+ ```bash
85
+ git clone https://github.com/jsmastery-pro/jsm-hq && cd jsm-hq
86
+ pnpm install
87
+ pnpm dev # UI with mock data, no agents
88
+ HQ_REPO=~/developer/hq-test pnpm dev:hq # real HQ server + UI with hot reload
89
+ ```
90
+
91
+ | Command | Does |
92
+ | ---------------- | ---------------------------------------------------------------------------- |
93
+ | `pnpm dev` | Demo UI with mock data at http://localhost:5173 (nothing leaves the browser) |
94
+ | `pnpm dev:hq` | HQ server + UI with hot reload (`HQ_REPO=<path>`) |
95
+ | `pnpm hq` | Builds the UI, then runs HQ like a release (`--repo <path> --port 7420`) |
96
+ | `pnpm build` | Type-checks, builds the UI to `dist/` and the server to `dist-server/` |
97
+ | `pnpm typecheck` | Type-check only |
98
+ | `npm pack` | Builds and packs the npm tarball, to test it before publishing |
99
+
100
+ **Releasing:** bump `version` in `package.json`, merge to `main`, then from a clean `main` run `npm publish` (it builds first). Only members of the `therealjsmastery` npm org can publish.
101
+
102
+ Start HQ with `HQ_DEBUG=1` to log why a queued message is waiting.
103
+
104
+ **Keyboard:** `1`–`9` jump to an agent · `Esc` closes panels · `D` toggles debug · `+` / `-` zoom. Drag to pan, scroll to zoom.
105
+
106
+ ```
107
+ src/
108
+ data/ Domain types, the OfficeDataSource interface, mock (data/mock) and real (data/ws) sources
109
+ store/ Zustand stores; the only code that talks to the data source
110
+ office/ The PixiJS pixel office: layout generator, sprites, agents, belt
111
+ ui/ Top bar, team panel, activity feed, drawers, settings, setup checklist, welcome
112
+ server/ Local HQ server: setup checks, workspaces, tmux + sbx sessions, hooks, Team MCP, GitHub
113
+ bin/ The jsm-hq command
114
+ docs/ Product idea and build spec
115
+ context/ Implementation plans
116
+ ```
117
+
118
+ ## License
119
+
120
+ Code: [MIT](LICENSE). The JSM HQ name and logo are not covered by the license; see [TRADEMARKS.md](TRADEMARKS.md).
package/TRADEMARKS.md ADDED
@@ -0,0 +1,17 @@
1
+ # Trademarks
2
+
3
+ The code in this repository is MIT licensed (see `LICENSE`). The license covers the code only.
4
+
5
+ The names **JSM HQ**, **JavaScript Mastery** and **JSM**, and their logos, are trademarks of JavaScript Mastery. The MIT license does not give you any right to use them.
6
+
7
+ **You may:**
8
+
9
+ - Say that your project is based on, forked from or works with JSM HQ.
10
+ - Use the name in plain text to refer to this project, for example in a blog post or a talk.
11
+
12
+ **Please don't:**
13
+
14
+ - Publish a fork, package or hosted service under the name JSM HQ, or a name or logo that could be confused with it.
15
+ - Suggest that JavaScript Mastery made, endorses or supports your version.
16
+
17
+ If you publish a fork, give it a different name and logo. Questions: open an issue on the repository.
package/bin/jsm-hq.mjs ADDED
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ // jsm-hq — run JSM HQ for the git repo you're in.
3
+ import { readFileSync } from "node:fs";
4
+
5
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
6
+ const args = process.argv.slice(2);
7
+
8
+ if (args.includes("--version") || args.includes("-v")) {
9
+ console.log(pkg.version);
10
+ process.exit(0);
11
+ }
12
+ if (args.includes("--help") || args.includes("-h")) {
13
+ console.log(`JSM HQ ${pkg.version} — a pixel office for your team of AI coding agents.
14
+
15
+ Usage:
16
+ npx @therealjsmastery/jsm-hq [options] run inside a git repo
17
+
18
+ Options:
19
+ --repo <path> the git repo to manage (default: current folder)
20
+ --port <n> HQ server port (default: 7420)
21
+ --no-open don't open the browser
22
+ -v, --version print the version
23
+ -h, --help show this help
24
+
25
+ Needs: Docker Sandboxes (sbx) or Claude Code/Codex, tmux, git, gh.
26
+ HQ checks all of this on start and shows how to fix anything missing.
27
+ Docs: ${pkg.homepage ?? "https://github.com/jsmastery-pro/jsm-hq"}`);
28
+ process.exit(0);
29
+ }
30
+
31
+ const major = Number(process.versions.node.split(".")[0]);
32
+ if (major < 20) {
33
+ console.error(`JSM HQ needs Node.js 20 or newer (you have ${process.versions.node}).`);
34
+ process.exit(1);
35
+ }
36
+
37
+ // Check option values here so a typo gets a clear message instead of a silent default.
38
+ const fail = (msg) => {
39
+ console.error(`jsm-hq: ${msg}\nRun "npx @therealjsmastery/jsm-hq --help" for usage.`);
40
+ process.exit(1);
41
+ };
42
+ for (const name of ["--repo", "--port"]) {
43
+ const i = args.indexOf(name);
44
+ if (i === -1) continue;
45
+ const value = args[i + 1];
46
+ if (value === undefined || value.startsWith("-")) fail(`${name} needs a value.`);
47
+ if (name === "--port" && !(/^\d+$/.test(value) && Number(value) >= 1024 && Number(value) <= 65535)) fail(`--port must be a number from 1024 to 65535 (got "${value}").`);
48
+ }
49
+
50
+ await import("../dist-server/main.mjs");
@@ -0,0 +1 @@
1
+ import{S as _,a as S,G as m,b as w,c as C,d as u,v as g,D as x,w as F,n as p,i as b,e as k}from"./index-DPTN0V6X.js";const v=class o extends _{constructor(e){e={...o.defaultOptions,...e},super(e),this.enabled=!0,this._state=S.for2d(),this.blendMode=e.blendMode,this.padding=e.padding,typeof e.antialias=="boolean"?this.antialias=e.antialias?"on":"off":this.antialias=e.antialias,this.resolution=e.resolution,this.blendRequired=e.blendRequired,this.clipToViewport=e.clipToViewport,this.addResource("uTexture",0,1),e.blendRequired&&this.addResource("uBackTexture",0,3)}apply(e,s,t,n){e.applyFilter(this,s,t,n)}get blendMode(){return this._state.blendMode}set blendMode(e){this._state.blendMode=e}static from(e){const{gpu:s,gl:t,...n}=e;let i,a;return s&&(i=m.from(s)),t&&(a=w.from(t)),new o({gpuProgram:i,glProgram:a,...n})}};v.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let R=v;const c=32767;function f(h,e){return(h<<17)+(e<<2)}class M{constructor(e){this._buckets=new Map,this._screens=new C,this._enableFullScreen=!1,this.canvasOptions=e||{}}get enableFullScreen(){return u(g,"CanvasPool.enableFullScreen is no longer used, the pool sizes canvases to the screens registered with setScreenSize."),this._enableFullScreen}set enableFullScreen(e){u(g,"CanvasPool.enableFullScreen is no longer used, the pool sizes canvases to the screens registered with setScreenSize."),this._enableFullScreen=e}_createCanvasAndContext(e,s){const t=x.get().createCanvas();t.width=e,t.height=s;const n=t.getContext("2d");return{canvas:t,context:n}}getOptimalCanvasAndContext(e,s,t=1){const{width:n,height:i}=this.getOptimalSize(e,s,t);(n>c||i>c)&&F(`CanvasPool: ${n}x${i} is larger than the ${c}px pool key limit, canvases of this size may be pooled together`);const a=f(n,i);let r=this._buckets.get(a);r||(r=[],this._buckets.set(a,r));let l=r.pop();return l||(l=this._createCanvasAndContext(n,i)),l}getOptimalSize(e,s,t=1){const n=Math.ceil(e*t-1e-6),i=Math.ceil(s*t-1e-6),a=p(n),r=this._screens.getFittingWidth(n),l=p(i),d=this._screens.getFittingHeight(i);return{width:r!==void 0?Math.min(r,a):a,height:d!==void 0?Math.min(d,l):l}}returnCanvasAndContext(e){const s=e.canvas,{width:t,height:n}=s,i=this._buckets.get(f(t,n));i&&(e.context.resetTransform(),e.context.clearRect(0,0,t,n),i.push(e))}setScreenSize(e,s,t){this._screens.set(e,s,t)&&this._pruneScreenCanvases()}removeScreen(e){this._screens.remove(e)&&this._pruneScreenCanvases()}clear(){this._buckets.clear()}_pruneScreenCanvases(){for(const[e]of this._buckets){const s=e>>>17,t=e>>>2&32767;(b(s)||this._screens.hasWidth(s))&&(b(t)||this._screens.hasHeight(t))||this._buckets.delete(e)}}}const y=new M;k.register(y);export{y as C,R as F};
@@ -0,0 +1 @@
1
+ import{g as Se,l as Me,m as oe,M as G,o as S,p as Xe,w as we,s as Re,q as Ie,C as Ae,T as Be,r as ze,F as Je,t as Ke,x as Qe,D as He,A as Ze,R as et,y as ne}from"./index-DPTN0V6X.js";import{R as tt,S as st,B as nt,a as at,b as rt,c as ot,A as it,C as ct}from"./RenderTargetSystem-BccyHTeF.js";import{c as P,a as lt}from"./canvasUtils-C3DGUQjp.js";import"./CanvasPool-O1IaWL-9.js";const ge=class X{static _getPatternRepeat(e,t){const s=e&&e!=="clamp-to-edge",n=t&&t!=="clamp-to-edge";return s&&n?"repeat":s?"repeat-x":n?"repeat-y":"no-repeat"}start(e,t,s){}execute(e,t){var c,i,l,u;const s=t.elements;if(!s||!s.length)return;const n=e.renderer,r=n.canvasContext,o=r.activeContext;for(let x=0;x<s.length;x++){const E=s[x];if(!E.packAsQuad)continue;const v=E,f=v.texture,M=f?P.getCanvasSource(f):null;if(!M)continue;const y=f.source.style,A=r.smoothProperty,Y=y.scaleMode!=="nearest";o[A]!==Y&&(o[A]=Y),r.setBlendMode(t.blendMode);const U=((c=n.globalUniforms.globalUniformData)==null?void 0:c.worldColor)??4294967295,W=v.color,k=(U>>>24&255)/255,C=(W>>>24&255)/255,V=((i=n.filter)==null?void 0:i.alphaMultiplier)??1,Q=k*C*V;if(Q<=0)continue;o.globalAlpha=Q;const Z=U&16777215,z=W&16777215,_=Me(oe(z,Z)),w=f.frame,R=y.addressModeU??y.addressMode,ce=y.addressModeV??y.addressMode,ee=X._getPatternRepeat(R,ce),q=f.source._resolution??f.source.resolution??1,$=(u=(l=v.renderable)==null?void 0:l.renderGroup)==null?void 0:u.isCachedAsTexture,p=w.x*q,m=w.y*q,g=w.width*q,L=w.height*q,I=v.bounds,b=n.renderTarget.renderTarget.isRoot,D=I.minX,F=I.minY,B=I.maxX-I.minX,H=I.maxY-I.minY,N=f.rotate,h=f.uvs,O=Math.min(h.x0,h.x1,h.x2,h.x3,h.y0,h.y1,h.y2,h.y3),j=Math.max(h.x0,h.x1,h.x2,h.x3,h.y0,h.y1,h.y2,h.y3),T=ee!=="no-repeat"&&(O<0||j>1),ae=N&&!(!T&&(_!==16777215||N));ae?(X._tempPatternMatrix.copyFrom(v.transform),Se.matrixAppendRotationInv(X._tempPatternMatrix,N,D,F,B,H),r.setContextTransform(X._tempPatternMatrix,v.roundPixels===1,void 0,$&&b)):r.setContextTransform(v.transform,v.roundPixels===1,void 0,$&&b);const le=B,he=H;let te=ae?0:D,se=ae?0:F;if(!ae&&v.roundPixels===1&&(te|=0,se|=0),T){let de=M;const J=_!==16777215&&!N,K=w.width<=f.source.width&&w.height<=f.source.height;J&&K&&(de=P.getTintedCanvas({texture:f},_));const pe=o.createPattern(de,ee);if(!pe)continue;const ye=le,xe=he;if(ye===0||xe===0)continue;const Ce=1/ye,Te=1/xe,Pe=(h.x1-h.x0)*Ce,ke=(h.y1-h.y0)*Ce,_e=(h.x3-h.x0)*Te,be=(h.y3-h.y0)*Te,Ve=h.x0-Pe*te-_e*se,$e=h.y0-ke*te-be*se,ue=f.source.pixelWidth,me=f.source.pixelHeight;X._tempPatternMatrix.set(Pe*ue,ke*me,_e*ue,be*me,Ve*ue,$e*me),P.applyPatternTransform(pe,X._tempPatternMatrix),o.fillStyle=pe,o.fillRect(te,se,le,he)}else{const J=_!==16777215||N?P.getTintedCanvas({texture:f},_):M,K=J!==M;o.drawImage(J,K?0:p,K?0:m,K?J.width:g,K?J.height:L,te,se,le,he)}}}};ge._tempPatternMatrix=new G;ge.extension={type:[S.CanvasPipesAdaptor],name:"batch"};let ht=ge;class Ge{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,s){this._renderer.renderPipes.batch.break(s);const n=this._colorStack;n[this._colorStackIndex]=n[this._colorStackIndex-1]&e.mask;const r=this._colorStack[this._colorStackIndex];r!==this._currentColor&&(this._currentColor=r,s.add({renderPipeId:"colorMask",colorMask:r,canBundle:!1})),this._colorStackIndex++}pop(e,t,s){this._renderer.renderPipes.batch.break(s);const n=this._colorStack;this._colorStackIndex--;const r=n[this._colorStackIndex-1];r!==this._currentColor&&(this._currentColor=r,s.add({renderPipeId:"colorMask",colorMask:r,canBundle:!1}))}execute(e){}destroy(){this._renderer=null,this._colorStack=null}}Ge.extension={type:[S.CanvasPipes],name:"colorMask"};function dt(a,e,t,s,n,r){r=Math.max(0,Math.min(r,Math.min(s,n)/2)),a.moveTo(e+r,t),a.lineTo(e+s-r,t),a.quadraticCurveTo(e+s,t,e+s,t+r),a.lineTo(e+s,t+n-r),a.quadraticCurveTo(e+s,t+n,e+s-r,t+n),a.lineTo(e+r,t+n),a.quadraticCurveTo(e,t+n,e,t+n-r),a.lineTo(e,t+r),a.quadraticCurveTo(e,t,e+r,t)}function Ee(a,e){switch(e.type){case"rectangle":{const t=e;a.rect(t.x,t.y,t.width,t.height);break}case"roundedRectangle":{const t=e;dt(a,t.x,t.y,t.width,t.height,t.radius);break}case"circle":{const t=e;a.moveTo(t.x+t.radius,t.y),a.arc(t.x,t.y,t.radius,0,Math.PI*2);break}case"ellipse":{const t=e;a.ellipse?(a.moveTo(t.x+t.halfWidth,t.y),a.ellipse(t.x,t.y,t.halfWidth,t.halfHeight,0,0,Math.PI*2)):(a.save(),a.translate(t.x,t.y),a.scale(t.halfWidth,t.halfHeight),a.moveTo(1,0),a.arc(0,0,1,0,Math.PI*2),a.restore());break}case"triangle":{const t=e;a.moveTo(t.x,t.y),a.lineTo(t.x2,t.y2),a.lineTo(t.x3,t.y3),a.closePath();break}case"polygon":default:{const t=e,s=t.points;if(!(s!=null&&s.length))break;a.moveTo(s[0],s[1]);for(let n=2;n<s.length;n+=2)a.lineTo(s[n],s[n+1]);t.closePath&&a.closePath();break}}}function pt(a,e,t){const s=[],n=[],r=[],o=Re[e.type];if(!(o!=null&&o.build(e,s)))return!1;const c=e.closePath??!0;Ie(s,t,!1,c,n,r);for(let i=0;i<r.length;i+=3){const l=r[i]*2,u=r[i+1]*2,x=r[i+2]*2;a.moveTo(n[l],n[l+1]),a.lineTo(n[u],n[u+1]),a.lineTo(n[x],n[x+1]),a.closePath()}return!0}function ut(a,e){if(!(e!=null&&e.length))return!1;for(let t=0;t<e.length;t++){const s=e[t];if(!(s!=null&&s.shape))continue;const n=s.transform,r=n&&!n.isIdentity();r&&(a.save(),a.transform(n.a,n.b,n.c,n.d,n.tx,n.ty)),Ee(a,s.shape),r&&a.restore()}return!0}class We{constructor(e){this._warnedMaskTypes=new Set,this._canvasMaskStack=[],this._renderer=e}push(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"stencilMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){var u,x,E;if(e.action!=="pushMaskBegin"&&e.action!=="popMaskEnd")return;const t=this._renderer,s=t.canvasContext,n=s==null?void 0:s.activeContext;if(!n)return;if(e.action==="popMaskEnd"){this._canvasMaskStack.pop()&&n.restore();return}e.inverse&&this._warnOnce("inverse","CanvasRenderer: inverse masks are not supported on Canvas2D; ignoring inverse flag.");const r=e.mask.mask;if(!(r instanceof Xe)){this._warnOnce("nonGraphics","CanvasRenderer: only Graphics masks are supported in Canvas2D; skipping mask."),this._canvasMaskStack.push(!1);return}const o=r,c=(u=o.context)==null?void 0:u.instructions;if(!(c!=null&&c.length)){this._canvasMaskStack.push(!1);return}n.save(),s.setContextTransform(o.groupTransform,(t._roundPixels|o._roundPixels)===1),n.beginPath();let i=!1,l=!1;for(let v=0;v<c.length;v++){const f=c[v],M=f.action;if(M!=="fill"&&M!=="stroke")continue;const y=f.data,A=(x=y==null?void 0:y.path)==null?void 0:x.shapePath;if(!((E=A==null?void 0:A.shapePrimitives)!=null&&E.length))continue;const Y=M==="stroke",U=A.shapePrimitives;for(let W=0;W<U.length;W++){const k=U[W];if(!(k!=null&&k.shape))continue;const C=k.transform,V=C&&!C.isIdentity();V&&(n.save(),n.transform(C.a,C.b,C.c,C.d,C.tx,C.ty)),Y&&y.style?i=pt(n,k.shape,y.style)||i:(Ee(n,k.shape),l=ut(n,k.holes)||l,i=!0),V&&n.restore()}}if(!i){n.restore(),this._canvasMaskStack.push(!1);return}l?n.clip("evenodd"):n.clip(),this._canvasMaskStack.push(!0)}destroy(){this._renderer=null,this._warnedMaskTypes=null,this._canvasMaskStack=null}_warnOnce(e,t){this._warnedMaskTypes.has(e)||(this._warnedMaskTypes.add(e),we(t))}}We.extension={type:[S.CanvasPipes],name:"stencilMask"};const d="source-over";function mt(){const a=lt(),e=Object.create(null);return e.inherit=d,e.none=d,e.normal="source-over",e.add="lighter",e.multiply=a?"multiply":d,e.screen=a?"screen":d,e.overlay=a?"overlay":d,e.darken=a?"darken":d,e.lighten=a?"lighten":d,e["color-dodge"]=a?"color-dodge":d,e["color-burn"]=a?"color-burn":d,e["hard-light"]=a?"hard-light":d,e["soft-light"]=a?"soft-light":d,e.difference=a?"difference":d,e.exclusion=a?"exclusion":d,e.saturation=a?"saturation":d,e.color=a?"color":d,e.luminosity=a?"luminosity":d,e["linear-burn"]=a?"color-burn":d,e["linear-dodge"]=a?"color-dodge":d,e["linear-light"]=a?"hard-light":d,e["pin-light"]=a?"hard-light":d,e["vivid-light"]=a?"hard-light":d,e["hard-mix"]=d,e.negation=a?"difference":d,e["normal-npm"]=e.normal,e["add-npm"]=e.add,e["screen-npm"]=e.screen,e.erase="destination-out",e.subtract=d,e.divide=d,e.min=d,e.max=d,e}const ft=new G;class De{constructor(e){this.activeResolution=1,this.smoothProperty="imageSmoothingEnabled",this.blendModes=mt(),this._activeBlendMode="normal",this._projTransform=null,this._outerBlend=!1,this._warnedBlendModes=new Set,this._renderer=e}resolutionChange(e){this.activeResolution=e}init(){const e=this._renderer.background.alpha<1;if(this.rootContext=this._renderer.canvas.getContext("2d",{alpha:e}),this.activeContext=this.rootContext,this.activeResolution=this._renderer.resolution,!this.rootContext.imageSmoothingEnabled){const t=this.rootContext;t.webkitImageSmoothingEnabled?this.smoothProperty="webkitImageSmoothingEnabled":t.mozImageSmoothingEnabled?this.smoothProperty="mozImageSmoothingEnabled":t.oImageSmoothingEnabled?this.smoothProperty="oImageSmoothingEnabled":t.msImageSmoothingEnabled&&(this.smoothProperty="msImageSmoothingEnabled")}}setContextTransform(e,t,s,n){var l;const r=n?G.IDENTITY:((l=this._renderer.globalUniforms.globalUniformData)==null?void 0:l.worldTransformMatrix)||G.IDENTITY;let o=ft;o.copyFrom(r),o.append(e);const c=this._projTransform,i=this.activeResolution;if(s=s||i,c){const u=G.shared;u.copyFrom(o),u.prepend(c),o=u}t?this.activeContext.setTransform(o.a*s,o.b*s,o.c*s,o.d*s,o.tx*i|0,o.ty*i|0):this.activeContext.setTransform(o.a*s,o.b*s,o.c*s,o.d*s,o.tx*i,o.ty*i)}clear(e,t){const s=this.activeContext,n=this._renderer;if(s.clearRect(0,0,n.width,n.height),e){const r=Ae.shared.setValue(e);s.globalAlpha=t??r.alpha,s.fillStyle=r.toHex(),s.fillRect(0,0,n.width,n.height),s.globalAlpha=1}}setBlendMode(e){if(this._activeBlendMode===e)return;this._activeBlendMode=e,this._outerBlend=!1;const t=this.blendModes[e];if(!t){this._warnedBlendModes.has(e)||(console.warn(`CanvasRenderer: blend mode "${e}" is not supported in Canvas2D; falling back to "source-over".`),this._warnedBlendModes.add(e)),this.activeContext.globalCompositeOperation="source-over";return}this.activeContext.globalCompositeOperation=t}destroy(){this.rootContext=null,this.activeContext=null,this._warnedBlendModes.clear()}}De.extension={type:[S.CanvasSystem],name:"canvasContext"};class Fe{constructor(){this.maxTextures=16,this.maxBatchableTextures=16,this.maxUniformBindings=0}init(){}}Fe.extension={type:[S.CanvasSystem],name:"limits"};const gt="#808080",re=new G,vt=new G,yt=new G,fe=new G,xt=new G;function Ct(a,e,t){a.beginPath();for(let s=0;s<t.length;s+=3){const n=t[s]*2,r=t[s+1]*2,o=t[s+2]*2;a.moveTo(e[n],e[n+1]),a.lineTo(e[r],e[r+1]),a.lineTo(e[o],e[o+1]),a.closePath()}a.fill()}function Tt(a){return`#${(a&16777215).toString(16).padStart(6,"0")}`}function Pt(a,e,t,s,n,r){r=Math.max(0,Math.min(r,Math.min(s,n)/2)),a.moveTo(e+r,t),a.lineTo(e+s-r,t),a.quadraticCurveTo(e+s,t,e+s,t+r),a.lineTo(e+s,t+n-r),a.quadraticCurveTo(e+s,t+n,e+s-r,t+n),a.lineTo(e+r,t+n),a.quadraticCurveTo(e,t+n,e,t+n-r),a.lineTo(e,t+r),a.quadraticCurveTo(e,t,e+r,t)}function ie(a,e){switch(e.type){case"rectangle":{const t=e;a.rect(t.x,t.y,t.width,t.height);break}case"roundedRectangle":{const t=e;Pt(a,t.x,t.y,t.width,t.height,t.radius);break}case"circle":{const t=e;a.arc(t.x,t.y,t.radius,0,Math.PI*2);break}case"ellipse":{const t=e;a.ellipse?a.ellipse(t.x,t.y,t.halfWidth,t.halfHeight,0,0,Math.PI*2):(a.save(),a.translate(t.x,t.y),a.scale(t.halfWidth,t.halfHeight),a.arc(0,0,1,0,Math.PI*2),a.restore());break}case"triangle":{const t=e;a.moveTo(t.x,t.y),a.lineTo(t.x2,t.y2),a.lineTo(t.x3,t.y3),a.closePath();break}case"polygon":default:{const t=e,s=t.points;if(!(s!=null&&s.length))break;a.moveTo(s[0],s[1]);for(let n=2;n<s.length;n+=2)a.lineTo(s[n],s[n+1]);t.closePath&&a.closePath();break}}}function kt(a,e){if(!(e!=null&&e.length))return!1;for(let t=0;t<e.length;t++){const s=e[t];if(!(s!=null&&s.shape))continue;const n=s.transform,r=n&&!n.isIdentity();r&&(a.save(),a.transform(n.a,n.b,n.c,n.d,n.tx,n.ty)),ie(a,s.shape),r&&a.restore()}return!0}function _t(a,e,t,s){const n=a.fill;if(n instanceof Je){n.buildGradient();const o=n.texture;if(o){const c=P.getTintedPattern(o,e),i=t?fe.copyFrom(t).scale(o.source.pixelWidth,o.source.pixelHeight):fe.copyFrom(n.transform);return s&&!a.textureSpace&&i.append(s),P.applyPatternTransform(c,i),c}}if(n instanceof Ke){const o=P.getTintedPattern(n.texture,e);return P.applyPatternTransform(o,n.transform,!1),o}const r=a.texture;if(r&&r!==Be.WHITE){if(!r.source.resource)return gt;const o=P.getTintedPattern(r,e);let c=a.matrix;if(t){const{resolution:i}=r.source;if(c=fe.copyFrom(t),r.rotate){const{uvs:l,orig:u}=r;c.prepend(xt.set(l.x1-l.x0,l.y1-l.y0,l.x3-l.x0,l.y3-l.y0,l.x0,l.y0).invert()).scale(u.width*i,u.height*i)}else c.scale(r.source.pixelWidth,r.source.pixelHeight).translate(-r.frame.x*i,-r.frame.y*i)}return P.applyPatternTransform(o,c),o}return Tt(e)}class Ue{constructor(){this.shader=null}contextChange(e){}execute(e,t){var Y,U,W,k,C,V,Q;const s=e.renderer,n=s.canvasContext,r=n.activeContext,o=t.groupTransform,c=((Y=s.globalUniforms.globalUniformData)==null?void 0:Y.worldColor)??4294967295,i=t.groupColorAlpha,l=(c>>>24&255)/255,u=(i>>>24&255)/255,x=((U=s.filter)==null?void 0:U.alphaMultiplier)??1,E=l*u*x;if(E<=0)return;const v=c&16777215,f=i&16777215,M=Me(oe(f,v)),y=s._roundPixels|t._roundPixels;r.save(),n.setContextTransform(o,y===1),n.setBlendMode(t.groupBlendMode);const A=t.context.instructions;for(let Z=0;Z<A.length;Z++){const z=A[Z];if(z.action==="texture"){const p=z.data,m=p.image,g=m?P.getCanvasSource(m):null;if(!g)continue;const L=p.alpha*E;if(L<=0)continue;const I=oe(p.style,M);r.globalAlpha=L;let b=g;I!==16777215&&(b=P.getTintedCanvas({texture:m},I));const D=m.frame,F=m.source._resolution??m.source.resolution??1;let B=D.x*F,H=D.y*F;const N=D.width*F,h=D.height*F;b!==g&&(B=0,H=0);const O=p.transform,j=O&&!O.isIdentity(),T=m.rotate;j||T?(re.copyFrom(o),j&&re.append(O),T&&Se.matrixAppendRotationInv(re,T,p.dx,p.dy,p.dw,p.dh),n.setContextTransform(re,y===1)):n.setContextTransform(o,y===1),r.drawImage(b,B,H,b===g?N:b.width,b===g?h:b.height,T?0:p.dx,T?0:p.dy,p.dw,p.dh),(j||T)&&n.setContextTransform(o,y===1);continue}const _=z.data,w=(W=_==null?void 0:_.path)==null?void 0:W.shapePath;if(!((k=w==null?void 0:w.shapePrimitives)!=null&&k.length))continue;const R=_.style,ce=oe(R.color,M),ee=R.alpha*E;if(ee<=0)continue;const q=z.action==="stroke";if(r.globalAlpha=ee,q){const p=R;r.lineWidth=p.width,r.lineCap=p.cap,r.lineJoin=p.join,r.miterLimit=p.miterLimit}const $=w.shapePrimitives;if(!q&&((Q=(V=(C=_.hole)==null?void 0:C.shapePath)==null?void 0:V.shapePrimitives)!=null&&Q.length)){const p=$[$.length-1];p.holes=_.hole.shapePath.shapePrimitives}for(let p=0;p<$.length;p++){const m=$[p];if(!(m!=null&&m.shape))continue;const g=m.transform,L=g&&!g.isIdentity(),I=R.texture&&R.texture!==Be.WHITE,b=R.textureSpace==="global"?g:null,D=I?ze(vt,R,m.shape,b):null,F=L?yt.copyFrom(o).append(g):o,B=_t(R,ce,D,F);if(L&&(r.save(),r.transform(g.a,g.b,g.c,g.d,g.tx,g.ty)),q){const H=R;if(H.alignment!==.5&&!H.pixelLine){const h=[],O=[],j=[],T=Re[m.shape.type];if(T!=null&&T.build(m.shape,h)){const ve=m.shape.closePath??!0;Ie(h,H,!1,ve,O,j),r.fillStyle=B,Ct(r,O,j)}else r.strokeStyle=B,r.beginPath(),ie(r,m.shape),r.stroke()}else r.strokeStyle=B,r.beginPath(),ie(r,m.shape),r.stroke()}else r.fillStyle=B,r.beginPath(),ie(r,m.shape),kt(r,m.holes)?r.fill("evenodd"):r.fill();L&&r.restore()}}r.restore()}destroy(){this.shader=null}}Ue.extension={type:[S.CanvasPipesAdaptor],name:"graphics"};class bt{init(e,t){this._renderer=e,this._renderTargetSystem=t}initGpuRenderTarget(e){const t=e.colorTexture,{canvas:s,context:n}=this._ensureCanvas(t);return{canvas:s,context:n,width:s.width,height:s.height}}resizeGpuRenderTarget(e){const t=e.colorTexture,{canvas:s}=this._ensureCanvas(t);s.width=e.pixelWidth,s.height=e.pixelHeight}startRenderPass(e,t,s,n){const r=this._renderTargetSystem.getGpuRenderTarget(e);this._renderer.canvasContext.activeContext=r.context,this._renderer.canvasContext.activeResolution=e.resolution,t&&this.clear(e,t,s,n)}clear(e,t,s,n){const o=this._renderTargetSystem.getGpuRenderTarget(e).context,c=n||{x:0,y:0,width:e.pixelWidth,height:e.pixelHeight};if(o.setTransform(1,0,0,1,0,0),o.clearRect(c.x,c.y,c.width,c.height),s){const i=Ae.shared.setValue(s);i.alpha>0&&(o.globalAlpha=i.alpha,o.fillStyle=i.toHex(),o.fillRect(c.x,c.y,c.width,c.height),o.globalAlpha=1)}}finishRenderPass(){}copyToTexture(e,t,s,n,r){const c=this._renderTargetSystem.getGpuRenderTarget(e).canvas,i=t.source,{context:l}=this._ensureCanvas(i),u=(r==null?void 0:r.x)??0,x=(r==null?void 0:r.y)??0;return l.drawImage(c,s.x,s.y,n.width,n.height,u,x,n.width,n.height),i.update(),t}copyDepthTexture(e,t,s,n,r){we("[CanvasRenderTargetAdaptor] copyDepthTexture is not supported in the canvas renderer")}destroyGpuRenderTarget(e){}_ensureCanvas(e){let t=e.resource;(!t||!Qe.test(t))&&(t=He.get().createCanvas(e.pixelWidth,e.pixelHeight),e.resource=t),(t.width!==e.pixelWidth||t.height!==e.pixelHeight)&&(t.width=e.pixelWidth,t.height=e.pixelHeight);const s=t.getContext("2d");return{canvas:t,context:s}}}class qe extends tt{constructor(e){super(e),this.adaptor=new bt,this.adaptor.init(e,this)}}qe.extension={type:[S.CanvasSystem],name:"renderTarget"};class Le{constructor(e){}init(){}initSource(e){}generateCanvas(e){const t=He.get().createCanvas(),s=t.getContext("2d"),n=P.getCanvasSource(e);if(!n)return t;const r=e.frame,o=e.source._resolution??e.source.resolution??1,c=r.x*o,i=r.y*o,l=r.width*o,u=r.height*o;return t.width=Math.ceil(l),t.height=Math.ceil(u),s.drawImage(n,c,i,l,u,0,0,l,u),t}getPixels(e){const t=this.generateCanvas(e);return{pixels:t.getContext("2d",{willReadFrequently:!0}).getImageData(0,0,t.width,t.height).data,width:t.width,height:t.height}}destroy(){}}Le.extension={type:[S.CanvasSystem],name:"texture"};const St=[...st,De,Fe,Le,qe],Mt=[nt,at,rt,ot,it,We,Ge,ct],wt=[ht,Ue],Ne=[],Oe=[],je=[],Ye=[];ne.handleByNamedList(S.CanvasSystem,Ne);ne.handleByNamedList(S.CanvasPipes,Oe);ne.handleByNamedList(S.CanvasPipesAdaptor,je);ne.handleByNamedList(S.CanvasLoader,Ye);ne.add(...St,...Mt,...wt);class Ht extends Ze{constructor(){const e={name:"canvas",type:et.CANVAS,systems:Ne,renderPipes:Oe,renderPipeAdaptors:je,loaders:Ye};super(e)}}export{Ht as CanvasRenderer};
@@ -0,0 +1,184 @@
1
+ import{a1 as Xe,Y as me,M as x,G as Je,b as Qe,w as R,T as _,a as Ze,a2 as ge,o as d,y as Y,a3 as E,a4 as et,a5 as $,a6 as v,R as L,a7 as _e,a8 as tt,h as T,W as U,a9 as oe,aa as xe,ab as be,ac as ye,ad as Te,I as O,C as W,D as q,V as w,X as P,ae as rt,P as st,af as nt,N as at,z as le,ag as de,d as f,E as it,k as ot,x as V,e as lt,ah as dt,ai as ht,aj as ct,v as ut}from"./index-DPTN0V6X.js";import{F as pt,C as he}from"./CanvasPool-O1IaWL-9.js";var ft=`in vec2 vMaskCoord;
2
+ in vec2 vTextureCoord;
3
+
4
+ uniform sampler2D uTexture;
5
+ uniform sampler2D uMaskTexture;
6
+
7
+ uniform float uAlpha;
8
+ uniform vec4 uMaskClamp;
9
+ uniform float uInverse;
10
+ uniform float uChannel;
11
+
12
+ out vec4 finalColor;
13
+
14
+ void main(void)
15
+ {
16
+ float clip = step(3.5,
17
+ step(uMaskClamp.x, vMaskCoord.x) +
18
+ step(uMaskClamp.y, vMaskCoord.y) +
19
+ step(vMaskCoord.x, uMaskClamp.z) +
20
+ step(vMaskCoord.y, uMaskClamp.w));
21
+
22
+ // TODO look into why this is needed
23
+ float npmAlpha = uAlpha;
24
+ vec4 original = texture(uTexture, vTextureCoord);
25
+ vec4 masky = texture(uMaskTexture, vMaskCoord);
26
+
27
+ float a;
28
+ if (uChannel == 1.0) {
29
+ a = masky.a * npmAlpha * clip;
30
+ } else {
31
+ float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);
32
+ a = alphaMul * masky.r * npmAlpha * clip;
33
+ }
34
+
35
+ if (uInverse == 1.0) {
36
+ a = 1.0 - a;
37
+ }
38
+
39
+ finalColor = original * a;
40
+ }
41
+ `,mt=`in vec2 aPosition;
42
+
43
+ out vec2 vTextureCoord;
44
+ out vec2 vMaskCoord;
45
+
46
+
47
+ uniform vec4 uInputSize;
48
+ uniform vec4 uOutputFrame;
49
+ uniform vec4 uOutputTexture;
50
+ uniform mat3 uFilterMatrix;
51
+
52
+ vec4 filterVertexPosition( vec2 aPosition )
53
+ {
54
+ vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;
55
+
56
+ position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;
57
+ position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;
58
+
59
+ return vec4(position, 0.0, 1.0);
60
+ }
61
+
62
+ vec2 filterTextureCoord( vec2 aPosition )
63
+ {
64
+ return aPosition * (uOutputFrame.zw * uInputSize.zw);
65
+ }
66
+
67
+ vec2 getFilterCoord( vec2 aPosition )
68
+ {
69
+ return ( uFilterMatrix * vec3( filterTextureCoord(aPosition), 1.0) ).xy;
70
+ }
71
+
72
+ void main(void)
73
+ {
74
+ gl_Position = filterVertexPosition(aPosition);
75
+ vTextureCoord = filterTextureCoord(aPosition);
76
+ vMaskCoord = getFilterCoord(aPosition);
77
+ }
78
+ `,ce=`struct GlobalFilterUniforms {
79
+ uInputSize:vec4<f32>,
80
+ uInputPixel:vec4<f32>,
81
+ uInputClamp:vec4<f32>,
82
+ uOutputFrame:vec4<f32>,
83
+ uGlobalFrame:vec4<f32>,
84
+ uOutputTexture:vec4<f32>,
85
+ };
86
+
87
+ struct MaskUniforms {
88
+ uFilterMatrix:mat3x3<f32>,
89
+ uMaskClamp:vec4<f32>,
90
+ uAlpha:f32,
91
+ uInverse:f32,
92
+ uChannel:f32,
93
+ };
94
+
95
+ @group(0) @binding(0) var<uniform> gfu: GlobalFilterUniforms;
96
+ @group(0) @binding(1) var uTexture: texture_2d<f32>;
97
+ @group(0) @binding(2) var uSampler : sampler;
98
+
99
+ @group(1) @binding(0) var<uniform> filterUniforms : MaskUniforms;
100
+ @group(1) @binding(1) var uMaskTexture: texture_2d<f32>;
101
+
102
+ struct VSOutput {
103
+ @builtin(position) position: vec4<f32>,
104
+ @location(0) uv : vec2<f32>,
105
+ @location(1) filterUv : vec2<f32>,
106
+ };
107
+
108
+ fn filterVertexPosition(aPosition:vec2<f32>) -> vec4<f32>
109
+ {
110
+ var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;
111
+
112
+ position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;
113
+ position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;
114
+
115
+ return vec4(position, 0.0, 1.0);
116
+ }
117
+
118
+ fn filterTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>
119
+ {
120
+ return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);
121
+ }
122
+
123
+ fn globalTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>
124
+ {
125
+ return (aPosition.xy / gfu.uGlobalFrame.zw) + (gfu.uGlobalFrame.xy / gfu.uGlobalFrame.zw);
126
+ }
127
+
128
+ fn getFilterCoord(aPosition:vec2<f32> ) -> vec2<f32>
129
+ {
130
+ return ( filterUniforms.uFilterMatrix * vec3( filterTextureCoord(aPosition), 1.0) ).xy;
131
+ }
132
+
133
+ fn getSize() -> vec2<f32>
134
+ {
135
+ return gfu.uGlobalFrame.zw;
136
+ }
137
+
138
+ @vertex
139
+ fn mainVertex(
140
+ @location(0) aPosition : vec2<f32>,
141
+ ) -> VSOutput {
142
+ return VSOutput(
143
+ filterVertexPosition(aPosition),
144
+ filterTextureCoord(aPosition),
145
+ getFilterCoord(aPosition)
146
+ );
147
+ }
148
+
149
+ @fragment
150
+ fn mainFragment(
151
+ @location(0) uv: vec2<f32>,
152
+ @location(1) filterUv: vec2<f32>,
153
+ @builtin(position) position: vec4<f32>
154
+ ) -> @location(0) vec4<f32> {
155
+
156
+ var maskClamp = filterUniforms.uMaskClamp;
157
+ var uAlpha = filterUniforms.uAlpha;
158
+
159
+ var clip = step(3.5,
160
+ step(maskClamp.x, filterUv.x) +
161
+ step(maskClamp.y, filterUv.y) +
162
+ step(filterUv.x, maskClamp.z) +
163
+ step(filterUv.y, maskClamp.w));
164
+
165
+ var mask = textureSample(uMaskTexture, uSampler, filterUv);
166
+ var source = textureSample(uTexture, uSampler, uv);
167
+
168
+ var a: f32;
169
+ if (filterUniforms.uChannel == 1.0) {
170
+ a = mask.a * uAlpha * clip;
171
+ } else {
172
+ var alphaMul = 1.0 - uAlpha * (1.0 - mask.a);
173
+ a = alphaMul * mask.r * uAlpha * clip;
174
+ }
175
+
176
+ if (filterUniforms.uInverse == 1.0) {
177
+ a = 1.0 - a;
178
+ }
179
+
180
+ return source * a;
181
+ }
182
+ `;class gt extends pt{constructor(e){const{sprite:t,...r}=e,s=new Xe(t.texture),n=new me({uFilterMatrix:{value:new x,type:"mat3x3<f32>"},uMaskClamp:{value:s.uClampFrame,type:"vec4<f32>"},uAlpha:{value:1,type:"f32"},uInverse:{value:e.inverse?1:0,type:"f32"},uChannel:{value:e.channel==="alpha"?1:0,type:"f32"}}),i=Je.from({vertex:{source:ce,entryPoint:"mainVertex"},fragment:{source:ce,entryPoint:"mainFragment"}}),l=Qe.from({vertex:mt,fragment:ft,name:"mask-filter"});super({...r,gpuProgram:i,glProgram:l,clipToViewport:!1,resources:{filterUniforms:n,uMaskTexture:t.texture.source}}),this.sprite=t,this._textureMatrix=s}setSprite(e){this.sprite=e;const t=this._getSafeTexture();this._textureMatrix.texture=t,this.resources.uMaskTexture=t.source}set inverse(e){this.resources.filterUniforms.uniforms.uInverse=e?1:0}get inverse(){return this.resources.filterUniforms.uniforms.uInverse===1}set channel(e){this.resources.filterUniforms.uniforms.uChannel=e==="alpha"?1:0}get channel(){return this.resources.filterUniforms.uniforms.uChannel===1?"alpha":"red"}apply(e,t,r,s){const n=this._getSafeTexture();this._textureMatrix.texture=n,e.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=n.source,e.applyFilter(this,t,r,s)}_getSafeTexture(){const e=this.sprite.texture;return e.destroyed||!e.source||e.source.destroyed?(R("[MaskFilter] The mask texture was destroyed while the mask is still in use. Remove the mask before destroying its texture."),_.EMPTY):e}destroy(e=!1){this._textureMatrix.destroy(),super.destroy(e)}}class ve{constructor(){this.batcherName="default",this.topology="triangle-list",this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this._attributeStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null}destroy(){this.reset()}}const K=class Ce{constructor(e,t){var r,s;this.state=Ze.for2d(),this._batchersByInstructionSet=Object.create(null),this._activeBatches=Object.create(null),this.renderer=e,this._adaptor=t,(s=(r=this._adaptor).init)==null||s.call(r,this)}static getBatcher(e,t){return new this._availableBatchers[e]({maxTextures:t})}buildStart(e){let t=this._batchersByInstructionSet[e.uid];t||(t=this._batchersByInstructionSet[e.uid]=Object.create(null),t.default||(t.default=new ge({maxTextures:this.renderer.limits.maxBatchableTextures}))),this._activeBatches=t,this._activeBatch=this._activeBatches.default;for(const r in this._activeBatches)this._activeBatches[r].begin()}addToBatch(e,t){if(this._activeBatch.name!==e.batcherName){this._activeBatch.break(t);let r=this._activeBatches[e.batcherName];r||(r=this._activeBatches[e.batcherName]=Ce.getBatcher(e.batcherName,this.renderer.limits.maxBatchableTextures),r.begin()),this._activeBatch=r}this._activeBatch.add(e)}break(e){this._activeBatch.break(e)}buildEnd(e){this._activeBatch.break(e);const t=this._activeBatches;for(const r in t){const s=t[r],n=s.geometry;n.indexBuffer.setDataWithSize(s.indexBuffer,s.indexSize,!0),n.buffers[0].setDataWithSize(s.attributeBuffer.float32View,s.attributeSize,!1)}}upload(e){const t=this._batchersByInstructionSet[e.uid];for(const r in t){const s=t[r],n=s.geometry;s.dirty&&(s.dirty=!1,n.buffers[0].update(s.attributeSize*4))}}execute(e){if(e.action==="startBatch"){const t=e.batcher,r=t.geometry,s=t.shader;this._adaptor.start(this,r,s)}this._adaptor.execute(this,e)}destroyInstructionSet(e){const t=this._batchersByInstructionSet[e.uid];if(t){for(const r in t)t[r].destroy();delete this._batchersByInstructionSet[e.uid],this._activeBatches===t&&(this._activeBatches=Object.create(null),this._activeBatch=null)}}destroy(){this.state=null,this.renderer=null,this._adaptor=null;for(const e in this._activeBatches)this._activeBatches[e].destroy();this._activeBatches=null}};K.extension={type:[d.WebGLPipes,d.WebGPUPipes,d.CanvasPipes],name:"batch"};K._availableBatchers=Object.create(null);let Se=K;Y.handleByMap(d.Batcher,Se._availableBatchers);Y.add(ge);const _t=new $;class xt extends _e{constructor(){super(),this._placeholderSprite=new tt(_.EMPTY),this.filters=[new gt({sprite:this._placeholderSprite,inverse:!1,resolution:"inherit",antialias:"inherit"})]}get sprite(){return this.filters[0].sprite}set sprite(e){this.filters[0].setSprite(e)}get inverse(){return this.filters[0].inverse}set inverse(e){this.filters[0].inverse=e}get channel(){return this.filters[0].channel}set channel(e){this.filters[0].channel=e}reset(){this._placeholderSprite.texture=_.EMPTY,this.sprite=this._placeholderSprite}}class ke{constructor(e){this._activeMaskStage=[],this._usedEffects=[],this._renderer=e,e.runners.postrender.add(this)}push(e,t,r){const s=this._renderer;if(s.renderPipes.batch.break(r),r.add({renderPipeId:"alphaMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1,maskedContainer:t}),e.inverse=t._maskOptions.inverse,e.channel=t._maskOptions.channel??"red",e.renderMaskToTexture){const n=e.mask;n.includeInBuild=!0,n.collectRenderables(r,s,null),n.includeInBuild=!1}s.renderPipes.batch.break(r),r.add({renderPipeId:"alphaMask",action:"pushMaskEnd",mask:e,maskedContainer:t,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,r){this._renderer.renderPipes.batch.break(r),r.add({renderPipeId:"alphaMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){const t=this._renderer,r=e.mask.renderMaskToTexture;if(e.action==="pushMaskBegin"){const s=E.get(xt);if(s.inverse=e.inverse,s.channel=e.mask.channel,r){e.mask.mask.measurable=!0;const n=et(e.mask.mask,!0,_t);e.mask.mask.measurable=!1,n.ceil();const i=t.renderTarget.renderTarget.colorTexture.source,l=v.getOptimalTexture({width:n.width,height:n.height,resolution:i._resolution,antialias:i.antialias});t.renderTarget.push({target:l,clear:!0}),t.globalUniforms.push({offset:n,worldColor:4294967295});const o=s.sprite;o.texture=l,o.worldTransform.tx=n.minX,o.worldTransform.ty=n.minY,this._activeMaskStage.push({filterEffect:s,maskedContainer:e.maskedContainer,filterTexture:l})}else s.sprite=e.mask.mask,this._activeMaskStage.push({filterEffect:s,maskedContainer:e.maskedContainer})}else if(e.action==="pushMaskEnd"){const s=this._activeMaskStage[this._activeMaskStage.length-1];r&&(t.type===L.WEBGL&&t.renderTarget.finishRenderPass(),t.renderTarget.pop(),t.globalUniforms.pop()),t.filter.push({renderPipeId:"filter",action:"pushFilter",container:s.maskedContainer,filterEffect:s.filterEffect,canBundle:!1})}else if(e.action==="popMaskEnd"){t.filter.pop();const s=this._activeMaskStage.pop();r&&v.returnTexture(s.filterTexture),this._usedEffects.push(s.filterEffect)}}postrender(){const e=this._usedEffects;for(let t=0;t<e.length;t++)E.return(e[t]);e.length=0}destroy(){this.postrender(),this._renderer.runners.postrender.remove(this),this._renderer=null,this._activeMaskStage=null,this._usedEffects=null}}ke.extension={type:[d.WebGLPipes,d.WebGPUPipes,d.CanvasPipes],name:"alphaMask"};class Re{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,r){this._renderer.renderPipes.batch.break(r);const n=this._colorStack;n[this._colorStackIndex]=n[this._colorStackIndex-1]&e.mask;const i=this._colorStack[this._colorStackIndex];i!==this._currentColor&&(this._currentColor=i,r.add({renderPipeId:"colorMask",colorMask:i,canBundle:!1})),this._colorStackIndex++}pop(e,t,r){this._renderer.renderPipes.batch.break(r);const n=this._colorStack;this._colorStackIndex--;const i=n[this._colorStackIndex-1];i!==this._currentColor&&(this._currentColor=i,r.add({renderPipeId:"colorMask",colorMask:i,canBundle:!1}))}execute(e){this._renderer.colorMask.setMask(e.colorMask)}destroy(){this._renderer=null,this._colorStack=null}}Re.extension={type:[d.WebGLPipes,d.WebGPUPipes],name:"colorMask"};class Me{constructor(e){this._maskHash=new WeakMap,this._renderer=e}push(e,t,r){const s=e,n=this._renderer;n.renderPipes.batch.break(r),n.renderPipes.blendMode.setBlendMode(s.mask,"none",r),r.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const i=s.mask;i.includeInBuild=!0,this._maskHash.has(s)||this._maskHash.set(s,{instructionsStart:0,instructionsLength:0});const l=this._maskHash.get(s);l.instructionsStart=r.instructionSize,i.collectRenderables(r,n,null),i.includeInBuild=!1,n.renderPipes.batch.break(r),r.add({renderPipeId:"stencilMask",action:"pushMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const o=r.instructionSize-l.instructionsStart-1;l.instructionsLength=o}pop(e,t,r){const s=e,n=this._renderer;n.renderPipes.batch.break(r),n.renderPipes.blendMode.setBlendMode(s.mask,"none",r),r.add({renderPipeId:"stencilMask",action:"popMaskBegin",inverse:t._maskOptions.inverse,canBundle:!1});const i=this._maskHash.get(e);for(let l=0;l<i.instructionsLength;l++)r.instructions[r.instructionSize++]=r.instructions[i.instructionsStart++];r.add({renderPipeId:"stencilMask",action:"popMaskEnd",canBundle:!1})}execute(e){const r=this._renderer,s=r.renderTarget.getGpuRenderTarget(r.renderTarget.renderTarget);let n=s.maskStackIndex;e.action==="pushMaskBegin"?(r.renderTarget.ensureDepthStencil(),r.stencil.setStencilMode(T.RENDERING_MASK_ADD,n),n++,r.colorMask.setMask(0)):e.action==="pushMaskEnd"?(e.inverse?r.stencil.setStencilMode(T.INVERSE_MASK_ACTIVE,n):r.stencil.setStencilMode(T.MASK_ACTIVE,n),r.colorMask.setMask(15)):e.action==="popMaskBegin"?(r.colorMask.setMask(0),n!==0?r.stencil.setStencilMode(T.RENDERING_MASK_REMOVE,n):(r.renderTarget.clear(null,U.STENCIL),r.stencil.setStencilMode(T.DISABLED,n)),n--):e.action==="popMaskEnd"&&(e.inverse?r.stencil.setStencilMode(T.INVERSE_MASK_ACTIVE,n):r.stencil.setStencilMode(T.MASK_ACTIVE,n),r.colorMask.setMask(15)),s.maskStackIndex=n}destroy(){this._renderer=null,this._maskHash=null}}Me.extension={type:[d.WebGLPipes,d.WebGPUPipes],name:"stencilMask"};class we{constructor(e){this._renderer=e}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}addRenderable(e,t){this._renderer.renderPipes.batch.break(t),t.add(e)}execute(e){e.isRenderable&&e.render(this._renderer)}destroy(){this._renderer=null}}we.extension={type:[d.WebGLPipes,d.WebGPUPipes,d.CanvasPipes],name:"customRender"};function N(a,e){const t=a.instructionSet,r=t.instructions;for(let s=0;s<t.instructionSize;s++){const n=r[s];e[n.renderPipeId].execute(n)}}class Pe{constructor(e){this._renderer=e}addRenderGroup(e,t){e.isCachedAsTexture?this._addRenderableCacheAsTexture(e,t):this._addRenderableDirect(e,t)}execute(e){e.isRenderable&&(e.isCachedAsTexture?this._executeCacheAsTexture(e):this._executeDirect(e))}destroy(){this._renderer=null}_addRenderableDirect(e,t){this._renderer.renderPipes.batch.break(t),e._batchableRenderGroup&&(E.return(e._batchableRenderGroup),e._batchableRenderGroup=null),t.add(e)}_addRenderableCacheAsTexture(e,t){const r=e._batchableRenderGroup??(e._batchableRenderGroup=E.get(ve));r.renderable=e.root,r.transform=e.root.relativeGroupTransform,r.texture=e.texture,r.bounds=e._textureBounds,t.add(e),this._renderer.renderPipes.blendMode.pushBlendMode(e,e.root.groupBlendMode,t),this._renderer.renderPipes.batch.addToBatch(r,t),this._renderer.renderPipes.blendMode.popBlendMode(t)}_executeCacheAsTexture(e){if(e.textureNeedsUpdate){e.textureNeedsUpdate=!1;const t=new x().translate(-e._textureBounds.x,-e._textureBounds.y);this._renderer.renderTarget.push({target:e.texture,clear:!0,frame:e.texture.frame}),this._renderer.globalUniforms.push({worldTransformMatrix:t,worldColor:4294967295,offset:{x:0,y:0}}),N(e,this._renderer.renderPipes),this._renderer.renderTarget.finishRenderPass(),this._renderer.renderTarget.pop(),this._renderer.globalUniforms.pop()}e._batchableRenderGroup._batcher.updateElement(e._batchableRenderGroup),e._batchableRenderGroup._batcher.geometry.buffers[0].update()}_executeDirect(e){this._renderer.globalUniforms.push({worldTransformMatrix:e.inverseParentTextureTransform,worldColor:e.worldColorAlpha}),N(e,this._renderer.renderPipes),this._renderer.globalUniforms.pop()}}Pe.extension={type:[d.WebGLPipes,d.WebGPUPipes,d.CanvasPipes],name:"renderGroup"};class Be{constructor(e){this._renderer=e}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._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,t),t._batcher.updateElement(t)}validateRenderable(e){const t=this._getGpuSprite(e);return!t._batcher.checkAndUpdateTexture(t,e._texture)}_updateBatchableSprite(e,t){t.bounds=e.visualBounds,t.texture=e._texture}_getGpuSprite(e){return e._gpuData[this._renderer.uid]||this._initGPUSprite(e)}_initGPUSprite(e){const t=new ve;return t.renderable=e,t.transform=e.groupTransform,t.texture=e._texture,t.bounds=e.visualBounds,t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,t}destroy(){this._renderer=null}}Be.extension={type:[d.WebGLPipes,d.WebGPUPipes,d.CanvasPipes],name:"sprite"};const B={};Y.handle(d.BlendMode,a=>{if(!a.name)throw new Error("BlendMode extension must have a name property");B[a.name]=a.ref},a=>{delete B[a.name]});class Ge{constructor(e){this._blendModeStack=[],this._isAdvanced=!1,this._filterHash=Object.create(null),this._renderer=e,this._renderer.runners.prerender.add(this)}prerender(){this._activeBlendMode="normal",this._isAdvanced=!1}pushBlendMode(e,t,r){this._blendModeStack.push(t),this.setBlendMode(e,t,r)}popBlendMode(e){this._blendModeStack.pop();const t=this._blendModeStack[this._activeBlendMode.length-1]??"normal";this.setBlendMode(null,t,e)}setBlendMode(e,t,r){var n;const s=e instanceof oe;if(this._activeBlendMode===t){this._isAdvanced&&e&&!s&&((n=this._renderableList)==null||n.push(e));return}this._isAdvanced&&this._endAdvancedBlendMode(r),this._activeBlendMode=t,e&&(this._isAdvanced=!!B[t],this._isAdvanced&&this._beginAdvancedBlendMode(e,r))}_beginAdvancedBlendMode(e,t){this._renderer.renderPipes.batch.break(t);const r=this._activeBlendMode;if(!B[r]){R(`Unable to assign BlendMode: '${r}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}const s=this._ensureFilterEffect(r),n=e instanceof oe,i={renderPipeId:"filter",action:"pushFilter",filterEffect:s,renderables:n?null:[e],container:n?e.root:null,canBundle:!1};this._renderableList=i.renderables,t.add(i)}_ensureFilterEffect(e){let t=this._filterHash[e];return t||(t=this._filterHash[e]=new _e,t.filters=[new B[e]]),t}_endAdvancedBlendMode(e){this._isAdvanced=!1,this._renderableList=null,this._renderer.renderPipes.batch.break(e),e.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}buildStart(){this._isAdvanced=!1}buildEnd(e){this._isAdvanced&&this._endAdvancedBlendMode(e)}destroy(){this._renderer=null,this._renderableList=null;for(const e in this._filterHash)this._filterHash[e].destroy();this._filterHash=null}}Ge.extension={type:[d.WebGLPipes,d.WebGPUPipes,d.CanvasPipes],name:"blendMode"};function j(a,e){e||(e=0);for(let t=e;t<a.length&&a[t];t++)a[t]=null}const bt=new O,ue=be|ye|Te;function Ae(a,e=!1){yt(a);const t=a.childrenToUpdate,r=a.updateTick++;for(const s in t){const n=Number(s),i=t[s],l=i.list,o=i.index;for(let c=0;c<o;c++){const h=l[c];h.parentRenderGroup===a&&h.relativeRenderGroupDepth===n&&Ue(h,r,0)}j(l,o),i.index=0}if(e)for(let s=0;s<a.renderGroupChildren.length;s++)Ae(a.renderGroupChildren[s],e)}function yt(a){const e=a.root;let t;if(a.renderGroupParent){const r=a.renderGroupParent;a.worldTransform.appendFrom(e.relativeGroupTransform,r.worldTransform),a.worldColor=xe(e.groupColor,r.worldColor),t=e.groupAlpha*r.worldAlpha}else a.worldTransform.copyFrom(e.localTransform),a.worldColor=e.localColor,t=e.localAlpha;t=t<0?0:t>1?1:t,a.worldAlpha=t,a.worldColorAlpha=a.worldColor+((t*255|0)<<24)}function Ue(a,e,t){if(e===a.updateTick)return;a.updateTick=e,a.didChange=!1;const r=a.localTransform;a.updateLocalTransform();const s=a.parent;if(s&&!s.renderGroup?(t|=a._updateFlags,a.relativeGroupTransform.appendFrom(r,s.relativeGroupTransform),t&ue&&pe(a,s,t)):(t=a._updateFlags,a.relativeGroupTransform.copyFrom(r),t&ue&&pe(a,bt,t)),!a.renderGroup){const n=a.children,i=n.length;for(let c=0;c<i;c++)Ue(n[c],e,t);const l=a.parentRenderGroup,o=a;o.renderPipeId&&!l.structureDidChange&&l.updateRenderable(o)}}function pe(a,e,t){if(t&ye){a.groupColor=xe(a.localColor,e.groupColor);let r=a.localAlpha*e.groupAlpha;r=r<0?0:r>1?1:r,a.groupAlpha=r,a.groupColorAlpha=a.groupColor+((r*255|0)<<24)}t&Te&&(a.groupBlendMode=a.localBlendMode==="inherit"?e.groupBlendMode:a.localBlendMode),t&be&&(a.globalDisplayStatus=a.localDisplayStatus&e.globalDisplayStatus),a._updateFlags=0}function Tt(a,e){const{list:t}=a.childrenRenderablesToUpdate;let r=!1;for(let s=0;s<a.childrenRenderablesToUpdate.index;s++){const n=t[s];if(r=e[n.renderPipeId].validateRenderable(n),r)break}return a.structureDidChange=r,r}const vt=new x;class Ie{constructor(e){this._renderer=e}render({container:e,transform:t}){const r=e.parent,s=e.renderGroup.renderGroupParent;e.parent=null,e.renderGroup.renderGroupParent=null;const n=this._renderer,i=vt;t&&(i.copyFrom(e.renderGroup.localTransform),e.renderGroup.localTransform.copyFrom(t));const l=n.renderPipes;this._updateCachedRenderGroups(e.renderGroup,null),this._updateRenderGroups(e.renderGroup),n.globalUniforms.start({worldTransformMatrix:t?e.renderGroup.localTransform:e.renderGroup.worldTransform,worldColor:e.renderGroup.worldColorAlpha}),N(e.renderGroup,l),l.uniformBatch&&l.uniformBatch.renderEnd(),t&&e.renderGroup.localTransform.copyFrom(i),e.parent=r,e.renderGroup.renderGroupParent=s}destroy(){this._renderer=null}_updateCachedRenderGroups(e,t){if(e._parentCacheAsTextureRenderGroup=t,e.isCachedAsTexture){if(!e.textureNeedsUpdate)return;t=e}for(let r=e.renderGroupChildren.length-1;r>=0;r--)this._updateCachedRenderGroups(e.renderGroupChildren[r],t);if(e.invalidateMatrices(),e.isCachedAsTexture){if(e.textureNeedsUpdate){const r=e.root.getLocalBounds(),s=this._renderer,n=e.textureOptions.resolution||s.view.resolution,i=e.textureOptions.antialias??s.view.antialias,l=e.textureOptions.scaleMode??"linear",o=e.texture;r.ceil(),e.texture&&v.returnTexture(e.texture);const c=v.getOptimalTexture({width:r.width,height:r.height,resolution:n,antialias:i,scaleMode:l});e.texture=c,e._textureBounds||(e._textureBounds=new $),e._textureBounds.copyFrom(r),o!==e.texture&&e.renderGroupParent&&(e.renderGroupParent.structureDidChange=!0)}}else e.texture&&(v.returnTexture(e.texture),e.texture=null)}_updateRenderGroups(e){const t=this._renderer,r=t.renderPipes;if(e.runOnRender(t),e.instructionSet.renderPipes=r,e.structureDidChange?j(e.childrenRenderablesToUpdate.list,0):Tt(e,r),Ae(e),e.structureDidChange?(e.structureDidChange=!1,this._buildInstructions(e,t)):this._updateRenderables(e),e.childrenRenderablesToUpdate.index=0,t.renderPipes.batch.upload(e.instructionSet),!(e.isCachedAsTexture&&!e.textureNeedsUpdate))for(let s=0;s<e.renderGroupChildren.length;s++)this._updateRenderGroups(e.renderGroupChildren[s])}_updateRenderables(e){const{list:t,index:r}=e.childrenRenderablesToUpdate;for(let s=0;s<r;s++){const n=t[s];n.didViewUpdate&&e.updateRenderable(n)}j(t,r)}_buildInstructions(e,t){const r=e.root,s=e.instructionSet;s.reset();const n=t.renderPipes?t:t.batch.renderer,i=n.renderPipes;i.batch.buildStart(s),i.blendMode.buildStart(),i.colorMask.buildStart(),r.sortableChildren&&r.sortChildren(),r.collectRenderablesWithEffects(s,n,null),i.batch.buildEnd(s),i.blendMode.buildEnd(s)}}Ie.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"renderGroup"};const X=class De{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new W(0),this.color=this._backgroundColor,this.alpha=1}init(e){e={...De.defaultOptions,...e},this.clearBeforeRender=e.clearBeforeRender,this.color=e.background||e.backgroundColor||this._backgroundColor,this.alpha=e.backgroundAlpha,this._backgroundColor.setAlpha(e.backgroundAlpha)}get color(){return this._backgroundColor}set color(e){W.shared.setValue(e).alpha<1&&this._backgroundColor.alpha===1&&R("Cannot set a transparent background on an opaque canvas. To enable transparency, set backgroundAlpha < 1 when initializing your Application."),this._backgroundColor.setValue(e)}get alpha(){return this._backgroundColor.alpha}set alpha(e){this._backgroundColor.setAlpha(e)}get colorRgba(){return this._backgroundColor.toArray()}destroy(){}};X.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"background",priority:0};X.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0};let Ct=X;const H={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},J=class Ee{constructor(e){this._renderer=e}_normalizeOptions(e,t={}){return e instanceof O||e instanceof _?{target:e,...t}:{...t,...e}}async image(e){const t=q.get().createImage();return t.src=await this.base64(e),t}async base64(e){e=this._normalizeOptions(e,Ee.defaultImageOptions);const{format:t,quality:r}=e,s=this.canvas(e);if(s.toBlob!==void 0)return new Promise((n,i)=>{s.toBlob(l=>{if(!l){i(new Error("ICanvas.toBlob failed!"));return}const o=new FileReader;o.onload=()=>n(o.result),o.onerror=i,o.readAsDataURL(l)},H[t],r)});if(s.toDataURL!==void 0)return s.toDataURL(H[t],r);if(s.convertToBlob!==void 0){const n=await s.convertToBlob({type:H[t],quality:r});return new Promise((i,l)=>{const o=new FileReader;o.onload=()=>i(o.result),o.onerror=l,o.readAsDataURL(n)})}throw new Error("Extract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(e){e=this._normalizeOptions(e);const t=e.target,r=this._renderer;if(t instanceof _)return r.texture.generateCanvas(t);const s=r.textureGenerator.generateTexture(e),n=r.texture.generateCanvas(s);return s.destroy(!0),n}pixels(e){e=this._normalizeOptions(e);const t=e.target,r=this._renderer,s=t instanceof _?t:r.textureGenerator.generateTexture(e),n=r.texture.getPixels(s);return t instanceof O&&s.destroy(!0),n}texture(e){return e=this._normalizeOptions(e),e.target instanceof _?e.target:this._renderer.textureGenerator.generateTexture(e)}download(e){e=this._normalizeOptions(e);const t=this.canvas(e),r=document.createElement("a");r.download=e.filename??"image.png",r.href=t.toDataURL("image/png"),document.body.appendChild(r),r.click(),document.body.removeChild(r)}log(e){const t=e.width??200;e=this._normalizeOptions(e);const r=this.canvas(e),s=r.toDataURL();console.log(`[Pixi Texture] ${r.width}px ${r.height}px`);const n=["font-size: 1px;",`padding: ${t}px 300px;`,`background: url(${s}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",n)}destroy(){this._renderer=null}};J.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"extract"};J.defaultImageOptions={format:"png",quality:1};let St=J;class Q extends _{static create(e){const{dynamic:t,textureOptions:r,...s}=e;return new Q({...r,source:new w(s),dynamic:t??!1})}resize(e,t,r){return this.source.resize(e,t,r),this}}const kt=new P,Rt=new $,Mt=[0,0,0,0];class Oe{constructor(e){this._renderer=e}generateTexture(e){var h;e instanceof O&&(e={target:e,frame:void 0,textureSourceOptions:{},resolution:void 0});const t=e.resolution||this._renderer.resolution,r=e.antialias||this._renderer.view.antialias,s=e.target;let n=e.clearColor;n?n=Array.isArray(n)&&n.length===4?n:W.shared.setValue(n).toArray():n=Mt;const i=((h=e.frame)==null?void 0:h.copyTo(kt))||rt(s,Rt).rectangle,l=e.defaultAnchor&&{defaultAnchor:e.defaultAnchor};i.width=Math.max(i.width,1/t)|0,i.height=Math.max(i.height,1/t)|0;const o=Q.create({...e.textureSourceOptions,width:i.width,height:i.height,resolution:t,antialias:r,textureOptions:l}),c=x.shared.translate(-i.x,-i.y);return this._renderer.render({container:s,transform:c,target:o,clearColor:n}),o.source.updateMipmaps(),o}destroy(){this._renderer=null}}Oe.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"textureGenerator"};function wt(a){let e=!1;for(const r in a)if(a[r]==null){e=!0;break}if(!e)return a;const t=Object.create(null);for(const r in a){const s=a[r];s&&(t[r]=s)}return t}function Pt(a){let e=0;for(let t=0;t<a.length;t++)a[t]==null?e++:a[t-e]=a[t];return a.length-=e,a}const Z=class Le{constructor(e){this._managedResources=[],this._managedResourceHashes=[],this._managedCollections=[],this._ready=!1,this._running=!1,this._renderer=e}init(e){e={...Le.defaultOptions,...e},this.maxUnusedTime=e.gcMaxUnusedTime,this._frequency=e.gcFrequency,this.enabled=e.gcActive,this.now=performance.now()}get enabled(){return!!this._handler}set enabled(e){this.enabled!==e&&(e?(this._handler=this._renderer.scheduler.repeat(()=>{this._ready=!0},this._frequency,!1),this._collectionsHandler=this._renderer.scheduler.repeat(()=>{for(const t of this._managedCollections){const{context:r,collection:s,type:n}=t;n==="hash"?r[s]=wt(r[s]):r[s]=Pt(r[s])}},this._frequency)):(this._renderer.scheduler.cancel(this._handler),this._renderer.scheduler.cancel(this._collectionsHandler),this._handler=0,this._collectionsHandler=0))}prerender({container:e}){this.now=performance.now(),e.renderGroup.gcTick=this._renderer.tick++,this._updateInstructionGCTick(e.renderGroup,e.renderGroup.gcTick)}postrender(){!this._ready||!this.enabled||(this.run(),this._ready=!1)}_updateInstructionGCTick(e,t){e.instructionSet.gcTick=t,e.gcTick=t;for(const r of e.renderGroupChildren)this._updateInstructionGCTick(r,t)}addCollection(e,t,r){this._managedCollections.push({context:e,collection:t,type:r})}addResource(e,t){var s,n;if(e._gcLastUsed!==-1){e._gcLastUsed=this.now,(s=e._onTouch)==null||s.call(e,this.now);return}const r=this._managedResources.length;e._gcData={index:r,type:t},e._gcLastUsed=this.now,(n=e._onTouch)==null||n.call(e,this.now),e.once("unload",this.removeResource,this),this._managedResources.push(e)}removeResource(e){const t=e._gcData;if(!t)return;const r=t.index,s=this._managedResources.length-1;if(this._running)this._managedResources[r]=null;else{if(r!==s){const n=this._managedResources[s];this._managedResources[r]=n,n._gcData.index=r}this._managedResources.length--}e._gcData=null,e._gcLastUsed=-1}addResourceHash(e,t,r,s=0){this._managedResourceHashes.push({context:e,hash:t,type:r,priority:s}),this._managedResourceHashes.sort((n,i)=>n.priority-i.priority)}run(){if(this._running)return;const e=performance.now(),t=this._managedResourceHashes,r=this._managedResources;this._running=!0;try{for(const n of t)this.runOnHash(n,e);const s=r.length;for(let n=0;n<s;n++){const i=r[n];i&&this.runOnResource(i,e)}}finally{let s=0;for(let n=0;n<r.length;n++){const i=r[n];i&&(s!==n&&(r[s]=i,i._gcData.index=s),s++)}r.length=s,this._running=!1}}updateRenderableGCTick(e,t){var n,i;const r=e.renderGroup??e.parentRenderGroup,s=((n=r==null?void 0:r.instructionSet)==null?void 0:n.gcTick)??-1;((r==null?void 0:r.gcTick)??0)===s&&(e._gcLastUsed=t,(i=e._onTouch)==null||i.call(e,t))}runOnResource(e,t){e._gcData.type==="renderable"&&this.updateRenderableGCTick(e,t),!(t-e._gcLastUsed<this.maxUnusedTime||!e.autoGarbageCollect)&&(e.off("unload",this.removeResource,this),e.unload(),this.removeResource(e))}_createHashClone(e,t){const r=Object.create(null);for(const s in e){if(s===t)break;e[s]!==null&&(r[s]=e[s])}return r}runOnHash(e,t){var c;const{context:r,hash:s,type:n}=e,i=r[s];let l=null,o=0;for(const h in i){const u=i[h];if(u===null){o++,o===1e4&&!l&&(l=this._createHashClone(i,h));continue}if(u._gcLastUsed===-1){u._gcLastUsed=t,(c=u._onTouch)==null||c.call(u,t),l&&(l[h]=u);continue}if(n==="renderable"&&this.updateRenderableGCTick(u,t),!(t-u._gcLastUsed<this.maxUnusedTime)&&u.autoGarbageCollect){if(n==="renderable"){const p=u,m=p.renderGroup??p.parentRenderGroup;m&&(m.structureDidChange=!0)}u.unload(),u._gcData=null,u._gcLastUsed=-1,l||(o+1!==1e4?(i[h]=null,o++):l=this._createHashClone(i,h))}else l&&(l[h]=u)}l&&(r[s]=l)}destroy(){this.enabled=!1,this._managedResources.forEach(e=>{e==null||e.off("unload",this.removeResource,this)}),this._managedResources.length=0,this._managedResourceHashes.length=0,this._managedCollections.length=0,this._renderer=null}};Z.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"gc",priority:0};Z.defaultOptions={gcActive:!0,gcMaxUnusedTime:6e4,gcFrequency:3e4};let Bt=Z;class ze{constructor(e){this._stackIndex=0,this._globalUniformDataStack=[],this._uniformsPool=[],this._activeUniforms=[],this._bindGroupPool=[],this._activeBindGroups=[],this._renderer=e}reset(){this._stackIndex=0;for(let e=0;e<this._activeUniforms.length;e++)this._uniformsPool.push(this._activeUniforms[e]);for(let e=0;e<this._activeBindGroups.length;e++)this._bindGroupPool.push(this._activeBindGroups[e]);this._activeUniforms.length=0,this._activeBindGroups.length=0}start(e){this.reset(),this.push(e)}bind({size:e,projectionMatrix:t,worldTransformMatrix:r,worldColor:s,offset:n}){const i=this._renderer.renderTarget.renderTarget,l=this._stackIndex?this._globalUniformDataStack[this._stackIndex-1]:{worldTransformMatrix:new x,worldColor:4294967295,offset:new st},o={projectionMatrix:t||this._renderer.renderTarget.projectionMatrix,resolution:e||i.size,worldTransformMatrix:r||l.worldTransformMatrix,worldColor:s||l.worldColor,offset:n||l.offset,bindGroup:null},c=this._uniformsPool.pop()||this._createUniforms();this._activeUniforms.push(c);const h=c.uniforms;h.uProjectionMatrix=o.projectionMatrix,h.uResolution=o.resolution,h.uWorldTransformMatrix.copyFrom(o.worldTransformMatrix),h.uWorldTransformMatrix.tx-=o.offset.x,h.uWorldTransformMatrix.ty-=o.offset.y,nt(o.worldColor,h.uWorldColorAlpha,0),c.update();let u;this._renderer.renderPipes.uniformBatch?u=this._renderer.renderPipes.uniformBatch.getUniformBindGroup(c,!1):(u=this._bindGroupPool.pop()||new at,this._activeBindGroups.push(u),u.setResource(c,0)),o.bindGroup=u,this._currentGlobalUniformData=o}push(e){this.bind(e),this._globalUniformDataStack[this._stackIndex++]=this._currentGlobalUniformData}pop(){this._currentGlobalUniformData=this._globalUniformDataStack[--this._stackIndex-1],this._renderer.type===L.WEBGL&&this._currentGlobalUniformData.bindGroup.resources[0].update()}get bindGroup(){return this._currentGlobalUniformData.bindGroup}get globalUniformData(){return this._currentGlobalUniformData}get uniformGroup(){return this._currentGlobalUniformData.bindGroup.resources[0]}_createUniforms(){return new me({uProjectionMatrix:{value:new x,type:"mat3x3<f32>"},uWorldTransformMatrix:{value:new x,type:"mat3x3<f32>"},uWorldColorAlpha:{value:new Float32Array(4),type:"vec4<f32>"},uResolution:{value:[0,0],type:"vec2<f32>"}},{isStatic:!0})}destroy(){this._renderer=null,this._globalUniformDataStack.length=0,this._uniformsPool.length=0,this._activeUniforms.length=0,this._bindGroupPool.length=0,this._activeBindGroups.length=0,this._currentGlobalUniformData=null}}ze.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"globalUniforms"};let Gt=1;class Fe{constructor(){this._tasks=[],this._offset=0}init(){le.system.add(this._update,this)}repeat(e,t,r=!0){const s=Gt++;let n=0;return r&&(this._offset+=1e3,n=this._offset),this._tasks.push({func:e,duration:t,start:performance.now(),offset:n,last:performance.now(),repeat:!0,id:s}),s}cancel(e){for(let t=0;t<this._tasks.length;t++)if(this._tasks[t].id===e){this._tasks.splice(t,1);return}}_update(){const e=performance.now();for(let t=0;t<this._tasks.length;t++){const r=this._tasks[t];if(e-r.offset-r.last>=r.duration){const s=e-r.start;r.func(s),r.last=e}}}destroy(){le.system.remove(this._update,this),this._tasks.length=0}}Fe.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"scheduler",priority:0};let fe=!1;function At(a){if(!fe){if(q.get().getNavigator().userAgent.toLowerCase().indexOf("chrome")>-1){const e=[`%c %c %c %c %c PixiJS %c v${de} (${a}) http://www.pixijs.com/
183
+
184
+ `,"background: #E72264; padding:5px 0;","background: #6CA2EA; padding:5px 0;","background: #B5D33D; padding:5px 0;","background: #FED23F; padding:5px 0;","color: #FFFFFF; background: #E72264; padding:5px 0;","color: #E72264; background: #FFFFFF; padding:5px 0;"];globalThis.console.log(...e)}else globalThis.console&&globalThis.console.log(`PixiJS ${de} - ${a} - http://www.pixijs.com/`);fe=!0}}class ee{constructor(e){this._renderer=e}init(e){if(e.hello){let t=this._renderer.name;this._renderer.type===L.WEBGL&&(t+=` ${this._renderer.context.webGLVersion}`),At(t)}}}ee.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"hello",priority:-2};ee.defaultOptions={hello:!1};const te=class He{constructor(e){this._renderer=e}init(e){e={...He.defaultOptions,...e},this.maxUnusedTime=e.renderableGCMaxUnusedTime}get enabled(){return f("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled}set enabled(e){f("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled=e}addManagedHash(e,t){f("8.15.0","RenderableGCSystem.addManagedHash is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"hash")}addManagedArray(e,t){f("8.15.0","RenderableGCSystem.addManagedArray is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"array")}addRenderable(e){f("8.15.0","RenderableGCSystem.addRenderable is deprecated, please use the GCSystem instead."),this._renderer.gc.addResource(e,"renderable")}run(){f("8.15.0","RenderableGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};te.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"renderableGC",priority:0};te.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4};let Ut=te;const re=class I{get count(){return this._renderer.tick}get checkCount(){return this._checkCount}set checkCount(e){f("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._checkCount=e}get maxIdle(){return this._renderer.gc.maxUnusedTime/1e3*60}set maxIdle(e){f("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.maxUnusedTime=e/60*1e3}get checkCountMax(){return Math.floor(this._renderer.gc._frequency/1e3)}set checkCountMax(e){f("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead.")}get active(){return this._renderer.gc.enabled}set active(e){f("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.enabled=e}constructor(e){this._renderer=e,this._checkCount=0}init(e){e.textureGCActive!==I.defaultOptions.textureGCActive&&(this.active=e.textureGCActive),e.textureGCMaxIdle!==I.defaultOptions.textureGCMaxIdle&&(this.maxIdle=e.textureGCMaxIdle),e.textureGCCheckCountMax!==I.defaultOptions.textureGCCheckCountMax&&(this.checkCountMax=e.textureGCCheckCountMax)}run(){f("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};re.extension={type:[d.WebGLSystem,d.WebGPUSystem],name:"textureGC"};re.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:3600,textureGCCheckCountMax:600};let It=re;const We=class Ve extends it{constructor(e={}){super(),this.uid=ot("renderTarget"),this.colorAttachments=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,this._depth=!1,this._stencil=!1,this._colorTextures=null;const t="colorAttachments"in e?e:this._normalizeOptions(e);if(this.isRoot=t.isRoot??!1,this.label=t.label,this.colorAttachments=t.colorAttachments,this.depthStencilAttachment=t.depthStencilAttachment,this.depthStencilAttachment){const r=this.depthStencilAttachment.texture.format;this._depth||(this._depth=r.includes("depth")),this._stencil||(this._stencil=r.includes("stencil"))}if(this.colorAttachments.length===0&&!this.depthStencilAttachment)throw new Error("[RenderTarget] no color textures or depth textures were provided. Provide a depthStencilTexture or set depth/stencil to true when using colorTextures: 0.");if(this.colorAttachments.length>0){const r=this.colorTexture;this.resize(r.width,r.height,r._resolution)}this.sizeSource&&this.sizeSource.on("resize",this.onSourceResize,this)}_normalizeOptions(e){const t={...Ve.defaultOptions,...e},r=[];let s;if(typeof t.colorTextures=="number"){if(t.colorTextures>0){this._managedColorTextures=!0;for(let i=0;i<t.colorTextures;i++)r.push({texture:new w({width:t.width,height:t.height,resolution:t.resolution,antialias:t.antialias}),loadOp:"clear",storeOp:"store"})}}else t.colorTextures.forEach(i=>{r.push({texture:i.source,loadOp:"clear",storeOp:"store"})});const n=t.depthStencilTexture===!0;if(this._depth=!!(t.depth||n),this._stencil=!!(t.stencil||n),t.depthStencilTexture instanceof _||t.depthStencilTexture instanceof w){if(t.isRoot)throw new Error("[RenderTarget] cannot attach a depth-stencil texture to the screen — the canvas owns its own depth/stencil buffers. Render to a texture target instead.");s={texture:t.depthStencilTexture.source}}else(n&&!t.isRoot||(t.stencil||t.depth)&&r.length===0)&&(s=this._createDepthStencilTexture(t.width,t.height,t.resolution));return{colorAttachments:r,depthStencilAttachment:s,isRoot:t.isRoot,label:t.label}}get size(){const e=this._size;return e[0]=this.pixelWidth,e[1]=this.pixelHeight,e}get width(){return this.sizeSource.width}get height(){return this.sizeSource.height}get pixelWidth(){return this.sizeSource.pixelWidth}get pixelHeight(){return this.sizeSource.pixelHeight}get resolution(){return this.sizeSource._resolution}get colorTextures(){return this._colorTextures||(this._colorTextures=this.colorAttachments.map(e=>e.texture)),this._colorTextures}get depthStencilTexture(){var e;return((e=this.depthStencilAttachment)==null?void 0:e.texture)??null}get depth(){return this._depth}get stencil(){return this._stencil}get colorTexture(){var e;return(e=this.colorAttachments[0])==null?void 0:e.texture}get sizeSource(){var e,t;return((e=this.colorAttachments[0])==null?void 0:e.texture)??((t=this.depthStencilAttachment)==null?void 0:t.texture)}onSourceResize(e){this.resize(e.width,e.height,e._resolution,!0)}ensureDepthStencilTexture(){this._createDepthStencilTexture(this.sizeSource.width,this.sizeSource.height,this.sizeSource._resolution),this._depth=!0,this._stencil=!0}resize(e,t,r=this.resolution,s=!1){if(this.dirtyId++,this.colorAttachments.forEach((n,i)=>{s&&i===0||n.texture.resize(e,t,r)}),this.depthStencilAttachment){if(s&&this.colorAttachments.length===0)return;this.depthStencilAttachment.texture.resize(e,t,r)}}destroy(){!this.colorAttachments&&!this.depthStencilAttachment||(this.emit("destroy",this),this.sizeSource.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorAttachments.forEach(e=>{e.texture.destroy()}),this.depthStencilAttachment&&(this.depthStencilAttachment.texture.destroy(),delete this.depthStencilAttachment),this.colorAttachments=null,this._colorTextures=null,this.removeAllListeners())}_createDepthStencilTexture(e,t,r){return this.depthStencilAttachment??(this.depthStencilAttachment={texture:new w({width:e,height:t,resolution:r,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1})}),this.depthStencilAttachment}};We.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let D=We;const k=new Map;lt.register(k);function Ne(a,e){if(!k.has(a)){const t=new _({source:new V({resource:a,...e})}),r=()=>{k.get(a)===t&&k.delete(a)};t.once("destroy",r),t.source.once("destroy",r),k.set(a,t)}return k.get(a)}const se=class je{get autoDensity(){return this.texture.source.autoDensity}set autoDensity(e){this.texture.source.autoDensity=e}get resolution(){return this.texture.source._resolution}set resolution(e){this.texture.source.resize(this.texture.source.width,this.texture.source.height,e)}constructor(e){this._renderer=e}init(e){e={...je.defaultOptions,...e},e.view&&(f(dt,"ViewSystem.view has been renamed to ViewSystem.canvas"),e.canvas=e.view),this.screen=new P(0,0,e.width,e.height),this.canvas=e.canvas||q.get().createCanvas(),this.antialias=!!e.antialias;const{depth:t,...r}=e;this.texture=Ne(this.canvas,r),this.renderTarget=new D({colorTextures:[this.texture],depth:!!t,isRoot:!0}),this.texture.source.transparent=e.backgroundAlpha<1,this.texture.source.on("resize",this._updateScreenSize,this),this.resolution=e.resolution,this._updateScreenSize()}resize(e,t,r){this.texture.source.resize(e,t,r),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height}destroy(e=!1){(typeof e=="boolean"?e:!!(e!=null&&e.removeView))&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.texture.source.off("resize",this._updateScreenSize,this),v.removeScreen(this._renderer.uid),he.removeScreen(this._renderer.uid),this.texture.destroy()}_updateScreenSize(){const{pixelWidth:e,pixelHeight:t}=this.texture.source,r=this._renderer.uid;v.setScreenSize(r,e,t),he.setScreenSize(r,e,t)}};se.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"view",priority:0};se.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1};let Dt=se;const Ft=[Ct,ze,ee,Dt,Ie,Bt,It,Oe,St,ht,Ut,Fe],Ht=[Ge,Se,Be,Pe,ke,Me,Re,we];function Et(a,e,t,r,s,n){const i=n?1:-1;return a.identity(),a.a=1/r*2,a.d=i*(1/s*2),a.tx=-1-e*a.a,a.ty=-i-t*a.d,a}function Ot(a){if(a.colorAttachments.length===0)return!1;const e=a.colorTexture.resource;return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement&&document.body.contains(e)}class Wt{constructor(e){this.rootViewPort=new P,this.viewport=new P,this.onRenderTargetChange=new ct("onRenderTargetChange"),this.projectionMatrix=new x,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._bindState={target:null,frame:void 0,mipLevel:0,layer:0,flipY:!1},this._bindFrame=new P,this._renderer=e,e.gc.addCollection(this,"_gpuRenderTargetHash","hash")}get renderSurface(){return this._bindState.target}get mipLevel(){return this._bindState.mipLevel}get layer(){return this._bindState.layer}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart(e){var t,r;this._renderTargetStack.length=0,this.push(e),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=Ot(this.rootRenderTarget),(r=(t=this.adaptor).prerender)==null||r.call(t,this.rootRenderTarget)}postrender(){var e,t;(t=(e=this.adaptor).postrender)==null||t.call(e,this.rootRenderTarget)}bind(e,t=!0,r,s,n=0,i=0,l){var ae,ie;let o;"target"in e?o=e:(f("8.20.0","RenderTargetSystem.bind: positional arguments are deprecated, please use an options object instead: bind({ target, clear, clearColor, frame, mipLevel, layer, flipY })"),o={target:e,clear:t,clearColor:r,frame:s,mipLevel:n,layer:i,flipY:l});const c=o.target;t=o.clear??!0,r=o.clearColor,n=(o.mipLevel??0)|0,i=(o.layer??0)|0,l=o.flipY,s=o.frame;const h=this.getRenderTarget(c),u=this.renderTarget!==h||!!h.flipY!=!!l;this.renderTarget=h;const g=this.getGpuRenderTarget(h);(h.pixelWidth!==g.width||h.pixelHeight!==g.height)&&(this.adaptor.resizeGpuRenderTarget(h),g.width=h.pixelWidth,g.height=h.pixelHeight);const p=((ae=h.colorAttachments[0])==null?void 0:ae.texture)||((ie=h.depthStencilAttachment)==null?void 0:ie.texture),m=this.viewport,ne=p.dimension==="3d"?Math.max(p.depth>>n,1):p.depthOrArrayLayers;if(i<0||i>=ne)throw new Error(`[RenderTargetSystem] layer ${i} is out of bounds (layer count=${ne}).`);const M=this._bindState;M.target=c,M.frame=s?this._bindFrame.copyFrom(s):void 0,M.mipLevel=n,M.layer=i,M.flipY=l;const z=Math.max(p.pixelWidth>>n,1),F=Math.max(p.pixelHeight>>n,1);if(!s&&c instanceof _&&(s=c.frame),s){const G=p._resolution,A=1<<Math.max(n,0),Ye=s.x*G+.5|0,$e=s.y*G+.5|0,qe=s.width*G+.5|0,Ke=s.height*G+.5|0;let b=Math.floor(Ye/A),y=Math.floor($e/A),C=Math.ceil(qe/A),S=Math.ceil(Ke/A);b<0&&(C+=b,b=0),y<0&&(S+=y,y=0),b=Math.min(b,z-1),y=Math.min(y,F-1),C=Math.min(C,z-b),S=Math.min(S,F-y),C=Math.max(C,1),S=Math.max(S,1),m.x=b,m.y=y,m.width=C,m.height=S}else m.x=0,m.y=0,m.width=z,m.height=F;return h.flipY=l,Et(this.projectionMatrix,0,0,m.width/p.resolution,m.height/p.resolution,!h.isRoot!=!!h.flipY),this.adaptor.startRenderPass(h,t,r,m,n,i),u&&this.onRenderTargetChange.emit(h),h}getBindState(e){if(!this.renderTarget)throw new Error("[RenderTargetSystem] getBindState is only valid while a render surface is bound");const t=this._bindState;return e??(e={}),e.target=t.target,e.clear=U.NONE,e.clearColor=void 0,t.frame?e.frame?e.frame.copyFrom(t.frame):e.frame=t.frame.clone():e.frame=void 0,e.mipLevel=t.mipLevel,e.layer=t.layer,e.flipY=!!t.flipY,e}isFrontFaceInverted(e,t){if(!e){if(e=this.renderTarget,!e)return!1;t=e.flipY}return!!t!=(this._renderer.type===L.WEBGL&&!e.isRoot)}get frontFaceInverted(){return f(ut,"RenderTargetSystem.frontFaceInverted is deprecated, use isFrontFaceInverted() instead"),this.isFrontFaceInverted()}clear(e,t=U.ALL,r,s=this.mipLevel,n=this.layer){t&&(e&&(e=this.getRenderTarget(e)),this.adaptor.clear(e||this.renderTarget,t,r,this.viewport,s,n))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(e,t=U.ALL,r,s,n=0,i=0,l){let o;"target"in e?o=e:(f("8.20.0","RenderTargetSystem.push: positional arguments are deprecated, please use an options object instead: push({ target, clear, clearColor, frame, mipLevel, layer, flipY })"),o={target:e,clear:t,clearColor:r,frame:s,mipLevel:n,layer:i,flipY:l});const c=this.bind(o);return this._renderTargetStack.push({target:o.target,clear:!1,clearColor:void 0,frame:o.frame?o.frame.clone():void 0,mipLevel:o.mipLevel,layer:o.layer,flipY:o.flipY}),c}pop(){this._renderTargetStack.pop();const e=this._renderTargetStack[this._renderTargetStack.length-1];if(!e)throw new Error("[RenderTargetSystem] pop: no previous binding to restore (unbalanced pop)");return this.bind(e)}getRenderTarget(e){return e.isTexture&&(e=e.source),this._renderSurfaceToRenderTargetHash.get(e)??this._initRenderTarget(e)}copyToTexture(e,t,r,s,n){const i=this.getRenderTarget(e);r.x<0&&(s.width+=r.x,n.x-=r.x,r.x=0),r.y<0&&(s.height+=r.y,n.y-=r.y,r.y=0);const{pixelWidth:l,pixelHeight:o}=i;return s.width=Math.min(s.width,l-r.x),s.height=Math.min(s.height,o-r.y),this.adaptor.copyToTexture(i,t,r,s,n)}copyDepthTexture(e,t,r,s,n={x:0,y:0}){const i=this.getRenderTarget(e);if(!i.depthStencilAttachment){R("[RenderTargetSystem] copyDepthTexture: the source render target has no depth attachment to copy from");return}const l=t.source;if(!l.format.includes("depth")&&!l.format.includes("stencil")){R(`[RenderTargetSystem] copyDepthTexture: the destination texture must have a depth/stencil format (got '${l.format}')`);return}let o=r.x,c=r.y,h=n.x,u=n.y,g=s.width,p=s.height;o<0&&(g+=o,h-=o,o=0),c<0&&(p+=c,u-=c,c=0),g=Math.min(g,i.pixelWidth-o),p=Math.min(p,i.pixelHeight-c),g=Math.min(g,l.pixelWidth-h),p=Math.min(p,l.pixelHeight-u),!(g<=0||p<=0)&&this.adaptor.copyDepthTexture(i,t,{x:o,y:c},{width:g,height:p},{x:h,y:u})}ensureDepthStencil(){if(!this.renderTarget.stencil){if(this.renderTarget.depthStencilTexture){R(`[RenderTargetSystem] a stencil mask is being used, but the render target's depthStencilTexture format '${this.renderTarget.depthStencilTexture.format}' has no stencil aspect, so masking cannot work here. Use a 'depth24plus-stencil8' texture instead.`);return}this.renderTarget._depth=!0,this.renderTarget._stencil=!0,this.adaptor.startRenderPass(this.renderTarget,!1,null,this.viewport,0,this.layer)}}destroy(){this._renderer=null,this._renderSurfaceToRenderTargetHash.forEach((e,t)=>{e!==t?this._releaseRenderTarget(t,e):e.off("destroy",this._onRenderTargetDestroy,this)}),this._renderSurfaceToRenderTargetHash.clear();for(const e of Object.values(this._gpuRenderTargetHash))e&&this.adaptor.destroyGpuRenderTarget(e);this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(e){let t=null;if(V.test(e)&&(e=Ne(e).source),e instanceof D)t=e,e.once("destroy",this._onRenderTargetDestroy,this);else if(e instanceof w){const r=e.format;t=r.includes("depth")||r.includes("stencil")?new D({colorTextures:0,depthStencilTexture:e}):new D({colorTextures:[e]}),e.source instanceof V&&(t.isRoot=!0),e.once("destroy",this._onRenderSurfaceDestroy,this)}return this._renderSurfaceToRenderTargetHash.set(e,t),t}_onRenderSurfaceDestroy(e){const t=this._renderSurfaceToRenderTargetHash.get(e);t&&this._releaseRenderTarget(e,t)}_onRenderTargetDestroy(e){this._renderSurfaceToRenderTargetHash.delete(e),this._releaseGpuRenderTarget(e)}_releaseRenderTarget(e,t){t.destroy(),this._renderSurfaceToRenderTargetHash.delete(e),e.off("destroy",this._onRenderSurfaceDestroy,this),this._releaseGpuRenderTarget(t)}_releaseGpuRenderTarget(e){const t=this._gpuRenderTargetHash[e.uid];t&&(this._gpuRenderTargetHash[e.uid]=null,this.adaptor.destroyGpuRenderTarget(t))}getGpuRenderTarget(e){return this._gpuRenderTargetHash[e.uid]||(this._gpuRenderTargetHash[e.uid]=this.adaptor.initGpuRenderTarget(e))}resetState(){this.renderTarget=null,this._bindState.target=null}}export{ke as A,Ge as B,we as C,Wt as R,Ft as S,Se as a,Be as b,Pe as c,Ht as d};