diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..4a094bf --- /dev/null +++ b/.dockerignore @@ -0,0 +1,13 @@ +node_modules +dist +data +.e2e-data +.tmp-data +test-results +playwright-report +coverage +.env +.git +.vscode +.idea +*.log diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..51249fe --- /dev/null +++ b/.env.example @@ -0,0 +1,19 @@ +# 复制为 .env 后修改。生产环境(Docker)请通过环境变量传入。 + +# 登录口令(生产环境必填) +BOUNDLESS_PASSWORD=change-me + +# 会话签名密钥,可选。不填会自动生成并保存在数据目录里 +# BOUNDLESS_SECRET= + +# 数据目录(SQLite 数据库与图片),默认 ./data +# DATA_DIR=./data + +# 服务端口,默认 3000 +# PORT=3000 + +# 登录有效天数,默认 90 +# SESSION_DAYS=90 + +# 单张图片大小上限(MB),默认 20 +# MAX_IMAGE_MB=20 diff --git a/.gitignore b/.gitignore index f81ee87..bab2871 100644 --- a/.gitignore +++ b/.gitignore @@ -40,3 +40,8 @@ __screenshots__/ test-results/ playwright-report/ + +# 本地数据与环境变量 +/data +/.e2e-data +.env diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..eca7804 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +24.22.0 \ No newline at end of file diff --git a/.oxlintrc.json b/.oxlintrc.json index 86b5cc2..553576e 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -6,5 +6,6 @@ }, "categories": { "correctness": "error" - } + }, + "ignorePatterns": ["public/painterly/**"] } diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..4d8ee4e --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,72 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## 项目概述 + +无界笺 Boundless:自部署的无限画布笔记应用(文字便笺、图片卡片、连线、多空间),单用户口令登录,多台设备实时同步。界面文案与提示均为简体中文。 + +- 前端:Vue 3 + TypeScript 6、Vite 8、Vue Flow(`@vue-flow/*`)、Pinia、Tailwind CSS 4 +- 同步:Yjs + Hocuspocus v4(WebSocket),y-indexeddb 做本机离线缓存 +- 服务端:Node.js 直接运行 `.ts`(原生类型剥离,无编译步骤)、Hono、`node:sqlite` +- 包管理器 pnpm(lockfile v9,用 pnpm 10),Node `^22.18.0 || >=24.12.0` + +## 常用命令 + +```sh +pnpm install +pnpm dev # run-p:服务端 :3000(--watch)+ Vite :5173(代理 /api 与 /collab) +pnpm start # 只启动服务端;会托管 dist/(如果存在) +pnpm build # vue-tsc --build(含 server/shared)+ vite build +pnpm lint # oxlint + eslint,都带 --fix,会直接改文件 + +pnpm test:unit -- --run # Vitest(src/__tests__ 与 server/__tests__) +pnpm test:unit -- --run server/__tests__/server.spec.ts # 单个文件 +pnpm exec playwright test --project=chromium # e2e:自动 build + 启动真实服务端(:4174,数据目录 .e2e-data) +pnpm exec playwright test -g "多端同步" --project=chromium +``` + +开发时口令默认 `boundless`;可在 `.env`(见 `.env.example`)里设置 `BOUNDLESS_PASSWORD` 等变量。生产环境未设置口令会拒绝启动。数据在 `DATA_DIR`(默认 `./data`):`boundless.sqlite`、`images/`、`session.secret`。 + +## 架构 + +### 目录分工 + +- `shared/board.ts`:前后端共用的 Yjs 文档结构与读写函数(唯一的数据格式定义处) +- `server/`:`index.ts` 组装 HTTP 服务与 WebSocket 升级;`app.ts` 是 Hono 路由;`collab.ts` 包装 Hocuspocus(鉴权、持久化、空间增删、历史版本、搜索);`db.ts` 是 SQLite;`auth.ts` 是会话令牌与同源校验 +- `src/sync/`:客户端同步层(共享 WebSocket、`MetaSession` 空间列表、`BoardSession` 单个画布) +- `src/stores/canvas.ts`:Pinia store,连接同步层与 Vue Flow + +### Yjs 文档 + +- `meta`:空间列表 `spaces`(id → Y.Map)。**客户端连接是只读的**,增删改空间都走 REST(`/api/spaces`),由服务端通过 DirectConnection 写入,再广播给所有设备。卡片数 `cardCount` 由服务端在保存画布时回写。 +- `board:`:`cards`(id → 嵌套 Y.Map,字段级合并)与 `edges`(id → 普通对象)。叠放顺序靠卡片的 `z` 字段,不靠数组顺序。 +- 新增卡片字段:改 `shared/board.ts` 的 `CardFields`/`readCard`,再改 store 里的 `cardToNode`/`applyCardToNode` 和 `src/types/canvas.ts`。 + +### 数据流(单向) + +本机操作 → store action 用 `board.transact()` 写 Yjs(带 `LOCAL_ORIGIN`)→ Yjs observer → `store.syncFromDoc()` 把文档状态补丁到 `nodes`/`edges`(复用已有节点对象,保留 Vue Flow 的选中、尺寸等字段)→ `v-model` 渲染。远端更新走同一条 observer 路径。**不要直接改 `nodes` 里的位置或内容来"保存"**,那样不会同步。 + +- 拖拽、缩放进行中的卡片记在 `busyIds`,`syncFromDoc` 不覆盖它们的位置和尺寸;拖拽期间节流写入位置,`beginGesture`/`endGesture` 把整次拖拽合并成一步撤销。 +- 撤销/重做使用 `Y.UndoManager`,只跟踪 `LOCAL_ORIGIN`,所以只撤销本机操作。 +- Yjs 对象不能放进 Pinia 响应式状态,`meta`/`board` 会话放在 `canvas.ts` 的模块作用域。 + +### 服务端要点 + +- 鉴权:HttpOnly Cookie `boundless_session`(HMAC 签名,密钥由 secret + 口令派生,改口令即全部登出)。WebSocket 在 `upgrade` 阶段和 Hocuspocus `onAuthenticate` 都校验;拒绝时 `error.reason` 为 `unauthorized` 或 `not-found`,客户端据此区分"登录过期"和"空间已删除"。 +- 非 GET 的 `/api/*` 与 WebSocket 都做同源校验(兼容 `X-Forwarded-Host`)。 +- 历史版本:每次保存画布前,若距上个版本超过 10 分钟,就把**上一次保存的状态**存为快照(所以保存的是改动前的样子);每个空间最多 120 个。恢复时先备份当前状态,再通过 DirectConnection 替换内容,所有设备自动更新。 +- 图片:`POST /api/images` 原始字节,按文件头识别格式,以 SHA-1 命名去重;读取需要登录。被删除卡片引用的图片不会自动清理。 +- 服务端代码由 Node 直接运行:只能用可擦除的 TS 语法(不能用 enum、参数属性),相对导入必须带 `.ts` 后缀(`tsconfig.server.json` 会检查)。 + +### 前端要点 + +- 路由:`/login`、`/s/:spaceId`;`/` 会跳到上次打开的空间。`WorkspaceView` 是懒加载的。 +- 不要用 `crypto.randomUUID()`(非 HTTPS 下不可用),用 `src/sync/connection.ts` 的 `randomId()`。 +- 加载动画:`index.html` 里的 `#boot` 启动画面 + `src/boot.ts`;`PaintingLoader.vue` 用于登录页和切换空间。画作在 `public/painterly/`(第三方代码,原样保留,lint 已忽略),通过 iframe 隔离 p5 全局模式,用 `postMessage` 通知父页面。 +- 样式全部在 `src/style.css`(BEM 类名 + `:root` CSS 变量),组件里没有 ` +
+ +
+ 正在展开你的平面… + +
+
+
diff --git a/package.json b/package.json index 5525643..cd37d2f 100644 --- a/package.json +++ b/package.json @@ -4,9 +4,12 @@ "private": true, "type": "module", "scripts": { - "dev": "vite", + "dev": "run-p dev:server dev:web", + "dev:web": "vite", + "dev:server": "node --experimental-strip-types --disable-warning=ExperimentalWarning --env-file-if-exists=.env --watch server/index.ts", + "start": "node --experimental-strip-types --disable-warning=ExperimentalWarning --env-file-if-exists=.env server/index.ts", "build": "run-p type-check \"build-only {@}\" --", - "preview": "vite preview", + "preview": "run-s build-only start", "test:unit": "vitest", "test:e2e": "playwright test", "build-only": "vite build", @@ -17,6 +20,10 @@ "format": "prettier --write --experimental-cli src/" }, "dependencies": { + "@hocuspocus/extension-database": "4.7.1", + "@hocuspocus/provider": "4.7.1", + "@hocuspocus/server": "4.7.1", + "@hono/node-server": "2.1.5", "@lucide/vue": "^1.31.0", "@vue-flow/background": "^1.3.2", "@vue-flow/controls": "^1.1.3", @@ -24,10 +31,13 @@ "@vue-flow/minimap": "^1.5.4", "@vue-flow/node-resizer": "^1.5.1", "@vueuse/core": "^14.4.0", - "dexie": "^4.4.4", + "crossws": "0.4.15", + "hono": "4.13.13", "pinia": "^4.0.2", "vue": "^3.5.40", - "vue-router": "^5.2.0" + "vue-router": "^5.2.0", + "y-indexeddb": "9.0.12", + "yjs": "13.6.33" }, "devDependencies": { "@playwright/test": "^1.61.1", diff --git a/playwright.config.ts b/playwright.config.ts index 5ece956..5323437 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -1,110 +1,62 @@ import process from 'node:process' import { defineConfig, devices } from '@playwright/test' -/** - * Read environment variables from file. - * https://github.com/motdotla/dotenv - */ -// require('dotenv').config(); +import { E2E_PASSWORD } from './e2e/helpers' + +// e2e 跑的是生产构建 + 真实服务端,使用独立的临时数据目录 +const PORT = 4174 + /** * See https://playwright.dev/docs/test-configuration. */ export default defineConfig({ testDir: './e2e', - /* Maximum time one test can run for. */ - timeout: 30 * 1000, + timeout: 45 * 1000, expect: { - /** - * Maximum time expect() should wait for the condition to be met. - * For example in `await expect(locator).toHaveText();` - */ - timeout: 5000, + timeout: 8000, }, + fullyParallel: false, /* Fail the build on CI if you accidentally left test.only in the source code. */ forbidOnly: !!process.env.CI, - /* Retry on CI only */ retries: process.env.CI ? 2 : 0, - /* Opt out of parallel tests on CI. */ - workers: process.env.CI ? 1 : undefined, - /* Reporter to use. See https://playwright.dev/docs/test-reporters */ - reporter: 'html', - /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ + // 所有用例共用一个服务端和数据目录,串行执行更可靠 + workers: 1, + reporter: process.env.CI ? 'github' : 'list', use: { - /* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */ - actionTimeout: 0, - /* Base URL to use in actions like `await page.goto('/')`. */ - baseURL: process.env.CI ? 'http://localhost:4173' : 'http://localhost:5173', - - /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ + baseURL: `http://localhost:${PORT}`, trace: 'on-first-retry', - - /* Only on CI systems run the tests headless */ - headless: !!process.env.CI, + // 默认跳过加载动画,专门的用例会单独打开 + contextOptions: { reducedMotion: 'reduce' }, + locale: 'zh-CN', }, - /* Configure projects for major browsers */ projects: [ { name: 'chromium', - use: { - ...devices['Desktop Chrome'], - }, + use: { ...devices['Desktop Chrome'] }, }, { name: 'firefox', - use: { - ...devices['Desktop Firefox'], - }, + use: { ...devices['Desktop Firefox'] }, }, { name: 'webkit', - use: { - ...devices['Desktop Safari'], - }, + use: { ...devices['Desktop Safari'] }, }, - - /* Test against mobile viewports. */ - // { - // name: 'Mobile Chrome', - // use: { - // ...devices['Pixel 5'], - // }, - // }, - // { - // name: 'Mobile Safari', - // use: { - // ...devices['iPhone 12'], - // }, - // }, - - /* Test against branded browsers. */ - // { - // name: 'Microsoft Edge', - // use: { - // channel: 'msedge', - // }, - // }, - // { - // name: 'Google Chrome', - // use: { - // channel: 'chrome', - // }, - // }, ], - /* Folder for test artifacts such as screenshots, videos, traces, etc. */ - // outputDir: 'test-results/', - - /* Run your local dev server before starting the tests */ webServer: { - /** - * Use the dev server by default for faster feedback loop. - * Use the preview server on CI for more realistic testing. - * Playwright will re-use the local server if there is already a dev-server running. - */ - command: process.env.CI ? 'npm run preview' : 'npm run dev', - port: process.env.CI ? 4173 : 5173, - reuseExistingServer: !process.env.CI, + command: + 'node -e "require(\'fs\').rmSync(\'.e2e-data\',{recursive:true,force:true})" && npm run build-only && npm run start', + url: `http://localhost:${PORT}/healthz`, + reuseExistingServer: false, + timeout: 180 * 1000, + env: { + PORT: String(PORT), + DATA_DIR: '.e2e-data', + BOUNDLESS_PASSWORD: E2E_PASSWORD, + BOUNDLESS_SECRET: 'e2e-secret', + }, }, }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e9406e9..14dcc8d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,6 +8,18 @@ importers: .: dependencies: + '@hocuspocus/extension-database': + specifier: 4.7.1 + version: 4.7.1(y-protocols@1.0.7(yjs@13.6.33))(yjs@13.6.33) + '@hocuspocus/provider': + specifier: 4.7.1 + version: 4.7.1(y-protocols@1.0.7(yjs@13.6.33))(yjs@13.6.33) + '@hocuspocus/server': + specifier: 4.7.1 + version: 4.7.1(y-protocols@1.0.7(yjs@13.6.33))(yjs@13.6.33) + '@hono/node-server': + specifier: 2.1.5 + version: 2.1.5(hono@4.13.13) '@lucide/vue': specifier: ^1.31.0 version: 1.31.0(vue@3.5.41(typescript@6.0.3)) @@ -29,9 +41,12 @@ importers: '@vueuse/core': specifier: ^14.4.0 version: 14.4.0(vue@3.5.41(typescript@6.0.3)) - dexie: - specifier: ^4.4.4 - version: 4.4.4 + crossws: + specifier: 0.4.15 + version: 0.4.15 + hono: + specifier: 4.13.13 + version: 4.13.13 pinia: specifier: ^4.0.2 version: 4.0.2(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.41(typescript@6.0.3)) @@ -41,6 +56,12 @@ importers: vue-router: specifier: ^5.2.0 version: 5.2.0(@vue/compiler-sfc@3.5.41)(pinia@4.0.2(@vue/devtools-api@8.2.1)(typescript@6.0.3)(vue@3.5.41(typescript@6.0.3)))(rolldown@1.2.3)(vite@8.2.1(@types/node@24.13.3)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.41(typescript@6.0.3)) + y-indexeddb: + specifier: 9.0.12 + version: 9.0.12(yjs@13.6.33) + yjs: + specifier: 13.6.33 + version: 13.6.33 devDependencies: '@playwright/test': specifier: ^1.61.1 @@ -381,6 +402,33 @@ packages: '@noble/hashes': optional: true + '@hocuspocus/common@4.7.1': + resolution: {integrity: sha512-+N4t8AdBIWBUK+yHsuBvCcBm96eV2E3quIewma9+TYomqVMXhrovAf3dA6XFbYHRM7ggtXklHt2mFqTcpiMdAQ==} + + '@hocuspocus/extension-database@4.7.1': + resolution: {integrity: sha512-9qpwJAY6QHu/++KNpz7wWHEmo/4zxEYFR3G5UD7Td5crnGT8DcZ5fM4LsZ9Uy3KCFYAdCnidnsSXvjy+7gcWRQ==} + peerDependencies: + yjs: ^13.6.8 + + '@hocuspocus/provider@4.7.1': + resolution: {integrity: sha512-znulqyCwwuhq86aFmTF6izOomwRWlZGReCAf+SZpLgpvdfvBQJzjoj9HdtuXXfL9wkBM2Ydt86kaMs2rjaicRA==} + peerDependencies: + y-protocols: ^1.0.6 + yjs: ^13.6.8 + + '@hocuspocus/server@4.7.1': + resolution: {integrity: sha512-f2TWNi5rFnju1ttOesxkR1kPIukFmMClHY4pAx0RlIBMzjAoUVlEgilETIAQlrwmw1UMxsy31fse0tmBzYEpwQ==} + engines: {node: '>=22'} + peerDependencies: + y-protocols: ^1.0.6 + yjs: ^13.6.8 + + '@hono/node-server@2.1.5': + resolution: {integrity: sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q==} + engines: {node: '>=20'} + peerDependencies: + hono: ^4 || ^5.0.0-0 + '@humanfs/core@0.19.2': resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} engines: {node: '>=18.18.0'} @@ -441,6 +489,9 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@lifeomic/attempt@3.1.0': + resolution: {integrity: sha512-QZqem4QuAnAyzfz+Gj5/+SLxqwCAw2qmt7732ZXodr6VDWGeYLG6w1i/vYLa55JQM9wRuBKLmXmiZ2P0LtE5rw==} + '@lucide/vue@1.31.0': resolution: {integrity: sha512-NtjEHhcAa7umPh40wrRmlESJqNGdnpc7LziBKFnW3fmlrW0g2xMCDpdWU7WeEHRSl3xOpxbqiFTLKxoK3CoVCg==} peerDependencies: @@ -1148,6 +1199,9 @@ packages: resolution: {integrity: sha512-IJdzo2vLiElBxKzwS36VsCue/62d6IdWjnPB2v3nuPKeWGynp6FF/CYoLa5i/3jXH/z97ZDdsXz6abpgM6w07A==} engines: {node: '>=20.19.0'} + async-mutex@0.5.0: + resolution: {integrity: sha512-1A94B18jkJ3DYq284ohPxoXbfTA5HsQ7/Mf4DEhcyLx3Bz27Rh59iScbB6EPiP+B+joue6YCxcMXSbFC1tZKwA==} + balanced-match@1.0.0: resolution: {integrity: sha512-9Y0g0Q8rmSt+H33DfKv7FOc3v+iRI+o1lbzt8jGcIosYW37IIW/2XVYq5NPdmaD5NQ59Nk26Kl/vZbwW9Fr8vg==} @@ -1234,6 +1288,14 @@ packages: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} + crossws@0.4.15: + resolution: {integrity: sha512-NsUOpDZosz7nyI+qEIl05yaiXOWaXH2oTeM+XBWtiSWZtb5rzcIsl1AST/HzM2jzUn76eFuyrkn83E6iSBRUvw==} + peerDependencies: + srvx: '>=0.11.5' + peerDependenciesMeta: + srvx: + optional: true + css-tree@3.2.1: resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==} engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} @@ -1319,9 +1381,6 @@ packages: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} - dexie@4.4.4: - resolution: {integrity: sha512-jIwsYI8Os2hgnqc6O49YwFDKGc5v5QjGx0wPVp543ip1F53VFAKMLthV2pQosQcVTv3eAskTWYspOx195PM0FQ==} - eastasianwidth@0.2.0: resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} @@ -1541,6 +1600,10 @@ packages: graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + hono@4.13.13: + resolution: {integrity: sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==} + engines: {node: '>=16.9.0'} + hookable@5.5.3: resolution: {integrity: sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==} @@ -1619,6 +1682,9 @@ packages: resolution: {integrity: sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==} engines: {node: '>=20'} + isomorphic.js@0.2.5: + resolution: {integrity: sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==} + jackspeak@3.1.2: resolution: {integrity: sha512-kWmLKn2tRtfYMF/BakihVVRzBKOxz4gJMiL2Rj91WnAB5TPZumSH99R/Yf1qE1u4uRimvCSJfm6hnxohXeEXjQ==} engines: {node: '>=14'} @@ -1673,6 +1739,10 @@ packages: keyv@4.5.4: resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} + kleur@4.1.5: + resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==} + engines: {node: '>=6'} + kolorist@1.8.0: resolution: {integrity: sha512-Y+60/zizpJ3HRH8DCss+q95yr6145JXZo46OTpFvDZWLfRCE4qChOyk1b26nMaNpfHHgxagk9dXT5OP0Tfe+dQ==} @@ -1680,6 +1750,11 @@ packages: resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} engines: {node: '>= 0.8.0'} + lib0@0.2.119: + resolution: {integrity: sha512-vh+TiejVy8Xm+hCdnRfn9BthGNvNUZdEXltNjVZL3TzRIKP3s1lnQh8pWd/Q0wCgY0FPAGVVjFF4ZiHUV3LFgA==} + engines: {node: '>=16'} + hasBin: true + lightningcss-android-arm64@1.32.0: resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==} engines: {node: '>= 12.0.0'} @@ -2235,6 +2310,9 @@ packages: peerDependencies: typescript: '>=4.8.4' + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + type-check@0.4.0: resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} engines: {node: '>= 0.8.0'} @@ -2547,6 +2625,18 @@ packages: xmlchars@2.2.0: resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} + y-indexeddb@9.0.12: + resolution: {integrity: sha512-9oCFRSPPzBK7/w5vOkJBaVCQZKHXB/v6SIT+WYhnJxlEC61juqG0hBrAf+y3gmSMLFLwICNH9nQ53uscuse6Hg==} + engines: {node: '>=16.0.0', npm: '>=8.0.0'} + peerDependencies: + yjs: ^13.0.0 + + y-protocols@1.0.7: + resolution: {integrity: sha512-YSVsLoXxO67J6eE/nV4AtFtT3QEotZf5sK5BHxFBXso7VDUT3Tx07IfA6hsu5Q5OmBdMkQVmFZ9QOA7fikWvnw==} + engines: {node: '>=16.0.0', npm: '>=8.0.0'} + peerDependencies: + yjs: ^13.0.0 + yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} @@ -2555,6 +2645,10 @@ packages: engines: {node: '>= 14.6'} hasBin: true + yjs@13.6.33: + resolution: {integrity: sha512-q/UYvr1gOk4XII+Cu1CW2dINjYqJJFifTzogEaIARznrvX7uOlHsdTEXcnOBMuIsrCGEEKdNxi74kyMLZlKVfw==} + engines: {node: '>=16.0.0', npm: '>=8.0.0'} + snapshots: '@asamuzakjp/css-color@5.1.11': @@ -2850,6 +2944,42 @@ snapshots: '@exodus/bytes@1.15.1': {} + '@hocuspocus/common@4.7.1': + dependencies: + lib0: 0.2.119 + + '@hocuspocus/extension-database@4.7.1(y-protocols@1.0.7(yjs@13.6.33))(yjs@13.6.33)': + dependencies: + '@hocuspocus/server': 4.7.1(y-protocols@1.0.7(yjs@13.6.33))(yjs@13.6.33) + yjs: 13.6.33 + transitivePeerDependencies: + - srvx + - y-protocols + + '@hocuspocus/provider@4.7.1(y-protocols@1.0.7(yjs@13.6.33))(yjs@13.6.33)': + dependencies: + '@hocuspocus/common': 4.7.1 + '@lifeomic/attempt': 3.1.0 + lib0: 0.2.119 + y-protocols: 1.0.7(yjs@13.6.33) + yjs: 13.6.33 + + '@hocuspocus/server@4.7.1(y-protocols@1.0.7(yjs@13.6.33))(yjs@13.6.33)': + dependencies: + '@hocuspocus/common': 4.7.1 + async-mutex: 0.5.0 + crossws: 0.4.15 + kleur: 4.1.5 + lib0: 0.2.119 + y-protocols: 1.0.7(yjs@13.6.33) + yjs: 13.6.33 + transitivePeerDependencies: + - srvx + + '@hono/node-server@2.1.5(hono@4.13.13)': + dependencies: + hono: 4.13.13 + '@humanfs/core@0.19.2': dependencies: '@humanfs/types': 0.15.0 @@ -2910,6 +3040,8 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.4.14 + '@lifeomic/attempt@3.1.0': {} + '@lucide/vue@1.31.0(vue@3.5.41(typescript@6.0.3))': dependencies: vue: 3.5.41(typescript@6.0.3) @@ -3559,6 +3691,10 @@ snapshots: '@babel/types': 7.29.8 ast-kit: 2.2.0 + async-mutex@0.5.0: + dependencies: + tslib: 2.8.1 + balanced-match@1.0.0: {} balanced-match@4.0.4: {} @@ -3634,6 +3770,8 @@ snapshots: shebang-command: 2.0.0 which: 2.0.1 + crossws@0.4.15: {} + css-tree@3.2.1: dependencies: mdn-data: 2.27.1 @@ -3705,8 +3843,6 @@ snapshots: detect-libc@2.1.2: {} - dexie@4.4.4: {} - eastasianwidth@0.2.0: {} editorconfig@1.0.7: @@ -3929,6 +4065,8 @@ snapshots: graceful-fs@4.2.11: {} + hono@4.13.13: {} + hookable@5.5.3: {} html-encoding-sniffer@6.0.0: @@ -3982,6 +4120,8 @@ snapshots: isexe@4.0.0: {} + isomorphic.js@0.2.5: {} + jackspeak@3.1.2: dependencies: '@isaacs/cliui': 8.0.2 @@ -4043,6 +4183,8 @@ snapshots: dependencies: json-buffer: 3.0.1 + kleur@4.1.5: {} + kolorist@1.8.0: {} levn@0.4.1: @@ -4050,6 +4192,10 @@ snapshots: prelude-ls: 1.2.1 type-check: 0.4.0 + lib0@0.2.119: + dependencies: + isomorphic.js: 0.2.5 + lightningcss-android-arm64@1.32.0: optional: true @@ -4523,6 +4669,8 @@ snapshots: dependencies: typescript: 6.0.3 + tslib@2.8.1: {} + type-check@0.4.0: dependencies: prelude-ls: 1.2.1 @@ -4796,6 +4944,20 @@ snapshots: xmlchars@2.2.0: {} + y-indexeddb@9.0.12(yjs@13.6.33): + dependencies: + lib0: 0.2.119 + yjs: 13.6.33 + + y-protocols@1.0.7(yjs@13.6.33): + dependencies: + lib0: 0.2.119 + yjs: 13.6.33 + yallist@3.1.1: {} yaml@2.9.0: {} + + yjs@13.6.33: + dependencies: + lib0: 0.2.119 diff --git a/public/icon.svg b/public/icon.svg new file mode 100644 index 0000000..d645b00 --- /dev/null +++ b/public/icon.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/public/manifest.webmanifest b/public/manifest.webmanifest new file mode 100644 index 0000000..6c4113f --- /dev/null +++ b/public/manifest.webmanifest @@ -0,0 +1,13 @@ +{ + "name": "无界笺 Boundless", + "short_name": "无界笺", + "description": "一张可以无限延伸、在所有设备间同步的灵感平面。", + "start_url": "/", + "display": "standalone", + "background_color": "#f4f3ee", + "theme_color": "#f4f3ee", + "lang": "zh-CN", + "icons": [ + { "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" } + ] +} diff --git a/public/painterly/engine.js b/public/painterly/engine.js new file mode 100644 index 0000000..9c2e16b --- /dev/null +++ b/public/painterly/engine.js @@ -0,0 +1,316 @@ +/* ===================================================================== + * engine.js — the reveal loop, shared by every style. + * + * Lifted from loader.html without changing how anything paints: each + * stroke is drawn once into an offscreen buffer, then copied onto the + * visible canvas in slices along its direction so it looks drawn. + * + * A styleConfig is: + * { + * label: 'Impressionism', + * canvasSize: 600, + * loopMs: 9000, + * holdMs: 1500, + * palette: { ground, phrases, ...whatever the style's strokes want }, + * strokes: (palette) => [ descriptor, ... ], + * vocabulary: [ fn, ... ], // for the gallery's Copy code button + * } + * + * A descriptor is { fn, bb, axis, dir, dur, gap } — see D() below. + * + * Three p5.brush facts this file is built around, all verified in 2.2.2: + * - scaleBrushes() multiplies the shared brush registry in place, so it + * must run exactly once per page. See ensureBrushes(). + * - brush.load(target) is a global retarget, so it is re-issued whenever + * a config is (re)loaded rather than only once in setup. + * - brush.wash is deferred until the next drawing call. See flushWash(). + * ===================================================================== */ + +/* Canvas dimensions live at module scope so the style vocabularies can go on + referencing bare W / H / m exactly as they did inside loader.html. The + engine sets them from styleConfig.canvasSize before anything paints. */ +let W = 600, H = 600, m = 600; + +/* ---- seeded helpers (all randomness goes through p5's seeded random) ---- */ +const rr = (a, b) => random(a, b); +const pickOne = (arr) => arr[Math.floor(random(arr.length))]; +const clamp01 = (v) => Math.max(0, Math.min(1, v)); +const clampN = (v, a, b) => Math.max(a, Math.min(b, v)); + +/* ---- colour maths ---- */ +function hexRgb(h) { h = h.replace('#', ''); if (h.length === 3) h = h.split('').map((c) => c + c).join(''); return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16)); } +function mixHex(a, b, t) { const A = hexRgb(a), B = hexRgb(b); return '#' + A.map((v, i) => Math.round(v + (B[i] - v) * t).toString(16).padStart(2, '0')).join(''); } +function hexHsl(hex) { + const [r, g, b] = hexRgb(hex).map((v) => v / 255); + const max = Math.max(r, g, b), min = Math.min(r, g, b), l = (max + min) / 2; + let h = 0, s = 0; + if (max !== min) { const d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); if (max === r) h = (g - b) / d + (g < b ? 6 : 0); else if (max === g) h = (b - r) / d + 2; else h = (r - g) / d + 4; h /= 6; } + return [h, s, l]; +} +function hslHex(h, s, l) { + const f = (p, q, t) => { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; if (t < 1 / 2) return q; if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; }; + let r, g, b; + if (s === 0) { r = g = b = l; } else { const q = l < 0.5 ? l * (1 + s) : l + s - l * s, p = 2 * l - q; r = f(p, q, h + 1 / 3); g = f(p, q, h); b = f(p, q, h - 1 / 3); } + return '#' + [r, g, b].map((v) => Math.round(v * 255).toString(16).padStart(2, '0')).join(''); +} +function vivid(hex, amt) { if (!amt) return hex; const [h, s, l] = hexHsl(hex); return hslHex(h, s + (1 - s) * amt, l - (l - 0.45) * amt * 0.5); } + +/* ---- geometry ---- */ +function jitterEllipse(cx, cy, rx, ry, n, jitter, rot = 0) { + const pts = [], a0 = rr(0, TWO_PI), cr = Math.cos(rot), sr = Math.sin(rot); + for (let i = 0; i < n; i++) { + const a = a0 + (i / n) * TWO_PI, k = 1 + rr(-jitter, jitter); + const x = Math.cos(a) * rx * k, y = Math.sin(a) * ry * k; + pts.push([cx + x * cr - y * sr, cy + x * sr + y * cr]); + } + return pts; +} +function rosette(cx, cy, r, lobes, inner, rot = 0, jit = 0.05) { + const n = Math.max(24, lobes * 6), pts = []; + for (let i = 0; i < n; i++) { + const a = (i / n) * TWO_PI, k = inner + (1 - inner) * (0.5 + 0.5 * Math.cos(lobes * a)); + const rad = r * k * (1 + rr(-jit, jit)); + pts.push([cx + Math.cos(a + rot) * rad, cy + Math.sin(a + rot) * rad]); + } + return pts; +} +function bandPolygon(y0, y1, wobble, n = 9) { + const top = [], bottom = []; + for (let i = 0; i <= n; i++) { const x = -10 + (W + 20) * (i / n); top.push([x, y0 + rr(-wobble, wobble)]); bottom.push([x, y1 + rr(-wobble, wobble)]); } + return top.concat(bottom.reverse()); +} +const bboxOf = (pts, pad) => { + let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity; + for (const [x, y] of pts) { if (x < x0) x0 = x; if (y < y0) y0 = y; if (x > x1) x1 = x; if (y > y1) y1 = y; } + return [Math.max(0, Math.floor(x0 - pad)), Math.max(0, Math.floor(y0 - pad)), Math.min(W, Math.ceil(x1 + pad)), Math.min(H, Math.ceil(y1 + pad))]; +}; + +/* ---- style switches (fill, wash and stroke are independent in p5.brush, + so each one turns the others off before drawing) ---- */ +function fillStyle(color, opacity, bleed, texture, border) { brush.noStroke(); brush.noHatch(); brush.noWash(); brush.fill(color, opacity); brush.fillBleed(bleed, 'out'); brush.fillTexture(texture, border); } +function washStyle(color, opacity) { brush.noStroke(); brush.noHatch(); brush.noFill(); brush.wash(color, opacity); } +function strokeStyle(name, color, weight) { brush.noFill(); brush.noWash(); brush.noHatch(); brush.set(name, color, weight); } + +/* ---- descriptor constructor: each stroke is revealed along its axis over + `dur` ms, like a brush travelling across the paper ---- */ +const D = (fn, bb, axis, dir, dur, gap = 60) => ({ fn, bb, axis, dir, dur, gap }); +const rdir = () => (random() < 0.5 ? 1 : -1); +const raxis = () => (random() < 0.5 ? 'x' : 'y'); + +/* p5.brush queues flat washes and only renders them on the next drawing call + (bleed fills are immediate). A tiny fully transparent fill off-canvas forces + that flush so the buffer is complete before it is copied. */ +function flushWash() { + brush.noStroke(); brush.noHatch(); brush.noWash(); + brush.fill('#000000', 0); brush.fillBleed(0); brush.fillTexture(0, 0); + brush.polygon([[-8, -8], [-6, -8], [-6, -6]]); +} + +/* scaleBrushes() multiplies the shared brush registry in place, so calling it + twice compounds. This runs once per page; a later call at a different scale + is refused loudly rather than silently doubling every brush. */ +let brushScale = null; +function ensureBrushes(scale) { + if (brushScale !== null) { + if (Math.abs(brushScale - scale) > 1e-6) { + console.warn(`engine: brushes already scaled to ${brushScale}; ignoring request for ${scale}. ` + + 'scaleBrushes multiplies in place, so all canvases on a page must share one size.'); + } + return; + } + brush.add('flick', { weight: 0.7, vibration: 0.12, definition: 0.9, quality: 0.8, opacity: 200, spacing: 0.1, pressure: { curve: [0.25, 0.25], min_max: [1.1, 0.85] } }); + brush.add('rim', { weight: 0.45, vibration: 0.35, definition: 0.7, quality: 0.8, opacity: 190, spacing: 0.1, pressure: { curve: [0.15, 0.2], min_max: [1.2, 1] } }); + brush.scaleBrushes(scale); + brushScale = scale; +} + +/* ===================================================================== + * createEngine(styleConfig, opts) + * + * opts: + * mount element the canvas is appended to (moved, if it already exists) + * statusEl element that receives the palette's phrases (optional) + * freeze progress 0..1 to freeze at instead of looping (optional) + * nextConfig (cycle) => styleConfig, called at each cycle boundary. + * Defaults to the config passed in. loader.html uses this to + * keep its garden -> dawn -> willow -> wisteria rotation; + * the engine itself knows nothing about rotation. + * ===================================================================== */ +function createEngine(styleConfig, opts = {}) { + let cfg = styleConfig; + let buf, paint, canvasEl; + let strokes = [], idx = 0; + let startMs = null, currentCycle = -1, phaseIndex = -1, fadeTimer = null; + let statusEl = opts.statusEl || null; + const freeze = typeof opts.freeze === 'number' ? clamp01(opts.freeze) : null; + const nextConfig = opts.nextConfig || (() => cfg); + + function setup() { + W = cfg.canvasSize; H = cfg.canvasSize; m = Math.min(W, H); + const cnv = createCanvas(W, H, WEBGL); + canvasEl = cnv.elt || cnv.canvas || document.querySelector('canvas'); + if (opts.mount) mount(opts.mount); + + ensureBrushes(3 * m / 600); + + // `paint` holds everything finished so far; `buf` is paint plus the stroke + // being drawn. Drawing each stroke over a copy of the painting lets its wet + // edges mix with the real colours underneath, and every copy between the + // three surfaces is opaque (no fringes). + paint = createGraphics(W, H, WEBGL); + buf = createGraphics(W, H, WEBGL); + paint.imageMode(CORNER); buf.imageMode(CORNER); + brush.load(buf); + // pre-warm the fill shaders into the buffer, then wipe it + buf.push(); buf.translate(-W / 2, -H / 2); + fillStyle('#7a86bd', 200, 0.3, 0.5, 0.3); brush.circle(W / 2, H / 2, 12); + buf.pop(); buf.clear(); + imageMode(CORNER); + background(cfg.palette.ground); + } + + /* Move the one canvas into a new parent. Used by the gallery to hand the + live canvas from card to card. */ + function mount(el) { + if (canvasEl && el && canvasEl.parentElement !== el) el.appendChild(canvasEl); + } + + /* Point the engine at a different style and start it from the first stroke. */ + function load(nextCfg) { + cfg = nextCfg || cfg; + // The canvas and the scaled brushes are both fixed at setup, so every style + // sharing a page has to share its size. Say so rather than paint at the + // wrong coordinates. + if (cfg.canvasSize !== W) { + console.warn(`engine: "${cfg.label}" wants canvasSize ${cfg.canvasSize} but the canvas is ${W}. ` + + 'Painting at ' + W + '. All styles on one page must share a canvasSize.'); + } + brush.load(buf); // brush.load is a global retarget + randomSeed(cfg.palette.seed); noiseSeed(cfg.palette.seed); + strokes = cfg.strokes(cfg.palette); + // give every stroke its own seed, then lay the timeline out end to end + // and fit it to loopMs + let cursor = 0; + for (const s of strokes) { s.seed = Math.floor(random() * 1e9); s.begun = false; s.rev = null; s.start = cursor; cursor += s.dur + s.gap; } + const k = cfg.loopMs / cursor; + for (const s of strokes) { s.start *= k; s.dur *= k; s.end = s.start + s.dur; } + idx = 0; phaseIndex = -1; + paint.background(cfg.palette.ground); + background(cfg.palette.ground); + } + + function beginStroke(s) { + buf.clear(); + buf.push(); buf.translate(-W / 2, -H / 2); + buf.image(paint, 0, 0, W, H); // start from the painting so far + randomSeed(s.seed); noiseSeed(s.seed); + s.fn(); + flushWash(); + buf.pop(); + s.begun = true; s.p = 0; + } + // a finished stroke becomes part of the painting + function foldStroke() { + paint.push(); paint.translate(-W / 2, -H / 2); + paint.image(buf, 0, 0, W, H); + paint.pop(); + } + // draw the revealed part of the stroke in progress: a slice of its box, + // growing along its direction + function revealSlice(s) { + const [x0, y0, x1, y1] = s.bb; + if (x1 <= x0 || y1 <= y0 || s.p <= 0) return; + if (s.axis === 'x') { + const w = Math.round((x1 - x0) * s.p); if (w <= 0) return; + const a = s.dir > 0 ? x0 : x1 - w; + image(buf, a, y0, w, y1 - y0, a, y0, w, y1 - y0); + } else { + const h = Math.round((y1 - y0) * s.p); if (h <= 0) return; + const a = s.dir > 0 ? y0 : y1 - h; + image(buf, x0, a, x1 - x0, h, x0, a, x1 - x0, h); + } + } + function paintUpTo(t) { + while (idx < strokes.length && strokes[idx].start <= t) { + const s = strokes[idx]; + if (!s.begun) beginStroke(s); + s.p = Math.min(1, (t - s.start) / s.dur); + if (s.p >= 1) { foldStroke(); idx++; } else break; + } + } + function drawFrame(t) { + paintUpTo(t); + image(paint, 0, 0, W, H); + const s = strokes[idx]; + if (s && s.begun) revealSlice(s); + } + + function draw() { + translate(-W / 2, -H / 2); + if (freeze !== null) { + if (!strokes.length) { load(nextConfig(0)); drawFrame(freeze * cfg.loopMs); updateStatus(freeze); noLoop(); } + return; + } + if (startMs === null) startMs = millis(); + const now = millis() - startMs, cycleMs = cfg.loopMs + cfg.holdMs; + const cycle = Math.floor(now / cycleMs), elapsed = now % cycleMs; + if (cycle !== currentCycle) { currentCycle = cycle; load(nextConfig(cycle)); } + drawFrame(Math.min(elapsed, cfg.loopMs)); + updateStatus(Math.min(elapsed / cfg.loopMs, 1)); + } + + /* Restart from the first stroke on the next frame. */ + function restart() { startMs = null; currentCycle = -1; } + + /* Paint up to t on demand, outside the animation loop. drawFrame is already + incremental — paintUpTo resumes from where it left off — so the caller can + walk t up over several frames to paint a whole picture without blocking. + The gallery uses this to render each card's finished still at load. */ + function renderTo(t) { push(); translate(-W / 2, -H / 2); drawFrame(t); pop(); } + + /* Point at a different style and restart. The strokes are not rebuilt here — + the next draw() does that once, via nextConfig. Used by the gallery when + the live canvas moves to another card. */ + function switchTo(nextCfg, nextStatusEl) { + cfg = nextCfg || cfg; + if (nextStatusEl !== undefined) { + if (statusEl && statusEl !== nextStatusEl) { clearTimeout(fadeTimer); statusEl.textContent = ''; } + statusEl = nextStatusEl; + } + restart(); + } + + function updateStatus(progress) { + if (!statusEl) return; + const list = cfg.palette.phrases; + if (!list || !list.length) return; + let i; + if (progress >= 1) i = list.length - 1; + else { const active = Math.max(list.length - 1, 1); i = Math.min(Math.floor(progress * active), active - 1); } + if (i === phaseIndex) return; + const fresh = phaseIndex === -1; + phaseIndex = i; + clearTimeout(fadeTimer); + if (fresh) { statusEl.classList.remove('fade'); statusEl.textContent = list[i]; return; } + statusEl.classList.add('fade'); + fadeTimer = setTimeout(() => { statusEl.textContent = list[i]; statusEl.classList.remove('fade'); }, 250); + } + + return { + setup, draw, load, mount, restart, switchTo, renderTo, + get config() { return cfg; }, + get canvas() { return canvasEl; }, + }; +} + +/* Every function above that a copied standalone file needs, in dependency + order. The gallery serialises these with Function.prototype.toString(). + Keep in step when adding a shared helper. */ +const SHARED_FOR_COPY = [ + rr, pickOne, clamp01, clampN, + hexRgb, mixHex, hexHsl, hslHex, vivid, + jitterEllipse, rosette, bandPolygon, bboxOf, + fillStyle, washStyle, strokeStyle, + D, rdir, raxis, + flushWash, ensureBrushes, createEngine, +]; diff --git a/public/painterly/index.html b/public/painterly/index.html new file mode 100644 index 0000000..dbd411f --- /dev/null +++ b/public/painterly/index.html @@ -0,0 +1,31 @@ + + + + + + Painting + + + + + + + + + + + diff --git a/public/painterly/loader.js b/public/painterly/loader.js new file mode 100644 index 0000000..ad2f9bf --- /dev/null +++ b/public/painterly/loader.js @@ -0,0 +1,72 @@ +/* ===================================================================== + * loader.js — 无界笺的加载动画外壳。 + * + * 绘画引擎与 12 幅画作来自 Painting Loaders + * (https://painterly.design-tools.workers.dev,作者 Sasha / x.com/aleksksaa), + * engine.js 与 style-*.js 原样保留。这里只负责:随机挑一幅(不与上次重复), + * 把画布铺满本页,并通知父页面已经开始作画。 + * + * 本页通过 iframe 嵌入,p5 的全局模式不会污染主应用。 + * ===================================================================== */ + +const PAINTINGS = [ + { key: 'garden', style: 'impressionismGarden', name: '花园', label: 'Garden' }, + { key: 'dawn', style: 'impressionismDawn', name: '晨曦', label: 'Dawn' }, + { key: 'willow', style: 'impressionismWillow', name: '垂柳', label: 'Willow' }, + { key: 'wisteria', style: 'impressionismWisteria', name: '紫藤', label: 'Wisteria' }, + { key: 'orchard', style: 'impressionismOrchard', name: '果园', label: 'Orchard' }, + { key: 'irises', style: 'impressionismIrises', name: '鸢尾', label: 'Irises' }, + { key: 'poppies', style: 'impressionismPoppies', name: '虞美人', label: 'Poppies' }, + { key: 'koi', style: 'impressionismKoi', name: '锦鲤', label: 'Koi' }, + { key: 'roses', style: 'impressionismRoses', name: '玫瑰', label: 'Roses' }, + { key: 'oranges', style: 'impressionismOranges', name: '橘子', label: 'Oranges' }, + { key: 'sail', style: 'impressionismSail', name: '远帆', label: 'Sail' }, + { key: 'dusk', style: 'abstractionDusk', name: '黄昏', label: 'Dusk' }, +]; + +const LAST_KEY = 'boundless-last-painting'; + +function choosePainting() { + const wanted = new URLSearchParams(location.search).get('p'); + const exact = PAINTINGS.find((item) => item.key === wanted); + if (exact) return exact; + + let last = null; + try { last = localStorage.getItem(LAST_KEY); } catch (e) { /* 隐私模式 */ } + const pool = PAINTINGS.filter((item) => item.key !== last); + const picked = pool[Math.floor(Math.random() * pool.length)] || PAINTINGS[0]; + try { localStorage.setItem(LAST_KEY, picked.key); } catch (e) { /* 隐私模式 */ } + return picked; +} + +const painting = choosePainting(); +const config = window.STYLES[painting.style]; +document.documentElement.style.background = config.palette.ground; + +function notifyParent(type) { + if (window.parent === window) return; + window.parent.postMessage( + { source: 'boundless-painterly', type, key: painting.key, name: painting.name, label: painting.label, ground: config.palette.ground }, + location.origin, + ); +} + +notifyParent('chosen'); + +let engine = null; +const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; + +// p5 全局模式:页面加载后若 window 上有 setup / draw 就会自动开始。 +// 系统要求减少动态效果时不作画,只留下画纸底色。 +if (!reduceMotion) { + window.setup = function () { + // 画布内部固定 600×600,再由 CSS 缩放;不跟随设备像素比可以省下不少显存 + pixelDensity(1); + engine = createEngine(config, { mount: document.body }); + engine.setup(); + notifyParent('start'); + }; + window.draw = function () { + if (engine) engine.draw(); + }; +} diff --git a/public/painterly/style-abstraction.js b/public/painterly/style-abstraction.js new file mode 100644 index 0000000..a1ba98e --- /dev/null +++ b/public/painterly/style-abstraction.js @@ -0,0 +1,239 @@ +/* ===================================================================== + * style-abstraction.js — Abstraction · Dusk. + * + * The playground's `abstract` generator at its dusk mood: no scene, no + * subject. Wide soft columns of colour stained down the paper, translucent + * marker glazes running with them, then a crowd of tall wet drips clustered + * around two or three attractors, a last veil of glaze over the top and a + * few light touches. Everything travels vertically, which is what makes it + * read as poured rather than composed. + * + * Ported from playground.html rather than rewritten: the build draws the + * same random numbers in the same order as the playground does, so at seed + * 1874 this is the picture the mood was picked from. The one thing that + * cannot carry over is per-stroke brush grain — the engine reseeds before + * each stroke so it can redraw them independently — so the shapes, colours + * and paint order match while the wet texture inside them differs. + * + * Same contract as the other style files: an IIFE exporting onto + * window.STYLES, dials named S (Copy code emits `const S = …`), palette + * carrying ground / seed / phrases, strokes naming its builder literally. + * ===================================================================== */ +window.STYLES = window.STYLES || {}; + +(function () { + // The dusk preset's dials, baked in. pattern picks the mark shape and flow + // the direction everything runs; the rest are the playground's sliders. + // detail and brushSize come from the playground's MARK_DEFAULTS, which the + // abstract moods inherit rather than set. + const S = { + pattern: 'drips', flow: 'vertical', + water: 0.7, coverage: 0.5, density: 0.35, scale: 1, soft: 0.6, glaze: 0.4, touch: 0.2, + detail: 0.6, brushSize: 1, + }; + + const PALETTE = { + seed: 1874, + ground: '#f4ece6', // warm paper, barely tinted + washes: ['#8f7fa8', '#c68aa0', '#e6b39a', '#f0cfa0'], // violet → rose → apricot → sand + accents: ['#6d5c8a', '#e28f8f', '#d9a56b'], // the drips + highlights: ['#f9dc9c', '#fff3e0'], // the last touches + phrases: ['creating…', 'washing…', 'flowing…', 'blooming…', 'finished'], + }; + + // ===================================================================== + // Geometry + // ===================================================================== + // The vertical twin of engine.js's bandPolygon: a column between x0 and x1, + // both edges wobbling, run off the top and bottom of the canvas. + function columnPolygon(x0, x1, wobble, n = 9) { + const left = [], right = []; + for (let i = 0; i <= n; i++) { + const y = -20 + (H + 40) * (i / n); + left.push([x0 + rr(-wobble, wobble), y]); + right.push([x1 + rr(-wobble, wobble), y]); + } + return left.concat(right.reverse()); + } + + // The playground scheduled every stroke on a 0..1 timeline and painted them + // in t order; the engine paints them in array order. Keeping the schedule and + // sorting on it at the end reproduces the playground's paint order — which + // marks land on top of which — and, because it draws its random numbers in + // the same places, everything built after it. + function schedule(items, t0, t1, jitter = 0.3) { + const step = (t1 - t0) / Math.max(items.length, 1); + items.forEach((it, i) => { it.t = t0 + step * (i + 0.5) + rr(-jitter, jitter) * step; }); + return items; + } + + // ===================================================================== + // Drawing vocabulary + // ===================================================================== + function glazeDraw(x0, y0, x1, y1, color, weight, field = 'hand') { + brush.field(field); strokeStyle('marker', color, weight * S.brushSize); + brush.line(x0, y0, x1, y1); brush.noField(); + } + function flickDraw(x, y, len, a, color, weight) { + strokeStyle('flick', color, weight * S.brushSize); + brush.line(x - Math.cos(a) * len / 2, y - Math.sin(a) * len / 2, x + Math.cos(a) * len / 2, y + Math.sin(a) * len / 2); + } + + // ===================================================================== + // Descriptor factories + // + // Nothing here calls raxis() / rdir(): the flow already says which way the + // paint travels, and drawing extra random numbers would move every shape + // built after it off the composition this mood was picked at. + // ===================================================================== + const flowAxis = () => (S.flow === 'horizontal' ? 'x' : 'y'); + const longAxis = (bb) => ((bb[2] - bb[0]) >= (bb[3] - bb[1]) ? 'x' : 'y'); + + function dWash(color, opacity) { + const pts = [[-20, -20], [W + 20, -20], [W + 20, H + 20], [-20, H + 20]]; + return D(() => { washStyle(color, opacity); brush.polygon(pts); }, [0, 0, W, H], flowAxis(), 1, 700, 120); + } + // One of the wide stained columns (or bands, or pools) the picture is built on. + function dGround(pts, color, opacity, bleed, texture) { + return D(() => { fillStyle(color, opacity, bleed, texture, 0.3); brush.polygon(pts); }, + bboxOf(pts, m * 0.25), flowAxis(), 1, 520, 90); + } + function dGlaze(x0, y0, x1, y1, color, weight, field) { + const bb = bboxOf([[x0, y0], [x1, y1]], 14 + weight * 4 * S.brushSize); + const axis = Math.abs(x1 - x0) >= Math.abs(y1 - y0) ? 'x' : 'y'; + const dir = axis === 'x' ? (Math.sign(x1 - x0) || 1) : (Math.sign(y1 - y0) || 1); + const len = Math.hypot(x1 - x0, y1 - y0); + return D(() => glazeDraw(x0, y0, x1, y1, color, weight, field), bb, axis, dir, 90 + len * 0.45, 45); + } + // A mark: at this water the bleed drifts well past the polygon, so the reveal + // box is padded generously — the buffer holds only this stroke, so an + // oversized box copies nothing but transparency. Drips are revealed downwards + // whatever their shape, so each one runs rather than appearing. + function dMark(pts, color, opacity, bleed, texture) { + const bb = bboxOf(pts, m * 0.08 + 14); + const axis = S.pattern === 'drips' ? 'y' : longAxis(bb); + const extent = axis === 'x' ? bb[2] - bb[0] : bb[3] - bb[1]; + return D(() => { fillStyle(color, opacity, bleed, texture, 0.3); brush.polygon(pts); }, + bb, axis, 1, 180 + extent * 0.9, 70); + } + function dFlick(x, y, len, a, color, weight) { + const ends = [[x - Math.cos(a) * len / 2, y - Math.sin(a) * len / 2], [x + Math.cos(a) * len / 2, y + Math.sin(a) * len / 2]]; + const axis = Math.abs(Math.cos(a)) >= Math.abs(Math.sin(a)) ? 'x' : 'y'; + return D(() => flickDraw(x, y, len, a, color, weight), bboxOf(ends, 10 + weight * 5), axis, 1, 90, 25); + } + // Small light strokes dropped near the marks already placed. + function dTouches(points, C, count, angleFn, sizeMul = 1) { + const items = []; + count = Math.round(count * (0.4 + 0.6 * S.detail)); + for (let i = 0; i < count; i++) { + const p = points.length ? pickOne(points) : [rr(0, W), rr(0, H), 20]; + const x = p[0] + rr(-p[2], p[2]), y = p[1] + rr(-p[2] * 0.6, p[2] * 0.6); + const color = random() < 0.85 ? pickOne(C.highlights) : pickOne(C.accents); + const len = rr(8, 22) * S.scale * sizeMul, weight = rr(0.6, 1.1) * S.scale; + items.push(dFlick(x, y, len, angleFn(), color, weight)); + } + return items; + } + + // ===================================================================== + // The picture + // ===================================================================== + function buildAbstraction(C) { + const out = []; + const group = (items, t0, t1) => { schedule(items, t0, t1); out.push(...items); }; + const { water, density: dens, scale: sc, soft } = S; + const { washes, accents, highlights } = C; + const horizontal = S.flow === 'horizontal', vertical = S.flow === 'vertical'; + + // 1. the coverage wash, flat, under everything + if (S.coverage > 0.02) { + const w = dWash(washes[0], Math.round(S.coverage * 200)); + w.t = 0.02; + out.push(w); + } + + // 2. the ground: a few wide stains, one per wash colour, overlapping + const nGround = 2 + Math.round(dens * 2); + const ground = []; + for (let i = 0; i < nGround; i++) { + const color = washes[i % washes.length]; + const opacity = Math.round(225 - water * 80); + const bleed = 0.25 + water * 0.55, texture = 0.3 + water * 0.5; + let pts; + if (horizontal) { const y0 = -20 + (i / nGround) * H + rr(-30, 30), h = H / nGround * rr(1.2, 1.8); pts = bandPolygon(y0, y0 + h, 14 + soft * 20); } + else if (vertical) { const x0 = -20 + (i / nGround) * W + rr(-30, 30), w = W / nGround * rr(1.2, 1.8); pts = columnPolygon(x0, x0 + w, 14 + soft * 20); } + else pts = jitterEllipse(rr(W * 0.2, W * 0.8), rr(H * 0.2, H * 0.8), W * rr(0.35, 0.6), H * rr(0.25, 0.45), 14, 0.1 + soft * 0.25, rr(-0.6, 0.6)); + ground.push(dGround(pts, color, opacity, bleed, texture)); + } + group(ground, 0.03, 0.16); + + // 3. glazes travelling with the flow. A quarter of them are held back as a + // veil and laid over the marks at the end instead. + const glazes = []; + for (let i = 0; i < Math.round(S.glaze * 22); i++) { + const color = random() < 0.7 ? pickOne(washes) : pickOne(accents); + const weight = rr(1.2, 3.2) * Math.sqrt(sc); + let x0, y0, x1, y1, field; + if (horizontal) { y0 = rr(0, H); x0 = rr(-10, W * 0.5); x1 = x0 + rr(W * 0.3, W * 0.9); y1 = y0 + rr(-8, 8); field = random() < 0.25 ? 'waves' : 'hand'; } + else if (vertical) { x0 = rr(0, W); y0 = rr(-10, H * 0.5); y1 = y0 + rr(H * 0.25, H * 0.8); x1 = x0 + rr(-8, 8); field = 'hand'; } + else { x0 = rr(0, W); y0 = rr(0, H); const a = rr(-0.6, 0.6), len = rr(m * 0.2, m * 0.5); x1 = x0 + Math.cos(a) * len; y1 = y0 + Math.sin(a) * len; field = random() < 0.5 ? 'curved' : 'seabed'; } + glazes.push(dGlaze(x0, y0, x1, y1, color, weight, field)); + } + const veil = glazes.splice(0, Math.round(glazes.length * 0.25)); + group(glazes, 0.16, 0.30); + + // 4. the marks. Most fall near two or three attractors, which is what gives + // the picture its clusters and its empty right-hand side; the rest are + // scattered anywhere. Painted biggest first so the small ones sit on top. + const nMarks = Math.round((3 + dens * 34) * (S.pattern === 'dapple' ? 1.6 : 1)); + const attractors = []; + for (let i = 0, n = 2 + Math.floor(rr(0, 3)); i < n; i++) attractors.push([rr(W * 0.15, W * 0.85), rr(H * 0.15, H * 0.85)]); + const s0 = m * 0.06 * sc; + const marks = [], centers = []; + for (let i = 0; i < nMarks; i++) { + let x, y; + if (random() < 0.25) { x = rr(0, W); y = rr(0, H); } + else { const a = pickOne(attractors); const sd = m * (S.pattern === 'dapple' ? 0.1 : 0.16); x = a[0] + randomGaussian(0, sd); y = a[1] + randomGaussian(0, sd); } + const r = s0 * rr(0.5, 1.6); + const color = random() < 0.2 ? pickOne(highlights) : pickOne(accents); + const jit = 0.08 + soft * 0.3; + let pts, opacity, bleed, texture; + switch (S.pattern) { + case 'bands': pts = jitterEllipse(x, y, r * rr(2.5, 4.5), r * rr(0.25, 0.5), 14, jit * 0.6); opacity = 205 - water * 60; bleed = 0.3 + water * 0.5; texture = 0.4 + water * 0.4; break; + case 'petals': pts = jitterEllipse(x, y, r * rr(0.7, 1.1), r * rr(0.28, 0.45), 10, jit * 0.5, rr(0, TWO_PI)); opacity = 225 - water * 45; bleed = 0.12 + water * 0.3; texture = 0.3 + water * 0.3; break; + case 'drips': pts = jitterEllipse(x, y, r * rr(0.3, 0.5), r * rr(2, 4), 14, jit * 0.7); opacity = 200 - water * 60; bleed = 0.4 + water * 0.4; texture = 0.4 + water * 0.4; break; + case 'dapple': pts = jitterEllipse(x, y, r * 0.45, r * rr(0.35, 0.45), 10, jit); opacity = 200 - water * 40; bleed = 0.2 + water * 0.3; texture = 0.3 + water * 0.3; break; + default: pts = jitterEllipse(x, y, r, r * rr(0.6, 1), 12, jit); opacity = 200 - water * 60; bleed = 0.3 + water * 0.5; texture = 0.4 + water * 0.4; + } + centers.push([x, y, r]); + const d = dMark(pts, color, Math.round(opacity), bleed, texture); + d.r = r; + marks.push(d); + } + marks.sort((a, b) => b.r - a.r); + group(marks, 0.30, 0.86); + + // 5. the held-back glazes over the top, then the touches + group(veil, 0.86, 0.92); + const angle = () => (horizontal ? rr(-0.1, 0.1) : vertical ? HALF_PI + rr(-0.15, 0.15) : rr(0, TWO_PI)); + group(dTouches(centers, C, Math.round(S.touch * 20), angle), 0.92, 1.0); + + // the engine paints in array order; t is the playground's paint order + return out.sort((a, b) => a.t - b.t); + } + + STYLES.abstractionDusk = { + key: 'abstraction-dusk', + movement: 'Abstraction', + note: 'The hour when color stops trying to be anything specific.', + label: 'Dusk', + canvasSize: 600, + loopMs: 9000, + holdMs: 1500, + dials: S, + palette: PALETTE, + strokes: (palette) => buildAbstraction(palette), + vocabulary: [columnPolygon, schedule, glazeDraw, flickDraw, flowAxis, longAxis, + dWash, dGround, dGlaze, dMark, dFlick, dTouches, buildAbstraction], + }; +})(); diff --git a/public/painterly/style-impressionism.js b/public/painterly/style-impressionism.js new file mode 100644 index 0000000..811f5f4 --- /dev/null +++ b/public/painterly/style-impressionism.js @@ -0,0 +1,1144 @@ +/* ===================================================================== + * style-impressionism.js — Monet. + * + * Everything here is lifted verbatim from loader.html; only the wrapper + * changed. The vocabulary lives inside an IIFE so later movements can + * reuse names like drawFlower without colliding, and reads W / H / m from + * engine.js at call time (never captured at load time). + * + * Exports eleven sibling configs sharing one vocabulary, all of them + * cards in index.html. loader.html rotates the first four (garden, dawn, + * willow, wisteria). + * ===================================================================== */ +window.STYLES = window.STYLES || {}; + +(function () { + // The dials settled on in the playground, baked in. + // `flower` scales blooms only — not pads, leaves or the compositions around them. + // At 1.8 a willow lily grows from ~20px to ~36px on its unchanged ~60px pad, so it + // sits proud of the pad rather than on it, the way Monet paints them. + const S = { water: 0.55, coverage: 0.84, density: 0.5, scale: 1.1, soft: 0.7, glaze: 0.3, touch: 0.2, detail: 0.45, brushSize: 1.49, vivid: 0.45, flower: 1.8 }; + + const SCENES = { + garden: { + seed: 1874, ground: '#f6f0ea', + washes: ['#eed7dc', '#dcc3cf', '#cdd8c0', '#f1e2d2'], foliage: ['#8fae72', '#5f8656', '#3f6146', '#b8cf95'], + accents: ['#f4b3cb', '#ea8fb4', '#d8679a', '#fbd7e3', '#f7e6ec'], highlights: ['#f7e0a4', '#fff4f7'], + phrases: ['creating…', 'growing…', 'blooming…', 'catching the light…', 'finished'], + }, + dawn: { + seed: 1874, ground: '#f4efe9', + washes: ['#f2c9d3', '#e8b0c6', '#c9c0d9', '#b8cfd4'], foliage: ['#b9cfae', '#7fa38f', '#5a8272', '#d5e2c4'], + accents: ['#f3b8cf', '#e79ab9', '#d97fa3', '#fbe6ee'], highlights: ['#fde7b8', '#fff7e6'], + phrases: ['creating…', 'glowing…', 'growing the reeds…', 'opening the lilies…', 'finished'], + }, + willow: { + seed: 1874, ground: '#f3efe6', + washes: ['#6f8fb3', '#4f6fa0', '#a9c8d6', '#3f5a86'], foliage: ['#5f8a5a', '#8fb15b', '#31504a', '#d2c96a'], + accents: ['#f2b6c9', '#e88fb0', '#d9749a', '#fbe3ea'], highlights: ['#f6e0a0', '#fff6d6'], + phrases: ['creating…', 'painting the water…', 'hanging the willow…', 'floating the lilies…', 'finished'], + }, + wisteria: { + seed: 1874, ground: '#f5efe3', + washes: ['#e9dfa0', '#d9c9b8', '#c9b9d9', '#b7c68a'], foliage: ['#9bb26f', '#7c9a5e', '#5a7a4c', '#b9c98a'], + accents: ['#b99bd6', '#9c7fc4', '#e8b3c7', '#f3d6a2', '#7f63b0'], highlights: ['#fbf1c4', '#fff8e8'], + phrases: ['creating…', 'dappling the meadow…', 'hanging the wisteria…', 'scattering blossoms…', 'finished'], + }, + poppies: { + seed: 1874, ground: '#f5f0e6', + washes: ['#c9d6e3', '#a9bfd4', '#b9c98a', '#8fa86a'], foliage: ['#7f9d5e', '#5b7f4d', '#3a5a40', '#c9d47a'], + accents: ['#d9463f', '#e4614f', '#b73838', '#f2a49e'], highlights: ['#f7e7b4', '#fff6e6'], + phrases: ['creating…', 'washing the sky…', 'growing the meadow…', 'scattering poppies…', 'finished'], + }, + irises: { + seed: 1874, ground: '#f4eee2', + washes: ['#e6d6b8', '#d9c9a6', '#c8b8d6', '#b6c9a2'], foliage: ['#7fa565', '#5b8452', '#3c5f45', '#b9cf8a'], + accents: ['#8a6bb8', '#6c4fa0', '#4e3a85', '#c9b3e0', '#b28fd0'], highlights: ['#f4e3a6', '#fff6e6'], + phrases: ['creating…', 'laying the path…', 'raising the blades…', 'opening the irises…', 'finished'], + }, + orchard: { + seed: 1874, ground: '#f5f1e8', + washes: ['#cfdcea', '#b9cbe0', '#c5d39a', '#9db877'], foliage: ['#7fa26a', '#5c8455', '#3e5f47', '#c0d28d'], + accents: ['#f6d4dc', '#eeb6c4', '#e39bb0', '#fff1f4', '#f9e4ea'], highlights: ['#f7e6b4', '#fff8ee'], + phrases: ['creating…', 'washing the sky…', 'planting the orchard…', 'blossoming…', 'finished'], + }, + // The second set. The four colour lists keep their generic names; what each + // slot means in these scenes is noted per palette. + // koi: washes = teals / foliage = deep water and the shadow fish / accents = koi oranges / highlights = cream flecks + koi: { + seed: 1874, ground: '#3f7f8a', + washes: ['#4f9aa0', '#7fc0b8', '#2f6e8a', '#a8d4c6'], foliage: ['#2a5d70', '#1f4a60', '#173a4a', '#5f9a90'], + accents: ['#e8621e', '#f08a2a', '#c9471a', '#f6b06a'], highlights: ['#f3efc9', '#e9e6a8'], + phrases: ['creating…', 'stirring the water…', 'swirling…', 'the koi come up…', 'finished'], + }, + // roses: washes = lilac-grey, gold, pale blue, cream / accents = rose pinks light to deep, coral heart / highlights = gold light, white + roses: { + seed: 1874, ground: '#eee6dc', + washes: ['#d9cdc9', '#e8d9a8', '#c9c2d4', '#f1e2c4'], foliage: ['#5f7a4a', '#3f5a3a', '#2f4432', '#9bb47a'], + accents: ['#f3b4a9', '#ea8f8a', '#d96468', '#f8cfc4', '#fbe6de'], highlights: ['#f4d98a', '#fff6e6'], + phrases: ['creating…', 'dappling the light…', 'shading the leaves…', 'opening the roses…', 'finished'], + }, + // oranges: washes = sky blues and a pale ground / accents = the fruit, light to deep / highlights = blossom white, rind light + oranges: { + seed: 1874, ground: '#eef0ea', + washes: ['#b7cfe2', '#9fbfd9', '#d7e3ea', '#c2d4b0'], foliage: ['#6f9a3f', '#3f6b2f', '#24401f', '#a9c35a'], + accents: ['#f28c1e', '#e5731a', '#f7a23a', '#c95a12'], highlights: ['#fff6e0', '#fdf1c9'], + phrases: ['creating…', 'clearing the sky…', 'growing the leaves…', 'ripening…', 'finished'], + }, + // sail: washes = sky blue, lilac sea, pink glow, grey-blue ripple / foliage = hull and rowboat darks / accents = cloud peach + sail: { + seed: 1874, ground: '#e9e2e0', + washes: ['#b9c3d9', '#c9b4c6', '#e6b9b0', '#8d95b3'], foliage: ['#4a4f6a', '#3a3f55', '#2c3044', '#7a7f9a'], + accents: ['#f0b39a', '#e8a48e', '#f6cdb5', '#f9dccb'], highlights: ['#f8e6d2', '#fdf5ee'], + phrases: ['creating…', 'washing the sky…', 'stilling the sea…', 'raising a sail…', 'finished'], + }, + }; + + // ===================================================================== + // Drawing vocabulary (the watercolor style from the playground) + // ===================================================================== + function softBlobDraw(x, y, rx, ry, color, opacity, bleed, texture, rot = 0, jit = 0.12) { + const w = S.water - 0.5; + fillStyle(color, Math.round(opacity - w * 60), clamp01(bleed + w * 0.4), clamp01(texture + w * 0.2), 0.3); + brush.polygon(jitterEllipse(x, y, rx, ry, 14, jit, rot)); + } + function bloomFill(color, opacity, bleed) { fillStyle(color, opacity, clamp01(bleed + S.water * 0.3), 0.5, 0.4); } + // One bloom layer: a flat body inset under a bleeding fill of the same scalloped + // shape. The body makes the colour solid (no ground showing through), the fill + // keeps the rim wet. No outline is ever stroked, so nothing reads as a line. + function bloomShape(x, y, r, lobes, inner, color, bleed = 0.3, solid = 0.72) { + const rot = rr(0, TWO_PI); + washStyle(color, 255); brush.polygon(rosette(x, y, r * solid, lobes, inner, rot, 0.08)); + bloomFill(color, 250, bleed); brush.polygon(rosette(x, y, r, lobes, inner, rot, 0.05)); + } + function centerDot(x, y, r, color, opacity = 250) { washStyle(color, opacity); brush.polygon(jitterEllipse(x, y, r, r * rr(0.85, 1), 12, 0.14)); } + function flowerCols(C, v = S.vivid) { + const a = C.accents, h = C.highlights; + const light = vivid(a[0], v), mid = vivid(a[1] || a[0], v), deep = vivid(a[2] || a[1] || a[0], v); + return { light, mid, deep, base: a[3] || mixHex(light, '#ffffff', 0.45), center: vivid(h[0] || '#e6b94f', v), pale: h[1] || mixHex(light, '#ffffff', 0.7), shade: mixHex(deep, '#3b3550', 0.45) }; + } + function foliageCols(C) { const f = C.foliage; return { light: f[3] || mixHex(f[0], '#ffffff', 0.35), mid: f[0], deep: f[1] || f[0], shade: f[2] || mixHex(f[0], '#1f2f2a', 0.5) }; } + function drawPeony(x, y, s, F) { + const det = S.detail; + bloomShape(x, y, s * 1.08, 8, 0.74, mixHex(F.light, F.mid, S.vivid * 0.5), 0.32, 0.74); + bloomShape(x, y, s * 0.62, 6, 0.68, F.mid, 0.24, 0.68); + if (det > 0.35) bloomShape(x, y, s * 0.32, 5, 0.66, F.deep, 0.2, 0.62); + centerDot(x, y, 0.1 * s, F.center, 235); + } + function drawDaisy(x, y, s, F) { + const lobes = 7 + Math.round(4 * S.detail); + bloomShape(x, y, s * 1.05, lobes, 0.4, F.pale, 0.28, 0.8); + bloomFill(F.light, 170, 0.3); brush.polygon(rosette(x, y, s * 0.52, lobes, 0.55, rr(0, TWO_PI))); + centerDot(x, y, 0.24 * s, F.center, 245); + centerDot(x + 0.06 * s, y + 0.07 * s, 0.1 * s, mixHex(F.center, F.shade, 0.45), 190); + } + function drawBlossom(x, y, s, F) { + bloomShape(x, y, s * 0.9, 5, 0.5, random() < 0.5 ? F.light : F.mid, 0.26, 0.74); + centerDot(x, y, 0.14 * s, F.center, 240); + } + function drawLily(x, y, s, F) { + const pts = [], n = 36, lobes = 6; + for (let i = 0; i <= n; i++) { + const a = Math.PI + (i / n) * Math.PI, k = 0.62 + 0.38 * (0.5 + 0.5 * Math.cos(lobes * a)); + pts.push([x + Math.cos(a) * 10 * s * k * (1 + rr(-0.05, 0.05)), y + 2 * s + Math.sin(a) * 9 * s * k]); + } + pts.push([x + 4 * s, y + 4.5 * s], [x, y + 5.5 * s], [x - 4 * s, y + 4.5 * s]); + washStyle(F.light, 255); brush.polygon(pts.map(([px, py]) => [x + (px - x) * 0.76, y + 2 * s + (py - y - 2 * s) * 0.76])); + bloomFill(F.light, 250, 0.3); brush.polygon(pts); + bloomFill(F.deep, 235, 0.28); brush.polygon(jitterEllipse(x, y + 2 * s, 5.5 * s, 3.2 * s, 10, 0.12)); + centerDot(x, y + 1 * s, 2.2 * s, F.center, 242); + } + function drawFlower(type, x, y, s, F) { + if (type === 'peony') drawPeony(x, y, s, F); else if (type === 'daisy') drawDaisy(x, y, s, F); else if (type === 'lily') drawLily(x, y, s, F); else drawBlossom(x, y, s, F); + } + function drawPad(x, y, r, G) { + fillStyle(G.mid, 240, clamp01(0.2 + S.water * 0.25), 0.5, 0.35); + brush.polygon(jitterEllipse(x, y, r, r * 0.42, 12, 0.08)); + strokeStyle('flick', G.light, 1.1 * S.brushSize); + brush.spline([[x - r * 0.6, y - r * 0.2], [x - r * 0.1, y - r * 0.4], [x + r * 0.5, y - r * 0.3]], 0.5); + strokeStyle('rim', G.shade, 1.4 * S.brushSize); + brush.spline([[x - r * 0.7, y + r * 0.2], [x, y + r * 0.45], [x + r * 0.7, y + r * 0.2]], 0.5); + } + function drawStrand(x0, y0, len, sway, color, weight, name = 'flick') { + brush.field('hand'); + const watery = S.water > 0.6 && random() < (S.water - 0.6) * 1.5; + strokeStyle(watery ? 'marker' : name, color, weight * S.brushSize * (watery ? 2 : 1)); + brush.spline([[x0, y0], [x0 + sway * 0.5 + rr(-2, 2), y0 + len * 0.5], [x0 + sway, y0 + len]], 0.6); + brush.noField(); + } + function glazeDraw(x0, y0, x1, y1, color, weight, field = 'hand') { brush.field(field); strokeStyle('marker', color, weight * S.brushSize); brush.line(x0, y0, x1, y1); brush.noField(); } + function flickDraw(x, y, len, a, color, weight) { strokeStyle('flick', color, weight * S.brushSize); brush.line(x - Math.cos(a) * len / 2, y - Math.sin(a) * len / 2, x + Math.cos(a) * len / 2, y + Math.sin(a) * len / 2); } + + // ===================================================================== + // Descriptor factories + // ===================================================================== + function dWash(color, opacity) { + const pts = [[-10, -10], [W + 10, -10], [W + 10, H + 10], [-10, H + 10]]; + return D(() => { washStyle(color, opacity); brush.polygon(pts); }, [0, 0, W, H], 'x', rdir(), 700, 120); + } + function dBand(y0, y1, color, opacity, wobble) { + const pts = bandPolygon(y0, y1, wobble), water = S.water; + const bleed = 0.25 + water * 0.5, texture = 0.3 + water * 0.5; + return D(() => { fillStyle(color, opacity, bleed, texture, 0.3); brush.polygon(pts); }, bboxOf(pts, m * 0.25), 'x', rdir(), 600, 100); + } + // Reveal boxes are padded generously: bleed spreads well past the polygon, and since the + // buffer only holds the current stroke an oversized box copies nothing but transparency. + function dBlob(x, y, rx, ry, color, opacity, bleed, texture, rot = 0, jit = 0.12, dur = 420) { + const big = Math.max(rx, ry), pad = big * 0.9 + 14; + const bb = [Math.max(0, x - big - pad), Math.max(0, y - big - pad), Math.min(W, x + big + pad), Math.min(H, y + big + pad)]; + return D(() => softBlobDraw(x, y, rx, ry, color, opacity, bleed, texture, rot, jit), bb.map(Math.round), raxis(), rdir(), dur, 80); + } + function dGlaze(x0, y0, x1, y1, color, weight, field) { + const bb = bboxOf([[x0, y0], [x1, y1]], 14 + weight * 4 * S.brushSize); + const axis = Math.abs(x1 - x0) >= Math.abs(y1 - y0) ? 'x' : 'y'; + const dir = axis === 'x' ? Math.sign(x1 - x0) || 1 : Math.sign(y1 - y0) || 1; + const len = Math.hypot(x1 - x0, y1 - y0); + return D(() => glazeDraw(x0, y0, x1, y1, color, weight, field), bb, axis, dir, 160 + len * 1.4, 50); + } + function dStrand(x0, y0, len, sway, color, weight, name) { + const bb = bboxOf([[x0, y0], [x0 + sway, y0 + len]], 14 + weight * 5 * S.brushSize); + return D(() => drawStrand(x0, y0, len, sway, color, weight, name), bb, 'y', Math.sign(len) || 1, 120 + Math.abs(len) * 1.2, 30); + } + function dLeaves(cx, cy, rx, ry, n, cols, size, rot = 0) { + n = Math.max(2, Math.round(n * (0.3 + 0.7 * S.detail))); + size *= S.brushSize * (1.4 - 0.4 * S.detail); + const items = []; + let batch = []; + for (let i = 0; i < n; i++) { + const a = rr(0, TWO_PI), d = Math.sqrt(random()); + const x = cx + Math.cos(a) * rx * d, y = cy + Math.sin(a) * ry * d, r = size * rr(0.6, 1.4); + batch.push({ x, y, r, color: pickOne(cols), rot: rot + rr(-0.7, 0.7), op: Math.round(rr(170, 235) - S.water * 40) }); + if (batch.length === 5 || i === n - 1) { + const b = batch; batch = []; + const bb = bboxOf(b.map((lf) => [lf.x, lf.y]), size * 2.5 + 8); + items.push(D(() => { for (const lf of b) { washStyle(lf.color, lf.op); brush.polygon(jitterEllipse(lf.x, lf.y, lf.r * 1.7, lf.r * 0.7, 8, 0.12, lf.rot)); } }, bb, raxis(), rdir(), 200, 40)); + } + } + return items; + } + function dFlower(type, x, y, s, F) { + const r = (type === 'lily' ? 11 * s : s * 1.3) * 1.6 + 10; + const bb = [Math.max(0, x - r), Math.max(0, y - r), Math.min(W, x + r), Math.min(H, y + r)].map(Math.round); + const dur = type === 'blossom' ? 260 : type === 'lily' ? 380 : 420; + return D(() => drawFlower(type, x, y, s, F), bb, raxis(), rdir(), dur, 90); + } + function dPad(x, y, r, G) { + const bb = [Math.max(0, x - r * 1.8 - 8), Math.max(0, y - r * 1.2 - 8), Math.min(W, x + r * 1.8 + 8), Math.min(H, y + r * 1.3 + 8)].map(Math.round); + return D(() => drawPad(x, y, r, G), bb, 'x', rdir(), 240, 50); + } + function dFlick(x, y, len, a, color, weight) { + const bb = bboxOf([[x - Math.cos(a) * len / 2, y - Math.sin(a) * len / 2], [x + Math.cos(a) * len / 2, y + Math.sin(a) * len / 2]], 10 + weight * 5); + const axis = Math.abs(Math.cos(a)) >= Math.abs(Math.sin(a)) ? 'x' : 'y'; + return D(() => flickDraw(x, y, len, a, color, weight), bb, axis, rdir(), 90, 25); + } + function dTouches(points, C, count, angleFn, sizeMul = 1) { + const items = []; + count = Math.round(count * (0.4 + 0.6 * S.detail)); + for (let i = 0; i < count; i++) { + const p = points.length ? pickOne(points) : [rr(0, W), rr(0, H), 10]; + const x = p[0] + rr(-p[2], p[2]), y = p[1] + rr(-p[2] * 0.6, p[2] * 0.6); + const color = random() < 0.85 ? pickOne(C.highlights) : pickOne(C.accents); + items.push(dFlick(x, y, rr(6, 16) * S.scale * sizeMul * (m / 600) * 3, angleFn(), color, rr(0.6, 1.1) * S.scale)); + } + return items; + } + + // A batch of pre-computed flat wash marks — grass, petal dapple, iris heads. + // A meadow is hundreds of these; drawing them eight to a stroke keeps the + // reveal readable instead of turning one scene into 300 strokes. + function dMarks(marks, dur = 220, gap = 40) { + const items = []; + for (let i = 0; i < marks.length; i += 8) { + const b = marks.slice(i, i + 8); + let pts = []; + for (const d of b) pts = pts.concat(d.pts); + items.push(D(() => { for (const d of b) { washStyle(d.color, d.op); brush.polygon(d.pts); } }, bboxOf(pts, 10), raxis(), rdir(), dur, gap)); + } + return items; + } + + // ===================================================================== + // Scenes (proportions from the playground, scaled by canvas size) + // ===================================================================== + function buildGarden(C) { + const out = [], { water, density: dens, scale: sc, soft, detail: det, brushSize: bs } = S; + const F = flowerCols(C), G = foliageCols(C), washes = C.washes; + if (S.coverage > 0.02) out.push(dWash(washes[0], Math.round(S.coverage * 200))); + for (let i = 0; i < 3; i++) out.push(dBlob(rr(W * 0.2, W * 0.8), rr(H * 0.1, H * 0.5), W * rr(0.3, 0.5), H * rr(0.2, 0.35), washes[(i + 1) % washes.length], Math.round(190 - water * 40), 0.5 + water * 0.3, 0.5, rr(-0.5, 0.5), 0.2, 500)); + const nMass = 5 + Math.round(dens * 6); + for (let i = 0; i < nMass; i++) { + const y = H * rr(0.35, 0.95), x = rr(-W * 0.05, W * 1.05); + const rx = W * rr(0.12, 0.26) * (0.6 + y / H), ry = rx * rr(0.45, 0.8); + const color = random() < 0.5 ? G.mid : (random() < 0.5 ? G.deep : G.light); + out.push(dBlob(x, y, rx, ry, color, Math.round(200 - water * 30), 0.4 + water * 0.3, 0.6, rr(-0.4, 0.4), 0.2 + soft * 0.2, 380)); + } + out.push(...dLeaves(W * 0.5, H * 0.68, W * 0.55, H * 0.32, Math.round(24 + dens * 40), [G.deep, G.mid, G.light, F.light], m * 0.012 * sc, 0)); + // flowers planned first so stalks lead to them + const nFlower = Math.round(6 + dens * 16), flowers = []; + for (let i = 0; i < nFlower; i++) { + const y = H * (0.3 + 0.68 * Math.pow(random(), 0.8)), x = rr(W * 0.04, W * 0.96), depth = 0.55 + (y / H) * 0.7, r = random(); + const type = r < 0.5 ? 'peony' : r < 0.75 ? 'daisy' : 'blossom'; + const s = m * (type === 'peony' ? rr(0.055, 0.085) : type === 'daisy' ? rr(0.045, 0.065) : rr(0.03, 0.045)) * sc * depth * S.flower; + flowers.push({ x, y, s, type }); + } + flowers.sort((a, b) => a.y - b.y); + const paleF = { ...F, light: mixHex(F.light, '#ffffff', 0.35), mid: mixHex(F.mid, '#ffffff', 0.35) }; + // Distant scatter high in the frame: deliberately NOT scaled by S.flower. These are + // background texture, and growing them with the near blooms would flatten the depth. + for (let i = 0; i < Math.round((8 + dens * 12) * (0.4 + 0.6 * det)); i++) { + const x = rr(W * 0.03, W * 0.97), y = H * rr(0.12, 0.45), s = m * rr(0.012, 0.022) * sc * bs; + out.push(dFlower('blossom', x, y, s, paleF)); + } + for (const f of flowers) { + if (random() > 0.3 + 0.7 * det) continue; + const len = rr(H * 0.08, H * 0.22), sway = rr(-5, 5) * (m / 600) * 3; + const sc2 = random() < 0.5 ? G.mid : G.deep; + const stem = [[f.x, f.y + f.s * 0.3], [f.x + sway * 0.5, f.y + len * 0.5], [f.x + sway, f.y + len]]; + out.push(D(() => { brush.field('hand'); strokeStyle('marker', sc2, rr(2.4, 4.2) * bs); brush.spline(stem, 0.6); brush.noField(); }, bboxOf(stem, 10 * bs), 'y', 1, 100 + len * 1.5, 30)); + if (random() < 0.2 + 0.6 * det) { + const lx = f.x + rr(-f.s, f.s), ly = f.y + rr(f.s * 0.6, f.s * 2.2), lr = f.s * rr(0.6, 1.1) * bs, rot = rr(-1.2, 1.2), lc = random() < 0.5 ? G.mid : G.deep; + out.push(dBlob(lx, ly, lr * 1.6, lr * 0.55, lc, 230, 0.25, 0.5, rot, 0.1, 220)); + } + } + for (const f of flowers) out.push(dFlower(f.type, f.x, f.y, f.s, F)); + out.push(...dTouches(flowers.map((f) => [f.x, f.y - f.s * 0.4, f.s]), C, Math.round(S.touch * 18), () => rr(-0.3, 0.3), 0.7)); + return out; + } + + function buildDawn(C) { + const out = [], { water, density: dens, scale: sc, soft, detail: det, brushSize: bs } = S; + const F = flowerCols(C), G = foliageCols(C), washes = C.washes, highlights = C.highlights; + const sunX = W * 0.5, sunY = H * 0.34, horizon = H * 0.52; + if (S.coverage > 0.02) out.push(dWash(washes[0], Math.round(S.coverage * 200))); + out.push(dBand(-10, horizon + H * 0.05, washes[1], Math.round(200 - water * 40), m * 0.04)); + out.push(dBlob(W * 0.15, H * 0.2, W * 0.3, H * 0.28, washes[2], 180, 0.6, 0.6, 0.3)); + out.push(dBlob(W * 0.85, H * 0.22, W * 0.3, H * 0.28, washes[2], 180, 0.6, 0.6, -0.3)); + out.push(dBlob(sunX, sunY, W * 0.26, H * 0.2, highlights[1] || '#fff7e6', 170, 0.75, 0.5, 0, 0.2, 520)); + out.push(dBlob(sunX, sunY, W * 0.12, H * 0.09, highlights[0], 190, 0.7, 0.4, 0, 0.2, 360)); + out.push(dBand(horizon - H * 0.03, H * 0.8, washes[2], Math.round(205 - water * 40), m * 0.023)); + out.push(dBand(H * 0.72, H + 10, washes[3] || washes[2], Math.round(215 - water * 40), m * 0.023)); + out.push(dBlob(sunX, H * 0.72, W * 0.14, H * 0.24, highlights[1] || '#fff7e6', 140, 0.7, 0.5, 0, 0.2, 420)); + for (let i = 0; i < Math.round(4 + S.glaze * 12); i++) { + const y = rr(horizon, H), color = random() < 0.5 ? washes[0] : (random() < 0.5 ? washes[1] : washes[2]); + const x0 = rr(-5, W * 0.5), x1 = x0 + rr(W * 0.3, W * 0.9); + out.push(dGlaze(x0, y, x1, y + rr(-2, 2), color, rr(1.5, 3.5) * Math.sqrt(sc), random() < 0.3 ? 'waves' : 'hand')); + } + out.push(dBlob(W * 0.06, H * 0.62, W * 0.22, H * 0.36, G.mid, 190, 0.5, 0.6, 0.1)); + out.push(dBlob(W * 0.94, H * 0.6, W * 0.22, H * 0.38, G.mid, 190, 0.5, 0.6, -0.1)); + out.push(dBlob(W * 0.1, H * 0.85, W * 0.2, H * 0.2, G.deep, 180, 0.5, 0.6, 0)); + out.push(dBlob(W * 0.9, H * 0.85, W * 0.2, H * 0.2, G.deep, 180, 0.5, 0.6, 0)); + out.push(...dLeaves(W * 0.06, H * 0.62, W * 0.2, H * 0.3, Math.round(16 + dens * 24), [G.deep, G.mid, G.light], m * 0.011 * sc, 0.2)); + out.push(...dLeaves(W * 0.94, H * 0.6, W * 0.2, H * 0.3, Math.round(16 + dens * 24), [G.deep, G.mid, G.light], m * 0.011 * sc, -0.2)); + const nReed = Math.round((50 + dens * 110) * (0.35 + 0.65 * det)); + for (let i = 0; i < nReed; i++) { + const left = i % 2 === 0; + const edge = left ? rr(-3, W * 0.24) : rr(W * 0.76, W + 3); + const c = left ? edge / (W * 0.24) : (W - edge) / (W * 0.24); + const len = -H * rr(0.18, 0.55) * (1 - c * 0.5) * (0.8 + sc * 0.2); + const y0 = H + 4 - rr(0, H * 0.12), sway = (left ? -1 : 1) * rr(1.5, 7) * (m / 600) * 3; + const color = random() < 0.25 ? G.shade : (random() < 0.5 ? G.deep : (random() < 0.7 ? G.mid : G.light)); + out.push(dStrand(edge, y0, len, sway, color, rr(0.5, 1.1) * sc * (1.5 - 0.5 * det), random() < 0.6 ? 'rim' : 'flick')); + } + const rafts = [{ cx: W * 0.24, cy: H * 0.8, n: 4 }, { cx: W * 0.72, cy: H * 0.88, n: 5 }], lilies = []; + for (const rf of rafts) { + const pads = []; + for (let i = 0; i < rf.n + Math.round(dens * 2); i++) pads.push({ x: rf.cx + rr(-W * 0.1, W * 0.1), y: rf.cy + rr(-H * 0.035, H * 0.035), r: m * rr(0.03, 0.05) * sc }); + pads.sort((a, b) => a.y - b.y); + pads.forEach((p) => out.push(dPad(p.x, p.y, p.r, G))); + const byR = pads.slice().sort((a, b) => b.r - a.r); + for (let i = 0; i < 2; i++) { const p = byR[i]; const s = (p.r / (m * 0.045)) * 1.2 * sc * S.flower; lilies.push(dFlower('lily', p.x, p.y - p.r * 0.1, s, F)); } + } + out.push(...lilies); + const glintPts = []; + for (let i = 0; i < 10; i++) glintPts.push([sunX + randomGaussian(0, W * 0.08), rr(horizon + 4, H * 0.95), 6]); + out.push(...dTouches(glintPts, C, Math.round(S.touch * 20), () => rr(-0.06, 0.06))); + return out; + } + + function buildWillow(C) { + const out = [], { water, density: dens, scale: sc, soft, detail: det, brushSize: bs } = S; + const F = flowerCols(C), G = foliageCols(C), washes = C.washes, highlights = C.highlights, foliage = C.foliage; + const pathX = W * 0.5; + if (S.coverage > 0.02) out.push(dWash(washes[0], Math.round(S.coverage * 200))); + out.push(dBand(-10, H * 0.5, washes[2], Math.round(215 - water * 40), m * 0.027)); + out.push(dBand(H * 0.35, H * 0.78, washes[0], Math.round(220 - water * 40), m * 0.027)); + out.push(dBand(H * 0.68, H + 10, washes[3] || washes[1], Math.round(230 - water * 40), m * 0.027)); + out.push(dBlob(pathX, H * 0.62, W * 0.16, H * 0.42, highlights[1] || '#fff6d6', 150, 0.7, 0.6, 0, 0.15, 520)); + for (let i = 0; i < Math.round(4 + S.glaze * 10); i++) { + const y0 = rr(H * 0.3, H * 0.95), len = rr(H * 0.08, H * 0.22), x = pathX + randomGaussian(0, W * 0.05); + const color = i % 3 === 0 ? highlights[0] : mixHex(highlights[1] || '#fff6d6', washes[2], 0.4); + out.push(dGlaze(x, y0, x + rr(-2, 2), y0 + len, color, rr(2, 4), 'hand')); + } + const dark = G.shade, midG = G.mid, sunG = foliage[3] || mixHex(G.mid, highlights[0], 0.6); + out.push(dBlob(W * 0.12, H * 0.1, W * 0.36, H * 0.3, dark, 235, 0.35 + water * 0.3, 0.5, 0.3)); + out.push(dBlob(W * 0.9, H * 0.12, W * 0.34, H * 0.32, dark, 235, 0.35 + water * 0.3, 0.5, -0.3)); + out.push(dBand(-15, H * 0.09, dark, 225, m * 0.03)); + out.push(dBlob(W * 0.3, H * 0.14, W * 0.22, H * 0.14, midG, 200, 0.5, 0.6, 0.2)); + out.push(dBlob(W * 0.72, H * 0.16, W * 0.2, H * 0.13, midG, 200, 0.5, 0.6, -0.2)); + const leafCols = [G.shade, G.deep, G.mid, sunG]; + out.push(...dLeaves(W * 0.14, H * 0.16, W * 0.36, H * 0.2, Math.round(30 + dens * 40), leafCols, m * 0.012 * sc, 0.3)); + out.push(...dLeaves(W * 0.86, H * 0.18, W * 0.34, H * 0.2, Math.round(30 + dens * 40), leafCols, m * 0.012 * sc, -0.3)); + out.push(...dLeaves(W * 0.5, H * 0.05, W * 0.4, H * 0.08, Math.round(20 + dens * 30), [G.shade, G.deep, G.mid], m * 0.011 * sc, 0)); + const nStrand = Math.round((40 + dens * 110) * (0.35 + 0.65 * det)); + for (let i = 0; i < nStrand; i++) { + const x0 = rr(-3, W + 3), c = Math.abs(x0 - pathX) / (W * 0.5); + const y0 = H * 0.03 + Math.pow(c, 1.5) * H * 0.3 + rr(-5, 5); + const len = (H * rr(0.15, 0.5)) * (1 - 0.35 * (1 - c)) * (0.8 + sc * 0.2); + const backlit = c < 0.45 && random() < 0.7; + const color = backlit ? (random() < 0.5 ? sunG : highlights[0]) : (random() < 0.7 ? G.deep : G.mid); + out.push(dStrand(x0, y0, len, rr(-6, 6) * (m / 600) * 3, color, rr(0.7, 1.3) * sc * (1.5 - 0.5 * det), random() < 0.2 ? 'rim' : 'flick')); + } + const rafts = [ + { cx: W * 0.22, cy: H * 0.82, n: 5, r: [0.035, 0.055], flowers: 2 }, + { cx: W * 0.5, cy: H * 0.6, n: 4, r: [0.02, 0.032], flowers: 1 }, + { cx: W * 0.78, cy: H * 0.86, n: 5, r: [0.035, 0.05], flowers: 2 }, + ]; + const lilies = []; + for (const rf of rafts) { + const pads = []; + for (let i = 0; i < rf.n + Math.round(dens * 3); i++) pads.push({ x: rf.cx + rr(-W * 0.11, W * 0.11), y: rf.cy + rr(-H * 0.04, H * 0.04), r: m * rr(rf.r[0], rf.r[1]) * sc }); + pads.sort((a, b) => a.y - b.y); + pads.forEach((p) => out.push(dPad(p.x, p.y, p.r, G))); + const byR = pads.slice().sort((a, b) => b.r - a.r); + for (let i = 0; i < rf.flowers; i++) { const p = byR[i]; const s = (p.r / (m * 0.045)) * 0.9 * sc * S.flower; lilies.push(dFlower('lily', p.x + rr(-p.r * 0.2, p.r * 0.2), p.y - p.r * 0.12, s, F)); } + } + out.push(...lilies); + for (let i = 0; i < 3 + Math.round(dens * 4); i++) out.push(dFlower('blossom', rr(W * 0.02, W * 0.2), rr(H * 0.42, H * 0.72), m * rr(0.02, 0.035) * sc * S.flower, F)); + const sparklePts = []; + for (let i = 0; i < 12; i++) sparklePts.push([pathX + randomGaussian(0, W * 0.06), rr(H * 0.5, H * 0.95), 4]); + out.push(...dTouches(sparklePts, C, Math.round(S.touch * 24), () => rr(-0.08, 0.08))); + return out; + } + + function buildWisteria(C) { + const out = [], { water, density: dens, scale: sc, soft, detail: det, brushSize: bs } = S; + const F = flowerCols(C), G = foliageCols(C), washes = C.washes, accents = C.accents, highlights = C.highlights; + const lav = [accents[0], accents[1] || accents[0], accents[4] || accents[1] || accents[0]]; + if (S.coverage > 0.02) out.push(dWash(washes[0], Math.round(S.coverage * 200))); + out.push(dBand(-10, H * 0.45, washes[2], Math.round(200 - water * 40), m * 0.037)); + out.push(dBand(H * 0.3, H * 0.75, washes[0], Math.round(215 - water * 40), m * 0.037)); + out.push(dBand(H * 0.62, H + 10, washes[3] || washes[1], Math.round(215 - water * 40), m * 0.037)); + out.push(dBlob(W * 0.5, H * 0.5, W * 0.3, H * 0.14, highlights[0], 150, 0.7, 0.5, 0, 0.2, 420)); + // dappled meadow in small batches + const nDots = Math.round((80 + dens * 160) * (0.3 + 0.7 * det)); + const dotCols = [...washes, accents[2] || accents[0], accents[3] || highlights[0], highlights[0], G.light]; + let batch = []; + for (let i = 0; i < nDots; i++) { + const y = H * (0.25 + 0.75 * Math.pow(random(), 0.7)), x = rr(-2, W + 2); + const r = m * rr(0.005, 0.013) * sc * (0.6 + y / H) * bs * (1.5 - 0.5 * det); + const pts = jitterEllipse(x, y, r * rr(1.6, 2.6), r, 8, 0.15 + soft * 0.2, rr(-0.25, 0.25)); + batch.push({ color: pickOne(dotCols), pts, op: Math.round(rr(130, 210) - water * 30) }); + if (batch.length === 10 || i === nDots - 1) { + const b = batch; batch = []; + out.push(D(() => { for (const d of b) { washStyle(d.color, d.op); brush.polygon(d.pts); } }, bboxOf(b.flatMap((d) => d.pts), 8), 'x', rdir(), 220, 40)); + } + } + out.push(dBand(-15, H * 0.06, G.deep, 200, m * 0.023)); + const nRac = 5 + Math.round(dens * 6); + for (let i = 0; i < nRac; i++) { + const x = ((i + rr(0.2, 0.8)) / nRac) * W; + const y0 = rr(-4, H * 0.04), L = H * rr(0.14, 0.34) * (0.8 + sc * 0.2), w = m * rr(0.04, 0.065) * sc; + const parts = [[], [], []], nd = Math.round(L / ((4 + (1 - det) * 6) * (m / 600))); + for (let k = 0; k < nd; k++) { + const t = k / nd, half = (w * (1 - t * 0.75)) / 2; + const dx = randomGaussian(0, half / 1.6), dy = y0 + t * L + rr(-1, 1); + const r = m * rr(0.007, 0.012) * sc * (1 - t * 0.3) * bs * (1 + (1 - det) * 0.8); + const color = random() < 0.15 ? lav[2] : (random() < 0.5 ? lav[0] : lav[1]); + const pale = Math.abs(dx) > half * 0.6 && random() < 0.5; + parts[Math.min(2, Math.floor(t * 3))].push({ x: x + dx, y: dy, r, color: pale ? mixHex(color, '#ffffff', 0.35) : color, rot: rr(-0.5, 0.5) }); + } + const leaves = []; + for (let k = 0; k < 3; k++) leaves.push({ x: x + rr(-w, w), y: y0 + rr(0, L * 0.12), r: m * 0.014 * sc, rot: rr(-1, 1), color: random() < 0.5 ? G.mid : G.deep }); + out.push(D(() => { for (const lf of leaves) { washStyle(lf.color, 230); brush.polygon(jitterEllipse(lf.x, lf.y, lf.r * 1.8, lf.r * 0.7, 8, 0.1, lf.rot)); } }, bboxOf(leaves.map((l) => [l.x, l.y]), m * 0.05), 'x', rdir(), 140, 30)); + for (const part of parts) { + if (!part.length) continue; + out.push(D(() => { for (const d of part) { washStyle(d.color, 235); brush.polygon(jitterEllipse(d.x, d.y, d.r * 1.3, d.r, 8, 0.15, d.rot)); } }, bboxOf(part.map((d) => [d.x, d.y]), w + 8), 'y', 1, 220, 30)); + } + } + const blossomPts = [], fl = []; + for (let i = 0; i < 6 + Math.round(dens * 10); i++) { + const y = H * rr(0.55, 0.97), x = rr(W * 0.03, W * 0.97), s = m * rr(0.018, 0.032) * sc * (0.6 + y / H) * S.flower; + blossomPts.push([x, y, s]); + fl.push({ y, d: dFlower(random() < 0.35 ? 'daisy' : 'blossom', x, y, s, F) }); + } + fl.sort((a, b) => a.y - b.y); + out.push(...fl.map((f) => f.d)); + out.push(...dTouches(blossomPts, C, Math.round(S.touch * 16), () => rr(-0.2, 0.2))); + return out; + } + + // Poppy field. Deliberately the wettest and largest of the scenes: the + // playground preset already asked for water 0.7 against the 0.55 its siblings + // share, and the drift only reads as poppies when the blooms are big enough to + // carry a wet edge. Both are local to this scene rather than dials, so the + // other six paintings are untouched. + function buildPoppies(C) { + const out = [], { density: dens, scale: sc, soft, detail: det, brushSize: bs } = S; + const { washes, accents, highlights } = C; + const F = flowerCols(C), G = foliageCols(C); + const horizon = H * 0.38, wet = 0.72, pop = 1.35; + + // sky with two pale clouds, then the meadow in two warm-green bands + if (S.coverage > 0.02) out.push(dWash(washes[0], Math.round(S.coverage * 200))); + out.push(dBand(-20, horizon + H * 0.04, washes[1], Math.round(180 - wet * 40), m * 0.033)); + out.push(dBlob(W * 0.28, H * 0.14, W * 0.26, H * 0.09, highlights[1] || '#fff6e6', 160, 0.8, 0.5, 0.1, 0.2, 520)); + out.push(dBlob(W * 0.74, H * 0.22, W * 0.2, H * 0.07, highlights[1] || '#fff6e6', 150, 0.8, 0.5, -0.1, 0.2, 460)); + out.push(dBand(horizon - H * 0.02, H * 0.7, washes[2], Math.round(190 - wet * 40), m * 0.027)); + out.push(dBand(H * 0.6, H + 20, washes[3] || washes[2], Math.round(200 - wet * 40), m * 0.027)); + + // a dark tree line on the horizon, then grass that grows toward the front + out.push(dBand(horizon - H * 0.03, horizon + H * 0.02, G.deep, Math.round(200 - wet * 30), m * 0.01)); + const nTree = 4 + Math.round(dens * 2); + for (let i = 0; i < nTree; i++) { + const x = ((i + rr(0.2, 0.8)) / nTree) * W, rx = W * rr(0.05, 0.11), ry = H * rr(0.04, 0.09); + const color = random() < 0.6 ? G.shade : G.deep; + out.push(dBlob(x, horizon - ry * 0.6, rx, ry, color, 215, 0.35 + wet * 0.3, 0.5, rr(-0.2, 0.2), 0.18, 340)); + } + const grass = [], grassCols = [G.light, G.mid, washes[2], highlights[0], G.mid]; + for (let i = 0; i < Math.round((70 + dens * 140) * (0.3 + 0.7 * det)); i++) { + const y = horizon + (H - horizon) * Math.pow(random(), 0.75), x = rr(-5, W + 5); + const r = m * rr(0.003, 0.007) * sc * (0.5 + y / H) * bs * (1.5 - 0.5 * det); + grass.push({ color: pickOne(grassCols), pts: jitterEllipse(x, y, r * rr(2.5, 4.5), r * 0.55, 8, 0.15 + soft * 0.2, rr(-0.15, 0.15)), op: Math.round(rr(110, 190) - wet * 30) }); + } + out.push(...dMarks(grass)); + + // the poppy drift: a diagonal band from upper left to lower right, bigger as + // it comes forward. Small ones are a wet halo under a flat dab; the big ones + // are bleeding fills with a shade dot at the centre. + const reds = [accents[0], accents[1] || accents[0], accents[2] || accents[0]]; + const pops = [], blooms = []; + for (let i = 0; i < Math.round((60 + dens * 120) * (0.3 + 0.7 * det)); i++) { + const y = H * (0.4 + 0.6 * Math.pow(random(), 0.6)); + const depth = (y - horizon) / (H - horizon); // 0 far, 1 near + const cx = W * (0.15 + depth * 0.6); // the band walks right as it comes forward + const x = random() < 0.3 ? rr(-5, W + 5) : cx + randomGaussian(0, W * 0.16); + const r = m * rr(0.006, 0.012) * sc * (0.5 + depth * 1.4) * bs * (1.3 - 0.3 * det) * pop; + const color = pickOne(reds), rot = rr(-0.5, 0.5); + if (r > m * 0.018 && random() < 0.6) blooms.push({ x, y, r, color, rot }); + else { + pops.push({ color: mixHex(color, '#ffffff', 0.3), pts: jitterEllipse(x, y, r * 2.1, r * 1.7, 9, 0.22, rot), op: Math.round(120 - wet * 40) }); + pops.push({ color, pts: jitterEllipse(x, y, r * rr(1.1, 1.5), r, 9, 0.18, rot), op: Math.round(rr(160, 210) - wet * 40) }); + } + } + out.push(...dMarks(pops)); + blooms.sort((a, b) => a.y - b.y); + for (const b of blooms) { + const pad = b.r * 2.4 + 16; + const bb = [Math.max(0, b.x - pad), Math.max(0, b.y - pad), Math.min(W, b.x + pad), Math.min(H, b.y + pad)].map(Math.round); + out.push(D(() => { + softBlobDraw(b.x, b.y, b.r * 1.3, b.r, b.color, 195, 0.55, 0.65, b.rot, 0.22); + washStyle(F.shade, 200); + brush.polygon(jitterEllipse(b.x, b.y + b.r * 0.1, b.r * 0.3, b.r * 0.25, 8, 0.15)); + }, bb, raxis(), rdir(), 300, 60)); + } + + // a few readable poppies in front, grass stalks, light on the horizon + const redF = { ...F, light: vivid(accents[0], S.vivid), mid: vivid(accents[1] || accents[0], S.vivid), pale: mixHex(accents[0], '#ffffff', 0.5), center: F.shade }; + for (let i = 0; i < 5 + Math.round(dens * 4); i++) { + const y = H * rr(0.72, 0.97), x = rr(W * 0.05, W * 0.95), s = m * rr(0.03, 0.05) * sc * pop; + out.push(dFlower('blossom', x, y, s, redF)); + } + for (let i = 0; i < Math.round((10 + dens * 14) * (0.4 + 0.6 * det)); i++) { + const x = rr(0, W), y0 = H + 5 - rr(0, H * 0.1), len = -H * rr(0.06, 0.2) * sc; + out.push(dStrand(x, y0, len, rr(-8, 8) * (m / 600) * 3, random() < 0.5 ? G.deep : G.mid, rr(0.5, 0.9) * sc, 'rim')); + } + const glowPts = []; + for (let i = 0; i < 10; i++) glowPts.push([rr(0, W), horizon + rr(-H * 0.02, H * 0.05), 14]); + out.push(...dTouches(glowPts, C, Math.round(S.touch * 18), () => rr(-0.1, 0.1))); + return out; + } + + // Iris path at Giverny. Everything is arranged around a path that narrows to a + // point near the top, so the blades have to keep off it or the perspective goes. + function buildIrises(C) { + const out = [], { water, density: dens, scale: sc, detail: det, brushSize: bs } = S; + const { washes, accents, highlights } = C; + const F = flowerCols(C), G = foliageCols(C); + const topY = H * 0.28; + const pathHalf = (y) => { const t = clamp01((H - y) / (H - topY)); return W * (0.2 - 0.15 * t); }; + const pathX = (y) => W * 0.5 + (1 - clamp01((H - y) / (H - topY))) * W * 0.02; + const irisCols = [accents[0], accents[1] || accents[0], accents[2] || accents[0], accents[4] || accents[1] || accents[0]]; + const paleIris = accents[3] || mixHex(accents[0], '#ffffff', 0.5); + + // sky, the pale path, a warm core, meadow either side + if (S.coverage > 0.02) out.push(dWash(washes[0], Math.round(S.coverage * 200))); + out.push(dBand(-20, topY + H * 0.06, washes[2], Math.round(195 - water * 40), m * 0.033)); + out.push(dBand(topY - H * 0.02, H + 20, washes[3] || washes[1], Math.round(200 - water * 40), m * 0.03)); + const trap = []; + for (let i = 0; i <= 6; i++) { const y = H + 20 - (H + 20 - topY) * (i / 6); trap.push([pathX(y) - pathHalf(y) * rr(0.9, 1.1), y]); } + for (let i = 6; i >= 0; i--) { const y = H + 20 - (H + 20 - topY) * (i / 6); trap.push([pathX(y) + pathHalf(y) * rr(0.9, 1.1), y]); } + out.push(D(() => { fillStyle(washes[1], Math.round(220 - water * 40), 0.3 + water * 0.4, 0.4 + water * 0.4, 0.3); brush.polygon(trap); }, bboxOf(trap, m * 0.2), 'y', -1, 620, 100)); + out.push(dBlob(W * 0.5, H * 0.8, W * 0.12, H * 0.3, washes[0], 170, 0.6, 0.5, 0, 0.15, 480)); + out.push(dBlob(W * 0.5, topY + H * 0.04, W * 0.14, H * 0.06, highlights[1] || '#fff6e6', 160, 0.7, 0.5, 0, 0.2, 420)); + + // the beds: soft green masses, then rising blades that keep off the path + for (const side of [-1, 1]) { + out.push(dBlob(W * (0.5 + side * 0.33), H * 0.6, W * 0.2, H * 0.22, G.mid, 195, 0.5, 0.6, side * 0.15, 0.12, 400)); + out.push(dBlob(W * (0.5 + side * 0.36), H * 0.86, W * 0.2, H * 0.16, G.deep, 190, 0.5, 0.6, 0, 0.12, 400)); + out.push(dBlob(W * (0.5 + side * 0.24), H * 0.4, W * 0.16, H * 0.1, G.light, 170, 0.6, 0.6, side * 0.3, 0.12, 340)); + } + const tops = []; + for (let i = 0; i < Math.round((50 + dens * 110) * (0.35 + 0.65 * det)); i++) { + const side = i % 2 === 0 ? -1 : 1; + const y0 = H * (0.34 + 0.7 * Math.pow(random(), 0.8)); + const near = (y0 - topY) / (H - topY); // 0 far, 1 near + const x0 = pathX(y0) + side * (pathHalf(y0) + rr(4, W * 0.36 * (0.4 + 0.6 * near))); + const len = -H * rr(0.08, 0.26) * (0.3 + near) * (0.8 + sc * 0.2); + const sway = side * rr(-6, 14) * (m / 600) * 3; + const color = random() < 0.2 ? G.shade : (random() < 0.5 ? G.deep : (random() < 0.7 ? G.mid : G.light)); + out.push(dStrand(x0, y0, len, sway, color, rr(0.6, 1.1) * sc * (1.5 - 0.5 * det), random() < 0.6 ? 'rim' : 'flick')); + tops.push({ x: x0 + sway, y: y0 + len, near }); + } + + // iris heads on a subset of the blades: a tall standard over a wider fall + const heads = []; + const chosen = tops.slice().sort(() => random() - 0.5).slice(0, Math.round(tops.length * (0.45 + 0.2 * dens))); + for (const h of chosen) { + const r = m * rr(0.009, 0.015) * sc * (0.5 + h.near) * bs * (1.3 - 0.3 * det); + const pale = random() < 0.2; + const cs = pale ? paleIris : pickOne(irisCols), cf = pale ? mixHex(paleIris, irisCols[1], 0.4) : irisCols[2]; + heads.push({ color: vivid(cf, S.vivid), pts: jitterEllipse(h.x, h.y + r * 0.6, r * 1.5, r * 0.8, 8, 0.2, rr(-0.3, 0.3)), op: Math.round(225 - water * 30) }); + heads.push({ color: vivid(cs, S.vivid), pts: jitterEllipse(h.x, h.y - r * 0.4, r * 0.8, r * 1.4, 8, 0.18, rr(-0.3, 0.3)), op: Math.round(235 - water * 30) }); + if (det > 0.35 && r > m * 0.011) heads.push({ color: highlights[0], pts: jitterEllipse(h.x, h.y + r * 0.4, r * 0.25, r * 0.2, 6, 0.2), op: 235 }); + } + heads.sort((a, b) => a.pts[0][1] - b.pts[0][1]); + out.push(...dMarks(heads)); + + // a few large irises in the foreground beds, then light falling down the path + const purpleF = { ...F, light: vivid(irisCols[3], S.vivid), mid: vivid(irisCols[0], S.vivid), deep: vivid(irisCols[2], S.vivid), pale: paleIris }; + for (let i = 0; i < 6 + Math.round(dens * 4); i++) { + const side = i % 2 === 0 ? -1 : 1, y = H * rr(0.68, 0.96); + const x = pathX(y) + side * (pathHalf(y) + rr(W * 0.02, W * 0.26)); + const s = m * rr(0.026, 0.04) * sc, pad = s * 2.6 + 14; + const bb = [Math.max(0, x - pad), Math.max(0, y - pad), Math.min(W, x + pad), Math.min(H, y + pad)].map(Math.round); + out.push(D(() => { + washStyle(purpleF.deep, 230); + brush.polygon(jitterEllipse(x, y + s * 0.5, s * 1.1, s * 0.55, 10, 0.18)); + drawFlower('blossom', x, y - s * 0.2, s * 1.3, purpleF); + }, bb, raxis(), rdir(), 320, 80)); + } + const pathPts = []; + for (let i = 0; i < 10; i++) { const y = rr(topY + 10, H * 0.95); pathPts.push([pathX(y) + rr(-pathHalf(y), pathHalf(y)) * 0.8, y, 10]); } + out.push(...dTouches(pathPts, C, Math.round(S.touch * 18), () => HALF_PI + rr(-0.2, 0.2))); + return out; + } + + // Orchard in blossom. The trees are planned before anything is drawn, so the + // trunks, the canopies and the light on top all agree about where they stand. + function buildOrchard(C) { + const out = [], { water, density: dens, scale: sc, soft, detail: det, brushSize: bs } = S; + const { washes, accents, highlights } = C; + const F = flowerCols(C), G = foliageCols(C); + const horizon = H * 0.45; + + // sky with a glow upper right, then the meadow + if (S.coverage > 0.02) out.push(dWash(washes[0], Math.round(S.coverage * 200))); + out.push(dBand(-20, horizon + H * 0.03, washes[1], Math.round(195 - water * 40), m * 0.037)); + out.push(dBlob(W * 0.78, H * 0.16, W * 0.3, H * 0.18, highlights[1] || '#fff8ee', 150, 0.75, 0.5, 0, 0.2, 520)); + out.push(dBand(horizon - H * 0.02, H * 0.75, washes[2], Math.round(210 - water * 40), m * 0.027)); + out.push(dBand(H * 0.66, H + 20, washes[3] || washes[2], Math.round(220 - water * 40), m * 0.027)); + + const nTree = 3 + Math.round(dens * 1.5), trees = []; + for (let i = 0; i < nTree; i++) { + const x = W * (0.05 + 0.9 * (i + rr(0.25, 0.75)) / nTree), base = H * rr(0.72, 0.9); + const h = H * rr(0.3, 0.45) * sc, r = m * rr(0.12, 0.18) * sc * (0.7 + (base / H) * 0.4); + trees.push({ x, base, h, r, cy: base - h * 0.85 }); + } + trees.sort((a, b) => a.base - b.base); + + // trunks and branches, then grass + for (const t of trees) { + const lean = rr(-12, 12) * (m / 600) * 3; + const trunk = [[t.x, t.base], [t.x + lean * 0.5, t.base - t.h * 0.5], [t.x + lean, t.base - t.h]]; + const tw = rr(2.2, 3.2) * bs * sc; + out.push(D(() => { strokeStyle('rim', G.shade, tw); brush.spline(trunk, 0.4); }, bboxOf(trunk, 12 * bs), 'y', -1, 260, 40)); + for (let k = 0; k < 2 + Math.round(det * 2); k++) { + const y0 = t.base - t.h * rr(0.55, 0.85), x0 = t.x + lean * ((t.base - y0) / t.h); + const a = rr(-2.4, -0.7), len = t.r * rr(0.5, 0.9); + const br = [[x0, y0], [x0 + Math.cos(a) * len * 0.5, y0 + Math.sin(a) * len * 0.5 - 4], [x0 + Math.cos(a) * len, y0 + Math.sin(a) * len]]; + const bw = rr(1, 1.6) * bs * sc; + out.push(D(() => { strokeStyle('rim', G.shade, bw); brush.spline(br, 0.4); }, bboxOf(br, 10 * bs), raxis(), rdir(), 160, 30)); + } + } + const grass = [], grassCols = [G.light, G.mid, washes[2], highlights[0]]; + for (let i = 0; i < Math.round((50 + dens * 100) * (0.3 + 0.7 * det)); i++) { + const y = horizon + (H - horizon) * Math.pow(random(), 0.75), x = rr(-5, W + 5); + const r = m * rr(0.003, 0.007) * sc * (0.5 + y / H) * bs * (1.5 - 0.5 * det); + grass.push({ color: pickOne(grassCols), pts: jitterEllipse(x, y, r * rr(2.5, 4.5), r * 0.55, 8, 0.15 + soft * 0.2, rr(-0.15, 0.15)), op: Math.round(rr(110, 190) - water * 30) }); + } + out.push(...dMarks(grass)); + + // blossom clouds: a soft pink mass per tree, then a dapple of petals and leaves + const petalCols = [accents[0], accents[1] || accents[0], accents[2] || accents[0], accents[3] || '#fff1f4', accents[4] || accents[0]]; + for (const t of trees) { + out.push(dBlob(t.x, t.cy, t.r * 1.1, t.r * 0.8, accents[0], 170, 0.65, 0.5, rr(-0.3, 0.3), 0.25, 460)); + out.push(dBlob(t.x + rr(-t.r * 0.4, t.r * 0.4), t.cy - t.r * 0.3, t.r * 0.7, t.r * 0.5, accents[3] || '#fff1f4', 160, 0.7, 0.5, rr(-0.3, 0.3), 0.25, 400)); + const dots = []; + for (let i = 0; i < Math.round((40 + dens * 50) * (0.3 + 0.7 * det)); i++) { + const a = rr(0, TWO_PI), d = Math.sqrt(random()); + const x = t.x + Math.cos(a) * t.r * 1.05 * d, y = t.cy + Math.sin(a) * t.r * 0.8 * d; + const r0 = m * rr(0.005, 0.011) * sc * bs * (1.4 - 0.4 * det); + const low = y > t.cy + t.r * 0.3; + const color = random() < 0.25 ? G.light : (low && random() < 0.3 ? G.deep : pickOne(petalCols)); + dots.push({ color, pts: jitterEllipse(x, y, r0, r0 * rr(0.8, 1), 8, 0.15), op: Math.round(rr(170, 235) - water * 30) }); + } + out.push(...dMarks(dots)); + } + + // readable blossoms in the nearest canopy, fallen petals, light on the tops + const near = trees[trees.length - 1]; + for (let i = 0; i < 6 + Math.round(dens * 4); i++) { + const a = rr(0, TWO_PI), d = Math.sqrt(random()); + const x = near.x + Math.cos(a) * near.r * 0.9 * d, y = near.cy + Math.sin(a) * near.r * 0.7 * d; + out.push(dFlower('blossom', x, y, m * rr(0.02, 0.032) * sc, F)); + } + const fallen = []; + for (let i = 0; i < Math.round(20 + dens * 20); i++) { + const x = rr(0, W), y = rr(H * 0.72, H), r = m * rr(0.003, 0.006) * sc * bs; + fallen.push({ color: pickOne(petalCols), pts: jitterEllipse(x, y, r * 1.6, r, 6, 0.2), op: 200 }); + } + out.push(...dMarks(fallen)); + out.push(...dTouches(trees.map((t) => [t.x, t.cy - t.r * 0.6, t.r * 0.6]), C, Math.round(S.touch * 16), () => rr(-0.3, 0.3))); + return out; + } + + // ===================================================================== + // Second set: koi, roses, oranges, sail. Same rules as the flowers above: + // a flat wash body under a bleeding fill for solid colour, never an + // outline, never brush.circle at a small radius. + // + // Where the playground tuned one of these scenes away from the shared + // dials (wetter, more glazes, a paler rose), the builder keeps that value + // as a local constant, as buildPoppies does, so no other painting moves. + // ===================================================================== + function ringPts(cx, cy, r, a0, a1, n = 10) { + const pts = []; + for (let i = 0; i <= n; i++) { const a = a0 + (a1 - a0) * (i / n); pts.push([cx + Math.cos(a) * r, cy + Math.sin(a) * r]); } + return pts; + } + // a pointed ellipse: round at the base (-rx along rot), tapering to a tip at +rx. Petals, leaves, buds. + function petalPts(cx, cy, rx, ry, rot, n = 14, jit = 0.05) { + const pts = [], cr = Math.cos(rot), sr = Math.sin(rot); + for (let i = 0; i < n; i++) { + const a = (i / n) * TWO_PI, c = Math.cos(a), k = 1 + rr(-jit, jit); + const px = rx * c * k, py = ry * Math.sin(a) * Math.sqrt(1 - 0.9 * c) / 1.1 * k; + pts.push([cx + px * cr - py * sr, cy + px * sr + py * cr]); + } + return pts; + } + // a fish silhouette: blunt head toward `angle`, fullest a third of the way back, a waist, a forked tail + function taperedBody(x, y, len, wid, angle, jit = 0.06) { + const ca = Math.cos(angle), sa = Math.sin(angle); + const P = (t, v) => { const u = len / 2 - t * len; return [x + u * ca - v * sa, y + u * sa + v * ca]; }; + const T = [0, 0.1, 0.3, 0.5, 0.7, 0.82, 0.92, 1], HW = [0.3, 0.72, 1, 0.9, 0.62, 0.3, 0.55, 0.85]; + const top = [], bottom = []; + for (let i = 0; i < T.length; i++) { + const h = HW[i] * (wid / 2) * (1 + rr(-jit, jit)); + top.push(P(T[i], -h)); bottom.push(P(T[i], h)); + } + return top.concat([P(0.88, 0)], bottom.reverse()); + } + function drawKoi(x, y, len, angle, K) { + const ca = Math.cos(angle), sa = Math.sin(angle); + const off = (u, v) => [x + u * ca - v * sa, y + u * sa + v * ca]; + washStyle(K.body, 250); brush.polygon(taperedBody(x, y, len, len * 0.3, angle, 0.04)); + bloomFill(K.body, 235, 0.22); brush.polygon(taperedBody(x, y, len * 1.04, len * 0.33, angle, 0.08)); + // a deeper saddle along the back, a paler belly, cream flecks, an eye + const [bx, by] = off(len * 0.08, -len * 0.06); + washStyle(K.deep, 200); brush.polygon(jitterEllipse(bx, by, len * 0.28, len * 0.07, 10, 0.15, angle)); + const [px, py] = off(len * 0.05, len * 0.08); + washStyle(K.pale, 170); brush.polygon(jitterEllipse(px, py, len * 0.26, len * 0.05, 10, 0.15, angle)); + for (let i = 0; i < 3; i++) { const [fx, fy] = off(rr(-len * 0.2, len * 0.35), rr(-len * 0.08, len * 0.08)); centerDot(fx, fy, len * rr(0.02, 0.04), K.fleck, 220); } + const [ex, ey] = off(len * 0.4, -len * 0.04); centerDot(ex, ey, len * 0.018, K.eye, 230); + } + // a rose: four nested scalloped rings, the heart drifting off centre so it hints at the spiral, + // and a few pale petal rims between the rings + function drawRose(x, y, s, F) { + const rings = [ + { r: 1.0, lobes: 9, inner: 0.8, col: F.light }, + { r: 0.74, lobes: 7, inner: 0.74, col: mixHex(F.light, F.mid, 0.5) }, + { r: 0.5, lobes: 6, inner: 0.7, col: F.mid }, + { r: 0.3, lobes: 5, inner: 0.66, col: F.deep }, + ]; + const dx = rr(-0.08, 0.08) * s, dy = rr(-0.06, 0.06) * s; + // the outer ring gets a wider solid body so the bloom reads as paint, not a stain + rings.forEach((R, i) => bloomShape(x + dx * i, y + dy * i, s * R.r, R.lobes, R.inner, R.col, 0.26 - i * 0.03, 0.8 + i * 0.02)); + if (S.detail > 0.3) { + for (let i = 0; i < 3; i++) { + const a = rr(0, TWO_PI), d = s * rr(0.5, 0.8); + washStyle(F.pale, 120); brush.polygon(jitterEllipse(x + Math.cos(a) * d, y + Math.sin(a) * d, s * 0.22, s * 0.045, 8, 0.15, a + HALF_PI)); + } + } + centerDot(x + dx * 3, y + dy * 3, s * 0.1, mixHex(F.deep, F.shade, 0.4), 220); + } + // an orange: a solid disc, a shade crescent lower right, light upper left, one glint + function drawOrange(x, y, r, O) { + // mostly a solid wash disc: the bleed is kept low so the fruit has a rind, not a halo + const rot = rr(0, TWO_PI); + washStyle(O.mid, 252); brush.polygon(jitterEllipse(x, y, r * 0.94, r * 0.9, 14, 0.05, rot)); + fillStyle(O.mid, 235, 0.12 + S.water * 0.1, 0.4, 0.3); brush.polygon(jitterEllipse(x, y, r, r * 0.96, 14, 0.05, rot)); + washStyle(O.deep, 120); brush.polygon(jitterEllipse(x + r * 0.16, y + r * 0.2, r * 0.7, r * 0.6, 12, 0.08, 0.6)); + washStyle(O.light, 140); brush.polygon(jitterEllipse(x - r * 0.22, y - r * 0.26, r * 0.4, r * 0.3, 10, 0.1, 0.7)); + centerDot(x - r * 0.36, y - r * 0.4, r * 0.1, O.glint, 150); + } + + // a reveal box of half-size r around a point, clipped to the canvas + function boxAround(x, y, r) { return [Math.max(0, x - r), Math.max(0, y - r), Math.min(W, x + r), Math.min(H, y + r)].map(Math.round); } + // pointed leaf dabs inside an ellipse, batched through dMarks. rotBias(x, y) gives each leaf a direction to fan along. + function dLeafDabs(cx, cy, rx, ry, n, cols, size, rotBias = null, op = [170, 235]) { + const marks = []; + n = Math.max(2, Math.round(n * (0.3 + 0.7 * S.detail))); + size *= S.brushSize * (1.4 - 0.4 * S.detail); + for (let i = 0; i < n; i++) { + const a = rr(0, TWO_PI), d = Math.sqrt(random()); + const x = cx + Math.cos(a) * rx * d, y = cy + Math.sin(a) * ry * d, r = size * rr(0.6, 1.4); + const rot = rotBias ? rotBias(x, y) + rr(-0.5, 0.5) : rr(0, TWO_PI); + marks.push({ color: pickOne(cols), pts: petalPts(x, y, r * 2, r * 0.7, rot, 10, 0.1), op: Math.round(rr(op[0], op[1]) - S.water * 40) }); + } + return dMarks(marks); + } + + // Koi in swirling water. Darker, wetter and more heavily glazed than the + // shared dials; everything turns around one bright eye upper right. + function buildKoi(C) { + const out = [], { density: dens, scale: sc, detail: det, brushSize: bs } = S; + const water = 0.6, coverage = 0.9, glaze = 0.7, touch = 0.3; + const { washes, foliage, accents, highlights } = C; + const cx0 = W * 0.68, cy0 = H * 0.34; + const K = { body: vivid(accents[0], S.vivid), deep: accents[2] || accents[0], pale: accents[3] || mixHex(accents[1] || accents[0], '#ffffff', 0.4), fleck: highlights[0], eye: foliage[2] }; + + // the water: a lighter zone around the swirl, dark zones at the corners, a bright eye + out.push(dWash(washes[0], Math.round(coverage * 200))); + out.push(dBlob(cx0, cy0, W * 0.36, H * 0.3, washes[1] || washes[0], 200, 0.6, 0.5, 0.3, 0.25, 520)); + out.push(dBlob(W * 0.15, H * 0.15, W * 0.3, H * 0.28, foliage[0], 210, 0.5, 0.5, 0.4, 0.25, 460)); + out.push(dBlob(W * 0.2, H * 0.85, W * 0.34, H * 0.26, washes[2] || washes[0], 200, 0.5, 0.5, -0.3, 0.25, 460)); + out.push(dBlob(W * 0.9, H * 0.9, W * 0.2, H * 0.2, foliage[1], 190, 0.5, 0.5, 0, 0.25, 380)); + out.push(dBlob(W * 0.55, H * 0.55, W * 0.3, H * 0.14, washes[3] || washes[1] || washes[0], 150, 0.6, 0.5, -0.5, 0.25, 420)); + out.push(dBlob(cx0, cy0, W * 0.1, H * 0.08, highlights[0], 90, 0.7, 0.5, 0, 0.25, 300)); + + // the swirl: marker glazes along arcs around the eye, opening out a little as + // they go, inside first and four to a stroke; then the ripple rings at the eye + const swirlCols = [washes[1] || washes[0], washes[3] || washes[1] || washes[0], washes[2] || washes[0], highlights[0], foliage[3] || washes[0], washes[0], highlights[1] || highlights[0]]; + const nArc = Math.round((40 + glaze * 60) * (0.5 + 0.5 * det)); + const arcs = []; + for (let i = 0; i < nArc; i++) { + const r = m * (0.05 + 0.62 * Math.pow(random(), 0.8)) * sc; + const a0 = rr(0, TWO_PI), span = rr(0.4, 1.6) * (r < m * 0.15 ? 1.6 : 1); + const pts = ringPts(cx0, cy0, r, a0, a0 + span, 9).map(([px, py], k) => { const g = 1 + k * 0.012; return [cx0 + (px - cx0) * g, cy0 + (py - cy0) * g]; }); + arcs.push({ r, pts, color: pickOne(swirlCols), w: rr(1.4, 5) * bs * (0.6 + 0.4 * sc) }); + } + arcs.sort((a, b) => a.r - b.r); + for (let i = 0; i < arcs.length; i += 4) { + const b = arcs.slice(i, i + 4); + const bb = bboxOf(b.flatMap((A) => A.pts), 14 + Math.max(...b.map((A) => A.w)) * 4); + out.push(D(() => { for (const A of b) { brush.field('waves'); strokeStyle('marker', A.color, A.w); brush.spline(A.pts, 0.5); brush.noField(); } }, bb, raxis(), rdir(), 260, 40)); + } + const rings = []; + for (let k = 0; k < 4; k++) { + const r = m * (0.03 + k * 0.03) * sc, a0 = rr(0, TWO_PI); + const pts = ringPts(cx0 + rr(-2, 2), cy0 + rr(-2, 2), r, a0, a0 + TWO_PI * rr(0.7, 0.95), 14); + rings.push({ pts, color: k % 2 ? (highlights[1] || highlights[0]) : highlights[0], w: rr(1.5, 2.5) * bs }); + } + out.push(D(() => { for (const R of rings) { strokeStyle('marker', R.color, R.w); brush.spline(R.pts, 0.5); } }, bboxOf(rings.flatMap((R) => R.pts), 24), 'y', -1, 320, 60)); + + // two shadow koi deep in the water, then the orange ones, each revealed tail to head + const shadows = [{ x: W * 0.28, y: H * 0.3, len: m * 0.3 * sc, a: 0.5 }, { x: W * 0.7, y: H * 0.78, len: m * 0.26 * sc, a: -2.6 }]; + for (const s of shadows) { + const body = taperedBody(s.x, s.y, s.len, s.len * 0.3, s.a, 0.08); + out.push(D(() => { fillStyle(foliage[1], 130, 0.35 + water * 0.2, 0.5, 0.3); brush.polygon(body); }, bboxOf(body, s.len * 0.3 + 20), 'x', Math.sign(Math.cos(s.a)) || 1, 340, 60)); + } + const koi = [ + { x: W * 0.6, y: H * 0.3, len: m * 0.3 * sc, a: -0.5 + rr(-0.15, 0.15) }, + { x: W * 0.3, y: H * 0.68, len: m * 0.36 * sc, a: 0.35 + rr(-0.15, 0.15) }, + ]; + if (dens > 0.75) koi.push({ x: W * 0.85, y: H * 0.65, len: m * 0.2 * sc, a: 2.4 }); + for (const k of koi) out.push(D(() => drawKoi(k.x, k.y, k.len, k.a, K), boxAround(k.x, k.y, k.len * 0.55 + 20), 'x', Math.sign(Math.cos(k.a)) || 1, 440, 100)); + + // cream flecks riding the swirl, a glaze back over each tail so the fish sit in the water, light at the eye + const flecks = []; + for (let i = 0; i < Math.round((30 + dens * 30) * (0.4 + 0.6 * det)); i++) { + const r = m * rr(0.06, 0.6) * sc, a = rr(0, TWO_PI), x = cx0 + Math.cos(a) * r, y = cy0 + Math.sin(a) * r; + if (x < -5 || x > W + 5 || y < -5 || y > H + 5) continue; + const len = m * rr(0.01, 0.03) * sc * bs, h = m * rr(0.002, 0.004) * bs; + flecks.push({ color: random() < 0.6 ? highlights[0] : (highlights[1] || highlights[0]), pts: jitterEllipse(x, y, len, h, 8, 0.2, a + HALF_PI + rr(-0.2, 0.2)), op: Math.round(rr(150, 230)) }); + } + out.push(...dMarks(flecks)); + for (const k of koi) { + const tx = k.x - Math.cos(k.a) * k.len * 0.35, ty = k.y - Math.sin(k.a) * k.len * 0.35; + const th = Math.atan2(ty - cy0, tx - cx0), r = Math.hypot(tx - cx0, ty - cy0); + const pts = ringPts(cx0, cy0, r, th - 0.3, th + 0.3, 6), w = rr(3, 5) * bs; + out.push(D(() => { brush.field('waves'); strokeStyle('marker', washes[1] || washes[0], w); brush.spline(pts, 0.5); brush.noField(); }, bboxOf(pts, 14 + w * 4), raxis(), rdir(), 200, 40)); + } + const eyePts = []; + for (let i = 0; i < 8; i++) { const a = rr(0, TWO_PI), r = m * rr(0.05, 0.4); eyePts.push([cx0 + Math.cos(a) * r, cy0 + Math.sin(a) * r, 10]); } + out.push(...dTouches(eyePts, C, Math.round(touch * 16), () => rr(0, TWO_PI), 0.6)); + return out; + } + + // Roses in dappled light. Painted a little larger than the shared scale and + // less saturated than the shared vivid, so the pinks stay soft. + function buildRoses(C) { + const out = [], { water, density: dens, soft, detail: det, brushSize: bs } = S; + const sc = 1.2; + const { washes, accents, highlights } = C; + const F = flowerCols(C, 0.25), G = foliageCols(C); + const lilac = washes[0], gold = washes[1] || highlights[0], blue = washes[2] || lilac, cream = washes[3] || highlights[1] || highlights[0]; + + // a lilac-grey ground, a gold glow upper right, a cool patch low left, the dark leaf mass upper left + if (S.coverage > 0.02) out.push(dWash(lilac, Math.round(S.coverage * 200))); + out.push(dBlob(W * 0.5, H * 0.6, W * 0.55, H * 0.45, lilac, 190, 0.5, 0.5, 0, 0.2, 520)); + out.push(dBlob(W * 0.78, H * 0.14, W * 0.34, H * 0.24, gold, 200, 0.6, 0.5, 0.2, 0.25, 480)); + out.push(dBlob(W * 0.85, H * 0.06, W * 0.2, H * 0.12, highlights[0], 150, 0.7, 0.5, 0, 0.25, 360)); + out.push(dBlob(W * 0.2, H * 0.85, W * 0.32, H * 0.22, blue, 160, 0.6, 0.5, 0, 0.25, 440)); + out.push(dBlob(W * 0.18, H * 0.14, W * 0.26, H * 0.2, G.shade, 215, 0.4 + water * 0.2, 0.5, 0.3, 0.25, 440)); + out.push(dBlob(W * 0.36, H * 0.08, W * 0.16, H * 0.1, G.deep, 200, 0.45, 0.5, -0.2, 0.25, 340)); + out.push(dBlob(W * 0.08, H * 0.36, W * 0.14, H * 0.12, G.deep, 190, 0.45, 0.5, 0.4, 0.25, 340)); + + // the dapple, everywhere, then leaves in the dark mass and a few loose ones right of the roses + const dapple = []; + const dotCols = [lilac, gold, blue, cream, highlights[1] || cream, highlights[0], accents[3] || F.pale, mixHex(lilac, '#ffffff', 0.4)]; + for (let i = 0; i < Math.round((120 + dens * 160) * (0.3 + 0.7 * det)); i++) { + const x = rr(-5, W + 5), y = rr(-5, H + 5), r = m * rr(0.008, 0.02) * sc * bs * (1.4 - 0.4 * det); + dapple.push({ color: pickOne(dotCols), pts: jitterEllipse(x, y, r * rr(1, 1.6), r, 12, 0.1 + soft * 0.08, rr(0, TWO_PI)), op: Math.round(rr(90, 170) - water * 30) }); + } + out.push(...dMarks(dapple)); + out.push(...dLeafDabs(W * 0.2, H * 0.16, W * 0.26, H * 0.18, Math.round(22 + dens * 24), [G.shade, G.deep, G.mid, G.light], m * 0.011 * sc, null, [130, 200])); + out.push(...dLeafDabs(W * 0.62, H * 0.28, W * 0.14, H * 0.12, Math.round(6 + dens * 8), [G.deep, G.mid, G.light], m * 0.011 * sc, null, [130, 200])); + + // a pale bud-rose behind the group, two stems up into the leaves, then the roses back to front + const roses = [ + { x: W * 0.32, y: H * 0.36, s: m * 0.115 * sc }, + { x: W * 0.54, y: H * 0.6, s: m * 0.15 * sc }, + { x: W * 0.28, y: H * 0.7, s: m * 0.11 * sc }, + ]; + if (dens > 0.7) roses.push({ x: W * 0.78, y: H * 0.8, s: m * 0.08 * sc }); + const bud = { x: W * 0.74, y: H * 0.5, s: m * 0.07 * sc }; + out.push(D(() => bloomShape(bud.x, bud.y, bud.s, 7, 0.76, mixHex(F.light, cream, 0.5), 0.3, 0.72), boxAround(bud.x, bud.y, bud.s * 2.2 + 16), raxis(), rdir(), 320, 80)); + const sorted = roses.slice().sort((a, b) => a.y - b.y); + for (const r of sorted.slice(0, 2)) { + const stem = [[r.x - r.s * 0.2, r.y - r.s * 0.95], [r.x - W * 0.06 + rr(-8, 8), r.y - r.s - H * 0.1], [r.x - W * 0.12, H * 0.2]]; + const w = rr(1.8, 2.6) * bs; + out.push(D(() => { brush.field('hand'); strokeStyle('marker', G.deep, w); brush.spline(stem, 0.6); brush.noField(); }, bboxOf(stem, 14 + w * 4), 'y', 1, 220, 40)); + } + for (const r of sorted) out.push(D(() => drawRose(r.x, r.y, r.s, F), boxAround(r.x, r.y, r.s * 2.2 + 16), raxis(), rdir(), 460, 100)); + + // a lighter cream and gold dapple over the roses' rims, then light + const light = []; + for (let i = 0; i < Math.round(30 + dens * 30); i++) { + const r0 = pickOne(roses), a = rr(0, TWO_PI), d = r0.s * rr(1.1, 1.6); + const x = r0.x + Math.cos(a) * d, y = r0.y + Math.sin(a) * d, r = m * rr(0.006, 0.012) * sc * bs; + light.push({ color: random() < 0.5 ? cream : (random() < 0.5 ? gold : (highlights[1] || cream)), pts: jitterEllipse(x, y, r * 1.5, r, 8, 0.2, rr(0, TWO_PI)), op: 100 }); + } + out.push(...dMarks(light)); + out.push(...dTouches(roses.map((r) => [r.x, r.y - r.s * 0.6, r.s * 0.8]), C, Math.round(S.touch * 16), () => rr(-0.4, 0.4), 0.7)); + return out; + } + + // An orange tree against the sky. A little drier than the shared dials so + // the sky stays clear and the fruit keeps a rind instead of a halo. + function buildOranges(C) { + const out = [], { density: dens, scale: sc, detail: det, brushSize: bs } = S; + const water = 0.45; + const { washes, foliage, accents, highlights } = C; + const G = foliageCols(C); + const O = { light: vivid(accents[2] || accents[0], S.vivid), mid: vivid(accents[0], S.vivid), deep: accents[3] || accents[1] || accents[0], glint: highlights[1] || highlights[0] }; + const canopyX = W * 0.62, canopyY = H * 0.58; + + // a blue sky, brightest upper left, a pale ground behind the leaves lower right + if (S.coverage > 0.02) out.push(dWash(washes[2] || washes[0], Math.round(S.coverage * 200))); + out.push(dBand(-20, H * 0.45, washes[0], Math.round(200 - water * 40), m * 0.04)); + out.push(dBlob(W * 0.15, H * 0.2, W * 0.3, H * 0.28, washes[1] || washes[0], 190, 0.6, 0.5, 0.2, 0.2, 480)); + out.push(dBlob(W * 0.1, H * 0.5, W * 0.16, H * 0.2, mixHex(washes[0], highlights[0], 0.5), 150, 0.7, 0.5, 0, 0.25, 360)); + out.push(dBand(H * 0.4, H + 20, washes[3] || washes[2] || washes[0], Math.round(190 - water * 40), m * 0.04)); + + // canopy masses lower right and top right, blossom specks where the sky meets the leaves + out.push(dBlob(canopyX, canopyY, W * 0.44, H * 0.4, mixHex(G.deep, G.shade, 0.5), 235, 0.35 + water * 0.2, 0.5, 0.2, 0.25, 540)); + out.push(dBlob(W * 0.8, H * 0.14, W * 0.26, H * 0.14, G.deep, 205, 0.45, 0.5, -0.3, 0.25, 400)); + out.push(dBlob(W * 0.5, H * 0.85, W * 0.36, H * 0.16, G.shade, 215, 0.4, 0.5, 0.1, 0.25, 420)); + out.push(dBlob(W * 0.85, H * 0.62, W * 0.2, H * 0.24, G.shade, 200, 0.4, 0.5, 0, 0.25, 380)); + out.push(dBlob(W * 0.35, H * 0.42, W * 0.18, H * 0.14, G.mid, 190, 0.5, 0.5, 0.4, 0.25, 340)); + const specks = []; + for (let i = 0; i < Math.round((24 + dens * 30) * (0.4 + 0.6 * det)); i++) { + const x = rr(0, W * 0.55), y = rr(0, H * 0.5), r = m * rr(0.004, 0.008) * sc * bs; + specks.push({ color: random() < 0.7 ? highlights[0] : (highlights[1] || highlights[0]), pts: jitterEllipse(x, y, r, r * rr(0.8, 1), 8, 0.2), op: Math.round(rr(170, 240)) }); + } + out.push(...dMarks(specks)); + + // the fruit is planned now so the leaf pass can fan around it + const fruit = [ + { x: W * 0.42, y: H * 0.36, r: m * 0.09 * sc }, + { x: W * 0.8, y: H * 0.28, r: m * 0.075 * sc }, + { x: W * 0.56, y: H * 0.66, r: m * 0.085 * sc }, + ]; + if (dens > 0.4) fruit.push({ x: W * 0.1, y: H * 0.9, r: m * 0.06 * sc }); + if (dens > 0.7) fruit.push({ x: W * 0.92, y: H * 0.86, r: m * 0.055 * sc }); + + // the leaf pass, fanning out from the canopy centre, then the oranges + const leafCols = [G.shade, G.deep, G.mid, G.light, mixHex(G.mid, highlights[1] || highlights[0], 0.35), foliage[0]]; + const fan = (x, y) => Math.atan2(y - canopyY, x - canopyX); + out.push(...dLeafDabs(canopyX, canopyY, W * 0.48, H * 0.44, Math.round(150 + dens * 150), leafCols, m * 0.013 * sc, fan, [150, 235])); + out.push(...dLeafDabs(W * 0.8, H * 0.14, W * 0.26, H * 0.14, Math.round(26 + dens * 30), leafCols, m * 0.012 * sc, fan, [150, 235])); + out.push(...dLeafDabs(W * 0.3, H * 0.42, W * 0.2, H * 0.14, Math.round(18 + dens * 20), [G.mid, G.light, leafCols[4]], m * 0.011 * sc, fan, [150, 235])); + for (const f of fruit) out.push(D(() => drawOrange(f.x, f.y, f.r, O), boxAround(f.x, f.y, f.r * 1.6 + 16), 'y', 1, 380, 90)); + + // small half-hidden oranges, a few leaves crossing the fruit, light on the rinds + const small = []; + for (let i = 0; i < 3 + Math.round(dens * 4); i++) { + const x = rr(W * 0.2, W * 0.98), y = rr(H * 0.2, H * 0.98), r = m * rr(0.02, 0.035) * sc; + small.push({ color: random() < 0.5 ? O.mid : O.deep, pts: jitterEllipse(x, y, r, r * 0.95, 10, 0.1), op: 215 }); + } + out.push(...dMarks(small, 260)); + const over = []; + for (const f of fruit) for (let k = 0; k < 2; k++) { + const a = rr(0, TWO_PI), x = f.x + Math.cos(a) * f.r * 0.9, y = f.y + Math.sin(a) * f.r * 0.9, r = m * rr(0.012, 0.02) * sc * bs; + over.push({ color: random() < 0.5 ? G.deep : G.mid, pts: petalPts(x, y, r * 2, r * 0.7, a + rr(-0.6, 0.6), 10, 0.1), op: 200 }); + } + out.push(...dMarks(over)); + out.push(...dTouches(fruit.map((f) => [f.x - f.r * 0.3, f.y - f.r * 0.4, f.r * 0.5]), C, Math.round(S.touch * 14), () => rr(-0.5, 0.5), 0.6)); + return out; + } + + // Evening sea, one sail. Wetter than the shared dials, with more still-water + // glazes and more light on the water. + function buildSail(C) { + const out = [], { density: dens, scale: sc, soft, detail: det, brushSize: bs } = S; + const water = 0.6, glaze = 0.5, touch = 0.3; + const { washes, foliage, accents, highlights } = C; + const horizon = H * 0.52, sunX = W * 0.56; + const sky = washes[0], sea = washes[1], glow = washes[2] || highlights[0], ripple = washes[3] || mixHex(sea, foliage[0], 0.4); + + // sky, a warm band at the horizon, the sea in two bands, the glow's reflection + if (S.coverage > 0.02) out.push(dWash(sky, Math.round(S.coverage * 200))); + out.push(dBand(-20, horizon * 0.7, sky, Math.round(200 - water * 40), m * 0.033)); + out.push(dBand(horizon * 0.55, horizon + H * 0.02, glow, Math.round(190 - water * 40), m * 0.03)); + out.push(dBand(horizon - H * 0.01, H * 0.8, sea, Math.round(210 - water * 40), m * 0.017)); + out.push(dBand(H * 0.7, H + 20, mixHex(sea, ripple, 0.35), Math.round(215 - water * 40), m * 0.02)); + out.push(dBlob(sunX, horizon + H * 0.12, W * 0.2, H * 0.14, mixHex(glow, highlights[0], 0.5), 150, 0.7, 0.5, 0, 0.15, 460)); + + // cumulus: a big lit cloud upper right, a low bank left, each a grey underside + // under a peach body and a lit crown; then wisps near the horizon + const under = mixHex(sea, foliage[2], 0.3); + const clouds = [ + { x: W * 0.62, y: H * 0.2, rx: W * 0.2, ry: H * 0.12 }, + { x: W * 0.85, y: H * 0.32, rx: W * 0.16, ry: H * 0.07 }, + { x: W * 0.12, y: H * 0.24, rx: W * 0.17, ry: H * 0.06 }, + { x: W * 0.3, y: H * 0.4, rx: W * 0.22, ry: H * 0.045 }, + ]; + if (dens > 0.6) clouds.push({ x: W * 0.45, y: H * 0.1, rx: W * 0.1, ry: H * 0.05 }); + for (const c of clouds) { + const peach = random() < 0.5 ? accents[0] : (accents[1] || accents[0]); + out.push(dBlob(c.x, c.y + c.ry * 0.3, c.rx, c.ry * 0.7, under, 170, 0.5 + water * 0.2, 0.5, 0, 0.2, 380)); + out.push(dBlob(c.x, c.y, c.rx * 0.95, c.ry, peach, 215, 0.45 + water * 0.2, 0.5, rr(-0.1, 0.1), 0.25 + soft * 0.15, 420)); + out.push(dBlob(c.x - c.rx * 0.2, c.y - c.ry * 0.45, c.rx * 0.6, c.ry * 0.6, accents[2] || highlights[0], 200, 0.5, 0.5, rr(-0.2, 0.2), 0.3, 340)); + } + for (let i = 0; i < 3; i++) { + const x = rr(W * 0.1, W * 0.9), y = rr(horizon * 0.62, horizon * 0.92); + out.push(dBlob(x, y, W * rr(0.08, 0.16), H * rr(0.012, 0.025), under, 120, 0.6, 0.5, 0, 0.3, 300)); + } + + // the ripples: short horizontal dashes, grey-blue with a few warm ones, longer + // and denser toward the bottom; then still-water glazes + const dashes = []; + for (let i = 0; i < Math.round((90 + dens * 160) * (0.3 + 0.7 * det)); i++) { + const y = horizon + (H - horizon) * Math.pow(random(), 0.7), near = (y - horizon) / (H - horizon), x = rr(-5, W + 5); + const len = m * rr(0.012, 0.04) * sc * (0.5 + near) * bs, h = m * rr(0.002, 0.0035) * (0.6 + near) * bs; + const dark = random() < 0.65; + const color = dark ? (random() < 0.5 ? ripple : mixHex(ripple, sea, 0.4)) : (random() < 0.5 ? highlights[0] : mixHex(glow, highlights[1] || highlights[0], 0.5)); + dashes.push({ color, pts: jitterEllipse(x, y, len, h, 8, 0.2, rr(-0.06, 0.06)), op: Math.round(rr(120, 200) - water * 30) }); + } + out.push(...dMarks(dashes)); + for (let i = 0; i < Math.round(3 + glaze * 8); i++) { + const y = rr(horizon + 5, H), x0 = rr(-10, W * 0.5), x1 = x0 + rr(W * 0.3, W * 0.8); + const color = random() < 0.5 ? sea : (random() < 0.5 ? ripple : glow); + out.push(dGlaze(x0, y, x1, y + rr(-3, 3), color, rr(1.5, 3) * Math.sqrt(sc), 'waves')); + } + + // the sail and its hull over a faint reflection, a rowboat with two specks aboard, glints down the light + const sx = W * 0.55, sy = horizon + H * 0.1, sh = m * 0.165 * sc; + const sailPts = [[sx, sy - sh], [sx + sh * 0.45 + rr(-2, 2), sy], [sx - sh * 0.04, sy]]; + const jib = [[sx - sh * 0.02, sy - sh * 0.7], [sx - sh * 0.3, sy - sh * 0.02], [sx - sh * 0.03, sy]]; + const hull = jitterEllipse(sx + sh * 0.05, sy + sh * 0.03, sh * 0.32, sh * 0.035, 8, 0.15); + out.push(dBlob(sx, sy + sh * 0.5, sh * 0.35, sh * 0.5, highlights[1] || highlights[0], 110, 0.7, 0.5, 0, 0.2, 320)); + out.push(D(() => { + washStyle(highlights[1] || highlights[0], 250); brush.polygon(sailPts); brush.polygon(jib); + bloomFill(highlights[0], 160, 0.15); brush.polygon(sailPts); + washStyle(foliage[1], 235); brush.polygon(hull); + }, bboxOf([...sailPts, ...jib, ...hull], 24), 'y', -1, 440, 90)); + const bx = W * 0.38, by = horizon + H * 0.18; + const boat = jitterEllipse(bx, by, m * 0.02 * sc, m * 0.004 * sc, 8, 0.15); + out.push(D(() => { + washStyle(foliage[2], 230); brush.polygon(boat); + centerDot(bx - m * 0.005, by - m * 0.006, m * 0.004, foliage[2], 220); centerDot(bx + m * 0.006, by - m * 0.005, m * 0.0035, foliage[2], 220); + }, bboxOf(boat, 14), 'x', rdir(), 160, 40)); + const glintPts = []; + for (let i = 0; i < 10; i++) glintPts.push([sunX + randomGaussian(0, W * 0.1), rr(horizon + 5, H * 0.95), 12]); + out.push(...dTouches(glintPts, C, Math.round(touch * 18), () => rr(-0.05, 0.05))); + return out; + } + + // ===================================================================== + // Configs. Everything the vocabulary closes over that isn't in + // engine.js goes in `dials` so Copy code can emit it. + // ===================================================================== + const VOCABULARY = [ + softBlobDraw, bloomFill, bloomShape, centerDot, flowerCols, foliageCols, + drawPeony, drawDaisy, drawBlossom, drawLily, drawFlower, drawPad, drawStrand, + glazeDraw, flickDraw, + dWash, dBand, dBlob, dGlaze, dStrand, dLeaves, dMarks, dFlower, dPad, dFlick, dTouches, + buildGarden, buildDawn, buildWillow, buildWisteria, + buildPoppies, buildIrises, buildOrchard, + ringPts, petalPts, taperedBody, drawKoi, drawRose, drawOrange, boxAround, dLeafDabs, + buildKoi, buildRoses, buildOranges, buildSail, + ]; + + // `strokes` must name its builder literally: Copy code serialises this arrow + // with toString(), so a captured `builder` variable would be undefined in the + // emitted file. Each one has to resolve against VOCABULARY by name. + const scene = (key, label, note, strokes) => ({ + key: 'impressionism-' + key, + movement: 'Impressionism', + label, + note, + canvasSize: 600, + loopMs: 9000, + holdMs: 1500, + dials: S, + palette: SCENES[key], + strokes, + vocabulary: VOCABULARY, + }); + + STYLES.impressionismGarden = scene('garden', 'Garden', + 'Warm and a little too much, in the best way.', + (palette) => buildGarden(palette)); + STYLES.impressionismDawn = scene('dawn', 'Dawn', + 'Quiet, like nothing has happened yet.', + (palette) => buildDawn(palette)); + STYLES.impressionismWillow = scene('willow', 'Willow', + 'Cool and wistful, the kind of quiet you don’t want to leave.', + (palette) => buildWillow(palette)); + STYLES.impressionismWisteria = scene('wisteria', 'Wisteria', + 'Delicate in a way that already feels like a memory.', + (palette) => buildWisteria(palette)); + STYLES.impressionismPoppies = scene('poppies', 'Poppies', + 'Red that refuses to be background.', + (palette) => buildPoppies(palette)); + STYLES.impressionismIrises = scene('irises', 'Irises', + 'Purple standing at attention, politely.', + (palette) => buildIrises(palette)); + STYLES.impressionismOrchard = scene('orchard', 'Orchard', + 'Light and a little giddy, spring before it’s sure of itself.', + (palette) => buildOrchard(palette)); + STYLES.impressionismKoi = scene('koi', 'Koi', + 'Stillness is just movement too slow to notice.', + (palette) => buildKoi(palette)); + STYLES.impressionismRoses = scene('roses', 'Roses', + 'Everything opens at its own speed.', + (palette) => buildRoses(palette)); + STYLES.impressionismOranges = scene('oranges', 'Oranges', + 'Ripening is just time becoming sweet.', + (palette) => buildOranges(palette)); + STYLES.impressionismSail = scene('sail', 'Sail', + 'A boat is mostly waiting for wind.', + (palette) => buildSail(palette)); +})(); diff --git a/public/painterly/vendor/p5.brush.js b/public/painterly/vendor/p5.brush.js new file mode 100644 index 0000000..371e2e1 --- /dev/null +++ b/public/painterly/vendor/p5.brush.js @@ -0,0 +1,8 @@ +/** + * Skipped minification because the original files appears to be already minified. + * Original file: /npm/p5.brush@2.2.2/dist/p5.brush.js + * + * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files + */ +var t,e;t=this,e=function(t){const e={a:1,b:0,c:0,d:1,x:0,y:0};let r=()=>!1,n=t=>t,i=()=>{throw new Error("No runtime color adapter registered.")},o=()=>e,s=()=>{};const a=Math.sqrt(3),c=.5*(a-1),l=(3-a)/6,h=t=>0|Math.floor(t),u=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]);function f(t=Math.random){const e=function(t){const e=new Uint8Array(512);for(let t=0;t<256;t++)e[t]=t;for(let r=0;r<255;r++){const n=r+~~(t()*(256-r)),i=e[r];e[r]=e[n],e[n]=i}for(let t=256;t<512;t++)e[t]=e[t-256];return e}(t),r=new Float64Array(e).map(t=>u[t%12*2]),n=new Float64Array(e).map(t=>u[t%12*2+1]);return function(t,i){let o=0,s=0,a=0;const u=(t+i)*c,f=h(t+u),m=h(i+u),d=(f+m)*l,g=t-(f-d),x=i-(m-d);let p,y;g>x?(p=1,y=0):(p=0,y=1);const b=g-p+l,v=x-y+l,w=g-1+2*l,_=x-1+2*l,A=255&f,R=255&m;let E=.5-g*g-x*x;if(E>=0){const t=A+e[R];E*=E,o=E*E*(r[t]*g+n[t]*x)}let M=.5-b*b-v*v;if(M>=0){const t=A+p+e[R+y];M*=M,s=M*M*(r[t]*b+n[t]*v)}let S=.5-w*w-_*_;if(S>=0){const t=A+1+e[R+1];S*=S,a=S*S*(r[t]*w+n[t]*_)}return 70*(o+s+a)}}function m(t){let e=function(t){let e=0;const r=String(t);for(let t=0;t>>15;return e=0|Math.imul(e^e>>>16,2246822507),e=0|Math.imul(e^e>>>13,3266489909),(e^e>>>16)>>>0||1}(t);return()=>{e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t^=t+Math.imul(t^t>>>7,61|t),2.3283064365386963e-10*((t^t>>>14)>>>0)}}let d=m(Math.random()),g=m(Math.random()+":2");const x=[],p=t=>x.push(t),y=t=>{d=m(t),g=m(`${t}:2`),M=!1;for(const t of x)t()};f(m(Math.random()));let b=f(m(Math.random()+":2"));const v=t=>{f(m(t)),b=f(m(`${t}:2`))},w=(t=0,e=1)=>t+d()*(e-t),_=(t=0,e=1)=>t+g()*(e-t),A=t=>t[~~(d()*t.length)],R=(t,e)=>~~w(t,e),E=(t,e)=>~~_(t,e);let M=!1,S=0;const P=(t=0,e=1)=>{if(M)return M=!1,S*e+t;const r=1-d(),n=d(),i=Math.sqrt(-2*Math.log(r)),o=360*n;return S=i*B(o),M=!0,i*N(o)*e+t},T=(t,e,r,n,i,o=!1)=>{let s=n+(t-e)/(r-e)*(i-n);return o?nMath.max(Math.min(t,r),e),C=1440,I=2*Math.PI/C,F=new Float32Array(C),L=new Float32Array(C);for(let t=0;tt<0?t>=-360?~~(4*(t+360)):~~(4*((t%=360)<0?t+360:t)):t<360?~~(4*t):t<720?~~(4*(t-360)):t<1080?~~(4*(t-720)):~~(4*((t%=360)<0?t+360:t)),N=t=>F[D(t)],B=t=>L[D(t)],Y=new Float32Array(2),z=t=>{const e=D(t);return Y[0]=F[e],Y[1]=L[e],Y},O=(t,e=!1)=>{if(e||r()){let e=180*t/Math.PI%360;return e<0?e+360:e}return t},X=(t,e=!1)=>e||r()?180*t/Math.PI:t,U=(t,e,r,n,i)=>{const o=z(i),s=o[0],a=o[1];return{x:s*(r-t)+a*(n-e)+t,y:s*(n-e)-a*(r-t)+e}},G=(t,e,r,n)=>Math.hypot(r-t,n-e),V=(t,e,r,n)=>O(Math.atan2(-(n-e),r-t),!0),H=(t,e,r,n,i=!1)=>{const o=t.x,s=t.y,a=e.x,c=e.y,l=r.x,h=r.y,u=a-o,f=c-s,m=n.x-l,d=n.y-h,g=d*u-m*f;if(0===g)return!1;const x=s-h,p=o-l,y=(m*x-d*p)/g,b=(u*x-f*p)/g;return!(!i&&(b<0||b>1))&&{x:o+y*u,y:s+y*f}};let W,j,$,q,K,Z={load:()=>{throw new Error("No target runtime adapter registered.")},syncDensity:()=>K,isCanvasReady:()=>{throw new Error("No target runtime adapter registered.")},instance:t=>{$=t},activateInstance:t=>{$=t},deactivateInstance:()=>{},getActiveFramebuffer:()=>null,isFramebufferTarget:()=>!1};function J(t){"Cwidth"in t&&(W=t.Cwidth),"Cheight"in t&&(j=t.Cheight),"Instance"in t&&($=t.Instance),"Renderer"in t&&(q=t.Renderer),"Density"in t&&(K=t.Density)}const Q=()=>Z.isCanvasReady(),tt=t=>Z.instance(t),et=t=>Z.activateInstance(t),rt=()=>Z.deactivateInstance(),nt=()=>Z.getActiveFramebuffer(),it=t=>Z.isFramebufferTarget(t),ot=(t,e=0)=>t?{minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}:null,st=(t,e,r=!1)=>{const n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(t,e):(()=>{const r=document.createElement("canvas");return r.width=t,r.height=e,r})();return n.drawingContext=n.getContext("2d",r?{willReadFrequently:!0}:void 0),n};let at={clearTarget:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendShaderProgram:()=>{throw new Error("No compositor runtime adapter registered.")},ensureBlendSourceFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},createFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")},runBlendShaderPass:()=>{throw new Error("No compositor runtime adapter registered.")},blitSourceToFramebuffer:()=>{throw new Error("No compositor runtime adapter registered.")}};const ct=(...t)=>at.createFramebuffer(...t);let lt=null,ht=null;const ut=t=>{((...t)=>{at.clearTarget(...t)})(q,t,it)},ft=()=>({width:Math.max(1,Math.round(W*K)),height:Math.max(1,Math.round(j*K))}),mt=t=>{if(!t)return null;const{width:e,height:r}=ft();return((t,e,r)=>{if(!t)return null;const n=Math.max(0,Math.floor(Math.min(t.minX,t.maxX))),i=Math.max(0,Math.floor(Math.min(t.minY,t.maxY))),o=Math.min(e,Math.ceil(Math.max(t.minX,t.maxX))),s=Math.min(r,Math.ceil(Math.max(t.minY,t.maxY)));return o<=n||s<=i?null:{minX:n,minY:i,maxX:o,maxY:s}})(t,e,r)},dt=()=>{const{width:t,height:e}=ft();return((t,e)=>({minX:0,minY:0,maxX:t,maxY:e}))(t,e)},gt=(t,e=!0)=>{const r=mt(t);if(!r)return null;const{height:n}=ft();return{x:r.minX,y:e?n-r.maxY:r.minY,width:r.maxX-r.minX,height:r.maxY-r.minY}},xt=(t,e,r,n=!0)=>{const i=gt(e,n);if(i){t.enable(t.SCISSOR_TEST),t.scissor(i.x,i.y,i.width,i.height);try{r()}finally{t.disable(t.SCISSOR_TEST)}}else r()},pt={},yt=()=>{q?.loaded||(Q(),bt.load())},bt={isBlending:!1,cachedColor:null,markDirtyRect(t,e){const r=mt(e);var n,i;t&&r&&(t.dirtyRect=(i=r,(n=t.dirtyRect)?i?{minX:Math.min(n.minX,i.minX),minY:Math.min(n.minY,i.minY),maxX:Math.max(n.maxX,i.maxX),maxY:Math.max(n.maxY,i.maxY)}:n:i),t.isDrawn=!0)},clearMask(t){if(!t)return;const e=t===this.glMask?lt:ht;e?.clearMask?.(t,ut)},getCompositeRect(t,e){const r=e?lt:ht;return r?.getCompositeRect?.(t,nt,dt,ot,mt)},load(){Z.syncDensity();const t=!q.blendSourceFramebuffer||q.blendSourceFramebuffer.width!==W||q.blendSourceFramebuffer.height!==j||"function"==typeof q.blendSourceFramebuffer.pixelDensity&&q.blendSourceFramebuffer.pixelDensity()!==K;((...t)=>{at.ensureBlendShaderProgram(...t)})(q,"#version 300 es\n#define GLSLIFY 1\nout vec2 p;void main(){vec3 v=vec3(-1);v[gl_VertexID]=3.;p=v.xy;gl_Position=vec4(v.x,-v.y,0,1);}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nuniform bool u_isBrush;uniform bool u_targetIsFramebuffer;uniform sampler2D u_source;uniform sampler2D u_mask;uniform vec3 u_color;in vec2 p;out vec4 outColor;const int SPECTRAL_SIZE=38;const float SPECTRAL_GAMMA=2.4;const float SPECTRAL_EPSILON=0.0001;float spectral_uncompand(float x){return(x<0.04045)? x/12.92 : pow((x+0.055)/1.055,SPECTRAL_GAMMA);}float spectral_compand(float x){return(x<0.0031308)? x*12.92 : 1.055*pow(x,1.0/SPECTRAL_GAMMA)-0.055;}vec3 spectral_srgb_to_linear(vec3 srgb){return vec3(spectral_uncompand(srgb[0]),spectral_uncompand(srgb[1]),spectral_uncompand(srgb[2]));}vec3 spectral_linear_to_srgb(vec3 lrgb){return clamp(vec3(spectral_compand(lrgb[0]),spectral_compand(lrgb[1]),spectral_compand(lrgb[2])),0.,1.);}void spectral_linear_to_reflectance(vec3 lrgb,inout float R[SPECTRAL_SIZE]){float w=min(lrgb.r,min(lrgb.g,lrgb.b));lrgb-=w;float c=min(lrgb.g,lrgb.b);float m=min(lrgb.r,lrgb.b);float y=min(lrgb.r,lrgb.g);float r=min(max(0.0,lrgb.r-lrgb.b),max(0.0,lrgb.r-lrgb.g));float g=min(max(0.0,lrgb.g-lrgb.b),max(0.0,lrgb.g-lrgb.r));float b=min(max(0.0,lrgb.b-lrgb.g),max(0.0,lrgb.b-lrgb.r));R[0]=max(SPECTRAL_EPSILON,w*1.0011607271876400+c*0.9705850013229620+m*0.9906735573199880+y*0.0210523371789306+r*0.0315605737777207+g*0.0095560747554212+b*0.9794047525020140);R[1]=max(SPECTRAL_EPSILON,w*1.0011606515972800+c*0.9705924981434250+m*0.9906715249619790+y*0.0210564627517414+r*0.0315520718330149+g*0.0095581580120851+b*0.9794007068431300);R[2]=max(SPECTRAL_EPSILON,w*1.0011603192274700+c*0.9706253487298910+m*0.9906625823534210+y*0.0210746178695038+r*0.0315148215513658+g*0.0095673245444588+b*0.9793829034702610);R[3]=max(SPECTRAL_EPSILON,w*1.0011586727078900+c*0.9707868061190170+m*0.9906181076447950+y*0.0211649058448753+r*0.0313318044982702+g*0.0096129126297349+b*0.9792943649455940);R[4]=max(SPECTRAL_EPSILON,w*1.0011525984455200+c*0.9713686732282480+m*0.9904514808787100+y*0.0215027957272504+r*0.0306729857725527+g*0.0097837090401843+b*0.9789630146085700);R[5]=max(SPECTRAL_EPSILON,w*1.0011325252899800+c*0.9731632306212520+m*0.9898710814002040+y*0.0226738799041561+r*0.0286480476989607+g*0.0103786227058710+b*0.9778144666940430);R[6]=max(SPECTRAL_EPSILON,w*1.0010850066332700+c*0.9767402231587650+m*0.9882866087596400+y*0.0258235649693629+r*0.0246450407045709+g*0.0120026452378567+b*0.9747243211338360);R[7]=max(SPECTRAL_EPSILON,w*1.0009968788945300+c*0.9815876054913770+m*0.9842906927975040+y*0.0334879385639851+r*0.0192960753663651+g*0.0160977721473922+b*0.9671984823439730);R[8]=max(SPECTRAL_EPSILON,w*1.0008652515227400+c*0.9862802656529490+m*0.9739349056253060+y*0.0519069663740307+r*0.0142066612220556+g*0.0267061902231680+b*0.9490796575305750);R[9]=max(SPECTRAL_EPSILON,w*1.0006962900094000+c*0.9899491476891340+m*0.9418178384601450+y*0.1007490148334730+r*0.0102942608878609+g*0.0595555440185881+b*0.9008501289409770);R[10]=max(SPECTRAL_EPSILON,w*1.0005049611488800+c*0.9924927015384200+m*0.8173903261951560+y*0.2391298997068470+r*0.0076191460521811+g*0.1860398265328260+b*0.7631504454622400);R[11]=max(SPECTRAL_EPSILON,w*1.0003080818799200+c*0.9941456804052560+m*0.4324728050657290+y*0.5348043122727480+r*0.0058980410835420+g*0.5705798201161590+b*0.4659221716493190);R[12]=max(SPECTRAL_EPSILON,w*1.0001196660201300+c*0.9951839750332120+m*0.1384539782588700+y*0.7978075786430300+r*0.0048233247781713+g*0.8614677684002920+b*0.2012632804510050);R[13]=max(SPECTRAL_EPSILON,w*0.9999527659684070+c*0.9957567501108180+m*0.0537347216940033+y*0.9114498940673840+r*0.0042298748350633+g*0.9458790897676580+b*0.0877524413419623);R[14]=max(SPECTRAL_EPSILON,w*0.9998218368992970+c*0.9959128182867100+m*0.0292174996673231+y*0.9537979630045070+r*0.0040599171299341+g*0.9704654864743050+b*0.0457176793291679);R[15]=max(SPECTRAL_EPSILON,w*0.9997386095575930+c*0.9956061578345280+m*0.0213136517508590+y*0.9712416154654290+r*0.0043533695594676+g*0.9784136302844500+b*0.0284706050521843);R[16]=max(SPECTRAL_EPSILON,w*0.9997095516396120+c*0.9945976009618540+m*0.0201349530181136+y*0.9793031238075880+r*0.0053434425970201+g*0.9795890314112240+b*0.0205271767569850);R[17]=max(SPECTRAL_EPSILON,w*0.9997319302106270+c*0.9922157154923700+m*0.0241323096280662+y*0.9833801195075750+r*0.0076917201010463+g*0.9755335369086320+b*0.0165302792310211);R[18]=max(SPECTRAL_EPSILON,w*0.9997994363461950+c*0.9862364527832490+m*0.0372236145223627+y*0.9854612465677550+r*0.0135969795736536+g*0.9622887553978130+b*0.0145135107212858);R[19]=max(SPECTRAL_EPSILON,w*0.9999003303166710+c*0.9679433372645410+m*0.0760506552706601+y*0.9864350469766050+r*0.0316975442661115+g*0.9231215745131200+b*0.0136003508637687);R[20]=max(SPECTRAL_EPSILON,w*1.0000204065261100+c*0.8912850042449430+m*0.2053754719423990+y*0.9867382506701410+r*0.1078611963552490+g*0.7934340189431110+b*0.0133604258769571);R[21]=max(SPECTRAL_EPSILON,w*1.0001447879365800+c*0.5362024778620530+m*0.5412689034604390+y*0.9866178824450320+r*0.4638126031687040+g*0.4592701359024290+b*0.0135488943145680);R[22]=max(SPECTRAL_EPSILON,w*1.0002599790341200+c*0.1541081190018780+m*0.8158416850864860+y*0.9862777767586430+r*0.8470554052720110+g*0.1855741036663030+b*0.0139594356366992);R[23]=max(SPECTRAL_EPSILON,w*1.0003557969708900+c*0.0574575093228929+m*0.9128177041239760+y*0.9858605924440560+r*0.9431854093939180+g*0.0881774959955372+b*0.0144434255753570);R[24]=max(SPECTRAL_EPSILON,w*1.0004275378026900+c*0.0315349873107007+m*0.9463398301669620+y*0.9854749276762100+r*0.9688621506965580+g*0.0543630228766700+b*0.0148854440621406);R[25]=max(SPECTRAL_EPSILON,w*1.0004762334488800+c*0.0222633920086335+m*0.9599276963319910+y*0.9851769347655580+r*0.9780306674736030+g*0.0406288447060719+b*0.0152254296999746);R[26]=max(SPECTRAL_EPSILON,w*1.0005072096750800+c*0.0182022841492439+m*0.9662605952303120+y*0.9849715740141810+r*0.9820436438543060+g*0.0342215204316970+b*0.0154592848180209);R[27]=max(SPECTRAL_EPSILON,w*1.0005251915637300+c*0.0162990559732640+m*0.9693259700584240+y*0.9848463034157120+r*0.9839236237187070+g*0.0311185790956966+b*0.0156018026485961);R[28]=max(SPECTRAL_EPSILON,w*1.0005350960689600+c*0.0153656239334613+m*0.9708545367213990+y*0.9847753518111990+r*0.9848454841543820+g*0.0295708898336134+b*0.0156824871281936);R[29]=max(SPECTRAL_EPSILON,w*1.0005402209748200+c*0.0149111568733976+m*0.9716050665281280+y*0.9847380666252650+r*0.9852942758145960+g*0.0288108739348928+b*0.0157248764360615);R[30]=max(SPECTRAL_EPSILON,w*1.0005427281678400+c*0.0146954339898235+m*0.9719627697573920+y*0.9847196483117650+r*0.9855072952198250+g*0.0284486271324597+b*0.0157458108784121);R[31]=max(SPECTRAL_EPSILON,w*1.0005438956908700+c*0.0145964146717719+m*0.9721272722745090+y*0.9847110233919390+r*0.9856050715398370+g*0.0282820301724731+b*0.0157556123350225);R[32]=max(SPECTRAL_EPSILON,w*1.0005444821215100+c*0.0145470156699655+m*0.9722094177458120+y*0.9847066833006760+r*0.9856538499335780+g*0.0281988376490237+b*0.0157605443964911);R[33]=max(SPECTRAL_EPSILON,w*1.0005447695999200+c*0.0145228771899495+m*0.9722495776784240+y*0.9847045543930910+r*0.9856776850338830+g*0.0281581655342037+b*0.0157629637515278);R[34]=max(SPECTRAL_EPSILON,w*1.0005448988776200+c*0.0145120341118965+m*0.9722676219987420+y*0.9847035963093700+r*0.9856883918061220+g*0.0281398910216386+b*0.0157640525629106);R[35]=max(SPECTRAL_EPSILON,w*1.0005449625468900+c*0.0145066940939832+m*0.9722765094621500+y*0.9847031240775520+r*0.9856936646900310+g*0.0281308901665811+b*0.0157645892329510);R[36]=max(SPECTRAL_EPSILON,w*1.0005449892705800+c*0.0145044507314479+m*0.9722802433068740+y*0.9847029256150900+r*0.9856958798482050+g*0.0281271086805816+b*0.0157648147772649);R[37]=max(SPECTRAL_EPSILON,w*1.0005449969930000+c*0.0145038009464639+m*0.9722813248265600+y*0.9847028681227950+r*0.9856965214637620+g*0.0281260133612096+b*0.0157648801149616);}vec3 spectral_xyz_to_srgb(vec3 xyz){mat3 XYZ_RGB;XYZ_RGB[0]=vec3(3.2409699419045200,-1.537383177570090,-0.4986107602930030);XYZ_RGB[1]=vec3(-0.9692436362808790,1.875967501507720,0.0415550574071756);XYZ_RGB[2]=vec3(0.0556300796969936,-0.203976958888976,1.0569715142428700);float r=dot(XYZ_RGB[0],xyz);float g=dot(XYZ_RGB[1],xyz);float b=dot(XYZ_RGB[2],xyz);return spectral_linear_to_srgb(vec3(r,g,b));}vec3 spectral_reflectance_to_xyz(float R[SPECTRAL_SIZE]){vec3 xyz=vec3(0.);xyz+=R[0]*vec3(0.0000646919989576,0.0000018442894440,0.0003050171476380);xyz+=R[1]*vec3(0.0002194098998132,0.0000062053235865,0.0010368066663574);xyz+=R[2]*vec3(0.0011205743509343,0.0000310096046799,0.0053131363323992);xyz+=R[3]*vec3(0.0037666134117111,0.0001047483849269,0.0179543925899536);xyz+=R[4]*vec3(0.0118805536037990,0.0003536405299538,0.0570775815345485);xyz+=R[5]*vec3(0.0232864424191771,0.0009514714056444,0.1136516189362870);xyz+=R[6]*vec3(0.0345594181969747,0.0022822631748318,0.1733587261835500);xyz+=R[7]*vec3(0.0372237901162006,0.0042073290434730,0.1962065755586570);xyz+=R[8]*vec3(0.0324183761091486,0.0066887983719014,0.1860823707062960);xyz+=R[9]*vec3(0.0212332056093810,0.0098883960193565,0.1399504753832070);xyz+=R[10]*vec3(0.0104909907685421,0.0152494514496311,0.0891745294268649);xyz+=R[11]*vec3(0.0032958375797931,0.0214183109449723,0.0478962113517075);xyz+=R[12]*vec3(0.0005070351633801,0.0334229301575068,0.0281456253957952);xyz+=R[13]*vec3(0.0009486742057141,0.0513100134918512,0.0161376622950514);xyz+=R[14]*vec3(0.0062737180998318,0.0704020839399490,0.0077591019215214);xyz+=R[15]*vec3(0.0168646241897775,0.0878387072603517,0.0042961483736618);xyz+=R[16]*vec3(0.0286896490259810,0.0942490536184085,0.0020055092122156);xyz+=R[17]*vec3(0.0426748124691731,0.0979566702718931,0.0008614711098802);xyz+=R[18]*vec3(0.0562547481311377,0.0941521856862608,0.0003690387177652);xyz+=R[19]*vec3(0.0694703972677158,0.0867810237486753,0.0001914287288574);xyz+=R[20]*vec3(0.0830531516998291,0.0788565338632013,0.0001495555858975);xyz+=R[21]*vec3(0.0861260963002257,0.0635267026203555,0.0000923109285104);xyz+=R[22]*vec3(0.0904661376847769,0.0537414167568200,0.0000681349182337);xyz+=R[23]*vec3(0.0850038650591277,0.0426460643574120,0.0000288263655696);xyz+=R[24]*vec3(0.0709066691074488,0.0316173492792708,0.0000157671820553);xyz+=R[25]*vec3(0.0506288916373645,0.0208852059213910,0.0000039406041027);xyz+=R[26]*vec3(0.0354739618852640,0.0138601101360152,0.0000015840125870);xyz+=R[27]*vec3(0.0214682102597065,0.0081026402038399,0.0000000000000000);xyz+=R[28]*vec3(0.0125164567619117,0.0046301022588030,0.0000000000000000);xyz+=R[29]*vec3(0.0068045816390165,0.0024913800051319,0.0000000000000000);xyz+=R[30]*vec3(0.0034645657946526,0.0012593033677378,0.0000000000000000);xyz+=R[31]*vec3(0.0014976097506959,0.0005416465221680,0.0000000000000000);xyz+=R[32]*vec3(0.0007697004809280,0.0002779528920067,0.0000000000000000);xyz+=R[33]*vec3(0.0004073680581315,0.0001471080673854,0.0000000000000000);xyz+=R[34]*vec3(0.0001690104031614,0.0000610327472927,0.0000000000000000);xyz+=R[35]*vec3(0.0000952245150365,0.0000343873229523,0.0000000000000000);xyz+=R[36]*vec3(0.0000490309872958,0.0000177059860053,0.0000000000000000);xyz+=R[37]*vec3(0.0000199961492222,0.0000072209749130,0.0000000000000000);return xyz;}float KS(float R){return pow(1.0-R,2.0)/(2.0*R);}float KM(float KS){return 1.0+KS-sqrt(pow(KS,2.0)+2.0*KS);}vec3 spectral_mix(vec3 color1,float tintingStrength1,float factor1,vec3 color2,float tintingStrength2,float factor2){vec3 lrgb1=spectral_srgb_to_linear(color1);vec3 lrgb2=spectral_srgb_to_linear(color2);float R1[SPECTRAL_SIZE];float R2[SPECTRAL_SIZE];spectral_linear_to_reflectance(lrgb1,R1);spectral_linear_to_reflectance(lrgb2,R2);float luminance1=spectral_reflectance_to_xyz(R1)[1];float luminance2=spectral_reflectance_to_xyz(R2)[1];float R[SPECTRAL_SIZE];for(int i=0;iDARKEN_THRESHOLD)){float blacken=0.5*(min(maskColor.a,1.0)-DARKEN_THRESHOLD);pigment=pigment*(1.0-blacken)-vec4(0.5)*blacken;pigment.rgb=max(pigment.rgb,vec3(0.0));}float mixIntensity=min(maskColor.a,1.0);if(!u_isBrush){vec2 texelSize=1.0/vec2(textureSize(u_mask,0));float scaledAlpha=maskColor.a*15.0;float blurEdge=0.0;for(int i=-2;i<=2;i+=2){for(int j=-2;j<=2;j+=2){vec2 neighborUV=maskUV+vec2(float(i),float(j))*texelSize;float neighborAlpha=texture(u_mask,neighborUV).a*15.0;blurEdge+=smoothstep(EDGE_MIN,EDGE_MAX,length(vec2(dFdx(neighborAlpha),dFdy(neighborAlpha))));}}blurEdge/=9.0;mixIntensity=clamp(maskColor.a+blurEdge*0.1,0.0,1.0);}vec3 bgColor=mix(vec3(1.0),source.rgb,source.a);outColor=vec4(spectral_mix(bgColor,pigment.rgb,mixIntensity),1.);}"),this.glMask=lt?.ensureResources?.(q,W,j,K);const e=ht?.ensureResources?.(q,W,j,K,ut)??{mask:null,ctx:null};t&&(q.blendSourceFramebuffer=((...t)=>at.ensureBlendSourceFramebuffer(...t))(q,q.blendSourceFramebuffer,W,j,K)),this.mask=e.mask,this.ctx=e.ctx},blend(t=!1,e=!1){yt();const r=!0===this.isBrush,n=r?this.glMask:this.mask,i=r?this.mask:this.glMask,o=t?._array,a=!!o&&(this.cachedColor?.[0]!==o[0]||this.cachedColor?.[1]!==o[1]||this.cachedColor?.[2]!==o[2]||this.cachedColor?.[3]!==o[3]);!this.isBlending&&o&&(this.isBlending=!0,this.cachedColor=o,s(),this.clearMask(this.glMask)),(e||a)&&(this.justChanged&&(this.applyShader(i,!r),this.justChanged=!1),this.isBlending&&this.applyShader(n,r),o&&(this.cachedColor=o),e&&(this.isBlending=!1,this.cachedColor=null))},applyShader(t,e){if(!t?.isDrawn)return;const r=this.getCompositeRect(t,e);if(!r)return void this.clearMask(t);q.drawingContext;const n=q.shaderProgram,i=nt(),o=((...t)=>at.blitSourceToFramebuffer(...t))({renderer:q,sourceTarget:i??q,sourceFramebuffer:q.blendSourceFramebuffer,dirtyRect:r,isFramebufferTarget:it,Cwidth:W,Cheight:j,getTargetPixelSize:ft,toScissorBox:gt,withScissor:xt}),s=!!i,a=(e?lt:ht).getShaderMask(q,t,r,dt,ut);((...t)=>{at.runBlendShaderPass(...t)})({renderer:q,shader:n,source:o,mask:a,color:this.cachedColor,isBrushMask:e,Cwidth:W,Cheight:j,dirtyRect:r,targetIsFramebuffer:s,withScissor:xt}),this.clearMask(t)}},vt=()=>{yt(),bt.blend(!1,!0),bt.clearMask(bt.glMask),bt.clearMask(bt.mask),bt.justChanged=!1,bt.isBlending=!1,bt.isBrush=null,bt.cachedColor=null};let wt=!1;function _t(){wt||(yt(),Rt=.01*W,Et=-.5*W,Mt=-.5*j,St=Math.round(2*W/Rt),Pt=Math.round(2*j/Rt),Lt("hand",(t,e)=>{const r=_(.2,.8),n=E(5,10);return Nt(e,(e,i)=>.5*n*B(r*i*e+E(15,25))*.2*N(t)+b(e,i)*n*.7)}),Lt("curved",(t,e)=>{let r=E(-10,10);return E(0,100)%2==0&&(r*=-1),Nt(e,(e,n)=>3*T(b(.02*e+.03*t,.02*n+.03*t),0,1,-r,r))}),Lt("zigzag",(t,e)=>{let r=E(-30,-15)+Math.abs(44*B(t));E(0,100)%2==0&&(r*=-1);let n=r,i=0;for(let t=0;t{const r=E(10,15)+5*B(t),n=E(3,6)+3*N(t),i=E(20,35);return Nt(e,(t,e)=>B(r*t)*i*N(e*n)+E(-3,3))}),Lt("seabed",(t,e)=>{const r=_(.4,.8),n=E(18,26);return Nt(e,(e,i)=>1.1*n*B(r*i*e+E(15,20))*N(t))}),Lt("spiral",(t,e)=>{const r=E(5,10),n=2*E(0,2)-1,i=E(65,80),o=Array.from({length:r},()=>({x:_(.1,.9)*St,y:_(.1,.9)*Pt}));return Nt(e,(t,e)=>{let r=0,s=0;for(const a of o){const o=t-a.x,c=e-a.y,l=1/(o*o+c*c+1),h=Math.atan2(c,o)*(180/Math.PI),u=n*(h+i)*Math.PI/180;r+=l*Math.cos(u),s+=l*Math.sin(u)}return Math.atan2(s,r)*(180/Math.PI)})}),Lt("columns",(t,e)=>{const r=E(3,8),n=E(25,45);return Nt(e,(t,e)=>B(t*r)*n)}),wt=!0)}class At{constructor(t,e){_t();const r=o();this.mx=r.x,this.my=r.y,this.update(t,e),this.plotted=0}update(t,e){this.x=t,this.y=e,pt.field.isActive&&(this.colIdx=Math.round((t+this.mx-Et)/Rt),this.rowIdx=Math.round((e+this.my-Mt)/Rt))}reset(){this.plotted=0}isIn(){return pt.field.isActive?At.isIn(this.colIdx,this.rowIdx):this.isInCanvas(this.x,this.y)}isInCanvas(){const t=W,e=j,r=this.x+this.mx,n=this.y+this.my;return r>=-.5*t&&r<=1.5*t&&n>=-.5*e&&n<=1.5*e}angle(t=!1){return pt.field.isActive&&(t||this.isIn())?Tt.get(pt.field.current).field[this.colIdx][this.rowIdx]*pt.field.wiggle:0}moveTo(t,e,r=1){const n=X(t);pt.field.isActive?this.movePos(n,e,r):this._moveConstant(n,e,r)}_moveToDegrees(t,e,r=1){pt.field.isActive?this.movePos(t,e,r):this._moveConstant(t,e,r)}_moveConstant(t,e,r){if(!this.isIn())return void(this.plotted+=r);const n=e/r,i=z(-t),o=r*i[0],s=r*i[1];for(let t=0;t=0&&e>=0&&tnew Float32Array(Pt))),t.angleMode)}function Ft(t){if(pt.field.wiggle||(pt.field.wiggle=1),_t(),!Tt.has(t))throw new Error(`Field "${t}" does not exist. Available fields: ${Array.from(Tt.keys()).join(", ")}.`);pt.field.isActive=!0,pt.field.current=t;const e=Tt.get(t);e.field||(e.field=It(e,0))}function Lt(t,e,r={}){Tt.set(t,{gen:e,field:null,angleMode:Ct(r)})}function Dt(t=1){Ft("hand"),pt.field.wiggle=t}function Nt(t,e){for(let r=0;r({x:t,y:e})),this.sides=this.vertices.map((t,e,r)=>[t,r[(e+1)%r.length]]),this._intersectionCache={}}intersect(t){const e=`${t.point1.x},${t.point1.y}-${t.point2.x},${t.point2.y}`;if(this._intersectionCache[e])return this._intersectionCache[e];const r=[],n=this.sides,i=n.length;for(let e=0;e0&&this.angles.pop(),t=n?(t%360+360)%360:O(t),this.angles.push(t,t),this.pres.push(r),this._cumLen.push(this.length),this.segments.push(e),this.length+=e}endPlot(t=0,e=1,r=!1){t=r?(t%360+360)%360:O(t),this.angles[this.angles.length-1]=t,this.pres.push(e)}rotate(t){this.dir=O(t)}pressure(t){if(t>this.length)return this.pres[this.pres.length-1];const e=this.pres[this.index],r=this.pres[this.index+1],n=this.segments[this.index];return 0===n?e:e+(t-this.suma)/n*(r-e)}angle(t){if(t>this.length)return this.angles[this.angles.length-1];if(this.calcIndex(t),"curve"!==this.type)return this.angles[this.index]+this.dir;let e=this.angles[this.index],r=this.angles[this.index+1];Math.abs(r-e)>180&&(r>e?r=-(360-r):e=-(360-e));const n=this.segments[this.index];return e+(0===n?0:(t-this.suma)/n)*(r-e)+this.dir}calcIndex(t){const e=this._cumLen,r=e.length;if(0===r)return this.index=0,this.suma=0,0;let n=this.indext){let r=0,i=n-1;for(;r>1;e[n]<=t?r=n:i=n-1}n=r}return this.index=n,this.suma=e[n],n}genPol(t,e,r=1,n){_t();const i=n<0?4:1,o=[],s=Math.round(this.length/i),a=new At(t+W/2,e+j/2);let c=0,l=0;for(let t=0;t=(n<=0?8:Math.max(this.segments[t]*n*_(.7,1.3),20))||t>=l)&&a.x&&(o.push([a.x-W/2,a.y-j/2]),c=0,t>=l&&l++)}return new Bt(o)}show(t,e,r=1){pt.wash&&this.wash(t,e,r),pt.fill&&this.fill(t,e,r),pt.mass&&this.mass(t,e,r),pt.hatch&&this.hatch(t,e,r),pt.stroke&&this.draw(t,e,r)}}function zt(t,e,r,n,i){const o=X(n),s=((X(i)-o)%360+360)%360;if(0===s)return null;const a=new Yt("curve"),c=Math.max(1,Math.ceil(s/90)),l=s/c,h=Math.PI*r*l/180;for(let t=0;t0){let o,s,a,c=0;for(let l=0;l0&&l{throw new Error("No stroke runtime adapter registered.")},loadImageTip:()=>{throw new Error("No stroke runtime adapter registered.")}},Kt=!1;const Zt=(t,e,r)=>{const n=t.createProgram();for(let[i,o]of[[t.VERTEX_SHADER,e],[t.FRAGMENT_SHADER,r]]){const e=t.createShader(i);t.shaderSource(e,o),t.compileShader(e),t.attachShader(n,e)}return t.linkProgram(n),n};let Jt={beginDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},endDirectMaskDraw:()=>{throw new Error("No renderer runtime adapter registered.")},resetDirectShaderTracking:()=>{}};const Qt=(t,e)=>Jt.resetDirectShaderTracking(t,e);let te,ee,re,ne,ie,oe=!1,se=0,ae=0,ce=null;const le={},he={};let ue=1,fe=0,me=0,de=1,ge=0,xe=0,pe=0,ye=0,be=1,ve=1,we=new Float32Array(8192),_e=0,Ae=2048,Re=32768,Ee=null,Me=null,Se=null,Pe=null,Te=null;const ke={},Ce={};let Ie=0,Fe=new Float32Array(1280),Le=0,De=256,Ne=null;const Be=new Map,Ye=new Float32Array([-1,-1,1,-1,-1,1,1,1]);function ze(){return ee}function Oe(){return((t,e,r)=>Jt.beginDirectMaskDraw(t,e,r))(q,te,bt.glMask)}function Xe(t){((t,e,r)=>{Jt.endDirectMaskDraw(t,e,r)})(q,te,t)}function Ue(t,e,r,n,i){return t?(et.maxX&&(t.maxX=n),i>t.maxY&&(t.maxY=i),t):{minX:e,minY:r,maxX:n,maxY:i}}function Ge(t,e,r,n){if(_e>=Ae){Ae*=2;const t=new Float32Array(4*Ae);t.set(we),we=t}const i=t-pe,o=e-ye,s=4*_e,a=ue*i+me*o+ge+pe,c=fe*i+de*o+xe+ye,l=ve*r*be/2;we[s]=a,we[s+1]=c,we[s+2]=l,we[s+3]=n/255;const h=a*ve,u=c*ve;Ee=Ue(Ee,h-l-1,u-l-1,h+l+1,u+l+1),_e++}function Ve(t,e){if(0===Le)return;bt.glMask.isDrawn=!0;const r=Oe();let n=Be.get(e);n||(n=te.createTexture(),te.bindTexture(te.TEXTURE_2D,n),te.texImage2D(te.TEXTURE_2D,0,te.RGBA,te.RGBA,te.UNSIGNED_BYTE,t.canvas),te.texParameteri(te.TEXTURE_2D,te.TEXTURE_MIN_FILTER,te.LINEAR),te.texParameteri(te.TEXTURE_2D,te.TEXTURE_MAG_FILTER,te.LINEAR),te.texParameteri(te.TEXTURE_2D,te.TEXTURE_WRAP_S,te.CLAMP_TO_EDGE),te.texParameteri(te.TEXTURE_2D,te.TEXTURE_WRAP_T,te.CLAMP_TO_EDGE),Be.set(e,n)),te.useProgram(Me),te.enable(te.BLEND),te.blendFunc(te.ONE_MINUS_DST_ALPHA,te.ONE),te.activeTexture(te.TEXTURE0),te.bindTexture(te.TEXTURE_2D,n),te.uniform1i(Ce.u_tex,0);const i=pt.stroke.color._array;te.uniform4f(Ce.u_color,...i),te.uniformMatrix4fv(Ce.u_proj,!1,ze()),te.bindVertexArray(Se),te.bindBuffer(te.ARRAY_BUFFER,Te);const o=5*Le*4,s=Fe.subarray(0,5*Le);o>Ie?(te.bufferData(te.ARRAY_BUFFER,Fe,te.DYNAMIC_DRAW),Ie=Fe.byteLength):te.bufferSubData(te.ARRAY_BUFFER,0,s),te.drawArraysInstanced(te.TRIANGLE_STRIP,0,4,Le),te.bindVertexArray(null),te.bindTexture(te.TEXTURE_2D,null),Xe(r),Ne&&(bt.markDirtyRect(bt.glMask,Ne),Ne=null),Le=0,Qt(q,te)}Kt||(lt={ensureResources:function(t,e,r,n){return function(t,e,r,n){return!t.glMask||t.glMask.width!==e||t.glMask.height!==r||"function"==typeof t.glMask.pixelDensity&&t.glMask.pixelDensity()!==n}(t,e,r,n)&&(t.glMask?.remove&&t.glMask.remove(),t.glMask=ct(t,{width:e,height:r,density:n,antialias:!1,depth:!1,stencil:!1})),t.glMask.dirtyRect??=null,t.glMask.isDrawn??=!1,t.glMask},clearMask:function(t,e){t&&(e(t),t.isDrawn=!1,t.dirtyRect=null)},getCompositeRect:function(t,e,r,n,i){return t?t.dirtyRect?e()?r():i(n(t.dirtyRect,2)):r():null},getShaderMask:function(t,e){return e}},Kt=!0),pt.stroke={color:null,weight:1,type:"HB",isActive:!1,opacity:1};let He=new Map;const We={offset:.08,scale:.08,warp:.06,tilt:.06};function je(){return{...pt.stroke}}function $e(t){pt.stroke={...t}}function qe(t,e){if(e.type=["marker","custom","image","spray"].includes(e.type)?e.type:"default",void 0===e.markerTip&&(e.markerTip=!0),void 0===e.noise&&(e.noise=.3),e.noise=Math.max(0,Math.min(1,e.noise)),void 0!==e.vibration&&void 0===e.scatter&&(e.scatter=e.vibration),void 0!==e.definition&&void 0===e.sharpness&&(e.sharpness=e.definition),void 0!==e.quality&&void 0===e.grain&&(e.grain=e.quality),e.pressure=function(t){if(!t)return t;if("function"==typeof t)return{type:"custom",min_max:[0,1],curve:t,variation:{...We}};if("object"==typeof t&&!Array.isArray(t)){if("custom"===t.type||"custom"===t.mode){const{mode:e,...r}=t;return{...r,type:"custom",variation:{...We,...r.variation??{}}}}return"gaussian"===t.type||"gaussian"===t.mode||Array.isArray(t.curve)&&Array.isArray(t.min_max)?{...t,type:"gaussian",curve:t.curve,min_max:t.min_max}:t}if(Array.isArray(t)){const[e,r,n]=2===t.length?[t[0],(t[0]+t[1])/2,t[1]]:t,i=Math.min(e,r,n),o=Math.max(e,r,n),s=o-i||1,[a,c,l]=[(e-i)/s,(r-i)/s,(n-i)/s];return{type:"custom",min_max:[i,o],variation:{...We},curve:t=>t<.5?a+(c-a)*t*2:c+(l-c)*(t-.5)*2}}}(e.pressure),"custom"===e.type){if("function"!=typeof e.tip)throw new Error(`Brush "${t}" is type "custom" but is missing a tip function.`);const r=`custom::${t}`;!function(t){const e=Be.get(t);e&&te&&te.deleteTexture(e),Be.delete(t)}(r);const n=qt.createTipSurface(500,500);return n.pixelDensity(1),n.background(255),n.noSmooth(),n.push(),n.translate(250,250),n.scale(5),n.noStroke(),e.tip(n),n.pop(),wr.imageToWhite(n),wr.tips.set(r,n),e.tipKey=r,void He.set(t,{param:e,colors:[],buffers:[]})}if("image"===e.type){if(!e.image||!e.image.src)throw new Error(`Brush "${t}" is type "image" but is missing params.image.src. Example: image: { src: "./tip.jpg" }`);return wr.add(e.image.src),He.set(t,{param:e,colors:[],buffers:[]}),wr.load()}He.set(t,{param:e,colors:[],buffers:[]})}function Ke(t){return He.get(t)?.param??null}function Ze(t){if(!He.has(t))throw new Error(`Brush "${t}" not found. Available brushes: ${[...He.keys()].join(", ")}.`);pt.stroke.type=t}function Je(t,e,r){Q(),pt.stroke.color=i(...arguments),pt.stroke.isActive=!0}function Qe(t){pt.stroke.weight=t}function tr(t,e,r=1){Ze(t),Je(e),Qe(r)}let er,rr,nr,ir,or=0;const sr={};function ar(t,e,r,n=!1){!function(){const t=o();ue=t.a,fe=t.b,me=t.c,de=t.d,ge=t.x,xe=t.y,pe=W/2,ye=j/2,be=Math.sqrt(ue*ue+fe*fe),ve=K}(),er=new At(t+W/2,e+j/2),rr=r,nr=n,nr&&nr.calcIndex(0)}const cr=[];function lr(t,e){e||(ir=t),function(){sr.seed=999999*w();const{param:t}=He.get(pt.stroke.type)??{};if(!t)return;sr.p=t;const{pressure:e}=t;if(sr.isCustomPressure="custom"===e.type,sr.a=sr.isCustomPressure?0:w(-1,1),sr.b=sr.isCustomPressure?0:w(1,1.5),sr.isCustomPressure){const t=e.variation??We;sr.cp=w(-t.offset,t.offset),sr.ct=w(-t.warp,t.warp),sr.cs=w(1-t.scale,1+t.scale),sr.ck=w(-t.tilt,t.tilt)}else sr.cp=w(3,3.5),sr.ct=0,sr.cs=1,sr.ck=0;[sr.min,sr.max]=e.min_max,nr||(sr.cos=N(ir),sr.sin=B(ir)),function(){yt(),function(){const t=q?.glMask;t&&(ce=t,ce.dirtyRect??=null,ce.isDrawn??=!1,bt.glMask=ce)}();const t=q.drawingContext,e=!oe||te!==t;(e||se!==W||ae!==j)&&(ee=new Float32Array([2/W,0,0,0,0,2/j,0,0,0,0,1,0,-1,-1,0,1]),se=W,ae=j),e&&(function(){if(te&&!te.isContextLost?.()){for(const t of Be.values())te.deleteTexture(t);Be.clear(),ie&&te.deleteProgram(ie),re&&te.deleteVertexArray(re),ne&&te.deleteBuffer(ne),Me&&te.deleteProgram(Me),Se&&te.deleteVertexArray(Se),Pe&&te.deleteBuffer(Pe),Te&&te.deleteBuffer(Te),ie=re=ne=null,Me=Se=Pe=Te=null,Re=0,Ie=0}else Be.clear()}(),te=t,ie=Zt(te,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_position;in float a_radius;in float a_alpha;uniform mat4 u_matrix;out float v_alpha;void main(){gl_Position=u_matrix*vec4(a_position,0.0,1.0);v_alpha=a_alpha;gl_PointSize=a_radius*2.0;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin float v_alpha;out vec4 outColor;uniform vec4 u_color;void main(){vec2 v=gl_PointCoord-vec2(0.5);float f=length(v);float a=fwidth(f);f=1.0-smoothstep(0.5-a,0.5+a,f);if(f<0.01){discard;}outColor=vec4(u_color.xyz,v_alpha*f);}"),te.useProgram(ie),te.enable(te.BLEND),te.blendFunc(te.ONE_MINUS_DST_ALPHA,te.ONE),["a_position","a_radius","a_alpha"].forEach(t=>le[t]=te.getAttribLocation(ie,t)),["u_matrix","u_color"].forEach(t=>he[t]=te.getUniformLocation(ie,t)),re=te.createVertexArray(),te.bindVertexArray(re),ne=te.createBuffer(),te.bindBuffer(te.ARRAY_BUFFER,ne),te.bufferData(te.ARRAY_BUFFER,we.byteLength,te.DYNAMIC_DRAW),Re=we.byteLength,te.enableVertexAttribArray(le.a_position),te.vertexAttribPointer(le.a_position,2,te.FLOAT,!1,16,0),te.enableVertexAttribArray(le.a_radius),te.vertexAttribPointer(le.a_radius,1,te.FLOAT,!1,16,8),te.enableVertexAttribArray(le.a_alpha),te.vertexAttribPointer(le.a_alpha,1,te.FLOAT,!1,16,12),te.bindVertexArray(null),Me=Zt(te,"#version 300 es\n#define GLSLIFY 1\nin vec2 a_corner;in vec2 a_pos;in float a_size;in float a_angle;in float a_alpha;uniform mat4 u_proj;out vec2 v_uv;out float v_alpha;void main(){float c=cos(a_angle);float s=sin(a_angle);vec2 rotated=vec2(c*a_corner.x-s*a_corner.y,s*a_corner.x+c*a_corner.y);gl_Position=u_proj*vec4(a_pos+rotated*a_size,0.0,1.0);v_uv=a_corner*0.5+0.5;v_alpha=a_alpha;}","#version 300 es\nprecision highp float;\n#define GLSLIFY 1\nin vec2 v_uv;in float v_alpha;uniform sampler2D u_tex;uniform vec4 u_color;out vec4 outColor;void main(){float inkAlpha=texture(u_tex,v_uv).a;if(inkAlpha<0.01)discard;outColor=vec4(u_color.rgb,inkAlpha*v_alpha);}"),["a_corner","a_pos","a_size","a_angle","a_alpha"].forEach(t=>ke[t]=te.getAttribLocation(Me,t)),["u_proj","u_color","u_tex"].forEach(t=>Ce[t]=te.getUniformLocation(Me,t)),Se=te.createVertexArray(),te.bindVertexArray(Se),Pe=te.createBuffer(),te.bindBuffer(te.ARRAY_BUFFER,Pe),te.bufferData(te.ARRAY_BUFFER,Ye,te.STATIC_DRAW),te.enableVertexAttribArray(ke.a_corner),te.vertexAttribPointer(ke.a_corner,2,te.FLOAT,!1,0,0),Te=te.createBuffer(),te.bindBuffer(te.ARRAY_BUFFER,Te),te.bufferData(te.ARRAY_BUFFER,Fe.byteLength,te.DYNAMIC_DRAW),Ie=Fe.byteLength,te.enableVertexAttribArray(ke.a_pos),te.vertexAttribPointer(ke.a_pos,2,te.FLOAT,!1,20,0),te.vertexAttribDivisor(ke.a_pos,1),te.enableVertexAttribArray(ke.a_size),te.vertexAttribPointer(ke.a_size,1,te.FLOAT,!1,20,8),te.vertexAttribDivisor(ke.a_size,1),te.enableVertexAttribArray(ke.a_angle),te.vertexAttribPointer(ke.a_angle,1,te.FLOAT,!1,20,12),te.vertexAttribDivisor(ke.a_angle,1),te.enableVertexAttribArray(ke.a_alpha),te.vertexAttribPointer(ke.a_alpha,1,te.FLOAT,!1,20,16),te.vertexAttribDivisor(ke.a_alpha,1),te.bindVertexArray(null),oe=!0)}();const r=!0!==bt.isBrush;bt.isBrush=!0,r&&(bt.justChanged=!0),bt.blend(pt.stroke.color);const n=["default","spray"].includes(sr.p.type)?sr.p.opacity:sr.p.opacity/Math.min(pt.stroke.weight,1.3),i=.1*(sr.p.noise??0);sr.alpha=i>0?Math.max(0,n*(1+P(0,i))):n,sr.overscan=function(){const t=Math.max(1,sr.max??1),e=pt.stroke.weight*sr.p.scatter,r=pt.stroke.weight*sr.p.weight*t;return Math.max(8,1.5*e+.75*r)}(),sr.drawFn="spray"===sr.p.type?mr:"marker"===sr.p.type?dr:"custom"===sr.p.type||"image"===sr.p.type?gr:xr,pr()}();const r=sr.p?.spacing??1,n=Math.round(rr*(e?t:1)/r);sr.pressureCount=10,sr.cachedPressure=void 0;const i=2*n;for(;cr.lengthRe?(te.bufferData(te.ARRAY_BUFFER,we,te.DYNAMIC_DRAW),Re=we.byteLength):te.bufferSubData(te.ARRAY_BUFFER,0,n),te.uniform4f(he.u_color,...e),te.uniformMatrix4fv(he.u_matrix,!1,ze()),te.drawArrays(te.POINTS,0,_e),te.bindVertexArray(null),Xe(t),Ee&&(bt.markDirtyRect(bt.glMask,Ee),Ee=null),_e=0,Qt(q,te)}();const t=sr.p?.type;"image"===t?Ve(wr.tips.get(sr.p.image.src),sr.p.image.src):"custom"===t&&Ve(wr.tips.get(sr.p.tipKey),sr.p.tipKey)}()}function hr(){const t=ur();sr.drawFn(t)}function ur(){return(sr.pressureCount>=10||void 0===sr.cachedPressure)&&(sr.cachedPressure=nr?fr()*nr.pressure(er.plotted):fr(),sr.pressureCount=0),sr.pressureCount++,sr.cachedPressure}function fr(){if(!sr.isCustomPressure)return function(t=.5+sr.p.pressure.curve[0]*sr.a,e=1-sr.p.pressure.curve[1]*sr.b,r=sr.cp,n=sr.min,i=sr.max){const o=t*rr,s=(er.plotted=De){De*=2;const t=new Float32Array(5*De);t.set(Fe),Fe=t}const s=t-pe,a=e-ye,c=ue*s+me*a+ge+pe,l=fe*s+de*a+xe+ye,h=ve*r*be/2,u=ve*o*be,f=5*Le;Fe[f]=c,Fe[f+1]=l,Fe[f+2]=h,Fe[f+3]=n,Fe[f+4]=i/255;const m=c*ve,d=l*ve,g=1.42*h+u;Ne=Ue(Ne,m-g-1,d-g-1,m+g+1,d+g+1),Le++}(er.x+n,er.y+i,o,a,e*Math.max(.8,t)*w(.9,1.1),s)}function xr(t){if(w(0,1)>=sr.p.grain*t)return;const e=pt.stroke.weight*sr.p.scatter*(sr.p.sharpness+(1-sr.p.sharpness)*A(cr)/t);let r,n;if(nr){const t=or,i=N(t),o=B(t),s=e*w(-1,1),a=.3*e*w(-1,1);r=s*o+a*i,n=s*i-a*o}else{const t=e*w(-1,1),i=.3*e*w(-1,1);r=t*sr.sin+i*sr.cos,n=t*sr.cos-i*sr.sin}const i=t*t*sr.p.weight*w(.85,1.15)*pt.stroke.weight,o=Math.max(.9,t)*sr.alpha*w(.75,1.1);Ge(er.x+r,er.y+n,i,o)}function pr(){if(!1===sr.p.markerTip)return;let t=ur(),e=sr.alpha;if("marker"===sr.p.type)for(let r=1;r<10;r++)dr(t*r/10,!0,8*e);else if("custom"===sr.p.type||"image"===sr.p.type)for(let r=1;r<5;r++)gr(t*r/10,2*e)}function yr(t,e,r,n){if(!pt.stroke.isActive||!pt.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");_t();let i=G(t,e,r,n);0!=i&&(ar(t,e,i),lr(V(t,e,r,n),!1))}p(()=>{cr.length=0});const br=["weight","scatter","sharpness","grain","opacity","spacing","pressure","type","tip","rotate","markerTip","noise"],vr=[["pen",[.3,.15,.9,.7,150,.1,{curve:[.15,.2],min_max:[1.2,1]}]],["rotring",[.15,.05,.7,.9,210,.1,{curve:[.35,.2],min_max:[1.3,1]}]],["2B",[.3,.75,.45,.8,180,.1,{curve:[.1,.3],min_max:[1.1,.9]}]],["HB",[.3,.6,.3,.7,170,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["2H",[.2,.6,.3,.75,120,.1,{curve:[.15,.2],min_max:[1.1,.9]}]],["cpencil",[.35,.55,.8,.7,75,.1,{curve:[.15,.2],min_max:[.95,1.1]}]],["pastel",[.7,5,.91,1,30,.085/3,{mode:"gaussian",curve:[.4,.05],min_max:[1.09,.93]},"default",void 0,"natural",!0,1]],["crayon",[.33,1.9,.75,2,159,.07,[1.1,.9],"default",void 0,"natural",!0,1]],["charcoal",[.35,1.5,.68,2,120,.03,{curve:[.15,.4],min_max:[1.1,.95]}]],["spray",[.2,6,15,40,90,.5,{curve:[.2,.35],min_max:[.7,1]},"spray"]],["marker",[2,.2,null,null,1,.03,{curve:[.35,.25],min_max:[1.2,.85]},"marker"]]];for(let t of vr){let e={};for(let r=0;r!this.tips.get(t));await Promise.all(t.map(t=>((t,e)=>qt.loadImageTip(t,e))(t,wr.imageToWhite).then(e=>{this.tips.set(t,e)})))}};function _r(){return{...pt.hatch}}function Ar(t){pt.hatch={...t}}function Rr(t=5,e=45,r={rand:!1,continuous:!1,gradient:!1}){let n=pt.hatch;n.isActive=!0,n.dist=t,n.angle=X(e),n.options=r}pt.hatch={isActive:!1,dist:5,angle:45,options:{},hBrush:!1};let Er=new Float64Array(256),Mr=new Float64Array(256),Sr=new Float64Array(512),Pr=new Float64Array(512),Tr=new Float64Array(512),kr=new Float64Array(512);function Cr(t,e,r,n){const i=function(t,e,r,n){Array.isArray(t)||(t=[t]);const i=e*Math.PI/180,o=Math.cos(i),s=Math.sin(i);let a=0;for(const e of t)a+=e.a.length;if(0===a)return[];Er.lengthl&&(l=Mr[u]),u++}for(let t=0;te){const r=t;t=e,e=r}f.push({scanY:d,x1:t*o+d*s,y1:-t*s+d*o,x2:e*o+d*s,y2:-e*s+d*o})}else if(t>2){m.sort((t,e)=>t-e);for(let e=0;et.scanY===e.scanY?t.x1-e.x1:t.scanY-e.scanY),i}function Ir(t){const{dist:e,options:r,segs:n}=function(t){const e=pt.hatch.dist,r=(pt.hatch.angle%180+180)%180,n=pt.hatch.options;return{dist:e,options:n,segs:Cr(t,e,r,n.gradient?T(n.gradient,0,1,1,1.1,!0):1)}}(t),i=r.rand||0,o=[];for(let t=0;t0&&r.continuous){const t=o[o.length-2];o.push({x1:t.x2,y1:t.y2,x2:u.x1,y2:u.y1,scanY:s.scanY,isConnector:!0})}}return o}function Fr(t){!function(t,e){const r=Ir(t);!function(){const t=je();(()=>{for(let t=0;t{pt.hatch.hBrush&&tr(pt.hatch.hBrush.brush,pt.hatch.hBrush.color,pt.hatch.hBrush.weight*w(.9,1.1)),yr(t,e,r,n)})}function Lr(t,e,r){return new Bt(t.vertices.map(t=>[t.x+e,t.y+r]))}function Dr(t,e,r){return t.map(t=>Lr(t,e,r))}function Nr(t){const e=Array.isArray(t)?t.flatMap(t=>t?.a??[]):t?.a??[];let r=Infinity,n=Infinity,i=-Infinity,o=-Infinity;for(const[t,s]of e)ti&&(i=t),s>o&&(o=s);return{minX:r,minY:n,maxX:i,maxY:o,cx:(r+i)/2,cy:(n+o)/2,size:Math.hypot(i-r,o-n)}}function Br(t,e,r,n,i){const o=(e+n)/2,s=(r+i)/2,a=n-e,c=i-r,l=Math.hypot(a,c);if(!l)return null;const h=-c/l,u=a/l,f=(t.x-o)*h+(t.y-s)*u;return{x:o+h*f,y:s+u*f}}function Yr(t,e,r,n,i,o){if(!Array.isArray(t))return e;const s=(r+i)/2,a=(n+o)/2,c=Math.hypot(i-r,o-n),l=Math.max(Nr(t).size,c,1),h=.08+.18*(1-Math.min(1,c/(.42*l)));return{x:e.x+(s-e.x)*h,y:e.y+(a-e.y)*h}}function zr(t,e,r){let n=!1;for(let i=0,o=t.length-1;ir!=l>r&&e<(c-s)*(r-a)/(l-a||Number.EPSILON)+s&&(n=!n)}return n}function Or(t,e,r){if(Array.isArray(t)){let n=!1;for(const i of t)zr(i.a,e,r)&&(n=!n);return n}return zr(t.a,e,r)}function Xr(t,e,r,n,i,o,s){const a=o(n),c=(a+((o(i)-a)%360+360)%360*s)*Math.PI/180;return{x:t+r*Math.cos(c),y:e-r*Math.sin(c)}}function Ur(t,e,r,n,i,o,s){for(const a of[.125,.25,.375,.5,.625,.75,.875]){const c=Xr(e,r,n,i,o,s,a);if(!Or(t,c.x,c.y))return!1}return!0}function Gr(t,e,r,n,i,o,s,a,c,l){const h=function(t,e,r,n,i,o,s){let a=V(t,e,r,n),c=V(t,e,i,o);return((c-a)%360+360)%360>180&&([a,c]=[c,a]),[s(a),s(c)]}(e,r,i,o,s,a,c),u=[h[1],h[0]],f=Ur(t,e,r,n,h[0],h[1],l),m=Ur(t,e,r,n,u[0],u[1],l);return f&&!m?h:m&&!f?u:f?h:m?u:null}function Vr(t){const e=_(.35,.65),r=t.x1+(t.x2-t.x1)*e,n=t.y1+(t.y2-t.y1)*e,i=t.x2-t.x1,o=t.y2-t.y1,s=Math.hypot(i,o)||1,a=_(.04,.1)*s,c=i/s*a*.5,l=o/s*a*.5;return[{x1:t.x1,y1:t.y1,x2:r-c,y2:n-l},{x1:r+c,y1:n+l,x2:t.x2,y2:t.y2}]}function Hr(t,e,r,n){const i=function(t,e){const r=Nr(t),n=r.size*_(.6,1.4),[i,o]=e;return{x:r.cx+i*n,y:r.cy+o*n}}(t,e);for(const e of Ir(t)){const o=!e.isConnector&&_()<.35?Vr(e):[e];for(const e of o){const o=Br(i,e.x1,e.y1,e.x2,e.y2),s=o?Yr(t,o,e.x1,e.y1,e.x2,e.y2):null;if(!s)continue;const a=G(s.x,s.y,e.x1,e.y1);if(!a)continue;const c=Gr(t,s.x,s.y,a,e.x1,e.y1,e.x2,e.y2,r,n);if(!c)continue;const[l,h]=c;zt(s.x,s.y,a,l,h)}}}function Wr(t,e,r,n,i,o,s){Rr(e,r,Array.isArray(t)?{...n,continuous:!1}:n),Hr(t,i,o,s)}function jr(t,e,i,o){const s=function(t,e,r,n){const i=!1===e,o=Ke(pt.mass.brush)?.scatter??0,s=i?t:t.genPol(e,r,n,.15),a=Math.min(2*o,5),c=[[_(-a,a),_(-a,a)],[_(-a,a),_(-a,a)]];return Array.isArray(s)?[s,Dr(s,c[0][0],c[0][1]),Dr(s,c[1][0],c[1][1])]:[s,Lr(s,c[0][0],c[0][1]),Lr(s,c[1][0],c[1][1])]}(t,e,i,o),a=_r(),c=je(),l={...pt.field},h=pt.mass.options?.precision??.5,u=pt.mass.options?.strength??1,f=pt.mass.options?.gradient??.1,m=pt.mass.options?.outline??!1,d=Ke(pt.mass.brush)?.scatter??0,g=1.6*_(.65*d,.85*d)-.4*f,x=_(-90,90),p=((x+90)%180+180)%180-90>=0?_()<.5?[1,1]:[-1,-1]:_()<.5?[-1,1]:[1,-1],y=r()?t=>t*Math.PI/180:t=>t,b=r()?t=>180*t/Math.PI:t=>t;tr(pt.mass.brush,pt.mass.color,1),Dt(2-h),m&&function(t){if(Array.isArray(t))for(const e of t)e.draw();else t.draw()}(s[0]),Wr(s[0],.9*g,n(x),{gradient:f,rand:2-2*h,continuous:!0},p,y,b),u>.33&&Wr(s[1],g,n(x+20*_(-1,1)),{gradient:f,rand:.6-.6*h,continuous:!0},p,y,b),u>.66&&Wr(s[2],.8*g,n(x+15*_(-1,1)),{gradient:f,rand:.6-.6*h,continuous:!0},p,y,b),$e(c),Ar(a),pt.field={...l}}function $r(t,e=null){const r=bt.ctx;e||(e=r.getTransform());const n=e.a,i=e.b,o=e.c,s=e.d,a=e.e,c=e.f;let l=Infinity,h=Infinity,u=-Infinity,f=-Infinity;r.beginPath();const m=t[0];let d=n*m.x+o*m.y+a,g=i*m.x+s*m.y+c;l=u=d,h=f=g,r.moveTo(m.x,m.y);for(let e=1;e({...pt.fill});function on(t,e,r,n){pt.fill.opacity=(arguments.length<4?e:n)||150,pt.fill.color=arguments.length<3?i(t):i(t,e,r),pt.fill.isActive=!0}function sn(t,e="out",r=null){pt.fill.bleed_strength=k(t,0,1),pt.fill.direction=e,pt.fill.angle=null==r?null:X(r)}function an(t=.4,e=.4,r=!0){pt.fill.texture_strength=k(t,0,1),pt.fill.border_strength=k(e,0,1),pt.fill.scatter=r}let cn,ln,hn,un,fn;const mn=[[],[]];function dn(){for(let t=0;t<512;t++)mn[0][t]=P(.5,.2),mn[1][t]=P(0,.02)}p(dn);class gn{constructor(t,e,r,n=[],i=!1,o,s){if(this.v=t,this.m=e,this.dir=n,this.midP=r,i){let e=0,n=0;const i=[];for(let o=0;o1||(c*(n-e.y)-l*(r-e.x))/f*h<=.01||u++}this.dir[t]=u%2==0}const s=w(-.6,.6)*e,a=w(-.6,.6)*n;this.midP={x:r.x+s,y:r.y+a}}else this.sizeX=o,this.sizeY=s}trim(t=1){if(t>=1||t<0||this.v.length<=8)return{v:this.v,m:this.m,dir:this.dir};const e=this.v.length,r=~~((1-t)*e),n=~~(e/2-r/2),i=n,o=n+r,s=this.v[(i-1+e)%e],a=this.v[o%e],c=a.x-s.x,l=a.y-s.y,h=Math.hypot(c,l),u=n>=2?~~w(0,n-1):oun||h.yfn)u=!0;else{let t=0;for(const[e,r]of l){const n=e.y,i=r.y;if(n>h.y==i>h.y)continue;const o=(h.y-n)/(i-n);h.x!t),!1,this.sizeX,this.sizeY)}grow(t=1){const{v:e,m:r,dir:n}=this.trim(t),i=e.length,o=2*i;Qr.lengthJr?Math.ceil(2*i/Jr):1;if(y>=2&&!(1&y)){for(let e=0;e=.05&&(w(-1,1),u[~~(w(0,1)*f)],w(.65,1.35),m[~~(w(0,1)*d)])}return new gn(e,r,this.midP,n,!1,this.sizeX,this.sizeY)}for(let o=0;oJr){const t=Math.ceil(g/Jr),r=Math.ceil(g/t);b=new Array(r),v=new Array(r),_=new Array(r);let n=0;for(let r=0;r>1]:{x:s[r>>1],y:a[r>>1]},v[n]=c[r],_[n]=l[r]}else{b=new Array(g);for(let t=0;t>1]:{x:s[t>>1],y:a[t>>1]};v=c.slice(0,g),_=l.slice(0,g)}return new gn(b,v,this.midP,_,!1,this.sizeX,this.sizeY)}fill(t,e,r){const n=3*r,i=2*e*(1+r/2),s=!1!==bt.isBrush;bt.isBrush=!1,s&&(bt.justChanged=!0),bt.blend(t);const a=o();bt.ctx.save(),bt.ctx.setTransform(K*a.a,K*a.b,K*a.c,K*a.d,K*(a.x+W/2),K*(a.y+j/2)),bt.ctx.strokeStyle="rgb(255 0 0 / "+.01*pt.fill.border_strength+")",bt.ctx.lineCap="round",Jr=2024*Math.max(.2,2*pt.fill.bleed_strength);const c=bt.ctx.getTransform(),l=Math.max(this.sizeX,this.sizeY),h=w(.15,.7);let u=this.grow();const f=this.scatter(.1).grow().scatter(.75).flipDirs();let m;for(let r=0;r<20;r++){r%4==0&&(u=u.grow()),r%2==0&&(m=[u.grow(1-.0125*r),u.grow(.7-.0125*r),u.grow(.4-.0125*r)]);for(const t of m)t.grow(999).grow(997).layer(r,l,i,c);pt.fill.scatter&&f.grow(999).flipDirs().grow(997).layer(r,l,i*n,c),r%2==0&&u.grow(h).grow(999).layer(r,l,2*i,c),r%8!=0&&19!==r||(0!==n&&u.erase(3*n,e),bt.blend(t,!0))}bt.ctx.restore()}layer(t,e,r,n=null){bt.ctx.lineWidth=T(t,0,24,e/25,e/30,!0)*pt.fill.border_strength,bt.ctx.fillStyle="rgb(255 0 0 / "+r+"%)",$r(this.v,n),bt.ctx.fill(),bt.ctx.stroke()}erase(t,e){bt.ctx.save();const r=~~(w(80,110)*T(t,0,1,2,3.5)),n=this.sizeX/1.3,i=this.sizeY/1.3,o=1.3*Math.min(this.sizeX,this.sizeY),s=.03*o,a=.45*o,{x:c,y:l}=this.midP;bt.ctx.globalCompositeOperation="destination-out";const h=(5-T(e,80,100,.3,.7,!0))*t/255;bt.ctx.fillStyle=`rgb(255 0 0 / ${h})`,bt.ctx.lineWidth=0;for(let t=0;tun&&(un=e.x),e.yfn&&(fn=e.y);const e=[...t.vertices],r=w(0,75),n=~~(.25*e.length*(r<5?1:r<15?2:3)),i=pt.fill.bleed_strength,o=e.map((t,e)=>(e>n?1:.3)*w(.85,1.4)*i),s=null==pt.fill.angle?R(0,e.length):function(t,e){const r=z(e),n=r[0],i=-r[1];let o=0,s=Infinity;for(let e=0;e{pt.fill={...t}})(a),this},Yt.prototype.fill=function(t,e,r){nn().isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,pt.fill.bleed_strength<.06?0:T(pt.fill.bleed_strength,0,.6,.2,.6,!0)),this.pol.fill())},pt.wash={color:null,opacity:150,isActive:!1},Bt.prototype.wash=function(t=!1,e){const r={...pt.wash};return!1!==t&&xn(t,e),pt.wash.isActive&&function(t){if(!pt.wash?.isActive||!pt.wash.color||t.vertices.length<3)return;const e=!1!==bt.isBrush;bt.isBrush=!1,e&&(bt.justChanged=!0),bt.blend(pt.wash.color);const r=o();bt.ctx.save(),bt.ctx.setTransform(K*r.a,K*r.b,K*r.c,K*r.d,K*(r.x+W/2),K*(r.y+j/2)),$r(t.vertices);const n=pt.wash.opacity/255;bt.ctx.fillStyle="rgb(255 0 0 / "+n+")",bt.ctx.fill(),bt.ctx.restore()}(this),pt.wash={...r},this},Yt.prototype.wash=function(t,e,r){pt.wash?.isActive&&(this.origin&&(t=this.origin[0],e=this.origin[1],r=1),this.pol=this.genPol(t,e,r,0,-1),this.pol.wash())};let pn=null,yn=null;const bn=[];let vn=!1;const wn=t=>!!t&&"function"==typeof t.begin&&"function"==typeof t.end&&!!t.renderer&&!!t.renderer._pInst,_n=t=>"number"==typeof t&&Number.isFinite(t)&&t>0,An=t=>{try{return t()}catch(t){return}},Rn=t=>!!t&&"function"==typeof t.pixelDensity&&"function"==typeof t.createFramebuffer&&_n(An(()=>t.width))&&_n(An(()=>t.height))&&"webgl2"===An(()=>t.webglVersion),En=t=>(Rn(t)&&(pn=t),pn),Mn=()=>(yn&&Rn(yn)?En(yn):null)||En(window.self?.p5?.instance??null)||En($)||pn,Sn=(t=!1)=>{const e=((t=!1)=>{const e=Mn();if(!t){if(!e)throw new Error("p5.brush could not resolve an active WEBGL sketch. Call brush.instance(p) and brush.load() after createCanvas(..., WEBGL).");return{renderer:e,width:e.width,height:e.height}}if(wn(t)){const r=t.renderer._pInst;if(En(r),e&&r!==e)throw new Error("p5.brush only supports p5.Framebuffer targets created from the active sketch");return{renderer:r,width:t.width,height:t.height}}return{renderer:t,width:t.width,height:t.height}})(t);if(J({Renderer:e.renderer}),En(t?Mn():q),"webgl2"!==q.webglVersion)throw new Error("p5.brush requires a WEBGL canvas");J({Cwidth:e.width,Cheight:e.height}),vn=!0},Pn=t=>{J({Instance:t}),En(t)},Tn=()=>q??Mn?.()??window.self?.p5?.instance??null,kn={a:1,b:0,c:0,d:1,x:0,y:0},Cn={a:1,b:0,c:0,d:1,x:0,y:0};function In(){const t=Tn();return!!t&&"function"==typeof t.angleMode&&t.angleMode()===t.RADIANS}function Fn(t,e,r){const n=e.isEnabled(e.DEPTH_TEST);n&&e.disable(e.DEPTH_TEST);const i=t._renderer.activeFramebuffer?.()??null;return i?._beforeEnd&&i._beforeEnd(),e.bindFramebuffer(e.FRAMEBUFFER,function(t){return t?"function"==typeof t._framebufferToBind?t._framebufferToBind():t.framebuffer??null:null}(r)),e.viewport(0,0,r.width*r.density,r.height*r.density),{hadDepthTest:n,previousTarget:i}}function Ln(t,e,r){r?.hadDepthTest&&e.enable(e.DEPTH_TEST),r?.previousTarget?._beforeBegin?r.previousTarget._beforeBegin():(e.bindFramebuffer(e.FRAMEBUFFER,null),t._renderer.viewport(t._renderer._origViewport.width,t._renderer._origViewport.height),t._renderer._applyStencilTestIfClipping?.())}function Dn(t,e){const r=t?._renderer;r&&(r._curShader=null,r._cachedBlendMode=null,r._isBlending=null,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,null),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA))}function Nn(t,e,r){if(!e)return;if(r(e))return void e.draw(()=>t.clear());const n=e.drawingContext;n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,e.width,e.height),n.restore()}function Bn(t,e,r){return t.loaded||(t.loaded=!0,t.shaderProgram??=t.createShader(e,r)),t.shaderProgram}function Yn(t,e,r,n,i){return e?.remove&&e.remove(),t.createFramebuffer({width:r,height:n,density:i,antialias:!1,depth:!1,stencil:!1})}const zn=(t,e)=>t.createFramebuffer(e);function On({renderer:t,shader:e,source:r,mask:n,color:i,isBrushMask:o,Cwidth:s,Cheight:a,dirtyRect:c,targetIsFramebuffer:l,withScissor:h}){const u=t.drawingContext,f=u.isEnabled(u.DEPTH_TEST);u.disable(u.DEPTH_TEST),t.push(),t.translate(0,0),t.shader(e),e.setUniform("u_source",r),e.setUniform("u_targetIsFramebuffer",l),e.setUniform("u_isBrush",o),e.setUniform("u_mask",n),e.setUniform("u_color",i),h(u,c,()=>{t.fill(0,0,0,0),t.noStroke(),t.rect(-s/2,-a/2,s,a)},!l),t.pop(),t.resetShader(),f&&u.enable(u.DEPTH_TEST)}function Xn(t){return t.isFramebufferTarget(t.sourceTarget)?((t.sourceTarget.renderer??t.renderer)._renderer?.flushDraw?.(),t.sourceFramebuffer.draw(()=>{t.withScissor(t.renderer.drawingContext,t.dirtyRect,()=>{t.renderer.clear(),t.renderer.push(),t.renderer.imageMode(t.renderer.CENTER),t.renderer.image(t.sourceTarget,0,0,t.Cwidth,t.Cheight),t.renderer.pop()},!1)}),t.sourceFramebuffer):(t.renderer._renderer?.flushDraw?.(),function({renderer:t,sourceFramebuffer:e,dirtyRect:r,getTargetPixelSize:n,toScissorBox:i}){const o=t.drawingContext,{width:s,height:a}=n(),c=r?i(r):null,l=o.getParameter(o.READ_FRAMEBUFFER_BINDING),h=o.getParameter(o.DRAW_FRAMEBUFFER_BINDING);return o.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,e.framebuffer),o.blitFramebuffer(c?.x??0,c?.y??0,c?c.x+c.width:s,c?c.y+c.height:a,c?.x??0,c?.y??0,c?c.x+c.width:s,c?c.y+c.height:a,o.COLOR_BUFFER_BIT,o.NEAREST),o.bindFramebuffer(o.READ_FRAMEBUFFER,l),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,h),e}(t))}const Un=()=>q??$??window.self?.p5?.instance;function Gn(t,e){const r=Un();if(!r?.createGraphics)throw new Error("p5 stroke tip creation requires an active renderer or instance.");return r.createGraphics(t,e)}function Vn(t,e){return new Promise((r,n)=>{const i=new window.Image;i.onload=()=>{const t=Un();if(!t?.createImage)return void n(new Error("p5 image tip loading requires an active renderer or instance."));const o=t.createImage(i.naturalWidth,i.naturalHeight);o.drawingContext.drawImage(i,0,0),e(o),r(o)},i.onerror=()=>n(new Error(`Failed to load image tip: ${t}`)),i.crossOrigin="anonymous",i.src=t})}const Hn=[];var Wn;Wn={load:Sn,syncDensity:()=>{const t=q.pixelDensity();return J({Density:t}),t},isCanvasReady:()=>{vn||Sn()},instance:Pn,activateInstance:t=>{bn.push(yn),yn=t,Pn(t)},deactivateInstance:()=>{yn=bn.pop()??null},getActiveFramebuffer:()=>q?._renderer?.activeFramebuffer?.()??null,isFramebufferTarget:wn},Z={...Z,...Wn},function(){var t;(t={usesRadians:In,fromDegrees:t=>In()?t*Math.PI/180:t,createColor:(...t)=>{const e=Tn();if(!e?.color)throw new Error("p5 runtime color creation requires an active renderer.");return e.color(...t)},getAffineMatrix:()=>{const t=Tn(),e=t?._renderer?.uModelMatrix?.mat4;return e?(Cn.a=e[0],Cn.b=e[1],Cn.c=e[4],Cn.d=e[5],Cn.x=e[12],Cn.y=e[13],Cn):kn}}).usesRadians&&(r=t.usesRadians),t.fromDegrees&&(n=t.fromDegrees),t.createColor&&(i=t.createColor),t.getAffineMatrix&&(o=t.getAffineMatrix),t.notifyDraw&&(s=t.notifyDraw)}(),function(){var t;t={beginDirectMaskDraw:Fn,endDirectMaskDraw:Ln,resetDirectShaderTracking:Dn},Jt={...Jt,...t}}(),function(){var t;t={clearTarget:Nn,ensureBlendShaderProgram:Bn,ensureBlendSourceFramebuffer:Yn,createFramebuffer:zn,runBlendShaderPass:On,blitSourceToFramebuffer:Xn},at={...at,...t}}(),function(){var t;t={createTipSurface:Gn,loadImageTip:Vn},qt={...qt,...t}}(),"undefined"!=typeof p5&&p5.registerAddon(function(t,e,r){r.presetup=function(){et(this)},r.predraw=function(){et(this)},r.postsetup=function(){tt(this),vt(),rt()},r.postdraw=function(){tt(this),vt(),rt()};const n=e.push,i=e.pop,o=e.randomSeed,s=e.noiseSeed;e.push=function(){n.call(this),_t(),Hn.push({fill:{...pt.fill},wash:pt.wash?{...pt.wash}:null,stroke:{...pt.stroke},hatch:{...pt.hatch},mass:pt.mass?{...pt.mass}:null,field:{...pt.field}})},e.pop=function(){i.call(this),function(){const t=Hn.pop();t&&(pt.stroke={...t.stroke},pt.field={...t.field},pt.hatch={...t.hatch},pt.fill={...t.fill},t.wash&&(pt.wash={...t.wash}),t.mass?pt.mass={...t.mass}:pt.mass&&(pt.mass={...pt.mass,isActive:!1,brush:null,color:null,options:{}}))}()},e.randomSeed=function(t){o.call(this,t),y(t)},e.noiseSeed=function(t){s.call(this,t),v(t)}}),t.Plot=Yt,t.Polygon=Bt,t.Position=At,t.add=qe,t.addField=Lt,t.arc=zt,t.beginShape=Ht,t.beginStroke=function(t,e,r){if("curve"!==t&&"segments"!==t)throw new Error(`beginStroke() type must be "curve" or "segments", got "${t}".`);Gt=[e,r],Ut=new Yt(t)},t.box=function(){return[...He.keys()]},t.circle=function(t,e,r,n=!1){const i=new Yt("curve"),o=Math.PI*r,s=_(0,360),a=n?()=>1+.2*n*_():()=>1;for(let t=0;t<4;t++){const e=-90*t+s;i.addSegment(e*a(),o/2*a(),1,!0)}if(n){const t=n*E(-5,5);i.addSegment(s,Math.abs(t)*(Math.PI/180)*r,1,!0),i.endPlot(t+s,1,!0)}else i.endPlot(s,1,!0);const c=t-r*B(s),l=e-r*N(-s);return i.show(c,l,1),[i,c,l]},t.clip=function(t){return Q(),t},t.endShape=jt,t.endStroke=function(t,e){if(!Ut)throw new Error("endStroke() called without beginStroke(). Call beginStroke() first.");Ut.endPlot(t,e),Ut.draw(Gt[0],Gt[1],1),Ut=!1},t.field=Ft,t.fill=on,t.fillBleed=sn,t.fillTexture=an,t.flowLine=function(t,e,r,n){if(!pt.stroke.isActive||!pt.stroke.color)throw new Error("No brush or color set. Call brush.set('brushName', color) before drawing.");_t(),ar(t,e,r),lr(O(n),!1)},t.hatch=Rr,t.hatchArray=Fr,t.hatchStyle=function(t,e="black",r=1){pt.hatch.hBrush={brush:t,color:e,weight:r}},t.instance=tt,t.line=yr,t.listFields=function(){return _t(),Array.from(Tt.keys())},t.load=(t=!1)=>{((t=!1)=>{Z.load(t)})(t),q.loaded&&bt.load()},t.mass=function(t,e,r={}){pt.mass.brush=t,pt.mass.color=e,pt.mass.options=r,pt.mass.isActive=!0},t.massArray=function(t){return jr(t,!1)},t.move=function(t,e,r){if(!Ut)throw new Error("move() called without beginStroke(). Call beginStroke() first.");Ut.addSegment(t,e,r)},t.noClip=function(){},t.noField=function(){_t(),pt.field.isActive=!1},t.noFill=function(){pt.fill.isActive=!1},t.noHatch=function(){pt.hatch.isActive=!1,pt.hatch.hBrush=!1},t.noMass=function(){pt.mass.isActive=!1,pt.mass.brush=null,pt.mass.color=null,pt.mass.options={}},t.noStroke=function(){pt.stroke.isActive=!1},t.noWash=function(){pt.wash.isActive=!1},t.noiseSeed=v,t.pick=Ze,t.polygon=function(t){const e=new Bt(t);return e.show(),e},t.rect=function(t,e,r,n,i="corner"){"center"===i&&(t-=r/2,e-=n/2),Ht(0),Wt(t,e),Wt(t+r,e),Wt(t+r,e+n),Wt(t,e+n),jt(!0)},t.refreshField=function(t=0){if(!pt.field.isActive||!pt.field.current)throw new Error("No field is currently active. Call brush.field('name') to activate one before refreshing.");const e=Tt.get(pt.field.current);e.field=It(e,t)},t.scaleBrushes=function(t){for(const{param:e}of He.values())e&&(e.weight*=t,e.scatter*=t,e.spacing*=t)},t.seed=y,t.set=tr,t.spline=function(t,e=.5){if(!t||t.length<2)throw new Error("spline() requires at least 2 points. Each point should be [x, y, pressure].");let r=$t(t,e);return r.show(),r},t.stroke=Je,t.strokeWeight=Qe,t.vertex=Wt,t.wRand=t=>{let e=0;const r=[];for(const n in t)e+=t[n],r.push({key:n,cumulative:e});const n=d()*e;for(const{key:t,cumulative:e}of r)if(nwindow.devicePixelRatio,t.getURL=()=>location.href,t.getURLPath=()=>location.pathname.split("/").filter((e=>""!==e)),t.getURLParams=function(){const e=/[?&]([^&=]+)(?:[&=])([^&=]+)/gim;let t;const r={};for(;null!=(t=e.exec(location.search));)t.index===e.lastIndex&&e.lastIndex++,r[t[1]]=t[2];return r},t.worldToScreen=function(e){"number"==typeof e&&(e=this.createVector(...arguments));return this._renderer.getWorldToScreenMatrix().multiplyAndNormalizePoint(e)},t.screenToWorld=function(e){"number"==typeof e&&(e=this.createVector(...arguments));const t=this._renderer.getWorldToScreenMatrix();if(2===e.dimensions){let r=t.mat4[14]/t.mat4[15];e=this.createVector(e.x,e.y,r)}return t.invert(t).multiplyAndNormalizePoint(e)}}function Ze(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function Ke(e,t,r=[0,0,0]){const i=Ze(e,t[0]),n=Ze(e,t[1]),s=Ze(e,t[2]);return r[0]=i,r[1]=n,r[2]=s,r}function Je(e){return"string"===Qe(e)}function Qe(e){return(Object.prototype.toString.call(e).match(/^\[object\s+(.*?)\]$/)[1]||"").toLowerCase()}function et(e,{precision:t=16,unit:r}){return tt(e)?"none":(e=+rt(e,t))+(r??"")}function tt(e){return null===e}function rt(e,t){if(0===e)return 0;let r=~~e,i=0;r&&t&&(i=1+~~Math.log10(Math.abs(r)));const n=10**(t-i);return Math.floor(e*n+.5)/n}function it(e,t,r){return isNaN(e)?t:isNaN(t)?e:e+(t-e)*r}function nt(e,t,r){return!e||!t||e===t||e[0]===t[0]&&e[1]===t[1]||isNaN(r)||null===r?r:it(t[0],t[1],function(e,t,r){return(r-e)/(t-e)}(e[0],e[1],r))}function st(e,t,r){return Math.max(Math.min(r,t),e)}function at(e,t){return Math.sign(e)===Math.sign(t)?e:-e}function ot(e,t){return at(Math.abs(e)**t,e)}function ht(e,t){return 0===t?0:e/t}function ut(e,t){if(e instanceof t)return!0;const r=t.name;for(;e;){const t=Object.getPrototypeOf(e),i=t?.constructor?.name;if(i===r)return!0;if(!i||"Object"===i)return!1;e=t}return!1}void 0!==p5&&We(p5,p5.prototype),void 0!==p5&&Xe(0,p5.prototype),void 0!==p5&&Ye(0,p5.prototype);class lt{type;coordMeta;coordRange;range;constructor(e,t){if("object"==typeof e&&(this.coordMeta=e),t&&(this.coordMeta=t,this.coordRange=t.range??t.refRange),"string"==typeof e){let t=e.trim().match(/^(?<[a-z]+>)(\[(?-?[.\d]+),\s*(?-?[.\d]+)\])?$/);if(!t)throw new TypeError(`Cannot parse ${e} as a type definition.`);this.type=t.groups.type;let{min:r,max:i}=t.groups;(r||i)&&(this.range=[+r,+i])}}get computedRange(){return this.range?this.range:""===this.type?this.percentageRange():""===this.type?[0,360]:null}get unit(){return""===this.type?"%":""===this.type?"deg":""}resolve(e){if(""===this.type)return e;let t=this.computedRange,r=this.coordRange;return""===this.type&&(r??=this.percentageRange()),nt(t,r,e)}serialize(e,t){let r=""===this.type?this.percentageRange(100):this.computedRange,i=this.unit;return et(e=nt(this.coordRange,r,e),{unit:i,precision:t})}toString(){let e=this.type;if(this.range){let[t="",r=""]=this.range;e+=`[${t},${r}]`}return e}percentageRange(e=1){let t;return t=this.coordMeta&&this.coordMeta.range||this.coordRange&&this.coordRange[0]>=0?[0,1]:[-1,1],[t[0]*e,t[1]*e]}static get(e,t){return ut(e,this)?e:new this(e,t)}}const ct=Symbol("instance");class pt{type;name;spaceCoords;coords;id;alpha;constructor(e,t=e.space){e[ct]=this,this.type="function",this.name="color",Object.assign(this,e),this.space=t,"custom"!==this.type&&(this.spaceCoords=Object.values(t.coords),this.coords||(this.coords=this.spaceCoords.map((e=>{let t=["",""];return"angle"===e.type&&t.push(""),t}))),this.coords=this.coords.map(((e,t)=>{let r=this.spaceCoords[t];return"string"==typeof e&&(e=e.trim().split(/\s*\|\s*/)),e.map((e=>lt.get(e,r)))})))}serializeCoords(e,t,r){return r=e.map(((e,t)=>lt.get(r?.[t]??this.coords[t][0],this.spaceCoords[t]))),e.map(((e,i)=>r[i].serialize(e,t)))}coerceCoords(e,t){return Object.entries(this.space.coords).map((([r,i],n)=>{let s=e[n];if(tt(s)||isNaN(s))return s;let a=t[n],o=this.coords[n].find((e=>e.type==a));if(!o){let e=i.name||r;throw new TypeError(`${a??s?.raw??s} not allowed for ${e} in ${this.name}()`)}return s=o.resolve(s),o.range&&(t[n]=o.toString()),s}))}canSerialize(){return"function"===this.type||this.serialize}parse(e){return null}static get(e,...t){return!e||ut(e,this)?e:e[ct]?e[ct]:new pt(e,...t)}}const dt=new class{add(e,t,r){if("string"==typeof arguments[0])(Array.isArray(e)?e:[e]).forEach((function(e){this[e]=this[e]||[],t&&this[e][r?"unshift":"push"](t)}),this);else for(var e in arguments[0])this.add(e,arguments[0][e],arguments[1])}run(e,t){this[e]=this[e]||[],this[e].forEach((function(e){e.call(t&&t.context?t.context:t,t)}))}},ft={D50:[.3457/.3585,1,.2958/.3585],D65:[.3127/.329,1,.3583/.329]};function mt(e){return Array.isArray(e)?e:ft[e]}function gt(e,t,r,i={}){if(e=mt(e),t=mt(t),!e||!t)throw new TypeError(`Missing white point to convert ${e?"":"from"}${e||t?"":"/"}${t?"":"to"}`);if(e===t)return r;let n={W1:e,W2:t,XYZ:r,options:i};if(dt.run("chromatic-adaptation-start",n),n.M||(n.W1===ft.D65&&n.W2===ft.D50?n.M=[[1.0479297925449969,.022946870601609652,-.05019226628920524],[.02962780877005599,.9904344267538799,-.017073799063418826],[-.009243040646204504,.015055191490298152,.7518742814281371]]:n.W1===ft.D50&&n.W2===ft.D65&&(n.M=[[.955473421488075,-.02309845494876471,.06325924320057072],[-.0283697093338637,1.0099953980813041,.021041441191917323],[.012314014864481998,-.020507649298898964,1.330365926242124]])),dt.run("chromatic-adaptation-end",n),n.M)return Ke(n.XYZ,n.M);throw new TypeError("Only Bradford CAT with white points D50 and D65 supported for now.")}var yt={gamut_mapping:"css",precision:5,deltaE:"76",verbose:"test"!==globalThis?.process?.env?.NODE_ENV?.toLowerCase(),warn:function(e){this.verbose&&globalThis?.console?.warn?.(e)}};function xt(e,t){let r,i={str:String(e)?.trim(),options:t};if(dt.run("parse-start",i),i.color)return i.color;i.parsed=function(e){if(!e)return;e=e.trim();let t=e.match(bt.function);if(t){let e=[],r=[],i=!1,n=t[1].toLowerCase(),s=t[2].replace(bt.singleArgument,((t,s)=>{let{value:a,meta:o}=function(e){let t={},r=e.match(bt.unitValue)?.[0],i=t.raw=e;r?(t.type="%"===r?"":"",t.unit=r,t.unitless=Number(i.slice(0,-r.length)),i=t.unitless*vt[r]):bt.number.test(i)?(i=Number(i),t.type=""):"none"===i?i=null:"NaN"===i||"calc(NaN)"===i?(i=NaN,t.type=""):t.type="";return{value:i,meta:t}}(s);return(t.startsWith("/")||"color"!==n&&3===e.length)&&(i=!0),e.push(a),r.push(o),""}));return{name:n,args:e,argMeta:r,lastAlpha:i,commas:s.includes(","),rawName:t[1],rawArgs:t[2]}}}(i.str);let n=i.options?i.options.parseMeta??i.options.meta:null;if(i.parsed){let t,s,a=i.parsed.name,o=i.parsed.args,h=o.map(((e,t)=>i.parsed.argMeta[t]?.type));if("color"===a){let r=o.shift();h.shift();let n=r.startsWith("--")?r.substring(2):`--${r}`,u=[r,n];if(t=wt.findFormat({name:a,id:u,type:"function"}),!t){let t,s=r in wt.registry?r:n;if(s in wt.registry){let i=wt.registry[s].formats?.color?.id;if(i){t=`Did you mean ${e.replace("color("+r,"color("+i)}?`}}throw new TypeError(`Cannot parse ${i.str}. `+(t??"Missing a plugin?"))}s=t.space,t.id.startsWith("--")&&!r.startsWith("--")&&yt.warn(`${s.name} is a non-standard space and not currently supported in the CSS spec. Use prefixed color(${t.id}) instead of color(${r}).`),r.startsWith("--")&&!t.id.startsWith("--")&&yt.warn(`${s.name} is a standard space and supported in the CSS spec. Use color(${t.id}) instead of prefixed color(${r}).`)}else t=wt.findFormat({name:a,type:"function"}),s=t.space;n&&Object.assign(n,{format:t,formatId:t.name,types:h,commas:i.parsed.commas});let u=1;i.parsed.lastAlpha&&(u=i.parsed.args.pop(),n&&(n.alphaType=h.pop()));let l=t.coords.length;if(o.length!==l)throw new TypeError(`Expected ${l} coordinates for ${s.id} in ${i.str}), got ${o.length}`);o=t.coerceCoords(o,h),r={spaceId:s.id,coords:o,alpha:u}}else e:for(let e of wt.all)for(let t in e.formats){let s=e.formats[t];if("custom"!==s.type)continue;if(s.test&&!s.test(i.str))continue;let a=e.getFormat(s),o=a.parse(i.str);if(o){n&&Object.assign(n,{format:a,formatId:t}),r=o;break e}}if(!r)throw new TypeError(`Could not parse ${e} as a color. Missing a plugin?`);return r.alpha=tt(r.alpha)?r.alpha:void 0===r.alpha?1:st(0,r.alpha,1),r}const vt={"%":.01,deg:1,grad:.9,rad:180/Math.PI,turn:360},bt={function:/^([a-z]+)\(((?:calc\(NaN\)|.)+?)\)$/i,number:/^([-+]?(?:[0-9]*\.)?[0-9]+(e[-+]?[0-9]+)?)$/i,unitValue:RegExp(`(${Object.keys(vt).join("|")})$`),singleArgument:/\/?\s*(none|NaN|calc\(NaN\)|[-+\w.]+(?:%|deg|g?rad|turn)?)/g};function _t(e,t){if(Array.isArray(e))return e.map((e=>_t(e,t)));if(!e)throw new TypeError("Empty color reference");Je(e)&&(e=xt(e,t));let r=e.space||e.spaceId;return"string"==typeof r&&(e.space=wt.get(r)),void 0===e.alpha&&(e.alpha=1),e}class wt{constructor(e){this.id=e.id,this.name=e.name,this.base=e.base?wt.get(e.base):null,this.aliases=e.aliases,this.base&&(this.fromBase=e.fromBase,this.toBase=e.toBase);let t=e.coords??this.base.coords;for(let e in t)"name"in t[e]||(t[e].name=e);this.coords=t;let r=e.white??this.base.white??"D65";this.white=mt(r),this.formats=e.formats??{};for(let e in this.formats){let t=this.formats[e];t.type||="function",t.name||=e}this.formats.color?.id||(this.formats.color={...this.formats.color??{},id:e.cssId||this.id}),e.gamutSpace?this.gamutSpace="self"===e.gamutSpace?this:wt.get(e.gamutSpace):this.isPolar?this.gamutSpace=this.base:this.gamutSpace=this,this.gamutSpace.isUnbounded&&(this.inGamut=(e,t)=>!0),this.referred=e.referred,Object.defineProperty(this,"path",{value:Ct(this).reverse(),writable:!1,enumerable:!0,configurable:!0}),dt.run("colorspace-init-end",this)}inGamut(e,{epsilon:t=75e-6}={}){if(!this.equals(this.gamutSpace))return e=this.to(this.gamutSpace,e),this.gamutSpace.inGamut(e,{epsilon:t});let r=Object.values(this.coords);return e.every(((e,i)=>{let n=r[i];if("angle"!==n.type&&n.range){if(tt(e))return!0;let[r,i]=n.range;return(void 0===r||e>=r-t)&&(void 0===i||e<=i+t)}return!0}))}get isUnbounded(){return Object.values(this.coords).every((e=>!("range"in e)))}get cssId(){return this.formats?.color?.id||this.id}get isPolar(){for(let e in this.coords)if("angle"===this.coords[e].type)return!0;return!1}getFormat(e){if(!e)return null;"default"===e?e=Object.values(this.formats)[0]:"string"==typeof e&&(e=this.formats[e]);let t=pt.get(e,this);return t!==e&&e.name in this.formats&&(this.formats[e.name]=t),t}equals(e){return!!e&&(this===e||this.id===e||this.id===e.id)}to(e,t){if(1===arguments.length){const r=_t(e);[e,t]=[r.space,r.coords]}if(e=wt.get(e),this.equals(e))return t;t=t.map((e=>tt(e)?0:e));let r,i,n=this.path,s=e.path;for(let e=0;ei;e--)t=n[e].toBase(t);for(let e=i+1;et.includes(e)))}if(n){let e=pt.get(i,r);return e!==i&&(r.formats[i.name]=e),e}}return null}static resolveCoord(e,t){let r,i,n=Qe(e);if("string"===n?e.includes(".")?[r,i]=e.split("."):[r,i]=[,e]:Array.isArray(e)?[r,i]=e:(r=e.space,i=e.coordId),r=wt.get(r),r||(r=t),!r)throw new TypeError(`Cannot resolve coordinate reference ${e}: No color space specified and relative references are not allowed here`);if(n=Qe(i),"number"===n||"string"===n&&i>=0){let e=Object.entries(r.coords)[i];if(e)return{space:r,id:e[0],index:i,...e[1]}}r=wt.get(r);let s=i.toLowerCase(),a=0;for(let e in r.coords){let t=r.coords[e];if(e.toLowerCase()===s||t.name?.toLowerCase()===s)return{space:r,id:e,index:a,...t};a++}throw new TypeError(`No "${i}" coordinate found in ${r.name}. Its coordinates are: ${Object.keys(r.coords).join(", ")}`)}static DEFAULT_FORMAT={type:"functions",name:"color"}}function Ct(e){let t=[e];for(let r=e;r=r.base;)t.push(r);return t}var Et=new wt({id:"xyz-d65",name:"XYZ D65",coords:{x:{refRange:[0,1],name:"X"},y:{refRange:[0,1],name:"Y"},z:{refRange:[0,1],name:"Z"}},white:"D65",formats:{color:{ids:["xyz-d65","xyz"]}},aliases:["xyz"]});class At extends wt{constructor(e){e.coords||(e.coords={r:{range:[0,1],name:"Red"},g:{range:[0,1],name:"Green"},b:{range:[0,1],name:"Blue"}}),e.base||(e.base=Et),e.toXYZ_M&&e.fromXYZ_M&&(e.toBase??=t=>{let r=Ke(t,e.toXYZ_M);return this.white!==this.base.white&&(r=gt(this.white,this.base.white,r)),r},e.fromBase??=t=>Ke(t=gt(this.base.white,this.white,t),e.fromXYZ_M)),e.referred??="display",super(e)}}function Dt(e,t){e=_t(e);let r,i=wt.get(t,t?.space),n=t?.precision;return r=!i||e.space.equals(i)?e.coords.slice():i.from(e),void 0===n?r:r.map((e=>rt(e,n)))}function St(e,t){if(e=_t(e),"alpha"===t)return e.alpha??1;let{space:r,index:i}=wt.resolveCoord(t,e.space);return Dt(e,r)[i]}function Tt(e,t,r,i){return e=_t(e),Array.isArray(t)&&([t,r,i]=[e.space,t,r]),t=wt.get(t),e.coords=t===e.space?r.slice():t.to(e.space,r),void 0!==i&&(e.alpha=i),e}function Ft(e,t,r){if(e=_t(e),2===arguments.length&&"object"===Qe(arguments[1])){let t=arguments[1];for(let r in t)Ft(e,r,t[r])}else if("function"==typeof r&&(r=r(St(e,t))),"alpha"===t)e.alpha=r;else{let{space:i,index:n}=wt.resolveCoord(t,e.space),s=Dt(e,i);s[n]=r,Tt(e,i,s)}return e}Tt.returns="color",Ft.returns="color";var kt=new wt({id:"xyz-d50",name:"XYZ D50",white:"D50",base:Et,fromBase:e=>gt(Et.white,"D50",e),toBase:e=>gt("D50",Et.white,e)});const Mt=216/24389,It=24/116,Bt=24389/27;let Lt=ft.D50;var Ot=new wt({id:"lab",name:"Lab",coords:{l:{refRange:[0,100],name:"Lightness"},a:{refRange:[-125,125]},b:{refRange:[-125,125]}},white:Lt,base:kt,fromBase(e){let t=e.map(((e,t)=>e/Lt[t])),r=t.map((e=>e>Mt?Math.cbrt(e):(Bt*e+16)/116));return[116*r[1]-16,500*(r[0]-r[1]),200*(r[1]-r[2])]},toBase(e){let[t,r,i]=e,n=[];return n[1]=(t+16)/116,n[0]=r/500+n[1],n[2]=n[1]-i/200,[n[0]>It?Math.pow(n[0],3):(116*n[0]-16)/Bt,e[0]>8?Math.pow((e[0]+16)/116,3):e[0]/Bt,n[2]>It?Math.pow(n[2],3):(116*n[2]-16)/Bt].map(((e,t)=>e*Lt[t]))},formats:{lab:{coords:[" | "," | "," | "]}}});function Pt(e){return"number"!=typeof e?e:(e%360+360)%360}var Nt=new wt({id:"lch",name:"LCH",coords:{l:{refRange:[0,100],name:"Lightness"},c:{refRange:[0,150],name:"Chroma"},h:{refRange:[0,360],type:"angle",name:"Hue"}},base:Ot,fromBase(e){if(void 0===this.ε){let e=Object.values(this.base.coords)[1].refRange,t=e[1]-e[0];this.ε=t/1e5}let[t,r,i]=e,n=Math.abs(r) | "," | "," | "]}}});const Rt=25**7,Vt=Math.PI,Ut=180/Vt,zt=Vt/180;function jt(e){const t=e*e;return t*t*t*e}function Gt(e,t,{kL:r=1,kC:i=1,kH:n=1}={}){[e,t]=_t([e,t]);let[s,a,o]=Ot.from(e),h=Nt.from(Ot,[s,a,o])[1],[u,l,c]=Ot.from(t),p=Nt.from(Ot,[u,l,c])[1];h<0&&(h=0),p<0&&(p=0);let d=jt((h+p)/2),f=.5*(1-Math.sqrt(d/(d+Rt))),m=(1+f)*a,g=(1+f)*l,y=Math.sqrt(m**2+o**2),x=Math.sqrt(g**2+c**2),v=0===m&&0===o?0:Math.atan2(o,m),b=0===g&&0===c?0:Math.atan2(c,g);v<0&&(v+=2*Vt),b<0&&(b+=2*Vt),v*=Ut,b*=Ut;let _,w=u-s,C=x-y,E=b-v,A=v+b,D=Math.abs(E);y*x==0?_=0:D<=180?_=E:E>180?_=E-360:E<-180?_=E+360:yt.warn("the unthinkable has happened");let S,T=2*Math.sqrt(x*y)*Math.sin(_*zt/2),F=(s+u)/2,k=(y+x)/2,M=jt(k);S=y*x==0?A:D<=180?A/2:A<360?(A+360)/2:(A-360)/2;let I=(F-50)**2,B=1+.015*I/Math.sqrt(20+I),L=1+.045*k,O=1;O-=.17*Math.cos((S-30)*zt),O+=.24*Math.cos(2*S*zt),O+=.32*Math.cos((3*S+6)*zt),O-=.2*Math.cos((4*S-63)*zt);let P=1+.015*k*O,N=30*Math.exp(-1*((S-275)/25)**2),R=2*Math.sqrt(M/(M+Rt)),V=(w/(r*B))**2;return V+=(C/(i*L))**2,V+=(T/(n*P))**2,V+=-1*Math.sin(2*N*zt)*R*(C/(i*L))*(T/(n*P)),Math.sqrt(V)}const $t=[[.819022437996703,.3619062600528904,-.1288737815209879],[.0329836539323885,.9292868615863434,.0361446663506424],[.0481771893596242,.2642395317527308,.6335478284694309]],Ht=[[1.2268798758459243,-.5578149944602171,.2813910456659647],[-.0405757452148008,1.112286803280317,-.0717110580655164],[-.0763729366746601,-.4214933324022432,1.5869240198367816]],qt=[[.210454268309314,.7936177747023054,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],Wt=[[1,.3963377773761749,.2158037573099136],[1,-.1055613458156586,-.0638541728258133],[1,-.0894841775298119,-1.2914855480194092]];var Xt=new wt({id:"oklab",name:"Oklab",coords:{l:{refRange:[0,1],name:"Lightness"},a:{refRange:[-.4,.4]},b:{refRange:[-.4,.4]}},white:"D65",base:Et,fromBase(e){let t=Ke(e,$t);return t[0]=Math.cbrt(t[0]),t[1]=Math.cbrt(t[1]),t[2]=Math.cbrt(t[2]),Ke(t,qt,t)},toBase(e){let t=Ke(e,Wt);return t[0]=t[0]**3,t[1]=t[1]**3,t[2]=t[2]**3,Ke(t,Ht,t)},formats:{oklab:{coords:[" | "," | "," | "]}}});function Yt(e,t){[e,t]=_t([e,t]);let[r,i,n]=Xt.from(e),[s,a,o]=Xt.from(t),h=r-s,u=i-a,l=n-o;return Math.sqrt(h**2+u**2+l**2)}function Zt(e,t,{epsilon:r=75e-6}={}){e=_t(e),t||(t=e.space),t=wt.get(t);let i=e.coords;return t!==e.space&&(i=t.from(e)),t.inGamut(i,{epsilon:r})}function Kt(e){return{space:e.space,coords:e.coords.slice(),alpha:e.alpha}}const Jt=Math.PI/180;var Qt=new wt({id:"xyz-abs-d65",cssId:"--xyz-abs-d65",name:"Absolute XYZ D65",coords:{x:{refRange:[0,9504.7],name:"Xa"},y:{refRange:[0,1e4],name:"Ya"},z:{refRange:[0,10888.3],name:"Za"}},base:Et,fromBase:e=>e.map((e=>203*e)),toBase:e=>e.map((e=>e/203))});const er=1.15,tr=.66,rr=2610/16384,ir=16384/2610,nr=.8359375,sr=2413/128,ar=18.6875,or=1.7*2523/32,hr=32/(1.7*2523),ur=-.56,lr=16295499532821565e-27,cr=[[.41478972,.579999,.014648],[-.20151,1.120649,.0531008],[-.0166008,.2648,.6684799]],pr=[[1.9242264357876067,-1.0047923125953657,.037651404030618],[.35031676209499907,.7264811939316552,-.06538442294808501],[-.09098281098284752,-.3127282905230739,1.5227665613052603]],dr=[[.5,.5,0],[3.524,-4.066708,.542708],[.199076,1.096799,-1.295875]],fr=[[1,.13860504327153927,.05804731615611883],[1,-.1386050432715393,-.058047316156118904],[1,-.09601924202631895,-.811891896056039]];var mr=new wt({id:"jzazbz",name:"Jzazbz",coords:{jz:{refRange:[0,1],name:"Jz"},az:{refRange:[-.21,.21]},bz:{refRange:[-.21,.21]}},base:Qt,fromBase(e){let[t,r,i]=e,n=Ke([er*t-(er-1)*i,tr*r-(tr-1)*t,i],cr).map((function(e){let t=nr+sr*ot(e/1e4,rr),r=1+ar*ot(e/1e4,rr);return ot(t/r,or)})),[s,a,o]=Ke(n,dr);return[(1+ur)*s/(1+ur*s)-lr,a,o]},toBase(e){let[t,r,i]=e,n=Ke([(t+lr)/(1+ur-ur*(t+lr)),r,i],fr).map((function(e){let t=nr-ot(e,hr),r=ar*ot(e,hr)-sr;return 1e4*ot(t/r,ir)})),[s,a,o]=Ke(n,pr),h=(s+(er-1)*o)/er;return[h,(a+(tr-1)*h)/tr,o]},formats:{jzazbz:{coords:[" | "," | "," | "]}}}),gr=new wt({id:"jzczhz",name:"JzCzHz",coords:{jz:{refRange:[0,1],name:"Jz"},cz:{refRange:[0,.26],name:"Chroma"},hz:{refRange:[0,360],type:"angle",name:"Hue"}},base:mr,fromBase:Nt.fromBase,toBase:Nt.toBase,formats:{jzczhz:{coords:[" | "," | "," | "]}}});const yr=.8359375,xr=2413/128,vr=18.6875,br=2610/16384,_r=2523/32,wr=16384/2610,Cr=32/2523,Er=[[.3592832590121217,.6976051147779502,-.035891593232029],[-.1920808463704993,1.100476797037432,.0753748658519118],[.0070797844607479,.0748396662186362,.8433265453898765]],Ar=[[.5,.5,0],[6610/4096,-13613/4096,7003/4096],[17933/4096,-17390/4096,-543/4096]],Dr=[[.9999999999999998,.0086090370379328,.111029625003026],[.9999999999999998,-.0086090370379328,-.1110296250030259],[.9999999999999998,.5600313357106791,-.3206271749873188]],Sr=[[2.0701522183894223,-1.3263473389671563,.2066510476294053],[.3647385209748072,.6805660249472273,-.0453045459220347],[-.0497472075358123,-.0492609666966131,1.1880659249923042]];var Tr=new wt({id:"ictcp",name:"ICTCP",coords:{i:{refRange:[0,1],name:"I"},ct:{refRange:[-.5,.5],name:"CT"},cp:{refRange:[-.5,.5],name:"CP"}},base:Qt,fromBase:e=>function(e){let t=e.map((function(e){return((yr+xr*(e/1e4)**br)/(1+vr*(e/1e4)**br))**_r}));return Ke(t,Ar)}(Ke(e,Er)),toBase(e){let t=function(e){let t=Ke(e,Dr),r=t.map((function(e){return 1e4*(Math.max(e**Cr-yr,0)/(xr-vr*e**Cr))**wr}));return r}(e);return Ke(t,Sr)},formats:{ictcp:{coords:[" | "," | "," | "]}}});const Fr=ft.D65,kr=1/.42,Mr=2*Math.PI,Ir=[[.401288,.650173,-.051461],[-.250268,1.204414,.045854],[-.002079,.048952,.953127]],Br=[[1.8620678550872327,-1.0112546305316843,.14918677544445175],[.38752654323613717,.6214474419314753,-.008973985167612518],[-.015841498849333856,-.03412293802851557,1.0499644368778496]],Lr=[[460,451,288],[460,-891,-261],[460,-220,-6300]],Or={dark:[.8,.525,.8],dim:[.9,.59,.9],average:[1,.69,1]},Pr={h:[20.14,90,164.25,237.53,380.14],e:[.8,.7,1,1.2,.8],H:[0,100,200,300,400]},Nr=180/Math.PI,Rr=Math.PI/180;function Vr(e,t){return e.map((e=>{const r=ot(t*Math.abs(e)*.01,.42);return 400*at(r,e)/(r+27.13)}))}function Ur(e,t,r,i,n){const s={};s.discounting=n,s.refWhite=e,s.surround=i;const a=e.map((e=>100*e));s.la=t,s.yb=r;const o=a[1],h=Ke(a,Ir);let u=Or[s.surround];const l=u[0];s.c=u[1],s.nc=u[2];const c=(1/(5*s.la+1))**4;s.fl=c*s.la+.1*(1-c)*(1-c)*Math.cbrt(5*s.la),s.flRoot=s.fl**.25,s.n=s.yb/o,s.z=1.48+Math.sqrt(s.n),s.nbb=.725*s.n**-.2,s.ncb=s.nbb;const p=Math.max(Math.min(l*(1-1/3.6*Math.exp((-s.la-42)/92)),1),0);s.dRgb=h.map((e=>it(1,o/e,p))),s.dRgbInv=s.dRgb.map((e=>1/e));const d=h.map(((e,t)=>e*s.dRgb[t])),f=Vr(d,s.fl);return s.aW=s.nbb*(2*f[0]+f[1]+.05*f[2]),s}const zr=Ur(Fr,64/Math.PI*.2,20,"average",!1);function jr(e,t){if(!(void 0!==e.J^void 0!==e.Q))throw new Error("Conversion requires one and only one: 'J' or 'Q'");if(!(void 0!==e.C^void 0!==e.M^void 0!==e.s))throw new Error("Conversion requires one and only one: 'C', 'M' or 's'");if(!(void 0!==e.h^void 0!==e.H))throw new Error("Conversion requires one and only one: 'h' or 'H'");if(0===e.J||0===e.Q)return[0,0,0];let r=0;r=void 0!==e.h?Pt(e.h)*Rr:function(e){let t=(e%400+400)%400;const r=Math.floor(.01*t);t%=100;const[i,n]=Pr.h.slice(r,r+2),[s,a]=Pr.e.slice(r,r+2);return Pt((t*(a*i-s*n)-100*i*a)/(t*(a-s)-100*a))}(e.H)*Rr;const i=Math.cos(r),n=Math.sin(r);let s=0;void 0!==e.J?s=.1*ot(e.J,.5):void 0!==e.Q&&(s=.25*t.c*e.Q/((t.aW+4)*t.flRoot));let a=0;void 0!==e.C?a=e.C/s:void 0!==e.M?a=e.M/t.flRoot/s:void 0!==e.s&&(a=4e-4*e.s**2*(t.aW+4)/t.c);const o=ot(a*Math.pow(1.64-Math.pow(.29,t.n),-.73),10/9),h=.25*(Math.cos(r+2)+3.8),u=t.aW*ot(s,2/t.c/t.z),l=5e4/13*t.nc*t.ncb*h,c=u/t.nbb,p=23*(c+.305)*ht(o,23*l+o*(11*i+108*n)),d=function(e,t){const r=100/t*2588.068098016295;return e.map((e=>{const t=Math.abs(e);return at(r*ot(t/(400-t),kr),e)}))}(Ke([c,p*i,p*n],Lr).map((e=>1*e/1403)),t.fl);return Ke(d.map(((e,r)=>e*t.dRgbInv[r])),Br).map((e=>e/100))}function Gr(e,t){const r=Vr(Ke(e.map((e=>100*e)),Ir).map(((e,r)=>e*t.dRgb[r])),t.fl),i=r[0]+(-12*r[1]+r[2])/11,n=(r[0]+r[1]-2*r[2])/9,s=(Math.atan2(n,i)%Mr+Mr)%Mr,a=.25*(Math.cos(s+2)+3.8),o=ot(5e4/13*t.nc*t.ncb*ht(a*Math.sqrt(i**2+n**2),r[0]+r[1]+1.05*r[2]+.305),.9)*Math.pow(1.64-Math.pow(.29,t.n),.73),h=ot(t.nbb*(2*r[0]+r[1]+.05*r[2])/t.aW,.5*t.c*t.z),u=100*ot(h,2),l=4/t.c*h*(t.aW+4)*t.flRoot,c=o*h,p=c*t.flRoot,d=Pt(s*Nr),f=function(e){let t=Pt(e);t<=Pr.h[0]&&(t+=360);const r=function(e,t,r=0,i=e.length){for(;r>1;e[n]jr({J:e[0],M:e[1],h:e[2]},zr)});const $r=216/24389,Hr=24389/27;function qr(e){return e>8?Math.pow((e+16)/116,3):e/Hr}function Wr(e,t){const r=116*((i=e[1])>$r?Math.cbrt(i):(Hr*i+16)/116)-16;var i;if(0===r)return[0,0,0];const n=Gr(e,Xr);return[Pt(n.h),n.C,r]}const Xr=Ur(ft.D65,200/Math.PI*qr(50),100*qr(50),"average",!1);var Yr=new wt({id:"hct",name:"HCT",coords:{h:{refRange:[0,360],type:"angle",name:"Hue"},c:{refRange:[0,145],name:"Colorfulness"},t:{refRange:[0,100],name:"Tone"}},base:Et,fromBase(e){void 0===this.ε&&(this.ε=Object.values(this.coords)[1].refRange[1]/1e5);let t=Wr(e);return t[1]function(e,t){let[r,i,n]=e,s=[],a=0;if(0===n)return[0,0,0];let o=qr(n);a=n>0?.00379058511492914*n**2+.608983189401032*n+.9155088574762233:9514440756550361e-21*n**2+.08693057439788597*n-21.928975842194614;let h=0,u=1/0;for(;h<=15;){s=jr({J:a,C:i,h:r},t);const e=Math.abs(s[1]-o);if(e | "," | "," | "]}}});const Zr=Math.PI/180,Kr=[1,.007,.0228];function Jr(e){e[1]<0&&(e=Yr.fromBase(Yr.toBase(e)));const t=Math.log(Math.max(1+Kr[2]*e[1]*Xr.flRoot,1))/Kr[2],r=e[0]*Zr,i=t*Math.cos(r),n=t*Math.sin(r);return[e[2],i,n]}var Qr={deltaE76:function(e,t){return function(e,t,r="lab"){let i=(r=wt.get(r)).from(e),n=r.from(t);return Math.sqrt(i.reduce(((e,t,r)=>{let i=n[r];return tt(t)||tt(i)?e:e+(i-t)**2}),0))}(e,t,"lab")},deltaECMC:function(e,t,{l:r=2,c:i=1}={}){[e,t]=_t([e,t]);let[n,s,a]=Ot.from(e),[,o,h]=Nt.from(Ot,[n,s,a]),[u,l,c]=Ot.from(t),p=Nt.from(Ot,[u,l,c])[1];o<0&&(o=0),p<0&&(p=0);let d=n-u,f=o-p,m=(s-l)**2+(a-c)**2-f**2,g=.511;n>=16&&(g=.040975*n/(1+.01765*n));let y,x=.0638*o/(1+.0131*o)+.638;tt(h)&&(h=0),y=h>=164&&h<=345?.56+Math.abs(.2*Math.cos((h+168)*Jt)):.36+Math.abs(.4*Math.cos((h+35)*Jt));let v=Math.pow(o,4),b=Math.sqrt(v/(v+1900)),_=(d/(r*g))**2;return _+=(f/(i*x))**2,_+=m/(x*(b*y+1-b))**2,Math.sqrt(_)},deltaE2000:Gt,deltaEJz:function(e,t){[e,t]=_t([e,t]);let[r,i,n]=gr.from(e),[s,a,o]=gr.from(t),h=r-s,u=i-a;tt(n)&&tt(o)?(n=0,o=0):tt(n)?n=o:tt(o)&&(o=n);let l=n-o,c=2*Math.sqrt(i*a)*Math.sin(l/2*(Math.PI/180));return Math.sqrt(h**2+u**2+c**2)},deltaEITP:function(e,t){[e,t]=_t([e,t]);let[r,i,n]=Tr.from(e),[s,a,o]=Tr.from(t);return 720*Math.sqrt((r-s)**2+.25*(i-a)**2+(n-o)**2)},deltaEOK:Yt,deltaEOK2:function(e,t){[e,t]=_t([e,t]);let[r,i,n]=Xt.from(e),[s,a,o]=Xt.from(t),h=r-s,u=2*(i-a),l=2*(n-o);return Math.sqrt(h**2+u**2+l**2)},deltaEHCT:function(e,t){[e,t]=_t([e,t]);let[r,i,n]=Jr(Yr.from(e)),[s,a,o]=Jr(Yr.from(t));return Math.sqrt((r-s)**2+(i-a)**2+(n-o)**2)}};const ei={hct:{method:"hct.c",jnd:2,deltaEMethod:"hct",blackWhiteClamp:{}},"hct-tonal":{method:"hct.c",jnd:0,deltaEMethod:"hct",blackWhiteClamp:{channel:"hct.t",min:0,max:100}}};function ti(e,{method:t=yt.gamut_mapping,space:r,deltaEMethod:i="",jnd:n=2,blackWhiteClamp:s}={}){if(e=_t(e),Je(arguments[1])?r=arguments[1]:r||(r=e.space),Zt(e,r=wt.get(r),{epsilon:0}))return e;let a;if("css"===t)a=function(e,{space:t}={}){const r=.02,i=1e-4;e=_t(e),t||(t=e.space);t=wt.get(t);const n=wt.get("oklch");if(t.isUnbounded)return ii(e,t);const s=ii(e,n);let a=s.coords[0];if(a>=1){const r=ii(ri.WHITE,t);return r.alpha=e.alpha,ii(r,t)}if(a<=0){const r=ii(ri.BLACK,t);return r.alpha=e.alpha,ii(r,t)}if(Zt(s,t,{epsilon:0}))return ii(s,t);function o(e){const r=ii(e,t),i=Object.values(t.coords);return r.coords=r.coords.map(((e,t)=>{if("range"in i[t]){const[r,n]=i[t].range;return st(r,e,n)}return e})),r}let h=0,u=s.coords[1],l=!0,c=Kt(s),p=o(c),d=Yt(p,c);if(di;){const e=(h+u)/2;if(c.coords[1]=e,l&&Zt(c,t,{epsilon:0}))h=e;else if(p=o(c),d=Yt(p,c),dn){if(s&&3===Object.keys(s).length){let t=wt.resolveCoord(s.channel),r=St(ii(e,t.space),t.id);if(tt(r)&&(r=0),r>=s.max)return ii({space:"xyz-d65",coords:ft.D65},e.space);if(r<=s.min)return ii({space:"xyz-d65",coords:[0,0,0]},e.space)}let i=wt.resolveCoord(t),h=i.space,u=i.id,l=ii(e,h);l.coords.forEach(((e,t)=>{tt(e)&&(l.coords[t]=0)}));let c=(i.range||i.refRange)[0],p=function(e){const t=e?Math.floor(Math.log10(Math.abs(e))):0;return Math.max(parseFloat("1e"+(t-2)),1e-6)}(n),d=c,f=St(l,u);for(;f-d>p;){let e=Kt(l);e=ti(e,{space:r,method:"clip"}),o(l,e)-ne.range||[]));a.coords=a.coords.map(((t,r)=>{let[i,n]=e[r];return void 0!==i&&(t=Math.max(i,t)),void 0!==n&&(t=Math.min(t,n)),t}))}}return r!==e.space&&(a=ii(a,e.space)),e.coords=a.coords,e}ti.returns="color";const ri={WHITE:{space:Xt,coords:[1,0,0],alpha:1},BLACK:{space:Xt,coords:[0,0,0],alpha:1}};function ii(e,t,{inGamut:r}={}){e=_t(e);let i=(t=wt.get(t)).from(e),n={space:t,coords:i,alpha:e.alpha};return r&&(n=ti(n,!0===r?void 0:r)),n}ii.returns="color";var ni=new At({id:"p3-linear",cssId:"display-p3-linear",name:"Linear P3",white:"D65",toXYZ_M:[[.4865709486482162,.26566769316909306,.1982172852343625],[.2289745640697488,.6917385218365064,.079286914093745],[0,.04511338185890264,1.043944368900976]],fromXYZ_M:[[2.493496911941425,-.9313836179191239,-.40271078445071684],[-.8294889695615747,1.7626640603183463,.023624685841943577],[.03584583024378447,-.07617238926804182,.9568845240076872]]});var si=new At({id:"srgb-linear",name:"Linear sRGB",white:"D65",toXYZ_M:[[.41239079926595934,.357584339383878,.1804807884018343],[.21263900587151027,.715168678767756,.07219231536073371],[.01933081871559182,.11919477979462598,.9505321522496607]],fromXYZ_M:[[3.2409699419045226,-1.537383177570094,-.4986107602930034],[-.9692436362808796,1.8759675015077202,.04155505740717559],[.05563007969699366,-.20397695888897652,1.0569715142428786]]}),ai={aliceblue:[240/255,248/255,1],antiquewhite:[250/255,235/255,215/255],aqua:[0,1,1],aquamarine:[127/255,1,212/255],azure:[240/255,1,1],beige:[245/255,245/255,220/255],bisque:[1,228/255,196/255],black:[0,0,0],blanchedalmond:[1,235/255,205/255],blue:[0,0,1],blueviolet:[138/255,43/255,226/255],brown:[165/255,42/255,42/255],burlywood:[222/255,184/255,135/255],cadetblue:[95/255,158/255,160/255],chartreuse:[127/255,1,0],chocolate:[210/255,105/255,30/255],coral:[1,127/255,80/255],cornflowerblue:[100/255,149/255,237/255],cornsilk:[1,248/255,220/255],crimson:[220/255,20/255,60/255],cyan:[0,1,1],darkblue:[0,0,139/255],darkcyan:[0,139/255,139/255],darkgoldenrod:[184/255,134/255,11/255],darkgray:[169/255,169/255,169/255],darkgreen:[0,100/255,0],darkgrey:[169/255,169/255,169/255],darkkhaki:[189/255,183/255,107/255],darkmagenta:[139/255,0,139/255],darkolivegreen:[85/255,107/255,47/255],darkorange:[1,140/255,0],darkorchid:[.6,50/255,.8],darkred:[139/255,0,0],darksalmon:[233/255,150/255,122/255],darkseagreen:[143/255,188/255,143/255],darkslateblue:[72/255,61/255,139/255],darkslategray:[47/255,79/255,79/255],darkslategrey:[47/255,79/255,79/255],darkturquoise:[0,206/255,209/255],darkviolet:[148/255,0,211/255],deeppink:[1,20/255,147/255],deepskyblue:[0,191/255,1],dimgray:[105/255,105/255,105/255],dimgrey:[105/255,105/255,105/255],dodgerblue:[30/255,144/255,1],firebrick:[178/255,34/255,34/255],floralwhite:[1,250/255,240/255],forestgreen:[34/255,139/255,34/255],fuchsia:[1,0,1],gainsboro:[220/255,220/255,220/255],ghostwhite:[248/255,248/255,1],gold:[1,215/255,0],goldenrod:[218/255,165/255,32/255],gray:[128/255,128/255,128/255],green:[0,128/255,0],greenyellow:[173/255,1,47/255],grey:[128/255,128/255,128/255],honeydew:[240/255,1,240/255],hotpink:[1,105/255,180/255],indianred:[205/255,92/255,92/255],indigo:[75/255,0,130/255],ivory:[1,1,240/255],khaki:[240/255,230/255,140/255],lavender:[230/255,230/255,250/255],lavenderblush:[1,240/255,245/255],lawngreen:[124/255,252/255,0],lemonchiffon:[1,250/255,205/255],lightblue:[173/255,216/255,230/255],lightcoral:[240/255,128/255,128/255],lightcyan:[224/255,1,1],lightgoldenrodyellow:[250/255,250/255,210/255],lightgray:[211/255,211/255,211/255],lightgreen:[144/255,238/255,144/255],lightgrey:[211/255,211/255,211/255],lightpink:[1,182/255,193/255],lightsalmon:[1,160/255,122/255],lightseagreen:[32/255,178/255,170/255],lightskyblue:[135/255,206/255,250/255],lightslategray:[119/255,136/255,.6],lightslategrey:[119/255,136/255,.6],lightsteelblue:[176/255,196/255,222/255],lightyellow:[1,1,224/255],lime:[0,1,0],limegreen:[50/255,205/255,50/255],linen:[250/255,240/255,230/255],magenta:[1,0,1],maroon:[128/255,0,0],mediumaquamarine:[.4,205/255,170/255],mediumblue:[0,0,205/255],mediumorchid:[186/255,85/255,211/255],mediumpurple:[147/255,112/255,219/255],mediumseagreen:[60/255,179/255,113/255],mediumslateblue:[123/255,104/255,238/255],mediumspringgreen:[0,250/255,154/255],mediumturquoise:[72/255,209/255,.8],mediumvioletred:[199/255,21/255,133/255],midnightblue:[25/255,25/255,112/255],mintcream:[245/255,1,250/255],mistyrose:[1,228/255,225/255],moccasin:[1,228/255,181/255],navajowhite:[1,222/255,173/255],navy:[0,0,128/255],oldlace:[253/255,245/255,230/255],olive:[128/255,128/255,0],olivedrab:[107/255,142/255,35/255],orange:[1,165/255,0],orangered:[1,69/255,0],orchid:[218/255,112/255,214/255],palegoldenrod:[238/255,232/255,170/255],palegreen:[152/255,251/255,152/255],paleturquoise:[175/255,238/255,238/255],palevioletred:[219/255,112/255,147/255],papayawhip:[1,239/255,213/255],peachpuff:[1,218/255,185/255],peru:[205/255,133/255,63/255],pink:[1,192/255,203/255],plum:[221/255,160/255,221/255],powderblue:[176/255,224/255,230/255],purple:[128/255,0,128/255],rebeccapurple:[.4,.2,.6],red:[1,0,0],rosybrown:[188/255,143/255,143/255],royalblue:[65/255,105/255,225/255],saddlebrown:[139/255,69/255,19/255],salmon:[250/255,128/255,114/255],sandybrown:[244/255,164/255,96/255],seagreen:[46/255,139/255,87/255],seashell:[1,245/255,238/255],sienna:[160/255,82/255,45/255],silver:[192/255,192/255,192/255],skyblue:[135/255,206/255,235/255],slateblue:[106/255,90/255,205/255],slategray:[112/255,128/255,144/255],slategrey:[112/255,128/255,144/255],snow:[1,250/255,250/255],springgreen:[0,1,127/255],steelblue:[70/255,130/255,180/255],tan:[210/255,180/255,140/255],teal:[0,128/255,128/255],thistle:[216/255,191/255,216/255],tomato:[1,99/255,71/255],turquoise:[64/255,224/255,208/255],violet:[238/255,130/255,238/255],wheat:[245/255,222/255,179/255],white:[1,1,1],whitesmoke:[245/255,245/255,245/255],yellow:[1,1,0],yellowgreen:[154/255,205/255,50/255]};let oi=Array(3).fill(" | [0, 255]"),hi=Array(3).fill("[0, 255]");var ui=new At({id:"srgb",name:"sRGB",base:si,fromBase:e=>e.map((e=>{let t=e<0?-1:1,r=e*t;return r>.0031308?t*(1.055*r**(1/2.4)-.055):12.92*e})),toBase:e=>e.map((e=>{let t=e<0?-1:1,r=e*t;return r<=.04045?e/12.92:t*((r+.055)/1.055)**2.4})),formats:{rgb:{coords:oi},rgb_number:{name:"rgb",commas:!0,coords:hi,alpha:!1},color:{},rgba:{coords:oi,commas:!0,alpha:!0},rgba_number:{name:"rgba",commas:!0,coords:hi},hex:{type:"custom",toGamut:!0,test:e=>/^#(([a-f0-9]{2}){3,4}|[a-f0-9]{3,4})$/i.test(e),parse(e){e.length<=5&&(e=e.replace(/[a-f0-9]/gi,"$&$&"));let t=[];return e.replace(/[a-f0-9]{2}/gi,(e=>{t.push(parseInt(e,16)/255)})),{spaceId:"srgb",coords:t.slice(0,3),alpha:t.slice(3)[0]}},serialize:(e,t,{collapse:r=!0,alpha:i}={})=>{(!1!==i&&t<1||!0===i)&&e.push(t),e=e.map((e=>Math.round(255*e)));let n=r&&e.every((e=>e%17==0));return"#"+e.map((e=>n?(e/17).toString(16):e.toString(16).padStart(2,"0"))).join("")}},keyword:{type:"custom",test:e=>/^[a-z]+$/i.test(e),parse(e){let t={spaceId:"srgb",coords:null,alpha:1};if("transparent"===(e=e.toLowerCase())?(t.coords=ai.black,t.alpha=0):t.coords=ai[e],t.coords)return t}}}}),li=new At({id:"p3",cssId:"display-p3",name:"P3",base:ni,fromBase:ui.fromBase,toBase:ui.toBase});function ci(e){return St(e,[Et,"y"])}function pi(e,t){e=_t(e),t=_t(t);let r=Math.max(ci(e),0),i=Math.max(ci(t),0);return i>r&&([r,i]=[i,r]),(r+.05)/(i+.05)}function di(e){return e>=.022?e:e+(.022-e)**1.414}function fi(e){let t=e<0?-1:1,r=Math.abs(e);return t*Math.pow(r,2.4)}function mi(e,t){let r,i,n,s,a,o;t=_t(t),e=_t(e),t=ii(t,"srgb"),[s,a,o]=t.coords.map((e=>tt(e)?0:e));let h=.2126729*fi(s)+.7151522*fi(a)+.072175*fi(o);e=ii(e,"srgb"),[s,a,o]=e.coords.map((e=>tt(e)?0:e));let u=.2126729*fi(s)+.7151522*fi(a)+.072175*fi(o),l=di(h),c=di(u),p=c>l;return Math.abs(c-l)<5e-4?i=0:p?(r=c**.56-l**.57,i=1.14*r):(r=c**.65-l**.62,i=1.14*r),n=Math.abs(i)<.1?0:i>0?i-.027:i+.027,100*n}function gi(e,t,r={}){if("function"===Qe(i=e)&&i.rangeArgs){let[r,i]=[e,t];return gi(...r.rangeArgs.colors,{...r.rangeArgs.options,...i})}var i;let{space:n,outputSpace:s,progression:a,premultiplied:o}=r;e=_t(e),t=_t(t),e=Kt(e),t=Kt(t);let h={colors:[e,t],options:r};if(n=n?wt.get(n):wt.registry[yt.interpolationSpace]||e.space,s=s?wt.get(s):n,e=ii(e,n),t=ii(t,n),e=ti(e),t=ti(t),n.coords.h&&"angle"===n.coords.h.type){let i=r.hue=r.hue||"shorter",s=[n,"h"],[a,o]=[St(e,s),St(t,s)];tt(a)&&!tt(o)?a=o:tt(o)&&!tt(a)&&(o=a),[a,o]=function(e,t){let[r,i]=t,n=tt(r),s=tt(i);if(n&&s)return[r,i];if(n?r=i:s&&(i=r),"raw"===e)return t;r=Pt(r),i=Pt(i);let a=i-r;return"increasing"===e?a<0&&(i+=360):"decreasing"===e?a>0&&(r+=360):"longer"===e?-1800?r+=360:i+=360):"shorter"===e&&(a>180?r+=360:a<-180&&(i+=360)),[r,i]}(i,[a,o]),Ft(e,s,a),Ft(t,s,o)}return o&&(e.coords=e.coords.map((t=>t*e.alpha)),t.coords=t.coords.map((e=>e*t.alpha))),Object.assign((r=>{r=a?a(r):r;let i=e.coords.map(((e,i)=>it(e,t.coords[i],r))),h=it(e.alpha,t.alpha,r),u={space:n,coords:i,alpha:h};return o&&(u.coords=u.coords.map((e=>e/h))),s!==n&&(u=ii(u,s)),u}),{rangeArgs:h})}yt.interpolationSpace="lab";var yi=new wt({id:"hsl",name:"HSL",coords:{h:{refRange:[0,360],type:"angle",name:"Hue"},s:{range:[0,100],name:"Saturation"},l:{range:[0,100],name:"Lightness"}},base:ui,fromBase:e=>{let t=Math.max(...e),r=Math.min(...e),[i,n,s]=e,[a,o,h]=[null,0,(r+t)/2],u=t-r;if(0!==u){switch(o=0===h||1===h?0:(t-h)/Math.min(h,1-h),t){case i:a=(n-s)/u+(n=360&&(a-=360),[a,100*o,100*h]},toBase:e=>{let[t,r,i]=e;function n(e){let n=(e+t/30)%12,s=r*Math.min(i,1-i);return i-s*Math.max(-1,Math.min(n-3,9-n,1))}return t%=360,t<0&&(t+=360),r/=100,i/=100,[n(0),n(8),n(4)]},formats:{hsl:{coords:[" | "," | "," | "]},hsla:{coords:[" | "," | "," | "],commas:!0,alpha:!0}}}),xi=new wt({id:"hsv",name:"HSV",coords:{h:{refRange:[0,360],type:"angle",name:"Hue"},s:{range:[0,100],name:"Saturation"},v:{range:[0,100],name:"Value"}},base:ui,fromBase(e){let t=Math.max(...e),r=Math.min(...e),[i,n,s]=e,[a,o,h]=[null,0,t],u=t-r;if(0!==u){switch(t){case i:a=(n-s)/u+(n=360&&(a-=360),[a,100*o,100*h]},toBase(e){let[t,r,i]=e;function n(e){let n=(e+t/60)%6;return i-i*r*Math.max(0,Math.min(n,4-n,1))}return t%=360,t<0&&(t+=360),r/=100,i/=100,[n(5),n(3),n(1)]},formats:{color:{id:"--hsv",coords:[" | "," | "," | "]}}}),vi=new wt({id:"hwb",name:"HWB",coords:{h:{refRange:[0,360],type:"angle",name:"Hue"},w:{range:[0,100],name:"Whiteness"},b:{range:[0,100],name:"Blackness"}},base:xi,fromBase(e){let[t,r,i]=e;return[t,i*(100-r)/100,100-i]},toBase(e){let[t,r,i]=e;r/=100,i/=100;let n=r+i;if(n>=1){return[t,0,100*(r/n)]}let s=1-i;return[t,100*(0===s?0:1-r/s),100*s]},formats:{hwb:{coords:[" | "," | "," | "]}}}),bi=new wt({id:"oklch",name:"OkLCh",coords:{l:{refRange:[0,1],name:"Lightness"},c:{refRange:[0,.4],name:"Chroma"},h:{refRange:[0,360],type:"angle",name:"Hue"}},white:"D65",base:Xt,fromBase:Nt.fromBase,toBase:Nt.toBase,formats:{oklch:{coords:[" | "," | "," | "]}}}),_i=new wt({id:"hsb",name:"HSB",coords:{h:{refRange:[0,360],type:"angle",name:"Hue"},s:{range:[0,100],name:"Saturation"},b:{range:[0,100],name:"Brightness"}},base:ui,fromBase:e=>{const t=Math.max(...e),r=t-Math.min(...e);let i,n,[s,a,o]=e;return 0===r?(i=0,n=0):(n=r/t,s===t?i=(a-o)/r:a===t?i=2+(o-s)/r:o===t&&(i=4+(s-a)/r),i<0?i+=6:i>=6&&(i-=6)),[i/6*360,100*n,100*t]},toBase:wi,formats:{default:{type:"custom",serialize:(e,t)=>{const r=wi(e);let i=`rgb(${Math.round(100*r[0]*100)/100}% ${Math.round(100*r[1]*100)/100}% ${Math.round(100*r[2]*100)/100}%`;return t<1&&(i+=` / ${t}`),i+=")",i}},hsb:{coords:[" | ","",""]},hsba:{coords:[" | ","",""],commans:!0,lastAlpha:!0}}});function wi(e){const t=e[0]/360*6,r=e[1]/100,i=e[2]/100;let n=[];if(0===r)n=[i,i,i];else{const e=Math.floor(t),s=i*(1-r),a=i*(1-r*(t-e)),o=i*(1-r*(1+e-t));let h,u,l;1===e?(h=a,u=i,l=s):2===e?(h=s,u=i,l=o):3===e?(h=s,u=a,l=i):4===e?(h=o,u=s,l=i):5===e?(h=i,u=s,l=a):(h=i,u=o,l=s),n=[h,u,l]}return n}const Ci=(e,t,r,i,n,s)=>{let a=(e-t)/(r-t)*(n-i)+i;return s&&(a=Math.max(a,Math.min(i,n)),a=Math.min(a,Math.max(i,n))),a},Ei=e=>{const t=(~~(255*e)).toString(16);return t.length<2?"0"+t:t},Ai=new Map;class Di{static colorMap={};static#e={};static#t={};isColor=!0;static addColorMode(e,t){wt.register(t),Di.colorMap[e]=t.id,Di.#e[e]=Object.values(t.coords).reduce(((e,t)=>(e.push(t.refRange||t.range),e)),[]),Di.#e[e].push([0,1]),Di.#t[e]=t.fromGray}constructor(e,t,r,{clamp:i=!1}={}){if(this._cachedMode=t||Ti,e instanceof Di){const r=t?Di.colorMap[t]:Di.colorMap[e.mode];this._initialize=()=>{this._cachedColor=ii(e._color,r),this._cachedMode=r}}else if("object"!=typeof e||Array.isArray(e)||null===e)if("string"==typeof e[0])this._defaultStringValue=e[0],this._initialize=()=>{try{this._cachedColor=xt(e[0]);const[t]=Object.entries(Di.colorMap).find((([e,t])=>t===this._cachedColor.spaceId));this._cachedMode=t,this._cachedColor=ii(this._cachedColor,this._cachedColor.spaceId)}catch(e){throw new Error("Invalid color string")}};else{let t;if(r)if(4===e.length)t=Di.mapColorRange(e,this._cachedMode,r,i);else if(3===e.length)t=Di.mapColorRange([e[0],e[1],e[2]],this._cachedMode,r,i),t.push(1);else if(2===e.length){t=Di.#t[this._cachedMode]?Di.#t[this._cachedMode](e[0],r,i):Di.mapColorRange([e[0],e[0],e[0]],this._cachedMode,r,i);const n=Array.isArray(r[r.length-1])?r[r.length-1]:[0,r[r.length-1]];t.push(Ci(e[1],n[0],n[1],0,1,i))}else{if(1!==e.length)throw new Error("Invalid color");t=Di.#t[this._cachedMode]?Di.#t[this._cachedMode](e[0],r,i):Di.mapColorRange([e[0],e[0],e[0]],this._cachedMode,r,i),t.push(1)}else t=e;this._cachedMode===Ti&&(1===t[3]?this._defaultStringValue="#"+Ei(t[0])+Ei(t[1])+Ei(t[2]):this._defaultStringValue="#"+Ei(t[0])+Ei(t[1])+Ei(t[2])+Ei(t[3])),this._initialize=()=>{const e=Di.colorMap[this._cachedMode]||console.error("Invalid color mode"),r={space:e,coords:t.slice(0,3),alpha:t[3]};this._cachedColor=ii(r,e)}}else{const r=t?Di.colorMap[t]:e.spaceId;this._initialize=()=>{this._cachedColor=ii(e,r),this._cachedMode=t||Object.entries(Di.colorMap).find((([e,t])=>t===this._cachedColor.spaceId))}}}get mode(){return this._initialize&&(this._initialize(),this._initialize=void 0),this._cachedMode}get _color(){return this._initialize&&(this._initialize(),this._initialize=void 0),this._cachedColor}set _color(e){this._initialize&&(this._initialize(),this._initialize=void 0),this._cachedColor=e}static mapColorRange(e,t,r,i){const n=r.map((e=>Array.isArray(e)?e:[0,e])),s=Di.#e[t];return e.map(((e,t)=>Ci(e,n[t][0],n[t][1],s[t][0],s[t][1],i)))}static unmapColorRange(e,t,r){const i=r.map((e=>Array.isArray(e)?e:[0,e])),n=Di.#e[t];return e.map(((e,t)=>Ci(e,n[t][0],n[t][1],i[t][0],i[t][1])))}#r(e){return new Di(this._color,e)}get _array(){return this._getRGBA()}array(){return this._array}lerp(e,t,r){let i=-1;for(;(i+1",c=!0===o?.include||!0===n.alpha||!1!==o?.include&&!1!==n.alpha&&s<1,d="";if(h??=n.commas,c){if(null!==i){let e;""===l&&(e="%",s*=100),s=et(s,{precision:i,unit:e})}d=`${h?",":" /"} ${s}`}r=`${e}(${t.join(h?", ":" ")}${d})`}return r}(this._color,{format:t}),"#rrggbb"===e){if(i=String(i),4===i.length){const e=i[1],t=i[2],r=i[3];i=`#${e}${e}${t}${t}${r}${r}`}i.length>7&&(i=i.slice(0,7)),i=i.toLowerCase()}Ai.size>1e3&&Ai.delete(Ai.keys().next().value),Ai.set(r,i)}return i}contrast(e,t="WCAG21"){if("all"!==t){let r,i;switch(t){case"WCAG21":r=pi(this._color,e._color),i=4.5;break;case"APCA":r=Math.abs(mi(this._color,e._color)),i=75;break;default:return null}return r>=i}{const t=pi(this._color,e._color),r=mi(this._color,e._color);return{WCAG21:{value:t,passedMinimum:t>=4.5,passedAAA:t>=7},APCA:{value:r,passedMinimum:Math.abs(r)>=75}}}}setRed(e,t=[0,1]){this._defaultStringValue=void 0,Array.isArray(t)||(t=[0,t]);const r=Di.#e[Ti][0],i=Ci(e,t[0],t[1],r[0],r[1]);if(this.mode===Ti||this.mode===Fi)this._color.coords[0]=i;else{const e=this._color.space.id,t=ii(this._color,"srgb");t.coords[0]=i,this._color=ii(t,e)}}setGreen(e,t=[0,1]){this._defaultStringValue=void 0,Array.isArray(t)||(t=[0,t]);const r=Di.#e[Ti][1],i=Ci(e,t[0],t[1],r[0],r[1]);if(this.mode===Ti||this.mode===Fi)this._color.coords[1]=i;else{const e=this._color.space.id,t=ii(this._color,"srgb");t.coords[1]=i,this._color=ii(t,e)}}setBlue(e,t=[0,1]){this._defaultStringValue=void 0,Array.isArray(t)||(t=[0,t]);const r=Di.#e[Ti][2],i=Ci(e,t[0],t[1],r[0],r[1]);if(this.mode===Ti||this.mode===Fi)this._color.coords[2]=i;else{const e=this._color.space.id,t=ii(this._color,"srgb");t.coords[2]=i,this._color=ii(t,e)}}setAlpha(e,t=[0,1]){this._defaultStringValue=void 0,Array.isArray(t)||(t=[0,t]);const r=Di.#e[this.mode][3],i=Ci(e,t[0],t[1],r[0],r[1]);this._color.alpha=i}_getRGBA(e=[1,1,1,1]){const t=Di.#e[Ti];let r=structuredClone(ii(this._color,"srgb").coords);r.push(this._color.alpha);const i=e.map((e=>Array.isArray(e)?e:[0,e]));return r=r.map(((e,r)=>Ci(e,t[r][0],t[r][1],i[r][0],i[r][1]))),r}_getMode(){return this.mode}_getRed(e=[0,1]){if(Array.isArray(e)||(e=[0,e]),this.mode===Ti||this.mode===Fi){const t=Di.#e[this.mode][0];return Ci(this._color.coords[0],t[0],t[1],e[0],e[1])}{const t=Di.#e[Ti][0];return Ci(ii(this._color,"srgb").coords[0],t[0],t[1],e[0],e[1])}}_getGreen(e=[0,1]){if(Array.isArray(e)||(e=[0,e]),this.mode===Ti||this.mode===Fi){const t=Di.#e[this.mode][1];return Ci(this._color.coords[1],t[0],t[1],e[0],e[1])}{const t=Di.#e[Ti][1];return Ci(ii(this._color,"srgb").coords[1],t[0],t[1],e[0],e[1])}}_getBlue(e=[0,1]){if(Array.isArray(e)||(e=[0,e]),this.mode===Ti||this.mode===Fi){const t=Di.#e[this.mode][2];return Ci(this._color.coords[2],t[0],t[1],e[0],e[1])}{const t=Di.#e[Ti][2];return Ci(ii(this._color,"srgb").coords[2],t[0],t[1],e[0],e[1])}}_getAlpha(e=[0,1]){Array.isArray(e)||(e=[0,e]);const t=Di.#e[this.mode][3];return Ci(this._color.alpha,t[0],t[1],e[0],e[1])}_getHue(e=[0,360]){if(Array.isArray(e)||(e=[0,e]),this.mode===ki||this.mode===Mi){const t=Di.#e[this.mode][0];return Ci(this._color.coords[0],t[0],t[1],e[0],e[1])}{const t=Di.#e[Mi][0];return Ci(ii(this._color,"hsl").coords[0],t[0],t[1],e[0],e[1])}}_getSaturation(e=[0,100]){if(Array.isArray(e)||(e=[0,e]),this.mode===ki||this.mode===Mi){const t=Di.#e[this.mode][1];return Ci(this._color.coords[1],t[0],t[1],e[0],e[1])}{const t=Di.#e[Mi][1];return Ci(ii(this._color,"hsl").coords[1],t[0],t[1],e[0],e[1])}}_getBrightness(e=[0,100]){if(Array.isArray(e)||(e=[0,e]),this.mode===ki){const t=Di.#e[this.mode][2];return Ci(this._color.coords[2],t[0],t[1],e[0],e[1])}{const t=Di.#e[ki][2];return Ci(ii(this._color,"hsb").coords[2],t[0],t[1],e[0],e[1])}}_getLightness(e=[0,100]){if(Array.isArray(e)||(e=[0,e]),this.mode===Mi){const t=Di.#e[this.mode][2];return Ci(this._color.coords[2],t[0],t[1],e[0],e[1])}{const t=Di.#e[Mi][2];return Ci(ii(this._color,"hsl").coords[2],t[0],t[1],e[0],e[1])}}}function Si(e,t,r){e.Color=Di,ui.fromGray=li.fromGray=function(e,t,r){const i=t.map((e=>Array.isArray(e)?e:[0,e])),n=Ci(e,i[2][0],i[2][1],0,1,r);return[n,n,n]},_i.fromGray=yi.fromGray=function(e,t,r){const i=t.map((e=>Array.isArray(e)?e:[0,e]));return[0,0,Ci(e,i[2][0],i[2][1],0,100,r)]},vi.fromGray=function(e,t,r){const i=t.map((e=>Array.isArray(e)?e:[0,e])),n=Math.abs(i[1][0]-i[1][1])/2+Math.abs(i[2][0]-i[2][1])/2,s=Ci(e,0,n,0,100);let a,o;return s<50?(o=s,a=100-s):s>=50&&(a=s,o=100-s),[0,a,o]},Ot.fromGray=Nt.fromGray=Xt.fromGray=bi.fromGray=function(e,t,r){const i=t.map((e=>Array.isArray(e)?e:[0,e]));return[Ci(e,i[0][0],i[0][1],0,100,r),0,0]},e.Color.addColorMode(Ti,ui),e.Color.addColorMode(Fi,li),e.Color.addColorMode(ki,_i),e.Color.addColorMode(Mi,yi),e.Color.addColorMode(Ii,vi),e.Color.addColorMode(Bi,Ot),e.Color.addColorMode(Li,Nt),e.Color.addColorMode(Oi,Xt),e.Color.addColorMode(Pi,bi),r.presetup=function(){const t=this,r=["Red","Green","Blue","Alpha"];for(let i in r){const n=r[i],s=e.Color.prototype["set"+n];e.Color.prototype["set"+n]=function(e,r){return r=r||t?._renderer?.states?.colorMaxes?.[Ti][i],s.call(this,e,r)}}function i(r,i){const n=e.Color.prototype["_get"+r];e.Color.prototype["_get"+r]=function(e){if(Object.keys(i).includes(this.mode))e=e||t?._renderer?.states?.colorMaxes?.[this.mode][i[this.mode]];else{const r=Object.keys(i)[0];e=e||t?._renderer?.states?.colorMaxes?.[r][i[r]]}return n.call(this,e)}}i("Red",{[Ti]:0,[Fi]:0}),i("Green",{[Ti]:1,[Fi]:1}),i("Blue",{[Ti]:2,[Fi]:2}),i("Alpha",{[Ti]:3,[Fi]:3,[ki]:3,[Mi]:3,[Ii]:3,[Bi]:3,[Li]:3,[Oi]:3,[Pi]:3}),i("Hue",{[Mi]:0,[ki]:0,[Ii]:0,[Li]:2,[Pi]:2}),i("Saturation",{[Mi]:1,[ki]:1}),i("Brightness",{[ki]:2}),i("Lightness",{[Mi]:2})}}void 0!==p5&&Si(p5);const Ti="rgb",Fi="rgbp3",ki="hsb",Mi="hsl",Ii="hwb",Bi="lab",Li="lch",Oi="oklab",Pi="oklch",Ni="rgba";function Ri(e,t){t.RGB=Ti,t.RGBP3=Fi,t.HSB=ki,t.HSL=Mi,t.HWB=Ii,t.LAB=Bi,t.LCH=Li,t.OKLAB=Oi,t.OKLCH=Pi,t.RGBA=Ni,e.Renderer.states.colorMode=Ti,e.Renderer.states.colorMaxes={[Ti]:[255,255,255,255],[Fi]:[255,255,255,255],[ki]:[360,100,100,1],[Mi]:[360,100,100,1],[Ii]:[360,100,100,1],[Bi]:[100,[-125,125],[-125,125],1],[Li]:[100,150,360,1],[Oi]:[100,[-125,125],[-125,125],1],[Pi]:[100,150,360,1],clone:function(){const e={...this};for(const t in e)e[t]instanceof Array&&(e[t]=[...e[t]]);return e}},t.color=function(...e){if(e[0]instanceof Di)return e[0];const t=Array.isArray(e[0])?e[0]:e;return new Di(t,this._renderer.states.colorMode,this._renderer.states.colorMaxes[this._renderer.states.colorMode],{clamp:!0})},t.red=function(e){return this.color(e)._getRed()},t.green=function(e){return this.color(e)._getGreen()},t.blue=function(e){return this.color(e)._getBlue()},t.alpha=function(e){return this.color(e)._getAlpha()},t.hue=function(e){let t=Mi,r=0;return this._renderer.states.colorMode===ki||this._renderer.states.colorMode===Mi?t=this._renderer.states.colorMode:this._renderer.states.colorMode!==Li&&this._renderer.states.colorMode!==Pi||(t=this._renderer.states.colorMode,r=2),this.color(e)._getHue(this._renderer.states.colorMaxes[t][r])},t.saturation=function(e){const t=this._renderer.states.colorMode===ki?ki:Mi;return this.color(e)._getSaturation(this._renderer.states.colorMaxes[t][1])},t.brightness=function(e){return this.color(e)._getBrightness(this._renderer.states.colorMaxes.hsb[2])},t.lightness=function(e){return this.color(e)._getLightness(this._renderer.states.colorMaxes.hsl[2])},t.lerpColor=function(e,t,r){return e.lerp(t,r,this._renderer.states.colorMode)},t.paletteLerp=function(e,t){const r=e[0];if(t[t,e]))),Gi={[Vi.OPERATION]:["opCode","dependsOn","dimension","baseType"],[Vi.LITERAL]:["value","dimension","baseType"],[Vi.VARIABLE]:["identifier","dimension","baseType"],[Vi.CONSTANT]:["value","dimension","baseType"],[Vi.STRUCT]:[""],[Vi.PHI]:["dependsOn","phiBlocks","dimension","baseType"],[Vi.STATEMENT]:["statementType"],[Vi.ASSIGNMENT]:["dependsOn"]},$i="discard",Hi="break",qi="early_return",Wi="expression",Xi="empty",Yi="float",Zi="int",Ki="bool",Ji="mat",Qi="defer",en="assign_on_use",tn="sampler2D",rn="sampler",nn={[Yi]:3,[Zi]:2,[Ki]:1,[Ji]:0,[Qi]:-1,[en]:-2,[tn]:-10,[rn]:-11},sn={float1:{fnName:"float",baseType:Yi,dimension:1,priority:3},float2:{fnName:"vec2",baseType:Yi,dimension:2,priority:3},float3:{fnName:"vec3",baseType:Yi,dimension:3,priority:3},float4:{fnName:"vec4",baseType:Yi,dimension:4,priority:3},int1:{fnName:"int",baseType:Zi,dimension:1,priority:2},int2:{fnName:"ivec2",baseType:Zi,dimension:2,priority:2},int3:{fnName:"ivec3",baseType:Zi,dimension:3,priority:2},int4:{fnName:"ivec4",baseType:Zi,dimension:4,priority:2},bool1:{fnName:"bool",baseType:Ki,dimension:1,priority:1},bool2:{fnName:"bvec2",baseType:Ki,dimension:2,priority:1},bool3:{fnName:"bvec3",baseType:Ki,dimension:3,priority:1},bool4:{fnName:"bvec4",baseType:Ki,dimension:4,priority:1},mat2:{fnName:"mat2x2",baseType:Ji,dimension:2,priority:0},mat3:{fnName:"mat3x3",baseType:Ji,dimension:3,priority:0},mat4:{fnName:"mat4x4",baseType:Ji,dimension:4,priority:0},defer:{fnName:null,baseType:Qi,dimension:null,priority:-1},assign_on_use:{fnName:null,baseType:en,dimension:null,priority:-2},sampler2D:{fnName:"sampler2D",baseType:tn,dimension:1,priority:-10},sampler:{fnName:"sampler",baseType:rn,dimension:1,priority:-11}},an=function(e){let t=void 0===e.type?e:e.type;const r={name:e.name,properties:[],typeName:t.typeName};for(const e of t.properties){const t=e.type.dataType;r.properties.push({name:e.name,dataType:t})}return r};function on(e){return!(!e||!e.properties)}const hn={FLOAT:{baseType:Yi,dimension:null,priority:3},INT:{baseType:Zi,dimension:null,priority:2},BOOL:{baseType:Ki,dimension:null,priority:1}};const un=Object.fromEntries(Object.values(sn).filter((e=>null!==e.fnName)).map((e=>[e.fnName,e]))),ln={ADD:0,SUBTRACT:1,MULTIPLY:2,DIVIDE:3,MODULO:4,EQUAL:5,NOT_EQUAL:6,GREATER_THAN:7,GREATER_EQUAL:8,LESS_THAN:9,LESS_EQUAL:10,LOGICAL_AND:11,LOGICAL_OR:12,MEMBER_ACCESS:13,ARRAY_ACCESS:14},cn={LOGICAL_NOT:100,NEGATE:101,PLUS:102,SWIZZLE:103},pn={FUNCTION_CALL:200,CONSTRUCTOR:201,TERNARY:202},dn=[{arity:"unary",boolean:!0,name:"not",symbol:"!",opCode:cn.LOGICAL_NOT},{arity:"unary",name:"neg",symbol:"-",opCode:cn.NEGATE},{arity:"unary",name:"plus",symbol:"+",opCode:cn.PLUS},{arity:"binary",name:"add",symbol:"+",opCode:ln.ADD},{arity:"binary",name:"sub",symbol:"-",opCode:ln.SUBTRACT},{arity:"binary",name:"mult",symbol:"*",opCode:ln.MULTIPLY},{arity:"binary",name:"div",symbol:"/",opCode:ln.DIVIDE},{arity:"binary",name:"mod",symbol:"%",opCode:ln.MODULO},{arity:"binary",boolean:!0,name:"equalTo",symbol:"==",opCode:ln.EQUAL},{arity:"binary",boolean:!0,name:"notEqual",symbol:"!=",opCode:ln.NOT_EQUAL},{arity:"binary",boolean:!0,name:"greaterThan",symbol:">",opCode:ln.GREATER_THAN},{arity:"binary",boolean:!0,name:"greaterEqual",symbol:">=",opCode:ln.GREATER_EQUAL},{arity:"binary",boolean:!0,name:"lessThan",symbol:"<",opCode:ln.LESS_THAN},{arity:"binary",boolean:!0,name:"lessEqual",symbol:"<=",opCode:ln.LESS_EQUAL},{arity:"binary",boolean:!0,name:"and",symbol:"&&",opCode:ln.LOGICAL_AND},{arity:"binary",boolean:!0,name:"or",symbol:"||",opCode:ln.LOGICAL_OR}],mn={},gn={},yn={};for(const{symbol:e,opCode:t,name:r,arity:i,boolean:n}of dn)mn[t]=e,"unary"===i&&(gn[e]=r),n&&(yn[t]=!0);const xn={GLOBAL:"global",FUNCTION:"function",BRANCH:"branch",IF_COND:"if_cond",IF_BODY:"if_body",ELSE_COND:"else_cond",SCOPE_START:"scope_start",SCOPE_END:"scope_end",FOR:"for",MERGE:"merge",DEFAULT:"default"};Object.fromEntries(Object.entries(xn).map((([e,t])=>[t,e])));class vn{constructor(e){if(e)this.DOM=e;else{const e=document.implementation.createDocument(null,"doc");this.DOM=e.createElement("root")}}getParent(){return new vn(this.DOM.parentElement)}getName(){return this.DOM.tagName}setName(e){const t=this.DOM.innerHTML,r=this.DOM.attributes,i=document.implementation.createDocument(null,"default").createElement(e);i.innerHTML=t;for(let e=0;e0}listChildren(){const e=[];for(let t=0;t{e.stop()}))}}let e=this._pInst;if(e&&!e._elements&&e._pInst&&(e=e._pInst),e&&e._elements){const t=e._elements.indexOf(this);-1!==t&&e._elements.splice(t,1)}for(let e in this._events)this.elt.removeEventListener(e,this._events[e]);this.elt&&this.elt.parentNode&&this.elt.parentNode.removeChild(this.elt)}parent(e){return void 0===e?this.elt.parentNode:("string"==typeof e?("#"===e[0]&&(e=e.substring(1)),e=document.getElementById(e)):e instanceof En&&(e=e.elt),e.appendChild(this.elt),this)}child(e){return void 0===e?this.elt.childNodes:("string"==typeof e?("#"===e[0]&&(e=e.substring(1)),e=document.getElementById(e)):e instanceof En&&(e=e.elt),e instanceof HTMLElement&&this.elt.appendChild(e),this)}html(...e){return 0===e.length?this.elt.innerHTML:e[1]?(this.elt.insertAdjacentHTML("beforeend",e[0]),this):(this.elt.innerHTML=e[0],this)}id(e){return void 0===e?this.elt.id:(this.elt.id=e,this.width=this.elt.offsetWidth,this.height=this.elt.offsetHeight,this)}class(e){return void 0===e?this.elt.className:(this.elt.className=e,this)}addClass(e){return this.elt.className?this.hasClass(e)||(this.elt.className=this.elt.className+" "+e):this.elt.className=e,this}removeClass(e){return this.elt.classList.remove(e),this}hasClass(e){return this.elt.classList.contains(e)}toggleClass(e){return this.elt.classList.contains(e)?this.elt.classList.remove(e):this.elt.classList.add(e),this}center(e){const t=this.elt.style.display,r="none"===this.elt.style.display,i="none"===this.parent().style.display,n={x:this.elt.offsetLeft,y:this.elt.offsetTop};r&&this.show(),i&&this.parent().show(),this.elt.style.display="block",this.position(0,0);const s=Math.abs(this.parent().offsetWidth-this.elt.offsetWidth),a=Math.abs(this.parent().offsetHeight-this.elt.offsetHeight);return"both"===e||void 0===e?this.position(s/2+this.parent().offsetLeft,a/2+this.parent().offsetTop):"horizontal"===e?this.position(s/2+this.parent().offsetLeft,n.y):"vertical"===e&&this.position(n.x,a/2+this.parent().offsetTop),this.style("display",t),r&&this.hide(),i&&this.parent().hide(),this}position(...e){if(0===e.length)return{x:this.elt.offsetLeft,y:this.elt.offsetTop};{let t="absolute";return"static"!==e[2]&&"fixed"!==e[2]&&"relative"!==e[2]&&"sticky"!==e[2]&&"initial"!==e[2]&&"inherit"!==e[2]||(t=e[2]),this.elt.style.position=t,this.elt.style.left=e[0]+"px",this.elt.style.top=e[1]+"px",this.x=e[0],this.y=e[1],this}}show(){return this.elt.style.display="block",this}hide(){return this.elt.style.display="none",this}size(e,t){if(0===arguments.length)return{width:this.elt.offsetWidth,height:this.elt.offsetHeight};{let r=e,i=t;const n=Y;if(r!==n||i!==n){if(r===n?r=t*this.width/this.height:i===n&&(i=e*this.height/this.width),this.elt instanceof HTMLCanvasElement){const e={},t=this.elt.getContext("2d");let n;for(n in t)e[n]=t[n];for(n in this.elt.setAttribute("width",r*this._pInst._pixelDensity),this.elt.setAttribute("height",i*this._pInst._pixelDensity),this.elt.style.width=r+"px",this.elt.style.height=i+"px",this._pInst.scale(this._pInst._pixelDensity,this._pInst._pixelDensity),e)this.elt.getContext("2d")[n]=e[n]}else this.elt.style.width=r+"px",this.elt.style.height=i+"px",this.elt.width=r,this.elt.height=i;this.width=r,this.height=i,this._pInst&&this._pInst._curElement&&this._pInst._curElement.elt===this.elt&&(this._pInst.width=r,this._pInst.height=i)}return this}}style(e,t){const r=this;if(t instanceof Di&&(t=t.toString()),void 0===t){if(-1===e.indexOf(":")){return window.getComputedStyle(r.elt).getPropertyValue(e)}{const t=e.split(";");for(let e=0;e2&&(this.elt.style.transform="translate3d("+e[0]+"px,"+e[1]+"px,"+e[2]+"px)",3===e.length?this.elt.parentElement.style.perspective="1000px":this.elt.parentElement.style.perspective=e[3]+"px"),this.elt.style.transform+=t,this}_rotate(...e){let t="";return this.elt.style.transform&&(t=this.elt.style.transform.replace(/rotate3d\(.*\)/g,""),t=t.replace(/rotate[X-Z]?\(.*\)/g,"")),1===e.length?this.elt.style.transform="rotate("+e[0]+"deg)":2===e.length?this.elt.style.transform="rotate("+e[0]+"deg, "+e[1]+"deg)":3===e.length&&(this.elt.style.transform="rotateX("+e[0]+"deg)",this.elt.style.transform+="rotateY("+e[1]+"deg)",this.elt.style.transform+="rotateZ("+e[2]+"deg)"),this.elt.style.transform+=t,this}attribute(e,t){if(null==this.elt.firstChild||"checkbox"!==this.elt.firstChild.type&&"radio"!==this.elt.firstChild.type)return void 0===t?this.elt.getAttribute(e):(this.elt.setAttribute(e,t),this);if(void 0===t)return this.elt.firstChild.getAttribute(e);for(let r=0;r0?(this.elt.value=e[0],this):"range"===this.elt.type?parseFloat(this.elt.value):this.elt.value}mousePressed(e){return En._adjustListener("pointerdown",(function(t){return this._pInst.mouseIsPressed=!0,this._pInst._activePointers.set(t.pointerId,t),this._pInst._setMouseButton(t),this._pInst._updatePointerCoords(t),e.call(this,t)}),this),this}doubleClicked(e){return En._adjustListener("dblclick",e,this),this}mouseWheel(e){return En._adjustListener("wheel",e,this),this}mouseReleased(e){return En._adjustListener("pointerup",e,this),this}mouseClicked(e){return En._adjustListener("click",e,this),this}mouseMoved(e){return En._adjustListener("pointermove",e,this),this}mouseOver(e){return En._adjustListener("pointerover",e,this),this}mouseOut(e){return En._adjustListener("pointerout",e,this),this}dragOver(e){return En._adjustListener("dragover",e,this),this}dragLeave(e){return En._adjustListener("dragleave",e,this),this}changed(e){return En._adjustListener("change",e,this),this}input(e){return En._adjustListener("input",e,this),this}drop(e,t){if(window.File&&window.FileReader&&window.FileList&&window.Blob){if(!this._dragDisabled){this._dragDisabled=!0;const e=function(e){e.preventDefault()};this.elt.addEventListener("dragover",e),this.elt.addEventListener("dragleave",e)}En._attachListener("drop",(function(r){r.preventDefault(),"function"==typeof t&&t.call(this,r);const i=r.dataTransfer.files;for(const t of i)wn._load(t,e)}),this)}else console.log("The File APIs are not fully supported in this browser.");return this}draggable(e){let t,r="ontouchstart"in window,i=0,n=0,s=0,a=0,o=r?"touchstart":"mousedown",h=r?"touchend":"mouseup",u=r?"touchmove":"mousemove";function l(t){if(t=t||window.event,r){const e=t.changedTouches;i=s-parseInt(e[0].clientX),n=a-parseInt(e[0].clientY),s=parseInt(e[0].clientX),a=parseInt(e[0].clientY)}else i=s-parseInt(t.clientX),n=a-parseInt(t.clientY),s=parseInt(t.clientX),a=parseInt(t.clientY);e.style.left=e.offsetLeft-i+"px",e.style.top=e.offsetTop-n+"px"}function c(){document.removeEventListener(h,c,!1),document.removeEventListener(u,l,!1)}return void 0===e?t=e=this.elt:e!==this.elt&&e.elt!==this.elt&&(e=e.elt,t=this.elt),t.addEventListener(o,(function(e){if(e=e||window.event,r){const t=e.changedTouches;s=parseInt(t[0].clientX),a=parseInt(t[0].clientY)}else s=parseInt(e.clientX),a=parseInt(e.clientY);return document.addEventListener(h,c,!1),document.addEventListener(u,l,!1),!1}),!1),t.style.cursor="move",this}static _adjustListener(e,t,r){return!1===t?En._detachListener(e,r):En._attachListener(e,t,r),this}static _attachListener(e,t,r){r._events[e]&&En._detachListener(e,r);const i=t.bind(r);r.elt.addEventListener(e,i,{capture:!1,signal:r._pInst._removeSignal}),r._events[e]=i}static _detachListener(e,t){const r=t._events[e];t.elt.removeEventListener(e,r,!1),t._events[e]=null}}function An(e,t){e.Element=En}void 0!==p5&&An(p5);const Dn={_toPixels(e){if(e instanceof ImageData)return e.data;if(e.getContext("2d"))return e.getContext("2d").getImageData(0,0,e.width,e.height).data;if(e.getContext("webgl")){const t=e.getContext("webgl"),r=t.drawingBufferWidth*t.drawingBufferHeight*4,i=new Uint8Array(r);return t.readPixels(0,0,e.width,e.height,t.RGBA,t.UNSIGNED_BYTE,i),i}},_getARGB(e,t){const r=4*t;return e[r+3]<<24&4278190080|e[r]<<16&16711680|e[r+1]<<8&65280|255&e[r+2]},_setPixels(e,t){let r=0;for(let i=0,n=e.length;i>>16,e[r+1]=(65280&t[i])>>>8,e[r+2]=255&t[i],e[r+3]=(4278190080&t[i])>>>24},_toImageData:e=>e instanceof ImageData?e:e.getContext("2d").getImageData(0,0,e.width,e.height),_createImageData(e,t){return Dn._tmpCanvas=document.createElement("canvas"),Dn._tmpCtx=Dn._tmpCanvas.getContext("2d"),this._tmpCtx.createImageData(e,t)},apply(e,t,r){const i=e.getContext("2d"),n=i.getImageData(0,0,e.width,e.height),s=t(n,r);s instanceof ImageData?i.putImageData(s,0,0,0,0,e.width,e.height):i.putImageData(n,0,0,0,0,e.width,e.height)},threshold(e,t=.5){const r=Dn._toPixels(e),i=Math.floor(255*t);for(let e=0;e=i?255:0,r[e]=r[e+1]=r[e+2]=t}},gray(e){const t=Dn._toPixels(e);for(let e=0;e255)throw new Error("Level must be greater than 2 and less than 255 for posterize");const i=t-1;for(let e=0;e>8)/i,r[e+1]=255*(s*t>>8)/i,r[e+2]=255*(a*t>>8)/i}},dilate(e){const t=Dn._toPixels(e);let r=0;const i=t.length?t.length/4:0,n=new Int32Array(i);let s,a,o,h,u,l,c,p,d,f,m,g,y,x,v,b,_;for(;r=a&&(l=r),p<0&&(p=0),d>=i&&(d=r),g=Dn._getARGB(t,p),m=Dn._getARGB(t,c),y=Dn._getARGB(t,d),f=Dn._getARGB(t,l),u=77*(o>>16&255)+151*(o>>8&255)+28*(255&o),v=77*(m>>16&255)+151*(m>>8&255)+28*(255&m),x=77*(f>>16&255)+151*(f>>8&255)+28*(255&f),b=77*(g>>16&255)+151*(g>>8&255)+28*(255&g),_=77*(y>>16&255)+151*(y>>8&255)+28*(255&y),v>u&&(h=m,u=v),x>u&&(h=f,u=x),b>u&&(h=g,u=b),_>u&&(h=y,u=_),n[r++]=h;Dn._setPixels(t,n)},erode(e){const t=Dn._toPixels(e);let r=0;const i=t.length?t.length/4:0,n=new Int32Array(i);let s,a,o,h,u,l,c,p,d,f,m,g,y,x,v,b,_;for(;r=a&&(l=r),p<0&&(p=0),d>=i&&(d=r),g=Dn._getARGB(t,p),m=Dn._getARGB(t,c),y=Dn._getARGB(t,d),f=Dn._getARGB(t,l),u=77*(o>>16&255)+151*(o>>8&255)+28*(255&o),v=77*(m>>16&255)+151*(m>>8&255)+28*(255&m),x=77*(f>>16&255)+151*(f>>8&255)+28*(255&f),b=77*(g>>16&255)+151*(g>>8&255)+28*(255&g),_=77*(y>>16&255)+151*(y>>8&255)+28*(255&y),v=i)break;g=0}for(C=g;C=i);C++){const e=a[p+A];E=kn[C],c+=E[(-16777216&e)>>>24],h+=E[(16711680&e)>>16],u+=E[(65280&e)>>8],l+=E[255&e],o+=Fn[C],p++}d=A+_,y[d]=c/o,x[d]=h/o,v[d]=u/o,b[d]=l/o}A+=i}for(A=0,f=-Sn,m=f*i,w=0;w=n)break;g=0,d=f,p=_+m}for(C=g;C=n);C++)E=kn[C],c+=E[y[p]],h+=E[x[p]],u+=E[v[p]],l+=E[b[p]],o+=Fn[C],d++,p+=i;a[_+A]=c/o<<24|h/o<<16|u/o<<8|l/o}A+=i,m+=i,f++}Dn._setPixels(r,a)}(e,t)}};let Sn,Tn,Fn,kn;function Mn(e,t,r){const i=In(t,r)[0];let n=e;if(n instanceof Blob||(n=new Blob([e])),document){const e=URL.createObjectURL(n),t=document.createElement("a");t.href=e,t.download=i,t.click(),URL.revokeObjectURL(e)}}function In(e,t){t&&!0!==t&&"true"!==t||(t=""),e||(e="untitled");let r="";return e&&e.includes(".")&&(r=e.split(".").pop()),t&&r!==t&&(r=t,e=`${e}.${r}`),[e,r]}let Bn=class e{constructor(e,t){this.width=e,this.height=t,this.canvas=document.createElement("canvas"),this.canvas.width=this.width,this.canvas.height=this.height,this.drawingContext=this.canvas.getContext("2d"),this._pixelsState=this,this._pixelDensity=1,this.gifProperties=null,this._modified=!1,this.pixels=[]}_friendlyError(e){}pixelDensity(e){return void 0!==e?(e<=0&&(e=1),this._pixelDensity=e,this.width/=e,this.height/=e,this):this._pixelDensity}_animateGif(e){const t=this.gifProperties,r=e._lastRealFrameTime||window.performance.now();if(0===t.lastChangeTime&&(t.lastChangeTime=r),t.playing){t.timeDisplayed=r-t.lastChangeTime;const e=t.frames[t.displayIndex].delay;if(t.timeDisplayed>=e){const i=Math.floor(t.timeDisplayed/e);if(t.timeDisplayed=0,t.lastChangeTime=r,t.displayIndex+=i,t.loopCount=Math.floor(t.displayIndex/t.numFrames),null!==t.loopLimit&&t.loopCount>=t.loopLimit)t.playing=!1;else{const e=t.displayIndex%t.numFrames;this.drawingContext.putImageData(t.frames[e].image,0,0),t.displayIndex=e,this.setModified(!0)}}}}loadPixels(){const e=this._pixelsState,t=this._pixelDensity,r=this.width*t,i=this.height*t,n=this.drawingContext.getImageData(0,0,r,i);e.imageData=n,this.pixels=e.pixels=n.data,this.setModified(!0)}updatePixels(e,t,r,i){const n=this._pixelsState,s=this._pixelDensity;void 0===e&&void 0===t&&void 0===r&&void 0===i&&(e=0,t=0,r=this.width,i=this.height),e*=s,t*=s,r*=s,i*=s,this.gifProperties&&(this.gifProperties.frames[this.gifProperties.displayIndex].image=n.imageData),this.drawingContext.putImageData(n.imageData,e,t,0,0,r,i),this.setModified(!0)}get(t,r,i,n){const s=this._pixelsState,a=this._pixelDensity,o=this.canvas;if(void 0===t&&void 0===r)t=r=0,i=s.width,n=s.height;else if(t*=a,r*=a,void 0===i&&void 0===n)return t<0||r<0||t>=o.width||r>=o.height?[0,0,0,0]:this._getPixel(t,r);const h=new e(i*a,n*a);return h.pixelDensity(a),h.canvas.getContext("2d").drawImage(o,t,r,i*a,n*a,0,0,i*a,n*a),h}_getPixel(e,t){let r,i;return r=this.drawingContext.getImageData(e,t,1,1).data,i=0,[r[0],r[1],r[2],r[3]]}set(t,r,i){t=Math.floor(t),r=Math.floor(r);const n=this._pixelsState;if(i instanceof e)this.drawingContext.save(),this.drawingContext.setTransform(1,0,0,1,0,0),this.drawingContext.scale(this._pixelDensity,this._pixelDensity),this.drawingContext.clearRect(t,r,i.width,i.height),this.drawingContext.drawImage(i.canvas,t,r),this.drawingContext.restore();else{let e=0,s=0,a=0,o=0,h=4*(r*this._pixelDensity*(this.width*this._pixelDensity)+t*this._pixelDensity);if(n.imageData||n.loadPixels(),"number"==typeof i)h{let r=0;for(let i=0;i0&&this.loadPixels(),this.setModified(!0)}copy(...e){let t,r,i,n,s,a,o,h,u;if(9===e.length)t=e[0],r=e[1],i=e[2],n=e[3],s=e[4],a=e[5],o=e[6],h=e[7],u=e[8];else{if(8!==e.length)throw new Error("Signature not supported");t=this,r=e[0],i=e[1],n=e[2],s=e[3],a=e[4],o=e[5],h=e[6],u=e[7]}this._copyHelper(this,t,r,i,n,s,a,o,h,u)}_copyHelper(e,t,r,i,n,s,a,o,h,u){const l=t.canvas.width/t.width;let c=0,p=0;t._renderer&&t._renderer.isP3D&&(c=t.width/2,p=t.height/2),e._renderer&&e._renderer.isP3D?(e.push(),e.resetMatrix(),e.noLights(),e.blendMode(e.BLEND),e.imageMode(e.CORNER),e._renderer.image(t,r+c,i+p,n,s,a,o,h,u),e.pop()):e.drawingContext.drawImage(t.canvas,l*(r+c),l*(i+p),l*n,l*s,a,o,h,u)}mask(e){void 0===e&&(e=this);const t=this.drawingContext.globalCompositeOperation;let r=this._pixelDensity,i=1;e instanceof ds&&(i=e._pInst._renderer._pixelDensity);const n=[e,0,0,i*e.width,i*e.height,0,0,r*this.width,r*this.height];if(this.drawingContext.globalCompositeOperation="destination-in",this.gifProperties){for(let e=0;eparseInt(e)));o=o.concat(a[u].frames);const l=new Set(u);for(let e=1;eparseInt(e))).filter((e=>!l.has(e)));if(u.length+t.length<=256){for(let e=0;e{i?(void 0===h[e]&&(h[e]=n.length,n.push(e)),a[r]=h[e]):a[r]=c[e],t>0&&s[t-1][r]!==e&&l.add(e)}));const p={},d=n.filter((e=>!l.has(e)));if(d.length>0){const e=d[0],r=i?h[e]:c[e];if(t>0){for(let e=0;e0&&f.addFrame(0,0,e.width,e.height,m.pixelPaletteIndex,m.frameOpts),m={pixelPaletteIndex:a,frameOpts:p}}m.frameOpts.disposal=1,f.addFrame(0,0,e.width,e.height,m.pixelPaletteIndex,m.frameOpts);const g="gif";Mn(new Blob([n.slice(0,f.end())],{type:"image/gif"}),t,g)}(this,e);else{let r,i=this.canvas;switch(t=t||In(e,t)[1]||"png"){default:r="image/png";break;case"webp":r="image/webp";break;case"jpeg":case"jpg":r="image/jpeg"}i.toBlob((r=>{Mn(r,e,t)}),r)}}async toBlob(){return new Promise((e=>{this.canvas.toBlob(e)}))}reset(){if(this.gifProperties){const e=this.gifProperties;e.playing=!0,e.timeSinceStart=0,e.timeDisplayed=0,e.lastChangeTime=0,e.loopCount=0,e.displayIndex=0,this.drawingContext.putImageData(e.frames[0].image,0,0)}}getCurrentFrame(){if(this.gifProperties){const e=this.gifProperties;return e.displayIndex%e.numFrames}}setFrame(e){if(this.gifProperties){const t=this.gifProperties;e=0?(t.timeDisplayed=0,t.lastChangeTime=0,t.displayIndex=e,this.drawingContext.putImageData(t.frames[e].image,0,0)):this._friendlyError("Cannot set GIF to a frame number that is higher than total number of frames or below zero.","setFrame")}}numFrames(){if(this.gifProperties)return this.gifProperties.numFrames}play(){this.gifProperties&&(this.gifProperties.playing=!0)}pause(){this.gifProperties&&(this.gifProperties.playing=!1)}delay(e,t){if(this.gifProperties){const r=this.gifProperties;if(t=0)r.frames[t].delay=e;else for(const t of r.frames)t.delay=e}}};function Ln(e,t){e.Image=Bn,Bn.prototype._friendlyError=e._friendlyError}void 0!==p5&&Ln(p5);const On=function(e,t){const r=Math.min(e,t.length);return Array.isArray(t)&&e!==t.length&&console.warn("When working with two vectors of different sizes, the smaller dimension is used. In this operation, both vector will be treated as "+r+"D vectors, and any additional values of the linger vector will be ignored."),r},Pn=function(e,t){for(;e.length>t;)e.pop()};class Nn{values=[];static friendlyErrorsDisabled(){return!0}constructor(...e){if(0===e.length&&this._friendlyError("Requires valid arguments.","p5.Vector"),"function"==typeof e[0]&&(this.isPInst=!0,this._fromRadians=e.shift(),this._toRadians=e.shift()),this.values=e,Array.isArray(e))for(let t=0;t1&&(this.values[0]=e)}set y(e){this.values.length>1&&(this.values[1]=e)}set z(e){this.values.length>2&&(this.values[2]=e)}set w(e){this.values.length>3&&(this.values[3]=e)}toString(){return`vector[${this.values.join(", ")}]`}set(...e){return e[0]instanceof Nn?this.values=e[0].values.slice():Array.isArray(e[0])?this.values=e[0].map((e=>e||0)):this.values=e.map((e=>e||0)),this}copy(){return this.isPInst?new Nn(this._fromRadians,this._toRadians,...this.values):new Nn(...this.values)}add(e){const t=On(this.dimensions,e);Pn(this.values,t);for(let t=0;t0&&(this.values[t]=this.values[t]%e[t]);else if(e>0)for(let t=0;te*e&&this.div(Math.sqrt(t)).mult(e),this}setMag(e){return this.normalize().mult(e)}heading(){const e=Math.atan2(this.y,this.x);return this.isPInst?this._fromRadians(e):e}setHeading(e){if(this.dimensions<2||this._values instanceof Array&&this._values.slice(2).some((e=>0!==e)))return p5._friendlyError("p5.Vector.setHeading() only supports 2D vectors (z === 0). For 3D or higher-dimensional vectors, use rotate() or another appropriate method instead.","p5.Vector.setHeading"),this;const t=this.mag();return this.x=t*Math.cos(e),this.y=t*Math.sin(e),this}rotate(e){let t=this.heading()+e;this.isPInst&&(t=this._toRadians(t));const r=this.mag();return this.x=Math.cos(t)*r,this.y=Math.sin(t)*r,this}angleBetween(e){if(0===this.magSq()*e.magSq())return NaN;const t=this.cross(e);let r=Math.atan2(t.mag(),this.dot(e))*Math.sign(t.z||1);return this.isPInst&&(r=this._fromRadians(r)),r}lerp(e,t,r,i){return e instanceof Nn?this.lerp(e.x,e.y,e.z,t):(this.x+=(e-this.x)*i||0,this.y+=(t-this.y)*i||0,this.z+=(r-this.z)*i||0,this)}slerp(e,t){if(0===t)return this;if(1===t)return this.set(e);const r=this.mag(),i=e.mag();if(0===r*i)return this.mult(1-t).add(e.x*t,e.y*t,e.z*t),this;const n=this.cross(e),s=n.mag(),a=Math.atan2(s,this.dot(e));if(s>0)n.x/=s,n.y/=s,n.z/=s;else{if(a<.5*Math.PI)return this.mult(1-t).add(e.x*t,e.y*t,e.z*t),this;0===this.z&&0===e.z?n.set(0,0,1):0!==this.x?n.set(this.y,-this.x,0).normalize():n.set(1,0,0)}const o=n.cross(this),h=1-t+t*i/r,u=h*Math.cos(t*a),l=h*Math.sin(t*a);return this.x=this.x*u+o.x*l,this.y=this.y*u+o.y*l,this.z=this.z*u+o.z*l,this}reflect(e){const t=Nn.normalize(e);return this.sub(t.mult(2*this.dot(t)))}array(){return[this.x||0,this.y||0,this.z||0]}equals(...e){let t;t=e[0]instanceof Nn?e[0].values:Array.isArray(e[0])?e[0]:e;for(let e=0;e0))throw new Error("At least one vertex must be passed to the constructor.");this.vertices=e}get vertexCount(){return this.vertices.length}get vertexCapacity(){throw new Error("Getter vertexCapacity must be implemented.")}get _firstInterpolatedVertex(){return this.startVertex()}get canOverrideAnchor(){return!1}accept(e){throw new Error("Method accept() must be implemented.")}addToShape(e){let t=e.at(-1);if(0===t.primitives.length)t.primitives.push(this);else{let r,i,n=e.at(-1,-1),s=n instanceof this.constructor,a=n.vertexCapacity-n.vertexCount;s&&a>0?(r=this.vertices.splice(0,a),i=this.vertices,n.vertices.push(...r),i.length>0&&t.primitives.push(this)):t.primitives.push(this)}if(this.vertices.length>0){let t=e.at(-1);this._primitivesIndex=t.primitives.length-1,this._contoursIndex=e.contours.length-1,this._shape=e}return e.at(-1,-1)}get _nextPrimitive(){return this._belongsToShape?this._shape.at(this._contoursIndex,this._primitivesIndex+1):null}get _belongsToShape(){return null!==this._shape}handlesClose(){return!1}close(e){throw new Error("Unimplemented!")}}class jn{#i;primitives;constructor(e=8){this.#i=e,this.primitives=[]}get kind(){const e=0===this.primitives.length,t=8===this.#i;return e&&t?7:this.#i}accept(e){for(const t of this.primitives)t.accept(e)}}class Gn extends zn{get vertexCapacity(){return 1}accept(e){e.visitAnchor(this)}getEndVertex(){return this.vertices[0]}}class $n extends zn{constructor(...e){if(super(...e),new.target===$n)throw new Error("Segment is an abstract class: it cannot be instantiated.")}get _previousPrimitive(){return this._belongsToShape?this._shape.at(this._contoursIndex,this._primitivesIndex-1):null}getStartVertex(){return this._previousPrimitive.getEndVertex()}getEndVertex(){return this.vertices[this.vertices.length-1]}}class Hn extends $n{get vertexCapacity(){return 1}accept(e){e.visitLineSegment(this)}}let qn=class extends $n{#n;#s;constructor(e,...t){super(...t);let r=Array.isArray(e)?e[0]:e;this.#n=r,this.#s=r}get order(){return this.#n}get vertexCapacity(){return this.#s}#a;hullLength(){return void 0===this.#a&&(this.#a=Vn([this.getStartVertex(),...this.vertices])),this.#a}accept(e){e.visitBezierSegment(this)}};class Wn extends $n{#s=1/0;_splineProperties={ends:Ge,tightness:0};get vertexCapacity(){return this.#s}accept(e){e.visitSplineSegment(this)}get _comesAfterSegment(){return this._previousPrimitive instanceof $n}get canOverrideAnchor(){return this._splineProperties.ends===$e}get _firstInterpolatedVertex(){return this._splineProperties.ends===$e?this._comesAfterSegment?this.vertices[1]:this.vertices[0]:this.getStartVertex()}get _chainedToSegment(){if(this._belongsToShape&&this._comesAfterSegment){let e=this._firstInterpolatedVertex.position;return this.getStartVertex().position.equals(e)}return!1}addToShape(e){const t=super.addToShape(e);if(this._splineProperties.ends=e._splineProperties.ends,this._splineProperties.tightness=e._splineProperties.tightness,this._splineProperties.ends!==$e)return t;let r=!this._belongsToShape,i=e.at(-1,-1);if(r&&2===i.vertices.length&&i._comesAfterSegment&&!i._chainedToSegment){let e=i._firstInterpolatedVertex.position,t=i.getStartVertex().position;console.warn((n=e.array(),s=t.array(),`Spline does not start where previous path segment ends:\n second spline vertex at (${n})\n expected to be at (${s}).`))}var n,s;return t}getEndVertex(){return this._splineProperties.ends===Ge?super.getEndVertex():this._splineProperties.ends===$e?this.vertices.at(-2):this.getStartVertex()}getControlPoints(){let e=[];this._comesAfterSegment&&e.push(this.getStartVertex()),e.push(this.getStartVertex());for(const t of this.vertices)e.push(t);const t=this.getStartVertex();return this._splineProperties.ends===Ge?(e.unshift(t),e.push(this.vertices.at(-1))):this._splineProperties.ends===He&&(e.unshift(this.vertices.at(-1)),e.push(t,this.vertices.at(0))),e}handlesClose(){if(!this._belongsToShape)return!1;return 2===this._shape.at(this._contoursIndex).primitives.length&&1===this._primitivesIndex}close(){this._splineProperties.ends=He}}class Xn extends zn{get vertexCapacity(){return 1}accept(e){e.visitPoint(this)}}class Yn extends zn{get vertexCapacity(){return 2}accept(e){e.visitLine(this)}}class Zn extends zn{get vertexCapacity(){return 3}accept(e){e.visitTriangle(this)}}class Kn extends zn{get vertexCapacity(){return 4}accept(e){e.visitQuad(this)}}class Jn extends zn{#o;#h;#u;#l;#c;#p;#d;#s=2;constructor(e,t,r,i,n,s,a,o,h){super(e,t),this.#o=r,this.#h=i,this.#u=n,this.#l=s,this.#c=a,this.#p=o,this.#d=h}get x(){return this.#o}get y(){return this.#h}get w(){return this.#u}get h(){return this.#l}get start(){return this.#c}get stop(){return this.#p}get mode(){return this.#d}get startVertex(){return this.vertices[0]}get endVertex(){return this.vertices[1]}get vertexCapacity(){return this.#s}accept(e){e.visitArcPrimitive(this)}}class Qn extends zn{#o;#h;#u;#l;#s=1;constructor(e,t,r,i,n){super(e),this.#o=t,this.#h=r,this.#u=i,this.#l=n}get x(){return this.#o}get y(){return this.#h}get w(){return this.#u}get h(){return this.#l}get vertexCapacity(){return this.#s}accept(e){e.visitEllipsePrimitive(this)}}class es extends zn{#o;#h;#u;#l;#f;#m;#g;#y;#s=1;constructor(e,t,r,i,n,s,a,o,h){super(e),this.#o=t,this.#h=r,this.#u=i,this.#l=n,this.#f=s,this.#m=a,this.#g=o,this.#y=h}get x(){return this.#o}get y(){return this.#h}get w(){return this.#u}get h(){return this.#l}get tl(){return this.#f}get tr(){return this.#m}get br(){return this.#g}get bl(){return this.#y}get vertexCapacity(){return this.#s}accept(e){e.visitRectPrimitive(this)}}class ts extends zn{get vertexCapacity(){return 1/0}accept(e){e.visitTriangleFan(this)}}class rs extends zn{get vertexCapacity(){return 1/0}accept(e){e.visitTriangleStrip(this)}}class is extends zn{get vertexCapacity(){return 1/0}accept(e){e.visitQuadStrip(this)}}const ns={vertex:{[R]:(...e)=>new Gn(...e),[V]:(...e)=>new Hn(...e),[M]:(...e)=>new Xn(...e),[I]:(...e)=>new Yn(...e),[B]:(...e)=>new Zn(...e),[P]:(...e)=>new Kn(...e),[L]:(...e)=>new ts(...e),[O]:(...e)=>new rs(...e),[N]:(...e)=>new is(...e)},bezierVertex:{[R]:(e,...t)=>new Gn(...t),[V]:(e,...t)=>new qn(e,...t)},splineVertex:{[R]:(...e)=>new Gn(...e),[V]:(...e)=>new Wn(...e)}};class ss{#x;#v;#b;#_=3;kind=null;contours=[];_splineProperties={tightness:0,ends:Ge};userVertexProperties=null;constructor(e,t=ns){this.#v=e,this.#x=e,this.#b=t;for(const e in this.#x)"position"!==e&&"textureCoordinates"!==e&&(this[e]=function(t){this.#x[e]=t})}serializeToArray(e){if(null==e)return[];if(e instanceof Number)return[e];if(e instanceof Array)return e;if(e.array instanceof Function)return e.array();throw new Error(`Can't convert ${e} to array!`)}vertexToArray(e){const t=[];for(const r in this.#x){if(this.userVertexProperties&&r in this.userVertexProperties)continue;const i=e[r];t.push(...this.serializeToArray(i))}for(const r in this.userVertexProperties)r in e?t.push(...this.serializeToArray(e[r])):t.push(...new Array(this.userVertexProperties[r]).fill(0));return t}hydrateValue(e,t){if(null===t)return null;if(t instanceof Number)return e.shift();if(t instanceof Array){const r=[];for(let i=0;ie*t))}arraySum(e,...t){return e.map(((e,r)=>{let i=e;for(let e=0;ee-t[r]))}evaluateCubicBezier([e,t,r,i],n){return this.arraySum(this.arrayScale(e,Math.pow(1-n,3)),this.arrayScale(t,3*Math.pow(1-n,2)*n),this.arrayScale(r,3*(1-n)*Math.pow(n,2)),this.arrayScale(i,Math.pow(n,3)))}evaluateQuadraticBezier([e,t,r],i){return this.arraySum(this.arrayScale(e,Math.pow(1-i,2)),this.arrayScale(t,2*(1-i)*i),this.arrayScale(r,i*i))}catmullRomToBezier(e,t){let r=1-t,i=[];for(let t=0;t+30&&8===n.kind){const s=this.#w(e,t),a=n.primitives,o=a[a.length-1];if(!r&&o instanceof Hn&&!o.isClosing)return void o.vertices.push(s);const h=new Hn(s);return h.isClosing=r,h._primitivesIndex=a.length,h._contoursIndex=i.length-1,h._shape=this,void a.push(h)}this.#E("vertex",e,t).isClosing=r}bezierVertex(e,t){this.#E("bezierVertex",e,t)}splineVertex(e,t){this.#E("splineVertex",e,t)}arcVertex(e,t){this.#E("arcVertex",e,t)}arcPrimitive(e,t,r,i,n,s,a){this.beginShape();const o=e+r/2,h=t+i/2,u=r/2,l=i/2,c=this.#w(new Nn(o+u*Math.cos(n),h+l*Math.sin(n))),p=this.#w(new Nn(o+u*Math.cos(s),h+l*Math.sin(s)));return new Jn(c,p,e,t,r,i,n,s,a).addToShape(this),this.endShape(),this}ellipsePrimitive(e,t,r,i){const n=this.#w(new Nn(e+r/2,t+i/2));return new Qn(n,e,t,r,i).addToShape(this)}rectPrimitive(e,t,r,i,n,s,a,o){const h=this.#w(new Nn(e,t));return new es(h,e,t,r,i,n,s,a,o).addToShape(this)}point(e,t){const r=this.#w(new Nn(e,t));return new Xn(r).addToShape(this)}line(e,t,r,i){const n=this.#w(new Nn(e,t)),s=this.#w(new Nn(r,i));return new Yn(n,s).addToShape(this)}triangle(e,t,r,i,n,s){const a=this.#w(new Nn(e,t)),o=this.#w(new Nn(r,i)),h=this.#w(new Nn(n,s));return new Zn(a,o,h).addToShape(this)}quad(e,t,r,i,n,s,a,o){const h=this.#w(new Nn(e,t)),u=this.#w(new Nn(r,i)),l=this.#w(new Nn(n,s)),c=this.#w(new Nn(a,o));return new Kn(h,u,l,c).addToShape(this)}beginContour(e=8){7===this.at(-1)?.kind&&this.contours.pop(),this.contours.push(new jn(e))}endContour(e=z,t=this.contours.length-1){const r=this.at(t);if(e===U){const e=8===r.kind,i=this.at(t,0,0),n=Object.hasOwn(i,"position"),s=this.at(t,-1);if(e&&n)if(s.handlesClose())s.close(i);else{const e=this.contours.splice(t+1,this.contours.length-t-1),r=this.#x;this.#x={...r};for(const e in i)"position"!==e&&"textureCoordinates"!==e&&(this.#x[e]=i[e]);this.vertex(i.position,i.textureCoordinates,{isClosing:!0}),this.#x=r,this.contours.push(...e)}}}beginShape(e=8){this.kind=e,this.beginContour(e)}endShape(e=z){e===U&&this.endContour(e,0)}accept(e){for(const t of this.contours)t.accept(e)}}class as{constructor(){if(new.target===as)throw new Error("PrimitiveVisitor is an abstract class: it cannot be instantiated.")}visitAnchor(e){throw new Error("Method visitAnchor() has not been implemented.")}visitLineSegment(e){throw new Error("Method visitLineSegment() has not been implemented.")}visitBezierSegment(e){throw new Error("Method visitBezierSegment() has not been implemented.")}visitSplineSegment(e){throw new Error("Method visitSplineSegment() has not been implemented.")}visitArcSegment(e){throw new Error("Method visitArcSegment() has not been implemented.")}visitArcPrimitive(e){throw new Error("Method visitArcPrimitive() has not been implemented.")}visitEllipsePrimitive(e){throw new Error("Method visitEllipsePrimitive() has not been implemented.")}visitRectPrimitive(e){throw new Error("Method visitRectPrimitive() has not been implemented.")}visitPoint(e){throw new Error("Method visitPoint() has not been implemented.")}visitLine(e){throw new Error("Method visitLine() has not been implemented.")}visitTriangle(e){throw new Error("Method visitTriangle() has not been implemented.")}visitQuad(e){throw new Error("Method visitQuad() has not been implemented.")}visitTriangleFan(e){throw new Error("Method visitTriangleFan() has not been implemented.")}visitTriangleStrip(e){throw new Error("Method visitTriangleStrip() has not been implemented.")}visitQuadStrip(e){throw new Error("Method visitQuadStrip() has not been implemented.")}}class os extends as{path=new Path2D;strokePath=null;fillPath=null;strokeWeight;hasFill;hasStroke;constructor({strokeWeight:e,hasFill:t=!0,hasStroke:r=!0}){super(),this.strokeWeight=e,this.hasFill=t,this.hasStroke=r}visitAnchor(e){let t=e.getEndVertex();this.path.moveTo(t.position.x,t.position.y)}visitLineSegment(e){if(e.isClosing)this.path.closePath();else{const t=e.vertices;for(let e=0;et.vertexToArray(e)));let i=t.catmullRomToBezier(r,e._splineProperties.tightness).map((e=>e.map((e=>t.arrayToVertex(e)))));for(const e of i){const t=e.flatMap((e=>[e.position.x,e.position.y]));this.path.bezierCurveTo(...t)}}visitPoint(e){const{x:t,y:r}=e.vertices[0].position;this.path.moveTo(t,r),this.path.lineTo(t+1e-5,r)}visitLine(e){const{x:t,y:r}=e.vertices[0].position,{x:i,y:n}=e.vertices[1].position;this.path.moveTo(t,r),this.path.lineTo(i,n)}visitTriangle(e){const[t,r,i]=e.vertices;this.path.moveTo(t.position.x,t.position.y),this.path.lineTo(r.position.x,r.position.y),this.path.lineTo(i.position.x,i.position.y),this.path.closePath()}visitQuad(e){const[t,r,i,n]=e.vertices;this.path.moveTo(t.position.x,t.position.y),this.path.lineTo(r.position.x,r.position.y),this.path.lineTo(i.position.x,i.position.y),this.path.lineTo(n.position.x,n.position.y),this.path.closePath()}visitTriangleFan(e){const[t,...r]=e.vertices;for(let e=0;e1e-5,u=!(e.mode===j||e.mode===z||h);this.hasFill&&(this.fillPath||(this.fillPath=new Path2D(this.path)),this.fillPath.moveTo(s,a),this.fillPath.ellipse(t,r,i,n,0,e.start,e.stop),u&&this.fillPath.lineTo(t,r),this.fillPath.closePath()),this.hasStroke&&(this.strokePath||(this.strokePath=new Path2D(this.path)),this.strokePath.moveTo(s,a),this.strokePath.ellipse(t,r,i,n,0,e.start,e.stop),e.mode===G&&u&&this.strokePath.lineTo(t,r),e.mode!==G&&e.mode!==j||this.strokePath.closePath()),this.path.moveTo(s,a),this.path.ellipse(t,r,i,n,0,e.start,e.stop)}visitEllipsePrimitive(e){const t=e.x+e.w/2,r=e.y+e.h/2,i=e.w/2,n=e.h/2;this.path.moveTo(t+i,r),this.path.ellipse(t,r,i,n,0,0,2*Math.PI)}visitRectPrimitive(e){const t=e.x,r=e.y,i=e.w,n=e.h;let s=e.tl,a=e.tr,o=e.br,h=e.bl;if(void 0===s)this.path.rect(t,r,i,n);else{void 0===a&&(a=s),void 0===o&&(o=a),void 0===h&&(h=o);const e=Math.abs(i),u=Math.abs(n),l=e/2,c=u/2;e<2*s&&(s=l),u<2*s&&(s=c),e<2*a&&(a=l),u<2*a&&(a=c),e<2*o&&(o=l),u<2*o&&(o=c),e<2*h&&(h=l),u<2*h&&(h=c),this.path.roundRect(t,r,i,n,[s,a,o,h])}}visitQuadStrip(e){for(let t=0;te._shape.vertexToArray(t)));for(let n=0;nt.vertexToArray(e)));let n=t.catmullRomToBezier(i,e._splineProperties.tightness),s=t.vertexToArray(e._firstInterpolatedVertex);for(const e of n){const i=[s,...e],n=Math.max(1,Math.ceil(Vn(i.map((e=>t.arrayToVertex(e))))*this.curveDetail));for(let e=0;e[e,e]))):this.contours.push(e.vertices.slice())}visitLine(e){this.contours.push(e.vertices.slice())}visitTriangle(e){this.contours.push(e.vertices.slice())}visitQuad(e){this.contours.push(e.vertices.slice())}visitTriangleFan(e){this.contours.push(e.vertices.slice())}visitTriangleStrip(e){this.contours.push(e.vertices.slice())}visitQuadStrip(e){this.contours.push(e.vertices.slice())}visitArcPrimitive(e){const t=e.startVertex,r=e.endVertex,i=e.x+e.w/2,n=e.y+e.h/2,s=e.w/2,a=e.h/2,o=(s+a)/2*Math.abs(e.stop-e.start),h=Math.max(3,Math.ceil(this.curveDetail*o)),u=[],l=(e,t,r)=>{const i={};for(const[n,s]of Object.entries(e))"position"!==n&&("number"==typeof s&&"number"==typeof t[n]?i[n]=s*(1-r)+t[n]*r:i[n]=s);return i};if(e.mode===G){const e=l(t,r,.5);e.position=new Nn(i,n),u.push(new Un(e))}for(let o=0;o<=h;o++){const c=o/h,p=e.start+(e.stop-e.start)*c,d=l(t,r,c);d.position=new Nn(i+s*Math.cos(p),n+a*Math.sin(p)),u.push(new Un(d))}this.contours.push(u)}visitEllipsePrimitive(e){const t=e.x+e.w/2,r=e.y+e.h/2,i=e.w/2,n=e.h/2,s=(i+n)/2,a=2*Math.PI*s,o=Math.max(3,Math.ceil(this.curveDetail*a)),h=[],u=e.vertices[0];for(let e=0;e<=o;e++){const s=2*Math.PI*e/o,a={};for(const[e,t]of Object.entries(u))"position"!==e&&(a[e]=t);a.position=new Nn(t+i*Math.cos(s),r+n*Math.sin(s)),h.push(new Un(a))}this.contours.push(h)}visitRectPrimitive(e){const t=e.x,r=e.y,i=e.w,n=e.h;let s=e.tl,a=e.tr,o=e.br,h=e.bl;const u=e.vertices[0],l=(e,t)=>{const r={};for(const[e,t]of Object.entries(u))"position"!==e&&(r[e]=t);return r.position=new Nn(e,t),new Un(r)},c=[];if(void 0===s)c.push(l(t,r)),c.push(l(t+i,r)),c.push(l(t+i,r+n)),c.push(l(t,r+n)),c.push(l(t,r));else{void 0===a&&(a=s),void 0===o&&(o=a),void 0===h&&(h=o);const e=Math.abs(i),u=Math.abs(n),p=e/2,d=u/2;e<2*s&&(s=p),u<2*s&&(s=d),e<2*a&&(a=p),u<2*a&&(a=d),e<2*o&&(o=p),u<2*o&&(o=d),e<2*h&&(h=p),u<2*h&&(h=d);const f=(e,t,r,i,n,s)=>{const a=Math.PI/2*(r+i)/2,o=Math.max(1,Math.ceil(this.curveDetail*a));for(let a=0;a<=o;a++){const h=n+a/o*(s-n);c.push(l(e+r*Math.cos(h),t+i*Math.sin(h)))}};f(t+s,r+s,s,s,Math.PI,1.5*Math.PI),f(t+i-a,r+a,a,a,1.5*Math.PI,2*Math.PI),f(t+i-o,r+n-o,o,o,0,.5*Math.PI),f(t+h,r+n-h,h,h,.5*Math.PI,Math.PI),c.push(c[0])}this.contours.push(c)}}class us extends as{constructor(){super()}}function ls(e,t){e.Shape=ss,e.Contour=jn,e.ShapePrimitive=zn,e.Vertex=Un,e.Anchor=Gn,e.Segment=$n,e.LineSegment=Hn,e.BezierSegment=qn,e.SplineSegment=Wn,e.Point=Xn,e.Line=Yn,e.Triangle=Zn,e.Quad=Kn,e.TriangleFan=ts,e.TriangleStrip=rs,e.QuadStrip=is,e.PrimitiveVisitor=as,e.PrimitiveToPath2DConverter=os,e.PrimitiveToVerticesConverter=hs,e.PointAtLengthGetter=us,t.bezierOrder=function(e){return this._renderer.bezierOrder(e)},t.splineVertex=function(...e){let t=0,r=0,i=0,n=0,s=0;2===e.length?[t,r]=e:4===e.length?[t,r,n,s]=e:3===e.length?[t,r,i]=e:5===e.length&&([t,r,i,n,s]=e),this._renderer.splineVertex(t,r,i,n,s)},t.splineProperty=function(e,t){return this._renderer.splineProperty(e,t)},t.splineProperties=function(e){return this._renderer.splineProperties(e)},t.vertex=function(e,t){let r,i,n;r=i=n=0,3===arguments.length?r=arguments[2]:4===arguments.length?(i=arguments[2],n=arguments[3]):5===arguments.length&&(r=arguments[2],i=arguments[3],n=arguments[4]),this._renderer.vertex(e,t,r,i,n)},t.beginContour=function(e){this._renderer.beginContour(e)},t.endContour=function(e=z){this._renderer.endContour(e)}}void 0!==p5&&ls(p5,p5.prototype);class cs{#A={};constructor(e){for(const t in e)this[t]=e[t]}setValue(e,t){e in this.#A||(this.#A[e]=this[e]),this[e]=t}takeDiff(){const e=this.#A;return this.#A={},e}getModified(){return this.#A}applyDiff(e){for(const e in this.#A)this[e]=this.#A[e];this.#A=e}}class ps{constructor(e={}){for(const t in e)this[t]=e[t]}clone(){return new ps(this)}}class ds{static states={strokeColor:null,strokeSet:!1,fillColor:null,fillSet:!1,tint:null,imageMode:w,rectMode:w,ellipseMode:S,strokeWeight:1,bezierOrder:3,splineProperties:new ps({ends:Ge,tightness:0}),textFont:{family:"sans-serif"},textLeading:15,leadingSet:!1,textSize:12,textAlign:D,textBaseline:k,textWrap:_e,fontStyle:be,fontStretch:be,fontWeight:be,lineHeight:be,fontVariant:be,direction:"inherit"};constructor(e,t,r,i){this._pInst=e,this._isMainCanvas=i,this.pixels=[];const n="undefined"!=typeof window?Math.ceil(window.devicePixelRatio):1;if(i)this._pixelDensity=n;else{const t=e._pInst?._renderer?._pixelDensity;this._pixelDensity=t||n}this.width=t,this.height=r,this._events={},i&&(this._isMainCanvas=!0),this.states=new cs(ds.states),this.states.strokeColor=new Di([0,0,0]),this.states.fillColor=new Di([1,1,1]),this._pushPopStack=[],this._pushPopDepth=0,this._clipping=!1,this._clipInvert=!1,this._currentShape=void 0,this._supportsIndividualTextureCoordinates=void 0}get currentShape(){return this._currentShape||(this._currentShape=new ss(this.getCommonVertexProperties())),this._currentShape}remove(){}pixelDensity(e){let t;return"number"==typeof e?(e!==this._pixelDensity&&(this._pixelDensity=e),t=this,this.resize(this.width,this.height)):t=this._pixelDensity,t}push(){this._pushPopDepth++,this._pushPopStack.push(this.states.takeDiff())}pop(){this._pushPopDepth--;const e=this._pushPopStack.pop()||{},t=this.states.getModified();this.states.applyDiff(e),this.updateShapeVertexProperties(t),this.updateShapeProperties(t)}bezierOrder(e){if(void 0===e)return this.states.bezierOrder;this.states.setValue("bezierOrder",e),this.updateShapeProperties()}_individualTextureCoordinates(e,t){return void 0===this._supportsIndividualTextureCoordinates&&(this._supportsIndividualTextureCoordinates=this.getSupportedIndividualVertexProperties().textureCoordinates),this._supportsIndividualTextureCoordinates?new Nn(e,t):void 0}bezierVertex(e,t,r=0,i=0,n=0){const s=new Nn(e,t,r),a=this._individualTextureCoordinates(i,n);this.currentShape.bezierVertex(s,a)}splineProperty(e,t){if(void 0===t)return this.states.splineProperties[e];this.states.setValue("splineProperties",this.states.splineProperties.clone()),this.states.splineProperties[e]=t,this.updateShapeProperties()}splineProperties(e){if(!e)return{...this.states.splineProperties};for(const t in e)this.splineProperty(t,e[t])}splineVertex(e,t,r=0,i=0,n=0){const s=new Nn(e,t,r),a=this._individualTextureCoordinates(i,n);this.currentShape.splineVertex(s,a)}curveDetail(e){if(void 0===e)return this.states.curveDetail;this.states.setValue("curveDetail",e)}beginShape(...e){this.currentShape.reset(),this.updateShapeVertexProperties(),this.currentShape.beginShape(...e)}endShape(...e){this.currentShape.endShape(...e),this.drawShape(this.currentShape)}beginContour(e){this.currentShape.beginContour(e)}endContour(e){this.currentShape.endContour(e)}drawShape(e,t){throw new Error("Unimplemented")}vertex(e,t,r=0,i=0,n=0){const s=new Nn(e,t,r),a=this._individualTextureCoordinates(i,n);this.currentShape.vertex(s,a)}bezier(e,t,r,i,n,s,a,o){const h=this._pInst.bezierOrder();return this._pInst.bezierOrder(h),this._pInst.beginShape(),this._pInst.bezierVertex(e,t),this._pInst.bezierVertex(r,i),this._pInst.bezierVertex(n,s),this._pInst.bezierVertex(a,o),this._pInst.endShape(),this}spline(...e){if(8===e.length){const[t,r,i,n,s,a,o,h]=e;this._pInst.beginShape(),this._pInst.splineVertex(t,r),this._pInst.splineVertex(i,n),this._pInst.splineVertex(s,a),this._pInst.splineVertex(o,h),this._pInst.endShape()}else if(12===e.length){const[t,r,i,n,s,a,o,h,u,l,c,p]=e;this._pInst.beginShape(),this._pInst.splineVertex(t,r,i),this._pInst.splineVertex(n,s,a),this._pInst.splineVertex(o,h,u),this._pInst.splineVertex(l,c,p),this._pInst.endShape()}return this}beginClip(e={}){if(this._clipping)throw new Error("It looks like you're trying to clip while already in the middle of clipping. Did you forget to endClip()?");this._clipping=!0,this._clipInvert=e.invert}endClip(){if(!this._clipping)throw new Error("It looks like you've called endClip() without beginClip(). Did you forget to call beginClip() first?");this._clipping=!1}resize(e,t){this.width=e,this.height=t}get(e,t,r,i){const n=this._pixelDensity,s=this.canvas;if(void 0===e&&void 0===t)e=t=0,r=this.width,i=this.height;else if(e*=n,t*=n,void 0===r&&void 0===i)return e<0||t<0||e>=s.width||t>=s.height?[0,0,0,0]:this._getPixel(e,t);const a=new Bn(r*n,i*n);return a.pixelDensity(n),a.canvas.getContext("2d").drawImage(s,e,t,r*n,i*n,0,0,r*n,i*n),a}scale(e,t){}fill(...e){return e.length>0&&(this.states.setValue("fillSet",!0),this.states.setValue("fillColor",this._pInst.color(...e)),this.updateShapeVertexProperties()),this.states.fillColor}noFill(){this.states.setValue("fillColor",null)}strokeWeight(e){if(void 0===e)return this.states.strokeWeight;this.states.setValue("strokeWeight",e)}stroke(...e){if(0===e.length)return this.states.strokeColor;this.states.setValue("strokeSet",!0),this.states.setValue("strokeColor",this._pInst.color(...e)),this.updateShapeVertexProperties()}noStroke(){this.states.setValue("strokeColor",null)}getCommonVertexProperties(){return{}}getSupportedIndividualVertexProperties(){return{textureCoordinates:!1}}updateShapeProperties(e){if(!e||e.bezierOrder||e.splineProperties){const e=this.currentShape;e.bezierOrder(this.states.bezierOrder),e.splineProperty("ends",this.states.splineProperties.ends),e.splineProperty("tightness",this.states.splineProperties.tightness)}}updateShapeVertexProperties(e){const t=this.getCommonVertexProperties();if(!e||Object.keys(e).some((e=>e in t))){const e=this.currentShape;for(const r in t)e[r](t[r])}}_applyDefaults(){return this}finishDraw(){}_middleAlignOffset=function(){const{textFont:e,textSize:t}=this.states,r=e?.font,i=this.textDrawingContext().measureText("X");let n=(r?.data||{})["OS/2"]?.sCapHeight;if(n){n*=t/r.data.head.unitsPerEm}else n=i.fontBoundingBoxAscent;return i.alphabeticBaseline+n/2}}const fs="video",ms="audio";class gs{constructor(e,t,r,i){this.callback=e,this.time=t,this.id=r,this.val=i}}class ys extends En{constructor(e,t){super(e,t);const r=this;this.elt.crossOrigin="anonymous",this._prevTime=0,this._cueIDCounter=0,this._cues=[],this.pixels=[],this._pixelsState=this,this._pixelDensity=1,this._modified=!1,this._frameOnCanvas=-1,Object.defineProperty(r,"src",{get(){const e=r.elt.children[0].src,t=r.elt.src===window.location.href?"":r.elt.src;return e===window.location.href?t:e},set(t){for(let e=0;e1||this.elt.load(),e=this.elt.play(),e&&e.catch&&e.catch((e=>{"NotAllowedError"===e.name?console.error(e):console.error("Media play method encountered an unexpected error",e)})),this}stop(){return this.elt.pause(),this.elt.currentTime=0,this}pause(){return this.elt.pause(),this}loop(){return this.elt.setAttribute("loop",!0),this.play(),this}noLoop(){return this.elt.removeAttribute("loop"),this}_setupAutoplayFailDetection(){const t=setTimeout((()=>{console.error(e)}),500);this.elt.addEventListener("play",(()=>clearTimeout(t)),{passive:!0,once:!0})}autoplay(e){const t=this.elt.getAttribute("autoplay");if(this.elt.setAttribute("autoplay",e),e&&!t){const e=()=>this._setupAutoplayFailDetection();4===this.elt.readyState?e():this.elt.addEventListener("canplay",e,{passive:!0,once:!0})}return this}volume(e){if(void 0===e)return this.elt.volume;this.elt.volume=e}speed(e){if(void 0===e)return this.presetPlaybackRate||this.elt.playbackRate;this.loadedmetadata?this.elt.playbackRate=e:this.presetPlaybackRate=e}time(e){return void 0!==e&&(this.elt.currentTime=e),this.elt.currentTime}duration(){return this.elt.duration}_checkIfTextureNeedsUpdate(){this._frameOnTexture!==this._pInst.frameCount&&(this.setModified(!0),this._frameOnTexture=this._pInst.frameCount)}_ensureCanvas(){this.canvas||(this.canvas=document.createElement("canvas"),this.drawingContext=this.canvas.getContext("2d"),this.setModified(!0));const e=this._frameOnCanvas!==this._pInst.frameCount;this.loadedmetadata&&e&&(this.canvas.width!==this.elt.width&&(this.canvas.width=this.elt.width,this.canvas.height=this.elt.height,this.width=this.canvas.width,this.height=this.canvas.height),this.drawingContext.clearRect(0,0,this.canvas.width,this.canvas.height),!0===this.flipped&&(this.drawingContext.save(),this.drawingContext.scale(-1,1),this.drawingContext.translate(-this.canvas.width,0)),this.drawingContext.drawImage(this.elt,0,0,this.canvas.width,this.canvas.height),!0===this.flipped&&this.drawingContext.restore(),this.setModified(!0),this._frameOnCanvas=this._pInst.frameCount)}loadPixels(...e){return this._ensureCanvas(),p5.Renderer2D.prototype.loadPixels.apply(this,e)}updatePixels(e,t,r,i){return this.loadedmetadata&&(this._ensureCanvas(),p5.Renderer2D.prototype.updatePixels.call(this,e,t,r,i)),this.setModified(!0),this}get(...e){return this._ensureCanvas(),p5.Renderer2D.prototype.get.apply(this,e)}_getPixel(...e){return this.loadPixels(),p5.Renderer2D.prototype._getPixel.apply(this,e)}set(e,t,r){this.loadedmetadata&&(this._ensureCanvas(),p5.Renderer2D.prototype.set.call(this,e,t,r),this.setModified(!0))}copy(...e){this._ensureCanvas(),p5.prototype.copy.apply(this,e)}mask(...e){this.loadPixels(),this.setModified(!0),p5.Image.prototype.mask.apply(this,e)}isModified(){return this._modified}setModified(e){this._modified=e}onended(e){return this._onended=e,this}_getAudioContext(){}_getSoundOut(){}connect(e){let t,r;if(this._getAudioContext()&&this._getSoundOut())t=this._getAudioContext(),r=this._getSoundOut().input;else try{t=e.context,r=t.destination}catch(e){throw"connect() is meant to be used with Web Audio API or p5.sound.js"}this.audioSourceNode||(this.audioSourceNode=t.createMediaElementSource(this.elt),this.audioSourceNode.connect(r)),e?e.input?this.audioSourceNode.connect(e.input):this.audioSourceNode.connect(e):this.audioSourceNode.connect(r)}disconnect(){if(!this.audioSourceNode)throw"nothing to disconnect";this.audioSourceNode.disconnect()}showControls(){this.elt.style["text-align"]="inherit",this.elt.controls=!0}hideControls(){this.elt.controls=!1}addCue(e,t,r){const i=this._cueIDCounter++,n=new gs(t,e,i,r);return this._cues.push(n),this.elt.ontimeupdate||(this.elt.ontimeupdate=this._onTimeUpdate.bind(this)),i}removeCue(e){for(let t=0;t{a.width=s.videoWidth,a.height=s.videoHeight,0===a.elt.width&&(a.elt.width=s.videoWidth),0===a.elt.height&&(a.elt.height=s.videoHeight),a.presetPlaybackRate&&(a.elt.playbackRate=a.presetPlaybackRate,delete a.presetPlaybackRate),a.loadedmetadata=!0})),"function"==typeof n){const e=()=>{n(a),s.removeEventListener("canplaythrough",e)};s.addEventListener("canplaythrough",e)}return a}t.createVideo=function(e,t){return i(this,fs,e,t)},t.createAudio=function(e,t){return i(this,ms,e,t)},t.VIDEO=fs,t.AUDIO=ms,void 0===navigator.mediaDevices&&(navigator.mediaDevices={}),void 0===navigator.mediaDevices.getUserMedia&&(navigator.mediaDevices.getUserMedia=function(e){const t=navigator.webkitGetUserMedia||navigator.mozGetUserMedia;return t?new Promise((function(r,i){t.call(navigator,e,r,i)})):Promise.reject(new Error("getUserMedia is not implemented in this browser"))}),t.createCapture=function(...i){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new DOMException("getUserMedia not supported in this browser");let n,s,a=!0,o=!0,h=!1;for(const e of i)e===t.VIDEO?o=!1:e===t.AUDIO?a=!1:"object"==typeof e?(void 0!==e.flipped&&(h=e.flipped,delete e.flipped),n=Object.assign({},n,e)):"function"==typeof e&&(s=e);const u={video:a,audio:o};n=Object.assign({},u,n);const l=document.createElement(fs);l.setAttribute("playsinline",""),navigator.mediaDevices.getUserMedia(n).then((function(e){try{"srcObject"in l?l.srcObject=e:l.src=window.URL.createObjectURL(e)}catch(t){l.src=e}})).catch((t=>{"NotFoundError"===t.name&&e._friendlyError("No webcam found on this device","createCapture"),"NotAllowedError"===t.name&&e._friendlyError("Access to the camera was denied","createCapture"),console.error(t)}));const c=r(l,this,!0);return c.loadedmetadata=!1,l.addEventListener("loadedmetadata",(function(){l.play(),l.width?(c.width=l.width,c.height=l.height):(c.width=c.elt.width=l.videoWidth,c.height=c.elt.height=l.videoHeight),h&&(c.elt.style.transform="scaleX(-1)"),c.loadedmetadata=!0,s&&s(l.srcObject)})),c.flipped=h,c},e.MediaElement=ys,ys.prototype._getSoundOut=function(){return e.soundOut},ys.prototype._getAudioContext=function(){return"function"==typeof t.getAudioContext?t.getAudioContext():void 0}}void 0!==p5&&xs(p5,p5.prototype);var vs={modeAdjust:function(e,t,r,i,n){let s;return n===w?s={x:e,y:t,w:Math.abs(r),h:Math.abs(i)}:n===C?s={x:Math.min(e,r),y:Math.min(t,i),w:Math.abs(r-e),h:Math.abs(i-t)}:n===E?s={x:e-(r=Math.abs(r)),y:t-(i=Math.abs(i)),w:2*r,h:2*i}:n===S&&(s={x:e-.5*(r=Math.abs(r)),y:t-.5*(i=Math.abs(i)),w:r,h:i}),s}};function bs(e,t){t._normalizeArcAngles=(e,t,r,i,n)=>{let s;return e-=v*Math.floor(e/v),t-=v*Math.floor(t/v),s=Math.min(Math.abs(e-t),v-Math.abs(e-t)),n&&(e=e<=m?Math.atan(r/i*Math.tan(e)):e>m&&e<=3*m?Math.atan(r/i*Math.tan(e))+g:Math.atan(r/i*Math.tan(e))+v,t=t<=m?Math.atan(r/i*Math.tan(t)):t>m&&t<=3*m?Math.atan(r/i*Math.tan(t))+g:Math.atan(r/i*Math.tan(t))+v),e>t&&(t+=v),{start:e,stop:t,correspondToSamePoint:s<1e-5}},t.arc=function(e,t,r,i,n,s,a,o){if(!this._renderer.states.strokeColor&&!this._renderer.states.fillColor)return this;if(n===s)return this;n=this._toRadians(n),s=this._toRadians(s);const h=vs.modeAdjust(e,t,r,i,this._renderer.states.ellipseMode),u=this._normalizeArcAngles(n,s,h.w,h.h,!0);return u.correspondToSamePoint?this._renderer.ellipse([h.x,h.y,h.w,h.h,o]):(this._renderer.arc(h.x,h.y,h.w,h.h,u.start,u.stop,a,o),(this._accessibleOutputs.grid||this._accessibleOutputs.text)&&this._accsOutput("arc",[h.x,h.y,h.w,h.h,u.start,u.stop,a])),this},t.ellipse=function(e,t,r,i,n){return this._renderEllipse(...arguments)},t.circle=function(...e){const t=e.slice(0,2);return t.push(e[2],e[2]),this._renderEllipse(...t)},t._renderEllipse=function(e,t,r,i,n){if(!this._renderer.states.strokeColor&&!this._renderer.states.fillColor)return this;void 0===i&&(i=r);const s=vs.modeAdjust(e,t,r,i,this._renderer.states.ellipseMode);return this._renderer.ellipse([s.x,s.y,s.w,s.h,n]),(this._accessibleOutputs.grid||this._accessibleOutputs.text)&&this._accsOutput("ellipse",[s.x,s.y,s.w,s.h]),this},t.line=function(...e){return this._renderer.states.strokeColor&&this._renderer.line(...e),(this._accessibleOutputs.grid||this._accessibleOutputs.text)&&this._accsOutput("line",e),this},t.point=function(...t){return this._renderer.states.strokeColor&&(1===t.length&&t[0]instanceof e.Vector?this._renderer.point.call(this._renderer,t[0].x,t[0].y,t[0].z):(this._renderer.point(...t),(this._accessibleOutputs.grid||this._accessibleOutputs.text)&&this._accsOutput("point",t))),this},t.quad=function(...e){return(this._renderer.states.strokeColor||this._renderer.states.fillColor)&&(this._renderer.isP3D&&e.length<12?this._renderer.quad.call(this._renderer,e[0],e[1],0,e[2],e[3],0,e[4],e[5],0,e[6],e[7],0,e[8],e[9]):(this._renderer.quad(...e),(this._accessibleOutputs.grid||this._accessibleOutputs.text)&&this._accsOutput("quadrilateral",e))),this},t.rect=function(...e){return this._renderRect(...e)},t.square=function(e,t,r,i,n,s,a){return this._renderRect.call(this,e,t,r,r,i,n,s,a)},t._renderRect=function(){if(this._renderer.states.strokeColor||this._renderer.states.fillColor){3===arguments.length&&(arguments[3]=arguments[2]);const e=vs.modeAdjust(arguments[0],arguments[1],arguments[2],arguments[3],this._renderer.states.rectMode);this._renderer.states.rectMode===w&&(e.w=arguments[2],e.h=arguments[3]);const t=[e.x,e.y,e.w,e.h];for(let e=4;e>=h,l-=h,g!==s){if(g===a)break;for(var y=gs;)v=f[v]>>8,++x;var b=v;if(p+x+(y!==g?1:0)>i)return void console.log("Warning, gif stream longer than expected.");r[p++]=b;var _=p+=x;for(y!==g&&(r[p++]=b),v=y;x--;)v=f[v],r[--_]=255&v,v>>=8;null!==m&&o<4096&&(f[o++]=m<<8|b,o>=u+1&&h<12&&(++h,u=u<<1|1)),m=g}else o=a+1,u=(1<<(h=n+1))-1,m=null}return p!==i&&console.log("Warning, gif stream shorter than expected."),r}try{Ds=function(e,t,r,i){var n=0,s=void 0===(i=void 0===i?{}:i).loop?null:i.loop,a=void 0===i.palette?null:i.palette;if(t<=0||r<=0||t>65535||r>65535)throw new Error("Width/Height invalid.");function o(e){var t=e.length;if(t<2||t>256||t&t-1)throw new Error("Invalid code/color length, must be power of 2 and 2 .. 256.");return t}e[n++]=71,e[n++]=73,e[n++]=70,e[n++]=56,e[n++]=57,e[n++]=97;var h=0,u=0;if(null!==a){for(var l=o(a);l>>=1;)++h;if(l=1<=l)throw new Error("Background index out of range.");if(0===u)throw new Error("Background index explicitly passed as 0.")}}if(e[n++]=255&t,e[n++]=t>>8&255,e[n++]=255&r,e[n++]=r>>8&255,e[n++]=(null!==a?128:0)|h,e[n++]=u,e[n++]=0,null!==a)for(var c=0,p=a.length;c>16&255,e[n++]=d>>8&255,e[n++]=255&d}if(null!==s){if(s<0||s>65535)throw new Error("Loop count invalid.");e[n++]=33,e[n++]=255,e[n++]=11,e[n++]=78,e[n++]=69,e[n++]=84,e[n++]=83,e[n++]=67,e[n++]=65,e[n++]=80,e[n++]=69,e[n++]=50,e[n++]=46,e[n++]=48,e[n++]=3,e[n++]=1,e[n++]=255&s,e[n++]=s>>8&255,e[n++]=0}var f=!1;this.addFrame=function(t,r,i,s,h,u){if(!0===f&&(--n,f=!1),u=void 0===u?{}:u,t<0||r<0||t>65535||r>65535)throw new Error("x/y invalid.");if(i<=0||s<=0||i>65535||s>65535)throw new Error("Width/Height invalid.");if(h.length>=1;)++d;p=1<3)throw new Error("Disposal out of range.");var y=!1,x=0;if(void 0!==u.transparent&&null!==u.transparent&&(y=!0,(x=u.transparent)<0||x>=p))throw new Error("Transparent color index.");if((0!==g||y||0!==m)&&(e[n++]=33,e[n++]=249,e[n++]=4,e[n++]=g<<2|(!0===y?1:0),e[n++]=255&m,e[n++]=m>>8&255,e[n++]=x,e[n++]=0),e[n++]=44,e[n++]=255&t,e[n++]=t>>8&255,e[n++]=255&r,e[n++]=r>>8&255,e[n++]=255&i,e[n++]=i>>8&255,e[n++]=255&s,e[n++]=s>>8&255,e[n++]=!0===l?128|d-1:0,!0===l)for(var v=0,b=c.length;v>16&255,e[n++]=_>>8&255,e[n++]=255&_}return n=function(e,t,r,i){e[t++]=r;var n=t++,s=1<=r;)e[t++]=255&c,c>>=8,l-=8,t===n+256&&(e[n]=255,n=t++)}function d(e){c|=e<=8;)e[t++]=255&c,c>>=8,l-=8,t===n+256&&(e[n]=255,n=t++);4096===h?(d(s),h=o+1,u=r+1,m={}):(h>=1<>7,a=1<<1+(7&n);e[t++],e[t++];var o=null,h=null;s&&(o=t,h=a,t+=3*a);var u=!0,l=[],c=0,p=null,d=0,f=null;for(this.width=r,this.height=i;u&&t=0))throw Error("Invalid block size");if(0===S)break;t+=S}break;case 249:if(4!==e[t++]||0!==e[t+4])throw new Error("Invalid graphics extension block.");var m=e[t++];c=e[t++]|e[t++]<<8,p=e[t++],1&m||(p=null),d=m>>2&7,t++;break;case 254:for(;;){if(!((S=e[t++])>=0))throw Error("Invalid block size");if(0===S)break;t+=S}break;default:throw new Error("Unknown graphic control label: 0x"+e[t-1].toString(16))}break;case 44:var g=e[t++]|e[t++]<<8,y=e[t++]|e[t++]<<8,x=e[t++]|e[t++]<<8,v=e[t++]|e[t++]<<8,b=e[t++],_=b>>6&1,w=1<<1+(7&b),C=o,E=h,A=!1;b>>7&&(A=!0,C=t,E=w,t+=3*w);var D=t;for(t++;;){var S;if(!((S=e[t++])>=0))throw Error("Invalid block size");if(0===S)break;t+=S}l.push({x:g,y:y,width:x,height:v,has_local_palette:A,palette_offset:C,palette_size:E,data_offset:D,data_length:t-D,transparent_index:p,interlaced:!!_,delay:c,disposal:d});break;case 59:u=!1;break;default:throw new Error("Unknown gif block: 0x"+e[t-1].toString(16))}this.numFrames=function(){return l.length},this.loopCount=function(){return f},this.frameInfo=function(e){if(e<0||e>=l.length)throw new Error("Frame index out of range.");return l[e]},this.decodeAndBlitFrameBGRA=function(t,i){var n=this.frameInfo(t),s=n.width*n.height,a=new Uint8Array(s);Fs(e,n.data_offset,a,s);var o=n.palette_offset,h=n.transparent_index;null===h&&(h=256);var u=n.width,l=r-u,c=u,p=4*(n.y*r+n.x),d=4*((n.y+n.height)*r+n.x),f=p,m=4*l;!0===n.interlaced&&(m+=4*r*7);for(var g=8,y=0,x=a.length;y=d&&(m=4*l+4*r*(g-1),f=p+(u+l)*(g<<1),g>>=1)),v===h)f+=4;else{var b=e[o+3*v],_=e[o+3*v+1],w=e[o+3*v+2];i[f++]=w,i[f++]=_,i[f++]=b,i[f++]=255}--c}},this.decodeAndBlitFrameRGBA=function(t,i){var n=this.frameInfo(t),s=n.width*n.height,a=new Uint8Array(s);Fs(e,n.data_offset,a,s);var o=n.palette_offset,h=n.transparent_index;null===h&&(h=256);var u=n.width,l=r-u,c=u,p=4*(n.y*r+n.x),d=4*((n.y+n.height)*r+n.x),f=p,m=4*l;!0===n.interlaced&&(m+=4*r*7);for(var g=8,y=0,x=a.length;y=d&&(m=4*l+4*r*(g-1),f=p+(u+l)*(g<<1),g>>=1)),v===h)f+=4;else{var b=e[o+3*v],_=e[o+3*v+1],w=e[o+3*v+2];i[f++]=b,i[f++]=_,i[f++]=w,i[f++]=255}--c}}}}catch(e){}function ks(e,t){t.createImage=function(t,r){return new e.Image(t,r)},t.saveCanvas=function(...e){let r,i,n,s,a;if(e[0]instanceof HTMLCanvasElement)r=e[0],e.shift();else if(e[0]instanceof En)r=e[0].elt,e.shift();else if(e[0]instanceof mo){const t=e[0];s=this.createGraphics(t.width,t.height),s.pixelDensity(t.pixelDensity()),t.loadPixels(),s.loadPixels(),s.pixels.set(t.pixels),s.updatePixels(),r=s._renderer.canvas,e.shift()}else r=this._curElement&&this._curElement.elt;switch(e.length>=1&&(i=e[0]),e.length>=2&&(n=e[1]),n=n||t._checkFileExtension(i,n)[1]||"png",n){default:a="image/png";break;case"webp":a="image/webp";break;case"jpeg":case"jpg":a="image/jpeg"}r.toBlob((e=>{t.downloadFile(e,i,n),s&&s.remove()}),a)},t.encodeAndDownloadGif=function(e,r){const i=e.gifProperties;let n=i.loopLimit;1===n?n=null:null===n&&(n=0);const s=new Uint8Array(e.width*e.height*i.numFrames),a=[],o={};for(let t=0;tparseInt(e)));h=h.concat(o[l].frames);const c=new Set(l);for(let e=1;eparseInt(e))).filter((e=>!c.has(e)));if(l.length+t.length<=256){for(let e=0;e{r?(void 0===o[e]&&(o[e]=n.length,n.push(e)),s[i]=o[e]):s[i]=p[e],t>0&&a[t-1][i]!==e&&u.add(e)}));const c={},d=n.filter((e=>!u.has(e)));if(d.length>0){const e=d[0],i=r?o[e]:p[e];if(t>0){for(let e=0;e0&&m.addFrame(0,0,e.width,e.height,g.pixelPaletteIndex,g.frameOpts),g={pixelPaletteIndex:s,frameOpts:c}}g.frameOpts.disposal=1,m.addFrame(0,0,e.width,e.height,g.pixelPaletteIndex,g.frameOpts);const y=new Blob([s.slice(0,m.end())],{type:"image/gif"});t.downloadFile(y,r,"gif")},t.saveFrames=function(e,r,i,n,s){let a=i||3;a=Math.max(Math.min(a,15),0),a*=1e3;let o=n||15;o=Math.max(Math.min(o,22),0);let h=0;const u=t._makeFrame,l=this._curElement.elt;let c=[];const p=setInterval((()=>{c.push(u(e+h,r,l)),h++}),1e3/o);setTimeout((()=>{if(clearInterval(p),s)s(c);else for(const e of c)t.downloadFile(e.imageData,e.filename,e.ext);c=[]}),a+.01)},t._makeFrame=function(e,t,r){let i,n;if(i=this?this._curElement.elt:r,t)switch(t.toLowerCase()){case"png":default:n="image/png";break;case"jpeg":case"jpg":n="image/jpeg"}else t="png",n="image/png";let s=i.toDataURL(n);s=s.replace(n,"image/octet-stream");const a={};return a.imageData=s,a.filename=e,a.ext=t,a}}function Ms(e){const t=e.options.typed?function(e){switch(!0){case"true"===e:case"false"===e:return"true"===e;case/.\./.test(e):return parseFloat(e);case isFinite(e):return parseInt(e);default:return e}}(e.value):e.value;e.entry.push(e.reviver(t,e.row,e.col)),e.value="",e.col++}function Is(e){e.output.push(e.entry),e.entry=[],e.row++,e.col=1}function Bs(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}void 0!==p5&&ks(p5,p5.prototype);class Ls extends Error{status;response;ok}async function Os(e,t){try{const r=await fetch(e);if(r.ok){let e;switch(t){case"json":e=await r.json();break;case"text":e=await r.text();break;case"arrayBuffer":e=await r.arrayBuffer();break;case"blob":e=await r.blob();break;case"bytes":if(r.bytes)e=await r.bytes();else{const t=await r.arrayBuffer();e=new Uint8Array(t)}break;default:throw new Error("Unsupported response type")}return{data:e,headers:r.headers}}{const e=new Ls(r.statusText);throw e.status=r.status,e.response=r,e.ok=!1,e}}catch(e){throw e instanceof TypeError?console.log("You may have encountered a CORS error"):e instanceof Ls?console.log("You have encountered a HTTP error"):e instanceof SyntaxError&&console.log("There is an error parsing the response to requested data structure"),e}}function Ps(e,t){function r(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}t.loadJSON=async function(t,r,i){try{const{data:e}=await Os(t,"json"),i=()=>r?r(e):e;return this._internal?this._internal(i):i()}catch(r){if(e._friendlyFileLoadError(5,t),i)return i(r);throw r}},t.loadStrings=async function(t,r,i){try{let{data:e}=await Os(t,"text");const i=()=>(e=e.split(/\r?\n/),r?r(e):e);return this._internal?this._internal(i):i()}catch(r){if(e._friendlyFileLoadError(3,t),i)return i(r);throw r}},t.loadTable=async function(t,r,i,n,s){"function"==typeof arguments[arguments.length-1]&&("function"==typeof arguments[arguments.length-2]?(n=arguments[arguments.length-2],s=arguments[arguments.length-1]):n=arguments[arguments.length-1]),"string"!=typeof r&&(r=","),"function"==typeof i&&(i=!1);try{let{data:s}=await Os(t,"text");const a=()=>{let t=new e.Table;return s=function(e,t,r=e=>e){const i=Object.create(null);if(i.options=t||{},i.reviver=r,i.value="",i.entry=[],i.output=[],i.col=1,i.row=1,i.options.delimiter=void 0===i.options.delimiter?'"':t.delimiter,i.options.delimiter.length>1||0===i.options.delimiter.length)throw Error(`CSVError: delimiter must be one character [${i.options.separator}]`);if(i.options.separator=void 0===i.options.separator?",":t.separator,i.options.separator.length>1||0===i.options.separator.length)throw Error(`CSVError: separator must be one character [${i.options.separator}]`);const n=new RegExp(`${Bs(i.options.delimiter)}|${Bs(i.options.separator)}|\r\n|\n|\r|[^${Bs(i.options.delimiter)}${Bs(i.options.separator)}\r\n]+`,"y"),s=/^(\r\n|\n|\r)$/;let a=[],o="",h=0;for(;null!==(a=n.exec(e));)switch(o=a[0],h){case 0:switch(!0){case o===i.options.delimiter:h=3;break;case o===i.options.separator:h=0,Ms(i);break;case s.test(o):h=0,Ms(i),Is(i);break;default:i.value+=o,h=2}break;case 2:switch(!0){case o===i.options.separator:h=0,Ms(i);break;case s.test(o):h=0,Ms(i),Is(i);break;default:throw h=4,Error(`CSVError: Illegal state [row:${i.row}, col:${i.col}]`)}break;case 3:1==(o===i.options.delimiter)?h=4:(h=3,i.value+=o);break;case 4:switch(!0){case o===i.options.delimiter:h=3,i.value+=o;break;case o===i.options.separator:h=0,Ms(i);break;case s.test(o):h=0,Ms(i),Is(i);break;default:throw Error(`CSVError: Illegal state [row:${i.row}, col:${i.col}]`)}}return 0!==i.entry.length&&(Ms(i),Is(i)),i.output}(s,{separator:r}),t.columns=i?s.shift():Array(s[0].length).fill(null),s.forEach((r=>{const i=new e.TableRow(r);t.addRow(i)})),n?n(t):t};return this._internal?this._internal(a):a()}catch(r){if(e._friendlyFileLoadError(2,t),s)return s(r);throw r}},t.loadXML=async function(t,r,i){try{const i=new DOMParser;let{data:n}=await Os(t,"text");const s=()=>{const t=i.parseFromString(n,"application/xml");return n=new e.XML(t),r?r(n):n};return this._internal?this._internal(s):s()}catch(r){if(e._friendlyFileLoadError(1,t),i)return i(r);throw r}},t.loadBytes=async function(t,r,i){try{let{data:e}=await Os(t,"arrayBuffer");const i=()=>(e=new Uint8Array(e),r?r(e):e);return this._internal?this._internal(i):i()}catch(r){if(e._friendlyFileLoadError(6,t),i)return i(r);throw r}},t.loadBlob=async function(e,t,r){try{const{data:r}=await Os(e,"blob"),i=()=>t?t(r):r;return this._internal?this._internal(i):i()}catch(e){if(r)return r(e);throw e}},t.httpGet=async function(e,t="text",r,i){return"function"==typeof t&&(i=r,r=t,t="text"),this.httpDo(e,"GET",t,r,i)},t.httpPost=async function(t,r,i="text",n,s){"function"==typeof r?(n=r,s=i,r=void 0,i="text"):"function"==typeof i&&(s=n,n=i,i="text");let a=r,o="text/plain";r instanceof e.XML?(a=r.serialize(),o="application/xml"):r instanceof e.Image?(a=await r.toBlob(),o="image/png"):"object"==typeof r&&(a=JSON.stringify(r),o="application/json");const h={method:"POST",body:a,headers:{"Content-Type":o}};a&&(h.body=a);const u=new Request(t,h);return this.httpDo(u,"POST",i,n,s)},t.httpDo=async function(e,t,r,i,n){if("function"==typeof r&&(n=i,i=r,r=void 0),!r){switch("string"==typeof e?e.split(".").pop():e.url.split(".").pop()){case"json":r="json";break;case"jpg":case"jpeg":case"png":case"webp":case"gif":r="blob";break;default:r="text"}}const s=new Request(e,{method:t});try{const{data:e}=await Os(s,r);return i?i(e):e}catch(e){if(n)return n(e);throw e}},t._pWriters=[],t.createWriter=function(r,i){let n;for(const s in t._pWriters)if(t._pWriters[s].name===r)return n=new e.PrintWriter(r+this.millis(),i),t._pWriters.push(n),n;return n=new e.PrintWriter(r,i),t._pWriters.push(n),n},e.PrintWriter=function(e,r){let i=this;this.name=e,this.content="",this.write=function(e){this.content+=e},this.print=function(e){this.content+=`${e}\n`},this.clear=function(){this.content=""},this.close=function(){const n=[];n.push(this.content),t.writeFile(n,e,r);for(const e in t._pWriters)t._pWriters[e].name===this.name&&t._pWriters.splice(e,1);i.clear(),i={}}},t.save=function(r,i,n){const s=arguments,a=this._curElement?this._curElement.elt:this.elt;if(0!==s.length)if(s[0]instanceof ds||s[0]instanceof Ja)t.saveCanvas(s[0].canvas,s[1],s[2]);else if(1===s.length&&"string"==typeof s[0])t.saveCanvas(a,s[0]);else{switch(In(s[1],s[2])[1]){case"json":return void t.saveJSON(s[0],s[1],s[2]);case"txt":return void t.saveStrings(s[0],s[1],s[2]);default:s[0]instanceof Array?t.saveStrings(s[0],s[1],s[2]):s[0]instanceof e.Table?t.saveTable(s[0],s[1],s[2]):s[0]instanceof e.Image?t.saveCanvas(s[0].canvas,s[1]):s[0]instanceof e.SoundFile&&t.saveSound(s[0],s[1],s[2],s[3])}}else t.saveCanvas(a)},t.saveJSON=function(e,t,r){let i;i=r?JSON.stringify(e):JSON.stringify(e,void 0,2),this.saveStrings(i.split("\n"),t,"json")},t.saveStrings=function(t,r,i,n){const s=i||"txt",a=new e.PrintWriter(r,s);for(let e of t)n?a.write(e+"\r\n"):a.write(e+"\n");a.close(),a.clear()},t.saveTable=function(e,t,i){let n;void 0===i?(n=t.substring(t.lastIndexOf(".")+1,t.length),n===t&&(n="csv")):n=i;const s=this.createWriter(t,n),a=e.columns;let o=",";if("tsv"===n&&(o="\t"),"html"!==n){const t=e.toString(o);s.write(t)}else{s.print(""),s.print("");let t=' "),s.print(""),s.print(" "),"0"!==a[0]){s.print(" ");for(let e=0;e${t}`),s.print(" ")}s.print(" ")}for(let t=0;t");for(let i=0;i${n}`),s.print(" ")}s.print(" ")}s.print("
"),s.print(""),s.print("")}s.close(),s.clear()},t.writeFile=function(e,r,i){let n="application/octet-stream";t._isSafari()&&(n="text/plain");const s=new Blob(e,{type:n});t.downloadFile(s,r,i)},t.downloadFile=Mn,t._checkFileExtension=In,t._isSafari=function(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}void 0!==p5&&Ps(p5,p5.prototype);var Ns=59;function Rs(e=256){let t=0,r=new Uint8Array(e);return{get buffer(){return r.buffer},reset(){t=0},bytesView:()=>r.subarray(0,t),bytes:()=>r.slice(0,t),writeByte(e){i(t+1),r[t]=e,t++},writeBytes(e,n=0,s=e.length){i(t+s);for(let i=0;i=e)return;e=Math.max(e,i*(i<1048576?2:1.125)>>>0),0!=i&&(e=Math.max(e,256));let n=r;r=new Uint8Array(e),t>0&&r.set(n.subarray(0,t),0)}}var Vs=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];var Us=function(e,t,r,i,n=Rs(512),s=new Uint8Array(256),a=new Int32Array(5003),o=new Int32Array(5003)){let h=a.length,u=Math.max(2,i);s.fill(0),o.fill(0),a.fill(-1);let l=0,c=0,p=u+1,d=p,f=!1,m=d,g=(1<=0;)if(n-=s,n<0&&(n+=h),a[n]===i){_=o[n];break e}E(_),_=t,v<4096?(o[n]=v++,a[n]=i):(a.fill(-1),v=y+2,f=!0,E(y))}return E(_),E(x),n.writeByte(0),n.bytesView();function E(e){for(l&=Vs[c],c>0?l|=e<=8;)s[b++]=255&l,b>=254&&(n.writeByte(b),n.writeBytesView(s,0,b),b=0),l>>=8,c-=8;if((v>g||f)&&(f?(m=d,g=(1<0;)s[b++]=255&l,b>=254&&(n.writeByte(b),n.writeBytesView(s,0,b),b=0),l>>=8,c-=8;b>0&&(n.writeByte(b),n.writeBytesView(s,0,b),b=0)}}};function zs(e,t,r){return e<<8&63488|t<<2&992|r>>3}function js(e,t,r,i){return e>>4|240&t|(240&r)<<4|(240&i)<<8}function Gs(e,t,r){return e>>4<<8|240&t|r>>4}function $s(e,t,r){return er?r:e}function Hs(e){return e*e}function qs(e,t,r){var i=0,n=1e100;let s=e[t],a=s.cnt,o=s.rc,h=s.gc,u=s.bc;for(var l=s.fw;0!=l;l=e[l].fw){let t=e[l],r=t.cnt,s=a*r/(a+r);if(!(s>=n)){var c=0;!((c+=s*Hs(t.rc-o))>=n)&&(!((c+=s*Hs(t.gc-h))>=n)&&(!((c+=s*Hs(t.bc-u))>=n)&&(n=c,i=l)))}}s.err=n,s.nn=i}function Ws(e,t,r={}){let{format:i="rgb565",clearAlpha:n=!0,clearAlphaColor:s=0,clearAlphaThreshold:a=0,oneBitAlpha:o=!1}=r;if(!e||!e.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(e instanceof Uint8Array||e instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");let h=new Uint32Array(e.buffer),u=!1!==r.useSqrt,l="rgba4444"===i,c=function(e,t){let r=new Array("rgb444"===t?4096:65536),i=e.length;if("rgba4444"===t)for(let t=0;t>24&255,s=i>>16&255,a=i>>8&255,o=255&i,h=js(o,a,s,n),u=h in r?r[h]:r[h]={ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0};u.rc+=o,u.gc+=a,u.bc+=s,u.ac+=n,u.cnt++}else if("rgb444"===t)for(let t=0;t>16&255,s=i>>8&255,a=255&i,o=Gs(a,s,n),h=o in r?r[o]:r[o]={ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0};h.rc+=a,h.gc+=s,h.bc+=n,h.cnt++}else for(let t=0;t>16&255,s=i>>8&255,a=255&i,o=zs(a,s,n),h=o in r?r[o]:r[o]={ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0};h.rc+=a,h.gc+=s,h.bc+=n,h.cnt++}return r}(h,i),p=c.length,d=p-1,f=new Uint32Array(p+1);for(var m=0,g=0;g1&&!(c[x=f[b=v>>1]].err<=_);v=b)f[v]=x;f[v]=g}var w=m-t;for(g=0;g=C.mtm&&c[C.nn].mtm<=C.tm)break;C.mtm==d?E=f[1]=f[f[0]--]:(qs(c,E),C.tm=g);_=c[E].err;for(v=1;(b=v+v)<=f[0]&&(bc[f[b+1]].err&&b++,!(_<=c[x=f[b]].err));v=b)f[v]=x;f[v]=E}var A=c[C.nn],D=C.cnt,S=A.cnt;y=1/(D+S);l&&(C.ac=y*(D*C.ac+S*A.ac)),C.rc=y*(D*C.rc+S*A.rc),C.gc=y*(D*C.gc+S*A.gc),C.bc=y*(D*C.bc+S*A.bc),C.cnt+=A.cnt,C.mtm=++g,c[A.bk].fw=A.fw,c[A.fw].bk=A.bk,A.mtm=d}let T=[];var F=0;for(g=0;;++F){let e=$s(Math.round(c[g].rc),0,255),t=$s(Math.round(c[g].gc),0,255),r=$s(Math.round(c[g].bc),0,255),i=255;if(l){if(i=$s(Math.round(c[g].ac),0,255),o){i=i<=("number"==typeof o?o:127)?0:255}n&&i<=a&&(e=t=r=s,i=0)}let h=l?[e,t,r,i]:[e,t,r];if(Xs(T,h)||T.push(h),0==(g=c[g].fw))break}return T}function Xs(e,t){for(let r=0;r=4&&t.length>=4)||i[3]===t[3];if(n&&s)return!0}return!1}function Ys(e,t){var r,i=0;for(r=0;ri.bytes(),bytesView:()=>i.bytesView(),get buffer(){return i.buffer},get stream(){return i},writeHeader:h,writeFrame(e,t,u,l={}){let{transparent:c=!1,transparentIndex:p=0,delay:d=0,palette:f=null,repeat:m=0,colorDepth:g=8,dispose:y=-1}=l,x=!1;if(r?o||(x=!0,h(),o=!0):x=Boolean(l.first),t=Math.max(0,Math.floor(t)),u=Math.max(0,Math.floor(u)),x){if(!f)throw new Error("First frame must include a { palette } option");(function(e,t,r,i,n=8){let s=1,a=0,o=ta(i.length)-1,h=s<<7|n-1<<4|a<<3|o,u=0,l=0;Qs(e,t),Qs(e,r),e.writeBytes([h,u,l])})(i,t,u,f,g),Js(i,f),m>=0&&function(e,t){e.writeByte(33),e.writeByte(255),e.writeByte(11),ea(e,"NETSCAPE2.0"),e.writeByte(3),e.writeByte(1),Qs(e,t),e.writeByte(0)}(i,m)}let v=Math.round(d/10);!function(e,t,r,i,n){var s,a;e.writeByte(33),e.writeByte(249),e.writeByte(4),n<0&&(n=0,i=!1),i?(s=1,a=2):(s=0,a=0),t>=0&&(a=7&t),a<<=2;let o=0;e.writeByte(a|o|s),Qs(e,r),e.writeByte(n||0),e.writeByte(0)}(i,y,v,c,p);let b=Boolean(f)&&!x;(function(e,t,r,i){if(e.writeByte(44),Qs(e,0),Qs(e,0),Qs(e,t),Qs(e,r),i){let t=0,r=0,n=ta(i.length)-1;e.writeByte(128|t|r|n)}else e.writeByte(0)})(i,t,u,b?f:null),b&&Js(i,f),function(e,t,r,i,n=8,s,a,o){Us(r,i,t,n,e,s,a,o)}(i,e,t,u,g,n,s,a)}};function h(){ea(i,"GIF89a")}}function Js(e,t){let r=1<>8&255)}function ea(e,t){for(var r=0;r0&&e{try{i.decodeAndBlitFrameRGBA(t,a)}catch(t){throw e._friendlyFileLoadError(8,r.src),t}};for(let e=0;e1&&(r.gifProperties={displayIndex:0,loopLimit:h,loopCount:0,frames:n,numFrames:s,playing:!0,timeDisplayed:0,lastChangeTime:0});return r}(s,i);else{const e=await new Promise(((e,t)=>{const r=new Image,i=new Blob([s],{type:o}),n=URL.createObjectURL(i);r.onerror=e=>{URL.revokeObjectURL(n),t(e)},r.onload=()=>{URL.revokeObjectURL(n),e(r)},r.src=n}));i.width=i.canvas.width=e.width,i.height=i.canvas.height=e.height,i.drawingContext.drawImage(e,0,0)}const h=()=>(i.modified=!0,r?r(i):i);return this._internal?this._internal(h):h()}catch(r){if(e._friendlyFileLoadError(0,t),"function"==typeof i)return i(r);throw r}},t.saveGif=async function(i,n,s={delay:0,units:"seconds",silent:!1,notificationDuration:0,notificationID:"progressBar",reset:!0}){if("string"!=typeof i)throw TypeError("fileName parameter must be a string");if("number"!=typeof n)throw TypeError("Duration parameter must be a number");const a=s&&s.delay||0,o=s&&s.units||"seconds",h=s&&s.silent||!1,u=s&&s.notificationDuration||0,l=s&&s.notificationID||"progressBar",c=!s||void 0===s.reset||s.reset;if("number"!=typeof a)throw TypeError("Delay parameter must be a number");if("seconds"!==o&&"frames"!==o)throw TypeError('Units parameter must be either "frames" or "seconds"');if("boolean"!=typeof h)throw TypeError("Silent parameter must be a boolean");if("number"!=typeof u)throw TypeError("Notification duration parameter must be a number");if("string"!=typeof l)throw TypeError("Notification ID parameter must be a string");this._recording=!0;let p=this._targetFrameRate;p!==1/0&&void 0!==p&&0!==p||(p=60);let d=1/p*1e3;d=d<20?20:d;const f="seconds"===o?n*p:n,m="seconds"===o?a*p:a;let g,y;c?(g=m,this.frameCount=g,y=f+m):(g=this.frameCount+m,y=g+f);const x=this._renderer._pixelDensity;this.pixelDensity(1);let v,b,_,w=[];for(null!==document.getElementById(l)&&document.getElementById(l).remove(),h||(v=this.createP(""),v.id(l),v.style("font-size","16px"),v.style("font-family","Montserrat"),v.style("background-color","#ffffffa0"),v.style("padding","8px"),v.style("border-radius","10px"),v.position(0,0)),this._renderer instanceof e.RendererGL&&(_=this.drawingContext,b=new Uint8Array(_.drawingBufferWidth*_.drawingBufferHeight*4)),this.noLoop(),await new Promise(requestAnimationFrame);g"+w.length.toString()+" out of "+f.toString()),await new Promise((e=>setTimeout(e,0)))}h||v.html("Frames processed, generating color palette..."),this.loop(),this.pixelDensity(x);const C=Ks(),E=function(e){let t=new Uint8Array(e.length*e[0].length);for(let r=0;r{const t=e.length/4,r=new Uint8Array(t);for(let i=0;i"+e.toString()+" out of "+f.toString()),await new Promise((e=>setTimeout(e,0)))}C.finish();const F=C.bytesView(),k=new Blob([F],{type:"image/gif"});w=[],this._recording=!1,this.loop(),h||(v.html("Done. Downloading your gif!🌸"),u>0&&setTimeout((()=>v.remove()),1e3*u)),t.downloadFile(k,i,"gif")},t.image=function(e,t,r,s,a,o,h,u,l,c,p,d){let f=e.width,m=e.height;d=d||S,p=p||S,e.elt&&(f=void 0!==f?f:e.elt.width,m=void 0!==m?m:e.elt.height),e.elt&&e.elt.videoWidth&&!e.canvas&&(f=void 0!==f?f:e.elt.videoWidth,m=void 0!==m?m:e.elt.videoHeight);let g=t,y=r,x=s||f,v=a||m,b=o||0,_=h||0,w=void 0!==u?u:f,C=void 0!==l?l:m;w=n(w,f),C=n(C,m);let E=1;e.elt&&!e.canvas&&e.elt.style.width&&(E=e.elt.videoWidth&&!s?e.elt.videoWidth:e.elt.width,E/=parseInt(e.elt.style.width,10)),b*=E,_*=E,C*=E,w*=E;let A=vs.modeAdjust(g,y,x,v,this._renderer.states.imageMode);A=i(c,p,d,A.x,A.y,A.w,A.h,b,_,w,C),this._renderer.image(e,A.sx,A.sy,A.sw,A.sh,A.dx,A.dy,A.dw,A.dh)},t.tint=function(...e){return 0===e.length?this._renderer.states.tint:(this._renderer.states.setValue("tint",this.color(...e)),this)},t.noTint=function(){return this._renderer.states.setValue("tint",null),this},t.imageMode=function(e){if(void 0===e)return this._renderer.states.imageMode;e!==w&&e!==C&&e!==S||this._renderer.states.setValue("imageMode",e)}}function ia(e,t){t.blend=function(...t){this._renderer?this._renderer.blend(...t):e.Renderer2D.prototype.blend.apply(this,t)},t.copy=function(...e){let r,i,n,s,a,o,h,u,l;if(9===e.length)r=e[0],i=e[1],n=e[2],s=e[3],a=e[4],o=e[5],h=e[6],u=e[7],l=e[8];else{if(8!==e.length)throw new Error("Signature not supported");r=this,i=e[0],n=e[1],s=e[2],a=e[3],o=e[4],h=e[5],u=e[6],l=e[7]}t._copyHelper(this,r,i,n,s,a,o,h,u,l)},t._copyHelper=(e,t,r,i,n,s,a,o,h,u)=>{const l=t.canvas.width/t.width;let c=0,p=0;t._renderer&&t._renderer.isP3D&&(c=t.width/2,p=t.height/2),e._renderer&&e._renderer.isP3D?(e.push(),e.resetMatrix(),e.noLights(),e.blendMode(e.BLEND),e.imageMode(e.CORNER),e._renderer.image(t,r+c,i+p,n,s,a,o,h,u),e.pop()):e.drawingContext.drawImage(t.canvas,l*(r+c),l*(i+p),l*n,l*s,a,o,h,u)},t.getFilterGraphicsLayer=function(){return this._renderer.getFilterGraphicsLayer()},t.filter=function(...t){let{shader:r,operation:i,value:n,useWebGL:s}=function(...t){let r={shader:void 0,operation:void 0,value:void 0,useWebGL:!0};if(t[0]instanceof e.Shader)return r.shader=t[0],r;r.operation=t[0];t.length>1&&"number"==typeof t[1]&&(r.value=t[1]);!1===t[t.length-1]&&(r.useWebGL=!1);return r}(...t);this._renderer.isP3D&&r?this._renderer.filter(r):s||this._renderer.isP3D?(!s&&this._renderer.isP3D&&console.warn("filter() with useWebGL=false is not supported in WEBGL"),this._renderer.isP3D?this._renderer.filter(i,n):(r?this._renderer.filterRenderer.setOperation(i,n,r):this._renderer.filterRenderer.setOperation(i,n),this._renderer.filterRenderer.applyFilter())):void 0!==this.canvas?Dn.apply(this.canvas,Dn[i],n):Dn.apply(this.elt,Dn[i],n)},t.get=function(e,t,r,i){return this._renderer.get(...arguments)},t.loadPixels=function(...e){return this._renderer.loadPixels()},t.set=function(e,t,r){this._renderer.set(e,t,r)},t.updatePixels=function(e,t,r,i){0!==this.pixels.length&&this._renderer.updatePixels(e,t,r,i)}}void 0!==p5&&ra(p5,p5.prototype),void 0!==p5&&ia(p5,p5.prototype);class na{#D=null;constructor(...e){if(this.constructor===na)throw new Error("Class is of abstract type and can't be instantiated")}}const sa=e=>{if(Math.sqrt(e.length)%1!=0)throw new Error("Array length must be a perfect square.");return!0};let aa=Array,oa=e=>Array.isArray(e);"undefined"!=typeof Float32Array&&(aa=Float32Array,oa=e=>Array.isArray(e)||e instanceof Float32Array);class ha extends na{matrix;#S;constructor(...e){if(super(...e),oa(e[0])&&sa(e[0])){const t=Math.sqrt(e[0].length);this.#S=t,this.matrix=aa.from(e[0])}else"number"==typeof e[0]&&(this.#S=Number(e[0]),this.matrix=this.#T(e[0]));return this}get mat3(){return 3===this.#S?this.matrix:void 0}get mat4(){return 4===this.#S?this.matrix:void 0}add(e){if(this.matrix.length!==e.matrix.length)throw new Error("Matrices must be of the same dimension to add.");for(let t=0;t=0&&e4 at the moment, we are working on it")}createSubMatrix3x3(){if(4===this.#S){const e=new ha(3);return e.mat3[0]=this.matrix[0],e.mat3[1]=this.matrix[1],e.mat3[2]=this.matrix[2],e.mat3[3]=this.matrix[4],e.mat3[4]=this.matrix[5],e.mat3[5]=this.matrix[6],e.mat3[6]=this.matrix[8],e.mat3[7]=this.matrix[9],e.mat3[8]=this.matrix[10],e}throw new Error("Matrix dimension must be 4 to create a 3x3 submatrix.")}inverseTranspose4x4({mat4:e}){if(3!==this.#S)throw new Error("This function only works with 3×3 matrices.");this.matrix[0]=e[0],this.matrix[1]=e[1],this.matrix[2]=e[2],this.matrix[3]=e[4],this.matrix[4]=e[5],this.matrix[5]=e[6],this.matrix[6]=e[8],this.matrix[7]=e[9],this.matrix[8]=e[10];const t=this.invert();if(t)t.transpose(this.matrix);else for(let e=0;e<9;e++)this.matrix[e]=0;return this}apply(e){let t;if(e===this||e===this.matrix)t=this.copy().matrix;else if(e instanceof ha)t=e.matrix;else if(oa(e))t=e;else{if(16!==arguments.length)return;t=arguments}const r=this.matrix,i=r[0],n=r[4],s=r[8],a=r[12];r[0]=t[0]*i+t[1]*n+t[2]*s+t[3]*a,r[4]=t[4]*i+t[5]*n+t[6]*s+t[7]*a,r[8]=t[8]*i+t[9]*n+t[10]*s+t[11]*a,r[12]=t[12]*i+t[13]*n+t[14]*s+t[15]*a;const o=r[1],h=r[5],u=r[9],l=r[13];r[1]=t[0]*o+t[1]*h+t[2]*u+t[3]*l,r[5]=t[4]*o+t[5]*h+t[6]*u+t[7]*l,r[9]=t[8]*o+t[9]*h+t[10]*u+t[11]*l,r[13]=t[12]*o+t[13]*h+t[14]*u+t[15]*l;const c=r[2],p=r[6],d=r[10],f=r[14];r[2]=t[0]*c+t[1]*p+t[2]*d+t[3]*f,r[6]=t[4]*c+t[5]*p+t[6]*d+t[7]*f,r[10]=t[8]*c+t[9]*p+t[10]*d+t[11]*f,r[14]=t[12]*c+t[13]*p+t[14]*d+t[15]*f;const m=r[3],g=r[7],y=r[11],x=r[15];return r[3]=t[0]*m+t[1]*g+t[2]*y+t[3]*x,r[7]=t[4]*m+t[5]*g+t[6]*y+t[7]*x,r[11]=t[8]*m+t[9]*g+t[10]*y+t[11]*x,r[15]=t[12]*m+t[13]*g+t[14]*y+t[15]*x,this}scale(e,t,r){return e instanceof Nn?(t=e.y,r=e.z,e=e.x):e instanceof Array&&(t=e[1],r=e[2],e=e[0]),this.matrix[0]*=e,this.matrix[1]*=e,this.matrix[2]*=e,this.matrix[3]*=e,this.matrix[4]*=t,this.matrix[5]*=t,this.matrix[6]*=t,this.matrix[7]*=t,this.matrix[8]*=r,this.matrix[9]*=r,this.matrix[10]*=r,this.matrix[11]*=r,this}rotate4x4(e,t,r,i){t instanceof Nn?(r=t.y,i=t.z,t=t.x):t instanceof Array&&(r=t[1],i=t[2],t=t[0]);const n=Math.sqrt(t*t+r*r+i*i);t*=1/n,r*=1/n,i*=1/n;const s=this.matrix[0],a=this.matrix[1],o=this.matrix[2],h=this.matrix[3],u=this.matrix[4],l=this.matrix[5],c=this.matrix[6],p=this.matrix[7],d=this.matrix[8],f=this.matrix[9],m=this.matrix[10],g=this.matrix[11],y=Math.sin(e),x=Math.cos(e),v=1-x,b=t*t*v+x,_=r*t*v+i*y,w=i*t*v-r*y,C=t*r*v-i*y,E=r*r*v+x,A=i*r*v+t*y,D=t*i*v+r*y,S=r*i*v-t*y,T=i*i*v+x;return this.matrix[0]=s*b+u*_+d*w,this.matrix[1]=a*b+l*_+f*w,this.matrix[2]=o*b+c*_+m*w,this.matrix[3]=h*b+p*_+g*w,this.matrix[4]=s*C+u*E+d*A,this.matrix[5]=a*C+l*E+f*A,this.matrix[6]=o*C+c*E+m*A,this.matrix[7]=h*C+p*E+g*A,this.matrix[8]=s*D+u*S+d*T,this.matrix[9]=a*D+l*S+f*T,this.matrix[10]=o*D+c*S+m*T,this.matrix[11]=h*D+p*S+g*T,this}translate(e){const t=e[0],r=e[1],i=e[2]||0;return this.matrix[12]+=this.matrix[0]*t+this.matrix[4]*r+this.matrix[8]*i,this.matrix[13]+=this.matrix[1]*t+this.matrix[5]*r+this.matrix[9]*i,this.matrix[14]+=this.matrix[2]*t+this.matrix[6]*r+this.matrix[10]*i,this.matrix[15]+=this.matrix[3]*t+this.matrix[7]*r+this.matrix[11]*i,this}rotateX(e){this.rotate4x4(e,1,0,0)}rotateY(e){this.rotate4x4(e,0,1,0)}rotateZ(e){this.rotate4x4(e,0,0,1)}perspective(e,t,r,i){const n=1/Math.tan(e/2),s=1/(r-i);return this.matrix[0]=n/t,this.matrix[1]=0,this.matrix[2]=0,this.matrix[3]=0,this.matrix[4]=0,this.matrix[5]=n,this.matrix[6]=0,this.matrix[7]=0,this.matrix[8]=0,this.matrix[9]=0,this.matrix[10]=(i+r)*s,this.matrix[11]=-1,this.matrix[12]=0,this.matrix[13]=0,this.matrix[14]=2*i*r*s,this.matrix[15]=0,this}ortho(e,t,r,i,n,s){const a=1/(e-t),o=1/(r-i),h=1/(n-s);return this.matrix[0]=-2*a,this.matrix[1]=0,this.matrix[2]=0,this.matrix[3]=0,this.matrix[4]=0,this.matrix[5]=-2*o,this.matrix[6]=0,this.matrix[7]=0,this.matrix[8]=0,this.matrix[9]=0,this.matrix[10]=2*h,this.matrix[11]=0,this.matrix[12]=(e+t)*a,this.matrix[13]=(i+r)*o,this.matrix[14]=(s+n)*h,this.matrix[15]=1,this}multiplyVec4(e,t,r,i){const n=new Array(4),s=this.matrix;return n[0]=s[0]*e+s[4]*t+s[8]*r+s[12]*i,n[1]=s[1]*e+s[5]*t+s[9]*r+s[13]*i,n[2]=s[2]*e+s[6]*t+s[10]*r+s[14]*i,n[3]=s[3]*e+s[7]*t+s[11]*r+s[15]*i,n}multiplyPoint({x:e,y:t,z:r}){const i=this.multiplyVec4(e,t,r,1);return new Nn(i[0],i[1],i[2])}multiplyAndNormalizePoint({x:e,y:t,z:r}){const i=this.multiplyVec4(e,t,r,1);return i[0]/=i[3],i[1]/=i[3],i[2]/=i[3],new Nn(i[0],i[1],i[2])}multiplyDirection({x:e,y:t,z:r}){const i=this.multiplyVec4(e,t,r,0);return new Nn(i[0],i[1],i[2])}multiplyVec3(e,t){return void 0===t&&(t=e.copy()),t.x=this.row(0).dot(e),t.y=this.row(1).dot(e),t.z=this.row(2).dot(e),t}#T(e){if(3===e)return new aa([1,0,0,0,1,0,0,0,1]);if(4===e)return new aa([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);const t=new aa(e*e).fill(0);for(let r=0;r 4x4"),e instanceof ha?(t=e.matrix[1],r=e.matrix[2],i=e.matrix[3],n=e.matrix[6],s=e.matrix[7],a=e.matrix[11],this.matrix[0]=e.matrix[0],this.matrix[1]=e.matrix[4],this.matrix[2]=e.matrix[8],this.matrix[3]=e.matrix[12],this.matrix[4]=t,this.matrix[5]=e.matrix[5],this.matrix[6]=e.matrix[9],this.matrix[7]=e.matrix[13],this.matrix[8]=r,this.matrix[9]=n,this.matrix[10]=e.matrix[10],this.matrix[11]=e.matrix[14],this.matrix[12]=i,this.matrix[13]=s,this.matrix[14]=a,this.matrix[15]=e.matrix[15]):oa(e)&&(t=e[1],r=e[2],i=e[3],n=e[6],s=e[7],a=e[11],this.matrix[0]=e[0],this.matrix[1]=e[4],this.matrix[2]=e[8],this.matrix[3]=e[12],this.matrix[4]=t,this.matrix[5]=e[5],this.matrix[6]=e[9],this.matrix[7]=e[13],this.matrix[8]=r,this.matrix[9]=n,this.matrix[10]=e[10],this.matrix[11]=e[14],this.matrix[12]=i,this.matrix[13]=s,this.matrix[14]=a,this.matrix[15]=e[15]),this}#k(e){void 0===e&&(e=this.mat3);const t=e[1],r=e[2],i=e[5];return this.mat3[0]=e[0],this.mat3[1]=e[3],this.mat3[2]=e[6],this.mat3[3]=t,this.mat3[4]=e[4],this.mat3[5]=e[7],this.mat3[6]=r,this.mat3[7]=i,this.mat3[8]=e[8],this}#O(e){let t,r,i,n,s,a,o,h,u,l,c,p,d,f,m,g;e instanceof ha?(t=e.matrix[0],r=e.matrix[1],i=e.matrix[2],n=e.matrix[3],s=e.matrix[4],a=e.matrix[5],o=e.matrix[6],h=e.matrix[7],u=e.matrix[8],l=e.matrix[9],c=e.matrix[10],p=e.matrix[11],d=e.matrix[12],f=e.matrix[13],m=e.matrix[14],g=e.matrix[15]):oa(e)&&(t=e[0],r=e[1],i=e[2],n=e[3],s=e[4],a=e[5],o=e[6],h=e[7],u=e[8],l=e[9],c=e[10],p=e[11],d=e[12],f=e[13],m=e[14],g=e[15]);const y=t*a-r*s,x=t*o-i*s,v=t*h-n*s,b=r*o-i*a,_=r*h-n*a,w=i*h-n*o,C=u*f-l*d,E=u*m-c*d,A=u*g-p*d,D=l*m-c*f,S=l*g-p*f,T=c*g-p*m;let F=y*T-x*S+v*D+b*A-_*E+w*C;return F?(F=1/F,this.matrix[0]=(a*T-o*S+h*D)*F,this.matrix[1]=(i*S-r*T-n*D)*F,this.matrix[2]=(f*w-m*_+g*b)*F,this.matrix[3]=(c*_-l*w-p*b)*F,this.matrix[4]=(o*A-s*T-h*E)*F,this.matrix[5]=(t*T-i*A+n*E)*F,this.matrix[6]=(m*v-d*w-g*x)*F,this.matrix[7]=(u*w-c*v+p*x)*F,this.matrix[8]=(s*S-a*A+h*C)*F,this.matrix[9]=(r*A-t*S-n*C)*F,this.matrix[10]=(d*_-f*v+g*y)*F,this.matrix[11]=(l*v-u*_-p*y)*F,this.matrix[12]=(a*E-s*D-o*C)*F,this.matrix[13]=(t*D-r*E+i*C)*F,this.matrix[14]=(f*x-d*b-m*y)*F,this.matrix[15]=(u*b-l*x+c*y)*F,this):null}#P(){const e=this.mat3[0],t=this.mat3[1],r=this.mat3[2],i=this.mat3[3],n=this.mat3[4],s=this.mat3[5],a=this.mat3[6],o=this.mat3[7],h=this.mat3[8],u=h*n-s*o,l=-h*i+s*a,c=o*i-n*a;let p=e*u+t*l+r*c;return p?(p=1/p,this.mat3[0]=u*p,this.mat3[1]=(-h*t+r*o)*p,this.mat3[2]=(s*t-r*n)*p,this.mat3[3]=l*p,this.mat3[4]=(h*e-r*a)*p,this.mat3[5]=(-s*e+r*i)*p,this.mat3[6]=c*p,this.mat3[7]=(-o*e+t*a)*p,this.mat3[8]=(n*e-t*i)*p,this):null}#N(){if(4!==this.#S)throw new Error("Determinant is only implemented for 4x4 matrices. We are working on it.");const e=this.matrix[0]*this.matrix[5]-this.matrix[1]*this.matrix[4],t=this.matrix[0]*this.matrix[6]-this.matrix[2]*this.matrix[4],r=this.matrix[0]*this.matrix[7]-this.matrix[3]*this.matrix[4],i=this.matrix[1]*this.matrix[6]-this.matrix[2]*this.matrix[5],n=this.matrix[1]*this.matrix[7]-this.matrix[3]*this.matrix[5],s=this.matrix[2]*this.matrix[7]-this.matrix[3]*this.matrix[6],a=this.matrix[8]*this.matrix[13]-this.matrix[9]*this.matrix[12],o=this.matrix[8]*this.matrix[14]-this.matrix[10]*this.matrix[12],h=this.matrix[8]*this.matrix[15]-this.matrix[11]*this.matrix[12],u=this.matrix[9]*this.matrix[14]-this.matrix[10]*this.matrix[13],l=this.matrix[9]*this.matrix[15]-this.matrix[11]*this.matrix[13];return e*(this.matrix[10]*this.matrix[15]-this.matrix[11]*this.matrix[14])-t*l+r*u+i*h-n*o+s*a}}function ua(e,t){e.Matrix=ha}void 0!==p5&&ua(p5);class la{constructor(e=128){this.length=0,this.data=new Float32Array(e),this.initialLength=e}dataArray(){return this.subArray(0,this.length)}clear(){this.length=0}rescale(){if(this.length{t+=`v ${e.x} ${e.y} ${e.z}\n`})),this.uvs&&this.uvs.length>0)for(let e=0;e0&&this.vertexNormals.forEach((e=>{t+=`vn ${e.x} ${e.y} ${e.z}\n`})),this.faces.forEach((e=>{let r="f";e.forEach((e=>{r+=" ",r+=e+1,(this.vertexNormals.length>0||this.uvs.length>0)&&(r+="/",this.uvs.length>0&&(r+=e+1),r+="/",this.vertexNormals.length>0&&(r+=e+1))})),t+=r+"\n"}));Mn(new Blob([t],{type:"text/plain"}),e,"obj")}saveStl(e="model.stl",{binary:t=!1}={}){let r,i=e.substring(0,e.lastIndexOf(".")),n=[];for(let e of this.faces){const t=Nn.sub(this.vertices[e[1]],this.vertices[e[0]]),r=Nn.sub(this.vertices[e[2]],this.vertices[e[0]]),i=t.y*r.z-t.z*r.y,s=t.z*r.x-t.x*r.z,a=t.x*r.y-t.y*r.x;n.push(new Nn(i,s,a).normalize())}if(t){let e=80;const t=2*this.faces.length+3*this.faces.length*4*4+80+4,i=new ArrayBuffer(t);r=new DataView(i),r.setUint32(e,this.faces.length,!0),e+=4;for(const[t,i]of Object.entries(this.faces)){const s=n[t];r.setFloat32(e,s.x,!0),e+=4,r.setFloat32(e,s.y,!0),e+=4,r.setFloat32(e,s.z,!0),e+=4;for(let t of i){const i=this.vertices[t];r.setFloat32(e,i.x,!0),e+=4,r.setFloat32(e,i.y,!0),e+=4,r.setFloat32(e,i.z,!0),e+=4}r.setUint16(e,0,!0),e+=2}}else{r="solid "+i+"\n";for(const[e,t]of Object.entries(this.faces)){const i=n[e];r+=" facet norm "+i.x+" "+i.y+" "+i.z+"\n",r+=" outer loop\n";for(let e of t){const t=this.vertices[e];r+=" vertex "+t.x+" "+t.y+" "+t.z+"\n"}r+=" endloop\n",r+=" endfacet\n"}r+="endsolid "+i+"\n"}Mn(new Blob([r],{type:"text/plain"}),e,"stl")}flipU(){this.uvs=this.uvs.flat().map(((e,t)=>t%2==0?1-e:e))}flipV(){this.uvs=this.uvs.flat().map(((e,t)=>t%2==0?e:1-e))}computeFaces(){this.faces.length=0;const e=this.detailX+1;let t,r,i,n;for(let s=0;s1&&(u=1),o.mult(Math.asin(u)/h))}computeNormals(e=Me,{roundToPrecision:t=3}={}){const r=this.vertexNormals;let i=this.vertices;const n=this.faces;let s;if(e===Ie){const e={},r=[],s=Math.pow(10,t),a=e=>Math.round(e*s)/s,o=e=>`${a(e.x)},${a(e.y)},${a(e.z)}`;for(let t=0;t{for(let r=0;r<3;++r){const n=t[r],s=i[n],a=o(s);t[r]=e[a]}})),this.edges.forEach((t=>{for(let r=0;r<2;++r){const n=t[r],s=i[n],a=o(s);t[r]=e[a]}})),this.vertices=i=r}for(r.length=0,s=0;s{const i=this._getFaceNormal(t);for(let t=0;t<3;++t){const n=e[t];r[n].add(i)}})),s=0;sthis.vertices.length-1-this.detailX;t--)e.add(this.vertexNormals[t]);e=Nn.div(e,this.detailX);for(let t=this.vertices.length-1;t>this.vertices.length-1-this.detailX;t--)this.vertexNormals[t]=e;return this}_makeTriangleEdges(){this.edges.length=0;for(let e=0;e0&&n?this.vertexStrokeColors.slice(4*n[1],4*(n[1]+1)):[0,0,0,0],l=this.vertexStrokeColors.length>0?this.vertexStrokeColors.slice(4*s[0],4*(s[0]+1)):[0,0,0,0],c=this.vertexStrokeColors.length>0?this.vertexStrokeColors.slice(4*s[1],4*(s[1]+1)):[0,0,0,0],p=a?new Nn(0,1,0):h.copy().sub(o).normalize(),d=p.magSq()>0;if(d&&this._addSegment(o,h,l,c,p),!this.renderer?._simpleLines){if(i>0&&n[1]===s[0])t.has(s[0])||(t.add(s[0]),e.delete(s[0]),r&&d&&p.dot(r)<1-1e-8&&this._addJoin(o,r,p,l));else if(a)this._addCap(o,p.copy().mult(-1),l),this._addCap(o,p,l);else{if(d&&!t.has(s[0])){const r=e.get(s[0]);r?(this._addJoin(o,r.dir,p,l),e.delete(s[0]),t.add(s[0])):e.set(s[0],{point:o,dir:p.copy().mult(-1),color:l})}if(!a&&r&&!t.has(n[1])){const i=e.get(n[1]);i?(this._addJoin(this.vertices[n[1]],r,i.dir.copy().mult(-1),u),e.delete(n[1]),t.add(n[1])):e.set(n[1],{point:this.vertices[n[1]],dir:r,color:u}),r=void 0}}if(i===this.edges.length-1&&!t.has(s[1])){const r=e.get(s[1]);r?(this._addJoin(h,p,r.dir.copy().mult(-1),c),e.delete(s[1]),t.add(s[1])):e.set(s[1],{point:h,dir:p,color:c})}d&&(r=p)}}for(const{point:t,dir:r,color:i}of e.values())this._addCap(t,r,i);return this}_addSegment(e,t,r,i,n){const s=e.array(),a=t.array(),o=n.array();this.lineSides.push(1,1,-1,1,-1,-1);for(const e of[this.lineTangentsIn,this.lineTangentsOut])for(let t=0;t<6;t++)e.push(...o);return this.lineVertices.push(...s,...a,...s,...a,...a,...s),this.renderer?._simpleLines||this.lineVertexColors.push(...r,...i,...r,...i,...i,...r),this}_addCap(e,t,r){const i=e.array(),n=t.array(),s=[0,0,0];for(let e=0;e<6;e++)this.lineVertices.push(...i),this.lineTangentsIn.push(...n),this.lineTangentsOut.push(...s),this.lineVertexColors.push(...r);return this.lineSides.push(-1,2,-2,1,2,-1),this}_addJoin(e,t,r,i){const n=e.array(),s=t.array(),a=r.array();for(let e=0;e<12;e++)this.lineVertices.push(...n),this.lineTangentsIn.push(...s),this.lineTangentsOut.push(...a),this.lineVertexColors.push(...i);return this.lineSides.push(-1,-3,-2,-1,0,-3),this.lineSides.push(3,1,2,3,0,1),this}normalize(){if(this.vertices.length>0){const e=this.vertices[0].copy(),t=this.vertices[0].copy();for(let r=0;rthis.renderer.states.uModelMatrix.multiplyPoint(e))):e}transformNormals(e){return this.hasTransform?e.map((e=>this.renderer.scratchMat3.multiplyVec(e))):e}addGeometry(e){this.hasTransform=!this.renderer.states.uModelMatrix.mat4.every(((e,t)=>e===this.identityMatrix.mat4[t])),this.hasTransform&&this.renderer.scratchMat3.inverseTranspose4x4(this.renderer.states.uModelMatrix);let t=this.geometry.vertices.length;for(const t of this.transformVertices(e.vertices))this.geometry.vertices.push(t);for(const t of this.transformNormals(e.vertexNormals))this.geometry.vertexNormals.push(t);for(const t of e.uvs)this.geometry.uvs.push(t);const r=e.userVertexProperties,i=this.geometry.userVertexProperties,n=this.geometry.vertices.length-e.vertices.length;for(const t in i){if(t in r)continue;const n=i[t],s=n.getDataSize()*e.vertices.length,a=Array(s).fill(0);n.pushDirect(a)}for(const e in r){const t=r[e],s=t.getSrcArray(),a=t.getDataSize();if(n>0&&!(e in i)){const t=Array(a*n).fill(0);this.geometry.vertexProperty(e,t,a)}this.geometry.vertexProperty(e,s,a)}if(this.renderer.states.fillColor&&this.geometry.faces.push(...e.faces.map((e=>e.map((e=>e+t))))),this.renderer.states.strokeColor)for(const r of e.edges.map((e=>e.map((e=>e+t)))))this.geometry.edges.push(r);const s=[...e.vertexColors];for(;s.length<4*e.vertices.length;)s.push(...this.renderer.states.curFillColor);for(const e of s)this.geometry.vertexColors.push(e)}addImmediate(e,t,{validateFaces:r=!1}={}){const i=[];if(this.renderer.states.fillColor)if(5===t||t===N)for(let t=2;t0)&&i.push([t,t+1,t+2]);this.addGeometry(Object.assign({},e,{faces:i}))}addRetained(e){this.addGeometry(e)}finish(){return this.renderer._pInst.pop(),this.geometry}}fa.nextGeometryId=0;class ma{constructor(e,t,r,i){this.w=e,this.vec=new Nn(t,r,i)}static fromAxisAngle(e,t,r,i){const n=Math.cos(e/2),s=new Nn(t,r,i).normalize().mult(Math.sin(e/2));return new ma(n,s.x,s.y,s.z)}conjugate(){return new ma(this.w,-this.vec.x,-this.vec.y,-this.vec.z)}multiply(e){return new ma(this.w*e.w-this.vec.x*e.vec.x-this.vec.y*e.vec.y-this.vec.z-e.vec.z,this.w*e.vec.x+this.vec.x*e.w+this.vec.y*e.vec.z-this.vec.z*e.vec.y,this.w*e.vec.y-this.vec.x*e.vec.z+this.vec.y*e.w+this.vec.z*e.vec.x,this.w*e.vec.z+this.vec.x*e.vec.y-this.vec.y*e.vec.x+this.vec.z*e.w)}rotateVector(e){return Nn.mult(e,this.w*this.w-this.vec.dot(this.vec)).add(Nn.mult(this.vec,2*e.dot(this.vec))).add(Nn.mult(this.vec,2*this.w).cross(e)).clampToZero()}rotateBy(e){return e.multiply(this).multiply(e.conjugate()).vec.clampToZero()}}function ga(e,t){e.Quat=ma}void 0!==p5&&ga(p5);class ya{constructor(e){this._renderer=e,this.cameraType="default",this.useLinePerspective=!0,this.cameraMatrix=new ha(4),this.projMatrix=new ha(4),this.yScale=1}perspective(e,t,r,i){const n=this._renderer.zClipRange();this.cameraType=arguments.length>0?"custom":"default",void 0===e?(e=this.defaultCameraFOV,this.cameraFOV=e):this.cameraFOV=this._renderer._pInst._toRadians(e),void 0===t&&(t=this.defaultAspectRatio),void 0===r&&(r=this.defaultCameraNear),void 0===i&&(i=this.defaultCameraFar),r<=1e-4&&(r=.01,console.log("Avoid perspective near plane values close to or below 0. Setting value to 0.01.")),i1e-6&&(d=Nn.dot(l,c)/p,d=Math.max(0,Math.min(d,1)));const f=Nn.lerp(Nn.lerp(i,s,d),Nn.lerp(n,a,d),r),m=e.cameraMatrix.createSubMatrix3x3(),g=t.cameraMatrix.createSubMatrix3x3(),y=m.row(2),x=g.row(2),v=m.row(1),b=g.row(1),_=new Nn(0,0,0),w=new Nn(0,0,0),C=new Nn(0,0,0),E=new Nn(0,0,0),A=g.mult(m.copy().transpose()),D=A.diagonal();let S,T,F,k,M=.5*(D[0]+D[1]+D[2]-1);if(1-M<1e-7)return _.set(Nn.lerp(y,x,r)).normalize(),C.set(_).mult(d*u).add(f),E.set(_).mult((d-1)*u).add(f),w.set(Nn.lerp(v,b,r)).normalize(),void this.camera(C.x,C.y,C.z,E.x,E.y,E.z,w.x,w.y,w.z);let I=1/(1-M);const B=Math.max(D[0],D[1],D[2]),L=A.mat3[1]+A.mat3[3],O=A.mat3[2]+A.mat3[6],P=A.mat3[5]+A.mat3[7];B===D[0]?(S=Math.sqrt((D[0]-M)*I),I/=S,T=.5*L*I,F=.5*O*I,k=.5*(A.mat3[7]-A.mat3[5])/S):B===D[1]?(T=Math.sqrt((D[1]-M)*I),I/=T,F=.5*P*I,S=.5*L*I,k=.5*(A.mat3[2]-A.mat3[6])/T):(F=Math.sqrt((D[2]-M)*I),I/=F,S=.5*O*I,T=.5*P*I,k=.5*(A.mat3[3]-A.mat3[1])/F);const N=r*Math.atan2(k,M),R=Math.cos(N),V=Math.sin(N),U=1-R,z=S*T,j=T*F,G=F*S,$=new ha([R+U*S*S,U*z+V*F,U*G-V*T,U*z-V*F,R+U*T*T,U*j+V*S,U*G+V*T,U*j-V*S,R+U*F*F]);$.multiplyVec(y,_),C.set(_).mult(d*u).add(f),E.set(_).mult((d-1)*u).add(f),$.multiplyVec(v,w),this.camera(C.x,C.y,C.z,E.x,E.y,E.z,w.x,w.y,w.z)}_computeCameraDefaultSettings(){this.defaultAspectRatio=this._renderer.width/this._renderer.height,this.defaultEyeX=0,this.defaultEyeY=0,this.defaultEyeZ=800,this.defaultCameraFOV=2*Math.atan(this._renderer.height/2/this.defaultEyeZ),this.defaultCenterX=0,this.defaultCenterY=0,this.defaultCenterZ=0,this.defaultCameraNear=this.defaultEyeZ*this._renderer.defaultNearScale(),this.defaultCameraFar=this.defaultEyeZ*this._renderer.defaultFarScale()}_setDefaultCamera(){this.cameraFOV=this.defaultCameraFOV,this.aspectRatio=this.defaultAspectRatio,this.eyeX=this.defaultEyeX,this.eyeY=this.defaultEyeY,this.eyeZ=this.defaultEyeZ,this.centerX=this.defaultCenterX,this.centerY=this.defaultCenterY,this.centerZ=this.defaultCenterZ,this.upX=0,this.upY=1,this.upZ=0,this.cameraNear=this.defaultCameraNear,this.cameraFar=this.defaultCameraFar,this.perspective(),this.camera(),this.cameraType="default"}_resize(){"default"===this.cameraType&&(this._computeCameraDefaultSettings(),this.cameraFOV=this.defaultCameraFOV,this.aspectRatio=this.defaultAspectRatio,this.perspective())}copy(){const e=new ya(this._renderer);return e.cameraFOV=this.cameraFOV,e.aspectRatio=this.aspectRatio,e.eyeX=this.eyeX,e.eyeY=this.eyeY,e.eyeZ=this.eyeZ,e.centerX=this.centerX,e.centerY=this.centerY,e.centerZ=this.centerZ,e.upX=this.upX,e.upY=this.upY,e.upZ=this.upZ,e.cameraNear=this.cameraNear,e.cameraFar=this.cameraFar,e.cameraType=this.cameraType,e.useLinePerspective=this.useLinePerspective,e.cameraMatrix=this.cameraMatrix.copy(),e.projMatrix=this.projMatrix.copy(),e.yScale=this.yScale,e.cameraType=this.cameraType,e.defaultAspectRatio=this.defaultAspectRatio,e.defaultEyeX=this.defaultEyeX,e.defaultEyeY=this.defaultEyeY,e.defaultEyeZ=this.defaultEyeZ,e.defaultCameraFOV=this.defaultCameraFOV,e.defaultCenterX=this.defaultCenterX,e.defaultCenterY=this.defaultCenterY,e.defaultCenterZ=this.defaultCenterZ,e.defaultCameraNear=this.defaultCameraNear,e.defaultCameraFar=this.defaultCameraFar,e}clone(){return this.copy()}_getLocalAxes(){let e=this.eyeX-this.centerX,t=this.eyeY-this.centerY,r=this.eyeZ-this.centerZ;const i=Math.sqrt(e*e+t*t+r*r);0!==i&&(e/=i,t/=i,r/=i);let n=this.upX,s=this.upY,a=this.upZ,o=s*r-a*t,h=-n*r+a*e,u=n*t-s*e;n=t*u-r*h,s=-e*u+r*o,a=e*h-t*o;const l=Math.sqrt(o*o+h*h+u*u);0!==l&&(o/=l,h/=l,u/=l);const c=Math.sqrt(n*n+s*s+a*a);return 0!==c&&(n/=c,s/=c,a/=c),{x:[o,h,u],y:[n,s,a],z:[e,t,r]}}_orbit(e,t,r){const i=this.eyeX-this.centerX,n=this.eyeY-this.centerY,s=this.eyeZ-this.centerZ;let a=Math.hypot(i,n,s);const o=new Nn(i,n,s).normalize(),h=new Nn(this.upX,this.upY,this.upZ).normalize(),u=Nn.cross(h,o).normalize(),l=Nn.cross(u,h);a*=Math.pow(10,r),athis.cameraFar&&(a=this.cameraFar);const c=Math.acos(Math.max(-1,Math.min(1,Nn.dot(o,h))))+t,p=e;(c<=0||c>=Math.PI)&&(this.upX*=-1,this.upY*=-1,this.upZ*=-1),h.mult(Math.cos(c)),l.mult(Math.cos(p)*Math.sin(c)),u.mult(Math.sin(p)*Math.sin(c)),o.set(h).add(l).add(u),this.eyeX=a*o.x+this.centerX,this.eyeY=a*o.y+this.centerY,this.eyeZ=a*o.z+this.centerZ,this.camera(this.eyeX,this.eyeY,this.eyeZ,this.centerX,this.centerY,this.centerZ,this.upX,this.upY,this.upZ)}_orbitFree(e,t,r){const i=this.eyeX-this.centerX,n=this.eyeY-this.centerY,s=this.eyeZ-this.centerZ;let a=Math.hypot(i,n,s);const o=new Nn(i,n,s).normalize(),h=new Nn(this.upX,this.upY,this.upZ),u=Nn.cross(h,o).normalize(),l=Nn.cross(o,u),c=Math.atan2(t,e);l.mult(Math.sin(c)),u.mult(Math.cos(c)).add(l);const p=Math.sqrt(e*e+t*t),d=Nn.cross(o,u);a*=Math.pow(10,r),athis.cameraFar&&(a=this.cameraFar);const f=Math.cos(p),m=Math.sin(p),g=h.dot(o),y=h.dot(u),x=g*f+y*m,v=-g*m+y*f,b=h.dot(d);h.x=x*o.x+v*u.x+b*d.x,h.y=x*o.y+v*u.y+b*d.y,h.z=x*o.z+v*u.z+b*d.z,u.mult(-m),o.mult(f).add(u).mult(a),this.camera(o.x+this.centerX,o.y+this.centerY,o.z+this.centerZ,this.centerX,this.centerY,this.centerZ,h.x,h.y,h.z)}_isActive(){return this===this._renderer.states.curCamera}}function xa(e,t){t.camera=function(...e){return this._assert3d("camera"),this._renderer.camera(...e),this},t.perspective=function(...e){return this._assert3d("perspective"),this._renderer.perspective(...e),this},t.linePerspective=function(e){if(!(this._renderer instanceof Ua))throw new Error("linePerspective() must be called in WebGL mode.");return this._renderer.linePerspective(e)},t.ortho=function(...e){return this._assert3d("ortho"),this._renderer.ortho(...e),this},t.frustum=function(...e){return this._assert3d("frustum"),this._renderer.frustum(...e),this},t.createCamera=function(){return this._assert3d("createCamera"),this._renderer.createCamera()},t.setCamera=function(e){this._renderer.setCamera(e)},e.Camera=ya,Ua.prototype.camera=function(...e){this.states.setValue("curCamera",this.states.curCamera.clone()),this.states.curCamera.camera(...e)},Ua.prototype.perspective=function(...e){this.states.setValue("curCamera",this.states.curCamera.clone()),this.states.curCamera.perspective(...e)},Ua.prototype.linePerspective=function(e){if(void 0===e)return this.states.curCamera.useLinePerspective;this.states.setValue("curCamera",this.states.curCamera.clone()),this.states.curCamera.useLinePerspective=e},Ua.prototype.ortho=function(...e){this.states.setValue("curCamera",this.states.curCamera.clone()),this.states.curCamera.ortho(...e)},Ua.prototype.frustum=function(...e){this.states.setValue("curCamera",this.states.curCamera.clone()),this.states.curCamera.frustum(...e)},Ua.prototype.createCamera=function(){const e=new ya(this);return e._computeCameraDefaultSettings(),e._setDefaultCamera(),e},Ua.prototype.setCamera=function(e){this.states.setValue("curCamera",e),this.states.setValue("uPMatrix",this.states.uPMatrix.clone()),this.states.uPMatrix.set(e.projMatrix),this.states.setValue("uViewMatrix",this.states.uViewMatrix.clone()),this.states.uViewMatrix.set(e.cameraMatrix)}}void 0!==p5&&xa(p5,p5.prototype);var va={exports:{}};!function(e){var t;function r(e,t){return e.b===t.b&&e.a===t.a}function i(e,t){return e.be?0:e)<=(r=0>r?0:r)?0===r?(t+i)/2:t+e/(e+r)*(i-t):i+r/(e+r)*(t-i)}function p(e){var t=y(e.b);return v(t,e.c),v(t.b,e.c),b(t,e.a),t}function d(e,t){var r=!1,i=!1;e!==t&&(t.a!==e.a&&(i=!0,w(t.a,e.a)),t.d!==e.d&&(r=!0,C(t.d,e.d)),x(t,e),i||(v(t,e.a),e.a.c=e),r||(b(t,e.d),e.d.a=e))}function f(e){var t=e.b,r=!1;e.d!==e.b.d&&(r=!0,C(e.d,e.b.d)),e.c===e?w(e.a,null):(e.b.d.a=Q(e),e.a.c=e.c,x(e,Q(e)),r||b(e,e.d)),t.c===t?(w(t.a,null),C(t.d,null)):(e.d.a=Q(t),t.a.c=t.c,x(t,Q(t))),_(e)}function m(e){var t=y(e),r=t.b;return x(t,e.e),t.a=e.b.a,v(r,t.a),t.d=r.d=e.d,t=t.b,x(e.b,Q(e.b)),x(e.b,t),e.b.a=t.a,t.b.a.c=t.b,t.b.d=e.b.d,t.f=e.f,t.b.f=e.b.f,t}function g(e,t){var r=!1,i=y(e),n=i.b;return t.d!==e.d&&(r=!0,C(t.d,e.d)),x(i,e.e),x(n,t),i.a=e.b.a,n.a=t.a,i.d=n.d=e.d,e.d.a=n,r||b(i,e.d),i}function y(e){var t=new J,r=new J,i=e.b.h;return r.h=i,i.b.h=t,t.h=e,e.b.h=r,t.b=r,t.c=t,t.e=r,r.b=t,r.c=r,r.e=t}function x(e,t){var r=e.c,i=t.c;r.b.e=t,i.b.e=e,e.c=i,t.c=r}function v(e,t){var r=t.f,i=new te(t,r);r.e=i,t.f=i,r=i.c=e;do{r.a=i,r=r.c}while(r!==e)}function b(e,t){var r=t.d,i=new K(t,r);r.b=i,t.d=i,i.a=e,i.c=t.c,r=e;do{r.d=i,r=r.e}while(r!==e)}function _(e){var t=e.h;e=e.b.h,t.b.h=e,e.b.h=t}function w(e,t){var r=e.c,i=r;do{i.a=t,i=i.c}while(i!==r);r=e.f,(i=e.e).f=r,r.e=i}function C(e,t){var r=e.a,i=r;do{i.d=t,i=i.e}while(i!==r);r=e.d,(i=e.b).d=r,r.b=i}function E(e){var t=0;return Math.abs(e[1])>Math.abs(e[0])&&(t=1),Math.abs(e[2])>Math.abs(e[t])&&(t=2),t}var A=4e150;function D(e,t){e.f+=t.f,e.b.f+=t.b.f}function S(e,t,r){return e=e.a,t=t.a,r=r.a,t.b.a===e?r.b.a===e?i(t.a,r.a)?0>=s(r.b.a,t.a,r.a):0<=s(t.b.a,r.a,t.a):0>=s(r.b.a,e,r.a):r.b.a===e?0<=s(t.b.a,e,t.a):(t=n(t.b.a,e,t.a))>=(e=n(r.b.a,e,r.a))}function T(e){e.a.i=null;var t=e.e;t.a.c=t.c,t.c.a=t.a,e.e=null}function F(e,t){f(e.a),e.c=!1,e.a=t,t.i=e}function k(e){var t=e.a.a;do{e=de(e)}while(e.a.a===t);return e.c&&(F(e,t=g(pe(e).a.b,e.a.e)),e=de(e)),e}function M(e,t,r){var i=new ce;return i.a=r,i.e=H(e.f,t.e,i),r.i=i}function I(e,t){switch(e.s){case 100130:return!!(1&t);case 100131:return 0!==t;case 100132:return 0t;case 100134:return 2<=t||-2>=t}return!1}function B(e){var t=e.a,r=t.d;r.c=e.d,r.a=t,T(e)}function L(e,t,r){for(e=t,t=t.a;e!==r;){e.c=!1;var i=pe(e),n=i.a;if(n.a!==t.a){if(!i.c){B(e);break}F(i,n=g(t.c.b,n.b))}t.c!==n&&(d(Q(n),n),d(t,n)),B(e),t=i.a,e=i}return t}function O(e,t,r,i,n,s){var a=!0;do{M(e,t,r.b),r=r.c}while(r!==i);for(null===n&&(n=pe(t).a.b.c);(r=(i=pe(t)).a.b).a===n.a;)r.c!==n&&(d(Q(r),r),d(Q(n),r)),i.f=t.f-r.f,i.d=I(e,i.f),t.b=!0,!a&&V(e,t)&&(D(r,n),T(t),f(n)),a=!1,t=i,n=r;t.b=!0,s&&z(e,t)}function P(e,t,r,i,n){var s=[t.g[0],t.g[1],t.g[2]];t.d=null,t.d=e.o&&e.o(s,r,i,e.c)||null,null===t.d&&(n?e.n||(Z(e,100156),e.n=!0):t.d=r[0])}function N(e,t,r){var i=[null,null,null,null];i[0]=t.a.d,i[1]=r.a.d,P(e,t.a,i,[.5,.5,0,0],!1),d(t,r)}function R(e,t,r,i,n){var s=Math.abs(t.b-e.b)+Math.abs(t.a-e.a),a=Math.abs(r.b-e.b)+Math.abs(r.a-e.a),o=n+1;i[n]=.5*a/(s+a),i[o]=.5*s/(s+a),e.g[0]+=i[n]*t.g[0]+i[o]*r.g[0],e.g[1]+=i[n]*t.g[1]+i[o]*r.g[1],e.g[2]+=i[n]*t.g[2]+i[o]*r.g[2]}function V(e,t){var n=pe(t),a=t.a,o=n.a;if(i(a.a,o.a)){if(0=p||i(l[u[p>>1]],l[u[p]])?ue(n,p):le(n,p)),l[h]=null,c[h]=n.b,n.b=h}else for(n.c[-(h+1)]=null;0s(a.b.a,o.a,a.a))return!1;de(t).b=t.b=!0,m(a.b),d(Q(o),a)}return!0}function U(e,t){var u=pe(t),l=t.a,p=u.a,f=l.a,g=p.a,y=l.b.a,x=p.b.a,v=new te;if(f===g||Math.min(f.a,y.a)>Math.max(g.a,x.a))return!1;if(i(f,g)){if(0s(y,g,f))return!1;var b,_,w=y,C=f,E=x,A=g;if(i(w,C)||(b=w,w=C,C=b),i(E,A)||(b=E,E=A,A=b),i(w,E)||(b=w,w=E,E=b,b=C,C=A,A=b),i(E,C)?i(C,A)?(0>(b=n(w,E,C))+(_=n(E,C,A))&&(b=-b,_=-_),v.b=c(b,E.b,_,C.b)):(0>(b=s(w,E,C))+(_=-s(w,A,C))&&(b=-b,_=-_),v.b=c(b,E.b,_,A.b)):v.b=(E.b+C.b)/2,a(w,C)||(b=w,w=C,C=b),a(E,A)||(b=E,E=A,A=b),a(w,E)||(b=w,w=E,E=b,b=C,C=A,A=b),a(E,C)?a(C,A)?(0>(b=o(w,E,C))+(_=o(E,C,A))&&(b=-b,_=-_),v.a=c(b,E.a,_,C.a)):(0>(b=h(w,E,C))+(_=-h(w,A,C))&&(b=-b,_=-_),v.a=c(b,E.a,_,A.a)):v.a=(E.a+C.a)/2,i(v,e.a)&&(v.b=e.a.b,v.a=e.a.a),w=i(f,g)?f:g,i(w,v)&&(v.b=w.b,v.a=w.a),r(v,f)||r(v,g))return V(e,t),!1;if(!r(y,e.a)&&0<=s(y,e.a,v)||!r(x,e.a)&&0>=s(x,e.a,v)){if(x===e.a)return m(l.b),d(p.b,l),l=pe(t=k(t)).a,L(e,pe(t),u),O(e,t,Q(l),l,l,!0),!0;if(y===e.a){m(p.b),d(l.e,Q(p)),g=(f=u=t).a.b.a;do{f=de(f)}while(f.a.b.a===g);return f=pe(t=f).a.b.c,u.a=Q(p),O(e,t,(p=L(e,u,null)).c,l.b.c,f,!0),!0}return 0<=s(y,e.a,v)&&(de(t).b=t.b=!0,m(l.b),l.a.b=e.a.b,l.a.a=e.a.a),0>=s(x,e.a,v)&&(t.b=u.b=!0,m(p.b),p.a.b=e.a.b,p.a.a=e.a.a),!1}return m(l.b),m(p.b),d(Q(p),l),l.a.b=v.b,l.a.a=v.a,l.a.h=ie(e.e,l.a),l=l.a,p=[0,0,0,0],v=[f.d,y.d,g.d,x.d],l.g[0]=l.g[1]=l.g[2]=0,R(l,f,y,p,0),R(l,g,x,p,2),P(e,l,v,p,!0),de(t).b=t.b=u.b=!0,!1}function z(e,t){for(var r=pe(t);;){for(;r.b;)t=r,r=pe(r);if(!t.b&&(r=t,null===(t=de(t))||!t.b))break;t.b=!1;var n,a=t.a,o=r.a;if(n=a.b.a!==o.b.a)e:{var h=pe(n=t),u=n.a,l=h.a,c=void 0;if(i(u.b.a,l.b.a)){if(0>s(u.b.a,l.b.a,u.a)){n=!1;break e}de(n).b=n.b=!0,c=m(u),d(l.b,c),c.d.c=n.d}else{if(0i.f&&(i.f*=2,i.c=ae(i.c,i.f+1)),0===i.b?r=n:(r=i.b,i.b=i.c[i.b]),i.e[r]=t,i.c[r]=n,i.d[n]=r,i.h&&le(i,n),r}return i=e.a++,e.c[i]=t,-(i+1)}function ne(e){if(0===e.a)return he(e.b);var t=e.c[e.d[e.a-1]];if(0!==e.b.a&&i(oe(e.b),t))return he(e.b);do{--e.a}while(0e.a||i(n[o],n[u])){r[a]=o,s[o]=a;break}r[a]=u,s[u]=a,a=h}}function le(e,t){for(var r=e.d,n=e.e,s=e.c,a=t,o=r[a];;){var h=a>>1,u=r[h];if(0===h||i(n[u],n[o])){r[a]=o,s[o]=a;break}r[a]=u,s[u]=a,a=h}}function ce(){this.e=this.a=null,this.f=0,this.c=this.b=this.h=this.d=!1}function pe(e){return e.e.c.b}function de(e){return e.e.a.b}(t=W.prototype).x=function(){Y(this,X)},t.B=function(e,t){switch(e){case 100142:return;case 100140:switch(t){case 100130:case 100131:case 100132:case 100133:case 100134:return void(this.s=t)}break;case 100141:return void(this.m=!!t);default:return void Z(this,100900)}Z(this,100901)},t.y=function(e){switch(e){case 100142:return 0;case 100140:return this.s;case 100141:return this.m;default:Z(this,100900)}return!1},t.A=function(e,t,r){this.j[0]=e,this.j[1]=t,this.j[2]=r},t.z=function(e,t){var r=t||null;switch(e){case 100100:case 100106:this.h=r;break;case 100104:case 100110:this.l=r;break;case 100101:case 100107:this.k=r;break;case 100102:case 100108:this.i=r;break;case 100103:case 100109:this.p=r;break;case 100105:case 100111:this.o=r;break;case 100112:this.r=r;break;default:Z(this,100900)}},t.C=function(e,t){var r=!1,i=[0,0,0];Y(this,2);for(var n=0;3>n;++n){var s=e[n];-1e150>s&&(s=-1e150,r=!0),1e150p;++p){var d=c.g[p];dn[p]&&(n[p]=d,o[p]=c)}if(c=0,n[1]-a[1]>n[0]-a[0]&&(c=1),n[2]-a[2]>n[c]-a[c]&&(c=2),a[c]>=n[c])t[0]=0,t[1]=0,t[2]=1;else{for(n=0,a=h[c],o=o[c],h=[0,0,0],a=[a.g[0]-o.g[0],a.g[1]-o.g[1],a.g[2]-o.g[2]],p=[0,0,0],c=e.e;c!==e;c=c.e)p[0]=c.g[0]-o.g[0],p[1]=c.g[1]-o.g[1],p[2]=c.g[2]-o.g[2],h[0]=a[1]*p[2]-a[2]*p[1],h[1]=a[2]*p[0]-a[0]*p[2],h[2]=a[0]*p[1]-a[1]*p[0],(d=h[0]*h[0]+h[1]*h[1]+h[2]*h[2])>n&&(n=d,t[0]=h[0],t[1]=h[1],t[2]=h[2]);0>=n&&(t[0]=t[1]=t[2]=0,t[E(a)]=1)}e=!0}for(h=E(t),c=this.b.c,n=(h+1)%3,o=(h+2)%3,h=0=(n=c.a).f))do{t+=(n.a.b-n.b.a.b)*(n.a.a+n.b.a.a),n=n.e}while(n!==c.a);if(0>t)for(e=(t=this.b.c).e;e!==t;e=e.e)e.a=-e.a}for(this.n=!1,c=(t=this.b.b).h;c!==t;c=e)e=c.h,n=c.e,r(c.a,c.b.a)&&c.e.e!==c&&(N(this,n,c),f(c),n=(c=n).e),n.e===c&&(n!==c&&(n!==e&&n!==e.b||(e=e.h),f(n)),c!==e&&c!==e.b||(e=e.h),f(c));for(this.e=t=new re,c=(e=this.b.c).e;c!==e;c=c.e)c.h=ie(t,c);for(function(e){e.d=[];for(var t=0;t=s(n.a,n.b.a,n.e.b.a));)n=(o=g(n.e,n)).b;n=n.c.b}else{for(;n.e!==c&&(l(c.c.b)||0<=s(c.b.a,c.a,c.c.b.a));)c=(o=g(c,c.c.b)).b;c=c.e}for(;n.e.e!==c;)n=(o=g(n.e,n)).b}if(this.h||this.i||this.k||this.l)if(this.m){for(e=(t=this.b).a.b;e!==t.a;e=e.b)if(e.c){this.h&&this.h(2,this.c),c=e.a;do{this.k&&this.k(c.a.d,this.c),c=c.e}while(c!==e.a);this.i&&this.i(this.c)}}else{for(t=this.b,e=!!this.l,c=!1,n=-1,o=t.a.d;o!==t.a;o=o.d)if(o.c){c||(this.h&&this.h(4,this.c),c=!0),h=o.a;do{e&&(n!==(a=h.b.d.c?0:1)&&(n=a,this.l&&this.l(!!n,this.c))),this.k&&this.k(h.a.d,this.c),h=h.e}while(h!==o.a)}c&&this.i&&this.i(this.c)}if(this.r){for(c=(t=this.b).a.b;c!==t.a;c=e)if(e=c.b,!c.c){o=(n=c.a).e,h=void 0;do{o=(h=o).e,h.d=null,null===h.b.d&&(h.c===h?w(h.a,null):(h.a.c=h.c,x(h,Q(h))),(a=h.b).c===a?w(a.a,null):(a.a.c=a.c,x(a,Q(a))),_(h))}while(h!==n);n=c.d,(c=c.b).d=n,n.b=c}return this.r(this.b),void(this.c=this.b=null)}}this.b=this.c=null},Ss.libtess={GluTesselator:W,windingRule:{GLU_TESS_WINDING_ODD:100130,GLU_TESS_WINDING_NONZERO:100131,GLU_TESS_WINDING_POSITIVE:100132,GLU_TESS_WINDING_NEGATIVE:100133,GLU_TESS_WINDING_ABS_GEQ_TWO:100134},primitiveType:{GL_LINE_LOOP:2,GL_TRIANGLES:4,GL_TRIANGLE_STRIP:5,GL_TRIANGLE_FAN:6},errorType:{GLU_TESS_MISSING_BEGIN_POLYGON:100151,GLU_TESS_MISSING_END_POLYGON:100153,GLU_TESS_MISSING_BEGIN_CONTOUR:100152,GLU_TESS_MISSING_END_CONTOUR:100154,GLU_TESS_COORD_TOO_LARGE:100155,GLU_TESS_NEED_COMBINE_CALLBACK:100156},gluEnum:{GLU_TESS_MESH:100112,GLU_TESS_TOLERANCE:100142,GLU_TESS_WINDING_RULE:100140,GLU_TESS_BOUNDARY_ONLY:100141,GLU_INVALID_ENUM:100900,GLU_INVALID_VALUE:100901,GLU_TESS_BEGIN:100100,GLU_TESS_VERTEX:100101,GLU_TESS_END:100102,GLU_TESS_ERROR:100103,GLU_TESS_EDGE_FLAG:100104,GLU_TESS_COMBINE:100105,GLU_TESS_BEGIN_DATA:100106,GLU_TESS_VERTEX_DATA:100107,GLU_TESS_END_DATA:100108,GLU_TESS_ERROR_DATA:100109,GLU_TESS_EDGE_FLAG_DATA:100110,GLU_TESS_COMBINE_DATA:100111}},W.prototype.gluDeleteTess=W.prototype.x,W.prototype.gluTessProperty=W.prototype.B,W.prototype.gluGetTessProperty=W.prototype.y,W.prototype.gluTessNormal=W.prototype.A,W.prototype.gluTessCallback=W.prototype.z,W.prototype.gluTessVertex=W.prototype.C,W.prototype.gluTessBeginPolygon=W.prototype.u,W.prototype.gluTessBeginContour=W.prototype.t,W.prototype.gluTessEndContour=W.prototype.v,W.prototype.gluTessEndPolygon=W.prototype.w,e.exports=Ss.libtess}(va);var ba=Ts(va.exports);class _a{constructor(e,t,r,i,n,s){this.size=e,this.src=t,this.dst=r,this.attr=i,this._renderer=n,this.map=s}default(e){return this.default=e,this}_prepareBuffer(e,t){this._renderer._prepareBuffer(this,e,t)}}function wa(e,t){e.RenderBuffer=_a}void 0!==p5&&wa(p5);const Ca={vertices:1,vertexNormals:1,vertexColors:4,vertexStrokeColors:4,uvs:2},Ea=Object.values(Ca).reduce(((e,t)=>e+t));class Aa{constructor(e){this.renderer=e,this.shapeMode=8,this.geometry=new pa(void 0,void 0,void 0,this.renderer),this.geometry.gid="__IMMEDIATE_MODE_GEOMETRY__",this.contourIndices=[],this._useUserVertexProperties=void 0,this._bezierVertex=[],this._quadraticVertex=[],this._curveVertex=[],this.isProcessingVertices=!1,this._tessy=this._initTessy(),this.tessyVertexSize=Ea,this.bufferStrides={...Ca}}friendlyErrorsDisabled(){return!1}constructFromContours(e,t){this._useUserVertexProperties&&this._resetUserVertexProperties(),this.geometry.reset(),this.contourIndices=[],this.shapeMode=e.contours[0].kind;const r=!!this.renderer.states.strokeColor,i={};if(e.userVertexProperties){this._useUserVertexProperties=!0;for(const t in e.userVertexProperties){const r=e.vertexPropertyName(t),n=this.geometry._userVertexPropertyHelper(r,[],e.userVertexProperties[t]);i[t]=n,this.tessyVertexSize+=n.getDataSize(),this.bufferStrides[n.getSrcName()]=n.getDataSize(),this.renderer.buffers.user.push(new _a(n.getDataSize(),n.getSrcName(),n.getDstName(),r,this.renderer))}}else this._useUserVertexProperties=!1;for(const e of t){this.contourIndices.push(this.geometry.vertices.length);for(const t of e){if(this.shapeMode===P&&this.geometry.vertices.length%6==3)for(const e in this.bufferStrides){const t=this.bufferStrides[e],r=this.geometry[e];r.push(...r.slice(r.length-3*t,r.length-2*t),...r.slice(r.length-t,r.length))}this.geometry.vertices.push(t.position),this.geometry.vertexNormals.push(t.normal||new Nn(0,0,0)),this.geometry.uvs.push(t.textureCoordinates.x,t.textureCoordinates.y),this.renderer.states.fillColor?this.geometry.vertexColors.push(...t.fill.array()):this.geometry.vertexColors.push(0,0,0,0),this.renderer.states.strokeColor?this.geometry.vertexStrokeColors.push(...t.stroke.array()):this.geometry.vertexStrokeColors.push(0,0,0,0);for(const e in i){const r=i[e];e in t&&r.setCurrentData(t[e]),r.pushCurrentData()}}}if(r&&(this.geometry.edges=this._calculateEdges(this.shapeMode,this.geometry.vertices)),r&&!this.renderer.geometryBuilder&&this.geometry._edgesToVertices(),8===this.shapeMode){const e=this.geometry.vertices.length;if(e>5e4&&!this.friendlyErrorsDisabled()&&!this.renderer._largeTessellationAcknowledged){if(!window.confirm(`🌸 p5.js says:\n\nThis shape has ${e} vertices. Tessellating shapes with this many vertices can be very slow and may cause your browser to become unresponsive.\n\nDo you want to continue tessellating this shape?`))return;this.renderer._largeTessellationAcknowledged=!0}this.isProcessingVertices=!0,this._tesselateShape(),this.isProcessingVertices=!1}else this.shapeMode===N?this.shapeMode=5:this.shapeMode===P&&(this.shapeMode=4);this.renderer.geometryBuilder||6!==this.shapeMode||this.renderer.supportsTriangleFan()||(this._convertFanToTriangles(),this.shapeMode=4),this.renderer.states.textureMode===Ae&&null!==this.renderer.states._tex&&this.renderer.states._tex.width>0&&this.renderer.states._tex.height>0&&(this.geometry.uvs=this.geometry.uvs.map(((e,t)=>t%2==0?e/this.renderer.states._tex.width:e/this.renderer.states._tex.height)))}_remapVertices(e){this.geometry.vertices=e.map((e=>this.geometry.vertices[e])),this.geometry.vertexNormals=e.map((e=>this.geometry.vertexNormals[e]));const t=(t,r)=>{const i=[];for(const n of e)for(let e=0;e0&&this.contourIndices[0]===t&&(this.contourIndices.shift(),e.push([])),e[e.length-1].push(this.geometry.vertices[t].x,this.geometry.vertices[t].y,this.geometry.vertices[t].z,this.geometry.uvs[2*t],this.geometry.uvs[2*t+1],this.geometry.vertexColors[4*t],this.geometry.vertexColors[4*t+1],this.geometry.vertexColors[4*t+2],this.geometry.vertexColors[4*t+3],this.geometry.vertexNormals[t].x,this.geometry.vertexNormals[t].y,this.geometry.vertexNormals[t].z);for(const r in this.geometry.userVertexProperties){const i=this.geometry.userVertexProperties[r],n=t*i.getDataSize(),s=n+i.getDataSize(),a=i.getSrcArray().slice(n,s);e[e.length-1].push(...a)}}const t=1e-6;for(const r of e){const e=this.tessyVertexSize;for(let i=e;it.map((t=>{if(!e.has(t)){const r=i[t];let n=this.geometry.vertices.findIndex((e=>r.x===e.x&&r.y===e.y&&r.z===e.z));if(-1===n){let e=1/0,t=0;for(let i=0;i{const i=new Array(this.tessyVertexSize).fill(0);for(let e=0;e1e3){const e=Object.keys(this.cache)[0];this.freeBuffers(e)}const r={geometry:e};this.cache[t]=r;const i=e.faces.length?e.faces.flat():null;let n=null;if(i){const e=i.some((e=>e>65535));n=e?Uint32Array:Uint16Array}return this.renderer._ensureGeometryBuffers(r,i,n),r}freeBuffers(e){const t=this.cache[e];t&&(delete this.cache[e],this.renderer._freeBuffers(t))}}const Sa={[ve]:3,[ge]:4,[pe]:.5},Ta="ideographic",Fa="middle",ka="_textBoundsSingle",Ma="_fontBoundsSingle",Ia="hanging",Ba="start",La="end";function Oa(e,t){const r=/\r?\n/g,i=/,\s+/,n=/^".*"$/,s=/[^\x00-\x7F]/,a=/\t/g,o=new RegExp(`(?:${["wght","wdth","ital","slnt","opsz"].join("|")})`);["text","textAlign","textAscent","textDescent","textLeading","textMode","textFont","textSize","textStyle","textWidth","textWrap","textBounds","textDirection","textProperty","textProperties","fontBounds","fontWidth","fontAscent","fontDescent","textWeight"].forEach((r=>{t[r]=function(...e){if(!(r in ds.prototype))throw Error(`Renderer2D.prototype.${r} is not defined.`);return this._renderer[r](...e)},e.Graphics.prototype[r]=function(...e){return this._renderer[r](...e)}}));const h={textAlign:{default:t.LEFT,type:"Context2d"},textBaseline:{default:t.BASELINE,type:"Context2d"},textFont:{default:{family:"sans-serif"}},textLeading:{default:15},textSize:{default:12},textWrap:{default:t.WORD},fontStretch:{default:t.NORMAL,isShorthand:!0},fontWeight:{default:t.NORMAL,isShorthand:!0},lineHeight:{default:t.NORMAL,isShorthand:!0},fontVariant:{default:t.NORMAL,isShorthand:!0},fontStyle:{default:t.NORMAL,isShorthand:!0},direction:{default:"inherit"}},u=["font","direction","fontKerning","fontStretch","fontVariantCaps","letterSpacing","textAlign","textBaseline","textRendering","wordSpacing"],l=Object.keys(h).filter((e=>h[e].isShorthand)),c=["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded"];let p,d;ds.prototype.text=function(e,t,r,i,n){let s=this.textDrawingContext().textBaseline;({x:t,y:r,width:i,height:n}=this._handleRectMode(t,r,i,n));let a=this._processLines(e,i,n);a=this._positionLines(t,r,i,n,a),a.forEach((e=>this._renderText(e.text,e.x,e.y))),this.textDrawingContext().textBaseline=s},ds.prototype.textBounds=function(e,t,r,i,n){return this._computeBounds(ka,e,t,r,i,n).bounds},ds.prototype.fontBounds=function(e,t,r,i,n){return this._computeBounds(Ma,e,t,r,i,n).bounds},ds.prototype.textWidth=function(e){let t=this._processLines(e);return Math.max(...t.map((e=>this._textWidthSingle(e))))},ds.prototype.fontWidth=function(e){let t=this._processLines(e);return Math.max(...t.map((e=>this._fontWidthSingle(e))))},ds.prototype.textAscent=function(e=""){return e.length?this.textDrawingContext().measureText(e).actualBoundingBoxAscent:this.fontAscent()},ds.prototype.fontAscent=function(){return this.textDrawingContext().measureText("_").fontBoundingBoxAscent},ds.prototype.textDescent=function(e=""){return e.length?this.textDrawingContext().measureText(e).actualBoundingBoxDescent:this.fontDescent()},ds.prototype.fontDescent=function(){return this.textDrawingContext().measureText("_").fontBoundingBoxDescent},ds.prototype.textAlign=function(e,r){return 0===arguments.length?{horizontal:this.states.textAlign,vertical:this.states.textBaseline}:("object"==typeof e&&null!==e&&(e.hasOwnProperty("vertical")&&(r=e.vertical),e.hasOwnProperty("horizontal")&&(e=e.horizontal)),("string"==typeof e||e instanceof String)&&this.states.setValue("textAlign",e),("string"==typeof r||r instanceof String)&&(r===t.CENTER&&(r=Fa),this.states.setValue("textBaseline",r)),this._applyTextProperties())},ds.prototype._currentTextFont=function(){return this.states.textFont.font||this.states.textFont.family},ds.prototype.textFont=function(t,r,i){if(0===arguments.length)return this._currentTextFont();let n=t;if(t instanceof e.Font?n=t.face.family:t.data instanceof Uint8Array?(n=t.name.fontFamily,t.name?.fontSubfamily&&(n+="-"+t.name.fontSubfamily)):"string"==typeof t&&void 0===r&&/[.0-9]+(%|em|p[xt])/.test(n)&&({family:n,size:r}=this._directSetFontString(n)),"string"!=typeof n)throw Error("null font in textFont()");return 2===arguments.length&&"object"==typeof r&&(i=r,r=void 0),this.states.setValue("textFont",{font:t,family:n,size:r}),void 0!==r&&this._setTextSize(r),"object"==typeof i&&this.textProperties(i),this._applyTextProperties()},ds.prototype._directSetFontString=function(e,t=0){t&&console.log('_directSetFontString"'+e+'"');let r=l.reduce(((e,t)=>(e[t]=h[t].default,e)),{}),i=this._cachedDiv(r);i.style.font=e;let n=getComputedStyle(i);return l.forEach((e=>{this.states[e]=n[e],t&&console.log(" this.states."+e+'="'+n[e]+'"')})),{family:n.fontFamily,size:n.fontSize}},ds.prototype.textLeading=function(e){return"number"==typeof e?(this.states.setValue("leadingSet",!0),this.states.setValue("textLeading",e),this._applyTextProperties()):this.states.textLeading},ds.prototype.textWeight=function(e){return"number"==typeof e?(this.states.setValue("fontWeight",e),void this._applyTextProperties()):this.states.fontWeight},ds.prototype.textSize=function(e){return void 0!==e?(this._setTextSize(e),this._applyTextProperties()):this.states.textSize},ds.prototype.textStyle=function(e){return void 0!==e?(this.states.setValue("fontStyle",e),this._applyTextProperties()):this.states.fontStyle},ds.prototype.textWrap=function(e){return e===t.WORD||e===t.CHAR?(this.states.setValue("textWrap",e),this._pInst):this.states.textWrap},ds.prototype.textDirection=function(e){return void 0!==e?(this.states.setValue("direction",e),this._applyTextProperties()):this.states.direction},ds.prototype.textProperty=function(e,t,r){let i=!1,n=r?.debug||!1;if(void 0===t){let t=this.textProperties();if(e in t)return t[e];throw Error('Unknown text option "'+e+'"')}return e in this.states&&this.states[e]!==t?(this.states[e]=t,i=!0,n&&console.log("this.states."+e+'="'+options[e]+'"')):e in this.textDrawingContext()?(this._setContextProperty(e,t,n),i=!0):e in this.textCanvas().style?(this._setCanvasStyleProperty(e,t,n),i=!0):console.warn('Ignoring unknown text option: "'+e+'"\n'),i?this._applyTextProperties():this._pInst},ds.prototype.textProperties=function(e){if(void 0!==e)return Object.keys(e).forEach((t=>{this.textProperty(t,e[t])})),this._pInst;let t=this.textDrawingContext();return e=u.reduce(((e,r)=>(e[r]=t[r],e)),{}),Object.keys(h).forEach((r=>{if("Context2d"===h[r]?.type)e[r]=t[r];else if("textFont"===r){let t=this._currentTextFont();"object"==typeof t&&"_pInst"in t&&(t=Object.assign({},t),delete t._pInst),e[r]=t}else e[r]=this.states[r]})),e},ds.prototype.textMode=function(){},ds.prototype._currentTextFont=function(){return this.states.textFont.font||this.states.textFont.family},ds.prototype._computeBounds=function(t,r,i,n,s,a,o){let h=this.textDrawingContext(),u=h.textBaseline,{textLeading:l,textAlign:c}=this.states;({width:s,height:a}=this._rectModeAdjust(i,n,s,a));let p=this._processLines(r,s,a),d=p.map(((e,r)=>this[t].bind(this)(e,i,n+r*l)));p.length>1&&void 0!==s&&d.forEach((t=>t.x+=e.Renderer2D.prototype._xAlignOffset.call(this,c,s))),e.Renderer2D.prototype._yAlignOffset.call(this,d,a||0);let f=d[0];return p.length>1&&(f=this._aggregateBounds(d),o?.ignoreRectMode||this._rectModeAlign(f,s||0,a||0)),h.textBaseline=u,{bounds:f,lines:p}},ds.prototype._rectModeAdjust=function(e,r,i,n){if(void 0!==i)switch(this.states.rectMode){case t.CENTER:break;case t.CORNERS:i-=e,n-=r;break;case t.RADIUS:i*=2,n*=2}return{x:e,y:r,width:i,height:n}},ds.prototype._setCanvasStyleProperty=function(e,t,r){let i=t.toString();r&&console.log("canvas.style."+e+'="'+i+'"'),"fontVariationSettings"===e&&this._handleFontVariationSettings(i),this.textCanvas().style[e]=i,this.textCanvas().style[e]},ds.prototype._handleFontVariationSettings=function(e,t=!1){"object"==typeof e&&(e=Object.keys(e).map((t=>t+" "+e[t])).join(", ")),e.split(i).forEach((e=>{e=e.replace(/["']/g,"");let r=o.exec(e);if(r&&r.length){let i=r[0],n=parseFloat(parseFloat(e.replace(i,"").trim()).toFixed(3));switch(i){case"wght":return t&&console.log("setting font-weight="+n),this.states.fontWeight!==n&&this.textWeight(n),n;case"wdth":break;case"ital":t&&console.log("setting font-style="+(n?"italic":"normal"));break;case"slnt":t&&console.log("setting font-style="+(n?"oblique":"normal"));break;case"opsz":t&&console.log("setting font-optical-size="+n)}}}))},ds.prototype._setContextProperty=function(e,t,r=!1){if(this.textDrawingContext()[e]===t)return this._pInst;(p??=[]).push([e,t]),r&&console.log("queued context2d."+e+'="'+t+'"')},ds.prototype._handleRectMode=function(e,r,i,n){let s=this.states.rectMode;if(void 0!==i)switch(s){case t.RADIUS:e-=(i*=2)/2,void 0!==n&&(r-=(n*=2)/2);break;case t.CENTER:e-=i/2,void 0!==n&&(r-=n/2);break;case t.CORNERS:i-=e,void 0!==n&&(n-=r)}return{x:e,y:r,width:i,height:n}},ds.prototype._fontSizePx=function(e,{family:t}=this.states.textFont){if(r=e,!isNaN(r)&&""!==r.trim())return parseFloat(e);var r;let i=this._cachedDiv({fontSize:e});i.style.fontSize=e,i.style.fontFamily=t;let n=getComputedStyle(i).fontSize,s=parseFloat(n);if("number"!=typeof s)throw Error("textSize: invalid font-size");return s},ds.prototype._cachedDiv=function(e){if(void 0===d){let t=document.createElement("div");t.ariaHidden="true",t.style.display="none",Object.entries(e).forEach((([e,r])=>{t.style[e]=r})),this.textCanvas().appendChild(t),d=t}return d},ds.prototype._aggregateBounds=function(e){let t=Math.min(...e.map((e=>e.x))),r=Math.min(...e.map((e=>e.y))),i=Math.max(...e.map((e=>e.y+e.h))),n=Math.max(...e.map((e=>e.x+e.w)));return{x:t,y:r,w:n-t,h:i-r}},ds.prototype._processLines=function(e,r,i){if(void 0!==r){this.textDrawingContext().textBaseline===t.BASELINE&&(this.drawingContext.textBaseline=t.TOP)}let n=this._splitOnBreaks(e.toString()),s=n.length>1,a=void 0!==r,o=a&&n.some((e=>this._textWidthSingle(e)>r)),{textLeading:h,textWrap:u}=this.states;if((s||o)&&a&&(n=this._lineate(u,n,r)),a&&void 0!==i){if(void 0===h)throw Error("leading is required if height is specified");for(let e=0;ei){n=n.slice(0,e);break}}}return n},ds.prototype._xAlignOffset=function(e,r){switch(e){case t.LEFT:return 0;case t.CENTER:return r/2;case t.RIGHT:return r;case Ba:return 0;case La:throw new Error("textBounds: END not yet supported for textAlign");default:return 0}},ds.prototype._rectModeAlign=function(e,r,i){if(void 0!==r){switch(this.states.rectMode){case t.CENTER:e.x-=(r-e.w)/2,e.y-=(i-e.h)/2;break;case t.CORNERS:e.w+=e.x,e.h+=e.y;break;case t.RADIUS:e.x-=(r-e.w)/2,e.y-=(i-e.h)/2,e.w/=2,e.h/=2}return e}},ds.prototype._rectModeAlignRevert=function(e,r,i){if(void 0!==r){switch(this.states.rectMode){case t.CENTER:e.x+=(r-e.w)/2,e.y+=(i-e.h)/2;break;case t.CORNERS:e.w-=e.x,e.h-=e.y;break;case t.RADIUS:e.x+=(r-e.w)/2,e.y+=(i-e.h)/2,e.w*=2,e.h*=2}return e}},ds.prototype._textWidthSingle=function(e){let t=this.textDrawingContext().measureText(e),r=t.actualBoundingBoxLeft;return t.actualBoundingBoxRight+r},ds.prototype._fontWidthSingle=function(e){return this.textDrawingContext().measureText(e).width},ds.prototype._textBoundsSingle=function(e,t=0,r=0){let i=this.textDrawingContext().measureText(e),n=i.actualBoundingBoxAscent,s=i.actualBoundingBoxDescent,a=i.actualBoundingBoxLeft;return{x:t-a,y:r-n,w:i.actualBoundingBoxRight+a,h:n+s}},ds.prototype._fontBoundsSingle=function(e,t=0,r=0){let i=this.textDrawingContext().measureText(e),n=i.fontBoundingBoxAscent,s=i.fontBoundingBoxDescent;return{x:t-=this._xAlignOffset(this.states.textAlign,i.width),y:r-n,w:i.width,h:n+s}},ds.prototype._setTextSize=function(e){if("string"==typeof e&&(e=this._fontSizePx(e)),"number"==typeof e){if(this.states.textSize!==e)return this.states.setValue("textSize",e),this.states.leadingSet||this.states.setValue("textLeading",1.275*this.states.textSize),!0}else console.warn("textSize: invalid size: "+e);return!1},ds.prototype._lineate=function(e,r,i=1/0,n={}){let s,a,o,h,u=n.splitChar??(e===t.WORD?" ":""),l=[];for(let e=0;e0&&o>i?(l.push(s.trim()),s=`${h[e]}`+u):s=a;l.push(s.trim())}return l},ds.prototype._splitOnBreaks=function(e){return e&&0!==e.length?e.replace(a," ").split(r):[""]},ds.prototype._parseFontFamily=function(e){return e.split(i).map((e=>(((e=e.trim()).indexOf(" ")>-1||s.test(e))&&!n.test(e)&&(e=`"${e}"`),e))).join(", ")},ds.prototype._applyFontString=function(){let{textFont:e,textSize:r,lineHeight:i,fontStyle:n,fontWeight:s,fontVariant:a}=this.states,o=this.textDrawingContext(),h=this._parseFontFamily(e.family),u=n!==t.NORMAL?`${n} `:"",l=s!==t.NORMAL?`${s} `:"",c=`${u}${a!==t.NORMAL?`${a} `:""}${l}${`${r}px`+(i!==t.NORMAL?`/${i} `:" ")}${h}`.trim();if(o.font=c,o.font!==c){if(c!==o.font)return!1}return!0},ds.prototype._applyTextProperties=function(e=!1){this._applyFontString();let t=this.textDrawingContext();t.direction=this.states.direction,t.textAlign=this.states.textAlign,t.textBaseline=this.states.textBaseline;let r=this.states.fontStretch;for(c.includes(r)&&t.fontStretch!==r&&(t.fontStretch=r);p?.length;){let[r,i]=p.shift();e&&console.log('apply context property "'+r+'" = "'+i+'"'),t[r]=i,t[r]!==i&&(console.warn(`Unable to set '${r}' property on context2d. It may not be supported.`),console.log('Expected "'+i+'" but got: "'+t[r]+'"'))}return this._pInst}}function Pa(e,t,r){switch(t){case de:return e.baseFilterShader().modify((({p5:e})=>{e.getColor(((t,r)=>{const i=e.getTexture(r,t.texCoord),n=e.dot(i.rgb,e.vec3(.2126,.7152,.0722));return e.vec4(n,n,n,i.a)}))}),{p5:r});case me:return e.baseFilterShader().modify((({p5:e})=>{e.getColor(((t,r)=>{const i=e.getTexture(r,t.texCoord),n=e.vec3(1)-i.rgb;return e.vec4(n,i.a)}))}),{p5:r});case pe:return e.baseFilterShader().modify((({p5:e})=>{const t=e.uniformFloat("filterParameter");e.getColor(((r,i)=>{const n=e.getTexture(i,r.texCoord),s=e.dot(n.rgb,e.vec3(.2126,.7152,.0722)),a=e.floor(255*t)/255,o=e.step(a,s);return e.vec4(e.vec3(o),n.a)}))}),{p5:r});case ge:return e.baseFilterShader().modify((({p5:e})=>{const t=e.uniformFloat("filterParameter");e.getColor(((r,i)=>{const n=e.getTexture(i,r.texCoord),s=((t,r)=>(t*=r,t=e.floor(t),t/(r-1)))(n.rgb,t);return e.vec4(s,n.a)}))}),{p5:r});case ve:return e.baseFilterShader().modify((({p5:e})=>{const t=e.uniformFloat("radius"),r=e.uniformVec2("direction"),i=(t,r)=>e.pow(r-e.abs(t),2);e.getColor(((n,s)=>{const a=n.texCoord;let o=e.floor(7*t);0==e.mod(o,2)&&o++;let h=e.vec4(0),u=0,l=1;o>64&&(l=o/64,o=64);const c=(l-1)*e.mix(-.5,.5,(t=>{let r=e.fract(.1031*t.xyx);return r+=e.dot(r,r.yzx+33.33),e.fract((r.x+r.y)*r.z)})(a*n.canvasSize));for(let t=0;t{const t=t=>e.dot(t.rgb,e.vec3(.2126,.7152,.0722));e.getColor(((r,i)=>{const n=r.texCoord;let s=e.getTexture(i,n),a=t(s);for(let o=-1;o<=1;o++)for(let h=-1;h<=1;h++)if(0!=o||0!=h){const u=e.vec2(o,h)*r.texelSize,l=e.getTexture(i,n+u),c=t(l);c{const t=t=>e.dot(t.rgb,e.vec3(.2126,.7152,.0722));e.getColor(((r,i)=>{const n=r.texCoord;let s=e.getTexture(i,n),a=t(s);for(let o=-1;o<=1;o++)for(let h=-1;h<=1;h++)if(0!=o||0!=h){const u=e.vec2(o,h)*r.texelSize,l=e.getTexture(i,n+u),c=t(l);c>a&&(a=c,s=l)}return s}))}),{p5:r});case fe:return e.baseFilterShader().modify((({p5:e})=>{e.getColor(((t,r)=>{const i=e.getTexture(r,t.texCoord);return e.vec4(i.rgb,1)}))}),{p5:r});default:throw new Error(`Unknown filter: ${t}`)}}function Na(e){const t={},r={};let i="";const n=function(r,n){i+=e(`STROKE_CAP_${r}`,`${n}`,"u32"),t[qe[r]]=n},s=function(t,n){i+=e(`STROKE_JOIN_${t}`,`${n}`,"u32"),r[qe[t]]=n};return n("ROUND",0),n("PROJECT",1),n("SQUARE",2),s("ROUND",0),s("MITER",1),s("BEVEL",2),{STROKE_CAP_ENUM:t,STROKE_JOIN_ENUM:r,lineDefs:i}}void 0!==p5&&Oa(p5,p5.prototype);const{STROKE_CAP_ENUM:Ra,STROKE_JOIN_ENUM:Va}=Na((()=>""));class Ua extends ds{constructor(e,t,r,i,n){super(e,t,r,i),this.canvas=this.elt=n||document.createElement("canvas"),this.contextReady=this.setupContext(),this._isMainCanvas?(this._pInst._curElement=this,this._pInst.canvas=this.canvas):this.canvas.style.display="none",this.elt.id="defaultCanvas0",this.elt.classList.add("p5Canvas"),this.wrappedElt=new En(this.elt,this._pInst);for(const e of Object.getOwnPropertyNames(En.prototype))"constructor"!==e&&"_"!==e[0]&&Object.defineProperty(this,e,{get(){return this.wrappedElt[e]}});const s=this._adjustDimensions(t,r);if(t=s.adjustedWidth,r=s.adjustedHeight,this.width=t,this.height=r,this.elt.width=t*this._pixelDensity,this.elt.height=r*this._pixelDensity,this.elt.style.width=`${t}px`,this.elt.style.height=`${r}px`,this._updateViewport(),this._pInst._userNode)this._pInst._userNode.appendChild(this.elt);else{if(0===document.getElementsByTagName("main").length){let e=document.createElement("main");document.body.appendChild(e)}document.getElementsByTagName("main")[0].appendChild(this.elt)}this.isP3D=!0,this.geometryBuilder=void 0,this.states.uModelMatrix=new ha(4),this.states.uViewMatrix=new ha(4),this.states.uPMatrix=new ha(4),this.mainCamera=new ya(this),this.states.curCamera||(this.states.curCamera=this.mainCamera),this.states.uPMatrix.set(this.states.curCamera.projMatrix),this.states.uViewMatrix.set(this.states.curCamera.cameraMatrix),this.states.enableLighting=!1,this.states.ambientLightColors=[],this.states.specularColors=[1,1,1],this.states.directionalLightDirections=[],this.states.directionalLightDiffuseColors=[],this.states.directionalLightSpecularColors=[],this.states.pointLightPositions=[],this.states.pointLightDiffuseColors=[],this.states.pointLightSpecularColors=[],this.states.spotLightPositions=[],this.states.spotLightDirections=[],this.states.spotLightDiffuseColors=[],this.states.spotLightSpecularColors=[],this.states.spotLightAngle=[],this.states.spotLightConc=[],this.states.activeImageLight=null,this.states.curFillColor=[1,1,1,1],this.states.curAmbientColor=[1,1,1,1],this.states.curSpecularColor=[0,0,0,0],this.states.curEmissiveColor=[0,0,0,0],this.states.curStrokeColor=[0,0,0,1],this.states.curBlendMode=Z,this.states._hasSetAmbient=!1,this.states._useSpecularMaterial=!1,this.states._useEmissiveMaterial=!1,this.states._useNormalMaterial=!1,this.states._useShininess=1,this.states._useMetalness=0,this.states.tint=null,this.states.constantAttenuation=1,this.states.linearAttenuation=0,this.states.quadraticAttenuation=0,this.states._currentNormal=new Nn(0,0,1),this.states.drawMode=Ce,this.states._tex=null,this.states.textureMode=Ae,this.states.textureWrapX=Fe,this.states.textureWrapY=Fe,this._isErasing=!1,this._simpleLines=!1,this._clipDepths=[],this._textContextSavedStack=[],this._isClipApplied=!1,this._stencilTestOn=!1,this.mixedAmbientLight=[],this.mixedSpecularColor=[],this.diffusedTextures=new Map,this.specularTextures=new Map,this.preEraseBlend=void 0,this._cachedFillStyle=[1,1,1,1],this._cachedStrokeStyle=[0,0,0,1],this._isBlending=!1,this._useLineColor=!1,this._useVertexColor=!1,this.registerEnabled=new Set,this.mainCamera._computeCameraDefaultSettings(),this.mainCamera._setDefaultCamera(),this.filterCamera=new ya(this),this.filterCamera._computeCameraDefaultSettings(),this.filterCamera._setDefaultCamera(),this.prevTouches=[],this.zoomVelocity=0,this.rotateVelocity=new Nn(0,0),this.moveVelocity=new Nn(0,0),this.executeZoom=!1,this.executeRotateAndMove=!1,this._drawingFilter=!1,this._drawingImage=!1,this.specularShader=void 0,this.sphereMapping=void 0,this.diffusedShader=void 0,this._baseFilterShader=void 0,this._defaultLightShader=void 0,this._defaultImmediateModeShader=void 0,this._defaultNormalShader=void 0,this._defaultColorShader=void 0,this.states.userFillShader=void 0,this.states.userStrokeShader=void 0,this.states.userImageShader=void 0,this.states.curveDetail=1/4,this.shapeBuilder=new Aa(this),this._largeTessellationAcknowledged=!1,this.geometryBufferCache=new Da(this),this.curStrokeCap=q,this.curStrokeJoin=q,this.textures=new Map,this.framebuffers=new Set,this.activeFramebuffers=[],this.states.filterShader=void 0,this.filterLayer=void 0,this.filterLayerTemp=void 0,this.defaultFilterShaders={},this.fontInfos={},this._curShader=void 0,this.drawShapeCount=1,this.scratchMat3=new ha(3),this._validateFaces=!1,this.buffers={fill:[new _a(3,"vertices","vertexBuffer","aPosition",this,this._vToNArray),new _a(3,"vertexNormals","normalBuffer","aNormal",this,this._vToNArray),new _a(4,"vertexColors","colorBuffer","aVertexColor",this).default((e=>e.vertices.flatMap((()=>[-1,-1,-1,-1])))),new _a(3,"vertexAmbients","ambientBuffer","aAmbientColor",this),new _a(2,"uvs","uvBuffer","aTexCoord",this,(e=>e.flat()))],stroke:[new _a(4,"lineVertexColors","lineColorBuffer","aVertexColor",this).default((e=>e.lineVertices.flatMap((()=>[-1,-1,-1,-1])))),new _a(3,"lineVertices","lineVerticesBuffer","aPosition",this),new _a(3,"lineTangentsIn","lineTangentsInBuffer","aTangentIn",this),new _a(3,"lineTangentsOut","lineTangentsOutBuffer","aTangentOut",this),new _a(1,"lineSides","lineSidesBuffer","aSide",this)],text:[new _a(3,"vertices","vertexBuffer","aPosition",this,this._vToNArray),new _a(2,"uvs","uvBuffer","aTexCoord",this,(e=>e.flat()))],user:[]}}async _resetContext(e,t,r=Ua){const i=this.width,n=this.height,s=this.canvas.id,a=this._pInst instanceof Ja,o={position:this.canvas.style.position,top:this.canvas.style.top,left:this.canvas.style.left};if(a){const e=this._pInst;e.canvas.parentNode.removeChild(e.canvas),e.canvas=document.createElement("canvas");(e._pInst._userNode||document.body).appendChild(e.canvas),En.call(e,e.canvas,e._pInst),e.width=i,e.height=n}else{let e=this.canvas;e&&e.parentNode.removeChild(e),e=document.createElement("canvas"),e.id=s,this._pInst._userNode?this._pInst._userNode.appendChild(e):document.body.appendChild(e),this._pInst.canvas=e,this.canvas=e,this.canvas.style.position=o.position,this.canvas.style.top=o.top,this.canvas.style.left=o.left}const h=new r(this._pInst,i,n,!a,this._pInst.canvas);this._pInst._renderer=h,h._applyDefaults(),h.contextReady&&await h.contextReady,"function"==typeof t&&setTimeout((()=>{t.apply(window._renderer,e)}),0)}remove(){this.wrappedElt.remove(),this.wrappedElt=null,this.canvas=null,this.elt=null}beginGeometry(){if(this.geometryBuilder)throw new Error("It looks like `beginGeometry()` is being called while another p5.Geometry is already being build.");this.geometryBuilder=new fa(this),this.geometryBuilder.prevFillColor=this.states.fillColor,this.fill(new Di([-1,-1,-1,-1]))}endGeometry(){if(!this.geometryBuilder)throw new Error("Make sure you call beginGeometry() before endGeometry()!");const e=this.geometryBuilder.finish();return this.geometryBuilder.prevFillColor?this.fill(this.geometryBuilder.prevFillColor):this.noFill(),this.geometryBuilder=void 0,e}buildGeometry(e){return this.beginGeometry(),e(),this.endGeometry()}beginShape(...e){super.beginShape(...e)}curveDetail(e){if(void 0===e)return this.states.curveDetail;this.states.setValue("curveDetail",e)}drawShape(e){const t=new hs({curveDetail:this.states.curveDetail});e.accept(t),this.shapeBuilder.constructFromContours(e,t.contours),this.geometryBuilder?this.geometryBuilder.addImmediate(this.shapeBuilder.geometry,this.shapeBuilder.shapeMode,{validateFaces:this._validateFaces}):(this.states.fillColor||this.states.strokeColor)&&this._drawGeometry(this.shapeBuilder.geometry,{mode:this.shapeBuilder.shapeMode,count:this.drawShapeCount}),this.drawShapeCount=1}endShape(e,t){this.drawShapeCount=t,super.endShape(e,t)}vertexProperty(...e){this.currentShape.vertexProperty(...e)}normal(e,t,r){e instanceof Nn?this.states.setValue("_currentNormal",e):this.states.setValue("_currentNormal",new Nn(e,t,r)),this.updateShapeVertexProperties()}model(e,t=1){e.vertices.length>0&&(this.geometryBuilder?this.geometryBuilder.addRetained(e):(this.geometryInHash(e.gid)||(e._edgesToVertices(),this._getOrMakeCachedBuffers(e)),this._drawGeometry(e,{count:t})))}_getOrMakeCachedBuffers(e){return this.geometryBufferCache.ensureCached(e)}_drawGeometry(e,{mode:t=4,count:r=1}={}){for(const t in e.userVertexProperties){const r=e.userVertexProperties[t];this.buffers.user.push(new _a(r.getDataSize(),r.getSrcName(),r.getDstName(),r.getName(),this))}this.states.fillColor&&e.vertices.length>=3&&![I,M].includes(t)&&this._drawFills(e,{mode:t,count:r}),this.states.strokeColor&&e.lineVertices.length>=1&&this._drawStrokes(e,{count:r}),this.buffers.user=[]}_drawFills(e,{count:t,mode:r}={}){this._useVertexColor=e.vertexColors.length>0&&!e.vertexColors.isDefault;const i=!this._drawingFilter&&this.states.userFillShader?this.states.userFillShader:this._getFillShader();i.bindShader("fill"),this._setGlobalUniforms(i),this._setFillUniforms(i),i.bindTextures();for(const t of this.buffers.fill)t._prepareBuffer(e,i);this._prepareUserAttributes(e,i),this._disableRemainingAttributes(i),this._applyColorBlend(this.states.curFillColor,e.hasFillTransparency()),this._drawBuffers(e,{mode:r,count:t}),i.unbindShader()}_drawStrokes(e,{count:t}={}){this._useLineColor=e.vertexStrokeColors.length>0;const r=this._getStrokeShader();r.bindShader("stroke"),this._setGlobalUniforms(r),this._setStrokeUniforms(r),r.bindTextures();for(const t of this.buffers.stroke)t._prepareBuffer(e,r);this._prepareUserAttributes(e,r),this._disableRemainingAttributes(r),this._applyColorBlend(this.states.curStrokeColor,e.hasStrokeTransparency()),this._drawBuffers(e,{count:t}),r.unbindShader()}_prepareUserAttributes(e,t){for(const r of this.buffers.user){if(!this._pInst.constructor.disableFriendleErrors){const t=e.userVertexProperties[r.attr];if(t){const r=t.getSrcArray().length/t.getDataSize();r>e.vertices.length?this._pInst.constructor._friendlyError(`One of the geometries has a custom vertex property '${t.getName()}' with more values than vertices. This is probably caused by directly using the Geometry.vertexProperty() method.`,"vertexProperty()"):rthis.clear()));let s=[1/(n.width*n.pixelDensity()),1/(n.height*n.pixelDensity())];if(r===ve){const e=this.getFilterLayerTemp();this.matchSize(e,n),this.push(),this.states.setValue("strokeColor",null),this.blendMode(Z),this.shader(this.states.filterShader),this.states.filterShader.setUniform("texelSize",s),this.states.filterShader.setUniform("canvasSize",[n.width,n.height]),this.states.filterShader.setUniform("radius",Math.max(1,t)),e.draw((()=>{this.states.filterShader.setUniform("direction",[1,0]),this.states.filterShader.setUniform("tex0",n),this.clear(),this.shader(this.states.filterShader),this.noLights(),this.plane(n.width,n.height)})),i.draw((()=>{this.states.filterShader.setUniform("direction",[0,1]),this.states.filterShader.setUniform("tex0",e),this.clear(),this.shader(this.states.filterShader),this.noLights(),this.plane(n.width,n.height)})),this.pop()}else i.draw((()=>{this.states.setValue("strokeColor",null),this.blendMode(Z),this.shader(this.states.filterShader),this.states.filterShader.setUniform("tex0",n),this.states.filterShader.setUniform("texelSize",s),this.states.filterShader.setUniform("canvasSize",[n.width,n.height]),this.states.filterShader.setUniform("filterParameter",t),this.noLights(),this.plane(n.width,n.height)}));this.push(),this.states.setValue("strokeColor",null),this.clear(),this.push(),this.states.setValue("imageMode",w),this.blendMode(Z),n.filterCamera._resize(),this.setCamera(n.filterCamera),this.resetMatrix(),this._drawingFilter=!0,this.image(i,0,0,i.width,i.height,-n.width/2,-n.height/2,n.width,n.height),this._drawingFilter=!1,this.clearDepth(),this.pop(),this.pop()}pixelDensity(e){return e?this._pInst.pixelDensity(e):this._pInst.pixelDensity()}blendMode(e){e===Q||e===ee||e===J||e===Z||e===re||e===se||e===ie||e===ae||e===ne||e===K?this.states.setValue("curBlendMode",e):e!==ce&&e!==oe&&e!==he&&e!==ue&&e!==le||console.warn("BURN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, and DODGE only work for blendMode in 2D mode.")}erase(e,t){this._isErasing||(this.preEraseBlend=this.states.curBlendMode,this._isErasing=!0,this.blendMode(K),this._cachedFillStyle=this.states.curFillColor.slice(),this.states.setValue("curFillColor",[1,1,1,e/255]),this._cachedStrokeStyle=this.states.curStrokeColor.slice(),this.states.setValue("curStrokeColor",[1,1,1,t/255]))}noErase(){this._isErasing&&(this.states.setValue("curFillColor",this._cachedFillStyle.slice()),this.states.setValue("curStrokeColor",this._cachedStrokeStyle.slice()),this.states.setValue("curBlendMode",this.preEraseBlend),this.blendMode(this.preEraseBlend),this._isErasing=!1,this._applyBlendMode())}_applyBlendMode(){}drawTarget(){return this.activeFramebuffers[this.activeFramebuffers.length-1]||this}beginClip(e={}){super.beginClip(e),this.drawTarget()._isClipApplied=!0,this._applyClip(),this.push(),this.resetShader(),this.states.fillColor&&this.fill(0,0),this.states.strokeColor&&this.stroke(0,0)}endClip(){this.pop(),this._unapplyClip(),this._clipDepths.push(this._pushPopDepth),super.endClip()}_clearClip(){this._clearClipBuffer(),this._clipDepths.length>0&&this._clipDepths.pop(),this.drawTarget()._isClipApplied=!1}_getTempFramebuffer(){return this._tempFramebuffer||(this._tempFramebuffer=new mo(this,{format:Ve,useDepth:this._pInst._glAttributes.depth,depthFormat:Ue,antialias:this._pInst._glAttributes.antialias})),this._tempFramebuffer}geometryInHash(e){return this.geometryBufferCache.isCached(e)}resize(e,t){super.resize(e,t);const r={};for(const e in this.drawingContext){const t=this.drawingContext[e];"object"!=typeof t&&"function"!=typeof t&&(r[e]=t)}const i=this._adjustDimensions(e,t);e=i.adjustedWidth,t=i.adjustedHeight,this.width=e,this.height=t,this.canvas.width=e*this._pixelDensity,this.canvas.height=t*this._pixelDensity,this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this._updateViewport(),this._updateSize(),this.mainCamera._resize(),this.states.curCamera!==this.mainCamera&&this.states.curCamera._resize(),void 0!==this.pixels&&this._createPixelsArray();for(const e of this.framebuffers)this.flushDraw?.(),e._canvasSizeChanged();this.flushDraw?.();for(const e in r)try{this.drawingContext[e]=r[e]}catch(e){}}applyMatrix(e,t,r,i,n,s){this.states.setValue("uModelMatrix",this.states.uModelMatrix.clone()),16===arguments.length?ha.prototype.apply.apply(this.states.uModelMatrix,arguments):this.states.uModelMatrix.apply([e,t,0,0,r,i,0,0,0,0,1,0,n,s,0,1])}translate(e,t,r){return e instanceof Nn&&(r=e.z,t=e.y,e=e.x),this.states.setValue("uModelMatrix",this.states.uModelMatrix.clone()),this.states.uModelMatrix.translate([e,t,r]),this}scale(e,t,r){return this.states.setValue("uModelMatrix",this.states.uModelMatrix.clone()),this.states.uModelMatrix.scale(e,t,r),this}rotate(e,t){return void 0===t?this.rotateZ(e):(this.states.setValue("uModelMatrix",this.states.uModelMatrix.clone()),ha.prototype.rotate4x4.apply(this.states.uModelMatrix,arguments),this)}rotateX(e){return this.rotate(e,1,0,0),this}rotateY(e){return this.rotate(e,0,1,0),this}rotateZ(e){return this.rotate(e,0,0,1),this}push(){super.push();const e=!!this.states.textFont?.font;e&&this.textDrawingContext().save(),this._textContextSavedStack.push(e)}pop(...e){this._clipDepths.length>0&&this._pushPopDepth===this._clipDepths[this._clipDepths.length-1]&&this._clearClip(),this._textContextSavedStack.pop()&&this.textDrawingContext().restore(),super.pop(...e),this._applyStencilTestIfClipping()}resetMatrix(){return this.states.setValue("uModelMatrix",this.states.uModelMatrix.clone()),this.states.uModelMatrix.reset(),this.states.setValue("uViewMatrix",this.states.uViewMatrix.clone()),this.states.uViewMatrix.set(this.states.curCamera.cameraMatrix),this}_getStrokeShader(){const e=this.states.userStrokeShader;return e||this._getLineShader()}_getFillShader(){return this._drawingImage?this.states.userImageShader&&!this._drawingFilter?this.states.userImageShader:this._getLightShader():this.states.userFillShader?this.states.userFillShader:this.states._useNormalMaterial?this._getNormalShader():this.states.enableLighting||this.states._tex?this._getLightShader():this._getColorShader()}baseMaterialShader(){return this._getLightShader()}baseNormalShader(){return this._getNormalShader()}baseColorShader(){return this._getColorShader()}baseStrokeShader(){return this._getLineShader()}activeFramebuffer(){return this.activeFramebuffers[this.activeFramebuffers.length-1]||null}createFramebuffer(e){return new mo(this,e)}_setGlobalUniforms(e){const t=this.states.uModelMatrix,r=this.states.uViewMatrix,i=this.states.uPMatrix,n=t.copy().mult(r);if(e.setUniform("uPerspective",this.states.curCamera.useLinePerspective?1:0),e.setUniform("uViewMatrix",r.mat4),e.setUniform("uProjectionMatrix",i.mat4),e.setUniform("uModelMatrix",t.mat4),e.setUniform("uModelViewMatrix",n.mat4),e.uniforms.uModelViewProjectionMatrix){const t=n.copy();t.mult(i),e.setUniform("uModelViewProjectionMatrix",t.mat4)}e.uniforms.uNormalMatrix&&(this.scratchMat3.inverseTranspose4x4(n),e.setUniform("uNormalMatrix",this.scratchMat3.mat3)),e.uniforms.uModelNormalMatrix&&(this.scratchMat3.inverseTranspose4x4(this.states.uModelMatrix),e.setUniform("uModelNormalMatrix",this.scratchMat3.mat3)),e.uniforms.uCameraNormalMatrix&&(this.scratchMat3.inverseTranspose4x4(this.states.uViewMatrix),e.setUniform("uCameraNormalMatrix",this.scratchMat3.mat3)),e.setUniform("uViewport",this._viewport)}_setStrokeUniforms(e){e.setUniform("uSimpleLines",this._simpleLines),e.setUniform("uUseLineColor",this._useLineColor),e.setUniform("uMaterialColor",this.states.curStrokeColor),e.setUniform("uStrokeWeight",this.states.strokeWeight),e.setUniform("uStrokeCap",Ra[this.curStrokeCap]),e.setUniform("uStrokeJoin",Va[this.curStrokeJoin])}_setFillUniforms(e){this.mixedSpecularColor=[...this.states.curSpecularColor];const t=this._getEmptyTexture();this.states._useMetalness>0&&(this.mixedSpecularColor=this.mixedSpecularColor.map(((e,t)=>this.states.curFillColor[t]*this.states._useMetalness+e*(1-this.states._useMetalness)))),e.setUniform("uUseVertexColor",this._useVertexColor),e.setUniform("uMaterialColor",this.states.curFillColor),e.setUniform("isTexture",!!this.states._tex),this._settingFillUniforms=!0,!this.states._tex&&e._userSetSampler||e.setUniform("uSampler",this.states._tex||t),this._settingFillUniforms=!1,e.setUniform("uTint",this.states.tint?._getRGBA([255,255,255,255])??[255,255,255,255]),e.setUniform("uHasSetAmbient",this.states._hasSetAmbient),e.setUniform("uAmbientMatColor",this.states.curAmbientColor),e.setUniform("uSpecularMatColor",this.mixedSpecularColor),e.setUniform("uEmissiveMatColor",this.states.curEmissiveColor),e.setUniform("uSpecular",this.states._useSpecularMaterial),e.setUniform("uEmissive",this.states._useEmissiveMaterial),e.setUniform("uShininess",this.states._useShininess),e.setUniform("uMetallic",this.states._useMetalness),this._setImageLightUniforms(e),e.setUniform("uUseLighting",this.states.enableLighting);const r=this.states.pointLightDiffuseColors.length/3;e.setUniform("uPointLightCount",r),e.setUniform("uPointLightLocation",this.states.pointLightPositions),e.setUniform("uPointLightDiffuseColors",this.states.pointLightDiffuseColors),e.setUniform("uPointLightSpecularColors",this.states.pointLightSpecularColors);const i=this.states.directionalLightDiffuseColors.length/3;e.setUniform("uDirectionalLightCount",i),e.setUniform("uLightingDirection",this.states.directionalLightDirections),e.setUniform("uDirectionalDiffuseColors",this.states.directionalLightDiffuseColors),e.setUniform("uDirectionalSpecularColors",this.states.directionalLightSpecularColors);let n=[0,0,0];for(let e=0;e0?n[t]+=Math.max(0,this.states.ambientLightColors[e+t]-this.states._useMetalness):n[t]+=this.states.ambientLightColors[e+t];e.setUniform("uAmbientColor",n);const s=this.states.spotLightDiffuseColors.length/3;e.setUniform("uSpotLightCount",s),e.setUniform("uSpotLightAngle",this.states.spotLightAngle),e.setUniform("uSpotLightConc",this.states.spotLightConc),e.setUniform("uSpotLightDiffuseColors",this.states.spotLightDiffuseColors),e.setUniform("uSpotLightSpecularColors",this.states.spotLightSpecularColors),e.setUniform("uSpotLightLocation",this.states.spotLightPositions),e.setUniform("uSpotLightDirection",this.states.spotLightDirections),e.setUniform("uConstantAttenuation",this.states.constantAttenuation),e.setUniform("uLinearAttenuation",this.states.linearAttenuation),e.setUniform("uQuadraticAttenuation",this.states.quadraticAttenuation)}_setImageLightUniforms(e){if(e.setUniform("uUseImageLight",null!=this.states.activeImageLight),this.states.activeImageLight){let t=this.getDiffusedTexture(this.states.activeImageLight);e.setUniform("environmentMapDiffused",t);let r=this.getSpecularTexture(this.states.activeImageLight);e.setUniform("environmentMapSpecular",r)}else e.setUniform("environmentMapDiffused",this._getEmptyTexture()),e.setUniform("environmentMapSpecular",this._getEmptyTexture())}_getEmptyTexture(){if(!this._emptyTexture){const e=new Bn(1,1);e.set(0,0,255),this._emptyTexture=new Qa(this,e)}return this._emptyTexture}getTexture(e){let t=e;t instanceof mo&&(t=t.color);const r=this.textures.get(t);if(r)return r;const i=new Qa(this,t);return this.textures.set(t,i),i}_normalizeBufferData(e,t=Float32Array){return e?e instanceof la?e.dataArray():e instanceof t?e:new t(e):null}_arraysEqual(e,t){return e.length===t.length&&e.every(((e,r)=>e===t[r]))}_isTypedArray(e){return[Float32Array,Float64Array,Int16Array,Uint16Array,Uint32Array].some((t=>e instanceof t))}_vToNArray(e){return e.flatMap((e=>[e.x,e.y,e.z]))}_beforeDrawText(){}_afterDrawText(){}textCanvas(){return this._textCanvas||(this._textCanvas=document.createElement("canvas"),this._textCanvas.width=1,this._textCanvas.height=1,this._textCanvas.style.display="none",this.canvas.parentElement.insertBefore(this._textCanvas,this.canvas)),this._textCanvas}textDrawingContext(){if(!this._textDrawingContext){const e=this.textCanvas();this._textDrawingContext=e.getContext("2d")}return this._textDrawingContext}_positionLines(e,t,r,i,n){let{textLeading:s,textAlign:a}=this.states;const o=n.map((e=>this._fontWidthSingle(e)));let h,u=new Array(n.length),l=void 0===r?Math.max(0,...o):r,c=void 0===i?0:i;for(let i=0;ie.y+=s)),e}_makeFilterShader(e,t){return Pa(this,t,this._pInst)}makeDiffusedTexture(e){if(null!=this.diffusedTextures.get(e))return this.diffusedTextures.get(e);let t,r=Math.floor(e.height/e.width*200);return t=new mo(this,{width:200,height:r,density:1}),this.diffusedShader||(this.diffusedShader=this._createImageLightShader("diffused")),t.draw((()=>{this.shader(this.diffusedShader),this._setImageLightShaderUniforms(this.diffusedShader,e),this.states.setValue("strokeColor",null),this.noLights(),this.plane(200,r)})),this.diffusedTextures.set(e,t),t}getDiffusedTexture(e){return this.diffusedTextures.get(e)}makeSpecularTexture(e){if(null!=this.specularTextures.get(e))return this.specularTextures.get(e);const t=512;let r,i=Math.floor(Math.log2(t))+1;this.specularShader||(this.specularShader=this._createImageLightShader("specular"));const n=this._prepareMipmapData(t,i),s=new mo(this,{width:t,height:t,density:1});let a=0;for(let r=t;r>=1;r/=2){s.resize(r,r);let t=1-Math.log(r)/Math.log(2)/i;s.draw((()=>{this.shader(this.specularShader),this.clear(),this._setImageLightShaderUniforms(this.specularShader,e,t),this.states.setValue("strokeColor",null),this.noLights(),this.plane(r,r)})),this._accumulateMipLevel(s,n,a,r,r),a++}return s.remove(),r=this._finalizeMipmapTexture(n),this.specularTextures.set(e,r),r}getSpecularTexture(e){return this.specularTextures.get(e)}_getSphereMapping(e){if(!this.sphereMapping){const e=this._pInst;this.sphereMapping=this.baseFilterShader().modify((({p5:e})=>{const t=e.uniformTexture("uEnvMap"),r=e.uniformFloat("uFovY"),i=e.uniformFloat("uAspect"),n=e.uniformVec3("uN1"),s=e.uniformVec3("uN2"),a=e.uniformVec3("uN3");e.getColor((o=>{const h=r*i,u=e.mix(r/2,-r/2,o.texCoord.y),l=e.mix(h/2,-h/2,o.texCoord.x);let c=e.normalize([l,u,1]);c=[e.dot(c,n),e.dot(c,s),e.dot(c,a)];const p=c.z;c.z=c.x,c.x=-p;const d=[e.atan(c.z,c.x)/(2*e.PI)+.5,.5+.5*-c.y];return e.getTexture(t,d)}))}),{p5:e})}this.scratchMat3.inverseTranspose4x4(this.states.uViewMatrix),this.scratchMat3.invert(this.scratchMat3),this.sphereMapping.setUniform("uFovY",this.states.curCamera.cameraFOV),this.sphereMapping.setUniform("uAspect",this.states.curCamera.aspectRatio);const t=this.scratchMat3.mat3;return this.sphereMapping.setUniform("uN1",[t[0],t[3],t[6]]),this.sphereMapping.setUniform("uN2",[t[1],t[4],t[7]]),this.sphereMapping.setUniform("uN3",[t[2],t[5],t[8]]),this.sphereMapping.setUniform("uEnvMap",e),this.sphereMapping}_createImageLightShader(e){throw new Error("_createImageLightShader must be implemented by the renderer")}_setImageLightShaderUniforms(e,t,r){e.setUniform("environmentMap",t),void 0!==r&&e.setUniform("roughness",r)}_createMipmapTexture(e){throw new Error("_createMipmapTexture must be implemented by the renderer")}_prepareMipmapData(e,t){throw new Error("_prepareMipmapData must be implemented by the renderer")}_accumulateMipLevel(e,t,r,i,n){throw new Error("_accumulateMipLevel must be implemented by the renderer")}_finalizeMipmapTexture(e){throw new Error("_finalizeMipmapTexture must be implemented by the renderer")}remove(){this._textCanvas&&this._textCanvas.parentElement.removeChild(this._textCanvas),super.remove()}}const za="Add the WebGPU add-on to your project and pass WEBGPU as the last argument to createCanvas.";function ja(e,t){e.Renderer3D=Ua,Aa.prototype.friendlyErrorsDisabled=function(){return Boolean(e.disableFriendlyErrors)},t.createStorage=function(t){if(this._renderer.createStorage)return this._renderer.createStorage(t);e._friendlyError(`createStorage() is only available with the WebGPU renderer. ${za}`,"createStorage")},t.baseComputeShader=function(){if(this._renderer.baseComputeShader)return this._renderer.baseComputeShader();e._friendlyError(`baseComputeShader() is only available with the WebGPU renderer. ${za}`,"baseComputeShader")},t.buildComputeShader=function(t,r){if(this._renderer.baseComputeShader)return this.baseComputeShader().modify(t,r,{hook:"iteration"});e._friendlyError(`buildComputeShader() is only available with the WebGPU renderer. ${za}`,"buildComputeShader")},t.compute=function(t,r,i,n){this._renderer.compute?this._renderer.compute(t,r,i,n):e._friendlyError(`compute() is only available with the WebGPU renderer. ${za}`,"compute")}}function Ga(e,t){t.strokeMode=function(e){if(void 0===e)return this._renderer._simpleLines?h:u;if(e===h)this._renderer._simpleLines=!0;else{if(e!==u)throw Error("no such parameter");this._renderer._simpleLines=!1}},t.buildGeometry=function(e){return this._renderer.buildGeometry(e)},t.freeGeometry=function(e){this._renderer.geometryBufferCache.freeBuffers(e.gid)},t.plane=function(e=50,t=e,r=1,i=1){return this._assert3d("plane"),this._renderer.plane(e,t,r,i),this},t.box=function(e,t,r,i,n){return this._assert3d("box"),this._renderer.box(e,t,r,i,n),this},t.sphere=function(e=50,t=24,r=16){return this._assert3d("sphere"),this._renderer.sphere(e,t,r),this},t.cylinder=function(e=50,t=e,r=24,i=1,n=!0,s=!0){return this._assert3d("cylinder"),this._renderer.cylinder(e,t,r,i,n,s),this},t.cone=function(e=50,t=e,r=24,i=1,n=!0){return this._assert3d("cone"),this._renderer.cone(e,t,r,i,n),this},t.ellipsoid=function(e=50,t=e,r=e,i=24,n=16){return this._assert3d("ellipsoid"),this._renderer.ellipsoid(e,t,r,i,n),this},t.torus=function(e,t,r,i){return this._assert3d("torus"),this._renderer.torus(e,t,r,i),this},Ua.prototype.point=function(e,t,r=0){return this.beginShape(M),this.vertex(e,t,r),this.endShape(),this},Ua.prototype.triangle=function(e){const t=e[0],r=e[1],i=e[2],n=e[3],s=e[4],a=e[5],o="tri";if(!this.geometryInHash(o)){const e=new pa(1,1,(function(){const e=[];e.push(new Nn(0,0,0)),e.push(new Nn(1,0,0)),e.push(new Nn(0,1,0)),this.edges=[[0,1],[1,2],[2,0]],this.vertices=e,this.faces=[[0,1,2]],this.uvs=[0,0,1,0,1,1]}),this);e._edgesToVertices(),e.computeNormals(),e.gid=o,this.geometryBufferCache.ensureCached(e)}const h=this.states.uModelMatrix.copy();try{const e=Math.sign(t*n-i*r+i*a-s*n+s*r-t*a),h=new ha([i-t,n-r,0,0,s-t,a-r,0,0,0,0,e,0,t,r,0,1]).mult(this.states.uModelMatrix);this.states.setValue("uModelMatrix",h),this.model(this.geometryBufferCache.getGeometryByID(o))}finally{this.states.setValue("uModelMatrix",h)}return this},Ua.prototype.ellipse=function(e){this.arc(e[0],e[1],e[2],e[3],0,v,z,e[4])},Ua.prototype.arc=function(...e){const t=e[0],r=e[1],i=e[2],n=e[3],s=e[4],a=e[5],o=e[6],h=e[7]||25;let u,l;if(Math.abs(a-s)>=v?(u="ellipse",l=`${u}|${h}|`):(u="arc",l=`${u}|${s}|${a}|${o}|${h}|`),!this.geometryInHash(l)){const e=function(){if(s.toFixed(10)!==a.toFixed(10)){o!==G&&void 0!==o||(this.vertices.push(new Nn(.5,.5,0)),this.uvs.push([.5,.5]));for(let e=0;e<=h;e++){const t=(a-s)*(e/h)+s,r=.5+Math.cos(t)/2,i=.5+Math.sin(t)/2;this.vertices.push(new Nn(r,i,0)),this.uvs.push([r,i]),e0&&o>0&&(this.edges=[[0,a],[a,(a+1)*(o+1)-1],[(a+1)*(o+1)-1,(a+1)*o],[(a+1)*o,0]])},t=new pa(a,o,e,this);t.computeFaces().computeNormals()._edgesToVertices(),t.gid=h,this.geometryBufferCache.ensureCached(t)}const u=this.states.uModelMatrix;this.states.setValue("uModelMatrix",this.states.uModelMatrix.copy());try{this.states.uModelMatrix.translate([t,r,0]),this.states.uModelMatrix.scale(i,n,1),this.model(this.geometryBufferCache.getGeometryByID(h))}finally{this.states.setValue("uModelMatrix",u)}}else{let s=e[4],a=void 0===e[5]?s:e[5],o=void 0===e[6]?a:e[6],h=void 0===e[7]?o:e[7],u=t,l=r,c=i,p=n;if(c+=u,p+=l,u>c){const e=u;u=c,c=e}if(l>p){const e=l;l=p,p=e}const d=Math.min((c-u)/2,(p-l)/2);s>d&&(s=d),a>d&&(a=d),o>d&&(o=d),h>d&&(h=d);let f=u,m=l,g=c,y=p;const x=this.states.textureMode;this.states.setValue("textureMode",be);const v=this.bezierOrder();this.bezierOrder(3),this.beginShape();const b=(e,t)=>[e,t,0,(e-f)/i,(t-m)/n],_=.5523;0!==a?(this.vertex(...b(g-a,m)),this.bezierVertex(...b(g-a+a*_,m)),this.bezierVertex(...b(g,m+a-a*_)),this.bezierVertex(...b(g,m+a))):this.vertex(...b(g,m)),0!==o?(this.vertex(...b(g,y-o)),this.bezierVertex(...b(g,y-o+o*_)),this.bezierVertex(...b(g-o+_*o,y)),this.bezierVertex(...b(g-o,y))):this.vertex(...b(g,y)),0!==h?(this.vertex(...b(f+h,y)),this.bezierVertex(...b(f+h-h*_,y)),this.bezierVertex(...b(f,y-h+h*_)),this.bezierVertex(...b(f,y-h))):this.vertex(...b(f,y)),0!==s?(this.vertex(...b(f,m+s)),this.bezierVertex(...b(f,m+s-s*_)),this.bezierVertex(...b(f+s-s*_,m)),this.bezierVertex(...b(f+s,m))):this.vertex(...b(f,m)),this.endShape(U),this.states.setValue("textureMode",x),this.bezierOrder(v)}return this},Ua.prototype.quad=function(e,t,r,i,n,s,a,o,h,u,l,c,p=2,d=2){const f=`quad|${e}|${t}|${r}|${i}|${n}|${s}|${a}|${o}|${h}|${u}|${l}|${c}|${p}|${d}`;if(!this.geometryInHash(f)){const m=new pa(p,d,(function(){let p=1/(this.detailX-1),d=1/(this.detailY-1);for(let f=0;fn?(o=r,a=1,s=t):s=e+(t-e)*a,-2!==p&&p!==n+2||(s=0),o-=r/2,d=0;dn&&t?new Nn(0,1,0):new Nn(h*c,l,u*c),this.vertexNormals.push(f),this.uvs.push(e,a)}}let m=0;if(s){for(f=0;f{const r=4*t;for(let t=0;t<4;t++){const r=e[t],i=new Nn((2*(1&r)-1)/2,((2&r)-1)/2,((4&r)/2-1)/2);this.vertices.push(i),this.uvs.push(1&t,(2&t)/2)}this.faces.push([r,r+1,r+2]),this.faces.push([r+2,r+1,r+3])}))},t=new pa(i,n,e,this);t.computeNormals(),i<=4&&n<=4?t._edgesToVertices():this.states.strokeColor&&console.log("Cannot draw stroke on box objects with more than 4 detailX or 4 detailY"),t.gid=a,this.geometryBufferCache.ensureCached(t)}this._drawGeometryScaled(this.geometryBufferCache.getGeometryByID(a),e,t,r)},Ua.prototype.sphere=function(e=50,t=24,r=16){this.ellipsoid(e,e,e,t,r)},Ua.prototype.ellipsoid=function(t=50,r=t,i=t,n=24,s=16){const a=`ellipsoid|${n}|${s}`;if(!this.geometryInHash(a)){const t=function(){for(let t=0;t<=this.detailY;t++){const r=t/this.detailY,i=Math.PI*r-Math.PI/2,n=Math.cos(i),s=Math.sin(i);for(let t=0;t<=this.detailX;t++){const i=t/this.detailX,a=2*Math.PI*i,o=Math.cos(a),h=Math.sin(a),u=new e.Vector(n*h,s,n*o);this.vertices.push(u),this.vertexNormals.push(u),this.uvs.push(i,r)}}},r=new pa(n,s,t,this);r.computeFaces(),n<=24&&s<=24?r._makeTriangleEdges()._edgesToVertices():this.states.strokeColor&&console.log("Cannot draw stroke on ellipsoids with more than 24 detailX or 24 detailY"),r.gid=a,this.geometryBufferCache.ensureCached(r)}this._drawGeometryScaled(this.geometryBufferCache.getGeometryByID(a),t,r,i)},Ua.prototype.cylinder=function(t=50,i=t,n=24,s=1,a=!0,o=!0){const h=`cylinder|${n}|${s}|${a}|${o}`;if(!this.geometryInHash(h)){const t=new e.Geometry(n,s,(function(){r.call(this,1,1,1,n,s,a,o)}),this);n<=24&&s<=16?t._makeTriangleEdges()._edgesToVertices():this.states.strokeColor&&console.log("Cannot draw stroke on cylinder objects with more than 24 detailX or 16 detailY"),t.gid=h,this.geometryBufferCache.ensureCached(t)}this._drawGeometryScaled(this.geometryBufferCache.getGeometryByID(h),t,i,t)},Ua.prototype.cone=function(e=50,t=e,i=24,n=1,s=!0){const a=`cone|${i}|${n}|${s}`;if(!this.geometryInHash(a)){const e=new pa(i,n,(function(){r.call(this,1,0,1,i,n,s,!1)}),this);i<=24&&n<=16?e._makeTriangleEdges()._edgesToVertices():this.states.strokeColor&&console.log("Cannot draw stroke on cone objects with more than 24 detailX or 16 detailY"),e.gid=a,this.geometryBufferCache.ensureCached(e)}this._drawGeometryScaled(this.geometryBufferCache.getGeometryByID(a),e,t,e)},Ua.prototype.torus=function(e=50,t=10,r=24,i=16){if(0===e)return;if(0===t)return;const n=(t/e).toPrecision(4),s=`torus|${n}|${r}|${i}`;if(!this.geometryInHash(s)){const e=function(){for(let e=0;e<=this.detailY;e++){const t=e/this.detailY,r=2*Math.PI*t,i=Math.cos(r),s=Math.sin(r),a=1+n*i;for(let e=0;e<=this.detailX;e++){const r=e/this.detailX,o=2*Math.PI*r,h=Math.cos(o),u=Math.sin(o),l=new Nn(a*h,a*u,n*s),c=new Nn(i*h,i*u,s);this.vertices.push(l),this.vertexNormals.push(c),this.uvs.push(r,t)}}},t=new pa(r,i,e,this);t.computeFaces(),r<=24&&i<=16?t._makeTriangleEdges()._edgesToVertices():this.states.strokeColor&&console.log("Cannot draw strokes on torus object with more than 24 detailX or 16 detailY"),t.gid=s,this.geometryBufferCache.ensureCached(t)}this._drawGeometryScaled(this.geometryBufferCache.getGeometryByID(s),e,e,e)},t.curveDetail=function(e){if(!(this._renderer instanceof Ua))throw new Error("curveDetail() only works in WebGL mode. Did you mean to call createCanvas(width, height, WEBGL)?");return this._renderer.curveDetail(e)}}function $a(e,t){t.ambientLight=function(e,t,r,i){return this._assert3d("ambientLight"),this._renderer.ambientLight(...arguments),this},t.specularColor=function(e,t,r){return this._assert3d("specularColor"),this._renderer.specularColor(...arguments),this},t.directionalLight=function(e,t,r,i,n,s){return this._assert3d("directionalLight"),this._renderer.directionalLight(...arguments),this},t.pointLight=function(e,t,r,i,n,s){return this._assert3d("pointLight"),this._renderer.pointLight(...arguments),this},t.imageLight=function(e){this._renderer.imageLight(e)},t.panorama=function(e){this.filter(this._renderer._getSphereMapping(e))},t.lights=function(){return this._assert3d("lights"),this._renderer.lights(),this},t.lightFalloff=function(e,t,r){return this._assert3d("lightFalloff"),this._renderer.lightFalloff(e,t,r),this},t.spotLight=function(e,t,r,i,n,s,a,o,h,u,l){return this._assert3d("spotLight"),this._renderer.spotLight(...arguments),this},t.noLights=function(...e){return this._assert3d("noLights"),this._renderer.noLights(),this},Ua.prototype.ambientLight=function(e,t,r,i){const n=this._pInst.color(...arguments);this.states.setValue("ambientLightColors",[...this.states.ambientLightColors]),this.states.ambientLightColors.push(n._array[0],n._array[1],n._array[2]),this.states.setValue("enableLighting",!0)},Ua.prototype.specularColor=function(e,t,r){const i=this._pInst.color(...arguments);this.states.setValue("specularColors",[i._array[0],i._array[1],i._array[2]])},Ua.prototype.directionalLight=function(e,t,r,i,n,s){let a,o,h,u;a=e instanceof Di?e:this._pInst.color(e,t,r);const l=arguments[arguments.length-1];"number"==typeof l?(o=arguments[arguments.length-3],h=arguments[arguments.length-2],u=arguments[arguments.length-1]):(o=l.x,h=l.y,u=l.z);const c=Math.sqrt(o*o+h*h+u*u);this.states.setValue("directionalLightDirections",[...this.states.directionalLightDirections]),this.states.directionalLightDirections.push(o/c,h/c,u/c),this.states.setValue("directionalLightDiffuseColors",[...this.states.directionalLightDiffuseColors]),this.states.directionalLightDiffuseColors.push(a._array[0],a._array[1],a._array[2]),this.states.setValue("directionalLightSpecularColors",[...this.states.directionalLightSpecularColors]),Array.prototype.push.apply(this.states.directionalLightSpecularColors,this.states.specularColors),this.states.setValue("enableLighting",!0)},Ua.prototype.pointLight=function(e,t,r,i,n,s){let a,o,h,u;a=e instanceof Di?e:this._pInst.color(e,t,r);const l=arguments[arguments.length-1];"number"==typeof l?(o=arguments[arguments.length-3],h=arguments[arguments.length-2],u=arguments[arguments.length-1]):(o=l.x,h=l.y,u=l.z),this.states.setValue("pointLightPositions",[...this.states.pointLightPositions]),this.states.pointLightPositions.push(o,h,u),this.states.setValue("pointLightDiffuseColors",[...this.states.pointLightDiffuseColors]),this.states.pointLightDiffuseColors.push(a._array[0],a._array[1],a._array[2]),this.states.setValue("pointLightSpecularColors",[...this.states.pointLightSpecularColors]),Array.prototype.push.apply(this.states.pointLightSpecularColors,this.states.specularColors),this.states.setValue("enableLighting",!0)},Ua.prototype.imageLight=function(e){this.states.setValue("activeImageLight",e),this.states.setValue("enableLighting",!0),this.makeDiffusedTexture(e),this.makeSpecularTexture(e)},Ua.prototype.lights=function(){const e=this._pInst.color("rgb(128,128,128)");this.ambientLight(e),this.directionalLight(e,0,0,-1)},Ua.prototype.lightFalloff=function(e,t,r){e<0&&(e=0,console.warn("Value of constant argument in lightFalloff() should be never be negative. Set to 0.")),t<0&&(t=0,console.warn("Value of linear argument in lightFalloff() should be never be negative. Set to 0.")),r<0&&(r=0,console.warn("Value of quadratic argument in lightFalloff() should be never be negative. Set to 0.")),0===e&&0===t&&0===r&&(e=1,console.warn("Either one of the three arguments in lightFalloff() should be greater than zero. Set constant argument to 1.")),this.states.setValue("constantAttenuation",e),this.states.setValue("linearAttenuation",t),this.states.setValue("quadraticAttenuation",r)},Ua.prototype.spotLight=function(e,t,r,i,n,s,a,o,h,u,l){if(this.states.spotLightDiffuseColors.length/3>=4)return;let c,p,d;const f=arguments.length;switch(f){case 11:case 10:c=this._pInst.color(e,t,r),p=new Nn(i,n,s),d=new Nn(a,o,h);break;case 9:e instanceof Di?(c=e,p=new Nn(t,r,i),d=new Nn(n,s,a),u=o,l=h):i instanceof Nn?(c=this._pInst.color(e,t,r),p=i,d=new Nn(n,s,a),u=o,l=h):a instanceof Nn?(c=this._pInst.color(e,t,r),p=new Nn(i,n,s),d=a,u=o,l=h):(c=this._pInst.color(e,t,r),p=new Nn(i,n,s),d=new Nn(a,o,h));break;case 8:e instanceof Di?(c=e,p=new Nn(t,r,i),d=new Nn(n,s,a),u=o):i instanceof Nn?(c=this._pInst.color(e,t,r),p=i,d=new Nn(n,s,a),u=o):(c=this._pInst.color(e,t,r),p=new Nn(i,n,s),d=a,u=o);break;case 7:e instanceof Di&&t instanceof Nn?(c=e,p=t,d=new Nn(r,i,n),u=s,l=a):e instanceof Di&&n instanceof Nn?(c=e,p=new Nn(t,r,i),d=n,u=s,l=a):i instanceof Nn&&n instanceof Nn?(c=this._pInst.color(e,t,r),p=i,d=n,u=s,l=a):e instanceof Di?(c=e,p=new Nn(t,r,i),d=new Nn(n,s,a)):i instanceof Nn?(c=this._pInst.color(e,t,r),p=i,d=new Nn(n,s,a)):(c=this._pInst.color(e,t,r),p=new Nn(i,n,s),d=a);break;case 6:i instanceof Nn&&n instanceof Nn?(c=this._pInst.color(e,t,r),p=i,d=n,u=s):e instanceof Di&&n instanceof Nn?(c=e,p=new Nn(t,r,i),d=n,u=s):e instanceof Di&&t instanceof Nn&&(c=e,p=t,d=new Nn(r,i,n),u=s);break;case 5:e instanceof Di&&t instanceof Nn&&r instanceof Nn?(c=e,p=t,d=r,u=i,l=n):i instanceof Nn&&n instanceof Nn?(c=this._pInst.color(e,t,r),p=i,d=n):e instanceof Di&&n instanceof Nn?(c=e,p=new Nn(t,r,i),d=n):e instanceof Di&&t instanceof Nn&&(c=e,p=t,d=new Nn(r,i,n));break;case 4:c=e,p=t,d=r,u=i;break;case 3:c=e,p=t,d=r;break;default:return void console.warn(`Sorry, input for spotlight() is not in prescribed format. Too ${f<3?"few":"many"} arguments were provided`)}this.states.setValue("spotLightDiffuseColors",[...this.states.spotLightDiffuseColors,c._array[0],c._array[1],c._array[2]]),this.states.setValue("spotLightSpecularColors",[...this.states.spotLightSpecularColors,...this.states.specularColors]),this.states.setValue("spotLightPositions",[...this.states.spotLightPositions,p.x,p.y,p.z]),d.normalize(),this.states.setValue("spotLightDirections",[...this.states.spotLightDirections,d.x,d.y,d.z]),void 0===u&&(u=Math.PI/3),void 0!==l&&l<1?(l=1,console.warn("Value of concentration needs to be greater than 1. Setting it to 1")):void 0===l&&(l=100),u=this._pInst._toRadians(u),this.states.setValue("spotLightAngle",[...this.states.spotLightAngle,Math.cos(u)]),this.states.setValue("spotLightConc",[...this.states.spotLightConc,l]),this.states.setValue("enableLighting",!0)},Ua.prototype.noLights=function(){this.states.setValue("activeImageLight",null),this.states.setValue("enableLighting",!1),this.states.setValue("ambientLightColors",[]),this.states.setValue("specularColors",[1,1,1]),this.states.setValue("directionalLightDirections",[]),this.states.setValue("directionalLightDiffuseColors",[]),this.states.setValue("directionalLightSpecularColors",[]),this.states.setValue("pointLightPositions",[]),this.states.setValue("pointLightDiffuseColors",[]),this.states.setValue("pointLightSpecularColors",[]),this.states.setValue("spotLightPositions",[]),this.states.setValue("spotLightDirections",[]),this.states.setValue("spotLightDiffuseColors",[]),this.states.setValue("spotLightSpecularColors",[]),this.states.setValue("spotLightAngle",[]),this.states.setValue("spotLightConc",[]),this.states.setValue("constantAttenuation",1),this.states.setValue("linearAttenuation",0),this.states.setValue("quadraticAttenuation",0),this.states.setValue("_useShininess",1),this.states.setValue("_useMetalness",0)}}void 0!==p5&&ja(p5,p5.prototype),void 0!==p5&&Ga(p5,p5.prototype),void 0!==p5&&$a(0,p5.prototype);const Ha=Object.getPrototypeOf(Uint8Array);class qa{constructor(e,t,r,i={}){this._renderer=e,"string"!=typeof t||void 0!==r&&("object"!=typeof r||Array.isArray(r))?(this._vertSrc=t,this._fragSrc=r,this._computeSrc=null):(this.shaderType="compute",this._computeSrc=t,this._vertSrc=null,this._fragSrc=null,"object"==typeof r&&(i=r)),this._vertShader=-1,this._fragShader=-1,this._compiled=!1,this._loadedAttributes=!1,this.attributes={},this._loadedUniforms=!1,this.uniforms={},this._bound=!1,this.samplers=[],this.hooks={uniforms:i.uniforms||{},storageUniforms:i.storageUniforms||{},declarations:i.declarations,varyingVariables:i.varyingVariables||[],instanceIDVarying:i.instanceIDVarying||null,helpers:i.helpers||{},vertex:i.vertex||{},fragment:i.fragment||{},compute:i.compute||{},hookAliases:i.hookAliases||{},modified:{vertex:i.modified&&i.modified.vertex||{},fragment:i.modified&&i.modified.fragment||{},compute:i.modified&&i.modified.compute||{}}}}hookTypes(e){return this._renderer.getShaderHookTypes(this,e)}shaderSrc(e,t){return this._renderer.populateHooks(this,e,t)}version(){const e=/#version (.+)$/m.exec(this.vertSrc());return e?e[1]:"100 es"}vertSrc(){return"compute"===this.shaderType?null:this.shaderSrc(this._vertSrc,"vertex")}fragSrc(){return"compute"===this.shaderType?null:this.shaderSrc(this._fragSrc,"fragment")}computeSrc(){return"compute"!==this.shaderType?null:this.shaderSrc(this._computeSrc,"compute")}inspectHooks(){if("compute"===this.shaderType){console.log("==== Compute shader hooks: ====");for(const e in this.hooks.compute)console.log((this.hooks.modified.compute[e]?"[MODIFIED] ":"")+e+this.hooks.compute[e])}else{console.log("==== Vertex shader hooks: ====");for(const e in this.hooks.vertex)console.log((this.hooks.modified.vertex[e]?"[MODIFIED] ":"")+e+this.hooks.vertex[e]);console.log(""),console.log("==== Fragment shader hooks: ====");for(const e in this.hooks.fragment)console.log((this.hooks.modified.fragment[e]?"[MODIFIED] ":"")+e+this.hooks.fragment[e])}console.log(""),console.log("==== Helper functions: ====");for(const e in this.hooks.helpers)console.log(e+this.hooks.helpers[e])}modify(e){const t={vertex:{},fragment:{},compute:{},helpers:{}};for(const r in e)"declarations"!==r&&"uniforms"!==r&&"storageUniforms"!==r&&"varyingVariables"!==r&&"instanceIDVarying"!==r&&("vertexDeclarations"===r?t.vertex.declarations=(t.vertex.declarations||"")+"\n"+e[r]:"fragmentDeclarations"===r?t.fragment.declarations=(t.fragment.declarations||"")+"\n"+e[r]:"computeDeclarations"===r?t.compute.declarations=(t.compute.declarations||"")+"\n"+e[r]:this.hooks.vertex[r]?t.vertex[r]=e[r]:this.hooks.fragment[r]?t.fragment[r]=e[r]:this.hooks.compute[r]?t.compute[r]=e[r]:t.helpers[r]=e[r]);const r=Object.assign({},this.hooks.modified.vertex),i=Object.assign({},this.hooks.modified.fragment),n=Object.assign({},this.hooks.modified.compute);for(const e in t.vertex||{})"declarations"!==e&&(r[e]=!0);for(const e in t.fragment||{})"declarations"!==e&&(i[e]=!0);for(const e in t.compute||{})"declarations"!==e&&(n[e]=!0);const s=[this._renderer];return"compute"===this.shaderType?s.push(this._computeSrc):s.push(this._vertSrc,this._fragSrc),s.push({declarations:(this.hooks.declarations||"")+"\n"+(e.declarations||""),uniforms:Object.assign({},this.hooks.uniforms,e.uniforms||{}),storageUniforms:Object.assign({},this.hooks.storageUniforms,e.storageUniforms||{}),varyingVariables:(e.varyingVariables||[]).concat(this.hooks.varyingVariables||[]),instanceIDVarying:e.instanceIDVarying||this.hooks.instanceIDVarying||null,fragment:Object.assign({},this.hooks.fragment,t.fragment||{}),vertex:Object.assign({},this.hooks.vertex,t.vertex||{}),compute:Object.assign({},this.hooks.compute,t.compute||{}),helpers:Object.assign({},this.hooks.helpers,t.helpers||{}),hookAliases:Object.assign({},this.hooks.hookAliases,t.hookAliases||{}),modified:{vertex:r,fragment:i,compute:n}}),new qa(...s)}init(){if(!this._initialized){try{this._renderer._initShader(this)}catch(e){throw new Error(`Whoops! Something went wrong initializing the shader:\n${e.message||e}`)}"compute"!==this.shaderType&&this._loadAttributes(),this._loadUniforms(),this._renderer._finalizeShader(this),this._initialized=!0}return this}setDefaultUniforms(){for(const e in this.hooks.uniforms){const t=this._renderer.uniformNameFromHookKey(e),r=this.hooks.uniforms[e];let i;i=r instanceof Function?r():r,null!=i&&this.setUniform(t,i)}for(const e in this.hooks.storageUniforms){const t=this.hooks.storageUniforms[e],r=t instanceof Function?t():t;null!=r&&this.setUniform(e,r)}}copyToContext(e){const t=[e._renderer];"compute"===this.shaderType?t.push(this._computeSrc):t.push(this._vertSrc,this._fragSrc),t.push(this.hooks);const r=new qa(...t);return r.ensureCompiledOnContext(e._renderer),r}ensureCompiledOnContext(e){if(this._compiled&&this._renderer!==e)throw new Error("The shader being run is attached to a different context. Do you need to copy it to this context first with .copyToContext()?");this._compiled||(this._renderer=e?._renderer?.filterRenderer?._renderer||e,this.init())}_loadAttributes(){this._loadedAttributes||(this.attributes=this._renderer._getShaderAttributes(this),this._loadedAttributes=!0)}_loadUniforms(){if(this._loadedUniforms)return;this.uniforms={},this.samplers=[];const e=this._renderer.getUniformMetadata(this);for(const t of e){const e={...t,_cachedData:void 0};e.isSampler&&this.samplers.push(e),this.uniforms[e.name]=e}this._loadedUniforms=!0}bindShader(e,t){if(this.shaderType&&this.shaderType!==e)throw new Error(`You've already used this shader as a ${this.shaderType} shader, but are now using it as a ${e}.`);this.shaderType=e,this.init(),this._bound||(this.useProgram(t),this._bound=!0)}unbindShader(){return this._bound&&(this.unbindTextures(),this._bound=!1),this}bindTextures(){const e=this._renderer._getEmptyTexture();for(const t of this.samplers){if(t.noData)continue;let r=t.texture;(void 0===r||r.isFramebufferTexture&&!r.src.framebuffer.antialias&&r.src.framebuffer===this._renderer.activeFramebuffer())&&(t.texture=r=e),this._renderer._updateTexture(t,r)}}unbindTextures(){for(const e of this.samplers)e.texture?.isFramebufferTexture&&this._renderer._unbindFramebufferTexture(e)}useProgram(e){return this._renderer._curShader!==this&&(this._renderer._useShader(this),this._renderer._curShader=this),this}setUniform(e,t){this.init();const r=this.uniforms[e];if(r){if("uSampler"!==e||this._renderer._settingFillUniforms||(this._userSetSampler=!0),t?.isVector?t=t.values.length!==t.dimensions?t.values.slice(0,t.dimensions):t.values:t?.isColor&&(t=t._getRGBA([1,1,1,1])),r.isArray){if(r._cachedData&&this._renderer._arraysEqual(r._cachedData,t))return;r._cachedData=t.slice(0)}else{if(r._cachedData&&r._cachedData===t)return;if(Array.isArray(t)||t instanceof Ha){if(r._cachedData&&this._renderer._arraysEqual(r._cachedData,t))return;r._cachedData=t.slice(0)}else{if(r._cachedData===t)return;r._cachedData=t}}this._renderer.updateUniformValue(this,r,t)}}enableAttrib(e,t,r,i,n,s){return e&&-1!==e.location&&this._renderer._enableAttrib(this,e,t,r,i,n,s),this}}function Wa(e,t){e.Shader=qa}async function Xa(e){const t=await fetch(e).then((e=>e.text()));return new Function(t)}function Ya(e,t){const r=e._runStrandsInGlobalMode;e._runStrandsInGlobalMode=!0;try{return t()}finally{e._runStrandsInGlobalMode=r}}function Za(e,t){t.loadShader=async function(e,t,r,i){const n=new qa;try{return n._vertSrc=(await Os(e,"text")).data,n._fragSrc=(await Os(t,"text")).data,r&&r(n)||n}catch(e){if(i)return i(e);throw e}},t.createShader=function(e,t,r){return new qa(this._renderer,e,t,r)},t.loadFilterShader=async function(e,t,r){try{const r=await this.loadStrings(e),i=await r.join("\n");let n;return n=/void\s+main/.exec(i)?this._internal((()=>this.createFilterShader(i,!0))):this._internal((()=>Ya(this,(()=>this.baseFilterShader().modify(new Function(i)))))),t&&(n=t(n)||n),n}catch(e){r?r(e):console.error(e)}},t.buildFilterShader=function(e,t){return this.baseFilterShader().modify(e,t)},t.createFilterShader=function(e,t=!1){let r=e.includes("#version 300 es")?"#version 300 es\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n\n in vec3 aPosition;\n in vec2 aTexCoord;\n out vec2 vTexCoord;\n\n void main() {\n // transferring texcoords for the frag shader\n vTexCoord = aTexCoord;\n\n // copy position with a fourth coordinate for projection (1.0 is normal)\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n // project to 3D space\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n }\n ":"\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n\n attribute vec3 aPosition;\n // texcoords only come from p5 to vertex shader\n // so pass texcoords on to the fragment shader in a varying variable\n attribute vec2 aTexCoord;\n varying vec2 vTexCoord;\n\n void main() {\n // transferring texcoords for the frag shader\n vTexCoord = aTexCoord;\n\n // copy position with a fourth coordinate for projection (1.0 is normal)\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n // project to 3D space\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n }\n ";const i=new qa(this._renderer,r,e);return t||(this._renderer.GL?i.ensureCompiledOnContext(this._renderer):i.ensureCompiledOnContext(this)),i},t.shader=function(e){return this._assert3d("shader"),this._renderer.shader(e),this},t.strokeShader=function(e){return this._assert3d("strokeShader"),this._renderer.strokeShader(e),this},t.imageShader=function(e){return this._assert3d("imageShader"),this._renderer.imageShader(e),this},t.buildMaterialShader=function(e,t){return this.baseMaterialShader().modify(e,t)},t.loadMaterialShader=async function(e,t,r){try{const r=await Xa(e);let i=this._internal((()=>Ya(this,(()=>this.buildMaterialShader(r)))));return t&&(i=t(i)||i),i}catch(e){console.error(e),r&&r(e)}},t.baseMaterialShader=function(){return this._assert3d("baseMaterialShader"),this._renderer.baseMaterialShader()},t.baseFilterShader=function(){return(this._renderer.filterRenderer||this._renderer).baseFilterShader()},t.buildNormalShader=function(e,t){return this.baseNormalShader().modify(e,t)},t.loadNormalShader=async function(e,t,r){try{const r=await Xa(e);let i=this._internal((()=>this.withGlobalStrands(this,(()=>this.buildNormalShader(r)))));return t&&(i=t(i)||i),i}catch(e){console.error(e),r&&r(e)}},t.baseNormalShader=function(){return this._assert3d("baseNormalShader"),this._renderer.baseNormalShader()},t.buildColorShader=function(e,t){return this.baseColorShader().modify(e,t)},t.loadColorShader=async function(e,t,r){try{const r=await Xa(e);let i=this._internal((()=>Ya(this,(()=>this.buildColorShader(r)))));return t&&(i=t(i)||i),i}catch(e){console.error(e),r&&r(e)}},t.baseColorShader=function(){return this._assert3d("baseColorShader"),this._renderer.baseColorShader()},t.buildStrokeShader=function(e,t){return this.baseStrokeShader().modify(e,t)},t.loadStrokeShader=async function(e,t,r){try{const r=await Xa(e);let i=this._internal((()=>Ya(this,(()=>this.buildStrokeShader(r)))));return t&&(i=t(i)||i),i}catch(e){console.error(e),r&&r(e)}},t.baseStrokeShader=function(){return this._assert3d("baseStrokeShader"),this._renderer.baseStrokeShader()},t.resetShader=function(){return this._renderer.resetShader(),this},t.texture=function(e){return this._assert3d("texture"),e.gifProperties&&e._animateGif(this),this._renderer.texture(e),this},t.textureMode=function(e){if(void 0===e)return this._renderer.states.textureMode;e!==Ae&&e!==be?console.warn(`You tried to set ${e} textureMode only supports IMAGE & NORMAL `):this._renderer.states.setValue("textureMode",e)},t.textureWrap=function(e,t=e){if(void 0===e)return{x:this._renderer.states.textureWrapX,y:this._renderer.states.textureWrapY};if(e.hasOwnProperty("x")&&e.hasOwnProperty("y")&&(t=(e=e.x).y),this._renderer.states.setValue("textureWrapX",e),this._renderer.states.setValue("textureWrapY",t),this._renderer.textures)for(const r of this._renderer.textures.values())r.setWrapMode(e,t);return this},t.normalMaterial=function(...e){return this._assert3d("normalMaterial"),this._renderer.normalMaterial(...e),this},t.ambientMaterial=function(e,r,i){this._assert3d("ambientMaterial");const n=t.color.apply(this,arguments);return this._renderer.states.setValue("_hasSetAmbient",!0),this._renderer.states.setValue("curAmbientColor",n._array),this._renderer.states.setValue("_useNormalMaterial",!1),this._renderer.states.setValue("enableLighting",!0),this._renderer.states.fillColor||this._renderer.states.setValue("fillColor",new Di([1,1,1])),this},t.emissiveMaterial=function(e,r,i,n){this._assert3d("emissiveMaterial");const s=t.color.apply(this,arguments);return this._renderer.states.setValue("curEmissiveColor",s._array),this._renderer.states.setValue("_useEmissiveMaterial",!0),this._renderer.states.setValue("_useNormalMaterial",!1),this._renderer.states.setValue("enableLighting",!0),this},t.specularMaterial=function(e,r,i,n){this._assert3d("specularMaterial");const s=t.color.apply(this,arguments);return this._renderer.states.setValue("curSpecularColor",s._array),this._renderer.states.setValue("_useSpecularMaterial",!0),this._renderer.states.setValue("_useNormalMaterial",!1),this._renderer.states.setValue("enableLighting",!0),this},t.shininess=function(e){return this._assert3d("shininess"),this._renderer.shininess(e),this},t.metalness=function(e){return this._assert3d("metalness"),this._renderer.metalness(e),this},Ua.prototype.shader=function(e){this.states.setValue("userFillShader",e),this.states.setValue("_useNormalMaterial",!1),e.ensureCompiledOnContext(this),e.setDefaultUniforms()},Ua.prototype.strokeShader=function(e){this.states.setValue("userStrokeShader",e),e.ensureCompiledOnContext(this),e.setDefaultUniforms()},Ua.prototype.imageShader=function(e){this.states.setValue("userImageShader",e),e.ensureCompiledOnContext(this),e.setDefaultUniforms()},Ua.prototype.resetShader=function(){this.states.setValue("userFillShader",null),this.states.setValue("userStrokeShader",null),this.states.setValue("userImageShader",null)},Ua.prototype.texture=function(e){this.states.setValue("drawMode",Ee),this.states.setValue("_useNormalMaterial",!1),this.states.setValue("_tex",e),this.states.setValue("fillColor",new Di([1,1,1]))},Ua.prototype.normalMaterial=function(...e){this.states.setValue("drawMode",Ce),this.states.setValue("_useSpecularMaterial",!1),this.states.setValue("_useEmissiveMaterial",!1),this.states.setValue("_useNormalMaterial",!0),this.states.setValue("curFillColor",[1,1,1,1]),this.states.setValue("fillColor",new Di([1,1,1])),this.states.setValue("strokeColor",null)},Ua.prototype.shininess=function(e){e<1&&(e=1),this.states.setValue("_useShininess",e)},Ua.prototype.metalness=function(e){const t=1-Math.exp(-e/100);this.states.setValue("_useMetalness",t)}}function Ka(e,t){const r=t.DEGREES="degrees",i=t.RADIANS="radians";t._angleMode=i,t.acos=function(e){return this._fromRadians(Math.acos(e))},t.asin=function(e){return this._fromRadians(Math.asin(e))},t.atan=function(e){return this._fromRadians(Math.atan(e))},t.atan2=function(e,t){return this._fromRadians(Math.atan2(e,t))},t.cos=function(e){return Math.cos(this._toRadians(e))},t.sin=function(e){return Math.sin(this._toRadians(e))},t.tan=function(e){return Math.tan(this._toRadians(e))},t.degrees=e=>e*_,t.radians=e=>e*b,t.angleMode=function(e){if(void 0===e)return this._angleMode;if(e===r||e===i){if(e===this._angleMode)return;e===i?(this.pRotationX=this.pRotationX*b,this.pRotationY=this.pRotationY*b,this.pRotationZ=this.pRotationZ*b):(this.pRotationX=this.pRotationX*_,this.pRotationY=this.pRotationY*_,this.pRotationZ=this.pRotationZ*_),this._angleMode=e}},t._toRadians=function(e){return void 0!==e&&this._angleMode===r?e*b:e},t._toDegrees=function(e){return this._angleMode===i?e*_:e},t._fromRadians=function(e){return this._angleMode===r?e*_:e},t._fromDegrees=function(e){return this._angleMode===i?e*b:e}}void 0!==p5&&Wa(p5),void 0!==p5&&loading(p5,p5.prototype),void 0!==p5&&Ka(0,p5.prototype);class Ja{constructor(e,t,r,n,s){const a=r||i;return this._pInst=n,this._renderer=new fo[a](this,e,t,!1,s),this._initializeInstanceVariables(this),this._renderer._applyDefaults(),this}get elt(){return this.canvas}get deltaTime(){return this._pInst.deltaTime}get canvas(){return this._renderer?.canvas}get drawingContext(){return this._renderer.drawingContext}get width(){return this._renderer?.width}get height(){return this._renderer?.height}get pixels(){return this._renderer?.pixels}pixelDensity(e){let t;return"number"==typeof e?(e!==this._renderer._pixelDensity&&(this._renderer._pixelDensity=e),t=this,this.resizeCanvas(this.width,this.height,!0)):t=this._renderer._pixelDensity,t}resizeCanvas(e,t){this._renderer.resize(e,t)}reset(){this._renderer.resetMatrix(),this._renderer.isP3D&&this._renderer._update()}remove(){this._renderer.remove(),this._renderer=void 0}createFramebuffer(e){return new mo(this._renderer,e)}_assert3d(e){if(!this._renderer.isP3D)throw new Error(`${e}() is only supported in WEBGL mode. If you'd like to use 3D graphics and WebGL, see https://p5js.org/examples/form-3d-primitives.html for more information.`)}_initializeInstanceVariables(){this._accessibleOutputs={text:!1,grid:!1,textLabel:!1,gridLabel:!1},this._styles=[],this._downKeys={}}}class Qa{constructor(e,t,r={}){this._renderer=e,this.src=t,this.format=r.format||"rgba8unorm",this.minFilter=r.minFilter||we,this.magFilter=r.magFilter||we,this.wrapS=r.wrapS||e.states.textureWrapX,this.wrapT=r.wrapT||e.states.textureWrapY,this.dataType=r.dataType||"uint8",this.textureHandle=null,this._detectSourceType();const i=this._getTextureDataFromSource();this.width=i.width,this.height=i.height,this.init(i)}_detectSourceType(){const e=this.src;this.isFramebufferTexture=e instanceof po,this.isSrcP5Image=e instanceof Bn,this.isSrcP5Graphics=e instanceof Ja,this.isSrcP5Renderer=e instanceof ds,this.isImageData="undefined"!=typeof ImageData&&e instanceof ImageData,this.isSrcMediaElement=void 0!==ys&&e instanceof ys,this.isSrcHTMLElement=void 0!==En&&e instanceof En&&!this.isSrcMediaElement&&!this.isSrcP5Graphics&&!this.isSrcP5Renderer}remove(){this.textureHandle&&(this._renderer.deleteTexture(this.textureHandle),this.textureHandle=null)}_getTextureDataFromSource(){let e;return this.isFramebufferTexture?e=this.src.rawTexture():this.isSrcP5Image?e=this.src.canvas:this.isSrcMediaElement||this.isSrcHTMLElement?this.isSrcMediaElement&&this.src.flipped?(this.src._ensureCanvas(),e=this.src.canvas):(this.src._checkIfTextureNeedsUpdate&&this.src._checkIfTextureNeedsUpdate(),e=this.src.elt):this.isSrcP5Graphics||this.isSrcP5Renderer?e=this.src.canvas:this.isImageData&&(e=this.src),e}init(e){this.isFramebufferTexture?this.textureHandle=this._renderer.createFramebufferTextureHandle(this.src):this.textureHandle=this._renderer.createTexture({format:this.format,dataType:this.dataType,width:e.width,height:e.height}),this._renderer.setTextureParams(this,{minFilter:this.minFilter,magFilter:this.magFilter,wrapS:this.wrapS,wrapT:this.wrapT}),this.bindTexture(),this._shouldDeferUpload()?this._renderer.uploadTextureFromData(this.textureHandle,new Uint8Array(1,1,1,1),1,1):this.isFramebufferTexture||this._renderer.uploadTextureFromSource(this.textureHandle,e),this.unbindTexture()}_shouldDeferUpload(){return 0===this.width||0===this.height||this.isSrcMediaElement&&!this.src.loadedmetadata}update(){const e=this._getTextureDataFromSource();if(!e)return!1;let t=!1;return this._shouldUpdate(e)&&(this.bindTexture(),this._renderer.uploadTextureFromSource(this.textureHandle,e),t=!0),t}_shouldUpdate(e){const t=this.src;if(0===t.width||0===t.height)return!1;if(this.isFramebufferTexture)return this.src.update(),!1;let r=!1;return e.width!==this.width||e.height!==this.height?(r=!0,this.width=e.width||t.width,this.height=e.height||t.height,this.isSrcP5Image?t.setModified(!1):(this.isSrcMediaElement||this.isSrcHTMLElement)&&t.setModified&&t.setModified(!0)):this.isSrcP5Image?(t.gifProperties&&t._animateGif(this._renderer._pInst),t.isModified()&&(r=!0,t.setModified(!1))):this.isSrcMediaElement?t.isModified()?(r=!0,t.setModified(!1)):t.loadedmetadata&&this._videoPrevUpdateTime!==t.time()&&(this._videoPrevUpdateTime=t.time(),r=!0):this.isImageData?t._dirty&&(t._dirty=!1,r=!0):r=!0,r}bindTexture(){return this._renderer.bindTexture(this),this}unbindTexture(){this._renderer.unbindTexture()}getTexture(){return this.isFramebufferTexture?this.src.rawTexture():this.textureHandle}getSampler(){return this._renderer.getSampler(this)}setInterpolation(e,t){this.minFilter=e,this.magFilter=t,this._renderer.setTextureParams(this)}setWrapMode(e,t){this.wrapS=e,this.wrapT=t,this._renderer.setTextureParams(this)}}class eo extends Qa{constructor(e,t,r={}){super(e,t,{minFilter:we,magFilter:we,...r}),this.levels=t}_getTextureDataFromSource(){return this.src}init(e){if(Array.isArray(e)){const t=e[0];this.width=t.width,this.height=t.height,this.textureHandle=this._renderer.createMipmapTextureHandle({levels:e,format:this.format,dataType:this.dataType,width:this.width,height:this.height})}else this.width=e.size,this.height=e.size,this.textureHandle=this._renderer.createMipmapTextureHandle({gpuTexture:e.gpuTexture,format:e.format,dataType:"uint8",width:this.width,height:this.height});this._renderer.setTextureParams(this,{minFilter:this.minFilter,magFilter:this.magFilter,wrapS:this.wrapS,wrapT:this.wrapT})}update(){}}function to(e,t){e.Texture=Qa,e.MipmapTexture=eo}function ro(e,t,r,i,n,s,a,o,h,u){const l=t.getParameter(t.FRAMEBUFFER_BINDING);t.bindFramebuffer(t.FRAMEBUFFER,r);const c=o===t.RGBA?4:3,p=s*a*c,d=h===t.UNSIGNED_BYTE?Uint8Array:Float32Array;if(e instanceof d&&e.length===p||(e=new d(p)),t.readPixels(i,u?u-n-a:n,s,a,o,h,e),t.bindFramebuffer(t.FRAMEBUFFER,l),u){const t=Math.floor(a/2),r=new d(s*c);for(let i=0;i!(e&e-1),o=e._getTextureDataFromSource();let h,u;o.naturalWidth&&o.naturalHeight?(h=o.naturalWidth,u=o.naturalHeight):(h=e.width,u=e.height);const l=a(h),c=a(u);let p,d;e.wrapS===Te?r===s||l&&c?p=t.REPEAT:(console.warn("You tried to set the wrap mode to REPEAT but the texture size is not a power of two. Setting to CLAMP instead"),p=t.CLAMP_TO_EDGE):e.wrapS===ke?r===s||l&&c?p=t.MIRRORED_REPEAT:(console.warn("You tried to set the wrap mode to MIRROR but the texture size is not a power of two. Setting to CLAMP instead"),p=t.CLAMP_TO_EDGE):p=t.CLAMP_TO_EDGE,e.wrapT===Te?r===s||l&&c?d=t.REPEAT:(console.warn("You tried to set the wrap mode to REPEAT but the texture size is not a power of two. Setting to CLAMP instead"),d=t.CLAMP_TO_EDGE):e.wrapT===ke?r===s||l&&c?d=t.MIRRORED_REPEAT:(console.warn("You tried to set the wrap mode to MIRROR but the texture size is not a power of two. Setting to CLAMP instead"),d=t.CLAMP_TO_EDGE):d=t.CLAMP_TO_EDGE,t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,p),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,d),e.unbindTexture()}function so(e,t,r,i,n){const s=t.location;switch(e.useProgram(),t.type){case n.BOOL:!0===r?n.uniform1i(s,1):n.uniform1i(s,0);break;case n.INT:t.size>1?r.length&&n.uniform1iv(s,r):n.uniform1i(s,r);break;case n.FLOAT:t.size>1?r.length&&n.uniform1fv(s,r):n.uniform1f(s,r);break;case n.FLOAT_MAT2:n.uniformMatrix2fv(s,!1,r);break;case n.FLOAT_MAT3:n.uniformMatrix3fv(s,!1,r);break;case n.FLOAT_MAT4:n.uniformMatrix4fv(s,!1,r);break;case n.FLOAT_VEC2:t.size>1?r.length&&n.uniform2fv(s,r):n.uniform2f(s,r[0],r[1]);break;case n.FLOAT_VEC3:t.size>1?r.length&&n.uniform3fv(s,r):n.uniform3f(s,r[0],r[1],r[2]);break;case n.FLOAT_VEC4:t.size>1?r.length&&n.uniform4fv(s,r):n.uniform4f(s,r[0],r[1],r[2],r[3]);break;case n.INT_VEC2:t.size>1?r.length&&n.uniform2iv(s,r):n.uniform2i(s,r[0],r[1]);break;case n.INT_VEC3:t.size>1?r.length&&n.uniform3iv(s,r):n.uniform3i(s,r[0],r[1],r[2]);break;case n.INT_VEC4:t.size>1?r.length&&n.uniform4iv(s,r):n.uniform4i(s,r[0],r[1],r[2],r[3]);break;case n.SAMPLER_2D:if("number"==typeof r){if(rn.TEXTURE31||r!==Math.ceil(r))return void console.log("🌸 p5.js says: You're trying to use a number as the data for a texture.Please use a texture.");n.activeTexture(r),n.uniform1i(s,r)}else n.activeTexture(n.TEXTURE0+t.samplerIndex),t.texture=r instanceof Qa?r:i(r),n.uniform1i(s,t.samplerIndex);break;case n.SAMPLER_CUBE:case n.SAMPLER_3D:case n.SAMPLER_2D_SHADOW:case n.SAMPLER_2D_ARRAY:case n.SAMPLER_2D_ARRAY_SHADOW:case n.SAMPLER_CUBE_SHADOW:case n.INT_SAMPLER_2D:case n.INT_SAMPLER_3D:case n.INT_SAMPLER_CUBE:case n.INT_SAMPLER_2D_ARRAY:case n.UNSIGNED_INT_SAMPLER_2D:case n.UNSIGNED_INT_SAMPLER_3D:case n.UNSIGNED_INT_SAMPLER_CUBE:case n.UNSIGNED_INT_SAMPLER_2D_ARRAY:if("number"!=typeof r)break;if(rn.TEXTURE31||r!==Math.ceil(r)){console.log("🌸 p5.js says: You're trying to use a number as the data for a texture.Please use a texture.");break}n.activeTexture(r),n.uniform1i(s,r)}}function ao(e,t){const r=e._glProgram,i=t.getProgramParameter(r,t.ACTIVE_UNIFORMS),n=[];let s=0;for(let e=0;e1&&(o=o.substring(0,o.indexOf("[0]"))),a.name=o,a.type=i.type,a._cachedData=void 0,a.type===t.SAMPLER_2D&&(a.isSampler=!0,a.samplerIndex=s,s++),a.isArray=i.size>1||a.type===t.FLOAT_MAT2||a.type===t.FLOAT_MAT3||a.type===t.FLOAT_MAT4||a.type===t.FLOAT_VEC2||a.type===t.FLOAT_VEC3||a.type===t.FLOAT_VEC4||a.type===t.INT_VEC2||a.type===t.INT_VEC4||a.type===t.INT_VEC3,n.push(a)}return n}function oo(e,t){const r={},i=t.getProgramParameter(e._glProgram,t.ACTIVE_ATTRIBUTES);for(let n=0;n0)for(const t of e.hooks.varyingVariables)"vertex"===r?a+=`OUT ${t};\n`:"fragment"===r&&(a+=`IN ${t};\n`);if(e.hooks.instanceIDVarying){const{declaration:t,source:i,interpolation:n}=e.hooks.instanceIDVarying,o=n?`${n} `:"";"vertex"===r?(a+=`${o}OUT ${t};\n`,s=s.replace(/\{/,`{\n ${t.split(" ").pop()} = ${i};`)):"fragment"===r&&(a+=`${o}IN ${t};\n`)}for(const t in e.hooks.helpers)a+=`${t}${e.hooks.helpers[t]}\n`;for(const t in e.hooks[r]){if("declarations"===t)continue;const[i,n]=t.split(" ");(e.hooks.modified.vertex[t]||e.hooks.modified.fragment[t])&&(o+="#define AUGMENTED_HOOK_"+n+"\n"),a+=i+" HOOK_"+n+e.hooks[r][t]+"\n"}return-1!==n.indexOf("#define HOOK_DEFINES")&&(n=n.replace("#define HOOK_DEFINES","\n"+o+"\n"),o=""),n+"\n"+o+a+i+s}function uo({GL:e,webglVersion:t}){const r=e,i=t===s?r.getExtension("EXT_color_buffer_float")&&r.getExtension("EXT_float_blend"):r.getExtension("OES_texture_float"),n=i&&r.getExtension("OES_texture_float_linear"),a=t===s?r.getExtension("EXT_color_buffer_float"):r.getExtension("OES_texture_half_float");return{float:i,floatLinear:n,halfFloat:a,halfFloatLinear:a&&r.getExtension("OES_texture_half_float_linear")}}void 0!==p5&&to(p5);const lo=(e,t,r)=>Math.max(Math.min(e,r),t);class co extends ya{constructor(e){super(e.renderer),this.fbo=e,this.yScale=e.renderer.framebufferYScale()}_computeCameraDefaultSettings(){super._computeCameraDefaultSettings(),this.defaultAspectRatio=this.fbo.width/this.fbo.height,this.defaultCameraFOV=2*Math.atan(this.fbo.height/2/this.defaultEyeZ)}copy(){const e=super.copy();return e.fbo=this.fbo,e}}class po{constructor(e,t){this.framebuffer=e,this.property=t}get width(){return this.framebuffer.width*this.framebuffer.density}get height(){return this.framebuffer.height*this.framebuffer.density}update(){this.framebuffer._update(this.property)}rawTexture(){return{texture:this.framebuffer[this.property]}}}let fo,mo=class{constructor(e,t={}){if(this.renderer=e,this.renderer.framebuffers.add(this),this._isClipApplied=!1,this._useCanvasFormat=t._useCanvasFormat||!1,this.dirty={colorTexture:!1,depthTexture:!1},this.pixels=[],this.format=t.format||Ve,this.channels=t.channels||(this.renderer.defaultFramebufferAlpha()?Ni:Ti),this.useDepth=void 0===t.depth||t.depth,this.depthFormat=t.depthFormat||ze,this.textureFiltering=t.textureFiltering||we,void 0===t.antialias?this.antialiasSamples=this.renderer.defaultFramebufferAntialias()?2:0:"number"==typeof t.antialias?this.antialiasSamples=t.antialias:this.antialiasSamples=t.antialias?2:0,this.antialias=this.antialiasSamples>0,this.antialias&&!this.renderer.supportsFramebufferAntialias()&&(console.warn("Framebuffer antialiasing is unsupported in this context"),this.antialias=!1),this.density=t.density||this.renderer._pixelDensity,t.width&&t.height){const e=this.renderer._adjustDimensions(t.width,t.height,this.density);this.width=e.adjustedWidth,this.height=e.adjustedHeight,this._autoSized=!1}else void 0===t.width!=(void 0===t.height)&&console.warn("Please supply both width and height for a framebuffer to give it a size. Only one was given, so the framebuffer will match the size of its canvas."),this.width=this.renderer.width,this.height=this.renderer.height,this._autoSized=!0;this.renderer.validateFramebufferFormats(this),t.stencil&&!this.useDepth&&console.warn("A stencil buffer can only be used if also using depth. Since the framebuffer has no depth buffer, the stencil buffer will be ignored."),this.useStencil=this.useDepth&&(void 0===t.stencil||t.stencil),this.renderer.createFramebufferResources(this),this._recreateTextures(),this.defaultCamera=this.createCamera(),this.filterCamera=this.createCamera(),this.draw((()=>this.renderer.clear()))}resize(e,t){this._autoSized=!1;const r=this.renderer._adjustDimensions(e,t,this.density);e=r.adjustedWidth,t=r.adjustedHeight,this.width=e,this.height=t,this._handleResize()}pixelDensity(e){if(!e)return this.density;this._autoSized=!1,this.density=e,this._handleResize()}autoSized(e){if(void 0===e)return this._autoSized;this._autoSized=e,this._handleResize()}_checkIfFormatsAvailable(){const e=this.gl;this.useDepth&&this.renderer.webglVersion===n&&!e.getExtension("WEBGL_depth_texture")&&(console.warn("Unable to create depth textures in this environment. Falling back to a framebuffer without depth."),this.useDepth=!1),this.useDepth&&this.renderer.webglVersion===n&&this.depthFormat===ze&&(console.warn("FLOAT depth format is unavailable in WebGL 1. Defaulting to UNSIGNED_INT."),this.depthFormat=Ue),[Ve,ze,je].includes(this.format)||(console.warn("Unknown Framebuffer format. Please use UNSIGNED_BYTE, FLOAT, or HALF_FLOAT. Defaulting to UNSIGNED_BYTE."),this.format=Ve),this.useDepth&&![Ue,ze].includes(this.depthFormat)&&(console.warn("Unknown Framebuffer depth format. Please use UNSIGNED_INT or FLOAT. Defaulting to FLOAT."),this.depthFormat=ze);const t=uo(this.renderer);t.float||this.format!==ze||(console.warn("This environment does not support FLOAT textures. Falling back to UNSIGNED_BYTE."),this.format=Ve),this.useDepth&&!t.float&&this.depthFormat===ze&&(console.warn("This environment does not support FLOAT depth textures. Falling back to UNSIGNED_INT."),this.depthFormat=Ue),t.halfFloat||this.format!==je||(console.warn("This environment does not support HALF_FLOAT textures. Falling back to UNSIGNED_BYTE."),this.format=Ve),this.channels===Ti&&[ze,je].includes(this.format)&&(console.warn("FLOAT and HALF_FLOAT formats do not work cross-platform with only RGB channels. Falling back to RGBA."),this.channels=Ni)}_deleteTextures(){this.renderer.deleteFramebufferTextures(this)}_recreateTextures(){if(this._updateSize(),this.renderer.recreateFramebufferTextures(this),this.useDepth){this.depth=new po(this,"depthTexture");const e=Se;this.depthP5Texture=new Qa(this.renderer,this.depth,{minFilter:e,magFilter:e}),this.renderer.textures.set(this.depth,this.depthP5Texture)}this.color=new po(this,"colorTexture");const e=this.textureFiltering===we?we:Se;this.colorP5Texture=new Qa(this.renderer,this.color,{minFilter:e,magFilter:e}),this.renderer.textures.set(this.color,this.colorP5Texture)}_updateSize(){this._autoSized&&(this.width=this.renderer.width,this.height=this.renderer.height,this.density=this.renderer._pixelDensity)}_canvasSizeChanged(){this._autoSized&&this._handleResize()}_handleResize(){this._deleteTextures(),this._recreateTextures(),this.defaultCamera._resize()}createCamera(){const e=new co(this);return e._computeCameraDefaultSettings(),e._setDefaultCamera(),e}remove(){this._deleteTextures(),this.renderer.deleteFramebufferResources(this),this.renderer.framebuffers.delete(this)}begin(){this.prevFramebuffer=this.renderer.activeFramebuffer(),this.prevFramebuffer&&this.prevFramebuffer._beforeEnd(),this.renderer.activeFramebuffers.push(this),this._beforeBegin(),this.renderer.push(),this.renderer.states.setValue("curCamera",this.defaultCamera),this.renderer.states.setValue("uPMatrix",this.renderer.states.uPMatrix.clone()),this.renderer.states.uPMatrix.set(this.defaultCamera.projMatrix),this.renderer.states.setValue("uViewMatrix",this.renderer.states.uViewMatrix.clone()),this.renderer.states.uViewMatrix.set(this.defaultCamera.cameraMatrix),this.renderer.resetMatrix(),this.renderer.states.uViewMatrix.set(this.renderer.states.curCamera.cameraMatrix),this.renderer.states.uModelMatrix.reset(),this.renderer._applyStencilTestIfClipping()}_framebufferToBind(){return this.renderer.getFramebufferToBind(this)}_update(e){this.dirty[e]&&(this.renderer.updateFramebufferTexture(this,e),this.dirty[e]=!1)}_beforeBegin(){this.renderer.bindFramebuffer(this),this.renderer.viewport(this.width*this.density,this.height*this.density),this.renderer.flushDraw&&this.renderer.flushDraw()}_beforeEnd(){this.antialias&&(this.dirty={colorTexture:!0,depthTexture:!0}),this.renderer.flushDraw&&this.renderer.flushDraw()}end(){this.renderer.pop();if(this.renderer.activeFramebuffers.pop()!==this)throw new Error("It looks like you've called end() while another Framebuffer is active.");this._beforeEnd(),this.prevFramebuffer?this.prevFramebuffer._beforeBegin():(this.renderer.bindFramebuffer(null),this.renderer.viewport(this.renderer._origViewport.width,this.renderer._origViewport.height)),this.renderer._applyStencilTestIfClipping()}draw(e){this.begin(),e(),this.end()}loadPixels(){this._update("colorTexture");const e=this.renderer.readFramebufferPixels(this);return e&&"function"==typeof e.then?e.then((e=>(this.pixels=e,e))):(this.pixels=e,e)}get(e,t,r,i){if(this._update("colorTexture"),void 0===e&&void 0===t)e=0,t=0,r=this.width,i=this.height;else if(void 0===r&&void 0===i)return(e<0||t<0||e>=this.width||t>=this.height)&&(console.warn("The x and y values passed to p5.Framebuffer.get are outside of its range and will be clamped."),e=lo(e,0,this.width-1),t=lo(t,0,this.height-1)),this.renderer.readFramebufferPixel(this,e*this.density,t*this.density);return e=lo(e,0,this.width-1),t=lo(t,0,this.height-1),r=lo(r,1,this.width-e),i=lo(i,1,this.height-t),this.renderer.readFramebufferRegion(this,e,t,r,i)}updatePixels(){this.renderer.updateFramebufferPixels(this)}};function go(e,t){e.FramebufferCamera=co,e.FramebufferTexture=po,e.Framebuffer=mo}function yo(e,t){e.renderers||(e.renderers={}),fo=e.renderers,t.createCanvas=function(t,r,n,...s){let o=i;return Reflect.ownKeys(fo).includes(n)?o=n:s.unshift(n),fo[o]||(o===a?e._friendlyError("To create a WEBGPU canvas, remember to add the WebGPU add-on to your project."):e._friendlyError(`We weren't able to find a renderer called ${o}.`)),this._renderer&&this._renderer.remove(),this._renderer=new fo[o](this,t,r,!0,...s),this._defaultGraphicsCreated=!0,this._elements.push(this._renderer),this._renderer._applyDefaults(),Object.hasOwn(this,"pixels")||Object.defineProperty(this,"pixels",{get(){return this._renderer?.pixels}}),this._renderer.contextReady?this._renderer.contextReady.then((()=>this._renderer)):this._renderer},t.resizeCanvas=function(e,t,r){this._renderer&&(this._renderer.resize(e,t),r||this.redraw()),this._addAccsOutput()&&this._updateAccsOutput()},t.noCanvas=function(){this.canvas&&this.canvas.parentNode.removeChild(this.canvas)},t.createGraphics=function(t,r,...n){return n[0]instanceof HTMLCanvasElement&&(n[1]=n[0],n[0]=i),new e.Graphics(t,r,n[0],this,n[1])},t.createFramebuffer=function(e){return new mo(this._renderer,e)},t.clearDepth=function(e){this._assert3d("clearDepth"),this._renderer.clearDepth(e)}}void 0!==p5&&go(p5),void 0!==p5&&yo(p5,p5.prototype);var xo="precision highp float;\n\nuniform sampler2D tex0;\nuniform vec2 canvasSize;\nuniform vec2 texelSize;\n\nIN vec2 vTexCoord;\n\nstruct FilterInputs {\n vec2 texCoord;\n vec2 canvasSize;\n vec2 texelSize;\n};\n\nvoid main(void) {\n FilterInputs inputs;\n inputs.texCoord = vTexCoord;\n inputs.canvasSize = canvasSize;\n inputs.texelSize = texelSize;\n OUT_COLOR = HOOK_getColor(inputs, tex0);\n OUT_COLOR.rgb *= outColor.a;\n}\n",vo="precision highp int;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nIN vec3 aPosition;\nIN vec2 aTexCoord;\nOUT vec2 vTexCoord;\n\nvoid main() {\n // transferring texcoords for the frag shader\n vTexCoord = aTexCoord;\n\n // copy position with a fourth coordinate for projection (1.0 is normal)\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n // project to 3D space\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n}\n",bo="#ifdef WEBGL2\n\n#define IN in\n#define OUT out\n\n#ifdef FRAGMENT_SHADER\nout vec4 outColor;\n#define OUT_COLOR outColor\n#endif\n#define TEXTURE texture\n\n#else\n\n#ifdef FRAGMENT_SHADER\n#define IN varying\n#else\n#define IN attribute\n#endif\n#define OUT varying\n#define TEXTURE texture2D\n\n#ifdef FRAGMENT_SHADER\n#define OUT_COLOR gl_FragColor\n#endif\n\n#endif\n\nvec4 getTexture(in sampler2D content, vec2 coord) {\n vec4 color = TEXTURE(content, coord);\n if (color.a > 0.) color.rgb /= color.a;\n return color;\n}\n",_o='// _p5_hash: "Hash without Sine" by Dave Hoskins (https://www.shadertoy.com/view/4djSRW)\n// Mixing constants: R₂ sequence by Martin Roberts (https://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/)\n// α₁ = 1/φ₂ = 0.7548776662 (plastic constant reciprocal)\n// α₂ = 1/φ₂² = 0.5698402910\n// 1/φ = 0.6180339887 (golden ratio conjugate)\n\nint _p5_randomCallIndex = 0;\n\nfloat _p5_hash(vec3 p) {\n p = fract(p * vec3(0.1031, 0.1030, 0.0973));\n p += dot(p, p.yxz + 33.33);\n return fract((p.x + p.y) * p.z);\n}\n\nfloat random(float seed) {\n vec2 pixelCoord = gl_FragCoord.xy;\n float callIndex = float(_p5_randomCallIndex);\n _p5_randomCallIndex += 1;\n // fract(seed * α₁) normalizes large seeds (e.g. performance.now()) into [0,1)\n // and spreads them optimally via the R₂ sequence\'s plastic constant\n float s = fract(seed * 0.7548776662);\n return _p5_hash(vec3(\n pixelCoord.x + s,\n pixelCoord.y + callIndex * 0.5698402910,\n s + callIndex * 0.6180339887\n ));\n}\n',wo='// _p5_hash: "Hash without Sine" by Dave Hoskins (https://www.shadertoy.com/view/4djSRW)\n// Mixing constants: R₂ sequence by Martin Roberts (https://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/)\n// α₁ = 1/φ₂ = 0.7548776662 (plastic constant reciprocal)\n// α₂ = 1/φ₂² = 0.5698402910\n// 1/φ = 0.6180339887 (golden ratio conjugate)\n\nint _p5_randomCallIndex = 0;\n\nfloat _p5_hash(vec3 p) {\n p = fract(p * vec3(0.1031, 0.1030, 0.0973));\n p += dot(p, p.yxz + 33.33);\n return fract((p.x + p.y) * p.z);\n}\n\nfloat random(float seed) {\n float vid = float(gl_VertexID);\n float callIndex = float(_p5_randomCallIndex);\n _p5_randomCallIndex += 1;\n float s = fract(seed * 0.7548776662);\n return _p5_hash(vec3(\n vid + s,\n vid * 0.5698402910 + callIndex * 0.6180339887,\n s + callIndex * 0.7548776662\n ));\n}\n';function Co(e){throw new Error(`[p5.strands internal error]: ${e}`)}function Eo(e,t){throw new Error(`[p5.strands ${e}]: ${t}`)}function Ao(e,t,r){Eo("dimension mismatch",`Cannot assign a value of dimension ${t} to \`${r}\`, which expects dimension ${e}.`)}function Do(){return{nextID:0,cache:new Map,nodeTypes:[],baseTypes:[],dimensions:[],opCodes:[],values:[],identifiers:[],phiBlocks:[],dependsOn:[],usedBy:[],statementTypes:[],swizzles:[]}}function So(e,t){const r=function(e,t){const r=e.nextID++;e.nodeTypes[r]=t.nodeType,e.opCodes[r]=t.opCode,e.values[r]=t.value,e.identifiers[r]=t.identifier,e.dependsOn[r]=t.dependsOn.slice(),e.usedBy[r]=t.usedBy,e.phiBlocks[r]=t.phiBlocks.slice(),e.baseTypes[r]=t.baseType,e.dimensions[r]=t.dimension,e.statementTypes[r]=t.statementType,e.swizzles[r]=t.swizzle;for(const i of t.dependsOn)Array.isArray(e.usedBy[i])||(e.usedBy[i]=[]),e.usedBy[i].push(r);return r}(e,t);return r}function To(e={}){const t={nodeType:e.nodeType??null,baseType:e.baseType??null,dimension:e.dimension??null,opCode:e.opCode??null,value:e.value??null,identifier:e.identifier??null,statementType:e.statementType??null,swizzle:e.swizzle??null,dependsOn:Array.isArray(e.dependsOn)?e.dependsOn:[],usedBy:Array.isArray(e.usedBy)?e.usedBy:[],phiBlocks:Array.isArray(e.phiBlocks)?e.phiBlocks:[]};return function(e){const t=e.nodeType,r=Gi[t];2===r.length&&Co(`Required fields for node type '${ji[t]}' not defined. Please add them to the utils.js file in p5.strands!`);const i=[];for(const t of r)null===e[t]&&i.push(t);if(e.dependsOn?.some((e=>void 0===e)))throw new Error("Undefined dependency!");i.length>0&&Co(`Missing fields ${i.join(", ")} for a node type '${ji[t]}'.`)}(t),t}function Fo(e,t){return{id:t,nodeType:e.nodeTypes[t],opCode:e.opCodes[t],value:e.values[t],identifier:e.identifiers[t],dependsOn:e.dependsOn[t],usedBy:e.usedBy[t],phiBlocks:e.phiBlocks[t],dimension:e.dimensions[t],baseType:e.baseTypes[t],statementType:e.statementTypes[t],swizzle:e.swizzles[t]}}function ko(e,t){return{baseType:e.baseTypes[t],dimension:e.dimensions[t],priority:nn[e.baseTypes[t]]}}function Mo(e,t,r,i,n=new Set){if(n.has(t))return;n.add(t);const s=Fo(e,t);if(s.baseType===en&&(e.baseTypes[t]=r,e.dimensions[t]=i,s.dependsOn&&s.dependsOn.length>0))for(const t of s.dependsOn){Fo(e,t).baseType===en&&Mo(e,t,r,i,n)}}function Io(e,t){e.blockStack.push(t),e.blockOrder.push(t),e.currentBlock=t}function Bo(e){e.blockStack.pop();const t=e.blockStack.length;e.currentBlock=e.blockStack[t-1]}function Lo(e,t){e.blockStack.push(t),e.currentBlock=t}function Oo(e,t){const r=e.nextID++;return e.blockTypes[r]=t,e.incomingEdges[r]=[],e.outgoingEdges[r]=[],e.blockInstructions[r]=[],r}function Po(e,t,r){e.outgoingEdges[t].push(r),e.incomingEdges[r].push(t)}function No(e,t,r){void 0===r&&Co("undefined nodeID in `recordInBasicBlock()`"),void 0===t&&Co("undefined blockID in `recordInBasicBlock()"),e.blockInstructions[t]=e.blockInstructions[t]||[],e.blockInstructions[t].push(r)}function Ro(e,t){const r=new Set,i=[];return function t(n){if(!r.has(n)){r.add(n);for(let r of e[n].sort(((e,t)=>t-e))||[])t(r);i.push(n)}}(t),i.reverse()}class Vo{constructor(e,t,r){this.id=e,this.strandsContext=r,this.dimension=t,this.structProperties=null,this._schema=null,this.isStrandsNode=!0;const i=Fo(this.strandsContext.dag,this.id);i&&i.identifier&&(this._originalIdentifier=i.identifier),i&&(this._originalBaseType=i.baseType,this._originalDimension=i.dimension)}withStructProperties(e){return this.structProperties=e,this}copy(){return Uo(this.id,this.dimension,this.strandsContext)}typeInfo(){return{baseType:this._originalBaseType||Yi,dimension:this.dimension}}bridge(e){const{dag:t,cfg:r}=this.strandsContext,i=Fo(t,this.id),n=i?.baseType??Yi;let s;if(e?.isStrandsNode)s=e.id;else{s=Yo(this.strandsContext,{baseType:n,dimension:this.dimension},e).id}if(this._originalIdentifier){const i=e?.isStrandsNode?e.dimension:Array.isArray(e)?e.length:1;i!==this._originalDimension&&1!==i&&Ao(this._originalDimension,i,this._originalIdentifier);const{id:n}=Go(this.strandsContext,{baseType:this._originalBaseType,dimension:this._originalDimension},this._originalIdentifier),a=So(t,To({nodeType:Vi.ASSIGNMENT,dependsOn:[n,s],phiBlocks:[]}));No(r,r.currentBlock,a);const o=So(t,To({nodeType:Vi.VARIABLE,baseType:this._originalBaseType,dimension:this._originalDimension,identifier:this._originalIdentifier}));this.id=o}else this.id=s;return this}bridgeSwizzle(e,t){const{dag:r,cfg:i}=this.strandsContext,n=Fo(r,this.id),s=n?.baseType??Yi;let a;if(t?.isStrandsNode)a=t.id;else{a=Yo(this.strandsContext,{baseType:s,dimension:this.dimension},t).id}if(this._originalIdentifier){const n=t?.isStrandsNode?t.dimension:Array.isArray(t)?t.length:1;n!==e.length&&1!==n&&Ao(e.length,n,`${this._originalIdentifier}.${e}`);const{id:s}=Go(this.strandsContext,{baseType:this._originalBaseType,dimension:this._originalDimension},this._originalIdentifier),o=So(r,To({nodeType:Vi.OPERATION,opCode:cn.SWIZZLE,baseType:this._originalBaseType,dimension:e.length,swizzle:e,dependsOn:[s]})),h=So(r,To({nodeType:Vi.ASSIGNMENT,dependsOn:[o,a],phiBlocks:[]}));No(i,i.currentBlock,h);const u=So(r,To({nodeType:Vi.VARIABLE,baseType:this._originalBaseType,dimension:this._originalDimension,identifier:this._originalIdentifier}));this.id=u}else this.id=a;return this}getValue(){if(this._originalIdentifier){const{id:e,dimension:t}=Go(this.strandsContext,{baseType:this._originalBaseType,dimension:this._originalDimension},this._originalIdentifier);return Uo(e,t,this.strandsContext)}return this}get(e){if("storage"===Fo(this.strandsContext.dag,this.id).baseType&&this._schema)return eh(this.strandsContext,this,e,this._schema);const{id:t,dimension:r}=function(e,t,r){const{dag:i,cfg:n}=e;let s;if(r instanceof Vo)s=r;else{const{id:t,dimension:i}=Yo(e,{baseType:Zi,dimension:1},r);s=Uo(t,i,e)}const a=To({nodeType:Vi.OPERATION,opCode:ln.ARRAY_ACCESS,dependsOn:[t.id,s.id],dimension:1,baseType:Yi}),o=So(i,a);return No(n,n.currentBlock,o),{id:o,dimension:1}}(this.strandsContext,this,e);return Uo(t,r,this.strandsContext)}set(e,t){if("storage"!==Fo(this.strandsContext.dag,this.id).baseType)throw new Error("set() can only be used on storage buffers");if(!this._originalIdentifier)throw new Error("set() can only be used on storage buffers with an identifier");if(null!==t&&"object"==typeof t&&!t.isStrandsNode&&this._schema){const r=eh(this.strandsContext,this,e,this._schema);for(const[e,i]of Object.entries(t))r[e]=i;return this}return function(e,t,r,i){const{dag:n,cfg:s}=e;let a,o;if(r instanceof Vo)a=r;else{const{id:t,dimension:i}=Yo(e,{baseType:Zi,dimension:1},r);a=Uo(t,i,e)}if(i instanceof Vo)o=i;else{const{id:t,dimension:r}=Yo(e,{baseType:Yi,dimension:1},i);o=Uo(t,r,e)}const h=To({nodeType:Vi.OPERATION,opCode:ln.ARRAY_ACCESS,dependsOn:[t.id,a.id],dimension:1,baseType:Yi}),u=So(n,h),l=To({nodeType:Vi.ASSIGNMENT,dependsOn:[u,o.id],phiBlocks:[]}),c=So(n,l);No(s,s.currentBlock,c)}(this.strandsContext,this,e,t),this}}function Uo(e,t,r,i){return new Proxy(new Vo(e,t,r),function(e,t,r,i){const n=[["x","y","z","w"],["r","g","b","a"],["s","t","p","q"]].map((e=>e.slice(0,t))),s={get(e,t,i){if(t in e)return Reflect.get(...arguments);for(const i of n)if([...t.toString()].every((e=>i.includes(e)))){const s=[...t].map((e=>{const t=i.indexOf(e);return n[0][t]})).join(""),a=Qo(r,e,s);return Uo(a.id,a.dimension,r)}},set(e,t,s,a){for(const a of n){const n=[...t];if(!(n.every((e=>a.includes(e)))&&new Set(n).size===n.length&&e.dimension>=n.length))continue;const o=e.dimension,h=new Array(o);for(let t=0;t 1.");const o=So(n,To({nodeType:Vi.LITERAL,dimension:s,baseType:a,value:r}));return No(i,i.currentBlock,o),{id:o,dimension:s}}function Go(e,t,r){const{cfg:i,dag:n}=e,{dimension:s,baseType:a}=t,o=So(n,To({nodeType:Vi.VARIABLE,dimension:s,baseType:a,identifier:r}));return No(i,i.currentBlock,o),{id:o,dimension:s}}function $o(e,t,r){const{dag:i,cfg:n}=e;let s,a;if(t?.isStrandsNode)a=t;else{const{id:r,dimension:i}=Yo(e,{baseType:Yi,dimension:null},t);a=Uo(r,i,e)}s=[a.id];const o={baseType:i.baseTypes[a.id],dimension:a.dimension};yn[r]&&(o.baseType=Ki,o.dimension=1);const h=So(i,To({nodeType:Vi.OPERATION,opCode:r,dependsOn:s,baseType:o.baseType,dimension:o.dimension}));return No(n,n.currentBlock,h),{id:h,dimension:a.dimension}}function Ho(e,t,r,i){const{dag:n,cfg:s}=e;let a;if(r[0]instanceof Vo&&1===r.length)a=r[0];else{const{id:t,dimension:i}=Yo(e,{baseType:Yi,dimension:null},r);a=Uo(t,i,e)}let o=t.id,h=a.id,u=ko(n,t.id),l=ko(n,a.id);u.baseType===en&&l.baseType!==en?(Mo(n,t.id,l.baseType,l.dimension),u=ko(n,t.id)):l.baseType===en&&u.baseType!==en&&(Mo(n,a.id,u.baseType,u.dimension),l=ko(n,a.id));const c={node:null,toType:u};if(u.baseType===l.baseType&&u.baseType===Qi){c.toType.baseType=Yi,u.dimension===l.dimension?c.toType.dimension=u.dimension:1===u.dimension&&l.dimension>1?c.toType.dimension=l.dimension:1===l.dimension&&u.dimension>1?c.toType.dimension=u.dimension:Eo("type error",`You have tried to perform a binary operation:\n${u.baseType+u.dimension} ${mn[i]} ${l.baseType+l.dimension}\nIt's only possible to operate on two nodes with the same dimension, or a scalar value and a vector.`);const r=Yo(e,c.toType,t),n=Yo(e,c.toType,a);o=r.id,h=n.id}else if(u.baseType!==l.baseType||u.dimension!==l.dimension){1===u.dimension&&l.dimension>1?(c.node=t,c.toType=l):1===l.dimension&&u.dimension>1||u.priority>l.priority?(c.node=a,c.toType=u):l.priority>u.priority?(c.node=t,c.toType=l):Eo("type error",`A vector of length ${u.dimension} operated with a vector of length ${l.dimension} is not allowed.`);const r=Yo(e,c.toType,c.node);c.node===t?o=(t=Uo(r.id,r.dimension,e)).id:(a=Uo(r.id,r.dimension,e),h=a.id)}yn[i]&&(c.toType.baseType=Ki,c.toType.dimension=1);const p=To({nodeType:Vi.OPERATION,opCode:i,dependsOn:[o,h],baseType:c.toType.baseType,dimension:c.toType.dimension}),d=So(n,p);return No(s,s.currentBlock,d),{id:d,dimension:p.dimension}}function qo(e,t,r,i){const{cfg:n,dag:s}=e;if(0===i.length)for(const e of t.properties){const t=e.dataType,a=So(s,To({nodeType:Vi.VARIABLE,baseType:t.baseType,dimension:t.dimension,identifier:`${r}.${e.name}`}));No(n,n.currentBlock,a),i.push(a)}const a=So(s,To({nodeType:Vi.VARIABLE,dimension:t.properties.length,baseType:t.typeName,identifier:r,dependsOn:i}));return No(n,n.currentBlock,a),{id:a,dimension:0,components:i}}function Wo(e,t,r){const i=Array.isArray(r)?r:[r],n=[];let{dimension:s,baseType:a}=t;const o=e.dag;let h=0,u=null;for(const t of i.flat(1/0))if(t&&t.isStrandsNode){const e=Fo(o,t.id);if(u=t.id,a=e.baseType,e.opCode===pn.CONSTRUCTOR)for(const t of e.dependsOn)n.push(t);else n.push(t.id);h+=e.dimension}else if("number"!=typeof t)if("boolean"!=typeof t)Eo("type error",`You've tried to construct a scalar or vector type with a non-numeric value: ${t}`);else{const{id:r,dimension:i}=jo(e,{dimension:1,baseType:Ki},t);n.push(r),h+=i,a!==Ki&&(a=Ki)}else{const{id:r,dimension:i}=jo(e,{dimension:1,baseType:a},t);n.push(r),h+=i}null===s?s=h:s>h&&1===h?h=s:1!==h&&h!==s&&Eo("type error",`You've tried to construct a ${a+s} with ${h} components`);return{originalNodeID:u,mappedDependencies:n,inferredTypeInfo:{dimension:s,baseType:a,priority:nn[a]}}}function Xo(e,t,r){const i=To({nodeType:Vi.OPERATION,opCode:pn.CONSTRUCTOR,dimension:t.dimension,baseType:t.baseType,dependsOn:r});return So(e.dag,i)}function Yo(e,t,r){const i=e.cfg;r=(Array.isArray(r)?r:[r]).flat(1/0).map((t=>t.isStrandsNode&&t.typeInfo().baseType===Zi&&1===t.typeInfo().dimension?function(e,t){const{id:r,dimension:i}=Ko(e,e.backend.getTypeName("float",t.typeInfo().dimension),[t],{overloads:[{params:[t.typeInfo()],returnType:{...t.typeInfo(),baseType:Yi}}]});return Uo(r,i,e)}(e,t):t));const{mappedDependencies:n,inferredTypeInfo:s}=Wo(e,t,r),a={baseType:s.baseType===Ki?Ki:t.baseType,dimension:s.dimension},o=Xo(e,a,n);return t.baseType!==Qi&&No(i,i.currentBlock,o),{id:o,dimension:a.dimension,components:n}}function Zo(e,t,r){const{cfg:i,dag:n}=e,{properties:s}=t;r.length!==s.length&&Eo("type error",`You've tried to construct a ${t.typeName} struct with ${r.length} properties, but it expects ${s.length} properties.\nThe properties it expects are:\n${s.map((e=>`${e.name}: ${e.dataType.baseType}${e.dataType.dimension}`)).join(", ")}`);const a=So(n,To({nodeType:Vi.OPERATION,opCode:pn.CONSTRUCTOR,dimension:s.length,baseType:t.typeName,dependsOn:r}));return No(i,i.currentBlock,a),{id:a,dimension:s.length,components:t.components}}function Ko(e,t,r,{overloads:i}={}){const{cfg:n,dag:s}=e,a=i||zo[t],o=r.map((t=>Wo(e,sn.defer,t))),h=a.filter((e=>e.params.length===o.length));if(0===h.length){const e=new Set,r=[];a.forEach((t=>e.add(t.params.length))),e.forEach((e=>r.push(`${e}`)));const i=r.join(", or ");Eo("parameter validation error",`Function '${t}' has ${a.length} variants which expect ${i} arguments, but ${o.length} arguments were provided.`)}const u=e=>null===e.dimension;let l=null,c=0,p=null,d=null;for(const e of h){let t=!0,r=0;for(let i=0;i=1||(t=!1),a=d):n.dimension>a&&(t=!1),n.baseType===s.baseType?r+=2:s.priority>n.priority&&(r+=1)}t&&(!l||r>c)&&(l=e,c=r,p={...e.returnType},u(p)&&(p.dimension=d))}null===l&&Eo("parameter validation",`No matching overload for ${t} was found!`);let f=[];for(let t=0;t{const i=To({nodeType:Vi.OPERATION,opCode:ln.ARRAY_ACCESS,dependsOn:[t.id,a.id],dimension:r.dim,baseType:Yi,identifier:r.name}),o=So(n,i),h=To({nodeType:Vi.ASSIGNMENT,dependsOn:[o,e],phiBlocks:[]}),u=So(n,h);No(s,s.currentBlock,u)}))},set(i){const o=To({nodeType:Vi.OPERATION,opCode:ln.ARRAY_ACCESS,dependsOn:[t.id,a.id],dimension:r.dim,baseType:Yi,identifier:r.name}),h=So(n,o);let u;if(i?.isStrandsNode)u=i.id;else{const{id:t}=Yo(e,{baseType:Yi,dimension:r.dim},i);u=t}const l=To({nodeType:Vi.ASSIGNMENT,dependsOn:[h,u],phiBlocks:[]}),c=So(n,l);No(s,s.currentBlock,c)},configurable:!0});return o}function th(e,t){if(e.nodeTypes[t]!==Vi.OPERATION)return!1;if(e.baseTypes[t]===tn)return!1;return(e.usedBy[t]||[]).length>1}const rh={float1:"float",float2:"vec2",float3:"vec3",float4:"vec4",int1:"int",int2:"ivec2",int3:"ivec3",int4:"ivec4",bool1:"bool",bool2:"bvec2",bool3:"bvec3",bool4:"bvec4",mat2:"mat2x2",mat3:"mat3x3",mat4:"mat4x4"},ih={[xn.DEFAULT]:(e,t,r)=>{const{dag:i,cfg:n}=t,s=n.blockInstructions[e]||[];for(const e of s){const t=i.nodeTypes[e];if(th(i,e)){const t=nh.generateDeclaration(r,i,e);r.write(t)}t===Vi.STATEMENT&&nh.generateStatement(r,i,e),t===Vi.ASSIGNMENT&&(nh.generateAssignment(r,i,e),r.visitedNodes.add(e))}},[xn.BRANCH](e,t,r){const{dag:i,cfg:n}=t,s=n.blockInstructions[e]||[];for(const e of s){const t=Fo(i,e);if(t.nodeType===Vi.PHI){const n=t.dependsOn||[];if(n.length>0){const t=n[0],i=r.tempNames[t];if(i){r.tempNames[e]=i;continue}}const s="T"+r.nextTempID++;r.tempNames[e]=s;const a=ko(i,e),o=nh.getTypeName(a.baseType,a.dimension);r.write(`${o} ${s};`)}}this[xn.DEFAULT](e,t,r)},[xn.IF_COND](e,t,r){const{dag:i,cfg:n}=t,s=n.blockConditions[e],a=nh.generateExpression(r,i,s);r.write(`if (${a})`),this[xn.DEFAULT](e,t,r)},[xn.ELSE_COND](e,t,r){r.write("else"),this[xn.DEFAULT](e,t,r)},[xn.IF_BODY](e,t,r){this[xn.DEFAULT](e,t,r),this.assignPhiNodeValues(e,t,r)},[xn.SCOPE_START](e,t,r){r.write("{"),r.indent++},[xn.SCOPE_END](e,t,r){r.indent--,r.write("}")},[xn.MERGE](e,t,r){this[xn.DEFAULT](e,t,r)},[xn.FUNCTION](e,t,r){this[xn.DEFAULT](e,t,r)},[xn.FOR](e,t,r){const{dag:i,cfg:n}=t,s=n.blockInstructions[e]||[];r.write("for (");const a=r.suppressSemicolon;for(let e=0;e`(${e.parameters.flatMap((e=>`${e.qualifiers?.length?e.qualifiers.join(" "):""}${e.type.typeName} ${zi}${e.name}`)).join(", ")}) {`,getNoiseShaderSnippet:()=>"// Based on https://github.com/stegu/webgl-noise/blob/22434e04d7753f7e949e8d724ab3da2864c17a0f/src/noise3D.glsl\n// MIT licensed, adapted for p5.strands\n\nvec3 mod289(vec3 x) {\n return x - floor(x * (1.0 / 289.0)) * 289.0;\n}\n\nvec4 mod289(vec4 x) {\n return x - floor(x * (1.0 / 289.0)) * 289.0;\n}\n\nvec4 permute(vec4 x) {\n return mod289(((x*34.0)+10.0)*x);\n}\n\nvec4 taylorInvSqrt(vec4 r)\n{\n return 1.79284291400159 - 0.85373472095314 * r;\n}\n\nfloat baseNoise(vec3 v)\n{\n const vec2 C = vec2(1.0/6.0, 1.0/3.0) ;\n const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);\n\n // First corner\n vec3 i = floor(v + dot(v, C.yyy) );\n vec3 x0 = v - i + dot(i, C.xxx) ;\n\n // Other corners\n vec3 g = step(x0.yzx, x0.xyz);\n vec3 l = 1.0 - g;\n vec3 i1 = min( g.xyz, l.zxy );\n vec3 i2 = max( g.xyz, l.zxy );\n\n // x0 = x0 - 0.0 + 0.0 * C.xxx;\n // x1 = x0 - i1 + 1.0 * C.xxx;\n // x2 = x0 - i2 + 2.0 * C.xxx;\n // x3 = x0 - 1.0 + 3.0 * C.xxx;\n vec3 x1 = x0 - i1 + C.xxx;\n vec3 x2 = x0 - i2 + C.yyy; // 2.0*C.x = 1/3 = C.y\n vec3 x3 = x0 - D.yyy; // -1.0+3.0*C.x = -0.5 = -D.y\n\n // Permutations\n i = mod289(i);\n vec4 p = permute( permute( permute(\n i.z + vec4(0.0, i1.z, i2.z, 1.0 ))\n + i.y + vec4(0.0, i1.y, i2.y, 1.0 ))\n + i.x + vec4(0.0, i1.x, i2.x, 1.0 ));\n\n // Gradients: 7x7 points over a square, mapped onto an octahedron.\n // The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)\n float n_ = 0.142857142857; // 1.0/7.0\n vec3 ns = n_ * D.wyz - D.xzx;\n\n vec4 j = p - 49.0 * floor(p * ns.z * ns.z); // mod(p,7*7)\n\n vec4 x_ = floor(j * ns.z);\n vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N)\n\n vec4 x = x_ *ns.x + ns.yyyy;\n vec4 y = y_ *ns.x + ns.yyyy;\n vec4 h = 1.0 - abs(x) - abs(y);\n\n vec4 b0 = vec4( x.xy, y.xy );\n vec4 b1 = vec4( x.zw, y.zw );\n\n //vec4 s0 = vec4(lessThan(b0,0.0))*2.0 - 1.0;\n //vec4 s1 = vec4(lessThan(b1,0.0))*2.0 - 1.0;\n vec4 s0 = floor(b0)*2.0 + 1.0;\n vec4 s1 = floor(b1)*2.0 + 1.0;\n vec4 sh = -step(h, vec4(0.0));\n\n vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ;\n vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ;\n\n vec3 p0 = vec3(a0.xy,h.x);\n vec3 p1 = vec3(a0.zw,h.y);\n vec3 p2 = vec3(a1.xy,h.z);\n vec3 p3 = vec3(a1.zw,h.w);\n\n //Normalise gradients\n vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));\n p0 *= norm.x;\n p1 *= norm.y;\n p2 *= norm.z;\n p3 *= norm.w;\n\n // Mix final noise value\n vec4 m = max(0.5 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);\n m = m * m;\n return 105.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1),\n dot(p2,x2), dot(p3,x3) ) );\n}\n\nfloat noise(vec3 st, int octaves, float ampFalloff) {\n float result = 0.0;\n float amplitude = 1.0;\n float frequency = 1.0;\n\n for (int i = 0; i < 8; i++) {\n if (i >= octaves) break;\n result += amplitude * baseNoise(st * frequency);\n frequency *= 2.0;\n amplitude *= ampFalloff;\n }\n return (result + 1.0) * 0.5;\n}\n",getRandomFragmentShaderSnippet:()=>_o,getRandomVertexShaderSnippet:()=>wo,getTypeName(e,t){const r=rh[e+t];return r||e},generateHookUniformKey(e,t){return`${this.getTypeName(t.baseType,t.dimension)} ${e}`},generateVaryingVariable:(e,t)=>`${t.fnName} ${e}`,generateLocalDeclaration:(e,t)=>`${t.fnName} ${e};`,generateStatement(e,t,r){const i=Fo(t,r),n=e.suppressSemicolon?"":";";if(i.statementType===$i)e.write(`discard${n}`);else if(i.statementType===Hi)e.write(`break${n}`);else if(i.statementType===Wi){const r=i.dependsOn[0],s=this.generateExpression(e,t,r);e.write(`${s}${n}`)}else if(i.statementType===Xi)e.write(n);else if(i.statementType===qi){const r=i.dependsOn[0],s=this.generateExpression(e,t,r);e.write(`return ${s}${n}`)}},generateAssignment(e,t,r){const i=Fo(t,r),n=i.dependsOn[0],s=i.dependsOn[1],a=this.generateExpression(e,t,n),o=this.generateExpression(e,t,s),h=e.suppressSemicolon?"":";";a&&o&&a!==o&&e.write(`${a} = ${o}${h}`)},generateDeclaration(e,t,r){const i=this.generateExpression(e,t,r),n="T"+e.nextTempID++;e.tempNames[r]=n;const s=ko(t,r);return`${this.getTypeName(s.baseType,s.dimension)} ${n} = ${i};`},generateReturnStatement(e,t,r,i){if(!i)return void t.write("return;");const n=e.dag,s=Fo(n,r);if(on(i)&&s.identifier){const e=i;for(let r=0;r0;if(i.opCode===pn.CONSTRUCTOR){if(i.baseType===tn)return this.generateExpression(e,t,i.dependsOn[0]);return`${this.getTypeName(i.baseType,i.dimension)}(${i.dependsOn.map((r=>this.generateExpression(e,t,r))).join(", ")})`}if(i.opCode===pn.FUNCTION_CALL){const r=i.dependsOn.map((r=>this.generateExpression(e,t,r)));return`${i.identifier}(${r.join(", ")})`}if(i.opCode===pn.TERNARY){const[r,n,s]=i.dependsOn;return`(${this.generateExpression(e,t,r)} ? ${this.generateExpression(e,t,n)} : ${this.generateExpression(e,t,s)})`}if(i.opCode===ln.MEMBER_ACCESS){const[r,n]=i.dependsOn;return`${this.generateExpression(e,t,r)}.${this.generateExpression(e,t,n)}`}if(i.opCode===cn.SWIZZLE){const r=i.dependsOn[0];return`${this.generateExpression(e,t,r)}.${i.swizzle}`}if(i.opCode===ln.ARRAY_ACCESS){const[r,n]=i.dependsOn;return`${this.generateExpression(e,t,r)}[${this.generateExpression(e,t,n)}]`}if(2===i.dependsOn.length){const[r,s]=i.dependsOn,a=this.generateExpression(e,t,r),o=this.generateExpression(e,t,s);if(i.opCode===ln.MODULO){const e=Fo(t,r),i=Fo(t,s);return e.baseType===Yi||i.baseType===Yi?`mod(${a}, ${o})`:`(${a} % ${o})`}const h=mn[i.opCode];return n?`(${a} ${h} ${o})`:`${a} ${h} ${o}`}if(i.opCode===cn.LOGICAL_NOT||i.opCode===cn.NEGATE||i.opCode===cn.PLUS){const[r]=i.dependsOn,n=this.generateExpression(e,t,r);return`${mn[i.opCode]}${n}`}case Vi.PHI:if(i.identifier)return i.identifier;if(e.tempNames?.[r])return e.tempNames[r];{const r=i.dependsOn.filter((e=>null!==e));if(r.length>0)return this.generateExpression(e,t,r[0]);throw new Error("No valid inputs for node")}case Vi.ASSIGNMENT:Co("ASSIGNMENT nodes should not be used as expressions");default:Co(`${ji[i.nodeType]} code generation not implemented yet`)}},generateBlock(e,t,r){const i=t.cfg.blockTypes[e];(ih[i]||ih[xn.DEFAULT]).call(ih,e,t,r)},createGetTextureCall(e,t){const{id:r,dimension:i}=Ko(e,"getTexture",t,{overloads:[{params:[sn.sampler2D,sn.float2],returnType:sn.float4}]});return{id:r,dimension:i}},instanceIdReference:()=>"gl_InstanceID",generateInstanceIDVarying:()=>({name:Ui,declaration:`int ${Ui}`,source:"gl_InstanceID",interpolation:"flat"})};function sh(e,t){let r=e._vertSrc,i=e.hooks.vertex[t];if(i||(i=e.hooks.fragment[t],r=e._fragSrc),!i)throw new Error(`Can't find hook ${t}!`);const n=t.split(/\s+/g),s=n.pop(),a=n.pop(),o=[...n],h=/\(([^\)]*)\)/.exec(i);if(!h)throw new Error(`Couldn't find function parameters in hook body:\n${i}`);const u=e=>{const t=new RegExp(`struct\\s+${e}\\s*{([^}]*)}`).exec(r);if(!t)return;const i=[];for(const e of t[1].split(";")){const t=e.trim().split(/\s+|,/g),r=t.shift(),n=[...t],s=u(r);for(const e of n){const t=un[r]||null;i.push({name:e,type:{typeName:r,qualifiers:[],properties:s,dataType:t}})}}return i},l=h[1].split(",").map((e=>{const t=e.trim().split(/\s+/g),r=t.pop(),i=t.pop();return{name:r,type:{typeName:i,qualifiers:[...t],properties:u(i),dataType:un[i]||null}}})),c=un[a]||null;return{name:s,returnType:{typeName:a,qualifiers:o,properties:u(a),dataType:c},parameters:l}}class ah{constructor(e){this.parentRenderer=e,this.canvas=document.createElement("canvas"),this.canvas.width=e.width,this.canvas.height=e.height;let t=s;this.gl=this.canvas.getContext("webgl2"),this.gl||(t=n,this.gl=this.canvas.getContext("webgl")),this.gl?(this.gl.pixelStorei(this.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),this.textures=new Map,this._renderer={GL:this.gl,registerEnabled:new Set,_curShader:null,_emptyTexture:null,webglVersion:t,states:{textureWrapX:Fe,textureWrapY:Fe},_arraysEqual:(e,t)=>JSON.stringify(e)===JSON.stringify(t),_getEmptyTexture:()=>{if(!this._emptyTexture){const e=new Bn(1,1);e.set(0,0,255),this._emptyTexture=new Qa(this._renderer,e)}return this._emptyTexture},_initShader:e=>{const t=this.gl,r=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(r,e.vertSrc()),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error(`Yikes! An error occurred compiling the vertex shader: ${t.getShaderInfoLog(r)}`);const i=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(i,e.fragSrc()),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS))throw new Error(`Darn! An error occurred compiling the fragment shader: ${t.getShaderInfoLog(i)}`);const n=t.createProgram();if(t.attachShader(n,r),t.attachShader(n,i),t.linkProgram(n),!t.getProgramParameter(n,t.LINK_STATUS))throw new Error(`Snap! Error linking shader program: ${t.getProgramInfoLog(n)}`);e._glProgram=n,e._vertShader=r,e._fragShader=i},getTexture:e=>{let t=e;t instanceof Framebuffer&&(t=t.color);const r=this.textures.get(t);if(r)return r;const i=new Qa(this._renderer,t);return this.textures.set(t,i),i},populateHooks:(e,t,r)=>ho(e,t,r),_getShaderAttributes:e=>oo(e,this.gl),getUniformMetadata:e=>ao(e,this.gl),_finalizeShader:()=>{},_useShader:e=>{this.gl.useProgram(e._glProgram)},bindTexture:e=>{this.gl.bindTexture(this.gl.TEXTURE_2D,e.getTexture().texture)},unbindTexture:()=>{this.gl.bindTexture(this.gl.TEXTURE_2D,null)},_unbindFramebufferTexture:e=>{const t=this.gl,r=this._getEmptyTexture();t.activeTexture(t.TEXTURE0+e.samplerIndex),r.bindTexture(),t.uniform1i(e.location,e.samplerIndex)},createTexture:({width:e,height:t,format:r,dataType:i})=>{const n=this.gl,s=n.createTexture();return n.bindTexture(n.TEXTURE_2D,s),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e,t,0,n.RGBA,n.UNSIGNED_BYTE,null),{texture:s,glFormat:n.RGBA,glDataType:n.UNSIGNED_BYTE}},uploadTextureFromSource:({texture:e,glFormat:t,glDataType:r},i)=>{const n=this.gl;n.bindTexture(n.TEXTURE_2D,e),n.texImage2D(n.TEXTURE_2D,0,t,t,r,i)},uploadTextureFromData:({texture:e,glFormat:t,glDataType:r},i,n,s)=>{const a=this.gl;a.bindTexture(a.TEXTURE_2D,e),a.texImage2D(a.TEXTURE_2D,0,t,n,s,0,t,r,i)},setTextureParams:e=>no(e,this.gl,this._renderer.webglVersion),updateUniformValue:(e,t,r)=>so(e,t,r,(e=>this._renderer.getTexture(e)),this.gl),_enableAttrib:(e,t,r,i,n,s,a)=>{const o=t.location,h=this.gl;this._renderer.registerEnabled.has(o)||(h.enableVertexAttribArray(o),this._renderer.registerEnabled.add(o)),h.vertexAttribPointer(o,r,i||h.FLOAT,n||!1,s||0,a||0)},_disableRemainingAttributes:e=>{for(const t of this._renderer.registerEnabled.values())Object.keys(e.attributes).some((r=>e.attributes[r].location===t))||(this.gl.disableVertexAttribArray(t),this._renderer.registerEnabled.delete(t))},_updateTexture:(e,t)=>{const r=this.gl;r.activeTexture(r.TEXTURE0+e.samplerIndex),t.bindTexture(),t.update(),r.uniform1i(e.location,e.samplerIndex)},baseFilterShader:()=>this.baseFilterShader(),strandsBackend:nh,getShaderHookTypes:(e,t)=>sh(e,t),uniformNameFromHookKey:e=>e.slice(e.indexOf(" ")+1)},this._baseFilterShader=void 0,this.filterShaders={},this.operation=null,this.filterParameter=1,this.customShader=null,this._shader=null,this.vertexBuffer=this.gl.createBuffer(),this.texcoordBuffer=this.gl.createBuffer(),this.vertices=new Float32Array([-1,-1,1,-1,-1,1,1,1]),this.texcoords=new Float32Array([0,1,1,1,0,0,1,0]),this._bindBufferData(this.vertexBuffer,this.gl.ARRAY_BUFFER,this.vertices),this._bindBufferData(this.texcoordBuffer,this.gl.ARRAY_BUFFER,this.texcoords)):console.error("WebGL not supported, cannot apply filter.")}_webGL2CompatibilityPrefix(e,t){let r="";return this._renderer.webglVersion===s&&(r+="#version 300 es\n#define WEBGL2\n"),"vert"===e?r+="#define VERTEX_SHADER\n":"frag"===e&&(r+="#define FRAGMENT_SHADER\n"),t&&(r+=`precision ${t} float;\n`),r}baseFilterShader(){return this._baseFilterShader||(this._baseFilterShader=new qa(this._renderer,this._webGL2CompatibilityPrefix("vert","highp")+bo+vo,this._webGL2CompatibilityPrefix("frag","highp")+bo+xo,{vertex:{},fragment:{"vec4 getColor":"(FilterInputs inputs, in sampler2D canvasContent) {\n return getTexture(canvasContent, inputs.texCoord);\n }"},hookAliases:{getColor:["filterColor"]}})),this._baseFilterShader}getRandomFragmentShaderSnippet(){return _o}getRandomVertexShaderSnippet(){return wo}setOperation(e,t,r=null){this.operation=e,this.filterParameter=t,e in Sa&&void 0===t&&(this.filterParameter=Sa[e]),this.customShader=r,this._initializeShader()}_initializeShader(){if(this.customShader)return void(this._shader=this.customShader);if(!this.operation)return void console.error("No operation set for FilterRenderer2D, cannot initialize shader.");if(this.filterShaders[this.operation])return void(this._shader=this.filterShaders[this.operation]);const e=Pa(this._renderer,this.operation,this.parentRenderer._pInst);this.filterShaders[this.operation]=e,this._shader=e}_bindBufferData(e,t,r){const i=this.gl;i.bindBuffer(t,e),i.bufferData(t,r,i.STATIC_DRAW)}get canvasTexture(){return this._canvasTexture||(this._canvasTexture=new Qa(this._renderer,this.parentRenderer)),this._canvasTexture}_renderPass(){const e=this.gl;this._shader.bindShader("fill");const t=this.parentRenderer.pixelDensity?this.parentRenderer.pixelDensity():1,r=[1/(this.parentRenderer.width*t),1/(this.parentRenderer.height*t)],i=this.canvasTexture;this._shader.setUniform("tex0",i),this._shader.setUniform("texelSize",r),this._shader.setUniform("canvasSize",[this.parentRenderer.width,this.parentRenderer.height]),this._shader.setUniform("radius",Math.max(1,this.filterParameter)),this._shader.setUniform("filterParameter",this.filterParameter),this._shader.setDefaultUniforms(),this.parentRenderer.states.setValue("rectMode",w),this.parentRenderer.states.setValue("imageMode",w),this.parentRenderer.blendMode(Z),this.parentRenderer.resetMatrix();const n=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];this._shader.setUniform("uModelViewMatrix",n),this._shader.setUniform("uProjectionMatrix",n),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),this._shader.enableAttrib(this._shader.attributes.aPosition,2),e.bindBuffer(e.ARRAY_BUFFER,this.texcoordBuffer),this._shader.enableAttrib(this._shader.attributes.aTexCoord,2),this._shader.bindTextures(),this._renderer._disableRemainingAttributes(this._shader),e.drawArrays(e.TRIANGLE_STRIP,0,4),this._shader.unbindShader()}applyFilter(){this._shader?(this.parentRenderer.push(),this.parentRenderer.resetMatrix(),this.operation!==ve||this.customShader?(this._renderPass(),this.parentRenderer.clear(),this.parentRenderer.blendMode(Z),this.parentRenderer.drawingContext.drawImage(this.canvas,0,0,this.parentRenderer.width,this.parentRenderer.height)):(this._shader.setUniform("direction",[1,0]),this._renderPass(),this.parentRenderer.clear(),this.parentRenderer.drawingContext.drawImage(this.canvas,0,0,this.parentRenderer.width,this.parentRenderer.height),this._shader.setUniform("direction",[0,1]),this._renderPass(),this.parentRenderer.clear(),this.parentRenderer.drawingContext.drawImage(this.canvas,0,0,this.parentRenderer.width,this.parentRenderer.height)),this.parentRenderer.pop()):console.error("Cannot apply filter: shader not initialized.")}}class oh extends ds{constructor(e,t,r,i,n,s={}){super(e,t,r,i),this.canvas=this.elt=n||document.createElement("canvas"),i?(this._pInst._curElement=this,this._pInst.canvas=this.canvas):this.canvas.style.display="none",this.elt.id||(this.elt.id="defaultCanvas"+hh.sketchCount++),this.elt.classList.add("p5Canvas");for(const e of Object.getOwnPropertyNames(En.prototype))"constructor"!==e&&"_"!==e[0]&&Object.defineProperty(this,e,{get(){return this.wrappedElt[e]}});if(this.elt.width=t*this._pixelDensity,this.elt.height=r*this._pixelDensity,this.elt.style.width=`${t}px`,this.elt.style.height=`${r}px`,this._pInst._userNode)this._pInst._userNode.appendChild(this.elt);else{if(0===document.getElementsByTagName("main").length){let e=document.createElement("main");document.body.appendChild(e)}document.getElementsByTagName("main")[0].appendChild(this.elt)}this.drawingContext=this.canvas.getContext("2d",s),"display-p3"===s.colorSpace&&(this.states.colorMode=Fi),this.scale(this._pixelDensity,this._pixelDensity),this.wrappedElt=new En(this.elt,this._pInst),this.clipPath=null}get filterRenderer(){return this._filterRenderer||(this._filterRenderer=new ah(this)),this._filterRenderer}remove(){this.wrappedElt.remove(),this.wrappedElt=null,this.canvas=null,this.elt=null}getFilterGraphicsLayer(){if(!this.filterGraphicsLayer){const e=this._pInst;this.filterGraphicsLayer=new Ja(this.width,this.height,n,e)}return this.filterGraphicsLayer.width===this.width&&this.filterGraphicsLayer.height===this.height||this.filterGraphicsLayer.resizeCanvas(this.width,this.height),this.filterGraphicsLayer.pixelDensity()!==this._pInst.pixelDensity()&&this.filterGraphicsLayer.pixelDensity(this._pInst.pixelDensity()),this.filterGraphicsLayer}_applyDefaults(){this.states.setValue("_cachedFillStyle",void 0),this.states.setValue("_cachedStrokeStyle",void 0),this._cachedBlendMode=Z,this._setFill(Le),this._setStroke(Be),this.drawingContext.lineCap=q,this.drawingContext.font="normal 12px sans-serif"}resize(e,t){super.resize(e,t);const r={};for(const e in this.drawingContext){const t=this.drawingContext[e];"object"!=typeof t&&"function"!=typeof t&&(r[e]=t)}this.canvas.width=e*this._pixelDensity,this.canvas.height=t*this._pixelDensity,this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.drawingContext.scale(this._pixelDensity,this._pixelDensity);for(const e in r)try{this.drawingContext[e]=r[e]}catch(e){}}background(...e){if(0===e.length)return this;if(this.push(),this.resetMatrix(),e[0]instanceof Bn){const t=e[0];e[1]>=0&&(this.drawingContext.globalAlpha=e[1]/255),this._pInst.image(t,0,0,this.width,this.height)}else{const t=this._pInst.color(...e);this._pInst._addAccsOutput?.()&&this._pInst._accsBackground?.(t._getRGBA([255,255,255,255]));const r=t.toString();this._setFill(r),this._isErasing&&this.blendMode(this._cachedBlendMode),this.drawingContext.fillRect(0,0,this.width,this.height),this._isErasing&&this._pInst.erase()}return this.pop(),this}clear(){this.drawingContext.save(),this.resetMatrix(),this.drawingContext.clearRect(0,0,this.width,this.height),this.drawingContext.restore()}fill(...e){super.fill(...e);const t=this.states.fillColor;if(0===e.length)return t;this._setFill(t.toString()),this._pInst._addAccsOutput?.()&&this._pInst._accsCanvasColors?.("fill",t._getRGBA([255,255,255,255]))}stroke(...e){super.stroke(...e);const t=this.states.strokeColor;if(0===e.length)return t;this._setStroke(t.toString()),this._pInst._addAccsOutput?.()&&this._pInst._accsCanvasColors?.("stroke",t._getRGBA([255,255,255,255]))}erase(e,t){if(!this._isErasing){this.states.setValue("_cachedFillStyle",this.drawingContext.fillStyle);const r=this._pInst.color(255,e).toString();this.drawingContext.fillStyle=r,this.states.setValue("_cachedStrokeStyle",this.drawingContext.strokeStyle);const i=this._pInst.color(255,t).toString();this.drawingContext.strokeStyle=i;const n=this._cachedBlendMode;this.blendMode(K),this._cachedBlendMode=n,this._isErasing=!0}}noErase(){this._isErasing&&(this.drawingContext.fillStyle=this.states._cachedFillStyle,this.drawingContext.strokeStyle=this.states._cachedStrokeStyle,this.blendMode(this._cachedBlendMode),this._isErasing=!1)}drawShape(e){const t=new os({strokeWeight:this.states.strokeWeight,hasFill:!this._clipping&&!!this.states.fillColor,hasStroke:!this._clipping&&!!this.states.strokeColor});if(e.accept(t),this._clipping){const e=this.drawingContext.getTransform(),r=this._clipBaseTransform.inverse().multiply(e);this.clipPath.addPath(t.path,r),this.clipPath.closePath()}else this.states.fillColor&&this.drawingContext.fill(t.fillPath||t.path),this.states.strokeColor&&this.drawingContext.stroke(t.strokePath||t.path)}beginClip(e={}){super.beginClip(e),this._clipBaseTransform=this.drawingContext.getTransform(),this.states.setValue("_cachedFillStyle",this.drawingContext.fillStyle);const t=this._pInst.color(255,0).toString();this.drawingContext.fillStyle=t,this.states.setValue("_cachedStrokeStyle",this.drawingContext.strokeStyle);const r=this._pInst.color(255,0).toString();this.drawingContext.strokeStyle=r;const i=this._cachedBlendMode;this.blendMode(Z),this._cachedBlendMode=i,this.clipPath=new Path2D,this._clipBaseTransform=this.drawingContext.getTransform(),this._clipInvert&&(this.clipPath.moveTo(-2*this.width,-2*this.height),this.clipPath.lineTo(-2*this.width,2*this.height),this.clipPath.lineTo(2*this.width,2*this.height),this.clipPath.lineTo(2*this.width,-2*this.height),this.clipPath.closePath())}endClip(){const e=this.drawingContext.getTransform();this.drawingContext.setTransform(this._clipBaseTransform),this.drawingContext.clip(this.clipPath),this.drawingContext.setTransform(e),this.clipPath=null,super.endClip(),this.drawingContext.fillStyle=this.states._cachedFillStyle,this.drawingContext.strokeStyle=this.states._cachedStrokeStyle,this.blendMode(this._cachedBlendMode)}image(e,t,r,i,n,s,a,o,h){let u;e.gifProperties&&e._animateGif(this._pInst);try{e instanceof ys&&e._ensureCanvas(),this.states.tint&&e.canvas&&(u=this._getTintedImageCanvas(e)),u||(u=e.canvas||e.elt);let l=1;e.width&&e.width>0&&(l=u.width/e.width),this._isErasing&&this.blendMode(this._cachedBlendMode),this.drawingContext.drawImage(u,l*t,l*r,l*i,l*n,s,a,o,h),this._isErasing&&this._pInst.erase()}catch(e){if("NS_ERROR_NOT_AVAILABLE"!==e.name)throw e}}_getTintedImageCanvas(e){if(!e.canvas)return e;e.tintCanvas||(e.tintCanvas=document.createElement("canvas")),e.tintCanvas.width!==e.canvas.width&&(e.tintCanvas.width=e.canvas.width),e.tintCanvas.height!==e.canvas.height&&(e.tintCanvas.height=e.canvas.height);const t=e.tintCanvas.getContext("2d");t.save(),t.clearRect(0,0,e.canvas.width,e.canvas.height);const r=this.states.tint._getRGBA([255,255,255,255]);return r[0]<255||r[1]<255||r[2]<255?(t.drawImage(e.canvas,0,0),t.globalCompositeOperation="luminosity",t.drawImage(e.canvas,0,0),t.globalCompositeOperation="color",t.drawImage(e.canvas,0,0),t.globalCompositeOperation="multiply",t.fillStyle=`rgb(${r.slice(0,3).join(", ")})`,t.fillRect(0,0,e.canvas.width,e.canvas.height),t.globalCompositeOperation="destination-in",t.globalAlpha=r[3]/255,t.drawImage(e.canvas,0,0)):(t.globalAlpha=r[3]/255,t.drawImage(e.canvas,0,0)),t.restore(),e.tintCanvas}blendMode(e){if(void 0===e)return this._cachedBlendMode;if(e===re)console.warn("blendMode(SUBTRACT) only works in WEBGL mode.");else{if(e!==Z&&e!==K&&e!==Q&&e!==ee&&e!==te&&e!==ne&&e!==ie&&e!==se&&e!==ae&&e!==oe&&e!==he&&e!==ue&&e!==le&&e!==ce&&e!==J)throw new Error(`Mode ${e} not recognized.`);this._cachedBlendMode=e,this.drawingContext.globalCompositeOperation=e}}blend(...e){const t=this.drawingContext.globalCompositeOperation,r=e[e.length-1],i=Array.prototype.slice.call(e,0,e.length-1);this.drawingContext.globalCompositeOperation=r,hh.prototype.copy.apply(this,i),this.drawingContext.globalCompositeOperation=t}_getPixel(e,t){let r,i;return r=this.drawingContext.getImageData(e,t,1,1).data,i=0,[r[0],r[1],r[2],r[3]]}loadPixels(){const e=this._pixelDensity,t=this.width*e,r=this.height*e,i=this.drawingContext.getImageData(0,0,t,r);this.imageData=i,this.pixels=i.data}set(e,t,r){if(e=Math.floor(e),t=Math.floor(t),r instanceof Ja||r instanceof Bn){this.drawingContext.save(),this.drawingContext.setTransform(1,0,0,1,0,0),this.drawingContext.scale(this._pixelDensity,this._pixelDensity);const i=r.width,n=r.height;this.drawingContext.clearRect(e,t,i,n),this.drawingContext.drawImage(r.canvas,e,t,i,n)}else{let i=0,n=0,s=0,a=0,o=4*(t*this._pixelDensity*(this.width*this._pixelDensity)+e*this._pixelDensity);if(this.imageData||this.loadPixels(),"number"==typeof r)o=i||(this.push(),s.strokeColor&&s.strokeSet&&a.strokeText(e,t,r),!this._clipping&&s.fillColor&&(s.fillSet||this._setFill("#000000"),a.fillText(e,t,r)),this.pop())}_positionLines(e,t,r,i,n){let s,{textLeading:a,textAlign:o}=this.states,h=new Array(n.length),u=void 0===r?0:r,l=void 0===i?0:i;for(let r=0;re.y+=n)),e}}let hh=class e{static VERSION=r;static instance=null;static sketchCount=0;static lifecycleHooks={presetup:[],postsetup:[],predraw:[],postdraw:[],remove:[]};static _checkForUserDefinedFunctions=()=>{};static _friendlyFileLoadError=()=>{};constructor(t,r){e.decorations.size>0&&(uh(e,e.decorations,"p5"),e.decorations.clear()),this.hitCriticalError=!1,this._setupDone=!1,this._userNode=r,this._curElement=null,this._elements=[],this._glAttributes=null,this._webgpuAttributes=null,this._requestAnimId=0,this._isGlobal=!1,this._loop=!0,this._startListener=null,this._initializeInstanceVariables(),this._events={},this._removeAbortController=new AbortController,this._removeSignal=this._removeAbortController.signal,this._millisStart=-1,this._recording=!1,this._lcg_random_state=null,this._gaussian_previous=!1,this._updateWindowSize();const i=function(e){return function(t){if("constructor"===t)return;const r=Object.getOwnPropertyDescriptor(e,t),i=Object.getOwnPropertyDescriptor(hh.prototype,t),n=r&&r.get||i&&i.get;let s,a=!1,o=!1;if(!n){const e=hh.prototype[t];a="function"==typeof e,a||void 0===qe[t]||(o=!0,s=e)}if(a){const r=hh.prototype[t].bind(e);Object.defineProperty(window,t,{configurable:!0,enumerable:!0,value:r})}else if(o)Object.defineProperty(window,t,{configurable:!0,enumerable:!0,value:s});else if(n||!a){let r=null,i=null,n=null;Object.defineProperty(window,t,{configurable:!0,enumerable:!0,get:()=>{const s=e[t];return null===n?(n="function"==typeof s,n?(r=s,i=s.bind(e),i):s):n?(s!==r&&(r=s,i=s.bind(e)),i):s}})}}}(this);if(t)t(this),e._checkForUserDefinedFunctions(this);else{if(this._isGlobal=!0,window.hitCriticalError)return;e.instance=this;for(const t of Object.getOwnPropertyNames(e.prototype))"_"!==t[0]&&i(t);const t=["constructor","length"];for(const e in this)if(this.hasOwnProperty(e)){if("_"===e[0]||t.includes(e))continue;i(e)}}const n=()=>{this.focused=!0},s=()=>{this.focused=!1};"undefined"!=typeof window?(window.addEventListener("focus",n),window.addEventListener("blur",s),e.lifecycleHooks.remove.push((function(){window.removeEventListener("focus",n),window.removeEventListener("blur",s)})),"complete"===document.readyState?this.#R():(this._startListener=this.#R.bind(this),window.addEventListener("load",this._startListener,!1))):this.#R()}get pixels(){return this._renderer?.pixels}get drawingContext(){return this._renderer?.drawingContext}static _registeredAddons=new Set;static registerAddon(t){const r={};if(e._registeredAddons.has(t))return;e._registeredAddons.add(t),t(e,e.prototype,r);const i=Object.keys(e.lifecycleHooks);for(const t of i)"function"==typeof r[t]&&e.lifecycleHooks[t].push(r[t])}static decorations=new Map;static registerDecorator(t,r){if("string"==typeof t){const e=t;t=({path:t})=>e===t}else if(Array.isArray(t)&&t.every((e=>"string"==typeof e))){const e=t;t=({path:t})=>e.includes(t)}else if("function"!=typeof t)throw new Error("Decorator matching pattern must be a function, a string, or an array of strings");e.decorations.set(t,r)}#V={};_customActions=new Proxy({},{get:(e,t)=>{if(!this.#V[t]){const e=this._isGlobal?window:this;"function"==typeof e[t]&&(this.#V[t]=e[t].bind(this))}return this.#V[t]}});async#R(){this.hitCriticalError||(this._userNode&&"string"==typeof this._userNode&&(this._userNode=document.getElementById(this._userNode)),await this.#U(),this.hitCriticalError||this._recording||this._draw())}async#U(){if(await this._runLifecycleHook("presetup"),this.hitCriticalError)return;"undefined"!=typeof window&&this.createCanvas(100,100,i),this._millisStart=globalThis.performance.now();const e=this._isGlobal?window:this;if("function"==typeof e.setup&&await e.setup(),!this.hitCriticalError){if("undefined"!=typeof document){const e=document.getElementsByTagName("canvas");for(const t of e)t.style.touchAction="none","true"===t.dataset.hidden&&(t.style.visibility="",delete t.dataset.hidden)}this._lastTargetFrameTime=globalThis.performance.now(),this._lastRealFrameTime=globalThis.performance.now(),this._setupDone=!0,(this._accessibleOutputs.grid||this._accessibleOutputs.text)&&this._updateAccsOutput(),await this._runLifecycleHook("postsetup"),this._millisStart=globalThis.performance.now()}}async _draw(e){if(this.hitCriticalError)return;const t=e||globalThis.performance.now(),r=t-this._lastTargetFrameTime,i=1e3/this._targetFrameRate;if((!this._loop||r>=i-5)&&(this.deltaTime=t-this._lastRealFrameTime,this._frameRate=1e3/this.deltaTime,await this.redraw(),this._lastTargetFrameTime=Math.max(this._lastTargetFrameTime+i,t),this._lastRealFrameTime=t,void 0!==this._updateMouseCoords&&(this._updateMouseCoords(),this.movedX=0,this.movedY=0)),this._loop){const e=this._draw.bind(this);this._requestAnimId="undefined"!=typeof window?window.requestAnimationFrame(e):setImmediate(e)}}async remove(){if(this._startListener&&window.removeEventListener("load",this._startListener,!1),this._curElement){this._loop=!1,this._requestAnimId&&window.cancelAnimationFrame(this._requestAnimId),this._removeAbortController.abort();for(const e of this._elements)e.elt&&e.elt.parentNode&&e.elt.parentNode.removeChild(e.elt);await this._runLifecycleHook("remove")}if(this._isGlobal){for(const t in e.prototype)try{delete window[t]}catch(e){window[t]=void 0}for(const e in this)if(this.hasOwnProperty(e))try{delete window[e]}catch(t){window[e]=void 0}e.instance=null}}async _runLifecycleHook(t){await Promise.all(e.lifecycleHooks[t].map((e=>e.call(this))))}_initializeInstanceVariables(){this._accessibleOutputs={text:!1,grid:!1,textLabel:!1,gridLabel:!1},this._styles=[],this._downKeys={},this._downKeyCodes={}}};for(const e in qe)hh.prototype[e]=qe[e];function uh(e,t,r){for(const i in e)if(!i.startsWith("_")){for(const[n,s]of t)if(n({path:`${r}.${i}`}))if("function"==typeof e[i]){const t=s(e[i],{kind:"method",name:i,static:!0});t&&Object.defineProperty(e,i,{enumerable:!0,writable:!0,value:t})}else{const t=s(void 0,{kind:"field",name:i,static:!0});t&&"function"==typeof t&&(e[i]=t(e[i]))}"function"==typeof e[i]&&e[i].prototype&&uh(e[i],t,`${r}.${i}`)}for(const i of Object.getOwnPropertyNames(e.prototype))if("constructor"!==i&&!i.startsWith("_"))for(const[n,s]of t)if(n({path:`${r}.prototype.${i}`}))if("function"==typeof e.prototype[i]){const t=s(e.prototype[i],{kind:"method",name:i,static:!1});t&&Object.defineProperty(e.prototype,i,{enumerable:!0,writable:!0,value:t})}else{const t=Object.getOwnPropertyDescriptor(e.prototype,i);if(t.hasOwnProperty("value")){const t=s(void 0,{kind:"field",name:i,static:!1});Object.defineProperty(e.prototype,i,{enumerable:!0,writable:!0,value:t&&"function"==typeof t?t(e.prototype[i]):e.prototype[i]})}else{const{get:r,set:n}=t,a=s(r,{kind:"getter",name:i,static:!1}),o=s(n,{kind:"setter",name:i,static:!1});Object.defineProperty(e.prototype,i,{enumerable:!0,get:a??r,set:o??n})}}}function lh(e,t){const r="_Description",i="_fallbackDesc",n="_fallbackTable",s="_fte_",a="_Label",o="_labelDesc",h="_labelTable",u="_lte_";function l(e){if("label"===e||"fallback"===e)throw new Error("description should not be LABEL or FALLBACK");return e.endsWith(".")||e.endsWith(";")||e.endsWith(",")||e.endsWith("?")||e.endsWith("!")||(e+="."),e}t.describe=function(e,t){if("string"!=typeof e)return;const r=this.canvas.id;e=l(e),this.dummyDOM||(this.dummyDOM=document.getElementById(r).parentNode),this.descriptions||(this.descriptions={}),this.descriptions.fallback?this.descriptions.fallback.innerHTML!==e&&(this.descriptions.fallback.innerHTML=e):this._describeHTML("fallback",e),t===this.LABEL&&(this.descriptions.label?this.descriptions.label.innerHTML!==e&&(this.descriptions.label.innerHTML=e):this._describeHTML("label",e))},t.describeElement=function(e,t,r){if("string"!=typeof t||"string"!=typeof e)return;const i=this.canvas.id;t=l(t);let n=function(e){if("label"===e||"fallback"===e)throw new Error("element name should not be LABEL or FALLBACK");e.endsWith(".")||e.endsWith(";")||e.endsWith(",")?e=e.replace(/.$/,":"):e.endsWith(":")||(e+=":");return e}(e);e=e.replace(/[^a-zA-Z0-9]/g,"");let s=`${n}${t}`;this.dummyDOM||(this.dummyDOM=document.getElementById(i).parentNode),this.descriptions?this.descriptions.fallbackElements||(this.descriptions.fallbackElements={}):this.descriptions={fallbackElements:{}},this.descriptions.fallbackElements[e]?this.descriptions.fallbackElements[e].innerHTML!==s&&(this.descriptions.fallbackElements[e].innerHTML=s):this._describeElementHTML("fallback",e,s),r===this.LABEL&&(this.descriptions.labelElements||(this.descriptions.labelElements={}),this.descriptions.labelElements[e]?this.descriptions.labelElements[e].innerHTML!==s&&(this.descriptions.labelElements[e].innerHTML=s):this._describeElementHTML("label",e,s))},t._describeHTML=function(e,t){const s=this.canvas.id;if("fallback"===e){if(this.dummyDOM.querySelector(`#${s+r}`))this.dummyDOM.querySelector("#"+s+n).insertAdjacentHTML("beforebegin",`

`);else{let e=`

`;this.dummyDOM.querySelector(`#${s}accessibleOutput`)?this.dummyDOM.querySelector(`#${s}accessibleOutput`).insertAdjacentHTML("beforebegin",e):this.dummyDOM.querySelector(`#${s}`).innerHTML=e}return this.descriptions.fallback=this.dummyDOM.querySelector(`#${s}${i}`),void(this.descriptions.fallback.innerHTML=t)}if("label"===e){if(this.dummyDOM.querySelector(`#${s+a}`))this.dummyDOM.querySelector(`#${s+h}`)&&this.dummyDOM.querySelector(`#${s+h}`).insertAdjacentHTML("beforebegin",`

`);else{let e=`

`;this.dummyDOM.querySelector(`#${s}accessibleOutputLabel`)?this.dummyDOM.querySelector(`#${s}accessibleOutputLabel`).insertAdjacentHTML("beforebegin",e):this.dummyDOM.querySelector("#"+s).insertAdjacentHTML("afterend",e)}return this.descriptions.label=this.dummyDOM.querySelector("#"+s+o),void(this.descriptions.label.innerHTML=t)}},t._describeElementHTML=function(e,t,l){const c=this.canvas.id;if("fallback"===e){if(this.dummyDOM.querySelector(`#${c+r}`))this.dummyDOM.querySelector("#"+c+n)||this.dummyDOM.querySelector("#"+c+i).insertAdjacentHTML("afterend",`
Canvas elements and their descriptions
`);else{let e=`
Canvas elements and their descriptions
`;this.dummyDOM.querySelector(`#${c}accessibleOutput`)?this.dummyDOM.querySelector(`#${c}accessibleOutput`).insertAdjacentHTML("beforebegin",e):this.dummyDOM.querySelector("#"+c).innerHTML=e}let e=document.createElement("tr");return e.id=c+s+t,this.dummyDOM.querySelector("#"+c+n).appendChild(e),this.descriptions.fallbackElements[t]=this.dummyDOM.querySelector(`#${c}${s}${t}`),void(this.descriptions.fallbackElements[t].innerHTML=l)}if("label"===e){if(this.dummyDOM.querySelector(`#${c+a}`))this.dummyDOM.querySelector(`#${c+h}`)||this.dummyDOM.querySelector("#"+c+o).insertAdjacentHTML("afterend",`
`);else{let e=`
`;this.dummyDOM.querySelector(`#${c}accessibleOutputLabel`)?this.dummyDOM.querySelector(`#${c}accessibleOutputLabel`).insertAdjacentHTML("beforebegin",e):this.dummyDOM.querySelector("#"+c).insertAdjacentHTML("afterend",e)}let e=document.createElement("tr");e.id=c+u+t,this.dummyDOM.querySelector("#"+c+h).appendChild(e),this.descriptions.labelElements[t]=this.dummyDOM.querySelector(`#${c}${u}${t}`),this.descriptions.labelElements[t].innerHTML=l}}}function ch(e,t){t._updateGridOutput=function(e){if(this._renderer&&this._renderer.isP3D)return void(this._didOutputGridWebGLMessage||(this._didOutputGridWebGLMessage=!0,console.error("gridOutput() does not yet work in WebGL mode.")));if(!this.dummyDOM.querySelector(`#${e}_summary`))return;let t=this._accessibleOutputs[e],r=function(e,t){let r="",i="",n=0;for(let s in t){let a=0;for(let i in t[s]){let o=`
  • ${t[s][i].color} ${s},`;"line"===s?o+=` location = ${t[s][i].pos}, length = ${t[s][i].length} pixels`:(o+=` location = ${t[s][i].pos}`,"point"!==s&&(o+=`, area = ${t[s][i].area} %`),o+="
  • "),r+=o,a++,n++}i=a>1?`${i} ${a} ${s}s`:`${i} ${a} ${s}`}return{numShapes:[n,i],details:r}}(e,this.ingredients.shapes),i=function(e,t,r,i){let n=`${t} canvas, ${r} by ${i} pixels, contains ${e[0]}`;n=1===e[0]?`${n} shape: ${e[1]}`:`${n} shapes: ${e[1]}`;return n}(r.numShapes,this.ingredients.colors.background,this.width,this.height),n=function(e,t){let r=0,i="",n=Array.from(Array(10),(()=>Array(10)));for(let i in t)for(let s in t[i]){let a;a="line"!==i?`${t[i][s].color} ${i}`:`${t[i][s].color} ${i} midpoint`,t[i][s].loc.locY";i=i+t+""}return i}(e,this.ingredients.shapes);i!==t.summary.innerHTML&&(t.summary.innerHTML=i),n!==t.map.innerHTML&&(t.map.innerHTML=n),r.details!==t.shapeDetails.innerHTML&&(t.shapeDetails.innerHTML=r.details),this._accessibleOutputs[e]=t}}function ph(e,t){t._updateTextOutput=function(e){if(this._renderer&&this._renderer.isP3D)return void(this._didOutputTextWebGLMessage||(this._didOutputTextWebGLMessage=!0,console.error("textOutput() does not yet work in WebGL mode.")));if(!this.dummyDOM.querySelector(`#${e}_summary`))return;let t=this._accessibleOutputs[e],r=function(e,t){let r="",i=0;for(let n in t)for(let s in t[n]){let a=`
  • ${t[n][s].color} ${n}`;"line"===n?a+=`, ${t[n][s].pos}, ${t[n][s].length} pixels long.
  • `:(a+=`, at ${t[n][s].pos}`,"point"!==n&&(a+=`, covering ${t[n][s].area}% of the canvas`),a+="."),r+=a,i++}return{numShapes:i,listShapes:r}}(e,this.ingredients.shapes),i=function(e,t,r,i){let n=`Your output is a, ${r} by ${i} pixels, ${t} canvas containing the following`;n=1===e?`${n} shape:`:`${n} ${e} shapes:`;return n}(r.numShapes,this.ingredients.colors.background,this.width,this.height),n=function(e,t){let r="",i=0;for(let n in t)for(let s in t[n]){let a=`${t[n][s].color} ${n}`;"line"===n?a+=`location = ${t[n][s].pos}length = ${t[n][s].length} pixels`:(a+=`location = ${t[n][s].pos}`,"point"!==n&&(a+=` area = ${t[n][s].area}%`),a+=""),r+=a,i++}return r}(e,this.ingredients.shapes);i!==t.summary.innerHTML&&(t.summary.innerHTML=i),r.listShapes!==t.list.innerHTML&&(t.list.innerHTML=r.listShapes),n!==t.shapeDetails.innerHTML&&(t.shapeDetails.innerHTML=n),this._accessibleOutputs[e]=t}}function dh(e,t){function r(e,t,r){let i=Math.floor(e[0]/t*10),n=Math.floor(e[1]/r*10);return 10===i&&(i-=1),10===n&&(n-=1),{locX:i,locY:n}}t.textOutput=function(e){this._accessibleOutputs.text||(this._accessibleOutputs.text=!0,this._createOutput("textOutput","Fallback"),e===this.LABEL&&(this._accessibleOutputs.textLabel=!0,this._createOutput("textOutput","Label")))},t.gridOutput=function(e){this._accessibleOutputs.grid||(this._accessibleOutputs.grid=!0,this._createOutput("gridOutput","Fallback"),e===this.LABEL&&(this._accessibleOutputs.gridLabel=!0,this._createOutput("gridOutput","Label")))},t._addAccsOutput=function(){return this._accessibleOutputs||(this._accessibleOutputs={text:!1,grid:!1,textLabel:!1,gridLabel:!1}),this._accessibleOutputs.grid||this._accessibleOutputs.text},t._createOutput=function(e,t){let r,i,n,s=this.canvas.id;this.ingredients||(this.ingredients={shapes:{},colors:{background:"white",fill:"white",stroke:"black"},pShapes:"",pBackground:""}),this.dummyDOM||(this.dummyDOM=document.getElementById(s).parentNode);let a="";"Fallback"===t?(r=s+e,i=s+"accessibleOutput",this.dummyDOM.querySelector(`#${i}`)||(this.dummyDOM.querySelector(`#${s}_Description`)?this.dummyDOM.querySelector(`#${s}_Description`).insertAdjacentHTML("afterend",`
    `):this.dummyDOM.querySelector(`#${s}`).innerHTML=`
    `)):"Label"===t&&(a=t,r=s+e+t,i=s+"accessibleOutput"+t,this.dummyDOM.querySelector(`#${i}`)||(this.dummyDOM.querySelector(`#${s}_Label`)?this.dummyDOM.querySelector(`#${s}_Label`).insertAdjacentHTML("afterend",`
    `):this.dummyDOM.querySelector(`#${s}`).insertAdjacentHTML("afterend",`
    `))),this._accessibleOutputs[r]={},"textOutput"===e?(a=`#${s}gridOutput${a}`,n=`
    Text Output

      `,this.dummyDOM.querySelector(a)?this.dummyDOM.querySelector(a).insertAdjacentHTML("beforebegin",n):this.dummyDOM.querySelector(`#${i}`).innerHTML=n,this._accessibleOutputs[r].list=this.dummyDOM.querySelector(`#${r}_list`)):"gridOutput"===e&&(a=`#${s}textOutput${a}`,n=`
      Grid Output

        `,this.dummyDOM.querySelector(a)?this.dummyDOM.querySelector(a).insertAdjacentHTML("afterend",n):this.dummyDOM.querySelector(`#${i}`).innerHTML=n,this._accessibleOutputs[r].map=this.dummyDOM.querySelector(`#${r}_map`)),this._accessibleOutputs[r].shapeDetails=this.dummyDOM.querySelector(`#${r}_shapeDetails`),this._accessibleOutputs[r].summary=this.dummyDOM.querySelector(`#${r}_summary`)},t._updateAccsOutput=function(){let e=this.canvas.id;JSON.stringify(this.ingredients.shapes)===this.ingredients.pShapes&&this.ingredients.colors.background===this.ingredients.pBackground||(this.ingredients.pShapes=JSON.stringify(this.ingredients.shapes),this._accessibleOutputs.text&&this._updateTextOutput(e+"textOutput"),this._accessibleOutputs.grid&&this._updateGridOutput(e+"gridOutput"),this._accessibleOutputs.textLabel&&this._updateTextOutput(e+"textOutputLabel"),this._accessibleOutputs.gridLabel&&this._updateGridOutput(e+"gridOutputLabel"))},t._accsBackground=function(e){this.ingredients.pShapes=JSON.stringify(this.ingredients.shapes),this.ingredients.pBackground=this.ingredients.colors.background,this.ingredients.shapes={},this.ingredients.colors.backgroundRGBA!==e&&(this.ingredients.colors.backgroundRGBA=e,this.ingredients.colors.background=this._rgbColorName(e))},t._accsCanvasColors=function(e,t){"fill"===e?this.ingredients.colors.fillRGBA!==t&&(this.ingredients.colors.fillRGBA=t,this.ingredients.colors.fill=this._rgbColorName(t)):"stroke"===e&&this.ingredients.colors.strokeRGBA!==t&&(this.ingredients.colors.strokeRGBA=t,this.ingredients.colors.stroke=this._rgbColorName(t))},t._accsOutput=function(e,t){"ellipse"===e&&t[2]===t[3]?e="circle":"rectangle"===e&&t[2]===t[3]&&(e="square");let i={},n=!0,s=function(e,t){let r,i;"rectangle"===e||"ellipse"===e||"arc"===e||"circle"===e||"square"===e?(r=Math.round(t[0]+t[2]/2),i=Math.round(t[1]+t[3]/2)):"triangle"===e?(r=(t[0]+t[2]+t[4])/3,i=(t[1]+t[3]+t[5])/3):"quadrilateral"===e?(r=(t[0]+t[2]+t[4]+t[6])/4,i=(t[1]+t[3]+t[5]+t[7])/4):"line"===e?(r=(t[0]+t[2])/2,i=(t[1]+t[3])/2):(r=t[0],i=t[1]);return[r,i]}(e,t);if("line"===e){i.color=this.ingredients.colors.stroke,i.length=Math.round(Math.hypot(t[2]-t[0],t[3]-t[1]));let e=this._getPos(t[0],[1]),n=this._getPos(t[2],[3]);i.loc=r(s,this.width,this.height),i.pos=e===n?`at ${e}`:`from ${e} to ${n}`}else"point"===e?i.color=this.ingredients.colors.stroke:(i.color=this.ingredients.colors.fill,i.area=this._getArea(e,t)),i.pos=this._getPos(...s),i.loc=r(s,this.width,this.height);if(this.ingredients.shapes[e]){for(let t in this.ingredients.shapes[e])JSON.stringify(this.ingredients.shapes[e][t])===JSON.stringify(i)&&(n=!1);!0===n&&this.ingredients.shapes[e].push(i)}else this.ingredients.shapes[e]=[i]},t._getPos=function(t,r){const{x:i,y:n}=this.worldToScreen(new e.Vector(t,r)),s=this.width,a=this.height;return i<.4*s?n<.4*a?"top left":n>.6*a?"bottom left":"mid left":i>.6*s?n<.4*a?"top right":n>.6*a?"bottom right":"mid right":n<.4*a?"top middle":n>.6*a?"bottom middle":"middle"},t._getArea=function(e,t){let r=0;if("arc"===e){const e=((t[5]-t[4])%(2*Math.PI)+2*Math.PI)%(2*Math.PI);if(r=e*t[2]*t[3]/8,"open"===t[6]||"chord"===t[6]){const i=t[0],n=t[1],s=t[0]+t[2]/2*Math.cos(t[4]).toFixed(2),a=t[1]+t[3]/2*Math.sin(t[4]).toFixed(2),o=t[0]+t[2]/2*Math.cos(t[5]).toFixed(2),h=t[1]+t[3]/2*Math.sin(t[5]).toFixed(2),u=Math.abs(i*(a-h)+s*(h-n)+o*(n-a))/2;e>Math.PI?r+=u:r-=u}}else"ellipse"===e||"circle"===e?r=3.14*t[2]/2*t[3]/2:"line"===e||"point"===e?r=0:"quadrilateral"===e?r=Math.abs((t[6]+t[0])*(t[7]-t[1])+(t[0]+t[2])*(t[1]-t[3])+(t[2]+t[4])*(t[3]-t[5])+(t[4]+t[6])*(t[5]-t[7]))/2:"rectangle"===e||"square"===e?r=t[2]*t[3]:"triangle"===e&&(r=Math.abs(t[0]*(t[3]-t[5])+t[2]*(t[5]-t[1])+t[4]*(t[1]-t[3]))/2);const i=this.width*this._renderer._pixelDensity,n=this.height*this._renderer._pixelDensity,s=[new DOMPoint(0,0),new DOMPoint(i,0),new DOMPoint(i,n),new DOMPoint(0,n)],a=(this._renderer.isP3D?new DOMMatrix(this._renderer.uMVMatrix.mat4):this.drawingContext.getTransform()).inverse(),o=s.map((e=>e.matrixTransform(a))),h=Math.abs((o[3].x+o[0].x)*(o[3].y-o[0].y)+(o[0].x+o[1].x)*(o[0].y-o[1].y)+(o[1].x+o[2].x)*(o[1].y-o[2].y)+(o[2].x+o[3].x)*(o[2].y-o[3].y))/2;return Math.round(100*r/h)}}hh.registerAddon(We),hh.registerAddon(Xe),hh.registerAddon(Ye),hh.registerAddon(yo),hh.registerAddon((function(e,t){e.Renderer=ds})),hh.registerAddon((function(e,t){e.Renderer2D=oh,e.renderers[i]=oh,e.renderers["p2d-p3"]=new Proxy(oh,{construct:(e,[t,r,i,n,s])=>new e(t,r,i,n,s,{colorSpace:"display-p3"})})})),hh.registerAddon((function(e,t){e.Graphics=Ja,bs(e,e.Graphics.prototype),_s(0,e.Graphics.prototype),ws(0,e.Graphics.prototype),Cs(0,e.Graphics.prototype),ls(e,e.Graphics.prototype),Es(0,e.Graphics.prototype),ra(e,e.Graphics.prototype),ks(e,e.Graphics.prototype),ia(e,e.Graphics.prototype),We(e,e.Graphics.prototype),Ga(e,e.Graphics.prototype),$a(0,e.Graphics.prototype),Za(0,e.Graphics.prototype),Ri(e,e.Graphics.prototype),Ka(0,e.Graphics.prototype)})),hh.registerAddon((function(e,t,r){r.presetup=function(){if("undefined"==typeof window||this._loadingIndicator)return;const e=this.canvas?.parentElement;let t=this._userNode||e||document.body;"string"==typeof t&&(t=document.getElementById(t)||document.body),this._loadingIndicator=function(e){if(!document.getElementById("p5-loading-style")){const e=document.createElement("style");e.id="p5-loading-style",e.textContent="@keyframes p5-loading-spin { to { transform: rotate(360deg); } }",document.head.appendChild(e)}const t=document.createElement("div");return t.className="loading-indicator",t.style.cssText="\n position: fixed;\n inset: 0;\n margin: auto;\n width: 30px;\n height: 30px;\n border-radius: 50%;\n\n border: 3px solid rgba(0, 0, 0, 0.1);\n border-top-color: rgba(0, 0, 0, 0.8);\n animation: p5-loading-spin 1s linear infinite;\n z-index: 9999;\n ",e.appendChild(t),t}(t)},r.postsetup=function(){this._loadingIndicator&&(this._loadingIndicator.remove(),this._loadingIndicator=null)}})),void 0!==p5&&lh(0,p5.prototype),void 0!==p5&&ch(0,p5.prototype),void 0!==p5&&ph(0,p5.prototype),void 0!==p5&&dh(p5,p5.prototype),hh.ColorConversion={_hsbaToHSLA(e){const t=e[0];let r=e[1];const i=e[2],n=(2-r)*i/2;return 0!==n&&(1===n?r=0:n<.5?r/=2-r:r=r*i/(2-2*n)),[t,r,n,e[3]]},_hsbaToRGBA(e){const t=6*e[0],r=e[1],i=e[2];let n=[];if(0===r)n=[i,i,i,e[3]];else{const s=Math.floor(t),a=i*(1-r),o=i*(1-r*(t-s)),h=i*(1-r*(1+s-t));let u,l,c;1===s?(u=o,l=i,c=a):2===s?(u=a,l=i,c=h):3===s?(u=a,l=o,c=i):4===s?(u=h,l=a,c=i):5===s?(u=i,l=a,c=o):(u=i,l=h,c=a),n=[u,l,c,e[3]]}return n},_hslaToHSBA(e){const t=e[0];let r=e[1];const i=e[2];let n;return n=i<.5?(1+r)*i:i+r-i*r,r=2*(n-i)/n,[t,r,n,e[3]]},_hslaToRGBA(e){const t=6*e[0],r=e[1],i=e[2];let n=[];if(0===r)n=[i,i,i,e[3]];else{let s;s=i<.5?(1+r)*i:i+r-i*r;const a=2*i-s,o=(e,t,r)=>(e<0?e+=6:e>=6&&(e-=6),e<1?t+(r-t)*e:e<3?r:e<4?t+(r-t)*(4-e):t);n=[o(t+2,a,s),o(t,a,s),o(t-2,a,s),e[3]]}return n},_rgbaToHSBA(e){const t=e[0],r=e[1],i=e[2],n=Math.max(t,r,i),s=n-Math.min(t,r,i);let a,o;return 0===s?(a=0,o=0):(o=s/n,t===n?a=(r-i)/s:r===n?a=2+(i-t)/s:i===n&&(a=4+(t-r)/s),a<0?a+=6:a>=6&&(a-=6)),[a/6,o,n,e[3]]},_rgbaToHSLA(e){const t=e[0],r=e[1],i=e[2],n=Math.max(t,r,i),s=Math.min(t,r,i),a=n+s,o=n-s;let h,u;return 0===o?(h=0,u=0):(u=a<1?o/a:o/(2-a),t===n?h=(r-i)/o:r===n?h=2+(i-t)/o:i===n&&(h=4+(t-r)/o),h<0?h+=6:h>=6&&(h-=6)),[h/6,u,a/2,e[3]]}};var fh=hh.ColorConversion;function mh(e,t){let r;const i=[{h:0,s:0,b:.8275,name:"gray"},{h:0,s:0,b:.8627,name:"gray"},{h:0,s:0,b:.7529,name:"gray"},{h:.0167,s:.1176,b:1,name:"light pink"}],n=[{h:0,s:0,b:0,name:"black"},{h:0,s:0,b:.5,name:"gray"},{h:0,s:0,b:1,name:"white"},{h:0,s:.5,b:.5,name:"dark maroon"},{h:0,s:.5,b:1,name:"salmon pink"},{h:0,s:1,b:0,name:"black"},{h:0,s:1,b:.5,name:"dark red"},{h:0,s:1,b:1,name:"red"},{h:5,s:0,b:1,name:"very light peach"},{h:5,s:.5,b:.5,name:"brown"},{h:5,s:.5,b:1,name:"peach"},{h:5,s:1,b:.5,name:"brick red"},{h:5,s:1,b:1,name:"crimson"},{h:10,s:0,b:1,name:"light peach"},{h:10,s:.5,b:.5,name:"brown"},{h:10,s:.5,b:1,name:"light orange"},{h:10,s:1,b:.5,name:"brown"},{h:10,s:1,b:1,name:"orange"},{h:15,s:0,b:1,name:"very light yellow"},{h:15,s:.5,b:.5,name:"olive green"},{h:15,s:.5,b:1,name:"light yellow"},{h:15,s:1,b:0,name:"dark olive green"},{h:15,s:1,b:.5,name:"olive green"},{h:15,s:1,b:1,name:"yellow"},{h:20,s:0,b:1,name:"very light yellow"},{h:20,s:.5,b:.5,name:"olive green"},{h:20,s:.5,b:1,name:"light yellow green"},{h:20,s:1,b:0,name:"dark olive green"},{h:20,s:1,b:.5,name:"dark yellow green"},{h:20,s:1,b:1,name:"yellow green"},{h:25,s:.5,b:.5,name:"dark yellow green"},{h:25,s:.5,b:1,name:"light green"},{h:25,s:1,b:.5,name:"dark green"},{h:25,s:1,b:1,name:"green"},{h:30,s:.5,b:1,name:"light green"},{h:30,s:1,b:.5,name:"dark green"},{h:30,s:1,b:1,name:"green"},{h:35,s:0,b:.5,name:"light green"},{h:35,s:0,b:1,name:"very light green"},{h:35,s:.5,b:.5,name:"dark green"},{h:35,s:.5,b:1,name:"light green"},{h:35,s:1,b:0,name:"very dark green"},{h:35,s:1,b:.5,name:"dark green"},{h:35,s:1,b:1,name:"green"},{h:40,s:0,b:1,name:"very light green"},{h:40,s:.5,b:.5,name:"dark green"},{h:40,s:.5,b:1,name:"light green"},{h:40,s:1,b:.5,name:"dark green"},{h:40,s:1,b:1,name:"green"},{h:45,s:.5,b:1,name:"light turquoise"},{h:45,s:1,b:.5,name:"dark turquoise"},{h:45,s:1,b:1,name:"turquoise"},{h:50,s:0,b:1,name:"light sky blue"},{h:50,s:.5,b:.5,name:"dark cyan"},{h:50,s:.5,b:1,name:"light cyan"},{h:50,s:1,b:.5,name:"dark cyan"},{h:50,s:1,b:1,name:"cyan"},{h:55,s:0,b:1,name:"light sky blue"},{h:55,s:.5,b:1,name:"light sky blue"},{h:55,s:1,b:.5,name:"dark blue"},{h:55,s:1,b:1,name:"sky blue"},{h:60,s:0,b:.5,name:"gray"},{h:60,s:0,b:1,name:"very light blue"},{h:60,s:.5,b:.5,name:"blue"},{h:60,s:.5,b:1,name:"light blue"},{h:60,s:1,b:.5,name:"navy blue"},{h:60,s:1,b:1,name:"blue"},{h:65,s:0,b:1,name:"lavender"},{h:65,s:.5,b:.5,name:"navy blue"},{h:65,s:.5,b:1,name:"light purple"},{h:65,s:1,b:.5,name:"dark navy blue"},{h:65,s:1,b:1,name:"blue"},{h:70,s:0,b:1,name:"lavender"},{h:70,s:.5,b:.5,name:"navy blue"},{h:70,s:.5,b:1,name:"lavender blue"},{h:70,s:1,b:.5,name:"dark navy blue"},{h:70,s:1,b:1,name:"blue"},{h:75,s:.5,b:1,name:"lavender"},{h:75,s:1,b:.5,name:"dark purple"},{h:75,s:1,b:1,name:"purple"},{h:80,s:.5,b:1,name:"pinkish purple"},{h:80,s:1,b:.5,name:"dark purple"},{h:80,s:1,b:1,name:"purple"},{h:85,s:0,b:1,name:"light pink"},{h:85,s:.5,b:.5,name:"purple"},{h:85,s:.5,b:1,name:"light fuchsia"},{h:85,s:1,b:.5,name:"dark fuchsia"},{h:85,s:1,b:1,name:"fuchsia"},{h:90,s:.5,b:.5,name:"dark fuchsia"},{h:90,s:.5,b:1,name:"hot pink"},{h:90,s:1,b:.5,name:"dark fuchsia"},{h:90,s:1,b:1,name:"fuchsia"},{h:95,s:0,b:1,name:"pink"},{h:95,s:.5,b:1,name:"light pink"},{h:95,s:1,b:.5,name:"dark magenta"},{h:95,s:1,b:1,name:"magenta"}];t._rgbColorName=function(e){let t=fh._rgbaToHSBA(e);return r=t,function(e){let t;if(0!==e[0]){e[0]=Math.round(100*e[0]);let t=e[0].toString().split("");const r=t.length-1;t[r]=parseInt(t[r]),t[r]<2.5?t[r]=0:t[r]>=2.5&&t[r]<7.5&&(t[r]=5),2===t.length?(t[0]=parseInt(t[0]),t[r]>=7.5&&(t[r]=0,t[0]=t[0]+1),e[0]=10*t[0]+t[1]):t[r]>=7.5?e[0]=10:e[0]=t[r]}e[2]=e[2]/255;for(let t=e.length-1;t>=1;t--)e[t]<=.25?e[t]=0:e[t]>.25&&e[t]<.75?e[t]=.5:e[t]=1;if(0===e[0]&&0===e[1]&&1===e[2]){for(let e=2;e>=0;e--)r[e]=Math.round(1e4*r[e])/1e4;for(let e=0;e{e.endsWith("p5TypeID")&&this.removeItem(e.replace("p5TypeID",""))}))},t.removeItem=function(t){"string"!=typeof t&&e._friendlyError(`The argument that you passed to removeItem() - ${t} is not a string.`,"removeItem"),localStorage.removeItem(t),localStorage.removeItem(`${t}p5TypeID`)}}function yh(e,t){function r(e,t,r){(t._userNode?t._userNode:document.body).appendChild(e);const i=r?new ys(e,t):new En(e,t);return t._elements.push(i),i}t.select=function(e,t){const r=this._getContainer(t).querySelector(e);return r?this._wrapElement(r):null},t.selectAll=function(e,t){const r=[],i=this._getContainer(t).querySelectorAll(e);if(i)for(let e=0;e0&&t.every((function(e){return"INPUT"===e.tagName||"LABEL"===e.tagName}))&&("DIV"===e.tagName||"SPAN"===e.tagName)?this.createRadio(new En(e,this)):new En(e,this)},t.createElement=function(e,t){const i=document.createElement(e);return void 0!==t&&(i.innerHTML=t),r(i,this)},t.removeElements=function(e){this._elements.filter((e=>!(e.elt instanceof HTMLCanvasElement))).map((e=>e.remove()))},t.createDiv=function(e=""){let t=document.createElement("div");return t.innerHTML=e,r(t,this)},t.createP=function(e=""){let t=document.createElement("p");return t.innerHTML=e,r(t,this)},t.createSpan=function(e=""){let t=document.createElement("span");return t.innerHTML=e,r(t,this)},t.createImg=function(){const e=document.createElement("img"),t=arguments;let i;return t.length>1&&"string"==typeof t[1]&&(e.alt=t[1]),t.length>2&&"string"==typeof t[2]&&(e.crossOrigin=t[2]),e.src=t[0],i=r(e,this),e.addEventListener("load",(function(){i.width=e.offsetWidth||e.width,i.height=e.offsetHeight||e.height;const r=t[t.length-1];"function"==typeof r&&r(i)})),i},t.createA=function(e,t,i){const n=document.createElement("a");return n.href=e,n.innerHTML=t,i&&(n.target=i),r(n,this)},t.createSlider=function(e,t,i,n){const s=document.createElement("input");return s.type="range",s.min=e,s.max=t,0===n?s.step=1e-18:n&&(s.step=n),"number"==typeof i&&(s.value=i),r(s,this)},t.createButton=function(e,t){const i=document.createElement("button");return i.innerHTML=e,t&&(i.value=t),r(i,this)},t.createCheckbox=function(...e){const t=document.createElement("div"),i=document.createElement("input");i.type="checkbox";const n=document.createElement("label");n.appendChild(i),t.appendChild(n);const s=r(t,this);if(s.checked=function(...e){const t=s.elt.firstElementChild.getElementsByTagName("input")[0];if(t){if(0===e.length)return t.checked;e[0]?t.checked=!0:t.checked=!1}return s},this.value=function(e){return s.value=e,this},e[0]){s.value(e[0]);const t=document.createElement("span");t.innerHTML=e[0],n.appendChild(t)}return e[1]&&(i.checked=!0),s},t.createSelect=function(...e){let t,i=e[0];if(i instanceof En&&i.elt instanceof HTMLSelectElement)t=i,this.elt=i.elt;else if(i instanceof HTMLSelectElement)t=r(i,this),this.elt=i;else{const e=document.createElement("select");i&&"boolean"==typeof i&&e.setAttribute("multiple","true"),t=r(e,this),this.elt=e}return t.option=function(e,t){let r;if(void 0!==e){for(let t=0;te instanceof HTMLInputElement&&"radio"===e.type,h=e=>e instanceof HTMLLabelElement;return t._getOptionsArray=function(){return Array.from(this.elt.children).filter((e=>o(e)||h(e)&&o(e.firstElementChild))).map((e=>o(e)?e:e.firstElementChild))},t.option=function(e,r){let i,n,s;for(const r of t._getOptionsArray())if(r.value===e){i=r;break}return void 0===i&&(i=document.createElement("input"),i.setAttribute("type","radio"),i.setAttribute("value",e)),i.setAttribute("name",t._name),h(i.parentElement)?n=i.parentElement:(n=document.createElement("label"),n.insertAdjacentElement("afterbegin",i)),n.lastElementChild instanceof HTMLSpanElement?s=n.lastElementChild:(s=document.createElement("span"),i.insertAdjacentElement("afterend",s)),s.innerHTML=void 0===r?e:r,this.elt.appendChild(n),i},t.remove=function(e){for(const r of t._getOptionsArray())if(r.value===e)return void(h(r.parentElement)?r.parentElement.remove():r.remove())},t.value=function(){let e="";for(const r of t._getOptionsArray())if(r.checked){e=r.value;break}return e},t.selected=function(e){let r=null;if(void 0===e){for(const e of t._getOptionsArray())if(e.checked){r=e;break}}else{t._getOptionsArray().forEach((e=>{e.checked=!1,e.removeAttribute("checked")}));for(const i of t._getOptionsArray())i.value===e&&(i.setAttribute("checked",!0),i.checked=!0,r=i)}return r},t.disable=function(e=!0){for(const r of t._getOptionsArray())r.setAttribute("disabled",e)},t},t.createColorPicker=function(t){const i=document.createElement("input");let n;i.type="color",t?t instanceof e.Color?i.value=t.toString("#rrggbb"):(this.push(),this.colorMode("rgb"),i.value=this.color(t).toString("#rrggbb"),this.pop()):i.value="#000000",n=r(i,this);const s=this;return n.color=function(){s.push(),t&&t.mode&&s.colorMode(t.mode,...t?.maxes&&t.maxes[t.mode]||[]);const e=s.color(this.elt.value);return s.pop(),e},n},t.createInput=function(e="",t="text"){let i=document.createElement("input");return i.setAttribute("value",e),i.setAttribute("type",t),r(i,this)},t.createFileInput=function(t,i=!1){if(!(window.File&&window.FileReader&&window.FileList&&window.Blob))return void e._friendlyError("The File APIs are not fully supported in this browser. Cannot create element.","createFileInput");const n=document.createElement("input");return n.setAttribute("type","file"),i&&n.setAttribute("multiple",!0),n.addEventListener("change",(function(e){for(const r of e.target.files)wn._load(r,t)}),!1),r(n,this)}}function xh(e,t,r){r.presetup=function(){const e=["deviceorientation","devicemotion"];for(const t of e)window.addEventListener(t,this[`_on${t}`].bind(this),{passive:!1,signal:this._removeSignal});this.deviceOrientation="undefined"!=typeof window&&window.innerWidth/window.innerHeight>1?"landscape":"portrait"},t.deviceOrientation="landscape",t.accelerationX=0,t.accelerationY=0,t.accelerationZ=0,t.pAccelerationX=0,t.pAccelerationY=0,t.pAccelerationZ=0,t._updatePAccelerations=function(){this.pAccelerationX=this.accelerationX,this.pAccelerationY=this.accelerationY,this.pAccelerationZ=this.accelerationZ},t.rotationX=0,t.rotationY=0,t.rotationZ=0,t.pRotationX=0,t.pRotationY=0,t.pRotationZ=0;let i=0,n=0,s=0,a="clockwise",o="clockwise",h="clockwise";t.pRotateDirectionX=void 0,t.pRotateDirectionY=void 0,t.pRotateDirectionZ=void 0,t._updatePRotations=function(){this.pRotationX=this.rotationX,this.pRotationY=this.rotationY,this.pRotationZ=this.rotationZ},t.turnAxis=void 0;let u=.5,l=30;t.setMoveThreshold=function(e){u=e},t.setShakeThreshold=function(e){l=e},t._ondeviceorientation=function(e){this._updatePRotations(),this.rotationX=this._fromDegrees(e.beta),this.rotationY=this._fromDegrees(e.gamma),this.rotationZ=this._fromDegrees(e.alpha),this._handleMotion()},t._ondevicemotion=function(e){this._updatePAccelerations(),this.accelerationX=2*e.acceleration.x,this.accelerationY=2*e.acceleration.y,this.accelerationZ=2*e.acceleration.z,this._handleMotion()},t._handleMotion=function(){if("landscape-primary"===screen.orientation.type||"landscape-secondary"===screen.orientation.type?this.deviceOrientation="landscape":"portrait-primary"===screen.orientation.type||"portrait-secondary"===screen.orientation.type?this.deviceOrientation="portrait":this.deviceOrientation="undefined","function"==typeof this._customActions.deviceMoved&&(Math.abs(this.accelerationX-this.pAccelerationX)>u||Math.abs(this.accelerationY-this.pAccelerationY)>u||Math.abs(this.accelerationZ-this.pAccelerationZ)>u)&&this._customActions.deviceMoved(),"function"==typeof this._customActions.deviceTurned){const e=this._toDegrees(this.rotationX)+180,t=this._toDegrees(this.pRotationX)+180;let r=i+180;e-t>0&&e-t<270||e-t<-270?a="clockwise":(e-t<0||e-t>270)&&(a="counter-clockwise"),a!==this.pRotateDirectionX&&(r=e),Math.abs(e-r)>90&&Math.abs(e-r)<270&&(r=e,this.turnAxis="X",this._customActions.deviceTurned()),this.pRotateDirectionX=a,i=r-180;const u=this._toDegrees(this.rotationY)+180,l=this._toDegrees(this.pRotationY)+180;let c=n+180;u-l>0&&u-l<270||u-l<-270?o="clockwise":(u-l<0||u-this.pRotationY>270)&&(o="counter-clockwise"),o!==this.pRotateDirectionY&&(c=u),Math.abs(u-c)>90&&Math.abs(u-c)<270&&(c=u,this.turnAxis="Y",this._customActions.deviceTurned()),this.pRotateDirectionY=o,n=c-180;const p=this._toDegrees(this.rotationZ),d=this._toDegrees(this.pRotationZ);p-d>0&&p-d<270||p-d<-270?h="clockwise":(p-d<0||p-d>270)&&(h="counter-clockwise"),h!==this.pRotateDirectionZ&&(s=p),Math.abs(p-s)>90&&Math.abs(p-s)<270&&(s=p,this.turnAxis="Z",this._customActions.deviceTurned()),this.pRotateDirectionZ=h,this.turnAxis=void 0}if("function"==typeof this._customActions.deviceShaken){let e,t;null!==this.pAccelerationX&&(e=Math.abs(this.accelerationX-this.pAccelerationX),t=Math.abs(this.accelerationY-this.pAccelerationY)),e+t>l&&this._customActions.deviceShaken()}}}function vh(e,t,r){r.presetup=function(){const e=["keydown","keyup","keypress","blur"];for(const t of e)window.addEventListener(t,this[`_on${t}`].bind(this),{passive:!1,signal:this._removeSignal})},t.keyIsPressed=!1,t.key="",t.code="",t.keyCode=0,t._onkeydown=function(e){if(!this._downKeys[e.code]&&(this.keyIsPressed=!0,this.keyCode=e.which,this.key=e.key,this.code=e.code,this._downKeyCodes[e.code]=!0,this._downKeys[e.key]=!0,"function"==typeof this._customActions.keyPressed&&!e.charCode)){!1===this._customActions.keyPressed(e)&&e.preventDefault()}},t._onkeyup=function(e){if("function"==typeof this._customActions.keyReleased){!1===this._customActions.keyReleased(e)&&e.preventDefault()}if(delete this._downKeyCodes[e.code],delete this._downKeys[e.key],this._areDownKeys()){const e=Object.keys(this._downKeyCodes).pop();this.code=e;const t=Object.keys(this._downKeys).pop();this.key=t}else this.keyIsPressed=!1,this.key="",this.code=""},t._onkeypress=function(e){if((e.which!==this._lastKeyCodeTyped||!e.repeat)&&(this._lastKeyCodeTyped=e.which,this.key=e.key||String.fromCharCode(e.which)||e.which,"function"==typeof this._customActions.keyTyped)){!1===this._customActions.keyTyped(e)&&e.preventDefault()}},t._onblur=function(e){this._downKeys={}},t.keyIsDown=function(e){return function(e){return!["Alt","Shift","Control","Meta"].includes(e)&&"string"==typeof e&&e.length>1}(e)?this._downKeyCodes[e]||this._downKeys[e]||!1:this._downKeys[e]||this._downKeyCodes[e]||!1},t._areDownKeys=function(){for(const e in this._downKeys)if(this._downKeys.hasOwnProperty(e)&&!0===this._downKeys[e])return!0;return!1}}function bh(e,t,r){function i(e,t,r,i){const n=e.getBoundingClientRect();return{x:(i.clientX-n.left)/t,y:(i.clientY-n.top)/r,winX:i.clientX,winY:i.clientY,id:i.pointerId}}r.presetup=function(){const e=["pointerdown","pointerup","pointercancel","pointermove","dragend","dragover","click","dblclick","wheel"];for(const t of e)window.addEventListener(t,this[`_on${t}`].bind(this),{passive:!1,signal:this._removeSignal});window.addEventListener("blur",(()=>{this.mouseIsPressed=!1}),{signal:this._removeSignal})},t.movedX=0,t.movedY=0,t._hasMouseInteracted=!1,t.mouseX=0,t.mouseY=0,t.pmouseX=0,t.pmouseY=0,t.winMouseX=0,t.winMouseY=0,t.pwinMouseX=0,t.pwinMouseY=0,t.mouseButton={left:!1,right:!1,center:!1},t.touches=[],t._activePointers=new Map,t.mouseIsPressed=!1,t._updatePointerCoords=function(e){if(null!==this._curElement){const t=this._curElement.elt,r=t.scrollWidth/this.width||1,n=t.scrollHeight/this.height||1;if("touch"===e.pointerType){const e=[];for(const s of this._activePointers.values())e.push(i(t,r,n,s));this.touches=e}const s=function(e,t,r,i){const n=e.getBoundingClientRect();return{x:(i.clientX-n.left)/t,y:(i.clientY-n.top)/r,winX:i.clientX,winY:i.clientY}}(t,r,n,e);this.movedX=e.movementX||0,this.movedY=e.movementY||0,this.mouseX=s.x,this.mouseY=s.y,this.winMouseX=s.winX,this.winMouseY=s.winY,this._hasMouseInteracted||(this._updateMouseCoords(),this._hasMouseInteracted=!0)}},t._updateMouseCoords=function(){this.pmouseX=this.mouseX,this.pmouseY=this.mouseY,this.pwinMouseX=this.winMouseX,this.pwinMouseY=this.winMouseY,this._pmouseWheelDeltaY=this._mouseWheelDeltaY},t._setMouseButton=function(e){this.mouseButton.left=Array.from(this._activePointers.values()).some((e=>!!(1&e.buttons))),this.mouseButton.center=Array.from(this._activePointers.values()).some((e=>!!(4&e.buttons))),this.mouseButton.right=Array.from(this._activePointers.values()).some((e=>!!(2&e.buttons)))},t._onpointermove=function(e){let t;this._updatePointerCoords(e),this._activePointers.set(e.pointerId,e),this._setMouseButton(e),this.mouseIsPressed&&0===e.buttons&&this._onpointerup(e),this.mouseIsPressed||"function"!=typeof this._customActions.mouseMoved?this.mouseIsPressed&&"function"==typeof this._customActions.mouseDragged&&(t=this._customActions.mouseDragged(e),!1===t&&e.preventDefault()):(t=this._customActions.mouseMoved(e),!1===t&&e.preventDefault())},t._onpointerdown=function(e){let t;this.mouseIsPressed=!0,this._activePointers.set(e.pointerId,e),this._setMouseButton(e),this._updatePointerCoords(e),"function"==typeof this._customActions.mousePressed&&(t=this._customActions.mousePressed(e),!1===t&&e.preventDefault())},t._onpointerup=function(e){let t;this.mouseIsPressed=!1,this._activePointers.delete(e.pointerId),this._setMouseButton(e),this._updatePointerCoords(e),"function"==typeof this._customActions.mouseReleased&&(t=this._customActions.mouseReleased(e),!1===t&&e.preventDefault())},t._ondragend=t._onpointerup,t._ondragover=t._onpointermove,t._onpointercancel=function(e){this._activePointers.delete(e.pointerId),this._setMouseButton(e),this._updatePointerCoords(e),0===this._activePointers.size&&(this.mouseIsPressed=!1)},t._onclick=function(e){if("function"==typeof this._customActions.mouseClicked){!1===this._customActions.mouseClicked(e)&&e.preventDefault()}},t._ondblclick=function(e){if("function"==typeof this._customActions.doubleClicked){!1===this._customActions.doubleClicked(e)&&e.preventDefault()}},t._mouseWheelDeltaY=0,t._pmouseWheelDeltaY=0,t._onwheel=function(e){if(this._mouseWheelDeltaY=e.deltaY,"function"==typeof this._customActions.mouseWheel){e.delta=e.deltaY;!1===this._customActions.mouseWheel(e)&&e.preventDefault()}},t.requestPointerLock=function(){const t=this._curElement.elt;return t.requestPointerLock=t.requestPointerLock||t.mozRequestPointerLock,t.requestPointerLock?(t.requestPointerLock(),!0):(e._friendlyError("requestPointerLock is not implemented in this browser","requestPointerLock"),!1)},t.exitPointerLock=function(){document.exitPointerLock()}}void 0!==p5&&mh(0,p5.prototype),void 0!==p5&&gh(p5,p5.prototype),void 0!==p5&&yh(p5,p5.prototype),void 0!==p5&&xh(0,p5.prototype),void 0!==p5&&vh(0,p5.prototype),void 0!==p5&&bh(p5,p5.prototype);class _h{constructor(e){this.columns=[],this.rows=[]}toString(e=","){let t=this.rows.map((e=>e.arr));return this.columns.some((e=>null===e))||(t=[this.columns,...t]),function(e,t={},r=e=>e){const i=Object.create(null);if(i.options=t,i.options.eof=void 0===i.options.eof||i.options.eof,i.row=1,i.col=1,i.output="",i.options.delimiter=void 0===i.options.delimiter?'"':t.delimiter,i.options.delimiter.length>1||0===i.options.delimiter.length)throw Error(`CSVError: delimiter must be one character [${i.options.separator}]`);if(i.options.separator=void 0===i.options.separator?",":t.separator,i.options.separator.length>1||0===i.options.separator.length)throw Error(`CSVError: separator must be one character [${i.options.separator}]`);const n=new RegExp(`${Bs(i.options.delimiter)}|${Bs(i.options.separator)}|\r\n|\n|\r`);return e.forEach(((t,s)=>{let a="";switch(i.col=1,t.forEach(((e,s)=>{"string"==typeof e&&(e=e.replace(new RegExp(i.options.delimiter,"g"),`${i.options.delimiter}${i.options.delimiter}`),e=n.test(e)?`${i.options.delimiter}${e}${i.options.delimiter}`:e),a+=r(e,i.row,i.col),s!==t.length-1&&(a+=i.options.separator),i.col++})),!0){case i.options.eof:case!i.options.eof&&s!==e.length-1:i.output+=`${a}\n`;break;default:i.output+=`${a}`}i.row++})),i.output}(t,{separator:e})}addRow(e){const t=e||new p5.TableRow;if(void 0===t.arr||void 0===t.obj)throw new Error(`invalid TableRow: ${t}`);return t.table=this,this.rows.push(t),t}removeRow(e){this.rows[e].table=null;const t=this.rows.splice(e+1,this.rows.length);this.rows.pop(),this.rows=this.rows.concat(t)}getRow(e){return this.rows[e]}getRows(){return this.rows}findRow(e,t){if("string"==typeof t){for(let r=0;r=0))throw new Error(`This table has no column named "${e}"`);n=r[e],t[n]=r}else t[s]=this.rows[s].obj;return t}getArray(){const e=[];for(let t=0;t=0))throw new Error(`This table has no column named "${e}"`);this.obj[e]=t,this.arr[r]=t}else{if(!(e{let t=-1/0;for(let r of e)t=Math.max(t,r);return t};return e[0]instanceof Array?t(e[0]):t(e)},t.min=function(...e){const t=e=>{let t=1/0;for(let r of e)t=Math.min(t,r);return t};return e[0]instanceof Array?t(e[0]):t(e)},t.norm=function(e,t,r){return this.map(e,t,r,0,1)},t.pow=Math.pow,t.round=function(e,t){if(!t)return Math.round(e);const r=Math.pow(10,t);return Math.round(e*r)/r},t.sq=e=>e*e,t.sqrt=Math.sqrt,t.fract=function(e){let t=0,r=Number(e);if(isNaN(r)||Math.abs(r)===1/0)return r;if(r<0&&(r=-r,t=1),String(r).includes(".")&&!String(r).includes("e")){let e=String(r);return e=Number("0"+e.slice(e.indexOf("."))),Math.abs(t-e)}return r<1?Math.abs(t-r):0}}function Dh(e,t){const r=4095;let i=4,n=.5;const s=e=>.5*(1-Math.cos(e*Math.PI));let a;t.noise=function(e,t=0,o=0){if(null==a){a=new Array(4096);for(let e=0;e<4096;e++)a[e]=Math.random()}e<0&&(e=-e),t<0&&(t=-t),o<0&&(o=-o);let h,u,l,c,p,d=Math.floor(e),f=Math.floor(t),m=Math.floor(o),g=e-d,y=t-f,x=o-m,v=0,b=.5;for(let e=0;e=1&&(d++,g--),y>=1&&(f++,y--),x>=1&&(m++,x--)}return v},t.noiseDetail=function(e,t=.5){e>0&&(i=e),t>0&&(n=t)},t._getNoiseOctaves=function(){return i},t._getNoiseAmpFalloff=function(){return n},t.noiseSeed=function(e){const t=(()=>{const e=4294967296;let t,r;return{setSeed(i){r=t=(null==i?Math.random()*e:i)>>>0},getSeed:()=>t,rand:()=>(r=(1664525*r+1013904223)%e,r/e)}})();t.setSeed(e),a=new Array(4096);for(let e=0;e<4096;e++)a[e]=t.rand()}}function Sh(e,t){const r="_lcg_random_state",i=4294967296;let n=0;t._lcg=function(e){return this[e]=(1664525*this[e]+1013904223)%i,this[e]/i},t._lcgSetSeed=function(e,t){this[e]=(null==t?Math.random()*i:t)>>>0},t.randomSeed=function(e){this._lcgSetSeed(r,e),this._gaussian_previous=!1},t.random=function(e,t){let i;if(i=null!=this[r]?this._lcg(r):Math.random(),void 0===e)return i;if(void 0===t)return e instanceof Array?e[Math.floor(i*e.length)]:i*e;if(e>t){const r=e;e=t,t=r}return i*(t-e)+e},t.randomGaussian=function(e,t=1){let r,i,s,a;if(this._gaussian_previous)r=n,this._gaussian_previous=!1;else{do{i=this.random(2)-1,s=this.random(2)-1,a=i*i+s*s}while(a>=1);a=Math.sqrt(-2*Math.log(a)/a),r=i*a,n=s*a,this._gaussian_previous=!0}return r*t+(e||0)}}function Th(e,t){t.createVector=function(...t){return this instanceof e?(this._boundFromRadians||(this._boundFromRadians=this._fromRadians.bind(this),this._boundToRadians=this._toRadians.bind(this)),new e.Vector(this._boundFromRadians,this._boundToRadians,...t)):new e.Vector(...t)},t.createMatrix=function(...t){return new e.Matrix(...t)}}function Fh(e){return function(...t){return 0===t.length?(this.constructor._friendlyError("In 1.x, createVector() was a shortcut for createVector(0, 0, 0). In 2.x, p5.js has vectors of any dimension, so you must provide your desired number of zeros. Use createVector(0, 0) for a 2D vector and createVector(0, 0, 0) for a 3D vector.","p5.createVector"),e.call(this,0,0,0)):(Array.isArray(t[0])&&(t=t[0]),e.call(this,...t))}}function kh(e){return function(t){return function(...r){if(0===r.length)return this;if(r[0]instanceof Nn?r=r[0].values:(Array.isArray(r[0])||1===r.length&&e)&&(r=r[0]),Array.isArray(r))for(let e=0;et.int(e,r))):void 0},t.str=function(e){return e instanceof Array?e.map(t.str):String(e)},t.boolean=function(e){return"number"==typeof e?0!==e:"string"==typeof e?"true"===e.toLowerCase():"boolean"==typeof e?e:e instanceof Array?e.map(t.boolean):void 0},t.byte=function(e){const r=t.int(e,10);return"number"==typeof r?(r+128)%256-128:r instanceof Array?r.map(t.byte):void 0},t.char=function(e){return"number"!=typeof e||isNaN(e)?e instanceof Array?e.map(t.char):"string"==typeof e?t.char(parseInt(e,10)):void 0:String.fromCharCode(e)},t.unchar=function(e){return"string"==typeof e&&1===e.length?e.charCodeAt(0):e instanceof Array?e.map(t.unchar):void 0},t.hex=function(e,r){if(r=null==r?r=8:r,e instanceof Array)return e.map((e=>t.hex(e,r)));if(e===1/0||e===-1/0){return(e===1/0?"F":"0").repeat(r)}if("number"==typeof e){e<0&&(e=4294967295+e+1);let t=Number(e).toString(16).toUpperCase();for(;t.length=r&&(t=t.substring(t.length-r,t.length)),t}},t.unhex=function(e){return e instanceof Array?e.map(t.unhex):parseInt(`0x${e}`,16)}}function Bh(e,t){function r(e,t,r){let i=e<0;e=Math.abs(e);let[n,s]=e.toString().split(".");if(void 0===r){n=n.padStart(t,"0");let e=s?n+"."+s:n;return i?"-"+e:e}{let a=e.toFixed(r);[n,s]=a.toString().split("."),n=n.padStart(t,"0");let o=void 0===s?n:n+"."+s;return i?"-"+o:o}}function i(e,t){const r=(e=e.toString()).indexOf(".");let i=-1!==r?e.substring(r):"",n=-1!==r?e.substring(0,r):e;if(n=n.toString().replace(/\B(?=(\d{3})+(?!\d))/g,","),0===t)i="";else if(void 0!==t)if(t>i.length){i+=-1===r?".":"";const e=t-i.length+1;for(let t=0;t0?`+${e.toString()}`:e.toString()}function s(e){return parseFloat(e)>=0?` ${e.toString()}`:e.toString()}t.nf=function(e,t,i){if(e instanceof Array)return e.map((e=>r(e,t,i)));return"[object Arguments]"===Object.prototype.toString.call(e)?3===e.length?this.nf(e[0],e[1],e[2]):2===e.length?this.nf(e[0],e[1]):this.nf(e[0]):r(e,t,i)},t.nfc=function(e,t){return e instanceof Array?e.map((e=>i(e,t))):i(e,t)},t.nfp=function(...e){const r=t.nf.apply(this,e);return r instanceof Array?r.map(n):n(r)},t.nfs=function(...e){const r=t.nf.apply(this,e);return r instanceof Array?r.map(s):s(r)},t.splitTokens=function(e,t){let r;if(void 0!==t){let e=t;const i=/\]/g.exec(e);let n=/\[/g.exec(e);n&&i?(e=e.slice(0,i.index)+e.slice(i.index+1),n=/\[/g.exec(e),e=e.slice(0,n.index)+e.slice(n.index+1),r=new RegExp(`[\\[${e}\\]]`,"g")):i?(e=e.slice(0,i.index)+e.slice(i.index+1),r=new RegExp(`[${e}\\]]`,"g")):n?(e=e.slice(0,n.index)+e.slice(n.index+1),r=new RegExp(`[${e}\\[]`,"g")):r=new RegExp(`[${e}]`,"g")}else r=/\s/g;return e.split(r).filter((e=>e))},t.shuffle=function(e,t){const r=ArrayBuffer&&ArrayBuffer.isView&&ArrayBuffer.isView(e);let i,n,s=(e=t||r?e:e.slice()).length;for(;s>1;)i=this.random(0,1)*s|0,n=e[--s],e[s]=e[i],e[i]=n;return e}}function Lh(e,t){t.day=function(){return(new Date).getDate()},t.hour=function(){return(new Date).getHours()},t.minute=function(){return(new Date).getMinutes()},t.millis=function(){return-1===this._millisStart?0:window.performance.now()-this._millisStart},t.month=function(){return(new Date).getMonth()+1},t.second=function(){return(new Date).getSeconds()},t.year=function(){return(new Date).getFullYear()}}function Oh(e,t){t.orbitControl=function(e,t,r,i){this._assert3d("orbitControl");const n=this._renderer.states.curCamera;void 0===e&&(e=1),void 0===t&&(t=e),void 0===r&&(r=1),"object"!=typeof i&&(i={}),!0!==this.contextMenuDisabled&&(this.canvas.oncontextmenu=()=>!1,this.contextMenuDisabled=!0),!0!==this.wheelDefaultDisabled&&(this.canvas.onwheel=()=>!1,this.wheelDefaultDisabled=!0);const{disableTouchActions:s=!0}=i;!0!==this.touchActionsDisabled&&s&&(this.canvas.style["touch-action"]="none",this.touchActionsDisabled=!0);const{freeRotation:a=!1}=i,o=[];this.touches.forEach((e=>{this._renderer.prevTouches.forEach((t=>{if(e.id===t.id){const r={x:e.x,y:e.y,px:t.x,py:t.y};o.push(r)}}))})),this._renderer.prevTouches=this.touches;let h=0,u=0,l=0,c=0,p=0;const d=.85,f=this.height0){if(m=o[0].x>0&&o[0].x0&&o[0].y0?m&&(this._renderer.executeRotateAndMove=!0,this._renderer.executeZoom=!0):(this._renderer.executeRotateAndMove=!1,this._renderer.executeZoom=!1)}else m=this.mouseX>0&&this.mouseX0&&this.mouseY.001?(a?n._orbitFree(0,0,this._renderer.zoomVelocity):n._orbit(0,0,this._renderer.zoomVelocity),0!==n.projMatrix.mat4[15]&&(n.projMatrix.mat4[0]*=Math.pow(10,-this._renderer.zoomVelocity),n.projMatrix.mat4[5]*=Math.pow(10,-this._renderer.zoomVelocity),this._renderer.states.setValue("uPMatrix",this._renderer.states.uPMatrix.clone()),this._renderer.states.uPMatrix.mat4[0]=n.projMatrix.mat4[0],this._renderer.states.uPMatrix.mat4[5]=n.projMatrix.mat4[5]),this._renderer.zoomVelocity*=d):this._renderer.zoomVelocity=0,0===u&&0===l||!this._renderer.executeRotateAndMove||this._renderer.rotateVelocity.add(.6*u,.6*l,0),this._renderer.rotateVelocity.magSq()>1e-6?(a?n._orbitFree(-this._renderer.rotateVelocity.x,this._renderer.rotateVelocity.y,0):n._orbit(this._renderer.rotateVelocity.x,this._renderer.rotateVelocity.y,0),this._renderer.rotateVelocity.mult(d)):this._renderer.rotateVelocity.set(0,0,0),(0!==c||0!==p)&&this._renderer.executeRotateAndMove){const e=2*c/this.width,t=2*-p/this.height;this._renderer.moveVelocity.add(.15*e,.15*t)}if(this._renderer.moveVelocity.magSq()>1e-6){const e=n._getLocalAxes(),t=n.eyeX-n.centerX,r=n.eyeY-n.centerY,i=n.eyeZ-n.centerZ,s=Math.sqrt(t*t+r*r+i*i);let a,o,h=new Nn(n.centerX,n.centerY,n.centerZ);h=n.cameraMatrix.multiplyPoint(h),h=this._renderer.states.uPMatrix.multiplyAndNormalizePoint(h),h.x-=this._renderer.moveVelocity.x,h.y-=this._renderer.moveVelocity.y;const u=this._renderer.states.uPMatrix.mat4;0===u[15]?(a=(u[8]+h.x)/u[0]*s,o=(u[9]+h.y)/u[5]*s):(a=(h.x-u[12])/u[0],o=(h.y-u[13])/u[5]),n.setPosition(n.eyeX+a*e.x[0]+o*e.y[0],n.eyeY+a*e.x[1]+o*e.y[1],n.eyeZ+a*e.x[2]+o*e.y[2]),this._renderer.moveVelocity.mult(d)}else this._renderer.moveVelocity.set(0,0);return this},t.debugMode=function(...t){this._assert3d("debugMode");for(let t=e.lifecycleHooks.postdraw.length-1;t>=0;t--)e.lifecycleHooks.postdraw[t].toString()!==this._grid().toString()&&e.lifecycleHooks.postdraw[t].toString()!==this._axesIcon().toString()||e.lifecycleHooks.postdraw.splice(t,1);t[0]===Oe?e.lifecycleHooks.postdraw.push(this._grid(t[1],t[2],t[3],t[4],t[5])):t[0]===Pe?e.lifecycleHooks.postdraw.push(this._axesIcon(t[1],t[2],t[3],t[4])):(e.lifecycleHooks.postdraw.push(this._grid(t[0],t[1],t[2],t[3],t[4])),e.lifecycleHooks.postdraw.push(this._axesIcon(t[5],t[6],t[7],t[8])))},t.noDebugMode=function(){this._assert3d("noDebugMode");for(let t=e.lifecycleHooks.postdraw.length-1;t>=0;t--)e.lifecycleHooks.postdraw[t].toString()!==this._grid().toString()&&e.lifecycleHooks.postdraw[t].toString()!==this._axesIcon().toString()||e.lifecycleHooks.postdraw.splice(t,1)},t._grid=function(e,t,r,i,n){void 0===e&&(e=this.width/2),void 0===t&&(t=Math.round(e/30)<4?4:Math.round(e/30)),void 0===r&&(r=0),void 0===i&&(i=0),void 0===n&&(n=0);const s=e/t,a=e/2;return function(){this.push(),this.stroke(255*this._renderer.states.curStrokeColor[0],255*this._renderer.states.curStrokeColor[1],255*this._renderer.states.curStrokeColor[2]),this._renderer.states.setValue("uModelMatrix",this._renderer.states.uModelMatrix.clone()),this._renderer.states.uModelMatrix.reset();for(let e=0;e<=t;e++)this.beginShape(this.LINES),this.vertex(-a+r,i,e*s-a+n),this.vertex(+a+r,i,e*s-a+n),this.endShape();for(let e=0;e<=t;e++)this.beginShape(this.LINES),this.vertex(e*s-a+r,i,-a+n),this.vertex(e*s-a+r,i,+a+n),this.endShape();this.pop()}},t._axesIcon=function(e,t,r,i){return void 0===e&&(e=this.width/20>40?this.width/20:40),void 0===t&&(t=-this.width/4),void 0===r&&(r=t),void 0===i&&(i=t),()=>{this.push(),this._renderer.states.setValue("uModelMatrix",this._renderer.states.uModelMatrix.clone()),this._renderer.states.uModelMatrix.reset(),this.strokeWeight(2),this.stroke(255,0,0),this.beginShape(this.LINES),this.vertex(t,r,i),this.vertex(t+e,r,i),this.endShape(),this.stroke(0,255,0),this.beginShape(this.LINES),this.vertex(t,r,i),this.vertex(t,r+e,i),this.endShape(),this.stroke(0,0,255),this.beginShape(this.LINES),this.vertex(t,r,i),this.vertex(t,r,i+e),this.endShape(),this.pop()}}}async function Ph(e){try{return(await fetch(e,{method:"HEAD"})).ok}catch(e){return!1}}function Nh(e,t){async function r(e){let t=null,r={};const{data:i}=await Os(e,"text"),n=i.split("\n");for(let e=0;e0)if("usemtl"===h[0])s=h[1];else if("v"===h[0]||"vn"===h[0]){const e=new Nn(parseFloat(h[1]),parseFloat(h[2]),parseFloat(h[3]));i[h[0]].push(e)}else if("vt"===h[0]){const e=[parseFloat(h[1]),1-parseFloat(h[2])];i[h[0]].push(e)}else if("f"===h[0])for(let t=3;t0&&(t-=1),c[e]=t}if(n[l]||(n[l]={}),void 0===n[l][s]){const t=e.vertices.length;if(e.vertices.push(i.v.at(c[0]).copy()),e.uvs.push(i.vt.at(c[1])?i.vt.at(c[1]).slice():[0,0]),e.vertexNormals.push(i.vn.at(c[2])?i.vn.at(c[2]).copy():new Nn(0,0,0)),n[l][s]=t,o.push(t),s&&r[s]&&r[s].diffuseColor){a=!0;const t=r[s].diffuseColor;e.vertexColors.push(t[0]),e.vertexColors.push(t[1]),e.vertexColors.push(t[2]),e.vertexColors.push(1)}else e.vertexColors.push(-1,-1,-1,-1)}else o.push(n[l][s])}o[0]!==o[1]&&o[0]!==o[2]&&o[1]!==o[2]&&e.faces.push(o)}}return 0===e.vertexNormals.length&&e.computeNormals(),a||(e.vertexColors=[]),e}function n(e,t){if(function(e){const t=new DataView(e),r=[115,111,108,105,100];for(let e=0;e<5;e++)if(s(r,t,e))return!1;return!0}(t))!function(e,t){const r=new DataView(t),i=r.getUint32(80,!0);let n,s,a,o,h,u,l,c=!1;for(let e=0;e<70;e++)1129270351===r.getUint32(e,!1)&&82===r.getUint8(e+4)&&61===r.getUint8(e+5)&&(c=!0,o=[],h=r.getUint8(e+6)/255,u=r.getUint8(e+7)/255,l=r.getUint8(e+8)/255);const p=84,d=50;for(let t=0;t>5&31)/31,a=(e>>10&31)/31)}const y=new Nn(f,m,g);for(let t=1;t<=3;t++){const h=i+12*t,u=new Nn(r.getFloat32(h,!0),r.getFloat32(h+4,!0),r.getFloat32(h+8,!0));e.vertices.push(u),e.vertexNormals.push(y),c&&o.push(n,s,a)}e.faces.push([3*t,3*t+1,3*t+2]),e.uvs.push([0,0],[0,0],[0,0])}}(e,t);else{const r=new DataView(t);if(!("TextDecoder"in window))return console.warn("Sorry, ASCII STL loading only works in browsers that support TextDecoder (https://caniuse.com/#feat=textencoder)"),e;!function(e,t){let r,i,n="",s=[];for(let a=0;a(n(c,e),a&&c.normalize(),u&&c.flipU(),l&&c.flipV(),c._makeTriangleEdges(),o?o(c):c);return this._internal?this._internal(r):r()}if(s.match(/\.obj$/i)){const{data:e}=await Os(t,"text"),n=e.split("\n"),s=await async function(e){const i=[];for(let n of e){const e=n.match(/^mtllib (.+)/);if(e){let n="";const s=e[1],a=t.split("/");if(a.length>1){a.pop();const e=a.join("/");n=e+"/"+s}else n=s;i.push(Ph(n).then((e=>e?r(n):(console.warn(`MTL file not found or error in parsing; proceeding without materials: ${n}`),{}))).catch((e=>(console.warn(`Error loading MTL file: ${n}`,e),{}))))}}try{const e=await Promise.all(i);return Object.assign({},...e)}catch(e){return{}}}(n),h=()=>(i(c,n,s),a&&c.normalize(),u&&c.flipU(),l&&c.flipV(),c._makeTriangleEdges(),o?o(c):c);return this._internal?this._internal(h):h()}}catch(r){if(e._friendlyFileLoadError(3,t),h)return h(r);throw r}},t.model=function(e,t=1){this._assert3d("model"),this._renderer.model(e,t)};let a=0;t.createModel=function(t,r=" ",s){let o,h,u=!1,l=!1,c=!1;s&&"object"==typeof s?(u=s.normalize||!1,o=s.successCallback,h=s.failureCallback,l=s.flipU||!1,c=s.flipV||!1):"boolean"==typeof s?(u=s,o=arguments[3],h=arguments[4]):(o="function"==typeof arguments[2]?arguments[2]:void 0,h=arguments[3]);const p=new e.Geometry;if(p.gid=`${r}|${u}|${a++}`,r.match(/\.stl$/i))try{n(p,(new TextEncoder).encode(t).buffer)}catch(t){return void(h?h(t):e._friendlyError("Error during parsing: "+t.message))}else if(r.match(/\.obj$/i))try{i(p,t.split("\n"))}catch(t){return void(h?h(t):e._friendlyError("Error during parsing: "+t.message))}else e._friendlyFileLoadError(3,t),h?h():e._friendlyError("Sorry, the file type is invalid. Only OBJ and STL files are supported.");return u&&p.normalize(),l&&p.flipU(),c&&p.flipV(),p._makeTriangleEdges(),"function"==typeof o&&o(p),p}}void 0!==p5&&Eh(p5),void 0!==p5&&Ah(0,p5.prototype),void 0!==p5&&Dh(0,p5.prototype),void 0!==p5&&Sh(0,p5.prototype),void 0!==p5&&Th(p5,p5.prototype),void 0!==p5&&Ih(0,p5.prototype),void 0!==p5&&Bh(0,p5.prototype),void 0!==p5&&Lh(0,p5.prototype),void 0!==p5&&Oh(p5,p5.prototype),void 0!==p5&&Nh(p5,p5.prototype);var Rh={};Object.defineProperty(Rh,"__esModule",{value:!0});var Vh=function(){function e(){}return e.parse=function(t){for(var r=new Set,i=0,n=t;i=0;)e[t]=0}jh(new Array(576));jh(new Array(60));jh(new Array(512));jh(new Array(256));jh(new Array(29));jh(new Array(30));var Gh=(e,t,r,i)=>{let n=65535&e,s=e>>>16&65535,a=0;for(;0!==r;){a=r>2e3?2e3:r,r-=a;do{n=n+t[i++]|0,s=s+n|0}while(--a);n%=65521,s%=65521}return n|s<<16};const $h=new Uint32Array((()=>{let e,t=[];for(var r=0;r<256;r++){e=r;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e}return t})());var Hh=(e,t,r,i)=>{const n=$h,s=i+r;e^=-1;for(let r=i;r>>8^n[255&(e^t[r])];return~e},qh={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},Wh={Z_NO_FLUSH:0,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_DEFLATED:8};const Xh=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var Yh=function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const r=t.shift();if(r){if("object"!=typeof r)throw new TypeError(r+"must be non-object");for(const t in r)Xh(r,t)&&(e[t]=r[t])}}return e},Zh=e=>{let t=0;for(let r=0,i=e.length;r=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;Jh[254]=Jh[254]=1;var Qh=e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,r,i,n,s,a=e.length,o=0;for(n=0;n>>6,t[s++]=128|63&r):r<65536?(t[s++]=224|r>>>12,t[s++]=128|r>>>6&63,t[s++]=128|63&r):(t[s++]=240|r>>>18,t[s++]=128|r>>>12&63,t[s++]=128|r>>>6&63,t[s++]=128|63&r);return t},eu=(e,t)=>{const r=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let i,n;const s=new Array(2*r);for(n=0,i=0;i4)s[n++]=65533,i+=a-1;else{for(t&=2===a?31:3===a?15:7;a>1&&i1?s[n++]=65533:t<65536?s[n++]=t:(t-=65536,s[n++]=55296|t>>10&1023,s[n++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&Kh)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let r="";for(let i=0;i{(t=t||e.length)>e.length&&(t=e.length);let r=t-1;for(;r>=0&&128==(192&e[r]);)r--;return r<0||0===r?t:r+Jh[e[r]]>t?r:t};var ru=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const iu=16209;var nu=function(e,t){let r,i,n,s,a,o,h,u,l,c,p,d,f,m,g,y,x,v,b,_,w,C,E,A;const D=e.state;r=e.next_in,E=e.input,i=r+(e.avail_in-5),n=e.next_out,A=e.output,s=n-(t-e.avail_out),a=n+(e.avail_out-257),o=D.dmax,h=D.wsize,u=D.whave,l=D.wnext,c=D.window,p=D.hold,d=D.bits,f=D.lencode,m=D.distcode,g=(1<>>24,p>>>=v,d-=v,v=x>>>16&255,0===v)A[n++]=65535&x;else{if(!(16&v)){if(64&v){if(32&v){D.mode=16191;break e}e.msg="invalid literal/length code",D.mode=iu;break e}x=f[(65535&x)+(p&(1<>>=v,d-=v),d<15&&(p+=E[r++]<>>24,p>>>=v,d-=v,v=x>>>16&255,16&v){if(_=65535&x,v&=15,do){e.msg="invalid distance too far back",D.mode=iu;break e}if(p>>>=v,d-=v,v=n-s,_>v){if(v=_-v,v>u&&D.sane){e.msg="invalid distance too far back",D.mode=iu;break e}if(w=0,C=c,0===l){if(w+=h-v,v2;)A[n++]=C[w++],A[n++]=C[w++],A[n++]=C[w++],b-=3;b&&(A[n++]=C[w++],b>1&&(A[n++]=C[w++]))}else{w=n-_;do{A[n++]=A[w++],A[n++]=A[w++],A[n++]=A[w++],b-=3}while(b>2);b&&(A[n++]=A[w++],b>1&&(A[n++]=A[w++]))}break}if(64&v){e.msg="invalid distance code",D.mode=iu;break e}x=m[(65535&x)+(p&(1<>3,r-=b,d-=b<<3,p&=(1<{const h=o.bits;let u,l,c,p,d,f,m=0,g=0,y=0,x=0,v=0,b=0,_=0,w=0,C=0,E=0,A=null;const D=new Uint16Array(16),S=new Uint16Array(16);let T,F,k,M=null;for(m=0;m<=su;m++)D[m]=0;for(g=0;g=1&&0===D[x];x--);if(v>x&&(v=x),0===x)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(y=1;y0&&(0===e||1!==x))return-1;for(S[1]=0,m=1;m852||2===e&&C>592)return 1;for(;;){T=m-_,a[g]+1=f?(F=M[a[g]-f],k=A[a[g]-f]):(F=96,k=0),u=1<>_)+l]=T<<24|F<<16|k}while(0!==l);for(u=1<>=1;if(0!==u?(E&=u-1,E+=u):E=0,g++,0==--D[m]){if(m===x)break;m=t[r+a[g]]}if(m>v&&(E&p)!==c){for(0===_&&(_=v),d+=y,b=m-_,w=1<852||2===e&&C>592)return 1;c=E&p,n[c]=v<<24|b<<16|d-s}}return 0!==E&&(n[d+E]=m-_<<24|64<<16),o.bits=v,0};const{Z_FINISH:cu,Z_BLOCK:pu,Z_TREES:du,Z_OK:fu,Z_STREAM_END:mu,Z_NEED_DICT:gu,Z_STREAM_ERROR:yu,Z_DATA_ERROR:xu,Z_MEM_ERROR:vu,Z_BUF_ERROR:bu,Z_DEFLATED:_u}=Wh,wu=16180,Cu=16190,Eu=16191,Au=16192,Du=16194,Su=16199,Tu=16200,Fu=16206,ku=16209,Mu=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function Iu(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const Bu=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode16211?1:0},Lu=e=>{if(Bu(e))return yu;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=wu,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,fu},Ou=e=>{if(Bu(e))return yu;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,Lu(e)},Pu=(e,t)=>{let r;if(Bu(e))return yu;const i=e.state;return t<0?(r=0,t=-t):(r=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?yu:(null!==i.window&&i.wbits!==t&&(i.window=null),i.wrap=r,i.wbits=t,Ou(e))},Nu=(e,t)=>{if(!e)return yu;const r=new Iu;e.state=r,r.strm=e,r.window=null,r.mode=wu;const i=Pu(e,t);return i!==fu&&(e.state=null),i};let Ru,Vu,Uu=!0;const zu=e=>{if(Uu){Ru=new Int32Array(512),Vu=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(lu(1,e.lens,0,288,Ru,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;lu(2,e.lens,0,32,Vu,0,e.work,{bits:5}),Uu=!1}e.lencode=Ru,e.lenbits=9,e.distcode=Vu,e.distbits=5},ju=(e,t,r,i)=>{let n;const s=e.state;return null===s.window&&(s.wsize=1<=s.wsize?(s.window.set(t.subarray(r-s.wsize,r),0),s.wnext=0,s.whave=s.wsize):(n=s.wsize-s.wnext,n>i&&(n=i),s.window.set(t.subarray(r-i,r-i+n),s.wnext),(i-=n)?(s.window.set(t.subarray(r-i,r),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whave{let r,i,n,s,a,o,h,u,l,c,p,d,f,m,g,y,x,v,b,_,w,C,E=0;const A=new Uint8Array(4);let D,S;const T=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(Bu(e)||!e.output||!e.input&&0!==e.avail_in)return yu;r=e.state,r.mode===Eu&&(r.mode=Au),a=e.next_out,n=e.output,h=e.avail_out,s=e.next_in,i=e.input,o=e.avail_in,u=r.hold,l=r.bits,c=o,p=h,C=fu;e:for(;;)switch(r.mode){case wu:if(0===r.wrap){r.mode=Au;break}for(;l<16;){if(0===o)break e;o--,u+=i[s++]<>>8&255,r.check=Hh(r.check,A,2,0),u=0,l=0,r.mode=16181;break}if(r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&u)<<8)+(u>>8))%31){e.msg="incorrect header check",r.mode=ku;break}if((15&u)!==_u){e.msg="unknown compression method",r.mode=ku;break}if(u>>>=4,l-=4,w=8+(15&u),0===r.wbits&&(r.wbits=w),w>15||w>r.wbits){e.msg="invalid window size",r.mode=ku;break}r.dmax=1<>8&1),512&r.flags&&4&r.wrap&&(A[0]=255&u,A[1]=u>>>8&255,r.check=Hh(r.check,A,2,0)),u=0,l=0,r.mode=16182;case 16182:for(;l<32;){if(0===o)break e;o--,u+=i[s++]<>>8&255,A[2]=u>>>16&255,A[3]=u>>>24&255,r.check=Hh(r.check,A,4,0)),u=0,l=0,r.mode=16183;case 16183:for(;l<16;){if(0===o)break e;o--,u+=i[s++]<>8),512&r.flags&&4&r.wrap&&(A[0]=255&u,A[1]=u>>>8&255,r.check=Hh(r.check,A,2,0)),u=0,l=0,r.mode=16184;case 16184:if(1024&r.flags){for(;l<16;){if(0===o)break e;o--,u+=i[s++]<>>8&255,r.check=Hh(r.check,A,2,0)),u=0,l=0}else r.head&&(r.head.extra=null);r.mode=16185;case 16185:if(1024&r.flags&&(d=r.length,d>o&&(d=o),d&&(r.head&&(w=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Uint8Array(r.head.extra_len)),r.head.extra.set(i.subarray(s,s+d),w)),512&r.flags&&4&r.wrap&&(r.check=Hh(r.check,i,d,s)),o-=d,s+=d,r.length-=d),r.length))break e;r.length=0,r.mode=16186;case 16186:if(2048&r.flags){if(0===o)break e;d=0;do{w=i[s+d++],r.head&&w&&r.length<65536&&(r.head.name+=String.fromCharCode(w))}while(w&&d>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=Eu;break;case 16189:for(;l<32;){if(0===o)break e;o--,u+=i[s++]<>>=7&l,l-=7&l,r.mode=Fu;break}for(;l<3;){if(0===o)break e;o--,u+=i[s++]<>>=1,l-=1,3&u){case 0:r.mode=16193;break;case 1:if(zu(r),r.mode=Su,t===du){u>>>=2,l-=2;break e}break;case 2:r.mode=16196;break;case 3:e.msg="invalid block type",r.mode=ku}u>>>=2,l-=2;break;case 16193:for(u>>>=7&l,l-=7&l;l<32;){if(0===o)break e;o--,u+=i[s++]<>>16^65535)){e.msg="invalid stored block lengths",r.mode=ku;break}if(r.length=65535&u,u=0,l=0,r.mode=Du,t===du)break e;case Du:r.mode=16195;case 16195:if(d=r.length,d){if(d>o&&(d=o),d>h&&(d=h),0===d)break e;n.set(i.subarray(s,s+d),a),o-=d,s+=d,h-=d,a+=d,r.length-=d;break}r.mode=Eu;break;case 16196:for(;l<14;){if(0===o)break e;o--,u+=i[s++]<>>=5,l-=5,r.ndist=1+(31&u),u>>>=5,l-=5,r.ncode=4+(15&u),u>>>=4,l-=4,r.nlen>286||r.ndist>30){e.msg="too many length or distance symbols",r.mode=ku;break}r.have=0,r.mode=16197;case 16197:for(;r.have>>=3,l-=3}for(;r.have<19;)r.lens[T[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,D={bits:r.lenbits},C=lu(0,r.lens,0,19,r.lencode,0,r.work,D),r.lenbits=D.bits,C){e.msg="invalid code lengths set",r.mode=ku;break}r.have=0,r.mode=16198;case 16198:for(;r.have>>24,y=E>>>16&255,x=65535&E,!(g<=l);){if(0===o)break e;o--,u+=i[s++]<>>=g,l-=g,r.lens[r.have++]=x;else{if(16===x){for(S=g+2;l>>=g,l-=g,0===r.have){e.msg="invalid bit length repeat",r.mode=ku;break}w=r.lens[r.have-1],d=3+(3&u),u>>>=2,l-=2}else if(17===x){for(S=g+3;l>>=g,l-=g,w=0,d=3+(7&u),u>>>=3,l-=3}else{for(S=g+7;l>>=g,l-=g,w=0,d=11+(127&u),u>>>=7,l-=7}if(r.have+d>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=ku;break}for(;d--;)r.lens[r.have++]=w}}if(r.mode===ku)break;if(0===r.lens[256]){e.msg="invalid code -- missing end-of-block",r.mode=ku;break}if(r.lenbits=9,D={bits:r.lenbits},C=lu(1,r.lens,0,r.nlen,r.lencode,0,r.work,D),r.lenbits=D.bits,C){e.msg="invalid literal/lengths set",r.mode=ku;break}if(r.distbits=6,r.distcode=r.distdyn,D={bits:r.distbits},C=lu(2,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,D),r.distbits=D.bits,C){e.msg="invalid distances set",r.mode=ku;break}if(r.mode=Su,t===du)break e;case Su:r.mode=Tu;case Tu:if(o>=6&&h>=258){e.next_out=a,e.avail_out=h,e.next_in=s,e.avail_in=o,r.hold=u,r.bits=l,nu(e,p),a=e.next_out,n=e.output,h=e.avail_out,s=e.next_in,i=e.input,o=e.avail_in,u=r.hold,l=r.bits,r.mode===Eu&&(r.back=-1);break}for(r.back=0;E=r.lencode[u&(1<>>24,y=E>>>16&255,x=65535&E,!(g<=l);){if(0===o)break e;o--,u+=i[s++]<>v)],g=E>>>24,y=E>>>16&255,x=65535&E,!(v+g<=l);){if(0===o)break e;o--,u+=i[s++]<>>=v,l-=v,r.back+=v}if(u>>>=g,l-=g,r.back+=g,r.length=x,0===y){r.mode=16205;break}if(32&y){r.back=-1,r.mode=Eu;break}if(64&y){e.msg="invalid literal/length code",r.mode=ku;break}r.extra=15&y,r.mode=16201;case 16201:if(r.extra){for(S=r.extra;l>>=r.extra,l-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=16202;case 16202:for(;E=r.distcode[u&(1<>>24,y=E>>>16&255,x=65535&E,!(g<=l);){if(0===o)break e;o--,u+=i[s++]<>v)],g=E>>>24,y=E>>>16&255,x=65535&E,!(v+g<=l);){if(0===o)break e;o--,u+=i[s++]<>>=v,l-=v,r.back+=v}if(u>>>=g,l-=g,r.back+=g,64&y){e.msg="invalid distance code",r.mode=ku;break}r.offset=x,r.extra=15&y,r.mode=16203;case 16203:if(r.extra){for(S=r.extra;l>>=r.extra,l-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=ku;break}r.mode=16204;case 16204:if(0===h)break e;if(d=p-h,r.offset>d){if(d=r.offset-d,d>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=ku;break}d>r.wnext?(d-=r.wnext,f=r.wsize-d):f=r.wnext-d,d>r.length&&(d=r.length),m=r.window}else m=n,f=a-r.offset,d=r.length;d>h&&(d=h),h-=d,r.length-=d;do{n[a++]=m[f++]}while(--d);0===r.length&&(r.mode=Tu);break;case 16205:if(0===h)break e;n[a++]=r.length,h--,r.mode=Tu;break;case Fu:if(r.wrap){for(;l<32;){if(0===o)break e;o--,u|=i[s++]<Nu(e,15),inflateInit2:Nu,inflate:Gu,inflateEnd:e=>{if(Bu(e))return yu;let t=e.state;return t.window&&(t.window=null),e.state=null,fu},inflateGetHeader:(e,t)=>{if(Bu(e))return yu;const r=e.state;return 2&r.wrap?(r.head=t,t.done=!1,fu):yu},inflateSetDictionary:(e,t)=>{const r=t.length;let i,n,s;return Bu(e)?yu:(i=e.state,0!==i.wrap&&i.mode!==Cu?yu:i.mode===Cu&&(n=1,n=Gh(n,t,r,0),n!==i.check)?xu:(s=ju(e,t,r,r),s?(i.mode=16210,vu):(i.havedict=1,fu)))},inflateInfo:"pako inflate (from Nodeca project)"};var Hu=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const qu=Object.prototype.toString,{Z_NO_FLUSH:Wu,Z_FINISH:Xu,Z_OK:Yu,Z_STREAM_END:Zu,Z_NEED_DICT:Ku,Z_STREAM_ERROR:Ju,Z_DATA_ERROR:Qu,Z_MEM_ERROR:el}=Wh;function tl(e){this.options=Yh({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(15&t.windowBits||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new ru,this.strm.avail_out=0;let r=$u.inflateInit2(this.strm,t.windowBits);if(r!==Yu)throw new Error(qh[r]);if(this.header=new Hu,$u.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=Qh(t.dictionary):"[object ArrayBuffer]"===qu.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(r=$u.inflateSetDictionary(this.strm,t.dictionary),r!==Yu)))throw new Error(qh[r])}tl.prototype.push=function(e,t){const r=this.strm,i=this.options.chunkSize,n=this.options.dictionary;let s,a,o;if(this.ended)return!1;for(a=t===~~t?t:!0===t?Xu:Wu,"[object ArrayBuffer]"===qu.call(e)?r.input=new Uint8Array(e):r.input=e,r.next_in=0,r.avail_in=r.input.length;;){for(0===r.avail_out&&(r.output=new Uint8Array(i),r.next_out=0,r.avail_out=i),s=$u.inflate(r,a),s===Ku&&n&&(s=$u.inflateSetDictionary(r,n),s===Yu?s=$u.inflate(r,a):s===Qu&&(s=Ku));r.avail_in>0&&s===Zu&&r.state.wrap>0&&0!==e[r.next_in];)$u.inflateReset(r),s=$u.inflate(r,a);switch(s){case Ju:case Qu:case Ku:case el:return this.onEnd(s),this.ended=!0,!1}if(o=r.avail_out,r.next_out&&(0===r.avail_out||s===Zu))if("string"===this.options.to){let e=tu(r.output,r.next_out),t=r.next_out-e,n=eu(r.output,e);r.next_out=t,r.avail_out=i-t,t&&r.output.set(r.output.subarray(e,e+t),0),this.onData(n)}else this.onData(r.output.length===r.next_out?r.output:r.output.subarray(0,r.next_out));if(s!==Yu||0!==o){if(s===Zu)return s=$u.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===r.avail_in)break}}return!0},tl.prototype.onData=function(e){this.chunks.push(e)},tl.prototype.onEnd=function(e){e===Yu&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=Zh(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var rl={inflate:function(e,t){const r=new tl(t);if(r.push(e),r.err)throw r.msg||qh[r.err];return r.result}};const{inflate:il}=rl;const nl={inflate:il};var sl,al={};function ol(e){const t=[];for(let r=0;r>8&255,e[t+1]=255&r},readUshorts:function(e,t,r){for(var i=[],n=0;n>24&255,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r},readUint64:function(e,t){return 4294967296*al.B.readUint(e,t)+al.B.readUint(e,t+4)},readASCII:function(e,t,r){for(var i="",n=0;n255?-1:al.T.CFF.glyphByUnicode(e,al.T.CFF.tableSE[t])},readCharset:function(e,t,r){var i=al.B,n=[".notdef"],s=e[t];if(t++,0==s)for(var a=0;a>4,f=15&p;if(15!=d&&c.push(d),15!=f&&c.push(f),15==f)break}for(var m="",g=[0,1,2,3,4,5,6,7,8,9,".","e","e-","reserved","-","endOfNumber"],y=0;y>>1;r.searchRange=n(e,t),t+=2,r.entrySelector=n(e,t),t+=2,r.rangeShift=n(e,t),t+=2,r.endCount=s(e,t,u),t+=2*u,t+=2,r.startCount=s(e,t,u),t+=2*u,r.idDelta=[];for(var l=0;l>1),r},parse6:function(e,t,r){var i=al.B;t+=2,i.readUshort(e,t),t+=2,i.readUshort(e,t),t+=2,r.firstCode=i.readUshort(e,t),t+=2;var n=i.readUshort(e,t);t+=2,r.glyphIdArray=[];for(var s=0;s=a.xMax||a.yMin>=a.yMax)return null;if(a.noc>0){a.endPts=[];for(var o=0;o>>8;0==(l&=15)&&(t=s.readFormat0(e,t,o))}return o},parseV1:function(e,t,r,i){var n=al.B,s=al.T.kern;n.readFixed(e,t);var a=n.readUint(e,t+4);t+=8;for(var o={glyph1:[],rval:[]},h=0;h>4),O=[];for(g=0;g>1+(15&I),R=P&(1<<1+(15&I))-1;O.push(C[N][R])}return[v,O]}},al.U=function(){var e=function(e,t,r){e.cmds.push("M"),e.crds.push(t,r)},t=function(e,t,r){e.cmds.push("L"),e.crds.push(t,r)},r=function(e,t,r,i,n,s,a){e.cmds.push("C"),e.crds.push(t,r,i,n,s,a)},i=function(e,t,r,i,n){e.cmds.push("Q"),e.crds.push(t,r,i,n)},n=function(e){e.cmds.push("Z")};function s(e,t,r,i){var n=t[r],s=t[r+1],a=e.kern;if(a){var o=a.glyph1.indexOf(n);if(-1!=o){var h=a.rval[o].glyph2.indexOf(s);if(-1!=h)return[0,0,a.rval[o].vals[h],0]}}return[0,0,0,0]}function a(e,t,r){for(var i=0,n=~~(e.length/t);i+1!=n;){var s=i+(n-i>>>1);e[s*t]<=r?i=s:n=s}return i*t}for(var o,h,u=[9,10,11,12,13,32,133,160,5760,6158,8232,8233,8239,8288,12288,65279],l={},c=0;c=o.map.length?0:o.map[t];else if(4==h){var c=o.endCount;if(u=0,t<=c[c.length-1]){var p=a(c,1,t);if(c[p]=o.startCount[p]){u=65535&(0!=o.idRangeOffset[p]?o.glyphIdArray[t-o.startCount[p]+(o.idRangeOffset[p]>>1)-(o.idRangeOffset.length-p)]:t+o.idDelta[p])}}}else if(6==h){var d=t-o.firstCode,f=o.glyphIdArray;u=d<0||d>=f.length?0:f[d]}else{if(12!=h)throw"unknown cmap table format "+o.format;var m=o.groups;u=0,t<=m[m.length-2]&&m[s=a(m,3,t)]<=t&&t<=m[s+1]&&(u=m[s+2]+(t-m[s]))}var g=e["SVG "],y=e.loca;return 0==u||null!=e["CFF "]||null!=g&&null!=g.entries[u]||!y||y[u]!=y[u+1]||null!=l[t]||(u=0),u}function d(e,t,r,i){var n={cmds:[],crds:[]};e.fvar&&(null==i&&(i=e.fvar[1][e._index][2]),i=g(e,i));var s=e["SVG "],a=e["CFF "],o=e.COLR,h=e.CBLC,u=e.CBDT,l=e.sbix,c=window.UPNG,p=null;if(h&&c)for(var m=0;m1){function U(e){var t=e.toString(16);return(1==t.length?"0":"")+t}var k=e.CPAL,M=o[0]["g"+t];for(m=0;m-1?function(r,s,a,o,h){var u=r.xs,l=r.ys;if(s.fvar&&h){u=u.slice(0),l=l.slice(0);for(var c=s.gvar,p=c?c[a]:null,d=0;dn[a]||n[a]>s[a]||i[a]<0&&s[a]>0&&0!=n[a]||0==n[a]?1:t[a]s[a]?0:t[a]==n[a]?1:t[a]h?(l-h)/(u-h):0,i&&-1!=s[a]){for(var c=i[a],p=0;p=s[a]);p+=2);var d=(s[a]-c[p-2])/(c[p]-c[p-2]);s[a]=d*c[p+1]+(1-d)*c[p-1]}}return s}function y(e,t,r,i,n){var s=r.length,a=new Array(2*s+8);a.fill(0);for(var o=0;od||y>=s||(f=g,-1==m&&(m=g))}for(g=0;gd||y>=s)&&(y>1,s=r>>1,a=new Uint8Array(n*s*4),o=new Uint32Array(e.buffer),h=new Uint32Array(a.buffer),u=0;u>>24,x=f>>>24,v=m>>>24,b=g>>>24,_=y+x+v+b;if(1020==_){var w=(d>>>0&255)+(f>>>0&255)+(m>>>0&255)+(g>>>0&255)+2>>>2,C=(d>>>8&255)+(f>>>8&255)+(m>>>8&255)+(g>>>8&255)+2>>>2,E=(d>>>16&255)+(f>>>16&255)+(m>>>16&255)+(g>>>16&255)+2>>>2;h[c]=255<<24|E<<16|C<<8|w}else if(0==_)h[c]=0;else{var A=1/_;w=~~((w=(d>>>0&255)*y+(f>>>0&255)*x+(m>>>0&255)*v+(g>>>0&255)*b)*A+.5),C=~~((C=(d>>>8&255)*y+(f>>>8&255)*x+(m>>>8&255)*v+(g>>>8&255)*b)*A+.5),E=~~((E=(d>>>16&255)*y+(f>>>16&255)*x+(m>>>16&255)*v+(g>>>16&255)*b)*A+.5),h[c]=_+2>>>2<<24|E<<16|C<<8|w}}return{buff:a,w:n,h:s}}function v(i,s,a,o,h){for(var u=s.stack,l=s.nStems,c=s.haveWidth,p=s.width,d=s.open,f=0,m=s.x,g=s.y,y=0,x=0,b=0,_=0,w=0,C=0,E=0,A=0,D=0,S=0,T=al.T.CFF,F=o.nominalWidthX,k={val:0,size:0};f>1,u.length=0,c=!0;else if("o3"==M||"o23"==M){u.length%2!=0&&!c&&(p=u.shift()+F),l+=u.length>>1,u.length=0,c=!0}else if("o4"==M)u.length>1&&!c&&(p=u.shift()+F,c=!0),d&&n(h),g+=u.pop(),e(h,m,g),d=!0;else if("o5"==M)for(;u.length>0;)m+=u.shift(),g+=u.shift(),t(h,m,g);else if("o6"==M||"o7"==M)for(var I=u.length,B="o6"==M,L=0;LMath.abs(A-g)?m=E+u.shift():g=A+u.shift(),r(h,y,x,b,_,D,S),r(h,w,C,E,A,m,g));else if("o14"==M){if(u.length>0&&4!=u.length&&!c&&(p=u.shift()+a.nominalWidthX,c=!0),4==u.length){var N=u.shift(),R=u.shift(),V=u.shift(),U=u.shift(),z=T.glyphBySE(a,V),j=T.glyphBySE(a,U);v(a.CharStrings[z],s,a,o,h),s.x=N,s.y=R,v(a.CharStrings[j],s,a,o,h)}d&&(n(h),d=!1)}else if("o19"==M||"o20"==M){u.length%2!=0&&!c&&(p=u.shift()+F),l+=u.length>>1,u.length=0,c=!0,f+=l+7>>3}else if("o21"==M)u.length>2&&!c&&(p=u.shift()+F,c=!0),g+=u.pop(),m+=u.pop(),d&&n(h),e(h,m,g),d=!0;else if("o22"==M)u.length>1&&!c&&(p=u.shift()+F,c=!0),m+=u.pop(),d&&n(h),e(h,m,g),d=!0;else if("o25"==M){for(;u.length>6;)m+=u.shift(),g+=u.shift(),t(h,m,g);y=m+u.shift(),x=g+u.shift(),b=y+u.shift(),_=x+u.shift(),m=b+u.shift(),g=_+u.shift(),r(h,y,x,b,_,m,g)}else if("o26"==M)for(u.length%2&&(m+=u.shift());u.length>0;)y=m,x=g+u.shift(),m=b=y+u.shift(),g=(_=x+u.shift())+u.shift(),r(h,y,x,b,_,m,g);else if("o27"==M)for(u.length%2&&(g+=u.shift());u.length>0;)x=g,b=(y=m+u.shift())+u.shift(),_=x+u.shift(),m=b+u.shift(),r(h,y,x,b,_,m,g=_);else if("o10"==M||"o29"==M){var G="o10"==M?o:a;if(0==u.length)console.log("error: empty stack");else{var $=u.pop(),H=G.Subrs[$+G.Bias];s.x=m,s.y=g,s.nStems=l,s.haveWidth=c,s.width=p,s.open=d,v(H,s,a,o,h),m=s.x,g=s.y,l=s.nStems,c=s.haveWidth,p=s.width,d=s.open}}else if("o30"==M||"o31"==M){var q=u.length,W=(P=0,"o31"==M);for(P+=q-(I=-3&q);P65535&&o++,a.push(p(e,h))}var u=[];for(o=0;o=0&&t.push(" "),t.push(s),r=a}return t.join("")}(s)},SVGToPath:function(e){var t={cmds:[],crds:[]};return al.U.SVG.svgToPath(e,t),{cmds:t.cmds,crds:t.crds}},pathToContext:function(e,t){for(var r=0,i=e.cmds,n=e.crds,s=0;s>>2;A.writeASCII(i,I,T[0].split("").reverse().join("")),n[F+1]=T[1],n[F+2]=T[2],n[F+3]=T[3]}}var k=0;if(b&&e.fvar){var M=e.fvar[0];for(k=d.malloc(8*b.length),S=0;S>>2,A.writeASCII(i,I,M[S][0].split("").reverse().join("")),a[F+1]=b[S]}}b&&d.hb_font_set_variations(c,k,b.length),d.hb_buffer_set_direction(_,x?4:5),d.hb_buffer_guess_segment_properties(_),d.hb_shape(c,_,D,v?v.length:0);var B=function(e){for(var t=d.hb_buffer_get_length(e),r=[],i=d.hb_buffer_get_glyph_infos(e,0)>>>2,a=d.hb_buffer_get_glyph_positions(e,0)>>>2,o=0;o1e-4&&(e/=i,r/=i),{x:e,y:r}}const r=1-t;let i=3*this.D.x*Math.pow(t,2)-3*this.C.x*Math.pow(t,2)+6*this.C.x*r*t-6*this.B.x*r*t+3*this.B.x*Math.pow(r,2)-3*this.A.x*Math.pow(r,2),n=3*this.D.y*Math.pow(t,2)-3*this.C.y*Math.pow(t,2)+6*this.C.y*r*t-6*this.B.y*r*t+3*this.B.y*Math.pow(r,2)-3*this.A.y*Math.pow(r,2);const s=Math.hypot(i,n);return Math.abs(s)>1e-4&&(i/=s,n/=s),{x:i,y:n}}isLinear(){return this.A.x===this.B.x&&this.A.y===this.B.y&&this.C.x===this.D.x&&this.C.y===this.D.y}pointAtParameter(e){const t=Math.max(0,Math.min(1,e));return{x:Math.pow(1-t,3)*this.A.x+3*Math.pow(1-t,2)*t*this.B.x+3*(1-t)*Math.pow(t,2)*this.C.x+Math.pow(t,3)*this.D.x,y:Math.pow(1-t,3)*this.A.y+3*Math.pow(1-t,2)*t*this.B.y+3*(1-t)*Math.pow(t,2)*this.C.y+Math.pow(t,3)*this.D.y}}getTotalLength(){if(void 0===this._totalLength)if(this.isLinear())this._totalLength=Math.hypot(this.D.x-this.A.x,this.D.y-this.A.y);else{const e=Math.max(10,Math.ceil((Math.hypot(this.B.x-this.A.x,this.B.y-this.A.y)+Math.hypot(this.C.x-this.B.x,this.C.y-this.B.y)+Math.hypot(this.D.x-this.C.x,this.D.y-this.C.y))/hl.sampleSpacing())),t=ol(e).map((t=>this.pointAtParameter(t/(e-1))));let r=0;for(let e=1;ee.getTotalLength())),r=[0];for(let e=1;eMath.max(4,Math.ceil(e.getTotalLength()/hl.sampleSpacing())))),n=i.reduce(((e,t)=>e+t)),s=1/n/10,a=this._totalLength/n;this.samples.push({dist:0,pt:this.segments[0].A,tan:this.segments[0].tangentAtParameter(0),segIdx:0,t:0}),e.forEach(((e,t)=>{const n=i[t],o=ol(n+1).map((e=>e/n)),h=o.map((t=>e.pointAtParameter(t)));let u;for(let t=0;t<4;t++){u=ol(n).map((e=>Math.hypot(h[e+1].x-h[e].x,h[e+1].y-h[e].y)));const t=u.map((e=>e-a));let r=0;for(let i=1;i{l+=u[i],this.samples.push({dist:r[t]+l,pt:e,tan:this.segments[t].tangentAtParameter(o[i+1]),segIdx:t,t:o[i+1]})}))})),this._jumps=[],this.segmentStartEnds=[{start:0,end:0}];for(let e=1;ee)r=i-1;else{if(!(this.samples[i].dist=this._totalLength)return this.samples[this.samples.length-1].pt;const r=this.findClosestSampleIdx(e),i=this.samples[r].distthis.samples[i].segIdx){return{x:(1-n)*this.samples[r].pt.x+n*this.samples[i].pt.x,y:(1-n)*this.samples[r].pt.y+n*this.samples[i].pt.y}}if(this.samples[r].segIdx!==this.samples[i].segIdx){const e=1-this.samples[r].t+this.samples[i].t,t=e>0?(1-this.samples[r].t)/e:.5;if(n=this._totalLength)return this.samples[this.samples.length-1].tan;const r=this.findClosestSampleIdx(e),i=this.samples[r].distthis.samples[i].segIdx){let e=(1-n)*this.samples[r].tan.x+n*this.samples[i].tan.x,t=(1-n)*this.samples[r].tan.y+n*this.samples[i].tan.y;const s=Math.max(Math.hypot(e,t),1e-4);return e/=s,t/=s,{x:e,y:t}}if(this.samples[r].segIdx!==this.samples[i].segIdx){if(n<.5){const e=this.segments[this.samples[r].segIdx],t=2*n,i=(1-t)*this.samples[r].t+t;return e.tangentAtParameter(i)}{const e=this.segments[this.samples[i].segIdx],t=2*(n-.5)*this.samples[i].t;return e.tangentAtParameter(t)}}{const e=this.segments[this.samples[r].segIdx],t=(1-n)*this.samples[r].t+n*this.samples[i].t;return e.tangentAtParameter(t)}}}const ll={M:2,L:2,C:6,Q:4},cl=["ttf","otf","woff"],pl=new RegExp(`\\.(${cl.join("|")})`,"i"),dl=new RegExp(`([^/]+)(\\.(?:${cl.join("|")}))`,"i"),fl="Sorry, only TTF, OTF and WOFF files are supported.",ml=["weight","stretch","style"];class gl{constructor(e,t,r,i,n){if(!(t instanceof FontFace))throw Error("FontFace is required");this._pInst=e,this.name=r,this.path=i,this.data=n,this.face=t}static hasGlyphData(e){let{font:t}=e;return"object"==typeof t&&void 0!==t.data}fontBounds(e,t,r,i,n,s){({width:i,height:n,options:s}=this._parseArgs(i,n,s));let a=s?.graphics?._renderer||this._pInst._renderer;if(!a)throw Error("p5 or graphics required for fontBounds()");return a.fontBounds(e,t,r,i,n)}textBounds(e,t,r,i,n,s){({width:i,height:n,options:s}=this._parseArgs(i,n,s));let a=s?.graphics?._renderer||this._pInst._renderer;if(!a)throw Error("p5 or graphics required for fontBounds()");return a.textBounds(e,t,r,i,n)}textToPaths(e,t,r,i,n,s){if(({width:i,height:n,options:s}=this._parseArgs(i,n,s)),!this.data)throw Error('No font data available for "'+this.name+'"\nTry downloading a local copy of the font file');return this._lineateAndPathify(e,t,r,i,n,s).map((e=>e.glyphs)).flat().map((e=>e.path.commands)).flat()}textToPoints(e,t,r,i,n,s){return this.textToContours(e,t,r,i,n,s).reduce(((e,t)=>(e.push(...t),e)),[])}textToContours(e,t=0,r=0,i,n,s){({width:i,height:n,options:s}=this._parseArgs(i,n,s));const a=this.textToPaths(e,t,r,i,n,s),o=[];for(const e of a)"M"===e[0]&&o.push([]),o[o.length-1].push(e);return o.map((e=>function(e,t,r){const i=(e,t)=>{if("object"!=typeof e)e=t;else for(const r in t)void 0===e[r]&&(e[r]=t[r]);return e},n=(e,t)=>{const r=e.length;return e[t<0?t%r+r:t%r]},s=(e,t)=>{t=t||0;let r=0;for(let i=e.length-1;e.length>3&&i>=0;--i)a(n(e,i-1),n(e,i),n(e,i+1),t)&&(e.splice(i%e.length,1),r++);return r},a=(e,t,r,i)=>{if(!i)return 0===o(e,t,r);void 0===a.tmpPoint1&&(a.tmpPoint1=[],a.tmpPoint2=[]);const n=a.tmpPoint1,s=a.tmpPoint2;n.x=t.x-e.x,n.y=t.y-e.y,s.x=r.x-t.x,s.y=r.y-t.y;const h=n.x*s.x+n.y*s.y,u=Math.sqrt(n.x*n.x+n.y*n.y),l=Math.sqrt(s.x*s.x+s.y*s.y);return Math.acos(h/(u*l))(t[0]-e[0])*(r[1]-e[1])-(r[0]-e[0])*(t[1]-e[1]),h=(e=>{const t=e.slice();if(t.length<2)throw new Error(`Path doesn't have enough commands: ${JSON.stringify(t)}`);if("M"!==t[0].type)throw new Error(`Path starts with ${t[0].type} instead of M!`);let r={x:t[0].x,y:t[0].y},i=Object.assign({},r);const n=[];for(;t.length>0;){const e=t.shift();if("M"===e.type)i={x:e.x,y:e.y},r=i;else if("C"===e.type)n.push(new hl(r,{x:e.x1,y:e.y1},{x:e.x2,y:e.y2},{x:e.x,y:e.y})),r={x:e.x,y:e.y};else if("L"===e.type)e.x===r.x&&e.y===r.y||n.push(new hl(r,r,{x:e.x,y:e.y},{x:e.x,y:e.y})),r={x:e.x,y:e.y};else if("H"===e.type)e.x!==r.x&&n.push(new hl(r,r,{x:e.x,y:r.y},{x:e.x,y:r.y})),r={x:e.x,y:r.y};else if("V"===e.type)e.y!==r.y&&n.push(new hl(r,r,{x:r.x,y:e.y},{x:r.x,y:e.y})),r={x:r.x,y:e.y};else if("Q"===e.type)n.push(new hl(r,{x:r.x+2/3*(e.x1-r.x),y:r.y+2/3*(e.y1-r.y)},{x:e.x+2/3*(e.x1-e.x),y:e.y+2/3*(e.y1-e.y)},{x:e.x,y:e.y})),r={x:e.x,y:e.y};else{if("Z"!==e.type)throw new Error(`Unsupported path command ${e.type}; use only H, V, M, L, C, Z!`);Math.hypot(r.x-i.x,r.y-i.y)>0&&n.push(new hl(r,r,i,i))}}return new ul(n)})(_l(e));let u=i(t,{sampleFactor:.1,simplifyThreshold:0});const l=Math.max(1,Math.ceil(h.getTotalLength()*u.sampleFactor));let c=[];const p=r._pInst.angleMode(),d=r._pInst.DEGREES;for(let e=0;e{const e=this._pInst._renderer._validateFaces;this._pInst._renderer._validateFaces=!0,this._pInst.beginShape();for(const e of o){this._pInst.beginContour();for(const t of e)this._pInst.vertex(t.x,t.y,0);this._pInst.endContour(this._pInst.CLOSE)}this._pInst.endShape(this._pInst.CLOSE),this._pInst._renderer._validateFaces=e}));if(0===a)return h;const u={},l=e=>`${e.x.toFixed(6)}-${e.y.toFixed(6)}-${e.z.toFixed(6)}`,c=[],p=[];for(const e of h.vertices){const t=l(e);if(!(t in u)){const r=c.length;u[t]=r,c.push(e.copy())}p.push(u[t])}const d=h.faces.map((e=>e.map((e=>p[e])))),f={};for(const e of d)for(let t=0;t{})),y=.5*a;g.vertices=[],g.faces=[],g.edges=[];for(const[e,t]of m){const r=c[e],i=c[t],n=new Nn(i.x-r.x,i.y-r.y,i.z-r.z),s=new Nn(0,0,a),o=Nn.cross(n,s),h=n.mag();if(o.mag()<1e-4||h<1e-4)continue;const u=g.vertices.length;g.vertices.push(new Nn(r.x,r.y,r.z+y));const l=g.vertices.length;g.vertices.push(new Nn(i.x,i.y,i.z+y));const p=g.vertices.length;g.vertices.push(new Nn(r.x,r.y,r.z-y));const d=g.vertices.length;g.vertices.push(new Nn(i.x,i.y,i.z-y)),g.faces.push([u,p,d]),g.faces.push([u,d,l]),g.edges.push([u,l]),g.edges.push([p,d]),g.edges.push([u,p]),g.edges.push([l,d])}const x=g.vertices.length;for(const e of c)g.vertices.push(new Nn(e.x,e.y,e.z+y));for(const e of d){if(e.length<3)continue;const t=e.map((e=>e+x));g.faces.push(t);for(let e=0;ee+v));g.faces.push(t);for(let e=0;e{e[t.tag]=t.value}))}return ml.forEach((t=>{let r=this.face[t];"normal"!==r&&(e[t]=e[t]||r)})),e}metadata(){let e=this.data?.name||{};for(let t in this.face)/^load/.test(t)||(e[t]=e[t]||this.face[t]);return e}static async list(e=!1){if(e){console.log("There are",document.fonts.size,"font-faces\n");let e=0;for(let t of document.fonts.values()){console.log("FontFace: {");for(let e in t)console.log(" "+e+": "+t[e]);console.log("}\n"),"loaded"===t.status&&e++}console.log(e+" loaded")}return await Array.from(document.fonts)}_lineateAndPathify(e,t,r,i,n,s={}){let a=s?.graphics?._renderer||this._pInst._renderer;a.push(),a.textFont(this);let{lines:o,bounds:h}=a._computeBounds(Ma,e,t,r,i,n,{ignoreRectMode:!0,...s});o=this._position(a,o,h,i,n);let u=this.data?.head?.unitsPerEm||1e3,l=a.states.textSize/u;const c=this._currentAxes(a);let p=o.map((e=>this._lineToGlyphs(e,{scale:l,axs:c})));return a.pop(),p}_currentAxes(e){let t;if((this.data?.fvar?.length??0)>0){t=this.data.fvar[0].map((([t,r,i,n,s,a])=>{if(!e)return i;if("wght"===t)return e.states.fontWeight;if("wdth"===t)return 100;if(e.textCanvas().style.fontVariationSettings){const r=new RegExp(`\\b${t}s+(d+)`).exec(e.textCanvas().style.fontVariationSettings);return r?parseInt(r[1]):i}return i}))}return t}_textToPathPoints(e,t,r,i,n,s){({width:i,height:n,options:s}=this._parseArgs(i,n,s));let a=this.textToPaths(e,t,r,i,n,s);const o=(e,t,r,i)=>{if(fn.dist(t.x,t.y,r.x,r.y)>i){let n={x:(t.x+r.x)/2,y:(t.y+r.y)/2};e.push(n),o(e,t,n,i),o(e,n,r,i)}};let h=[],{textSize:u}=this._pInst._renderer.states,l=u/this.data.head.unitsPerEm*500;for(let e=0;e0&&o(h,h[h.length-1],e,l),h.push(e)}}return h}_parseArgs(e,t,r={}){return"object"==typeof e?(r=e,e=t=void 0):"object"==typeof t&&(r=t,t=void 0),{width:e,height:t,options:r}}_position(e,t,r,i,n){let{textAlign:s,textLeading:a}=e.states,o=this._measureTextDefault(e,"X").fontBoundingBoxAscent;return t.map(((t,h)=>{let u=r.x,l=r.y+h*a+o,c=e._fontWidthSingle(t);if(s===S?u+=(r.w-c)/2:s===A&&(u+=r.w-c),void 0!==i)switch(e.states.rectMode){case S:u-=i/2,l-=n/2;break;case E:u-=i,l-=n}return{text:t,x:u,y:l}}))}_lineToGlyphs(e,{scale:t=1,axs:r}={}){if(!this.data)throw Error('No font data available for "'+this.name+'"\nTry downloading a local copy of the font file');let i=al.U.shape(this.data,e.text,{axs:r});return e.glyphShapes=i,e.glyphs=this._shapeToPaths(i,e,{scale:t,axs:r}),e}_positionGlyphs(e,t){let r=t?.graphics?._renderer||this._pInst._renderer;const i=this._currentAxes(r),n=al.U.shape(this.data,e,{axs:i}),s=[];let a=0;for(const e of n)s.push({x:a,index:e.g,shape:e}),a+=e.ax;return s}_singleShapeToPath(e,{scale:t=1,x:r=0,y:i=0,lineX:n=0,lineY:s=0,axs:a}={}){let o=this.data,h=0,{g:u,ax:l,ay:c,dx:p,dy:d}=e,{crds:f,cmds:m}=al.U.glyphToPath(o,u,!0,a),g={path:{commands:[]}};for(let e=0;e{"M"===t?e.moveTo(...r):"L"===t?e.lineTo(...r):"C"===t?e.bezierCurveTo(...r):"Q"===t?e.quadraticCurveTo(...r):"Z"===t&&e.closePath()})),r?.fill&&e.fill(),r?.stroke&&e.stroke()}_pathsToCommands(e,t){let r=[];for(let i=0;i0){r=r||{};for(const[e,t,n,s,a,o]of i.fvar[0])"wght"===e?r.weight=`${t} ${s}`:"wdth"===e&&(r.stretch=`${t}% ${s}%`)}let s=new FontFace(e,n,r);if("error"===s.status)throw Error('Failed to create FontFace for "'+e+'"');return s}(t,r,i,n);return"loaded"!==s.status&&await s.load(),document.fonts.add(s),await document.fonts.ready,new gl(e,s,t,r,n)}function xl(e){return(e.startsWith('"')||e.startsWith("'"))&&e.at(0)===e.at(-1)?e.slice(1,-1).replace(/\/(['"])/g,"$1"):e}function vl(...e){let t,r,i,n,s=e.shift();"string"==typeof s&&0!==s.length||p5._friendlyError(fl,"p5.loadFont"),"string"==typeof e[0]&&(t=e.shift());for(let t=0;te.text())))}if(u){const e=new CSSStyleSheet;await e.replace(i);const r=[];for(const i of e.cssRules)if(i instanceof CSSFontFaceRule){const e=i.style;let n=xl(e.getPropertyValue("font-family"));const s=e.getPropertyValue("src"),a={...h||{}};for(const t of e){if("font-family"===t||"src"===t)continue;const r=t.replace(/^font-/,"").split("-").map(((e,t)=>0===t?e:`${e[0].toUpperCase()}${e.slice(1)}`)).join("");a[r]=e.getPropertyValue(t)}r.push({name:n,src:s,fontDescriptors:a,loadWithData:async()=>{let e;try{const r=/url\(([^\)]+)\)/.exec(s);if(r){let i=r[1];/^['"]/.exec(i)&&i.at(0)===i.at(-1)&&(i=i.slice(1,-1)),e=await t.parseFontData(i)}}catch(e){}return yl(this,n,s,a,e)},loadWithoutData:()=>yl(this,n,s,a)})}o=o||["latin"];const n=(o instanceof Array?o:[o]).map((e=>e.toLowerCase())),s=zh.filter((e=>n.some((t=>e.category.includes(t)&&e.category.includes("ext")===t.includes("ext"))))),a=new Set(Uh.parse(s.map((e=>`U+${e.hexrange[0]}-${e.hexrange[1]}`))));let u,l=0,c=0;for(const e of r){if(!e.fontDescriptors.unicodeRange)continue;const t=[...new Set(Uh.parse(e.fontDescriptors.unicodeRange.split(/,\s*/g))).values()].filter((e=>a.has(e))).length,r={style:"normal",weight:400,...h},i=Object.keys(e.fontDescriptors).filter((t=>e.fontDescriptors[t]===r[t])).length;(i>c||i===c&&t>=l)&&(c=i,l=t,u=e)}const p=u||r.at(-1);for(const e of r)e!==p&&e.loadWithoutData();return p?.loadWithData()}try{const e=await t.parseFontData(i);n=n||function(e,t){let r,i=e?.name;if(i){if(i.fullName)return i.fullName;i.familyName&&(r=i.familyName)}if(!r){let e=dl.exec(t);r=e&&e.length>=3?e[1]:t}return r.includes(" ")&&(r=r.replace(/ /g,"_")),r}(e,i),r=await yl(this,n,i,h,e)}catch(e){let t=n||i.substring(i.lastIndexOf("/")+1).replace(/\.[^/.]+$/,"");console.warn(`WARN: No glyph data for '${t}', retrying as FontFace`);try{r=await yl(this,t,i,h)}catch(e){if(a)return a(e);throw e}}const l=()=>s?s(r):r;return this._internal?this._internal(l):l()}}const _l=e=>e.map((e=>{const t=e[0];switch(t){case"Z":return{type:t};case"M":case"L":{const[,r,i]=e;return{type:t,x:r,y:i}}case"Q":{const[,r,i,n,s]=e;return{type:t,x1:r,y1:i,x:n,y:s}}case"C":{const[,r,i,n,s,a,o]=e;return{type:t,x1:r,y1:i,x2:n,y2:s,x:a,y:o}}default:throw new Error(`Unexpected path command: ${t}`)}}));function wl(e,t){Ua.prototype.maxCachedGlyphs=function(){return 200},gl.prototype._getFontInfo=function(e){this._fontInfos=this._fontInfos||{};const t=JSON.stringify(e);if(this._fontInfos[t]){return this._fontInfos[t]}{const r=new s(this,{axs:e});return this._fontInfos[t]=r,r}};class r{constructor(e,t){this.width=e,this.height=t,this.infos=[]}findImage(e){const t=this.width*this.height;if(e>t)throw new Error("font is too complex to render in 3D");let r,i;for(let n=this.infos.length-1;n>=0;--n){const s=this.infos[n];if(s.index+e=o||h>=u||!s.length)return this.glyphInfos[e.index]={};const l=o-a,c=u-h,p=_l(s);let d;const f=[],m=[],g=[];for(d=8;d>=0;--d)g.push([]);for(d=8;d>=0;--d)m.push([]);function y(e,t,r){const i=f.length;function n(e,t,r){for(let i=e.length;i-- >0;){const n=e[i];t>n&&(t=n),rr?r:e}(255*e,0,255)}class v{constructor(e,t,r,i){this.p0=e,this.c0=t,this.c1=r,this.p1=i}toQuadratic(){return{x:this.p0.x,y:this.p0.y,x1:this.p1.x,y1:this.p1.y,cx:(3*(this.c0.x+this.c1.x)-(this.p0.x+this.p1.x))/4,cy:(3*(this.c0.y+this.c1.y)-(this.p0.y+this.p1.y))/4}}quadError(){return Nn.sub(Nn.sub(this.p1,this.p0),Nn.mult(Nn.sub(this.c1,this.c0),3)).mag()/2}split(e){const t=Nn.lerp(this.p0,this.c0,e),r=Nn.lerp(this.c0,this.c1,e),i=Nn.lerp(t,r,e);this.c1=Nn.lerp(this.c1,this.p1,e),this.c0=Nn.lerp(r,this.c1,e);const n=Nn.lerp(i,this.c0,e),s=new v(this.p0,t,i,n);return this.p0=n,s}splitInflections(){const e=Nn.sub(this.c0,this.p0),t=Nn.sub(Nn.sub(this.c1,this.c0),e),r=Nn.sub(Nn.sub(Nn.sub(this.p1,this.c1),e),Nn.mult(t,2)),i=[];let n=t.x*r.y-t.y*r.x;if(0!==n){let s=e.x*r.y-e.y*r.x,a=e.x*t.y-e.y*t.x;const o=s*s-4*n*a;if(o>=0){n<0&&(n=-n,s=-s,a=-a);const e=Math.sqrt(o),t=(-s-e)/(2*n);let r=(-s+e)/(2*n);t>0&&t<1&&(i.push(this.split(t)),r=1-(1-r)/(1-t)),r>0&&r<1&&i.push(this.split(r))}}return i.push(this),i}}function b(e,t,r,i,s,a,o,h){const u=new v(new Nn(e,t),new Nn(r,i),new Nn(s,a),new Nn(o,h)).splitInflections(),l=[],c=30/n;for(let e of u){const t=[];let r;for(;r=c/e.quadError(),!(r>=.125);){const i=Math.pow(r,1/3),n=e.split(i),s=e.split(1-i/(1-i));l.push(n),t.push(e),e=s}r<1&&l.push(e.split(.5)),l.push(e),Array.prototype.push.apply(l,t.reverse())}return l}function _(e,t,r,i){y([e,r],[t,i],{x:e,y:t,cx:(e+r)/2,cy:(t+i)/2})}function w(e,t,r,i){return Math.abs(r-e)<1e-5&&Math.abs(i-t)<1e-5}let C,E,A,D;for(const e of p){const t=(e.x-a)/l,r=(e.y-h)/c;if(!w(C,E,t,r)){switch(e.type){case"M":A=t,D=r;break;case"L":_(C,E,t,r);break;case"Q":{const i=(e.x1-a)/l,n=(e.y1-h)/c;y([C,t,i],[E,r,n],{x:C,y:E,cx:i,cy:n});break}case"Z":w(C,E,A,D)?f.push({x:C,y:E}):(_(C,E,A,D),f.push({x:A,y:D}));break;case"C":{const i=b(C,E,(e.x1-a)/l,(e.y1-h)/c,(e.x2-a)/l,(e.y2-h)/c,t,r);for(let e=0;e>7,127&a,n>>7,127&n);for(let e=0;e>7,127&t,0,0)}}return{cellImageInfo:h,dimOffset:a,dimImageInfo:s}}return t=this.glyphInfos[e.index]={glyph:e,uGlyphRect:[a,h,o,u],strokeImageInfo:T,strokes:f,colInfo:k(g,this.colDimImageInfos,this.colCellImageInfos),rowInfo:k(m,this.rowDimImageInfos,this.rowCellImageInfos)},t.uGridOffset=[t.colInfo.dimOffset,t.rowInfo.dimOffset],t}}Ua.prototype._renderText=function(t,r,i,n,s){if(!this.states.textFont||"string"==typeof this.states.textFont)return void console.log("WEBGL: you must load and set a font before drawing text. See `loadFont` and `textFont` for more details.");if(i>=n||!this.states.fillColor)return;if(!e.Font.hasGlyphData(this.states.textFont))return void console.log("WEBGL: only Opentype (.otf) and Truetype (.ttf) fonts with glyph data are supported. Make sure to set the font using textFont() before drawing text.");this.push();const a=this.states.strokeColor,o=this.states.drawMode;this.states.setValue("strokeColor",null),this.states.setValue("drawMode",Ee);const{font:h}=this.states.textFont;if(!h)throw new Error("In WebGL mode, textFont() needs to be given the result of loadFont() instead of a font family name.");const u=h._currentAxes(this);let l=h._getFontInfo(u);const c={x:r,y:i},p=this.states.textSize/(h.data?.head?.unitsPerEm||1e3);this.translate(c.x,c.y,0),this.scale(p,p,1);const d=!this._defaultFontShader,f=this._getFontShader();f.init(),f.bindShader("text"),d&&(f.setUniform("uGridImageSize",[64,64]),f.setUniform("uCellsImageSize",[64,64]),f.setUniform("uStrokeImageSize",[64,64]),f.setUniform("uGridSize",[9,9]));const m=this.states.fillSet?this.states.curFillColor:[0,0,0,1];this._setGlobalUniforms(f),this._applyColorBlend(m);let g=this.geometryBufferCache.getGeometryByID("glyph");g||(g=this._textGeom=new pa(1,1,(function(){for(let e=0;e<=1;e++)for(let t=0;t<=1;t++)this.vertices.push(new Nn(t,e,0)),this.uvs.push(t,e)}),this),g.gid="glyph",g.computeFaces().computeNormals(),this.geometryBufferCache.ensureCached(g));for(const e of this.buffers.text)e._prepareBuffer(g,f);f.setUniform("uMaterialColor",m),this._disableRemainingAttributes(f),this._beforeDrawText(),this.glyphDataCache=this.glyphDataCache||new Set;try{const e=h._positionGlyphs(t);for(const t of e){const e=l.getGlyphInfo(t);if(e.uGlyphRect){const r=e.rowInfo,i=e.colInfo,n=[e.strokeImageInfo.imageData,r.cellImageInfo.imageData,r.dimImageInfo.imageData,i.cellImageInfo.imageData,i.dimImageInfo.imageData];for(const e of n)this.glyphDataCache.delete(e),this.glyphDataCache.add(e);for(;this.glyphDataCache.size>this.maxCachedGlyphs();){const e=this.glyphDataCache.values().next().value;this.glyphDataCache.delete(e);const t=this.textures.get(e);t&&(t.remove(),this.textures.delete(e))}f.setUniform("uSamplerStrokes",e.strokeImageInfo.imageData),f.setUniform("uSamplerRowStrokes",r.cellImageInfo.imageData),f.setUniform("uSamplerRows",r.dimImageInfo.imageData),f.setUniform("uSamplerColStrokes",i.cellImageInfo.imageData),f.setUniform("uSamplerCols",i.dimImageInfo.imageData),f.setUniform("uGridOffset",e.uGridOffset),f.setUniform("uGlyphRect",e.uGlyphRect),f.setUniform("uGlyphOffset",t.x),f.bindTextures(),this._drawBuffers(g,{mode:4,count:1})}}}finally{f.unbindShader(),this.states.setValue("strokeColor",a),this.states.setValue("drawMode",o),this._afterDrawText(),this.pop()}}}void 0!==p5&&bl(p5,p5.prototype);var Cl='#define PI 3.141592\n\nprecision highp float;\nprecision highp int;\n\nuniform mat4 uViewMatrix;\nuniform mat3 uCameraNormalMatrix;\n\nuniform bool uUseLighting;\n\nuniform int uDirectionalLightCount;\nuniform vec3 uLightingDirection[5];\nuniform vec3 uDirectionalDiffuseColors[5];\nuniform vec3 uDirectionalSpecularColors[5];\n\nuniform int uPointLightCount;\nuniform vec3 uPointLightLocation[5];\nuniform vec3 uPointLightDiffuseColors[5];\t\nuniform vec3 uPointLightSpecularColors[5];\n\nuniform int uSpotLightCount;\nuniform float uSpotLightAngle[5];\nuniform float uSpotLightConc[5];\nuniform vec3 uSpotLightDiffuseColors[5];\nuniform vec3 uSpotLightSpecularColors[5];\nuniform vec3 uSpotLightLocation[5];\nuniform vec3 uSpotLightDirection[5];\n\nuniform bool uSpecular;\nuniform float uShininess;\nuniform float uMetallic;\n\nuniform float uConstantAttenuation;\nuniform float uLinearAttenuation;\nuniform float uQuadraticAttenuation;\n\n// setting from _setImageLightUniforms()\n// boolean to initiate the calculateImageDiffuse and calculateImageSpecular\nuniform bool uUseImageLight;\n// texture for use in calculateImageDiffuse\nuniform sampler2D environmentMapDiffused;\n// texture for use in calculateImageSpecular\nuniform sampler2D environmentMapSpecular;\n\nconst float specularFactor = 2.0;\nconst float diffuseFactor = 0.73;\n\nstruct LightResult {\n float specular;\n float diffuse;\n};\n\nfloat _phongSpecular(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float shininess) {\n\n vec3 R = reflect(lightDirection, surfaceNormal);\n return pow(max(0.0, dot(R, viewDirection)), shininess);\n}\n\nfloat _lambertDiffuse(vec3 lightDirection, vec3 surfaceNormal) {\n return max(0.0, dot(-lightDirection, surfaceNormal));\n}\n\nLightResult _light(vec3 viewDirection, vec3 normal, vec3 lightVector, float shininess, float metallic) {\n\n vec3 lightDir = normalize(lightVector);\n\n //compute our diffuse & specular terms\n LightResult lr;\n float specularIntensity = mix(1.0, 0.4, metallic);\n float diffuseIntensity = mix(1.0, 0.1, metallic);\n if (uSpecular)\n lr.specular = (_phongSpecular(lightDir, viewDirection, normal, shininess)) * specularIntensity;\n lr.diffuse = _lambertDiffuse(lightDir, normal) * diffuseIntensity;\n return lr;\n}\n\n// converts the range of "value" from [min1 to max1] to [min2 to max2]\nfloat map(float value, float min1, float max1, float min2, float max2) {\n return min2 + (value - min1) * (max2 - min2) / (max1 - min1);\n}\n\nvec2 mapTextureToNormal( vec3 v ){\n // x = r sin(phi) cos(theta) \n // y = r cos(phi) \n // z = r sin(phi) sin(theta)\n float phi = acos( v.y );\n // if phi is 0, then there are no x, z components\n float theta = 0.0;\n // else \n theta = acos(v.x / sin(phi));\n float sinTheta = v.z / sin(phi);\n if (sinTheta < 0.0) {\n // Turn it into -theta, but in the 0-2PI range\n theta = 2.0 * PI - theta;\n }\n theta = theta / (2.0 * 3.14159);\n phi = phi / 3.14159 ;\n \n vec2 angles = vec2( fract(theta + 0.25), 1.0 - phi );\n return angles;\n}\n\n\nvec3 calculateImageDiffuse(vec3 vNormal, vec3 vViewPosition, float metallic){\n // make 2 seperate builds \n vec3 worldCameraPosition = vec3(0.0, 0.0, 0.0); // hardcoded world camera position\n vec3 worldNormal = normalize(vNormal * uCameraNormalMatrix);\n vec2 newTexCoor = mapTextureToNormal( worldNormal );\n vec4 texture = TEXTURE( environmentMapDiffused, newTexCoor );\n // this is to make the darker sections more dark\n // png and jpg usually flatten the brightness so it is to reverse that\n return mix(smoothstep(vec3(0.0), vec3(1.0), texture.xyz), vec3(0.0), metallic);\n}\n\nvec3 calculateImageSpecular(vec3 vNormal, vec3 vViewPosition, float shininess, float metallic){\n vec3 worldCameraPosition = vec3(0.0, 0.0, 0.0);\n vec3 worldNormal = normalize(vNormal);\n vec3 lightDirection = normalize( vViewPosition - worldCameraPosition );\n vec3 R = reflect(lightDirection, worldNormal) * uCameraNormalMatrix;\n vec2 newTexCoor = mapTextureToNormal( R );\n#ifdef WEBGL2\n // In p5js the range of shininess is >= 1,\n // Therefore roughness range will be ([0,1]*8)*20 or [0, 160]\n // The factor of 8 is because currently the getSpecularTexture\n // only calculated 8 different levels of roughness\n // The factor of 20 is just to spread up this range so that,\n // [1, max] of shininess is converted to [0,160] of roughness\n float roughness = 20. / shininess;\n vec4 outColor = textureLod(environmentMapSpecular, newTexCoor, roughness * 8.);\n#else\n vec4 outColor = TEXTURE(environmentMapSpecular, newTexCoor);\n#endif\n // this is to make the darker sections more dark\n // png and jpg usually flatten the brightness so it is to reverse that\n return mix(\n pow(outColor.xyz, vec3(10)),\n pow(outColor.xyz, vec3(1.2)),\n metallic \n );\n}\n\nvoid totalLight(\n vec3 modelPosition,\n vec3 normal,\n float shininess,\n float metallic,\n out vec3 totalDiffuse,\n out vec3 totalSpecular\n) {\n\n totalSpecular = vec3(0.0);\n\n if (!uUseLighting) {\n totalDiffuse = vec3(1.0);\n return;\n }\n\n totalDiffuse = vec3(0.0);\n\n vec3 viewDirection = normalize(-modelPosition);\n\n for (int j = 0; j < 5; j++) {\n if (j < uDirectionalLightCount) {\n vec3 lightVector = (uViewMatrix * vec4(uLightingDirection[j], 0.0)).xyz;\n vec3 lightColor = uDirectionalDiffuseColors[j];\n vec3 specularColor = uDirectionalSpecularColors[j];\n LightResult result = _light(viewDirection, normal, lightVector, shininess, metallic);\n totalDiffuse += result.diffuse * lightColor;\n totalSpecular += result.specular * lightColor * specularColor;\n }\n\n if (j < uPointLightCount) {\n vec3 lightPosition = (uViewMatrix * vec4(uPointLightLocation[j], 1.0)).xyz;\n vec3 lightVector = modelPosition - lightPosition;\n //calculate attenuation\n float lightDistance = length(lightVector);\n float lightFalloff = 1.0 / (uConstantAttenuation + lightDistance * uLinearAttenuation + (lightDistance * lightDistance) * uQuadraticAttenuation);\n vec3 lightColor = lightFalloff * uPointLightDiffuseColors[j];\n vec3 specularColor = lightFalloff * uPointLightSpecularColors[j];\n\n LightResult result = _light(viewDirection, normal, lightVector, shininess, metallic);\n totalDiffuse += result.diffuse * lightColor;\n totalSpecular += result.specular * lightColor * specularColor;\n }\n\n if(j < uSpotLightCount) {\n vec3 lightPosition = (uViewMatrix * vec4(uSpotLightLocation[j], 1.0)).xyz;\n vec3 lightVector = modelPosition - lightPosition;\n \n float lightDistance = length(lightVector);\n float lightFalloff = 1.0 / (uConstantAttenuation + lightDistance * uLinearAttenuation + (lightDistance * lightDistance) * uQuadraticAttenuation);\n\n vec3 lightDirection = (uViewMatrix * vec4(uSpotLightDirection[j], 0.0)).xyz;\n float spotDot = dot(normalize(lightVector), normalize(lightDirection));\n float spotFalloff;\n if(spotDot < uSpotLightAngle[j]) {\n spotFalloff = 0.0;\n }\n else {\n spotFalloff = pow(spotDot, uSpotLightConc[j]);\n }\n lightFalloff *= spotFalloff;\n\n vec3 lightColor = uSpotLightDiffuseColors[j];\n vec3 specularColor = uSpotLightSpecularColors[j];\n \n LightResult result = _light(viewDirection, normal, lightVector, shininess, metallic);\n \n totalDiffuse += result.diffuse * lightColor * lightFalloff;\n totalSpecular += result.specular * lightColor * specularColor * lightFalloff;\n }\n }\n\n if( uUseImageLight ){\n totalDiffuse += calculateImageDiffuse(normal, modelPosition, metallic);\n totalSpecular += calculateImageSpecular(normal, modelPosition, shininess, metallic);\n }\n\n totalDiffuse *= diffuseFactor;\n totalSpecular *= specularFactor;\n}\n';const{lineDefs:El}=Na(((e,t)=>`#define ${e} ${t}\n`)),Al={normalVert:"IN vec3 aPosition;\nIN vec3 aNormal;\nIN vec2 aTexCoord;\nIN vec4 aVertexColor;\n\n#define HOOK_DEFINES\n\n#ifdef AUGMENTED_HOOK_getWorldInputs\nuniform mat4 uModelMatrix;\nuniform mat4 uViewMatrix;\nuniform mat3 uModelNormalMatrix;\nuniform mat3 uCameraNormalMatrix;\n#else\nuniform mat4 uModelViewMatrix;\nuniform mat3 uNormalMatrix;\n#endif\nuniform mat4 uProjectionMatrix;\n\nuniform vec4 uMaterialColor;\nuniform bool uUseVertexColor;\n\nOUT vec3 vVertexNormal;\nOUT highp vec2 vVertTexCoord;\nOUT vec4 vColor;\n\nstruct Vertex {\n vec3 position;\n vec3 normal;\n vec2 texCoord;\n vec4 color;\n};\n\nvoid main(void) {\n HOOK_beforeVertex();\n\n Vertex inputs;\n inputs.position = aPosition;\n inputs.normal = aNormal;\n inputs.texCoord = aTexCoord;\n inputs.color = (uUseVertexColor && aVertexColor.x >= 0.0) ? aVertexColor : uMaterialColor;\n#ifdef AUGMENTED_HOOK_getObjectInputs\n inputs = HOOK_getObjectInputs(inputs);\n#endif\n\n#ifdef AUGMENTED_HOOK_getWorldInputs\n inputs.position = (uModelMatrix * vec4(inputs.position, 1.)).xyz;\n inputs.normal = uModelNormalMatrix * inputs.normal;\n inputs = HOOK_getWorldInputs(inputs);\n#endif\n\n#ifdef AUGMENTED_HOOK_getWorldInputs\n // Already multiplied by the model matrix, just apply view\n inputs.position = (uViewMatrix * vec4(inputs.position, 1.)).xyz;\n inputs.normal = uCameraNormalMatrix * inputs.normal;\n#else\n // Apply both at once\n inputs.position = (uModelViewMatrix * vec4(inputs.position, 1.)).xyz;\n inputs.normal = uNormalMatrix * inputs.normal;\n#endif\n#ifdef AUGMENTED_HOOK_getCameraInputs\n inputs = HOOK_getCameraInputs(inputs);\n#endif\n\n // Pass varyings to fragment shader\n vVertTexCoord = inputs.texCoord;\n vVertexNormal = normalize(inputs.normal);\n vColor = inputs.color;\n\n gl_Position = uProjectionMatrix * vec4(inputs.position, 1.);\n\n HOOK_afterVertex();\n}\n",normalFrag:"IN vec3 vVertexNormal;\nIN highp vec2 vVertTexCoord;\nvoid main(void) {\n HOOK_beforeFragment();\n OUT_COLOR = HOOK_getFinalColor(vec4(vVertexNormal, 1.0), vVertTexCoord);\n HOOK_afterFragment();\n}",basicFrag:"IN vec4 vColor;\nIN highp vec2 vVertTexCoord;\nvoid main(void) {\n HOOK_beforeFragment();\n OUT_COLOR = HOOK_getFinalColor(vColor, vVertTexCoord);\n OUT_COLOR.rgb *= OUT_COLOR.a; // Premultiply alpha before rendering\n HOOK_afterFragment();\n}",lightVert:Cl+"// include lighting.glgl\n\nIN vec3 aPosition;\nIN vec3 aNormal;\nIN vec2 aTexCoord;\nIN vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nuniform bool uUseVertexColor;\nuniform vec4 uMaterialColor;\n\nOUT highp vec2 vVertTexCoord;\nOUT vec3 vDiffuseColor;\nOUT vec3 vSpecularColor;\nOUT vec4 vColor;\n\nvoid main(void) {\n\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * viewModelPosition;\n\n vec3 vertexNormal = normalize(uNormalMatrix * aNormal);\n vVertTexCoord = aTexCoord;\n\n totalLight(viewModelPosition.xyz, vertexNormal, vDiffuseColor, vSpecularColor);\n\n for (int i = 0; i < 8; i++) {\n if (i < uAmbientLightCount) {\n vDiffuseColor += uAmbientColor[i];\n }\n }\n \n vColor = ((uUseVertexColor && aVertexColor.x >= 0.0) ? aVertexColor : uMaterialColor);\n}\n",lightTextureFrag:"uniform vec4 uTint;\nuniform sampler2D uSampler;\nuniform bool isTexture;\nuniform bool uEmissive;\n\nIN highp vec2 vVertTexCoord;\nIN vec3 vDiffuseColor;\nIN vec3 vSpecularColor;\nIN vec4 vColor;\n\nvoid main(void) {\n if(uEmissive && !isTexture) {\n OUT_COLOR = vColor;\n }\n else {\n vec4 baseColor = isTexture\n // Textures come in with premultiplied alpha. To apply tint and still have\n // premultiplied alpha output, we need to multiply the RGB channels by the\n // tint RGB, and all channels by the tint alpha.\n ? TEXTURE(uSampler, vVertTexCoord) * vec4(uTint.rgb/255., 1.) * (uTint.a/255.)\n // Colors come in with unmultiplied alpha, so we need to multiply the RGB\n // channels by alpha to convert it to premultiplied alpha.\n : vec4(vColor.rgb * vColor.a, vColor.a);\n OUT_COLOR = vec4(baseColor.rgb * vDiffuseColor + vSpecularColor, baseColor.a);\n }\n}\n",phongVert:"precision highp int;\n\n#define HOOK_DEFINES\n\nIN vec3 aPosition;\nIN vec3 aNormal;\nIN vec2 aTexCoord;\nIN vec4 aVertexColor;\n\n#ifdef AUGMENTED_HOOK_getWorldInputs\nuniform mat4 uModelMatrix;\nuniform mat4 uViewMatrix;\nuniform mat3 uModelNormalMatrix;\nuniform mat3 uCameraNormalMatrix;\n#else\nuniform mat4 uModelViewMatrix;\nuniform mat3 uNormalMatrix;\n#endif\nuniform mat4 uProjectionMatrix;\n\nuniform bool uUseVertexColor;\nuniform vec4 uMaterialColor;\n\nOUT vec3 vNormal;\nOUT vec2 vTexCoord;\nOUT vec3 vViewPosition;\nOUT vec3 vAmbientColor;\nOUT vec4 vColor;\n\nstruct Vertex {\n vec3 position;\n vec3 normal;\n vec2 texCoord;\n vec4 color;\n};\n\nvoid main(void) {\n HOOK_beforeVertex();\n\n Vertex inputs;\n inputs.position = aPosition;\n inputs.normal = aNormal;\n inputs.texCoord = aTexCoord;\n inputs.color = (uUseVertexColor && aVertexColor.x >= 0.0) ? aVertexColor : uMaterialColor;\n#ifdef AUGMENTED_HOOK_getObjectInputs\n inputs = HOOK_getObjectInputs(inputs);\n#endif\n\n#ifdef AUGMENTED_HOOK_getWorldInputs\n inputs.position = (uModelMatrix * vec4(inputs.position, 1.)).xyz;\n inputs.normal = uModelNormalMatrix * inputs.normal;\n inputs = HOOK_getWorldInputs(inputs);\n#endif\n\n#ifdef AUGMENTED_HOOK_getWorldInputs\n // Already multiplied by the model matrix, just apply view\n inputs.position = (uViewMatrix * vec4(inputs.position, 1.)).xyz;\n inputs.normal = uCameraNormalMatrix * inputs.normal;\n#else\n // Apply both at once\n inputs.position = (uModelViewMatrix * vec4(inputs.position, 1.)).xyz;\n inputs.normal = uNormalMatrix * inputs.normal;\n#endif\n#ifdef AUGMENTED_HOOK_getCameraInputs\n inputs = HOOK_getCameraInputs(inputs);\n#endif\n\n // Pass varyings to fragment shader\n vViewPosition = inputs.position;\n vTexCoord = inputs.texCoord;\n vNormal = inputs.normal;\n vColor = inputs.color;\n\n gl_Position = uProjectionMatrix * vec4(inputs.position, 1.);\n HOOK_afterVertex();\n}\n",phongFrag:Cl+"// include lighting.glsl\nprecision highp int;\n\nuniform bool uHasSetAmbient;\nuniform vec3 uAmbientColor;\nuniform vec4 uSpecularMatColor;\nuniform vec4 uAmbientMatColor;\nuniform vec4 uEmissiveMatColor;\n\nuniform vec4 uTint;\nuniform sampler2D uSampler;\nuniform bool isTexture;\n\nIN vec3 vNormal;\nIN vec2 vTexCoord;\nIN vec3 vViewPosition;\nIN vec4 vColor;\n\nstruct ColorComponents {\n vec3 baseColor;\n float opacity;\n vec3 ambientColor;\n vec3 specularColor;\n vec3 diffuse;\n vec3 ambient;\n vec3 specular;\n vec3 emissive;\n};\n\nstruct Inputs {\n vec3 normal;\n vec2 texCoord;\n vec3 ambientLight;\n vec3 ambientMaterial;\n vec3 specularMaterial;\n vec3 emissiveMaterial;\n vec4 color;\n float shininess;\n float metalness;\n};\n\nvoid main(void) {\n HOOK_beforeFragment();\n\n Inputs inputs;\n inputs.normal = normalize(vNormal);\n inputs.texCoord = vTexCoord;\n inputs.ambientLight = uAmbientColor;\n inputs.color = isTexture\n ? TEXTURE(uSampler, vTexCoord) * (vec4(uTint.rgb/255., 1.) * uTint.a/255.)\n : vColor;\n if (isTexture && inputs.color.a > 0.0) {\n // Textures come in with premultiplied alpha. Temporarily unpremultiply it\n // so hooks users don't have to think about premultiplied alpha.\n inputs.color.rgb /= inputs.color.a;\n }\n inputs.shininess = uShininess;\n inputs.metalness = uMetallic;\n inputs.ambientMaterial = uHasSetAmbient ? uAmbientMatColor.rgb : inputs.color.rgb;\n inputs.specularMaterial = uSpecularMatColor.rgb;\n inputs.emissiveMaterial = uEmissiveMatColor.rgb;\n inputs = HOOK_getPixelInputs(inputs);\n\n vec3 diffuse;\n vec3 specular;\n totalLight(vViewPosition, inputs.normal, inputs.shininess, inputs.metalness, diffuse, specular);\n\n // Calculating final color as result of all lights (plus emissive term).\n\n vec4 baseColor = inputs.color;\n ColorComponents c;\n c.opacity = baseColor.a;\n c.baseColor = baseColor.rgb;\n c.ambientColor = inputs.ambientMaterial;\n c.specularColor = inputs.specularMaterial;\n c.diffuse = diffuse;\n c.ambient = inputs.ambientLight;\n c.specular = specular;\n c.emissive = inputs.emissiveMaterial;\n OUT_COLOR = HOOK_getFinalColor(HOOK_combineColors(c), vTexCoord);\n OUT_COLOR.rgb *= OUT_COLOR.a; // Premultiply alpha before rendering\n HOOK_afterFragment();\n}\n",fontVert:"IN vec3 aPosition;\nIN vec2 aTexCoord;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nuniform vec4 uGlyphRect;\nuniform float uGlyphOffset;\n\nOUT vec2 vTexCoord;\n\nvoid main() {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n // scale by the size of the glyph's rectangle\n positionVec4.xy *= uGlyphRect.zw - uGlyphRect.xy;\n\n // Expand glyph bounding boxes by 1px on each side to give a bit of room\n // for antialiasing\n vec3 newOrigin = (uModelViewMatrix * vec4(0., 0., 0., 1.)).xyz;\n vec3 newDX = (uModelViewMatrix * vec4(1., 0., 0., 1.)).xyz;\n vec3 newDY = (uModelViewMatrix * vec4(0., 1., 0., 1.)).xyz;\n vec2 pixelScale = vec2(\n 1. / length(newOrigin - newDX),\n 1. / length(newOrigin - newDY)\n );\n vec2 offset = pixelScale * normalize(aTexCoord - vec2(0.5, 0.5));\n vec2 textureOffset = offset * (1. / vec2(\n uGlyphRect.z - uGlyphRect.x,\n uGlyphRect.w - uGlyphRect.y\n ));\n\n // move to the corner of the glyph\n positionVec4.xy += uGlyphRect.xy;\n\n // move to the letter's line offset\n positionVec4.x += uGlyphOffset;\n\n positionVec4.xy += offset;\n \n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vTexCoord = aTexCoord + textureOffset;\n}\n",fontFrag:"#ifndef WEBGL2\n#extension GL_OES_standard_derivatives : enable\n#endif\n\n#if 0\n // simulate integer math using floats\n\t#define int float\n\t#define ivec2 vec2\n\t#define INT(x) float(x)\n\n\tint ifloor(float v) { return floor(v); }\n\tivec2 ifloor(vec2 v) { return floor(v); }\n\n#else\n // use native integer math\n\tprecision highp int;\n\t#define INT(x) x\n\n\tint ifloor(float v) { return int(v); }\n\tint ifloor(int v) { return v; }\n\tivec2 ifloor(vec2 v) { return ivec2(v); }\n\n#endif\n\nuniform sampler2D uSamplerStrokes;\nuniform sampler2D uSamplerRowStrokes;\nuniform sampler2D uSamplerRows;\nuniform sampler2D uSamplerColStrokes;\nuniform sampler2D uSamplerCols;\n\nuniform ivec2 uStrokeImageSize;\nuniform ivec2 uCellsImageSize;\nuniform ivec2 uGridImageSize;\n\nuniform ivec2 uGridOffset;\nuniform ivec2 uGridSize;\nuniform vec4 uMaterialColor;\n\nIN vec2 vTexCoord;\n\n// some helper functions\nint ROUND(float v) { return ifloor(v + 0.5); }\nivec2 ROUND(vec2 v) { return ifloor(v + 0.5); }\nfloat saturate(float v) { return clamp(v, 0.0, 1.0); }\nvec2 saturate(vec2 v) { return clamp(v, 0.0, 1.0); }\n\nint mul(float v1, int v2) {\n return ifloor(v1 * float(v2));\n}\n\nivec2 mul(vec2 v1, ivec2 v2) {\n return ifloor(v1 * vec2(v2) + 0.5);\n}\n\n// unpack a 16-bit integer from a float vec2\nint getInt16(vec2 v) {\n ivec2 iv = ROUND(v * 255.0);\n return iv.x * INT(128) + iv.y;\n}\n\nvec2 pixelScale;\nvec2 coverage = vec2(0.0);\nvec2 weight = vec2(0.5);\nconst float minDistance = 1.0/8192.0;\nconst float hardness = 1.05; // amount of antialias\n\n// the maximum number of curves in a glyph\nconst int N = INT(250);\n\n// retrieves an indexed pixel from a sampler\nvec4 getTexel(sampler2D sampler, int pos, ivec2 size) {\n int width = size.x;\n int y = ifloor(pos / width);\n int x = pos - y * width; // pos % width\n\n return TEXTURE(sampler, (vec2(x, y) + 0.5) / vec2(size));\n}\n\nvoid calulateCrossings(vec2 p0, vec2 p1, vec2 p2, out vec2 C1, out vec2 C2) {\n\n // get the coefficients of the quadratic in t\n vec2 a = p0 - p1 * 2.0 + p2;\n vec2 b = p0 - p1;\n vec2 c = p0 - vTexCoord;\n\n // found out which values of 't' it crosses the axes\n vec2 surd = sqrt(max(vec2(0.0), b * b - a * c));\n vec2 t1 = ((b - surd) / a).yx;\n vec2 t2 = ((b + surd) / a).yx;\n\n // approximate straight lines to avoid rounding errors\n if (abs(a.y) < 0.001)\n t1.x = t2.x = c.y / (2.0 * b.y);\n\n if (abs(a.x) < 0.001)\n t1.y = t2.y = c.x / (2.0 * b.x);\n\n // plug into quadratic formula to find the corrdinates of the crossings\n C1 = ((a * t1 - b * 2.0) * t1 + c) * pixelScale;\n C2 = ((a * t2 - b * 2.0) * t2 + c) * pixelScale;\n}\n\nvoid coverageX(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n // determine on which side of the x-axis the points lie\n bool y0 = p0.y > vTexCoord.y;\n bool y1 = p1.y > vTexCoord.y;\n bool y2 = p2.y > vTexCoord.y;\n\n // could web be under the curve (after t1)?\n if (y1 ? !y2 : y0) {\n // add the coverage for t1\n coverage.x += saturate(C1.x + 0.5);\n // calculate the anti-aliasing for t1\n weight.x = min(weight.x, abs(C1.x));\n }\n\n // are we outside the curve (after t2)?\n if (y1 ? !y0 : y2) {\n // subtract the coverage for t2\n coverage.x -= saturate(C2.x + 0.5);\n // calculate the anti-aliasing for t2\n weight.x = min(weight.x, abs(C2.x));\n }\n}\n\n// this is essentially the same as coverageX, but with the axes swapped\nvoid coverageY(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n bool x0 = p0.x > vTexCoord.x;\n bool x1 = p1.x > vTexCoord.x;\n bool x2 = p2.x > vTexCoord.x;\n\n if (x1 ? !x2 : x0) {\n coverage.y -= saturate(C1.y + 0.5);\n weight.y = min(weight.y, abs(C1.y));\n }\n\n if (x1 ? !x0 : x2) {\n coverage.y += saturate(C2.y + 0.5);\n weight.y = min(weight.y, abs(C2.y));\n }\n}\n\nvoid main() {\n\n // calculate the pixel scale based on screen-coordinates\n pixelScale = hardness / fwidth(vTexCoord);\n\n // which grid cell is this pixel in?\n ivec2 gridCoord = ifloor(vTexCoord * vec2(uGridSize));\n\n // intersect curves in this row\n {\n // the index into the row info bitmap\n int rowIndex = gridCoord.y + uGridOffset.y;\n // fetch the info texel\n vec4 rowInfo = getTexel(uSamplerRows, rowIndex, uGridImageSize);\n // unpack the rowInfo\n int rowStrokeIndex = getInt16(rowInfo.xy);\n int rowStrokeCount = getInt16(rowInfo.zw);\n\n for (int iRowStroke = INT(0); iRowStroke < N; iRowStroke++) {\n if (iRowStroke >= rowStrokeCount)\n break;\n\n // each stroke is made up of 3 points: the start and control point\n // and the start of the next curve.\n // fetch the indices of this pair of strokes:\n vec4 strokeIndices = getTexel(uSamplerRowStrokes, rowStrokeIndex++, uCellsImageSize);\n\n // unpack the stroke index\n int strokePos = getInt16(strokeIndices.xy);\n\n // fetch the two strokes\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n\n // calculate the coverage\n coverageX(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n // intersect curves in this column\n {\n int colIndex = gridCoord.x + uGridOffset.x;\n vec4 colInfo = getTexel(uSamplerCols, colIndex, uGridImageSize);\n int colStrokeIndex = getInt16(colInfo.xy);\n int colStrokeCount = getInt16(colInfo.zw);\n \n for (int iColStroke = INT(0); iColStroke < N; iColStroke++) {\n if (iColStroke >= colStrokeCount)\n break;\n\n vec4 strokeIndices = getTexel(uSamplerColStrokes, colStrokeIndex++, uCellsImageSize);\n\n int strokePos = getInt16(strokeIndices.xy);\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n coverageY(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n weight = saturate(1.0 - weight * 2.0);\n float distance = max(weight.x + weight.y, minDistance); // manhattan approx.\n float antialias = abs(dot(coverage, weight) / distance);\n float cover = min(abs(coverage.x), abs(coverage.y));\n OUT_COLOR = vec4(uMaterialColor.rgb, 1.) * uMaterialColor.a;\n OUT_COLOR *= saturate(max(antialias, cover));\n}\n",lineVert:El+"/*\n Part of the Processing project - http://processing.org\n Copyright (c) 2012-15 The Processing Foundation\n Copyright (c) 2004-12 Ben Fry and Casey Reas\n Copyright (c) 2001-04 Massachusetts Institute of Technology\n This library is free software; you can redistribute it and/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation, version 2.1.\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n You should have received a copy of the GNU Lesser General\n Public License along with this library; if not, write to the\n Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n Boston, MA 02111-1307 USA\n*/\n\n#define PROCESSING_LINE_SHADER\n\n#define HOOK_DEFINES\n\nprecision highp int;\nprecision highp float;\n\n#ifdef AUGMENTED_HOOK_getWorldInputs\nuniform mat4 uModelMatrix;\nuniform mat4 uViewMatrix;\n#else\nuniform mat4 uModelViewMatrix;\n#endif\n\nuniform mat4 uProjectionMatrix;\nuniform float uStrokeWeight;\n\nuniform bool uUseLineColor;\nuniform bool uSimpleLines;\nuniform vec4 uMaterialColor;\n\nuniform vec4 uViewport;\nuniform int uPerspective;\nuniform int uStrokeJoin;\n\nIN vec3 aPosition;\nIN vec3 aTangentIn;\nIN vec3 aTangentOut;\nIN float aSide;\nIN vec4 aVertexColor;\n\nOUT vec4 vColor;\nOUT vec2 vTangent;\nOUT vec2 vCenter;\nOUT vec2 vPosition;\nOUT float vMaxDist;\nOUT float vCap;\nOUT float vJoin;\nOUT float vStrokeWeight;\n\nvec2 lineIntersection(vec2 aPoint, vec2 aDir, vec2 bPoint, vec2 bDir) {\n // Rotate and translate so a starts at the origin and goes out to the right\n bPoint -= aPoint;\n vec2 rotatedBFrom = vec2(\n bPoint.x*aDir.x + bPoint.y*aDir.y,\n bPoint.y*aDir.x - bPoint.x*aDir.y\n );\n vec2 bTo = bPoint + bDir;\n vec2 rotatedBTo = vec2(\n bTo.x*aDir.x + bTo.y*aDir.y,\n bTo.y*aDir.x - bTo.x*aDir.y\n );\n float intersectionDistance =\n rotatedBTo.x + (rotatedBFrom.x - rotatedBTo.x) * rotatedBTo.y /\n (rotatedBTo.y - rotatedBFrom.y);\n return aPoint + aDir * intersectionDistance;\n}\n\nstruct StrokeVertex {\n vec3 position;\n vec3 tangentIn;\n vec3 tangentOut;\n vec4 color;\n float weight;\n};\n\nvoid main() {\n HOOK_beforeVertex();\n\n if (!uSimpleLines) {\n // Caps have one of either the in or out tangent set to 0\n vCap = (aTangentIn == vec3(0.)) != (aTangentOut == vec3(0.)) ? 1. : 0.;\n\n // Joins have two unique, defined tangents\n vJoin = (\n aTangentIn != vec3(0.) &&\n aTangentOut != vec3(0.) &&\n aTangentIn != aTangentOut\n ) ? 1. : 0.;\n }\n\n StrokeVertex inputs;\n inputs.position = aPosition.xyz;\n inputs.color = uUseLineColor ? aVertexColor : uMaterialColor;\n inputs.weight = uStrokeWeight;\n inputs.tangentIn = aTangentIn;\n inputs.tangentOut = aTangentOut;\n\n#ifdef AUGMENTED_HOOK_getObjectInputs\n inputs = HOOK_getObjectInputs(inputs);\n#endif\n\n#ifdef AUGMENTED_HOOK_getWorldInputs\n inputs.position = (uModelMatrix * vec4(inputs.position, 1.)).xyz;\n inputs.tangentIn = (uModelMatrix * vec4(aTangentIn, 0.)).xyz;\n inputs.tangentOut = (uModelMatrix * vec4(aTangentOut, 0.)).xyz;\n inputs = HOOK_getWorldInputs(inputs);\n#endif\n\n#ifdef AUGMENTED_HOOK_getWorldInputs\n // Already multiplied by the model matrix, just apply view\n inputs.position = (uViewMatrix * vec4(inputs.position, 1.)).xyz;\n inputs.tangentIn = (uViewMatrix * vec4(aTangentIn, 0.)).xyz;\n inputs.tangentOut = (uViewMatrix * vec4(aTangentOut, 0.)).xyz;\n#else\n // Apply both at once\n inputs.position = (uModelViewMatrix * vec4(inputs.position, 1.)).xyz;\n inputs.tangentIn = (uModelViewMatrix * vec4(aTangentIn, 0.)).xyz;\n inputs.tangentOut = (uModelViewMatrix * vec4(aTangentOut, 0.)).xyz;\n#endif\n#ifdef AUGMENTED_HOOK_getCameraInputs\n inputs = HOOK_getCameraInputs(inputs);\n#endif\n\n vec4 posp = vec4(inputs.position, 1.);\n vec4 posqIn = vec4(inputs.position + inputs.tangentIn, 1.);\n vec4 posqOut = vec4(inputs.position + inputs.tangentOut, 1.);\n vStrokeWeight = inputs.weight;\n\n float facingCamera = pow(\n // The word space tangent's z value is 0 if it's facing the camera\n abs(normalize(posqIn-posp).z),\n\n // Using pow() here to ramp `facingCamera` up from 0 to 1 really quickly\n // so most lines get scaled and don't get clipped\n 0.25\n );\n\n // Moving vertices slightly toward the camera\n // to avoid depth-fighting with the fill triangles.\n // A mix of scaling and offsetting is used based on distance\n // Discussion here:\n // https://github.com/processing/p5.js/issues/7200 \n\n // using a scale <1 moves the lines towards nearby camera\n // in order to prevent popping effects due to half of\n // the line disappearing behind the geometry faces.\n float zDistance = -posp.z; \n float distanceFactor = smoothstep(0.0, 800.0, zDistance); \n \n // Discussed here:\n // http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=252848 \n float scale = mix(1., 0.995, facingCamera);\n float dynamicScale = mix(scale, 1.0, distanceFactor); // Closer = more scale, farther = less\n\n posp.xyz = posp.xyz * dynamicScale;\n posqIn.xyz = posqIn.xyz * dynamicScale;\n posqOut.xyz = posqOut.xyz * dynamicScale;\n\n // Moving vertices slightly toward camera when far away \n // https://github.com/processing/p5.js/issues/6956 \n float zOffset = mix(0., -1., facingCamera);\n float dynamicZAdjustment = mix(0.0, zOffset, distanceFactor); // Closer = less zAdjustment, farther = more\n\n posp.z -= dynamicZAdjustment;\n posqIn.z -= dynamicZAdjustment;\n posqOut.z -= dynamicZAdjustment;\n \n vec4 p = uProjectionMatrix * posp;\n vec4 qIn = uProjectionMatrix * posqIn;\n vec4 qOut = uProjectionMatrix * posqOut;\n\n // formula to convert from clip space (range -1..1) to screen space (range 0..[width or height])\n // screen_p = (p.xy/p.w + <1,1>) * 0.5 * uViewport.zw\n\n // prevent division by W by transforming the tangent formula (div by 0 causes\n // the line to disappear, see https://github.com/processing/processing/issues/5183)\n // t = screen_q - screen_p\n //\n // tangent is normalized and we don't care which aDirection it points to (+-)\n // t = +- normalize( screen_q - screen_p )\n // t = +- normalize( (q.xy/q.w+<1,1>)*0.5*uViewport.zw - (p.xy/p.w+<1,1>)*0.5*uViewport.zw )\n //\n // extract common factor, <1,1> - <1,1> cancels out\n // t = +- normalize( (q.xy/q.w - p.xy/p.w) * 0.5 * uViewport.zw )\n //\n // convert to common divisor\n // t = +- normalize( ((q.xy*p.w - p.xy*q.w) / (p.w*q.w)) * 0.5 * uViewport.zw )\n //\n // remove the common scalar divisor/factor, not needed due to normalize and +-\n // (keep uViewport - can't remove because it has different components for x and y\n // and corrects for aspect ratio, see https://github.com/processing/processing/issues/5181)\n // t = +- normalize( (q.xy*p.w - p.xy*q.w) * uViewport.zw )\n\n vec2 tangentIn = normalize((qIn.xy*p.w - p.xy*qIn.w) * uViewport.zw);\n vec2 tangentOut = normalize((qOut.xy*p.w - p.xy*qOut.w) * uViewport.zw);\n\n vec2 curPerspScale;\n if(uPerspective == 1) {\n // Perspective ---\n // convert from world to clip by multiplying with projection scaling factor\n // to get the right thickness (see https://github.com/processing/processing/issues/5182)\n\n // The y value of the projection matrix may be flipped if rendering to a Framebuffer.\n // Multiplying again by its sign here negates the flip to get just the scale.\n curPerspScale = (uProjectionMatrix * vec4(1, sign(uProjectionMatrix[1][1]), 0, 0)).xy;\n } else {\n // No Perspective ---\n // multiply by W (to cancel out division by W later in the pipeline) and\n // convert from screen to clip (derived from clip to screen above)\n curPerspScale = p.w / (0.5 * uViewport.zw);\n }\n\n vec2 offset;\n if (vJoin == 1. && !uSimpleLines) {\n vTangent = normalize(tangentIn + tangentOut);\n vec2 normalIn = vec2(-tangentIn.y, tangentIn.x);\n vec2 normalOut = vec2(-tangentOut.y, tangentOut.x);\n float side = sign(aSide);\n float sideEnum = abs(aSide);\n\n // We generate vertices for joins on either side of the centerline, but\n // the \"elbow\" side is the only one needing a join. By not setting the\n // offset for the other side, all its vertices will end up in the same\n // spot and not render, effectively discarding it.\n if (sign(dot(tangentOut, vec2(-tangentIn.y, tangentIn.x))) != side) {\n // Side enums:\n // 1: the side going into the join\n // 2: the middle of the join\n // 3: the side going out of the join\n if (sideEnum == 2.) {\n // Calculate the position + tangent on either side of the join, and\n // find where the lines intersect to find the elbow of the join\n vec2 c = (posp.xy/posp.w + vec2(1.,1.)) * 0.5 * uViewport.zw;\n vec2 intersection = lineIntersection(\n c + (side * normalIn * inputs.weight / 2.),\n tangentIn,\n c + (side * normalOut * inputs.weight / 2.),\n tangentOut\n );\n offset = (intersection - c);\n\n // When lines are thick and the angle of the join approaches 180, the\n // elbow might be really far from the center. We'll apply a limit to\n // the magnitude to avoid lines going across the whole screen when this\n // happens.\n float mag = length(offset);\n float maxMag = 3. * inputs.weight;\n if (mag > maxMag) {\n offset *= maxMag / mag;\n }\n } else if (sideEnum == 1.) {\n offset = side * normalIn * inputs.weight / 2.;\n } else if (sideEnum == 3.) {\n offset = side * normalOut * inputs.weight / 2.;\n }\n }\n if (uStrokeJoin == STROKE_JOIN_BEVEL) {\n vec2 avgNormal = vec2(-vTangent.y, vTangent.x);\n vMaxDist = abs(dot(avgNormal, normalIn * inputs.weight / 2.));\n } else {\n vMaxDist = inputs.weight / 2.;\n }\n } else {\n vec2 tangent = aTangentIn == vec3(0.) ? tangentOut : tangentIn;\n\n vTangent = tangent;\n vec2 normal = vec2(-tangent.y, tangent.x);\n\n float normalOffset = sign(aSide);\n // Caps will have side values of -2 or 2 on the edge of the cap that\n // extends out from the line\n float tangentOffset = abs(aSide) - 1.;\n offset = (normal * normalOffset + tangent * tangentOffset) *\n inputs.weight * 0.5;\n vMaxDist = inputs.weight / 2.;\n }\n\n vCenter = p.xy;\n vPosition = vCenter + offset;\n vColor = inputs.color;\n\n gl_Position.xy = p.xy + offset.xy * curPerspScale;\n gl_Position.zw = p.zw;\n \n HOOK_afterVertex();\n}\n",lineFrag:El+"precision highp int;\nprecision highp float;\n\nuniform vec4 uMaterialColor;\nuniform int uStrokeCap;\nuniform int uStrokeJoin;\n\nIN vec4 vColor;\nIN vec2 vTangent;\nIN vec2 vCenter;\nIN vec2 vPosition;\nIN float vStrokeWeight;\nIN float vMaxDist;\nIN float vCap;\nIN float vJoin;\n\nfloat distSquared(vec2 a, vec2 b) {\n vec2 aToB = b - a;\n return dot(aToB, aToB);\n}\n\nstruct Inputs {\n vec4 color;\n vec2 tangent;\n vec2 center;\n vec2 position;\n float strokeWeight;\n};\n\nvoid main() {\n HOOK_beforeFragment();\n\n Inputs inputs;\n inputs.color = vColor;\n inputs.tangent = vTangent;\n inputs.center = vCenter;\n inputs.position = vPosition;\n inputs.strokeWeight = vStrokeWeight;\n inputs = HOOK_getPixelInputs(inputs);\n\n if (vCap > 0.) {\n if (\n uStrokeCap == STROKE_CAP_ROUND &&\n HOOK_shouldDiscard(distSquared(inputs.position, inputs.center) > inputs.strokeWeight * inputs.strokeWeight * 0.25)\n ) {\n discard;\n } else if (\n uStrokeCap == STROKE_CAP_SQUARE &&\n HOOK_shouldDiscard(dot(inputs.position - inputs.center, inputs.tangent) > 0.)\n ) {\n discard;\n // Use full area for PROJECT\n } else if (HOOK_shouldDiscard(false)) {\n discard;\n }\n } else if (vJoin > 0.) {\n if (\n uStrokeJoin == STROKE_JOIN_ROUND &&\n HOOK_shouldDiscard(distSquared(inputs.position, inputs.center) > inputs.strokeWeight * inputs.strokeWeight * 0.25)\n ) {\n discard;\n } else if (uStrokeJoin == STROKE_JOIN_BEVEL) {\n vec2 normal = vec2(-inputs.tangent.y, inputs.tangent.x);\n if (HOOK_shouldDiscard(abs(dot(inputs.position - inputs.center, normal)) > vMaxDist)) {\n discard;\n }\n // Use full area for MITER\n } else if (HOOK_shouldDiscard(false)) {\n discard;\n }\n }\n OUT_COLOR = HOOK_getFinalColor(inputs.color, vec2(0.0, 0.0));\n OUT_COLOR.rgb *= OUT_COLOR.a;\n HOOK_afterFragment();\n}\n",imageLightVert:"precision highp float;\nIN vec3 aPosition;\nIN vec3 aNormal;\nIN vec2 aTexCoord;\n\nOUT vec3 localPos;\nOUT vec3 vWorldNormal;\nOUT vec3 vWorldPosition;\nOUT vec2 vTexCoord;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nvoid main() {\n // Multiply the position by the matrix.\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * viewModelPosition; \n \n // orient the normals and pass to the fragment shader\n vWorldNormal = uNormalMatrix * aNormal;\n \n // send the view position to the fragment shader\n vWorldPosition = (uModelViewMatrix * vec4(aPosition, 1.0)).xyz;\n \n localPos = vWorldPosition;\n vTexCoord = aTexCoord;\n}\n\n\n/*\nin the vertex shader we'll compute the world position and world oriented normal of the vertices and pass those to the fragment shader as varyings.\n*/\n",imageLightDiffusedFrag:"precision highp float;\nIN vec3 localPos;\n\n// the HDR cubemap converted (can be from an equirectangular environment map.)\nuniform sampler2D environmentMap;\nIN vec2 vTexCoord;\n\nconst float PI = 3.14159265359;\n\nvec2 nTOE( vec3 v ){\n // x = r sin(phi) cos(theta) \n // y = r cos(phi) \n // z = r sin(phi) sin(theta)\n float phi = acos( v.y );\n // if phi is 0, then there are no x, z components\n float theta = 0.0;\n // else \n theta = acos(v.x / sin(phi));\n float sinTheta = v.z / sin(phi);\n if (sinTheta < 0.0) {\n // Turn it into -theta, but in the 0-2PI range\n theta = 2.0 * PI - theta;\n }\n theta = theta / (2.0 * 3.14159);\n phi = phi / 3.14159 ;\n \n vec2 angles = vec2( phi, theta );\n return angles;\n}\n\nfloat random(vec2 p) {\n vec3 p3 = fract(vec3(p.xyx) * .1031);\n p3 += dot(p3, p3.yzx + 33.33);\n return fract((p3.x + p3.y) * p3.z);\n}\n\nvoid main()\n{ \t \n\t// the sample direction equals the hemisphere's orientation\n float phi = vTexCoord.x * 2.0 * PI;\n float theta = vTexCoord.y * PI;\n float x = sin(theta) * cos(phi);\n float y = sin(theta) * sin(phi);\n float z = cos(theta);\n vec3 normal = vec3( x, y, z);\n\n\t// Discretely sampling the hemisphere given the integral's\n // spherical coordinates translates to the following fragment code:\n\tvec3 irradiance = vec3(0.0); \n\tvec3 up\t= vec3(0.0, 1.0, 0.0);\n\tvec3 right = normalize(cross(up, normal));\n\tup = normalize(cross(normal, right));\n\n\t// We specify a fixed sampleDelta delta value to traverse\n // the hemisphere; decreasing or increasing the sample delta\n // will increase or decrease the accuracy respectively.\n\tconst float sampleDelta = 0.100;\n\tfloat nrSamples = 0.0;\n float randomOffset = random(gl_FragCoord.xy) * sampleDelta;\n\tfor(float rawPhi = 0.0; rawPhi < 2.0 * PI; rawPhi += sampleDelta)\n\t{\n float phi = rawPhi + randomOffset;\n for(float rawTheta = 0.0; rawTheta < ( 0.5 ) * PI; rawTheta += sampleDelta)\n {\n float theta = rawTheta + randomOffset;\n // spherical to cartesian (in tangent space) // tangent space to world // add each sample result to irradiance\n float x = sin(theta) * cos(phi);\n float y = sin(theta) * sin(phi);\n float z = cos(theta);\n vec3 tangentSample = vec3( x, y, z);\n \n vec3 sampleVec = tangentSample.x * right + tangentSample.y * up + tangentSample.z * normal;\n irradiance += (TEXTURE(environmentMap, nTOE(sampleVec)).xyz) * cos(theta) * sin(theta);\n nrSamples++;\n }\n\t}\n\t// divide by the total number of samples taken, giving us the average sampled irradiance.\n\tirradiance = PI * irradiance * (1.0 / float(nrSamples )) ;\n \n \n\tOUT_COLOR = vec4(irradiance, 1.0);\n}",imageLightSpecularFrag:"precision highp float;\r\nIN vec3 localPos;\r\nIN vec2 vTexCoord;\r\n\r\n// our texture\r\nuniform sampler2D environmentMap;\r\nuniform float roughness;\r\n\r\nconst float PI = 3.14159265359;\r\n\r\nfloat VanDerCorput(int bits);\r\nvec2 HammersleyNoBitOps(int i, int N);\r\nvec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness);\r\n\r\n\r\nvec2 nTOE( vec3 v ){\r\n // x = r sin(phi) cos(theta) \r\n // y = r cos(phi) \r\n // z = r sin(phi) sin(theta)\r\n float phi = acos( v.y );\r\n // if phi is 0, then there are no x, z components\r\n float theta = 0.0;\r\n // else \r\n theta = acos(v.x / sin(phi));\r\n float sinTheta = v.z / sin(phi);\r\n if (sinTheta < 0.0) {\r\n // Turn it into -theta, but in the 0-2PI range\r\n theta = 2.0 * PI - theta;\r\n }\r\n theta = theta / (2.0 * 3.14159);\r\n phi = phi / 3.14159 ;\r\n \r\n vec2 angles = vec2( phi, theta );\r\n return angles;\r\n}\r\n\r\n\r\nvoid main(){\r\n const int SAMPLE_COUNT = 400; // 4096\r\n int lowRoughnessLimit = int(pow(2.0,(roughness+0.1)*20.0));\r\n float totalWeight = 0.0;\r\n vec3 prefilteredColor = vec3(0.0);\r\n float phi = vTexCoord.x * 2.0 * PI;\r\n float theta = vTexCoord.y * PI;\r\n float x = sin(theta) * cos(phi);\r\n float y = sin(theta) * sin(phi);\r\n float z = cos(theta);\r\n vec3 N = vec3(x,y,z);\r\n vec3 V = N;\r\n for (int i = 0; i < SAMPLE_COUNT; ++i)\r\n {\r\n // break at smaller sample numbers for low roughness levels\r\n if(i == lowRoughnessLimit)\r\n {\r\n break;\r\n }\r\n vec2 Xi = HammersleyNoBitOps(i, SAMPLE_COUNT);\r\n vec3 H = ImportanceSampleGGX(Xi, N, roughness);\r\n vec3 L = normalize(2.0 * dot(V, H) * H - V);\r\n\r\n float NdotL = max(dot(N, L), 0.0);\r\n if (NdotL > 0.0)\r\n {\r\n prefilteredColor += TEXTURE(environmentMap, nTOE(L)).xyz * NdotL;\r\n totalWeight += NdotL;\r\n }\r\n }\r\n prefilteredColor = prefilteredColor / totalWeight;\r\n\r\n OUT_COLOR = vec4(prefilteredColor, 1.0);\r\n}\r\n\r\nvec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness){\r\n float a = roughness * roughness;\r\n\r\n float phi = 2.0 * PI * Xi.x;\r\n float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a * a - 1.0) * Xi.y));\r\n float sinTheta = sqrt(1.0 - cosTheta * cosTheta);\r\n // from spherical coordinates to cartesian coordinates\r\n vec3 H;\r\n H.x = cos(phi) * sinTheta;\r\n H.y = sin(phi) * sinTheta;\r\n H.z = cosTheta;\r\n\r\n // from tangent-space vector to world-space sample vector\r\n vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);\r\n vec3 tangent = normalize(cross(up, N));\r\n vec3 bitangent = cross(N, tangent);\r\n\r\n vec3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z;\r\n return normalize(sampleVec);\r\n}\r\n\r\n\r\nfloat VanDerCorput(int n, int base)\r\n{\r\n#ifdef WEBGL2\r\n\r\n uint bits = uint(n);\r\n bits = (bits << 16u) | (bits >> 16u);\r\n bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);\r\n bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);\r\n bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);\r\n bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);\r\n return float(bits) * 2.3283064365386963e-10; // / 0x100000000\r\n\r\n#else\r\n\r\n float invBase = 1.0 / float(base);\r\n float denom = 1.0;\r\n float result = 0.0;\r\n\r\n\r\n for (int i = 0; i < 32; ++i)\r\n {\r\n if (n > 0)\r\n {\r\n denom = mod(float(n), 2.0);\r\n result += denom * invBase;\r\n invBase = invBase / 2.0;\r\n n = int(float(n) / 2.0);\r\n }\r\n }\r\n\r\n\r\n return result;\r\n\r\n#endif\r\n}\r\n\r\nvec2 HammersleyNoBitOps(int i, int N)\r\n{\r\n return vec2(float(i) / float(N), VanDerCorput(i, 2));\r\n}\r\n",filterBaseVert:vo,filterBaseFrag:xo};for(const e in Al)Al[e]=bo+Al[e];class Dl extends Ua{constructor(e,t,r,i,n){super(e,t,r,i,n),this.webglVersion===s?this.blendExt=this.GL:this.blendExt=this.GL.getExtension("EXT_blend_minmax"),this._userEnabledStencil=!1,this._internalEnable=this.drawingContext.enable,this._internalDisable=this.drawingContext.disable,this.drawingContext.enable=e=>(e===this.drawingContext.STENCIL_TEST&&(this._clipping||(this._userEnabledStencil=!0)),this._internalEnable.call(this.drawingContext,e)),this.drawingContext.disable=e=>(e===this.drawingContext.STENCIL_TEST&&(this._userEnabledStencil=!1),this._internalDisable.call(this.drawingContext,e)),this._cachedBlendMode=void 0,this.strandsBackend=nh}setupContext(){this._setAttributeDefaults(this._pInst),this._initContext(),this.GL=this.drawingContext}_applyBlendMode(){if(this._cachedBlendMode===this.states.curBlendMode)return;const e=this.GL;switch(this.states.curBlendMode){case Z:e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case J:e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE);break;case K:e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ZERO,e.ONE_MINUS_SRC_ALPHA);break;case ne:e.blendEquation(e.FUNC_ADD),e.blendFunc(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA);break;case se:e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_COLOR);break;case ie:e.blendEquationSeparate(e.FUNC_ADD,e.FUNC_ADD),e.blendFuncSeparate(e.ONE_MINUS_DST_COLOR,e.ONE_MINUS_SRC_COLOR,e.ONE,e.ONE);break;case ae:e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO);break;case re:e.blendEquationSeparate(e.FUNC_REVERSE_SUBTRACT,e.FUNC_ADD),e.blendFuncSeparate(e.ONE,e.ONE,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case Q:this.blendExt?(e.blendEquationSeparate(this.blendExt.MIN||this.blendExt.MIN_EXT,e.FUNC_ADD),e.blendFuncSeparate(e.ONE,e.ONE,e.ONE,e.ONE)):console.warn("blendMode(DARKEST) does not work in your browser in WEBGL mode.");break;case ee:this.blendExt?(e.blendEquationSeparate(this.blendExt.MAX||this.blendExt.MAX_EXT,e.FUNC_ADD),e.blendFuncSeparate(e.ONE,e.ONE,e.ONE,e.ONE)):console.warn("blendMode(LIGHTEST) does not work in your browser in WEBGL mode.");break;default:console.error("Oops! Somehow Renderer3D set curBlendMode to an unsupported mode.")}this._cachedBlendMode=this.states.curBlendMode}_shaderOptions(){}_useShader(e){this.GL.useProgram(e._glProgram)}_disableRemainingAttributes(e){for(const t of this.registerEnabled.values())Object.keys(e.attributes).some((r=>e.attributes[r].location===t))||(this.GL.disableVertexAttribArray(t),this.registerEnabled.delete(t))}_drawBuffers(e,{mode:t=4,count:r}){const i=this.GL,n=this.geometryBufferCache.getCached(e);if(n)if("stroke"===this._curShader.shaderType)if(1===r)i.drawArrays(i.TRIANGLES,0,e.lineVertices.length/3);else try{i.drawArraysInstanced(i.TRIANGLES,0,e.lineVertices.length/3,r)}catch(e){console.log("🌸 p5.js says: Instancing is only supported in WebGL2 mode")}else if("text"===this._curShader.shaderType)this._bindBuffer(n.indexBuffer,i.ELEMENT_ARRAY_BUFFER),i.drawElements(i.TRIANGLES,6,i.UNSIGNED_SHORT,0);else if(n.indexBuffer){if(this._bindBuffer(n.indexBuffer,i.ELEMENT_ARRAY_BUFFER),this._pInst.webglVersion!==s&&n.indexBufferType===i.UNSIGNED_INT&&!i.getExtension("OES_element_index_uint"))throw new Error("Unable to render a 3d model with > 65535 triangles. Your web browser does not support the WebGL Extension OES_element_index_uint.");if(1===r)i.drawElements(i.TRIANGLES,3*e.faces.length,n.indexBufferType,0);else try{i.drawElementsInstanced(i.TRIANGLES,3*e.faces.length,n.indexBufferType,0,r)}catch(e){console.log("🌸 p5.js says: Instancing is only supported in WebGL2 mode")}}else{let n;if(n=4===t?i.TRIANGLES:6===t?i.TRIANGLE_FAN:i.TRIANGLE_STRIP,1===r)i.drawArrays(n,0,e.vertices.length);else try{i.drawArraysInstanced(n,0,e.vertices.length,r)}catch(e){console.log("🌸 p5.js says: Instancing is only supported in WebGL2 mode")}}}_beforeDrawText(){this.GL.pixelStorei(this.GL.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1)}_afterDrawText(){this.GL.pixelStorei(this.GL.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0)}_setAttributeDefaults(e){const t={alpha:!0,depth:!0,stencil:!0,antialias:navigator.userAgent.toLowerCase().includes("safari"),premultipliedAlpha:!0,preserveDrawingBuffer:!0,perPixelLighting:!0,version:2};null===e._glAttributes?e._glAttributes=t:e._glAttributes=Object.assign(t,e._glAttributes)}_setAttributes(e,t){if(void 0===this._pInst._glAttributes)return void console.log("You are trying to use setAttributes on a p5.Graphics object that does not use a WEBGL renderer.");let r=!0;void 0!==t?(null===this._pInst._glAttributes&&(this._pInst._glAttributes={}),this._pInst._glAttributes[e]!==t&&(this._pInst._glAttributes[e]=t,r=!1)):e instanceof Object&&this._pInst._glAttributes!==e&&(this._pInst._glAttributes=e,r=!1),this.isP3D&&!r&&(!this._pInst._setupDone&&this.geometryBufferCache.numCached()>0?p5._friendlyError("Sorry, Could not set the attributes, you need to call setAttributes() before calling the other drawing methods in setup()"):(this._resetContext(null,null,Dl),this.states.curCamera&&(this.states.curCamera._renderer=this._renderer)))}_initContext(){if(1!==this._pInst._glAttributes?.version&&(this.drawingContext=this.canvas.getContext("webgl2",this._pInst._glAttributes)),this.webglVersion=this.drawingContext?s:n,this._pInst.webglVersion=this.webglVersion,this.drawingContext||(this.drawingContext=this.canvas.getContext("webgl",this._pInst._glAttributes)||this.canvas.getContext("experimental-webgl",this._pInst._glAttributes)),null===this.drawingContext)throw new Error("Error creating webgl context");{const e=this.drawingContext;e.enable(e.DEPTH_TEST),e.depthFunc(e.LEQUAL),e.viewport(0,0,e.drawingBufferWidth,e.drawingBufferHeight),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),this._viewport=this.drawingContext.getParameter(this.drawingContext.VIEWPORT)}}_updateSize(){}_getMaxTextureSize(){const e=this.drawingContext;return e.getParameter(e.MAX_TEXTURE_SIZE)}_adjustDimensions(e,t,r=this._pixelDensity){this._maxTextureSize||(this._maxTextureSize=this._getMaxTextureSize());let i=this._maxTextureSize,n=Math.floor(i/r),s=Math.min(e,n),a=Math.min(t,n);return s===e&&a===t||console.warn(`Warning: The requested width/height exceeds hardware limits. Adjusting dimensions to width: ${s}, height: ${a}.`),{adjustedWidth:s,adjustedHeight:a}}_resetBuffersBeforeDraw(){this.GL.clearStencil(0),this.GL.clear(this.GL.DEPTH_BUFFER_BIT|this.GL.STENCIL_BUFFER_BIT),this._userEnabledStencil||this._internalDisable.call(this.GL,this.GL.STENCIL_TEST)}_applyClip(){const e=this.GL;e.clearStencil(0),e.clear(e.STENCIL_BUFFER_BIT),this._internalEnable.call(e,e.STENCIL_TEST),this._stencilTestOn=!0,e.stencilFunc(e.ALWAYS,1,255),e.stencilOp(e.KEEP,e.KEEP,e.REPLACE),e.disable(e.DEPTH_TEST)}_unapplyClip(){const e=this.GL;e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.stencilFunc(this._clipInvert?e.EQUAL:e.NOTEQUAL,0,255),e.enable(e.DEPTH_TEST)}_clearClipBuffer(){this.GL.clearStencil(1),this.GL.clear(this.GL.STENCIL_BUFFER_BIT),this._userEnabledStencil||this._internalDisable.call(this.GL,this.GL.STENCIL_TEST)}_getPixel(e,t){const r=this.GL;return io(r,null,e,t,r.RGBA,r.UNSIGNED_BYTE,this._pInst.height*this._pInst.pixelDensity())}loadPixels(){if(!0!==this._pInst._glAttributes.preserveDrawingBuffer)return void console.log("loadPixels only works in WebGL when preserveDrawingBuffer is true.");const e=this._pixelDensity,t=this.GL;this.pixels=ro(this.pixels,t,null,0,0,this.width*e,this.height*e,t.RGBA,t.UNSIGNED_BYTE,this.height*e)}updatePixels(){const e=this._getTempFramebuffer();e.pixels=this.pixels,e.updatePixels(),this.push(),this.resetMatrix(),this.clear(),this.states.setValue("imageMode",w),this.image(e,0,0,e.width,e.height,-e.width/2,-e.height/2,e.width,e.height),this.pop(),this.GL.clearDepth(1),this.GL.clear(this.GL.DEPTH_BUFFER_BIT)}zClipRange(){return[-1,1]}defaultNearScale(){return.1}defaultFarScale(){return 10}supportsTriangleFan(){return!0}viewport(e,t){this._viewport=[0,0,e,t],this.GL.viewport(0,0,e,t)}_updateViewport(){this._origViewport={width:this.GL.drawingBufferWidth,height:this.GL.drawingBufferHeight},this.viewport(this._origViewport.width,this._origViewport.height)}_createPixelsArray(){this.pixels=new Uint8Array(this.GL.drawingBufferWidth*this.GL.drawingBufferHeight*4)}clear(...e){const t=e[0]||0,r=e[1]||0,i=e[2]||0;let n=e[3]||0;const s=this.activeFramebuffer();s&&s.format===Ve&&!s.antialias&&0===n&&(n=1e-10),this.GL.clearColor(t*n,r*n,i*n,n),this.GL.clearDepth(1),this.GL.clear(this.GL.COLOR_BUFFER_BIT|this.GL.DEPTH_BUFFER_BIT)}clearDepth(e=1){this.GL.clearDepth(e),this.GL.clear(this.GL.DEPTH_BUFFER_BIT)}_applyStencilTestIfClipping(){const e=this.drawTarget();e._isClipApplied!==this._stencilTestOn&&(e._isClipApplied?(this._internalEnable.call(this.GL,this.GL.STENCIL_TEST),this._stencilTestOn=!0):(this._userEnabledStencil||this._internalDisable.call(this.GL,this.GL.STENCIL_TEST),this._stencilTestOn=!1))}baseMaterialShader(){if(!this._pInst._glAttributes.perPixelLighting)throw new Error("The material shader does not support hooks without perPixelLighting. Try turning it back on.");return super.baseMaterialShader()}_getLightShader(){return this._defaultLightShader||(this._pInst._glAttributes.perPixelLighting?this._defaultLightShader=new qa(this,this._webGL2CompatibilityPrefix("vert","highp")+Al.phongVert,this._webGL2CompatibilityPrefix("frag","highp")+Al.phongFrag,{vertex:{"void beforeVertex":"() {}","Vertex getObjectInputs":"(Vertex inputs) { return inputs; }","Vertex getWorldInputs":"(Vertex inputs) { return inputs; }","Vertex getCameraInputs":"(Vertex inputs) { return inputs; }","void afterVertex":"() {}"},fragment:{"void beforeFragment":"() {}","Inputs getPixelInputs":"(Inputs inputs) { return inputs; }","vec4 combineColors":"(ColorComponents components) {\n vec4 color = vec4(0.);\n color.rgb += components.diffuse * components.baseColor;\n color.rgb += components.ambient * components.ambientColor;\n color.rgb += components.specular * components.specularColor;\n color.rgb += components.emissive;\n color.a = components.opacity;\n return color;\n }","vec4 getFinalColor":"(vec4 color, vec2 texCoord) { return color; }","void afterFragment":"() {}"}}):this._defaultLightShader=new qa(this,this._webGL2CompatibilityPrefix("vert","highp")+Al.lightVert,this._webGL2CompatibilityPrefix("frag","highp")+Al.lightTextureFrag)),this._defaultLightShader}_getNormalShader(){return this._defaultNormalShader||(this._defaultNormalShader=new qa(this,this._webGL2CompatibilityPrefix("vert","highp")+Al.normalVert,this._webGL2CompatibilityPrefix("frag","highp")+Al.normalFrag,{vertex:{"void beforeVertex":"() {}","Vertex getObjectInputs":"(Vertex inputs) { return inputs; }","Vertex getWorldInputs":"(Vertex inputs) { return inputs; }","Vertex getCameraInputs":"(Vertex inputs) { return inputs; }","void afterVertex":"() {}"},fragment:{"void beforeFragment":"() {}","vec4 getFinalColor":"(vec4 color, vec2 texCoord) { return color; }","void afterFragment":"() {}"}})),this._defaultNormalShader}_getColorShader(){return this._defaultColorShader||(this._defaultColorShader=new qa(this,this._webGL2CompatibilityPrefix("vert","highp")+Al.normalVert,this._webGL2CompatibilityPrefix("frag","highp")+Al.basicFrag,{vertex:{"void beforeVertex":"() {}","Vertex getObjectInputs":"(Vertex inputs) { return inputs; }","Vertex getWorldInputs":"(Vertex inputs) { return inputs; }","Vertex getCameraInputs":"(Vertex inputs) { return inputs; }","void afterVertex":"() {}"},fragment:{"void beforeFragment":"() {}","vec4 getFinalColor":"(vec4 color, vec2 texCoord) { return color; }","void afterFragment":"() {}"}})),this._defaultColorShader}_getLineShader(){return this._defaultLineShader||(this._defaultLineShader=new qa(this,this._webGL2CompatibilityPrefix("vert","highp")+Al.lineVert,this._webGL2CompatibilityPrefix("frag","highp")+Al.lineFrag,{vertex:{"void beforeVertex":"() {}","StrokeVertex getObjectInputs":"(StrokeVertex inputs) { return inputs; }","StrokeVertex getWorldInputs":"(StrokeVertex inputs) { return inputs; }","StrokeVertex getCameraInputs":"(StrokeVertex inputs) { return inputs; }","void afterVertex":"() {}"},fragment:{"void beforeFragment":"() {}","Inputs getPixelInputs":"(Inputs inputs) { return inputs; }","vec4 getFinalColor":"(vec4 color, vec2 texCoord) { return color; }","bool shouldDiscard":"(bool outside) { return outside; }","void afterFragment":"() {}"}})),this._defaultLineShader}_getFontShader(){return this._defaultFontShader||(this.webglVersion===n&&this.GL.getExtension("OES_standard_derivatives"),this._defaultFontShader=new qa(this,this._webGL2CompatibilityPrefix("vert","highp")+Al.fontVert,this._webGL2CompatibilityPrefix("frag","highp")+Al.fontFrag)),this._defaultFontShader}baseFilterShader(){return this._baseFilterShader||(this._baseFilterShader=new qa(this,this._webGL2CompatibilityPrefix("vert","highp")+Al.filterBaseVert,this._webGL2CompatibilityPrefix("frag","highp")+Al.filterBaseFrag,{vertex:{},fragment:{"vec4 getColor":"(FilterInputs inputs, in sampler2D canvasContent) {\n return getTexture(canvasContent, inputs.texCoord);\n }"},hookAliases:{getColor:["filterColor"]}})),this._baseFilterShader}_webGL2CompatibilityPrefix(e,t){let r="";return this.webglVersion===s&&(r+="#version 300 es\n#define WEBGL2\n"),"vert"===e?r+="#define VERTEX_SHADER\n":"frag"===e&&(r+="#define FRAGMENT_SHADER\n"),t&&(r+=`precision ${t} float;\n`),r}_createImageLightShader(e){if("diffused"===e)return new qa(this,this._webGL2CompatibilityPrefix("vert","highp")+Al.imageLightVert,this._webGL2CompatibilityPrefix("frag","highp")+Al.imageLightDiffusedFrag);if("specular"===e)return new qa(this,this._webGL2CompatibilityPrefix("vert","highp")+Al.imageLightVert,this._webGL2CompatibilityPrefix("frag","highp")+Al.imageLightSpecularFrag);throw new Error(`Unknown imageLight shader type: ${e}`)}_createMipmapTexture(e){return new eo(this,e,{})}_prepareMipmapData(e,t){return{levels:[],size:e,mipLevels:t}}_accumulateMipLevel(e,t,r,i,n){const s=e.get().drawingContext.getImageData(0,0,i,n);t.levels.push(s)}_finalizeMipmapTexture(e){return new eo(this,e.levels,{minFilter:De,magFilter:we})}createMipmapTextureHandle({levels:e,format:t,dataType:r,width:i,height:n}){const s=this.GL,a=s.createTexture();s.bindTexture(s.TEXTURE_2D,a);const o=s.RGBA,h=s.UNSIGNED_BYTE;for(let t=0;t0){const i=!o;if(i&&(s[e.dst]=o=n.createBuffer()),n.bindBuffer(n.ARRAY_BUFFER,o),i||!1!==t.dirtyFlags[e.src]){const r=e.map,i=r?r(h):h;this._bindBuffer(o,n.ARRAY_BUFFER,i),t.dirtyFlags[e.src]=!1}r.enableAttrib(a,e.size)}else{const e=a.location;if(-1===e||!this.registerEnabled.has(e))return;n.disableVertexAttribArray(e),this.registerEnabled.delete(e)}}_enableAttrib(e,t,r,i,n,s,a){const o=t.location,h=this.GL;this.registerEnabled.has(o)||(h.enableVertexAttribArray(o),this.registerEnabled.add(o)),h.vertexAttribPointer(o,r,i||h.FLOAT,n||!1,s||0,a||0)}_ensureGeometryBuffers(e,t,r){const i=this.GL;if(t){let n=e.indexBuffer;n||(n=i.createBuffer()),this._bindBuffer(n,i.ELEMENT_ARRAY_BUFFER,t,r),e.indexBuffer=n,e.indexBufferType=r===Uint32Array?i.UNSIGNED_INT:i.UNSIGNED_SHORT}else e.indexBuffer&&(i.deleteBuffer(e.indexBuffer),e.indexBuffer=null)}_freeBuffers(e){const t=this.GL;function r(r){for(const i of r)e[i.dst]&&(t.deleteBuffer(e[i.dst]),e[i.dst]=null)}e.indexBuffer&&t.deleteBuffer(e.indexBuffer),r(this.buffers.stroke),r(this.buffers.fill),r(this.buffers.user)}_initShader(e){const t=this.GL,r=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(r,e.vertSrc()),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error(`Yikes! An error occurred compiling the vertex shader: ${t.getShaderInfoLog(r)} in:\n\n${e.vertSrc()}`);const i=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(i,e.fragSrc()),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS))throw new Error(`Darn! An error occurred compiling the fragment shader: ${t.getShaderInfoLog(i)}`);const n=t.createProgram();if(t.attachShader(n,r),t.attachShader(n,i),t.linkProgram(n),!t.getProgramParameter(n,t.LINK_STATUS))throw new Error(`Snap! Error linking shader program: ${t.getProgramInfoLog(n)}`);e._compiled=!0,e._glProgram=n,e._vertShader=r,e._fragShader=i}_finalizeShader(){}_getShaderAttributes(e){return oo(e,this.GL)}getUniformMetadata(e){return ao(e,this.GL)}updateUniformValue(e,t,r){return so(e,t,r,(e=>this.getTexture(e)),this.GL)}_updateTexture(e,t){const r=this.GL;r.activeTexture(r.TEXTURE0+e.samplerIndex),t.bindTexture(),t.update(),r.uniform1i(e.location,e.samplerIndex)}bindTexture(e){this.GL.bindTexture(this.GL.TEXTURE_2D,e.getTexture().texture)}unbindTexture(){this.GL.bindTexture(this.GL.TEXTURE_2D,null)}_unbindFramebufferTexture(e){const t=this.GL,r=this._getEmptyTexture();t.activeTexture(t.TEXTURE0+e.samplerIndex),r.bindTexture(),t.uniform1i(e.location,e.samplerIndex)}createTexture({width:e,height:t,format:r,dataType:i}){const n=this.GL,s=n.createTexture();return n.bindTexture(n.TEXTURE_2D,s),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e,t,0,n.RGBA,n.UNSIGNED_BYTE,null),{texture:s,glFormat:n.RGBA,glDataType:n.UNSIGNED_BYTE}}createFramebufferTextureHandle(e){return null}uploadTextureFromSource({texture:e,glFormat:t,glDataType:r},i){const n=this.GL;n.texImage2D(n.TEXTURE_2D,0,t,t,r,i)}uploadTextureFromData({texture:e,glFormat:t,glDataType:r},i,n,s){const a=this.GL;a.texImage2D(a.TEXTURE_2D,0,t,n,s,0,t,r,i)}getSampler(e){}bindTextureToShader({texture:e},t,r,i){const n=this.GL;n.activeTexture(n.TEXTURE0+i),n.bindTexture(n.TEXTURE_2D,e);const s=n.getUniformLocation(glProgram,r);n.uniform1i(s,i)}setTextureParams(e){return no(e,this.GL,this.webglVersion)}deleteTexture({texture:e}){this.GL.deleteTexture(e)}_applyColorBlend(e,t){const r=this.GL,i=this.states.drawMode===Ee,n=t||this.states.userFillShader||this.states.userStrokeShader||i||this.states.curBlendMode!==Z||e[e.length-1]<1||this._isErasing;return n!==this._isBlending&&(n||this.states.curBlendMode!==Z&&this.states.curBlendMode!==J?r.enable(r.BLEND):r.disable(r.BLEND),r.depthMask(!0),this._isBlending=n),this._applyBlendMode(),e}uniformNameFromHookKey(e){return e.slice(e.indexOf(" ")+1)}populateHooks(e,t,r){return ho(e,t,r)}getShaderHookTypes(e,t){return sh(e,t)}defaultFramebufferAlpha(){return this._pInst._glAttributes.alpha}defaultFramebufferAntialias(){return!!this.supportsFramebufferAntialias()&&this._pInst._glAttributes.antialias}supportsFramebufferAntialias(){return this.webglVersion===s}createFramebufferResources(e){const t=this.GL;if(e.framebuffer=t.createFramebuffer(),!e.framebuffer)throw new Error("Unable to create a framebuffer");if(e.antialias&&(e.aaFramebuffer=t.createFramebuffer(),!e.aaFramebuffer))throw new Error("Unable to create a framebuffer for antialiasing")}validateFramebufferFormats(e){const t=this.GL;e.useDepth&&this.webglVersion===n&&!t.getExtension("WEBGL_depth_texture")&&(console.warn("Unable to create depth textures in this environment. Falling back to a framebuffer without depth."),e.useDepth=!1),e.useDepth&&this.webglVersion===n&&e.depthFormat===ze&&(console.warn("FLOAT depth format is unavailable in WebGL 1. Defaulting to UNSIGNED_INT."),e.depthFormat=Ue),[Ve,ze,je].includes(e.format)||(console.warn("Unknown Framebuffer format. Please use UNSIGNED_BYTE, FLOAT, or HALF_FLOAT. Defaulting to UNSIGNED_BYTE."),e.format=Ve),e.useDepth&&![Ue,ze].includes(e.depthFormat)&&(console.warn("Unknown Framebuffer depth format. Please use UNSIGNED_INT or FLOAT. Defaulting to FLOAT."),e.depthFormat=ze);const r=uo(this);r.float||e.format!==ze||(console.warn("This environment does not support FLOAT textures. Falling back to UNSIGNED_BYTE."),e.format=Ve),e.useDepth&&!r.float&&e.depthFormat===ze&&(console.warn("This environment does not support FLOAT depth textures. Falling back to UNSIGNED_INT."),e.depthFormat=Ue),r.halfFloat||e.format!==je||(console.warn("This environment does not support HALF_FLOAT textures. Falling back to UNSIGNED_BYTE."),e.format=Ve),e.channels===Ti&&[ze,je].includes(e.format)&&(console.warn("FLOAT and HALF_FLOAT formats do not work cross-platform with only RGB channels. Falling back to RGBA."),e.channels=Ni)}recreateFramebufferTextures(e){const t=this.GL,r=t.getParameter(t.TEXTURE_BINDING_2D),i=t.getParameter(t.FRAMEBUFFER_BINDING),n=t.createTexture();if(!n)throw new Error("Unable to create color texture");t.bindTexture(t.TEXTURE_2D,n);const s=this._getFramebufferColorFormat(e);if(t.texImage2D(t.TEXTURE_2D,0,s.internalFormat,e.width*e.density,e.height*e.density,0,s.format,s.type,null),e.colorTexture=n,t.bindFramebuffer(t.FRAMEBUFFER,e.framebuffer),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0),e.useDepth){const r=t.createTexture();if(!r)throw new Error("Unable to create depth texture");const i=this._getFramebufferDepthFormat(e);t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,i.internalFormat,e.width*e.density,e.height*e.density,0,i.format,i.type,null),t.framebufferTexture2D(t.FRAMEBUFFER,e.useStencil?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,t.TEXTURE_2D,r,0),e.depthTexture=r}if(e.antialias){if(e.colorRenderbuffer=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,e.colorRenderbuffer),t.renderbufferStorageMultisample(t.RENDERBUFFER,Math.max(0,Math.min(e.antialiasSamples,t.getParameter(t.MAX_SAMPLES))),s.internalFormat,e.width*e.density,e.height*e.density),e.useDepth){const r=this._getFramebufferDepthFormat(e);e.depthRenderbuffer=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,e.depthRenderbuffer),t.renderbufferStorageMultisample(t.RENDERBUFFER,Math.max(0,Math.min(e.antialiasSamples,t.getParameter(t.MAX_SAMPLES))),r.internalFormat,e.width*e.density,e.height*e.density)}t.bindFramebuffer(t.FRAMEBUFFER,e.aaFramebuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,e.colorRenderbuffer),e.useDepth&&t.framebufferRenderbuffer(t.FRAMEBUFFER,e.useStencil?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,t.RENDERBUFFER,e.depthRenderbuffer)}t.bindTexture(t.TEXTURE_2D,r),t.bindFramebuffer(t.FRAMEBUFFER,i)}_getFramebufferColorFormat(e){let t,r,i;const n=this.GL;if(t=e.format===ze?n.FLOAT:e.format===je?this.webglVersion===s?n.HALF_FLOAT:n.getExtension("OES_texture_half_float").HALF_FLOAT_OES:n.UNSIGNED_BYTE,r=e.channels===Ni?n.RGBA:n.RGB,this.webglVersion===s){i={[n.FLOAT]:{[n.RGBA]:n.RGBA32F},[n.HALF_FLOAT]:{[n.RGBA]:n.RGBA16F},[n.UNSIGNED_BYTE]:{[n.RGBA]:n.RGBA8,[n.RGB]:n.RGB8}}[t][r]}else i=e.format===je?n.RGBA:r;return{internalFormat:i,format:r,type:t}}_getFramebufferDepthFormat(e){let t,r,i;const n=this.GL;return t=e.useStencil?e.depthFormat===ze?n.FLOAT_32_UNSIGNED_INT_24_8_REV:this.webglVersion===s?n.UNSIGNED_INT_24_8:n.getExtension("WEBGL_depth_texture").UNSIGNED_INT_24_8_WEBGL:e.depthFormat===ze?n.FLOAT:n.UNSIGNED_INT,r=e.useStencil?n.DEPTH_STENCIL:n.DEPTH_COMPONENT,i=e.useStencil?e.depthFormat===ze?n.DEPTH32F_STENCIL8:this.webglVersion===s?n.DEPTH24_STENCIL8:n.DEPTH_STENCIL:this.webglVersion===s?e.depthFormat===ze?n.DEPTH_COMPONENT32F:n.DEPTH_COMPONENT24:n.DEPTH_COMPONENT,{internalFormat:i,format:r,type:t}}_deleteFramebufferTexture(e){this.GL.deleteTexture(e.rawTexture().texture),this.textures.delete(e)}deleteFramebufferTextures(e){this._deleteFramebufferTexture(e.color),e.depth&&this._deleteFramebufferTexture(e.depth);const t=this.GL;e.colorRenderbuffer&&t.deleteRenderbuffer(e.colorRenderbuffer),e.depthRenderbuffer&&t.deleteRenderbuffer(e.depthRenderbuffer)}deleteFramebufferResources(e){const t=this.GL;t.deleteFramebuffer(e.framebuffer),e.aaFramebuffer&&t.deleteFramebuffer(e.aaFramebuffer),e.depthRenderbuffer&&t.deleteRenderbuffer(e.depthRenderbuffer),e.colorRenderbuffer&&t.deleteRenderbuffer(e.colorRenderbuffer)}getFramebufferToBind(e){return e.antialias?e.aaFramebuffer:e.framebuffer}updateFramebufferTexture(e,t){if(e.antialias){const r=this.GL;r.bindFramebuffer(r.READ_FRAMEBUFFER,e.aaFramebuffer),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,e.framebuffer);const i={colorTexture:[r.COLOR_BUFFER_BIT,e.colorP5Texture.magFilter===we?r.LINEAR:r.NEAREST]};e.useDepth&&(i.depthTexture=[r.DEPTH_BUFFER_BIT,e.depthP5Texture.magFilter===we?r.LINEAR:r.NEAREST]);const[n,s]=i[t];r.blitFramebuffer(0,0,e.width*e.density,e.height*e.density,0,0,e.width*e.density,e.height*e.density,n,s);const a=this.activeFramebuffer();this.bindFramebuffer(a)}}bindFramebuffer(e){const t=this.GL;t.bindFramebuffer(t.FRAMEBUFFER,e?this.getFramebufferToBind(e):null)}framebufferYScale(){return-1}readFramebufferPixels(e){const t=this.GL,r=this.activeFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,e.framebuffer);const i=this._getFramebufferColorFormat(e),n=ro(e.pixels,t,e.framebuffer,0,0,e.width*e.density,e.height*e.density,i.format,i.type);return this.bindFramebuffer(r),n}readFramebufferPixel(e,t,r){const i=this._getFramebufferColorFormat(e);return io(this.GL,e.framebuffer,t,r,i.format,i.type)}readFramebufferRegion(e,t,r,i,n){const s=this.GL,a=this._getFramebufferColorFormat(e),o=ro(void 0,s,e.framebuffer,t*e.density,r*e.density,i*e.density,n*e.density,a.format,a.type),h=new Uint8ClampedArray(i*n*e.density*e.density*4);h.fill(255);const u=a.format===s.RGB?3:4;for(let t=0;te)return!1;if((r+=t[i+1])>=e)return!0}return!1}function Rl(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&Ol.test(String.fromCharCode(e)):!1!==t&&Nl(e,Fl)))}function Vl(e,t){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&Pl.test(String.fromCharCode(e)):!1!==t&&(Nl(e,Fl)||Nl(e,Tl)))))}var Ul=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function zl(e,t){return new Ul(e,{beforeExpr:!0,binop:t})}var jl={beforeExpr:!0},Gl={startsExpr:!0},$l={};function Hl(e,t){return void 0===t&&(t={}),t.keyword=e,$l[e]=new Ul(e,t)}var ql={num:new Ul("num",Gl),regexp:new Ul("regexp",Gl),string:new Ul("string",Gl),name:new Ul("name",Gl),privateId:new Ul("privateId",Gl),eof:new Ul("eof"),bracketL:new Ul("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new Ul("]"),braceL:new Ul("{",{beforeExpr:!0,startsExpr:!0}),braceR:new Ul("}"),parenL:new Ul("(",{beforeExpr:!0,startsExpr:!0}),parenR:new Ul(")"),comma:new Ul(",",jl),semi:new Ul(";",jl),colon:new Ul(":",jl),dot:new Ul("."),question:new Ul("?",jl),questionDot:new Ul("?."),arrow:new Ul("=>",jl),template:new Ul("template"),invalidTemplate:new Ul("invalidTemplate"),ellipsis:new Ul("...",jl),backQuote:new Ul("`",Gl),dollarBraceL:new Ul("${",{beforeExpr:!0,startsExpr:!0}),eq:new Ul("=",{beforeExpr:!0,isAssign:!0}),assign:new Ul("_=",{beforeExpr:!0,isAssign:!0}),incDec:new Ul("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new Ul("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:zl("||",1),logicalAND:zl("&&",2),bitwiseOR:zl("|",3),bitwiseXOR:zl("^",4),bitwiseAND:zl("&",5),equality:zl("==/!=/===/!==",6),relational:zl("/<=/>=",7),bitShift:zl("<>/>>>",8),plusMin:new Ul("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:zl("%",10),star:zl("*",10),slash:zl("/",10),starstar:new Ul("**",{beforeExpr:!0}),coalesce:zl("??",1),_break:Hl("break"),_case:Hl("case",jl),_catch:Hl("catch"),_continue:Hl("continue"),_debugger:Hl("debugger"),_default:Hl("default",jl),_do:Hl("do",{isLoop:!0,beforeExpr:!0}),_else:Hl("else",jl),_finally:Hl("finally"),_for:Hl("for",{isLoop:!0}),_function:Hl("function",Gl),_if:Hl("if"),_return:Hl("return",jl),_switch:Hl("switch"),_throw:Hl("throw",jl),_try:Hl("try"),_var:Hl("var"),_const:Hl("const"),_while:Hl("while",{isLoop:!0}),_with:Hl("with"),_new:Hl("new",{beforeExpr:!0,startsExpr:!0}),_this:Hl("this",Gl),_super:Hl("super",Gl),_class:Hl("class",Gl),_extends:Hl("extends",jl),_export:Hl("export"),_import:Hl("import",Gl),_null:Hl("null",Gl),_true:Hl("true",Gl),_false:Hl("false",Gl),_in:Hl("in",{beforeExpr:!0,binop:7}),_instanceof:Hl("instanceof",{beforeExpr:!0,binop:7}),_typeof:Hl("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:Hl("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:Hl("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},Wl=/\r\n?|\n|\u2028|\u2029/,Xl=new RegExp(Wl.source,"g");function Yl(e){return 10===e||13===e||8232===e||8233===e}function Zl(e,t,r){void 0===r&&(r=e.length);for(var i=t;i>10),56320+(1023&e)))}var oc=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,hc=function(e,t){this.line=e,this.column=t};hc.prototype.offset=function(e){return new hc(this.line,this.column+e)};var uc=function(e,t,r){this.start=t,this.end=r,null!==e.sourceFile&&(this.source=e.sourceFile)};function lc(e,t){for(var r=1,i=0;;){var n=Zl(e,i,t);if(n<0)return new hc(r,t-i);++r,i=n}}var cc={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},pc=!1;function dc(e){var t={};for(var r in cc)t[r]=e&&rc(e,r)?e[r]:cc[r];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!pc&&"object"==typeof console&&console.warn&&(pc=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),ic(t.onToken)){var i=t.onToken;t.onToken=function(e){return i.push(e)}}return ic(t.onComment)&&(t.onComment=function(e,t){return function(r,i,n,s,a,o){var h={type:r?"Block":"Line",value:i,start:n,end:s};e.locations&&(h.loc=new uc(this,a,o)),e.ranges&&(h.range=[n,s]),t.push(h)}}(t,t.onComment)),t}var fc=256,mc=259;function gc(e,t){return 2|(e?4:0)|(t?8:0)}var yc=function(e,t,r){this.options=e=dc(e),this.sourceFile=e.sourceFile,this.keywords=sc(Bl[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var i="";!0!==e.allowReserved&&(i=Ml[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(i+=" await")),this.reservedWords=sc(i);var n=(i?i+" ":"")+Ml.strict;this.reservedWordsStrict=sc(n),this.reservedWordsStrictBind=sc(n+" "+Ml.strictBind),this.input=String(t),this.containsEsc=!1,r?(this.pos=r,this.lineStart=this.input.lastIndexOf("\n",r-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(Wl).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=ql.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},xc={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};yc.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},xc.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},xc.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0},xc.inAsync.get=function(){return(4&this.currentVarScope().flags)>0},xc.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(768&t)return!1;if(2&t)return(4&t)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},xc.allowSuper.get=function(){return(64&this.currentThisScope().flags)>0||this.options.allowSuperOutsideMethod},xc.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},xc.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},xc.allowNewDotTarget.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(768&t||2&t&&!(16&t))return!0}return!1},xc.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&fc)>0},yc.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var r=this,i=0;i=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(i+1))}e+=t[0].length,Jl.lastIndex=e,e+=Jl.exec(this.input)[0].length,";"===this.input[e]&&e++}},vc.eat=function(e){return this.type===e&&(this.next(),!0)},vc.isContextual=function(e){return this.type===ql.name&&this.value===e&&!this.containsEsc},vc.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},vc.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},vc.canInsertSemicolon=function(){return this.type===ql.eof||this.type===ql.braceR||Wl.test(this.input.slice(this.lastTokEnd,this.start))},vc.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},vc.semicolon=function(){this.eat(ql.semi)||this.insertSemicolon()||this.unexpected()},vc.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},vc.expect=function(e){this.eat(e)||this.unexpected()},vc.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var _c=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};vc.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var r=t?e.parenthesizedAssign:e.parenthesizedBind;r>-1&&this.raiseRecoverable(r,t?"Assigning to rvalue":"Parenthesized pattern")}},vc.checkExpressionErrors=function(e,t){if(!e)return!1;var r=e.shorthandAssign,i=e.doubleProto;if(!t)return r>=0||i>=0;r>=0&&this.raise(r,"Shorthand property assignments are valid only in destructuring patterns"),i>=0&&this.raiseRecoverable(i,"Redefinition of __proto__ property")},vc.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&i<56320)return!0;if(Rl(i,!0)){for(var n=r+1;Vl(i=this.input.charCodeAt(n),!0);)++n;if(92===i||i>55295&&i<56320)return!0;var s=this.input.slice(r,n);if(!Ll.test(s))return!0}return!1},wc.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;Jl.lastIndex=this.pos;var e,t=Jl.exec(this.input),r=this.pos+t[0].length;return!(Wl.test(this.input.slice(this.pos,r))||"function"!==this.input.slice(r,r+8)||r+8!==this.input.length&&(Vl(e=this.input.charCodeAt(r+8))||e>55295&&e<56320))},wc.isUsingKeyword=function(e,t){if(this.options.ecmaVersion<17||!this.isContextual(e?"await":"using"))return!1;Jl.lastIndex=this.pos;var r=Jl.exec(this.input),i=this.pos+r[0].length;if(Wl.test(this.input.slice(this.pos,i)))return!1;if(e){var n,s=i+5;if("using"!==this.input.slice(i,s)||s===this.input.length||Vl(n=this.input.charCodeAt(s))||n>55295&&n<56320)return!1;Jl.lastIndex=s;var a=Jl.exec(this.input);if(a&&Wl.test(this.input.slice(s,s+a[0].length)))return!1}if(t){var o,h=i+2;if(!("of"!==this.input.slice(i,h)||h!==this.input.length&&(Vl(o=this.input.charCodeAt(h))||o>55295&&o<56320)))return!1}var u=this.input.charCodeAt(i);return Rl(u,!0)||92===u},wc.isAwaitUsing=function(e){return this.isUsingKeyword(!0,e)},wc.isUsing=function(e){return this.isUsingKeyword(!1,e)},wc.parseStatement=function(e,t,r){var i,n=this.type,s=this.startNode();switch(this.isLet(e)&&(n=ql._var,i="let"),n){case ql._break:case ql._continue:return this.parseBreakContinueStatement(s,n.keyword);case ql._debugger:return this.parseDebuggerStatement(s);case ql._do:return this.parseDoStatement(s);case ql._for:return this.parseForStatement(s);case ql._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(s,!1,!e);case ql._class:return e&&this.unexpected(),this.parseClass(s,!0);case ql._if:return this.parseIfStatement(s);case ql._return:return this.parseReturnStatement(s);case ql._switch:return this.parseSwitchStatement(s);case ql._throw:return this.parseThrowStatement(s);case ql._try:return this.parseTryStatement(s);case ql._const:case ql._var:return i=i||this.value,e&&"var"!==i&&this.unexpected(),this.parseVarStatement(s,i);case ql._while:return this.parseWhileStatement(s);case ql._with:return this.parseWithStatement(s);case ql.braceL:return this.parseBlock(!0,s);case ql.semi:return this.parseEmptyStatement(s);case ql._export:case ql._import:if(this.options.ecmaVersion>10&&n===ql._import){Jl.lastIndex=this.pos;var a=Jl.exec(this.input),o=this.pos+a[0].length,h=this.input.charCodeAt(o);if(40===h||46===h)return this.parseExpressionStatement(s,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===ql._import?this.parseImport(s):this.parseExport(s,r);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(s,!0,!e);var u=this.isAwaitUsing(!1)?"await using":this.isUsing(!1)?"using":null;if(u)return t&&"script"===this.options.sourceType&&this.raise(this.start,"Using declaration cannot appear in the top level when source type is `script`"),"await using"===u&&(this.canAwait||this.raise(this.start,"Await using cannot appear outside of async function"),this.next()),this.next(),this.parseVar(s,!1,u),this.semicolon(),this.finishNode(s,"VariableDeclaration");var l=this.value,c=this.parseExpression();return n===ql.name&&"Identifier"===c.type&&this.eat(ql.colon)?this.parseLabeledStatement(s,l,c,e):this.parseExpressionStatement(s,c)}},wc.parseBreakContinueStatement=function(e,t){var r="break"===t;this.next(),this.eat(ql.semi)||this.insertSemicolon()?e.label=null:this.type!==ql.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var i=0;i=6?this.eat(ql.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},wc.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(Cc),this.enterScope(0),this.expect(ql.parenL),this.type===ql.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var r=this.isLet();if(this.type===ql._var||this.type===ql._const||r){var i=this.startNode(),n=r?"let":this.value;return this.next(),this.parseVar(i,!0,n),this.finishNode(i,"VariableDeclaration"),this.parseForAfterInit(e,i,t)}var s=this.isContextual("let"),a=!1,o=this.isUsing(!0)?"using":this.isAwaitUsing(!0)?"await using":null;if(o){var h=this.startNode();return this.next(),"await using"===o&&this.next(),this.parseVar(h,!0,o),this.finishNode(h,"VariableDeclaration"),this.parseForAfterInit(e,h,t)}var u=this.containsEsc,l=new _c,c=this.start,p=t>-1?this.parseExprSubscripts(l,"await"):this.parseExpression(!0,l);return this.type===ql._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===ql._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(p.start!==c||u||"Identifier"!==p.type||"async"!==p.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),s&&a&&this.raise(p.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(p,!1,l),this.checkLValPattern(p),this.parseForIn(e,p)):(this.checkExpressionErrors(l,!0),t>-1&&this.unexpected(t),this.parseFor(e,p))},wc.parseForAfterInit=function(e,t,r){return(this.type===ql._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===t.declarations.length?(this.options.ecmaVersion>=9&&(this.type===ql._in?r>-1&&this.unexpected(r):e.await=r>-1),this.parseForIn(e,t)):(r>-1&&this.unexpected(r),this.parseFor(e,t))},wc.parseFunctionStatement=function(e,t,r){return this.next(),this.parseFunction(e,Dc|(r?0:Sc),!1,t)},wc.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(ql._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},wc.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(ql.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},wc.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(ql.braceL),this.labels.push(Ec),this.enterScope(0);for(var r=!1;this.type!==ql.braceR;)if(this.type===ql._case||this.type===ql._default){var i=this.type===ql._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),i?t.test=this.parseExpression():(r&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),r=!0,t.test=null),this.expect(ql.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},wc.parseThrowStatement=function(e){return this.next(),Wl.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var Ac=[];wc.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(ql.parenR),e},wc.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===ql._catch){var t=this.startNode();this.next(),this.eat(ql.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(ql._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},wc.parseVarStatement=function(e,t,r){return this.next(),this.parseVar(e,!1,t,r),this.semicolon(),this.finishNode(e,"VariableDeclaration")},wc.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(Cc),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},wc.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},wc.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},wc.parseLabeledStatement=function(e,t,r,i){for(var n=0,s=this.labels;n=0;o--){var h=this.labels[o];if(h.statementStart!==e.start)break;h.statementStart=this.start,h.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(i?-1===i.indexOf("label")?i+"label":i:"label"),this.labels.pop(),e.label=r,this.finishNode(e,"LabeledStatement")},wc.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},wc.parseBlock=function(e,t,r){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(ql.braceL),e&&this.enterScope(0);this.type!==ql.braceR;){var i=this.parseStatement(null);t.body.push(i)}return r&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},wc.parseFor=function(e,t){return e.init=t,this.expect(ql.semi),e.test=this.type===ql.semi?null:this.parseExpression(),this.expect(ql.semi),e.update=this.type===ql.parenR?null:this.parseExpression(),this.expect(ql.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},wc.parseForIn=function(e,t){var r=this.type===ql._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!r||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(r?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=r?this.parseExpression():this.parseMaybeAssign(),this.expect(ql.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,r?"ForInStatement":"ForOfStatement")},wc.parseVar=function(e,t,r,i){for(e.declarations=[],e.kind=r;;){var n=this.startNode();if(this.parseVarId(n,r),this.eat(ql.eq)?n.init=this.parseMaybeAssign(t):i||"const"!==r||this.type===ql._in||this.options.ecmaVersion>=6&&this.isContextual("of")?i||"using"!==r&&"await using"!==r||!(this.options.ecmaVersion>=17)||this.type===ql._in||this.isContextual("of")?i||"Identifier"===n.id.type||t&&(this.type===ql._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.raise(this.lastTokEnd,"Missing initializer in "+r+" declaration"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(ql.comma))break}return e},wc.parseVarId=function(e,t){e.id="using"===t||"await using"===t?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var Dc=1,Sc=2;function Tc(e,t){var r=t.key.name,i=e[r],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===i&&"iset"===n||"iset"===i&&"iget"===n||"sget"===i&&"sset"===n||"sset"===i&&"sget"===n?(e[r]="true",!1):!!i||(e[r]=n,!1)}function Fc(e,t){var r=e.computed,i=e.key;return!r&&("Identifier"===i.type&&i.name===t||"Literal"===i.type&&i.value===t)}wc.parseFunction=function(e,t,r,i,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!i)&&(this.type===ql.star&&t&Sc&&this.unexpected(),e.generator=this.eat(ql.star)),this.options.ecmaVersion>=8&&(e.async=!!i),t&Dc&&(e.id=4&t&&this.type!==ql.name?null:this.parseIdent(),!e.id||t&Sc||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var s=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(gc(e.async,e.generator)),t&Dc||(e.id=this.type===ql.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,r,!1,n),this.yieldPos=s,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&Dc?"FunctionDeclaration":"FunctionExpression")},wc.parseFunctionParams=function(e){this.expect(ql.parenL),e.params=this.parseBindingList(ql.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},wc.parseClass=function(e,t){this.next();var r=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var i=this.enterClassBody(),n=this.startNode(),s=!1;for(n.body=[],this.expect(ql.braceL);this.type!==ql.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(n.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(s&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),s=!0):a.key&&"PrivateIdentifier"===a.key.type&&Tc(i,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=r,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},wc.parseClassElement=function(e){if(this.eat(ql.semi))return null;var t=this.options.ecmaVersion,r=this.startNode(),i="",n=!1,s=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(ql.braceL))return this.parseClassStaticBlock(r),r;this.isClassElementNameStart()||this.type===ql.star?o=!0:i="static"}if(r.static=o,!i&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==ql.star||this.canInsertSemicolon()?i="async":s=!0),!i&&(t>=9||!s)&&this.eat(ql.star)&&(n=!0),!i&&!s&&!n){var h=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=h:i=h)}if(i?(r.computed=!1,r.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),r.key.name=i,this.finishNode(r.key,"Identifier")):this.parseClassElementName(r),t<13||this.type===ql.parenL||"method"!==a||n||s){var u=!r.static&&Fc(r,"constructor"),l=u&&e;u&&"method"!==a&&this.raise(r.key.start,"Constructor can't have get/set modifier"),r.kind=u?"constructor":a,this.parseClassMethod(r,n,s,l)}else this.parseClassField(r);return r},wc.isClassElementNameStart=function(){return this.type===ql.name||this.type===ql.privateId||this.type===ql.num||this.type===ql.string||this.type===ql.bracketL||this.type.keyword},wc.parseClassElementName=function(e){this.type===ql.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},wc.parseClassMethod=function(e,t,r,i){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),r&&this.raise(n.start,"Constructor can't be an async method")):e.static&&Fc(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var s=e.value=this.parseMethod(t,r,i);return"get"===e.kind&&0!==s.params.length&&this.raiseRecoverable(s.start,"getter should have no params"),"set"===e.kind&&1!==s.params.length&&this.raiseRecoverable(s.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===s.params[0].type&&this.raiseRecoverable(s.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},wc.parseClassField=function(e){return Fc(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&Fc(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(ql.eq)?(this.enterScope(576),e.value=this.parseMaybeAssign(),this.exitScope()):e.value=null,this.semicolon(),this.finishNode(e,"PropertyDefinition")},wc.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==ql.braceR;){var r=this.parseStatement(null);e.body.push(r)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},wc.parseClassId=function(e,t){this.type===ql.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},wc.parseClassSuper=function(e){e.superClass=this.eat(ql._extends)?this.parseExprSubscripts(null,!1):null},wc.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},wc.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,r=e.used;if(this.options.checkPrivateFields)for(var i=this.privateNameStack.length,n=0===i?null:this.privateNameStack[i-1],s=0;s=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==ql.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},wc.parseExport=function(e,t){if(this.next(),this.eat(ql.star))return this.parseExportAllDeclaration(e,t);if(this.eat(ql._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[]);else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==ql.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var r=0,i=e.specifiers;r=16&&(e.attributes=[])}this.semicolon()}return this.finishNode(e,"ExportNamedDeclaration")},wc.parseExportDeclaration=function(e){return this.parseStatement(null)},wc.parseExportDefaultDeclaration=function(){var e;if(this.type===ql._function||(e=this.isAsyncFunction())){var t=this.startNode();return this.next(),e&&this.next(),this.parseFunction(t,4|Dc,!1,e)}if(this.type===ql._class){var r=this.startNode();return this.parseClass(r,"nullableID")}var i=this.parseMaybeAssign();return this.semicolon(),i},wc.checkExport=function(e,t,r){e&&("string"!=typeof t&&(t="Identifier"===t.type?t.name:t.value),rc(e,t)&&this.raiseRecoverable(r,"Duplicate export '"+t+"'"),e[t]=!0)},wc.checkPatternExport=function(e,t){var r=t.type;if("Identifier"===r)this.checkExport(e,t,t.start);else if("ObjectPattern"===r)for(var i=0,n=t.properties;i=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},wc.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},wc.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},wc.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},wc.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===ql.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(ql.comma)))return e;if(this.type===ql.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(ql.braceL);!this.eat(ql.braceR);){if(t)t=!1;else if(this.expect(ql.comma),this.afterTrailingComma(ql.braceR))break;e.push(this.parseImportSpecifier())}return e},wc.parseWithClause=function(){var e=[];if(!this.eat(ql._with))return e;this.expect(ql.braceL);for(var t={},r=!0;!this.eat(ql.braceR);){if(r)r=!1;else if(this.expect(ql.comma),this.afterTrailingComma(ql.braceR))break;var i=this.parseImportAttribute(),n="Identifier"===i.key.type?i.key.name:i.key.value;rc(t,n)&&this.raiseRecoverable(i.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(i)}return e},wc.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===ql.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(ql.colon),this.type!==ql.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},wc.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===ql.string){var e=this.parseLiteral(this.value);return oc.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},wc.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var kc=yc.prototype;kc.toAssignable=function(e,t,r){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",r&&this.checkPatternErrors(r,!0);for(var i=0,n=e.properties;i=8&&!o&&"async"===h.name&&!this.canInsertSemicolon()&&this.eat(ql._function))return this.overrideContext(Ic.f_expr),this.parseFunction(this.startNodeAt(s,a),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(ql.arrow))return this.parseArrowExpression(this.startNodeAt(s,a),[h],!1,t);if(this.options.ecmaVersion>=8&&"async"===h.name&&this.type===ql.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return h=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(ql.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(s,a),[h],!0,t)}return h;case ql.regexp:var u=this.value;return(i=this.parseLiteral(u.value)).regex={pattern:u.pattern,flags:u.flags},i;case ql.num:case ql.string:return this.parseLiteral(this.value);case ql._null:case ql._true:case ql._false:return(i=this.startNode()).value=this.type===ql._null?null:this.type===ql._true,i.raw=this.type.keyword,this.next(),this.finishNode(i,"Literal");case ql.parenL:var l=this.start,c=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=l),e.parenthesizedBind<0&&(e.parenthesizedBind=l)),c;case ql.bracketL:return i=this.startNode(),this.next(),i.elements=this.parseExprList(ql.bracketR,!0,!0,e),this.finishNode(i,"ArrayExpression");case ql.braceL:return this.overrideContext(Ic.b_expr),this.parseObj(!1,e);case ql._function:return i=this.startNode(),this.next(),this.parseFunction(i,0);case ql._class:return this.parseClass(this.startNode(),!1);case ql._new:return this.parseNew();case ql.backQuote:return this.parseTemplate();case ql._import:return this.options.ecmaVersion>=11?this.parseExprImport(r):this.unexpected();default:return this.parseExprAtomDefault()}},Lc.parseExprAtomDefault=function(){this.unexpected()},Lc.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===ql.parenL&&!e)return this.parseDynamicImport(t);if(this.type===ql.dot){var r=this.startNodeAt(t.start,t.loc&&t.loc.start);return r.name="import",t.meta=this.finishNode(r,"Identifier"),this.parseImportMeta(t)}this.unexpected()},Lc.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(ql.parenR)?e.options=null:(this.expect(ql.comma),this.afterTrailingComma(ql.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(ql.parenR)||(this.expect(ql.comma),this.afterTrailingComma(ql.parenR)||this.unexpected())));else if(!this.eat(ql.parenR)){var t=this.start;this.eat(ql.comma)&&this.eat(ql.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},Lc.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},Lc.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=null!=t.value?t.value.toString():t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},Lc.parseParenExpression=function(){this.expect(ql.parenL);var e=this.parseExpression();return this.expect(ql.parenR),e},Lc.shouldParseArrow=function(e){return!this.canInsertSemicolon()},Lc.parseParenAndDistinguishExpression=function(e,t){var r,i=this.start,n=this.startLoc,s=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,h=this.startLoc,u=[],l=!0,c=!1,p=new _c,d=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==ql.parenR;){if(l?l=!1:this.expect(ql.comma),s&&this.afterTrailingComma(ql.parenR,!0)){c=!0;break}if(this.type===ql.ellipsis){a=this.start,u.push(this.parseParenItem(this.parseRestBinding())),this.type===ql.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}u.push(this.parseMaybeAssign(!1,p,this.parseParenItem))}var m=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(ql.parenR),e&&this.shouldParseArrow(u)&&this.eat(ql.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=d,this.awaitPos=f,this.parseParenArrowList(i,n,u,t);u.length&&!c||this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=f||this.awaitPos,u.length>1?((r=this.startNodeAt(o,h)).expressions=u,this.finishNodeAt(r,"SequenceExpression",m,g)):r=u[0]}else r=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(i,n);return y.expression=r,this.finishNode(y,"ParenthesizedExpression")}return r},Lc.parseParenItem=function(e){return e},Lc.parseParenArrowList=function(e,t,r,i){return this.parseArrowExpression(this.startNodeAt(e,t),r,!1,i)};var Nc=[];Lc.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===ql.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var r=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),r&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var i=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),i,n,!0,!1),this.eat(ql.parenL)?e.arguments=this.parseExprList(ql.parenR,this.options.ecmaVersion>=8,!1):e.arguments=Nc,this.finishNode(e,"NewExpression")},Lc.parseTemplateElement=function(e){var t=e.isTagged,r=this.startNode();return this.type===ql.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),r.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):r.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),r.tail=this.type===ql.backQuote,this.finishNode(r,"TemplateElement")},Lc.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var r=this.startNode();this.next(),r.expressions=[];var i=this.parseTemplateElement({isTagged:t});for(r.quasis=[i];!i.tail;)this.type===ql.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(ql.dollarBraceL),r.expressions.push(this.parseExpression()),this.expect(ql.braceR),r.quasis.push(i=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(r,"TemplateLiteral")},Lc.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===ql.name||this.type===ql.num||this.type===ql.string||this.type===ql.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===ql.star)&&!Wl.test(this.input.slice(this.lastTokEnd,this.start))},Lc.parseObj=function(e,t){var r=this.startNode(),i=!0,n={};for(r.properties=[],this.next();!this.eat(ql.braceR);){if(i)i=!1;else if(this.expect(ql.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(ql.braceR))break;var s=this.parseProperty(e,t);e||this.checkPropClash(s,n,t),r.properties.push(s)}return this.finishNode(r,e?"ObjectPattern":"ObjectExpression")},Lc.parseProperty=function(e,t){var r,i,n,s,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(ql.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===ql.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===ql.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(n=this.start,s=this.startLoc),e||(r=this.eat(ql.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!r&&this.isAsyncProp(a)?(i=!0,r=this.options.ecmaVersion>=9&&this.eat(ql.star),this.parsePropertyName(a)):i=!1,this.parsePropertyValue(a,e,r,i,n,s,t,o),this.finishNode(a,"Property")},Lc.parseGetterSetter=function(e){var t=e.key.name;this.parsePropertyName(e),e.value=this.parseMethod(!1),e.kind=t;var r="get"===e.kind?0:1;if(e.value.params.length!==r){var i=e.value.start;"get"===e.kind?this.raiseRecoverable(i,"getter should have no params"):this.raiseRecoverable(i,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},Lc.parsePropertyValue=function(e,t,r,i,n,s,a,o){(r||i)&&this.type===ql.colon&&this.unexpected(),this.eat(ql.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===ql.parenL?(t&&this.unexpected(),e.method=!0,e.value=this.parseMethod(r,i),e.kind="init"):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===ql.comma||this.type===ql.braceR||this.type===ql.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((r||i)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),t?e.value=this.parseMaybeDefault(n,s,this.copyNode(e.key)):this.type===ql.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,s,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.kind="init",e.shorthand=!0):this.unexpected():((r||i)&&this.unexpected(),this.parseGetterSetter(e))},Lc.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(ql.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(ql.bracketR),e.key;e.computed=!1}return e.key=this.type===ql.num||this.type===ql.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},Lc.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},Lc.parseMethod=function(e,t,r){var i=this.startNode(),n=this.yieldPos,s=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(i),this.options.ecmaVersion>=6&&(i.generator=e),this.options.ecmaVersion>=8&&(i.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|gc(t,i.generator)|(r?128:0)),this.expect(ql.parenL),i.params=this.parseBindingList(ql.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(i,!1,!0,!1),this.yieldPos=n,this.awaitPos=s,this.awaitIdentPos=a,this.finishNode(i,"FunctionExpression")},Lc.parseArrowExpression=function(e,t,r,i){var n=this.yieldPos,s=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(16|gc(r,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!r),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,i),this.yieldPos=n,this.awaitPos=s,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},Lc.parseFunctionBody=function(e,t,r,i){var n=t&&this.type!==ql.braceL,s=this.strict,a=!1;if(n)e.body=this.parseMaybeAssign(i),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);s&&!o||(a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var h=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!s&&!a&&!t&&!r&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,a&&!s),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=h}this.exitScope()},Lc.isSimpleParamList=function(e){for(var t=0,r=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t){this.currentScope().lexical.push(e)}else if(3===t){var s=this.currentScope();i=this.treatFunctionsAsVar?s.lexical.indexOf(e)>-1:s.lexical.indexOf(e)>-1||s.var.indexOf(e)>-1,s.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(32&o.flags&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){i=!0;break}if(o.var.push(e),this.inModule&&1&o.flags&&delete this.undefinedExports[e],o.flags&mc)break}i&&this.raiseRecoverable(r,"Identifier '"+e+"' has already been declared")},Vc.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},Vc.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},Vc.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(771&t.flags)return t}},Vc.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(771&t.flags&&!(16&t.flags))return t}};var zc=function(e,t,r){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new uc(e,r)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},jc=yc.prototype;function Gc(e,t,r,i){return e.type=t,e.end=r,this.options.locations&&(e.loc.end=i),this.options.ranges&&(e.range[1]=r),e}jc.startNode=function(){return new zc(this,this.start,this.startLoc)},jc.startNodeAt=function(e,t){return new zc(this,e,t)},jc.finishNode=function(e,t){return Gc.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},jc.finishNodeAt=function(e,t,r,i){return Gc.call(this,e,t,r,i)},jc.copyNode=function(e){var t=new zc(this,e.start,this.startLoc);for(var r in e)t[r]=e[r];return t};var $c="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",Hc=$c+" Extended_Pictographic",qc=Hc+" EBase EComp EMod EPres ExtPict",Wc={9:$c,10:Hc,11:Hc,12:qc,13:qc,14:qc},Xc={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Yc="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Zc="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Kc=Zc+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",Jc=Kc+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",Qc=Jc+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",ep=Qc+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",tp={9:Zc,10:Kc,11:Jc,12:Qc,13:ep,14:ep+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},rp={};function ip(e){var t=rp[e]={binary:sc(Wc[e]+" "+Yc),binaryOfStrings:sc(Xc[e]),nonBinary:{General_Category:sc(Yc),Script:sc(tp[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var np=0,sp=[9,10,11,12,13,14];np=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=rp[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function up(e){return 105===e||109===e||115===e}function lp(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function cp(e){return e>=65&&e<=90||e>=97&&e<=122}hp.prototype.reset=function(e,t,r){var i=-1!==r.indexOf("v"),n=-1!==r.indexOf("u");this.start=0|e,this.source=t+"",this.flags=r,i&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},hp.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},hp.prototype.at=function(e,t){void 0===t&&(t=!1);var r=this.source,i=r.length;if(e>=i)return-1;var n=r.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=i)return n;var s=r.charCodeAt(e+1);return s>=56320&&s<=57343?(n<<10)+s-56613888:n},hp.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var r=this.source,i=r.length;if(e>=i)return i;var n,s=r.charCodeAt(e);return!t&&!this.switchU||s<=55295||s>=57344||e+1>=i||(n=r.charCodeAt(e+1))<56320||n>57343?e+1:e+2},hp.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},hp.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},hp.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},hp.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},hp.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var r=this.pos,i=0,n=e;i-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(i=!0),"v"===a&&(n=!0)}this.options.ecmaVersion>=15&&i&&n&&this.raise(e.start,"Invalid regular expression flag")},ap.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},ap.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,r=e.backReferenceNames;t=16;for(t&&(e.branchID=new op(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},ap.regexp_alternative=function(e){for(;e.pos=9&&(r=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!r,!0}return e.pos=t,!1},ap.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},ap.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},ap.regexp_eatBracedQuantifier=function(e,t){var r=e.pos;if(e.eat(123)){var i=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(i=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var r=this.regexp_eatModifiers(e),i=e.eat(45);if(r||i){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(i){var a=this.regexp_eatModifiers(e);r||a||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var o=0;o-1||r.indexOf(h)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},ap.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},ap.regexp_eatModifiers=function(e){for(var t="",r=0;-1!==(r=e.current())&&up(r);)t+=ac(r),e.advance();return t},ap.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},ap.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},ap.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!lp(t)&&(e.lastIntValue=t,e.advance(),!0)},ap.regexp_eatPatternCharacters=function(e){for(var t=e.pos,r=0;-1!==(r=e.current())&&!lp(r);)e.advance();return e.pos!==t},ap.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t)&&(e.advance(),!0)},ap.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,r=e.groupNames[e.lastStringValue];if(r)if(t)for(var i=0,n=r;i=11,i=e.current(r);return e.advance(r),92===i&&this.regexp_eatRegExpUnicodeEscapeSequence(e,r)&&(i=e.lastIntValue),function(e){return Rl(e,!0)||36===e||95===e}(i)?(e.lastIntValue=i,!0):(e.pos=t,!1)},ap.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,r=this.options.ecmaVersion>=11,i=e.current(r);return e.advance(r),92===i&&this.regexp_eatRegExpUnicodeEscapeSequence(e,r)&&(i=e.lastIntValue),function(e){return Vl(e,!0)||36===e||95===e||8204===e||8205===e}(i)?(e.lastIntValue=i,!0):(e.pos=t,!1)},ap.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},ap.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var r=e.lastIntValue;if(e.switchU)return r>e.maxBackReference&&(e.maxBackReference=r),!0;if(r<=e.numCapturingParens)return!0;e.pos=t}return!1},ap.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},ap.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},ap.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},ap.regexp_eatZero=function(e){return 48===e.current()&&!fp(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},ap.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},ap.regexp_eatControlLetter=function(e){var t=e.current();return!!cp(t)&&(e.lastIntValue=t%32,e.advance(),!0)},ap.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var r,i=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var s=e.lastIntValue;if(n&&s>=55296&&s<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=1024*(s-55296)+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=s}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&((r=e.lastIntValue)>=0&&r<=1114111))return!0;n&&e.raise("Invalid unicode escape"),e.pos=i}return!1},ap.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t)&&(e.lastIntValue=t,e.advance(),!0)},ap.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1};function pp(e){return cp(e)||95===e}function dp(e){return pp(e)||fp(e)}function fp(e){return e>=48&&e<=57}function mp(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function gp(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function yp(e){return e>=48&&e<=55}ap.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var r=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((r=80===t)||112===t)){var i;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(i=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return r&&2===i&&e.raise("Invalid property name"),i;e.raise("Invalid property name")}return 0},ap.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var r=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var i=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,r,i),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},ap.regexp_validateUnicodePropertyNameAndValue=function(e,t,r){rc(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(r)||e.raise("Invalid property value")},ap.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},ap.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";pp(t=e.current());)e.lastStringValue+=ac(t),e.advance();return""!==e.lastStringValue},ap.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";dp(t=e.current());)e.lastStringValue+=ac(t),e.advance();return""!==e.lastStringValue},ap.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},ap.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),r=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===r&&e.raise("Negated character class may contain strings"),!0}return!1},ap.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},ap.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var r=e.lastIntValue;!e.switchU||-1!==t&&-1!==r||e.raise("Invalid character class"),-1!==t&&-1!==r&&t>r&&e.raise("Range out of order in character class")}}},ap.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var r=e.current();(99===r||yp(r))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var i=e.current();return 93!==i&&(e.lastIntValue=i,e.advance(),!0)},ap.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},ap.regexp_classSetExpression=function(e){var t,r=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(r=2);for(var i=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(r=1):e.raise("Invalid character in character class");if(i!==e.pos)return r;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(i!==e.pos)return r}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return r;2===t&&(r=2)}},ap.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var i=e.lastIntValue;return-1!==r&&-1!==i&&r>i&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},ap.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},ap.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var r=e.eat(94),i=this.regexp_classContents(e);if(e.eat(93))return r&&2===i&&e.raise("Negated character class may contain strings"),i;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},ap.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var r=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return r}else e.raise("Invalid escape");e.pos=t}return null},ap.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},ap.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},ap.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e))||(e.eat(98)?(e.lastIntValue=8,!0):(e.pos=t,!1));var r=e.current();return!(r<0||r===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(r))&&(!function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(r)&&(e.advance(),e.lastIntValue=r,!0))},ap.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},ap.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!fp(t)&&95!==t)&&(e.lastIntValue=t%32,e.advance(),!0)},ap.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},ap.regexp_eatDecimalDigits=function(e){var t=e.pos,r=0;for(e.lastIntValue=0;fp(r=e.current());)e.lastIntValue=10*e.lastIntValue+(r-48),e.advance();return e.pos!==t},ap.regexp_eatHexDigits=function(e){var t=e.pos,r=0;for(e.lastIntValue=0;mp(r=e.current());)e.lastIntValue=16*e.lastIntValue+gp(r),e.advance();return e.pos!==t},ap.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var r=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*r+e.lastIntValue:e.lastIntValue=8*t+r}else e.lastIntValue=t;return!0}return!1},ap.regexp_eatOctalDigit=function(e){var t=e.current();return yp(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},ap.regexp_eatFixedHexDigits=function(e,t){var r=e.pos;e.lastIntValue=0;for(var i=0;i=this.input.length?this.finishToken(ql.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},vp.readToken=function(e){return Rl(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},vp.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},vp.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,r=this.input.indexOf("*/",this.pos+=2);if(-1===r&&this.raise(this.pos-2,"Unterminated comment"),this.pos=r+2,this.options.locations)for(var i=void 0,n=t;(i=Zl(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=i;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,r),t,this.pos,e,this.curPosition())},vp.skipLineComment=function(e){for(var t=this.pos,r=this.options.onComment&&this.curPosition(),i=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&Kl.test(String.fromCharCode(e))))break e;++this.pos}}},vp.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var r=this.type;this.type=e,this.value=t,this.updateContext(r)},vp.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(ql.ellipsis)):(++this.pos,this.finishToken(ql.dot))},vp.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(ql.assign,2):this.finishOp(ql.slash,1)},vp.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),r=1,i=42===e?ql.star:ql.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++r,i=ql.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(ql.assign,r+1):this.finishOp(i,r)},vp.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12)if(61===this.input.charCodeAt(this.pos+2))return this.finishOp(ql.assign,3);return this.finishOp(124===e?ql.logicalOR:ql.logicalAND,2)}return 61===t?this.finishOp(ql.assign,2):this.finishOp(124===e?ql.bitwiseOR:ql.bitwiseAND,1)},vp.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(ql.assign,2):this.finishOp(ql.bitwiseXOR,1)},vp.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!Wl.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(ql.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(ql.assign,2):this.finishOp(ql.plusMin,1)},vp.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),r=1;return t===e?(r=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+r)?this.finishOp(ql.assign,r+1):this.finishOp(ql.bitShift,r)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(r=2),this.finishOp(ql.relational,r)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},vp.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(ql.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(ql.arrow)):this.finishOp(61===e?ql.eq:ql.prefix,1)},vp.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var r=this.input.charCodeAt(this.pos+2);if(r<48||r>57)return this.finishOp(ql.questionDot,2)}if(63===t){if(e>=12)if(61===this.input.charCodeAt(this.pos+2))return this.finishOp(ql.assign,3);return this.finishOp(ql.coalesce,2)}}return this.finishOp(ql.question,1)},vp.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,Rl(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(ql.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+ac(e)+"'")},vp.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(ql.parenL);case 41:return++this.pos,this.finishToken(ql.parenR);case 59:return++this.pos,this.finishToken(ql.semi);case 44:return++this.pos,this.finishToken(ql.comma);case 91:return++this.pos,this.finishToken(ql.bracketL);case 93:return++this.pos,this.finishToken(ql.bracketR);case 123:return++this.pos,this.finishToken(ql.braceL);case 125:return++this.pos,this.finishToken(ql.braceR);case 58:return++this.pos,this.finishToken(ql.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(ql.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(ql.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+ac(e)+"'")},vp.finishOp=function(e,t){var r=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,r)},vp.readRegexp=function(){for(var e,t,r=this.pos;;){this.pos>=this.input.length&&this.raise(r,"Unterminated regular expression");var i=this.input.charAt(this.pos);if(Wl.test(i)&&this.raise(r,"Unterminated regular expression"),e)e=!1;else{if("["===i)t=!0;else if("]"===i&&t)t=!1;else if("/"===i&&!t)break;e="\\"===i}++this.pos}var n=this.input.slice(r,this.pos);++this.pos;var s=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(s);var o=this.regexpState||(this.regexpState=new hp(this));o.reset(r,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var h=null;try{h=new RegExp(n,a)}catch(e){}return this.finishToken(ql.regexp,{pattern:n,flags:a,value:h})},vp.readInt=function(e,t,r){for(var i=this.options.ecmaVersion>=12&&void 0===t,n=r&&48===this.input.charCodeAt(this.pos),s=this.pos,a=0,o=0,h=0,u=null==t?1/0:t;h=97?l-97+10:l>=65?l-65+10:l>=48&&l<=57?l-48:1/0)>=e)break;o=l,a=a*e+c}}return i&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===s||null!=t&&this.pos-s!==t?null:a},vp.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var r=this.readInt(e);return null==r&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(r=bp(this.input.slice(t,this.pos)),++this.pos):Rl(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(ql.num,r)},vp.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var r=this.pos-t>=2&&48===this.input.charCodeAt(t);r&&this.strict&&this.raise(t,"Invalid number");var i=this.input.charCodeAt(this.pos);if(!r&&!e&&this.options.ecmaVersion>=11&&110===i){var n=bp(this.input.slice(t,this.pos));return++this.pos,Rl(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(ql.num,n)}r&&/[89]/.test(this.input.slice(t,this.pos))&&(r=!1),46!==i||r||(++this.pos,this.readInt(10),i=this.input.charCodeAt(this.pos)),69!==i&&101!==i||r||(43!==(i=this.input.charCodeAt(++this.pos))&&45!==i||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),Rl(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var s,a=(s=this.input.slice(t,this.pos),r?parseInt(s,8):parseFloat(s.replace(/_/g,"")));return this.finishToken(ql.num,a)},vp.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},vp.readString=function(e){for(var t="",r=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var i=this.input.charCodeAt(this.pos);if(i===e)break;92===i?(t+=this.input.slice(r,this.pos),t+=this.readEscapedChar(!1),r=this.pos):8232===i||8233===i?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(Yl(i)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(r,this.pos++),this.finishToken(ql.string,t)};var _p={};vp.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==_p)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},vp.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw _p;this.raise(e,t)},vp.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var r=this.input.charCodeAt(this.pos);if(96===r||36===r&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==ql.template&&this.type!==ql.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(ql.template,e)):36===r?(this.pos+=2,this.finishToken(ql.dollarBraceL)):(++this.pos,this.finishToken(ql.backQuote));if(92===r)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(Yl(r)){switch(e+=this.input.slice(t,this.pos),++this.pos,r){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(r)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},vp.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var i=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(i,8);return n>255&&(i=i.slice(0,-1),n=parseInt(i,8)),this.pos+=i.length-1,t=this.input.charCodeAt(this.pos),"0"===i&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-i.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return Yl(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},vp.readHexChar=function(e){var t=this.pos,r=this.readInt(16,e);return null===r&&this.invalidStringToken(t,"Bad character escape sequence"),r},vp.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,r=this.pos,i=this.options.ecmaVersion>=6;this.pos=0;--r)if(e[r].node===t)return!0;return!1}function m(e,t){return(new c).traverse(e,t)}function g(e,t){var r;return r=function(e,t){var r,i,n,s;for(i=e.length,n=0;i;)t(e[s=n+(r=i>>>1)])?i=r:(n=s+1,i-=r+1);return n}(t,(function(t){return t.range[0]>e.range[0]})),e.extendedRange=[e.range[0],e.range[1]],r!==t.length&&(e.extendedRange[1]=t[r].range[0]),(r-=1)>=0&&(e.extendedRange[0]=t[r].range[1]),e}return r={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ChainExpression:"ChainExpression",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportExpression:"ImportExpression",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",PrivateIdentifier:"PrivateIdentifier",Program:"Program",Property:"Property",PropertyDefinition:"PropertyDefinition",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"},n={AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","body"],AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ChainExpression:["expression"],ClassBody:["body"],ClassDeclaration:["id","superClass","body"],ClassExpression:["id","superClass","body"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportAllDeclaration:["source"],ExportDefaultDeclaration:["declaration"],ExportNamedDeclaration:["declaration","specifiers","source"],ExportSpecifier:["exported","local"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","body"],FunctionExpression:["id","params","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportExpression:["source"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["local"],ImportNamespaceSpecifier:["local"],ImportSpecifier:["imported","local"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MetaProperty:["meta","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],PrivateIdentifier:[],Program:["body"],Property:["key","value"],PropertyDefinition:["key","value"],RestElement:["argument"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],Super:[],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handler","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]},i={Break:s={},Skip:a={},Remove:o={}},u.prototype.replace=function(e){this.parent[this.key]=e},u.prototype.remove=function(){return Array.isArray(this.parent)?(this.parent.splice(this.key,1),!0):(this.replace(null),!1)},c.prototype.path=function(){var e,t,r,i,n;function s(e,t){if(Array.isArray(t))for(r=0,i=t.length;r=0;)if(x=o[c=y[m]])if(Array.isArray(x)){for(g=x.length;(g-=1)>=0;)if(x[g]&&!f(i,x[g])){if(d(h,y[m]))n=new l(x[g],[c,g],"Property",null);else{if(!p(x[g]))continue;n=new l(x[g],[c,g],null,null)}r.push(n)}}else if(p(x)){if(f(i,x))continue;r.push(new l(x,c,null,null))}}}else if(n=i.pop(),u=this.__execute(t.leave,n),this.__state===s||u===s)return},c.prototype.replace=function(e,t){var r,i,n,h,c,f,m,g,y,x,v,b,_;function w(e){var t,i,n,s;if(e.ref.remove())for(i=e.ref.key,s=e.ref.parent,t=r.length;t--;)if((n=r[t]).ref&&n.ref.parent===s){if(n.ref.key=0;)if(x=n[_=y[m]])if(Array.isArray(x)){for(g=x.length;(g-=1)>=0;)if(x[g]){if(d(h,y[m]))f=new l(x[g],[_,g],"Property",new u(x,g));else{if(!p(x[g]))continue;f=new l(x[g],[_,g],null,new u(x,g))}r.push(f)}}else p(x)&&r.push(new l(x,_,null,new u(n,_)))}}else if(f=i.pop(),void 0!==(c=this.__execute(t.leave,f))&&c!==s&&c!==a&&c!==o&&f.ref.replace(c),this.__state!==o&&c!==o||w(f),this.__state===s||c===s)return b.root;return b.root},t.Syntax=r,t.traverse=m,t.replace=function(e,t){return(new c).replace(e,t)},t.attachComments=function(e,t,r){var n,s,a,o,u=[];if(!e.range)throw new Error("attachComments needs range information");if(!r.length){if(t.length){for(a=0,s=t.length;ae.range[0]);)t.extendedRange[1]===e.range[0]?(e.leadingComments||(e.leadingComments=[]),e.leadingComments.push(t),u.splice(o,1)):o+=1;return o===u.length?i.Break:u[o].extendedRange[0]>e.range[1]?i.Skip:void 0}}),o=0,m(e,{leave:function(e){for(var t;oe.range[1]?i.Skip:void 0}}),e},t.VisitorKeys=n,t.VisitorOption=i,t.Controller=c,t.cloneEnvironment=function(){return e({})},t})(Tp);var Fp={},kp={exports:{}};!function(){function e(e){if(null==e)return!1;switch(e.type){case"BlockStatement":case"BreakStatement":case"ContinueStatement":case"DebuggerStatement":case"DoWhileStatement":case"EmptyStatement":case"ExpressionStatement":case"ForInStatement":case"ForStatement":case"IfStatement":case"LabeledStatement":case"ReturnStatement":case"SwitchStatement":case"ThrowStatement":case"TryStatement":case"VariableDeclaration":case"WhileStatement":case"WithStatement":return!0}return!1}function t(e){switch(e.type){case"IfStatement":return null!=e.alternate?e.alternate:e.consequent;case"LabeledStatement":case"ForStatement":case"ForInStatement":case"WhileStatement":case"WithStatement":return e.body}return null}kp.exports={isExpression:function(e){if(null==e)return!1;switch(e.type){case"ArrayExpression":case"AssignmentExpression":case"BinaryExpression":case"CallExpression":case"ConditionalExpression":case"FunctionExpression":case"Identifier":case"Literal":case"LogicalExpression":case"MemberExpression":case"NewExpression":case"ObjectExpression":case"SequenceExpression":case"ThisExpression":case"UnaryExpression":case"UpdateExpression":return!0}return!1},isStatement:e,isIterationStatement:function(e){if(null==e)return!1;switch(e.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":return!0}return!1},isSourceElement:function(t){return e(t)||null!=t&&"FunctionDeclaration"===t.type},isProblematicIfStatement:function(e){var r;if("IfStatement"!==e.type)return!1;if(null==e.alternate)return!1;r=e.consequent;do{if("IfStatement"===r.type&&null==r.alternate)return!0;r=t(r)}while(r);return!1},trailingStatement:t}}();var Mp=kp.exports,Ip={exports:{}};!function(){var e,t,r,i,n,s;function a(e){return e<=65535?String.fromCharCode(e):String.fromCharCode(Math.floor((e-65536)/1024)+55296)+String.fromCharCode((e-65536)%1024+56320)}for(t={NonAsciiIdentifierStart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/,NonAsciiIdentifierPart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/},e={NonAsciiIdentifierStart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,NonAsciiIdentifierPart:/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/},r=[5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279],i=new Array(128),s=0;s<128;++s)i[s]=s>=97&&s<=122||s>=65&&s<=90||36===s||95===s;for(n=new Array(128),s=0;s<128;++s)n[s]=s>=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||36===s||95===s;Ip.exports={isDecimalDigit:function(e){return 48<=e&&e<=57},isHexDigit:function(e){return 48<=e&&e<=57||97<=e&&e<=102||65<=e&&e<=70},isOctalDigit:function(e){return e>=48&&e<=55},isWhiteSpace:function(e){return 32===e||9===e||11===e||12===e||160===e||e>=5760&&r.indexOf(e)>=0},isLineTerminator:function(e){return 10===e||13===e||8232===e||8233===e},isIdentifierStartES5:function(e){return e<128?i[e]:t.NonAsciiIdentifierStart.test(a(e))},isIdentifierPartES5:function(e){return e<128?n[e]:t.NonAsciiIdentifierPart.test(a(e))},isIdentifierStartES6:function(t){return t<128?i[t]:e.NonAsciiIdentifierStart.test(a(t))},isIdentifierPartES6:function(t){return t<128?n[t]:e.NonAsciiIdentifierPart.test(a(t))}}}();var Bp=Ip.exports,Lp={exports:{}};!function(){var e=Bp;function t(e,t){return!(!t&&"yield"===e)&&r(e,t)}function r(e,t){if(t&&function(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return!0;default:return!1}}(e))return!0;switch(e.length){case 2:return"if"===e||"in"===e||"do"===e;case 3:return"var"===e||"for"===e||"new"===e||"try"===e;case 4:return"this"===e||"else"===e||"case"===e||"void"===e||"with"===e||"enum"===e;case 5:return"while"===e||"break"===e||"catch"===e||"throw"===e||"const"===e||"yield"===e||"class"===e||"super"===e;case 6:return"return"===e||"typeof"===e||"delete"===e||"switch"===e||"export"===e||"import"===e;case 7:return"default"===e||"finally"===e||"extends"===e;case 8:return"function"===e||"continue"===e||"debugger"===e;case 10:return"instanceof"===e;default:return!1}}function i(e,r){return"null"===e||"true"===e||"false"===e||t(e,r)}function n(e,t){return"null"===e||"true"===e||"false"===e||r(e,t)}function s(t){var r,i,n;if(0===t.length)return!1;if(n=t.charCodeAt(0),!e.isIdentifierStartES5(n))return!1;for(r=1,i=t.length;r=i)return!1;if(!(56320<=(s=t.charCodeAt(r))&&s<=57343))return!1;n=1024*(n-55296)+(s-56320)+65536}if(!a(n))return!1;a=e.isIdentifierPartES6}return!0}Lp.exports={isKeywordES5:t,isKeywordES6:r,isReservedWordES5:i,isReservedWordES6:n,isRestrictedWord:function(e){return"eval"===e||"arguments"===e},isIdentifierNameES5:s,isIdentifierNameES6:a,isIdentifierES5:function(e,t){return s(e)&&!i(e,t)},isIdentifierES6:function(e,t){return a(e)&&!n(e,t)}}}();var Op=Lp.exports;Fp.ast=Mp,Fp.code=Bp,Fp.keyword=Op;var Pp,Np,Rp={},Vp={},Up={},zp={};function jp(){if(Pp)return zp;Pp=1;var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");return zp.encode=function(t){if(0<=t&&t>>=5)>0&&(r|=32),i+=e.encode(r)}while(n>0);return i},Up.decode=function(t,r,i){var n,s,a,o,h=t.length,u=0,l=0;do{if(r>=h)throw new Error("Expected more digits in base 64 VLQ value.");if(-1===(s=e.decode(t.charCodeAt(r++))))throw new Error("Invalid base64 digit: "+t.charAt(r-1));n=!!(32&s),u+=(s&=31)<>1,1&~a?o:-o),i.rest=r},Up}var $p,Hp={};function qp(){return $p||($p=1,function(e){e.getArg=function(e,t,r){if(t in e)return e[t];if(3===arguments.length)return r;throw new Error('"'+t+'" is a required argument.')};var t=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,r=/^data:.+\,.+$/;function i(e){var r=e.match(t);return r?{scheme:r[1],auth:r[2],host:r[3],port:r[4],path:r[5]}:null}function n(e){var t="";return e.scheme&&(t+=e.scheme+":"),t+="//",e.auth&&(t+=e.auth+"@"),e.host&&(t+=e.host),e.port&&(t+=":"+e.port),e.path&&(t+=e.path),t}function s(t){var r=t,s=i(t);if(s){if(!s.path)return t;r=s.path}for(var a,o=e.isAbsolute(r),h=r.split(/\/+/),u=0,l=h.length-1;l>=0;l--)"."===(a=h[l])?h.splice(l,1):".."===a?u++:u>0&&(""===a?(h.splice(l+1,u),u=0):(h.splice(l,2),u--));return""===(r=h.join("/"))&&(r=o?"/":"."),s?(s.path=r,n(s)):r}function a(e,t){""===e&&(e="."),""===t&&(t=".");var a=i(t),o=i(e);if(o&&(e=o.path||"/"),a&&!a.scheme)return o&&(a.scheme=o.scheme),n(a);if(a||t.match(r))return t;if(o&&!o.host&&!o.path)return o.host=t,n(o);var h="/"===t.charAt(0)?t:s(e.replace(/\/+$/,"")+"/"+t);return o?(o.path=h,n(o)):h}e.urlParse=i,e.urlGenerate=n,e.normalize=s,e.join=a,e.isAbsolute=function(e){return"/"===e.charAt(0)||t.test(e)},e.relative=function(e,t){""===e&&(e="."),e=e.replace(/\/$/,"");for(var r=0;0!==t.indexOf(e+"/");){var i=e.lastIndexOf("/");if(i<0)return t;if((e=e.slice(0,i)).match(/^([^\/]+:\/)?\/*$/))return t;++r}return Array(r+1).join("../")+t.substr(e.length+1)};var o=!("__proto__"in Object.create(null));function h(e){return e}function u(e){if(!e)return!1;var t=e.length;if(t<9)return!1;if(95!==e.charCodeAt(t-1)||95!==e.charCodeAt(t-2)||111!==e.charCodeAt(t-3)||116!==e.charCodeAt(t-4)||111!==e.charCodeAt(t-5)||114!==e.charCodeAt(t-6)||112!==e.charCodeAt(t-7)||95!==e.charCodeAt(t-8)||95!==e.charCodeAt(t-9))return!1;for(var r=t-10;r>=0;r--)if(36!==e.charCodeAt(r))return!1;return!0}function l(e,t){return e===t?0:null===e?1:null===t?-1:e>t?1:-1}e.toSetString=o?h:function(e){return u(e)?"$"+e:e},e.fromSetString=o?h:function(e){return u(e)?e.slice(1):e},e.compareByOriginalPositions=function(e,t,r){var i=l(e.source,t.source);return 0!==i||0!==(i=e.originalLine-t.originalLine)||0!==(i=e.originalColumn-t.originalColumn)||r||0!==(i=e.generatedColumn-t.generatedColumn)||0!==(i=e.generatedLine-t.generatedLine)?i:l(e.name,t.name)},e.compareByGeneratedPositionsDeflated=function(e,t,r){var i=e.generatedLine-t.generatedLine;return 0!==i||0!==(i=e.generatedColumn-t.generatedColumn)||r||0!==(i=l(e.source,t.source))||0!==(i=e.originalLine-t.originalLine)||0!==(i=e.originalColumn-t.originalColumn)?i:l(e.name,t.name)},e.compareByGeneratedPositionsInflated=function(e,t){var r=e.generatedLine-t.generatedLine;return 0!==r||0!==(r=e.generatedColumn-t.generatedColumn)||0!==(r=l(e.source,t.source))||0!==(r=e.originalLine-t.originalLine)||0!==(r=e.originalColumn-t.originalColumn)?r:l(e.name,t.name)},e.parseSourceMapInput=function(e){return JSON.parse(e.replace(/^\)]}'[^\n]*\n/,""))},e.computeSourceURL=function(e,t,r){if(t=t||"",e&&("/"!==e[e.length-1]&&"/"!==t[0]&&(e+="/"),t=e+t),r){var o=i(r);if(!o)throw new Error("sourceMapURL could not be parsed");if(o.path){var h=o.path.lastIndexOf("/");h>=0&&(o.path=o.path.substring(0,h+1))}t=a(n(o),t)}return s(t)}}(Hp)),Hp}var Wp,Xp={};function Yp(){if(Wp)return Xp;Wp=1;var e=qp(),t=Object.prototype.hasOwnProperty,r="undefined"!=typeof Map;function i(){this._array=[],this._set=r?new Map:Object.create(null)}return i.fromArray=function(e,t){for(var r=new i,n=0,s=e.length;n=0)return n}else{var s=e.toSetString(i);if(t.call(this._set,s))return this._set[s]}throw new Error('"'+i+'" is not in the set.')},i.prototype.at=function(e){if(e>=0&&en||s==n&&o>=a||e.compareByGeneratedPositionsInflated(r,i)<=0?(this._last=t,this._array.push(t)):(this._sorted=!1,this._array.push(t))},t.prototype.toArray=function(){return this._sorted||(this._array.sort(e.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},Jp.MappingList=t,Jp}function ed(){if(Kp)return Vp;Kp=1;var e=Gp(),t=qp(),r=Yp().ArraySet,i=Qp().MappingList;function n(e){e||(e={}),this._file=t.getArg(e,"file",null),this._sourceRoot=t.getArg(e,"sourceRoot",null),this._skipValidation=t.getArg(e,"skipValidation",!1),this._sources=new r,this._names=new r,this._mappings=new i,this._sourcesContents=null}return n.prototype._version=3,n.fromSourceMap=function(e){var r=e.sourceRoot,i=new n({file:e.file,sourceRoot:r});return e.eachMapping((function(e){var n={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(n.source=e.source,null!=r&&(n.source=t.relative(r,n.source)),n.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(n.name=e.name)),i.addMapping(n)})),e.sources.forEach((function(n){var s=n;null!==r&&(s=t.relative(r,n)),i._sources.has(s)||i._sources.add(s);var a=e.sourceContentFor(n);null!=a&&i.setSourceContent(n,a)})),i},n.prototype.addMapping=function(e){var r=t.getArg(e,"generated"),i=t.getArg(e,"original",null),n=t.getArg(e,"source",null),s=t.getArg(e,"name",null);this._skipValidation||this._validateMapping(r,i,n,s),null!=n&&(n=String(n),this._sources.has(n)||this._sources.add(n)),null!=s&&(s=String(s),this._names.has(s)||this._names.add(s)),this._mappings.add({generatedLine:r.line,generatedColumn:r.column,originalLine:null!=i&&i.line,originalColumn:null!=i&&i.column,source:n,name:s})},n.prototype.setSourceContent=function(e,r){var i=e;null!=this._sourceRoot&&(i=t.relative(this._sourceRoot,i)),null!=r?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[t.toSetString(i)]=r):this._sourcesContents&&(delete this._sourcesContents[t.toSetString(i)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},n.prototype.applySourceMap=function(e,i,n){var s=i;if(null==i){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');s=e.file}var a=this._sourceRoot;null!=a&&(s=t.relative(a,s));var o=new r,h=new r;this._mappings.unsortedForEach((function(r){if(r.source===s&&null!=r.originalLine){var i=e.originalPositionFor({line:r.originalLine,column:r.originalColumn});null!=i.source&&(r.source=i.source,null!=n&&(r.source=t.join(n,r.source)),null!=a&&(r.source=t.relative(a,r.source)),r.originalLine=i.line,r.originalColumn=i.column,null!=i.name&&(r.name=i.name))}var u=r.source;null==u||o.has(u)||o.add(u);var l=r.name;null==l||h.has(l)||h.add(l)}),this),this._sources=o,this._names=h,e.sources.forEach((function(r){var i=e.sourceContentFor(r);null!=i&&(null!=n&&(r=t.join(n,r)),null!=a&&(r=t.relative(a,r)),this.setSourceContent(r,i))}),this)},n.prototype._validateMapping=function(e,t,r,i){if(t&&"number"!=typeof t.line&&"number"!=typeof t.column)throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if((!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0)||t||r||i)&&!(e&&"line"in e&&"column"in e&&t&&"line"in t&&"column"in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:t,name:i}))},n.prototype._serializeMappings=function(){for(var r,i,n,s,a=0,o=1,h=0,u=0,l=0,c=0,p="",d=this._mappings.toArray(),f=0,m=d.length;f0){if(!t.compareByGeneratedPositionsInflated(i,d[f-1]))continue;r+=","}r+=e.encode(i.generatedColumn-a),a=i.generatedColumn,null!=i.source&&(s=this._sources.indexOf(i.source),r+=e.encode(s-c),c=s,r+=e.encode(i.originalLine-1-u),u=i.originalLine-1,r+=e.encode(i.originalColumn-h),h=i.originalColumn,null!=i.name&&(n=this._names.indexOf(i.name),r+=e.encode(n-l),l=n)),p+=r}return p},n.prototype._generateSourcesContent=function(e,r){return e.map((function(e){if(!this._sourcesContents)return null;null!=r&&(e=t.relative(r,e));var i=t.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,i)?this._sourcesContents[i]:null}),this)},n.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},n.prototype.toString=function(){return JSON.stringify(this.toJSON())},Vp.SourceMapGenerator=n,Vp}var td,rd={},id={};function nd(){return td||(td=1,function(e){function t(r,i,n,s,a,o){var h=Math.floor((i-r)/2)+r,u=a(n,s[h],!0);return 0===u?h:u>0?i-h>1?t(h,i,n,s,a,o):o==e.LEAST_UPPER_BOUND?i1?t(r,h,n,s,a,o):o==e.LEAST_UPPER_BOUND?h:r<0?-1:r}e.GREATEST_LOWER_BOUND=1,e.LEAST_UPPER_BOUND=2,e.search=function(r,i,n,s){if(0===i.length)return-1;var a=t(-1,i.length,r,i,n,s||e.GREATEST_LOWER_BOUND);if(a<0)return-1;for(;a-1>=0&&0===n(i[a],i[a-1],!0);)--a;return a}}(id)),id}var sd,ad,od={};function hd(){if(sd)return od;function e(e,t,r){var i=e[t];e[t]=e[r],e[r]=i}function t(r,i,n,s){if(n=0){var o=this._originalMappings[a];if(void 0===r.column)for(var h=o.originalLine;o&&o.originalLine===h;)s.push({line:e.getArg(o,"generatedLine",null),column:e.getArg(o,"generatedColumn",null),lastColumn:e.getArg(o,"lastGeneratedColumn",null)}),o=this._originalMappings[++a];else for(var u=o.originalColumn;o&&o.originalLine===i&&o.originalColumn==u;)s.push({line:e.getArg(o,"generatedLine",null),column:e.getArg(o,"generatedColumn",null),lastColumn:e.getArg(o,"lastGeneratedColumn",null)}),o=this._originalMappings[++a]}return s},rd.SourceMapConsumer=s,a.prototype=Object.create(s.prototype),a.prototype.consumer=s,a.prototype._findSourceIndex=function(t){var r,i=t;if(null!=this.sourceRoot&&(i=e.relative(this.sourceRoot,i)),this._sources.has(i))return this._sources.indexOf(i);for(r=0;r1&&(s.source=m+h[1],m+=h[1],s.originalLine=d+h[2],d=s.originalLine,s.originalLine+=1,s.originalColumn=f+h[3],f=s.originalColumn,h.length>4&&(s.name=g+h[4],g+=h[4])),w.push(s),"number"==typeof s.originalLine&&_.push(s)}n(w,e.compareByGeneratedPositionsDeflated),this.__generatedMappings=w,n(_,e.compareByOriginalPositions),this.__originalMappings=_},a.prototype._findMapping=function(e,r,i,n,s,a){if(e[i]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[i]);if(e[n]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[n]);return t.search(e,r,s,a)},a.prototype.computeColumnSpans=function(){for(var e=0;e=0){var n=this._generatedMappings[i];if(n.generatedLine===r.generatedLine){var a=e.getArg(n,"source",null);null!==a&&(a=this._sources.at(a),a=e.computeSourceURL(this.sourceRoot,a,this._sourceMapURL));var o=e.getArg(n,"name",null);return null!==o&&(o=this._names.at(o)),{source:a,line:e.getArg(n,"originalLine",null),column:e.getArg(n,"originalColumn",null),name:o}}}return{source:null,line:null,column:null,name:null}},a.prototype.hasContentsOfAllSources=function(){return!!this.sourcesContent&&this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some((function(e){return null==e}))},a.prototype.sourceContentFor=function(t,r){if(!this.sourcesContent)return null;var i=this._findSourceIndex(t);if(i>=0)return this.sourcesContent[i];var n,s=t;if(null!=this.sourceRoot&&(s=e.relative(this.sourceRoot,s)),null!=this.sourceRoot&&(n=e.urlParse(this.sourceRoot))){var a=s.replace(/^file:\/\//,"");if("file"==n.scheme&&this._sources.has(a))return this.sourcesContent[this._sources.indexOf(a)];if((!n.path||"/"==n.path)&&this._sources.has("/"+s))return this.sourcesContent[this._sources.indexOf("/"+s)]}if(r)return null;throw new Error('"'+s+'" is not in the SourceMap.')},a.prototype.generatedPositionFor=function(t){var r=e.getArg(t,"source");if((r=this._findSourceIndex(r))<0)return{line:null,column:null,lastColumn:null};var i={source:r,originalLine:e.getArg(t,"line"),originalColumn:e.getArg(t,"column")},n=this._findMapping(i,this._originalMappings,"originalLine","originalColumn",e.compareByOriginalPositions,e.getArg(t,"bias",s.GREATEST_LOWER_BOUND));if(n>=0){var a=this._originalMappings[n];if(a.source===i.source)return{line:e.getArg(a,"generatedLine",null),column:e.getArg(a,"generatedColumn",null),lastColumn:e.getArg(a,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},rd.BasicSourceMapConsumer=a,h.prototype=Object.create(s.prototype),h.prototype.constructor=s,h.prototype._version=3,Object.defineProperty(h.prototype,"sources",{get:function(){for(var e=[],t=0;t=0;t--)this.prepend(e[t]);else{if(!e[i]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},n.prototype.walk=function(e){for(var t,r=0,n=this.children.length;r0){for(t=[],r=0;r":r.Relational,"<=":r.Relational,">=":r.Relational,in:r.Relational,instanceof:r.Relational,"<<":r.BitwiseSHIFT,">>":r.BitwiseSHIFT,">>>":r.BitwiseSHIFT,"+":r.Additive,"-":r.Additive,"*":r.Multiplicative,"%":r.Multiplicative,"/":r.Multiplicative,"**":r.Exponentiation};var T=32,F=33;function k(e,t){var r="";for(t|=0;t>0;t>>>=1,e+=e)1&t&&(r+=e);return r}function M(e){var t=e.length;return t&&a.code.isLineTerminator(e.charCodeAt(t-1))}function I(e,t){var r;for(r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);return e}function B(e,t){var r,i;function n(e){return"object"==typeof e&&e instanceof Object&&!(e instanceof RegExp)}for(r in t)t.hasOwnProperty(r)&&(n(i=t[r])?n(e[r])?B(e[r],i):e[r]=B({},i):e[r]=i);return e}function L(e,t){return 8232==(-2&e)?(t?"u":"\\u")+(8232===e?"2028":"2029"):10===e||13===e?(t?"":"\\")+(10===e?"n":"r"):String.fromCharCode(e)}function O(e,t){var r;return 8===e?"\\b":12===e?"\\f":9===e?"\\t":(r=e.toString(16).toUpperCase(),u||e>255?"\\u"+"0000".slice(r.length)+r:0!==e||a.code.isDecimalDigit(t)?11===e?"\\x0B":"\\x"+"00".slice(r.length)+r:"\\0")}function P(e){if(92===e)return"\\\\";if(10===e)return"\\n";if(13===e)return"\\r";if(8232===e)return"\\u2028";if(8233===e)return"\\u2029";throw new Error("Incorrectly classified character")}function N(e){var t,r,i,n="";for(t=0,r=e.length;th&&(u=h)}for(void 0!==t?(l=o,"*"===r[1][u]&&(t+=" "),o=t):(1&u&&--u,l=o),i=1,n=r.length;i0){if(u=r,E){for(r=[],d=(s=e.leadingComments[0]).extendedRange,f=s.range,(y=((g=C.substring(d[0],f[0])).match(/\n/g)||[]).length)>0?(r.push(k("\n",y)),r.push(z(G(s)))):(r.push(g),r.push(G(s))),m=f,i=1,n=e.leadingComments.length;i0?(r.push(k("\n",y)),r.push(z(G(s)))):(r.push(g),r.push(G(s)));else for(l=!M(R(r).toString()),c=k(" ",function(e){var t;for(t=e.length-1;t>=0&&!a.code.isLineTerminator(e.charCodeAt(t));--t);return e.length-1-t}(R([o,r,h]).toString())),i=0,n=e.trailingComments.length;i")),e.expression?(i.push(m),"{"===(n=this.generateExpression(e.body,r.Assignment,7)).toString().charAt(0)&&(n=["(",n,")"]),i.push(n)):i.push(this.maybeBlock(e.body,9)),i},X.prototype.generateIterationForStatement=function(e,i,n){var s=["for"+(i.await?V()+"await":"")+m+"("],a=this;return j((function(){i.left.type===t.VariableDeclaration?j((function(){s.push(i.left.kind+V()),s.push(a.generateStatement(i.left.declarations[0],0))})):s.push(a.generateExpression(i.left,r.Call,7)),s=U(s,e),s=[U(s,a.generateExpression(i.right,r.Assignment,7)),")"]})),s.push(this.maybeBlock(i.body,n)),s},X.prototype.generatePropertyKey=function(e,t){var i=[];return t&&i.push("["),i.push(this.generateExpression(e,r.Assignment,7)),t&&i.push("]"),i},X.prototype.generateAssignment=function(e,t,i,n,s){return r.Assignment2&&("\n"===(i=C.substring(r[0]+1,r[1]-1))[0]&&(n=["{"]),n.push(i)),u=1,8&t&&(u|=16),a=0,o=e.body.length;a0&&(e.body[a-1].trailingComments||e.body[a].leadingComments||H(e.body[a-1].range[1],e.body[a].range[0],n))),a===o-1&&(u|=T),h=e.body[a].leadingComments&&E?s.generateStatement(e.body[a],u):z(s.generateStatement(e.body[a],u)),n.push(h),M(R(h).toString())||E&&a1?j(h):h(),r.push(this.semicolon(t)),r},ThrowStatement:function(e,t){return[U("throw",this.generateExpression(e.argument,r.Sequence,7)),this.semicolon(t)]},TryStatement:function(e,t){var r,i,n,s;if(r=["try",this.maybeBlock(e.block,1)],r=this.maybeBlockSuffix(e.block,r),e.handlers)for(i=0,n=e.handlers.length;i0?"\n":""],a=17,n=0;n0&&(e.body[n-1].trailingComments||e.body[n].leadingComments||H(e.body[n-1].range[1],e.body[n].range[0],r))),i=z(this.generateStatement(e.body[n],a)),r.push(i),n+10){for(n.push("("),a=0,o=s;a=2&&48===o.charCodeAt(0))&&s.push(" "),s.push(e.optional?"?.":"."),s.push(Y(e.property))),q(s,r.Member,i)},MetaProperty:function(e,t,i){var n;return(n=[]).push("string"==typeof e.meta?e.meta:Y(e.meta)),n.push("."),n.push("string"==typeof e.property?e.property:Y(e.property)),q(n,r.Member,t)},UnaryExpression:function(e,t,i){var n,s,o,h,u;return s=this.generateExpression(e.argument,r.Unary,7),""===m?n=U(e.operator,s):(n=[e.operator],e.operator.length>2?n=U(n,s):(u=(h=R(n).toString()).charCodeAt(h.length-1),o=s.toString().charCodeAt(0),(43===u||45===u)&&u===o||a.code.isIdentifierPartES5(u)&&a.code.isIdentifierPartES5(o)?(n.push(V()),n.push(s)):n.push(s))),q(n,r.Unary,t)},YieldExpression:function(e,t,i){var n;return n=e.delegate?"yield*":"yield",e.argument&&(n=U(n,this.generateExpression(e.argument,r.Yield,7))),q(n,r.Yield,t)},AwaitExpression:function(e,t,i){return q(U(e.all?"await*":"await",this.generateExpression(e.argument,r.Await,7)),r.Await,t)},UpdateExpression:function(e,t,i){return e.prefix?q([e.operator,this.generateExpression(e.argument,r.Unary,7)],r.Unary,t):q([this.generateExpression(e.argument,r.Postfix,7),e.operator],r.Postfix,t)},FunctionExpression:function(e,t,r){var i=[Z(e,!0),"function"];return e.id?(i.push(K(e)||V()),i.push(Y(e.id))):i.push(K(e)||m),i.push(this.generateFunctionBody(e)),i},ArrayPattern:function(e,t,r){return this.ArrayExpression(e,t,r,!0)},ArrayExpression:function(e,t,i,n){var s,a,h=this;return e.elements.length?(a=!n&&e.elements.length>1,s=["[",a?f:""],j((function(t){var i,n;for(i=0,n=e.elements.length;i1,j((function(){a=u.generateExpression(e.properties[0],r.Sequence,7)})),n||(h=R(a).toString(),/[\r\n]/g.test(h))?(j((function(t){var i,o;if(s=["{",f,t,a],n)for(s.push(","+f),i=1,o=e.properties.length;i126))){o+=O(i,e.charCodeAt(t+1));continue}}o+=String.fromCharCode(i)}if(s=(n=!("double"===p||"auto"===p&&l0&&(n=+i.slice(s+1),i=i.slice(0,s)),r>=0&&(n-=i.length-r-1,i=+(i.slice(0,r)+i.slice(r+1))+""),s=0;48===i.charCodeAt(i.length+s-1);)--s;return 0!==s&&(n-=s,i=i.slice(0,s)),0!==n&&(i+="e"+n),(i.length1e12&&Math.floor(e)===e&&(i="0x"+e.toString(16)).length0||b.moz.comprehensionExpressionStartsWithAssignment?s=U(s,h):s.push(h)})),e.filter&&(s=U(s,"if"+m),h=this.generateExpression(e.filter,r.Sequence,7),s=U(s,["(",h,")"])),b.moz.comprehensionExpressionStartsWithAssignment||(h=this.generateExpression(e.body,r.Assignment,7),s=U(s,h)),s.push(e.type===t.GeneratorExpression?")":"]"),s},ComprehensionBlock:function(e,i,n){var s;return s=U(s=e.left.type===t.VariableDeclaration?[e.left.kind,V(),this.generateStatement(e.left.declarations[0],0)]:this.generateExpression(e.left,r.Call,7),e.of?"of":"in"),s=U(s,this.generateExpression(e.right,r.Sequence,7)),["for"+m+"(",s,")"]},SpreadElement:function(e,t,i){return["...",this.generateExpression(e.argument,r.Assignment,7)]},TaggedTemplateExpression:function(e,t,i){var n=3;return 2&i||(n=1),q([this.generateExpression(e.tag,r.Call,n),this.generateExpression(e.quasi,r.Primary,4)],r.TaggedTemplate,t)},TemplateElement:function(e,t,r){return e.value.raw},TemplateLiteral:function(e,t,i){var n,s,a;for(n=["`"],s=0,a=e.quasis.length;s":return"greaterThan";case">=":return"greaterEqual";case"<":return"lessThan";case"<=":return"lessEqual";case"&&":return"and";case"||":return"or"}}function xd(e){return e&&"CallExpression"===e.type&&("Identifier"===e.callee?.type&&e.callee?.name.startsWith("uniform")||"MemberExpression"===e.callee?.type&&e.callee?.property.name.startsWith("uniform"))}function vd(e,t){return!!t?.size&&(!("FunctionDeclaration"!==e.type||!t.has(e.id?.name))||!("VariableDeclarator"!==e.type||!t.has(e.id?.name)||"FunctionExpression"!==e.init?.type&&"ArrowFunctionExpression"!==e.init?.type))}function bd(e){if("Identifier"===e?.type)return e.name;if("MemberExpression"!==e?.type||e.computed)return null;const t=bd(e.object),r=e.property?.name;return t&&r?`${t}.${r}`:null}function _d(e){if("CallExpression"!==e?.type)return!1;const t=bd(e.callee);return!!t&&("loopProtect.protect"===t||t.endsWith(".loopProtect")||t.endsWith(".loopProtect.protect"))}function wd(e){if("VariableDeclaration"===e.type){return e.declarations.some((e=>"CallExpression"===e.init?.type&&("MemberExpression"===e.init?.callee?.type&&"Identifier"===e.init?.callee?.object?.type&&"__p5"===e.init?.callee?.object?.name&&("strandsFor"===e.init?.callee?.property?.name||"strandsIf"===e.init?.callee?.property?.name)||"Identifier"===e.init?.callee?.type&&("__p5.strandsFor"===e.init?.callee?.name||"__p5.strandsIf"===e.init?.callee?.name))))}return!1}function Cd(e){if(!e||"string"!=typeof e)return!1;return[["x","y","z","w"],["r","g","b","a"],["s","t","p","q"]].some((t=>[...e].every((e=>t.includes(e)))))}function Ed(e){const t=[];let r=e;for(;"MemberExpression"===r.type;){if(r.computed)return null;const e=r.property.name||r.property.value;if(Cd(e)){r=r.object;break}t.unshift(e),r=r.object}return"Identifier"!==r.type?null:(t.unshift(r.name),t.join("."))}function Ad(e,t,r){if(!e||"object"!=typeof e)return e;const i=e=>{if(!e||"object"!=typeof e)return e;if("Identifier"===e.type&&e.name===t)return{...e,name:r};const n={...e};for(const t in e)e.hasOwnProperty(t)&&"parent"!==t&&(Array.isArray(e[t])?n[t]=e[t].map(i):"object"==typeof e[t]&&(n[t]=i(e[t])));return n};return i(e)}function Dd(e,t,r){r.some((e=>xd(e)||vd(e,t.uniformCallbackNames)))||(e.left={type:"CallExpression",callee:{type:"Identifier",name:"__p5.strandsNode"},arguments:[e.left]},e.type="CallExpression",e.callee={type:"MemberExpression",object:e.left,property:{type:"Identifier",name:yd(e.operator)}},e.arguments=[e.right])}function Sd(e,t,r=null){if("BlockStatement"!==e.type)return;const i=new Map,n=[];for(const e of t){const t=e.split("."),s=`__copy_${t.join("_")}_${md++}`;i.set(e,s);let a=r?{type:"Identifier",name:r}:{type:"Identifier",name:t[0]};const o=r?t:t.slice(1);for(const e of o)a={type:"MemberExpression",object:a,property:{type:"Identifier",name:e},computed:!1};n.push({type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:s},init:{type:"CallExpression",callee:{type:"MemberExpression",object:a,property:{type:"Identifier",name:"copy"},computed:!1},arguments:[]}}],kind:"let"})}e.body.forEach((e=>function(e,t){const r=e=>{if(e&&"object"==typeof e){if("MemberExpression"===e.type){if(Cd(e.property.name||e.property.value))return void r(e.object);const i=Ed(e);if(i&&t.has(i))return void Object.assign(e,{type:"Identifier",name:t.get(i)})}if("Identifier"===e.type&&t.has(e.name)&&(e.name=t.get(e.name)),"AssignmentExpression"===e.type){let r=null;"Identifier"===e.left.type?r=e.left.name:"MemberExpression"===e.left.type&&(r=Ed(e.left)),r&&t.has(r)&&("Literal"===e.right.type||"ArrayExpression"===e.right.type)&&(e.right={type:"CallExpression",callee:{type:"Identifier",name:"__p5.strandsNode"},arguments:[e.right]})}for(const t in e)if(e.hasOwnProperty(t)&&"parent"!==t){if("MemberExpression"===e.type&&"property"===t&&!e.computed)continue;Array.isArray(e[t])?e[t].forEach(r):"object"==typeof e[t]&&r(e[t])}}};r(e)}(e,i))),e.body.unshift(...n);const s={type:"ObjectExpression",properties:Array.from(t).map((e=>({type:"Property",key:{type:"Literal",value:e},value:{type:"Identifier",name:i.get(e)},kind:"init",computed:!1,shorthand:!1})))};e.body.push({type:"ReturnStatement",argument:s})}const Td={UnaryExpression(e,t,r){if(r.some((e=>xd(e)||vd(e,t.uniformCallbackNames))))return;const i=gn[e.operator],n=e=>{e.type="CallExpression",e.callee={type:"Identifier",name:`__p5.${i}`},e.arguments=[e.argument]};if("MemberExpression"===e.type){const t=e.argument.property.name;let r=[["x","y","z","w"],["r","g","b","a"],["s","t","p","q"]].some((e=>[...t].every((t=>e.includes(t)))))&&"MemberExpression"===e.argument.type&&!e.argument.computed;r?(e.type="MemberExpression",e.object={type:"CallExpression",callee:{type:"Identifier",name:`__p5.${i}`},arguments:[e.argument.object]},e.property={type:"Identifier",name:t}):n(e)}else n(e);delete e.argument,delete e.operator},BreakStatement(e,t,r){r.some((e=>xd(e)||vd(e,t.uniformCallbackNames)))||(e.callee={type:"Identifier",name:"__p5.break"},e.arguments=[],e.type="CallExpression")},MemberExpression(e,t,r){if(!r.some((e=>xd(e)||vd(e,t.uniformCallbackNames)))&&("AssignmentExpression"!==r.at(-2)?.type||r.at(-2).left!==e)&&e.computed){const t=e.object,r=e.property;e.computed=void 0,e.object=void 0,e.callee={type:"MemberExpression",object:t,property:{type:"Identifier",name:"get"}},e.arguments=[r],e.type="CallExpression"}},VariableDeclarator(e,t,r){if(!r.some((e=>xd(e)||vd(e,t.uniformCallbackNames)))){if(xd(e.init)&&(0===e.init.arguments.length||"Literal"!==e.init.arguments[0].type||"string"!=typeof e.init.arguments[0].value)){const t={type:"Literal",value:e.id.name};e.init.arguments.unshift(t)}if(function(e){return e&&"CallExpression"===e.type&&("Identifier"===e.callee?.type&&(e.callee?.name.startsWith("varying")||e.callee?.name.startsWith("shared"))||"MemberExpression"===e.callee?.type&&(e.callee?.property.name.startsWith("varying")||e.callee?.property.name.startsWith("shared")))}(e.init))if(0===e.init.arguments.length||"Literal"!==e.init.arguments[0].type||"string"!=typeof e.init.arguments[0].value){const r={type:"Literal",value:e.id.name};e.init.arguments.unshift(r),t.varyings[e.id.name]=r}else t.varyings[e.id.name]=e.init.arguments[0]}},Identifier(e,t,r){r.some((e=>xd(e)||vd(e,t.uniformCallbackNames)))||t.varyings[e.name]&&!r.some((t=>"AssignmentExpression"===t.type&&t.left===e))&&(e.type="CallExpression",e.callee={type:"MemberExpression",object:{type:"Identifier",name:e.name},property:{type:"Identifier",name:"getValue"}},e.arguments=[])},ArrayExpression(e,t,r){if(r.some((e=>xd(e)||vd(e,t.uniformCallbackNames))))return;(e.elements.length<2||e.elements.length>4)&&Eo("type error",`Array literals in shader functions are transpiled to vectors and must have 2-4 elements (got ${e.elements.length}).`);const i=JSON.parse(JSON.stringify(e));e.type="CallExpression",e.callee={type:"Identifier",name:"__p5.strandsNode"},e.arguments=[i]},AssignmentExpression(e,t,r){if(r.some((e=>xd(e)||vd(e,t.uniformCallbackNames))))return;const i=["Literal","ArrayExpression","Identifier"];if("="!==e.operator){const t=yd(e.operator.replace("=","")),r={type:"CallExpression",callee:{type:"MemberExpression",object:i.includes(e.left.type)?{type:"CallExpression",callee:{type:"Identifier",name:"__p5.strandsNode"},arguments:[e.left]}:e.left,property:{type:"Identifier",name:t}},arguments:[e.right]};e.operator="=",e.right=r}if(t.varyings[e.left.name])e.type="ExpressionStatement",e.expression={type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:e.left.name},property:{type:"Identifier",name:"bridge"}},arguments:[e.right]};else if("MemberExpression"===e.left.type){if(e.left.computed){const t=e.left,r=e.right,i=t.object,n=t.property;return e.right=void 0,e.left=void 0,e.operator=void 0,e.callee={type:"MemberExpression",object:i,property:{type:"Identifier",name:"set"}},e.arguments=[n,r],void(e.type="CallExpression")}let r=null;if("Identifier"===e.left.object.type&&t.varyings[e.left.object.name]?r=e.left.object.name:"CallExpression"===e.left.object.type&&"MemberExpression"===e.left.object.callee?.type&&"getValue"===e.left.object.callee.property?.name&&"Identifier"===e.left.object.callee.object?.type&&t.varyings[e.left.object.callee.object.name]&&(r=e.left.object.callee.object.name),r){const t=e.left.property.name;e.type="ExpressionStatement",e.expression={type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:r},property:{type:"Identifier",name:"bridgeSwizzle"}},arguments:[{type:"Literal",value:t},e.right]}}}},BinaryExpression:Dd,LogicalExpression:Dd,ConditionalExpression(e,t,r){if(r.some((e=>xd(e)||vd(e,t.uniformCallbackNames))))return;const i=e.test,n=e.consequent,s=e.alternate;e.type="CallExpression",e.callee={type:"Identifier",name:"__p5.strandsTernary"},e.arguments=[i,n,s],delete e.test,delete e.consequent,delete e.alternate},IfStatement(e,t,r){if(r.some((e=>xd(e)||vd(e,t.uniformCallbackNames))))return;const i=e.test,n={type:"ArrowFunctionExpression",params:[],body:"BlockStatement"===e.consequent.type?e.consequent:{type:"BlockStatement",body:[e.consequent]}};let s,a={type:"CallExpression",callee:{type:"Identifier",name:"__p5.strandsIf"},arguments:[i,n]};s=e.alternate?{type:"ArrowFunctionExpression",params:[],body:"BlockStatement"===e.alternate.type?e.alternate:{type:"BlockStatement",body:[e.alternate]}}:{type:"ArrowFunctionExpression",params:[],body:{type:"BlockStatement",body:[]}},a={type:"CallExpression",callee:{type:"MemberExpression",object:a,property:{type:"Identifier",name:"Else"}},arguments:[s]};const o=new Set,h=e=>{const t=new Set;wp(e,{VariableDeclarator(e,r){r.some(wd)||"Identifier"===e.id.type&&t.add(e.id.name)}}),wp(e,{AssignmentExpression(e,r){if(r.some(wd))return;const i=e.left;if("Identifier"===i.type)t.has(i.name)||o.add(i.name);else if("MemberExpression"===i.type){const e=Ed(i);if(e){const r=e.split(".")[0];t.has(r)||o.add(e)}}}})};if(h(n.body),h(s.body),o.size>0){Sd(n.body,o),Sd(s.body,o);const t="__block_"+md++,r=[];for(const e of o){const t=e.split(".");let i={type:"Identifier",name:t[0]};for(let e=1;exd(e)||vd(e,t.uniformCallbackNames))))return;let i;if("++"===e.operator)i="+";else{if("--"!==e.operator)return;i="-"}const n={type:"AssignmentExpression",operator:"=",left:e.argument,right:{type:"BinaryExpression",operator:i,left:e.argument,right:{type:"Literal",value:1}}};Object.assign(e,n),delete e.prefix,Td.BinaryExpression(e.right,t,[...r,e]),Td.AssignmentExpression(e,t,r)},ForStatement(e,t,r){if(r.some((e=>xd(e)||vd(e,t.uniformCallbackNames))))return;const i="loopVar"+gd++;let n;if(e.init&&"VariableDeclaration"===e.init.type){let t=e.init.declarations[0].init;t={body:[{type:"ExpressionStatement",expression:t}]}.body[0].expression,n={type:"ArrowFunctionExpression",params:[],body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:t}]}}}else n={type:"ArrowFunctionExpression",params:[],body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Literal",value:0}}]}};let s=e.test||{type:"Literal",value:!0};if("VariableDeclaration"===e.init?.type){s=Ad(s,e.init.declarations[0].id.name,i)}s={body:[{type:"ExpressionStatement",expression:s}]}.body[0].expression;const a={type:"ArrowFunctionExpression",params:[{type:"Identifier",name:i}],body:s};let o;if(e.update){let t=e.update;if("VariableDeclaration"===e.init?.type){t=Ad(t,e.init.declarations[0].id.name,i)}t={body:[{type:"ExpressionStatement",expression:t}]}.body[0].expression,o={type:"ArrowFunctionExpression",params:[{type:"Identifier",name:i}],body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:t}]}}}else o={type:"ArrowFunctionExpression",params:[{type:"Identifier",name:i}],body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:i}}]}};let h="BlockStatement"===e.body.type?e.body:{type:"BlockStatement",body:[e.body]};if("VariableDeclaration"===e.init?.type){h=Ad(h,e.init.declarations[0].id.name,i)}const u={type:"ArrowFunctionExpression",params:[{type:"Identifier",name:i},{type:"Identifier",name:"vars"}],body:h},l=new Set,c=new Set;if(wp(u.body,{VariableDeclarator(e,t){t.some(wd)||"Identifier"===e.id.type&&c.add(e.id.name)}}),wp(u.body,{AssignmentExpression(e,t){if(t.some(wd))return;const r=e.left;if("Identifier"===r.type)c.has(r.name)||l.add(r.name);else if("MemberExpression"===r.type){const e=Ed(r);if(e){const t=e.split(".")[0];c.has(t)||l.add(e)}}}}),l.size>0){Sd(u.body,l,"vars");const t="__block_"+md++,r=[],i={type:"ObjectExpression",properties:Array.from(l).map((e=>{const t=e.split(".");let r={type:"Identifier",name:t[0]};for(let e=1;e0&&(t=!0)}};return e.body&&"BlockStatement"===e.body.type&&Cp(e.body,{},i),t}function kd(e){let t=!1;return e&&Cp(e,{},{ReturnStatement(){t=!0}}),t}function Md(e){if(!e.body||"BlockStatement"!==e.body.type)return;e.body.body.unshift({type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"__returnValue"},init:null}],kind:"let"}),function e(t){for(let r=0;r0&&(i.alternate={type:"BlockStatement",body:n},t.splice(r+1),e(i.alternate.body))}"IfStatement"===i.type?(i.consequent&&"BlockStatement"===i.consequent.type&&e(i.consequent.body),i.alternate&&"BlockStatement"===i.alternate.type&&e(i.alternate.body)):"ForStatement"===i.type&&i.body&&"BlockStatement"===i.body.type?e(i.body.body):"BlockStatement"===i.type&&e(i.body)}}(e.body.body);const t={ReturnStatement(e){e.type="ExpressionStatement",e.expression={type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"__returnValue"},right:e.argument||{type:"Identifier",name:"undefined"}},delete e.argument}};Cp(e.body,{},t);e.body.body.push({type:"ReturnStatement",argument:{type:"Identifier",name:"__returnValue"}})}function Id(e){let t=!1,r=0;const i={IfStatement(e,t,i){r++,e.test&&i(e.test,t),e.consequent&&i(e.consequent,t),e.alternate&&i(e.alternate,t),r--},ForStatement(e,t,i){r++,e.init&&i(e.init,t),e.test&&i(e.test,t),e.update&&i(e.update,t),e.body&&i(e.body,t),r--},CallExpression(e){r>0&&"MemberExpression"===e.callee?.type&&"set"===e.callee?.property?.name&&(t=!0)}};return e.body&&"BlockStatement"===e.body.type&&Cp(e.body,{},i),t}function Bd(e){if(!e.body||"BlockStatement"!==e.body.type)return;const t=new Map,r={CallExpression(e){if("MemberExpression"===e.callee?.type&&"set"===e.callee?.property?.name&&e.callee?.object){const r=e.callee.object,i=fd.generate(r);t.has(i)||t.set(i,r)}}};if(Cp(e.body,{},r),0!==t.size)for(const[r,i]of t){const t=`__${r.replace(/[^a-zA-Z0-9_]/g,"_")}_value`,n={type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:t},init:null}],kind:"let"};let s=-1;for(let t=0;t0){let r=null;for(let e=n.length-1;e>=0;e--)if("ExpressionStatement"===n[e].type){r=n[e];break}r&&(r.type="ExpressionStatement",r.expression={type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:t},right:e.arguments[0]})}}}};wp(e.body,a);const o={type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:JSON.parse(JSON.stringify(i)),property:{type:"Identifier",name:"set"},computed:!1},arguments:[{type:"Identifier",name:t}]}};let h=-1;for(let t=0;txd(e)||vd(e,t)))||Id(e)&&r.push(e)},FunctionExpression(e,i){i.some((e=>xd(e)||vd(e,t)))||Id(e)&&r.push(e)},FunctionDeclaration(e,i){i.some((e=>xd(e)||vd(e,t)))||Id(e)&&r.push(e)}});for(const e of r)Bd(e)}(n,s),function(e,t){const r={...Td};delete r.IfStatement,delete r.ForStatement,wp(e,r,void 0,{varyings:{},uniformCallbackNames:t})}(n,s),function(e,t){const r=[];wp(e,{VariableDeclarator(e,i){if(i.some((e=>xd(e)||vd(e,t))))return;const n=e.init;!n||"ArrowFunctionExpression"!==n.type&&"FunctionExpression"!==n.type||Fd(n)&&r.push(n)},FunctionDeclaration(e,i){i.some((e=>xd(e)||vd(e,t)))||Fd(e)&&r.push(e)},CallExpression(e,t){}});for(const e of r)Md(e)}(n,s),function(e,t){Cp(e,{varyings:{},inControlFlow:0,uniformCallbackNames:t},{CallExpression(e,t,r){if(!xd(e)){e.callee&&r(e.callee,t);for(const i of e.arguments)r(i,t)}},FunctionDeclaration(e,t,r){t.uniformCallbackNames?.has(e.id?.name)||e.body&&r(e.body,t)},VariableDeclarator(e,t,r){(!t.uniformCallbackNames?.has(e.id?.name)||"FunctionExpression"!==e.init?.type&&"ArrowFunctionExpression"!==e.init?.type)&&e.init&&r(e.init,t)},IfStatement(e,t,r){t.inControlFlow++,e.test&&r(e.test,t),e.consequent&&r(e.consequent,t),e.alternate&&r(e.alternate,t),Td.IfStatement(e,t,[]),t.inControlFlow--},ForStatement(e,t,r){t.inControlFlow++,e.init&&r(e.init,t),e.test&&r(e.test,t),e.update&&r(e.update,t),e.body&&r(e.body,t),Td.ForStatement(e,t,[]),t.inControlFlow--},ReturnStatement(e,t,r){t.inControlFlow&&(e.type="ExpressionStatement",e.expression={type:"CallExpression",callee:{type:"Identifier",name:"__p5.strandsEarlyReturn"},arguments:e.argument?[e.argument]:[]},delete e.argument)}})}(n,s),function(e,t,r){const i=fd.generate(t),n=Object.keys(r),s=/\(?\s*(?:function)?\s*\w*\s*\(([^)]*)\)\s*(?:=>)?\s*{((?:.|\n)*)}\s*;?\s*\)?/.exec(i);if(!s)throw console.log(i),new Error("Could not parse p5.strands function!");const a=s[1].split(/,\s*/).filter((e=>!!e.trim()));let o,h;a.length>0?(h=a,o=[r]):(h=n,o=n.map((e=>r[e])));const u=s[2];try{const t=new Function("__p5",...h,u);return()=>t(e,...o)}catch(e){throw console.error(e),console.log(h),console.log(u),new Error("Error transpiling p5.strands callback!")}}(e,n,i)}function Od(e,t,r){const i=t.filter((e=>null!==e.value.id));if(0===i.length)throw new Error(`No valid inputs for phi node for variable ${r}`);const n=i.map((t=>Fo(e.dag,t.value.id)));let s=n.find((e=>e.baseType!==en&&e.dimension))??n.find((e=>e.baseType!==en));s||(s=n[0]);const a=s.dimension,o=s.baseType;if(o!==en)for(const t of n)t.baseType===en&&Mo(e.dag,t.id,o,a);const h={nodeType:Vi.PHI,dimension:a,baseType:o,dependsOn:t.map((e=>e.value.id)).filter((e=>null!==e)),phiBlocks:t.map((e=>e.blockId))},u=So(e.dag,h);return No(e.cfg,e.cfg.currentBlock,u),{id:u,dimension:a,baseType:o}}class Pd{constructor(e,t,r){this.branches=[{condition:t,branchCallback:r,blockType:xn.IF_BODY}],this.ctx=e}ElseIf(e,t){return this.branches.push({condition:e,branchCallback:t,blockType:xn.IF_BODY}),this}Else(e=()=>({})){this.branches.push({condition:null,branchCallback:e,blockType:xn.IF_BODY});const t=function(e,t){const r=e.cfg,i=t.branches,n=Oo(r,xn.MERGE),s=[],a=[],o={},h={},u=Oo(r,xn.BRANCH);Po(r,r.currentBlock,u),Po(r,u,n);let l=u;for(let t=0;t1&&(i.dependsOn[1]=t.id),i.phiInputs&&i.phiInputs.length>1&&(i.phiInputs[1].value=t)}Bo(e),Lo(e,r);for(const[t,i]of Object.entries(this.initialVars))if("loopVar"!==t&&h[t]){const n=h[t].id,s=i.id,a=To({nodeType:Vi.ASSIGNMENT,dependsOn:[n,s],phiBlocks:[]});No(e,r,So(this.strandsContext.dag,a))}Bo(e),Lo(e,this.finalBodyBlock);for(const[t,r]of Object.entries(this.bodyResults))if("loopVar"!==t&&h[t]){const i=h[t].id,n=r.id,s=To({nodeType:Vi.ASSIGNMENT,dependsOn:[i,n],phiBlocks:[]}),a=So(this.strandsContext.dag,s);No(e,this.finalBodyBlock,a)}Bo(e);const u={};for(const[e,t]of Object.entries(h))u[e]=Uo(t.id,t.dimension,this.strandsContext);return Io(e,t),u}buildBoundedLoop(e,t,r,i,n,s,a){const o=Oo(e,xn.FOR);if(Po(e,t,o),Io(e,o),i){const t=To({nodeType:Vi.ASSIGNMENT,dependsOn:[n.id,i.id],phiBlocks:[]});No(e,o,So(this.strandsContext.dag,t))}const h=To({nodeType:Vi.STATEMENT,statementType:Wi,dependsOn:[s.id],phiBlocks:[]});No(e,o,So(this.strandsContext.dag,h));const u=To({nodeType:Vi.ASSIGNMENT,dependsOn:[n.id,a.id],phiBlocks:[]});No(e,o,So(this.strandsContext.dag,u)),Bo(e);const l=e.blockInstructions[o]||[],c=i?3:2;if(l.length!==c)throw new Error(`FOR block must have exactly ${c} statements, got ${l.length}`);const p=Oo(e,xn.SCOPE_START);Po(e,o,p);const d=Oo(e,xn.DEFAULT);this.bodyBlock=d,Po(e,p,d),this.executeBodyCallback(e,t,d,n);const f=Oo(e,xn.SCOPE_END);Po(e,d,f),Po(e,f,r)}buildUnboundedLoop(e,t,r,i,n,s,a){const o=Oo(e,xn.FOR);if(Po(e,t,o),Io(e,o),i){const t=To({nodeType:Vi.ASSIGNMENT,dependsOn:[n.id,i.id],phiBlocks:[]});No(e,o,So(this.strandsContext.dag,t))}else{const t=To({nodeType:Vi.STATEMENT,statementType:Xi,dependsOn:[],phiBlocks:[]});No(e,o,So(this.strandsContext.dag,t))}const h=To({nodeType:Vi.STATEMENT,statementType:Xi,dependsOn:[],phiBlocks:[]});No(e,o,So(this.strandsContext.dag,h));const u=To({nodeType:Vi.STATEMENT,statementType:Xi,dependsOn:[],phiBlocks:[]});No(e,o,So(this.strandsContext.dag,u)),Bo(e);const l=Oo(e,xn.SCOPE_START);Po(e,o,l);const c=Oo(e,xn.DEFAULT);Po(e,l,c),Io(e,c);const p=s,d=this.createLogicalNotNode(p),f=Oo(e,xn.IF_COND);Po(e,c,f),e.blockConditions[f]=d.id;const m=Oo(e,xn.SCOPE_START);Po(e,f,m);const g=Oo(e,xn.DEFAULT);Po(e,m,g),Io(e,g);const y=To({nodeType:Vi.STATEMENT,statementType:Hi,dependsOn:[],phiBlocks:[]});No(e,g,So(this.strandsContext.dag,y)),Bo(e);const x=Oo(e,xn.SCOPE_END);Po(e,g,x),Po(e,x,r),Bo(e);const v=Oo(e,xn.DEFAULT);this.bodyBlock=v,Po(e,c,v),this.executeBodyCallback(e,t,v,n);const b=Oo(e,xn.DEFAULT);Po(e,v,b),Io(e,b);const _=To({nodeType:Vi.ASSIGNMENT,dependsOn:[n.id,a.id],phiBlocks:[]});No(e,b,So(this.strandsContext.dag,_)),Bo(e);const w=Oo(e,xn.SCOPE_END);Po(e,b,w),Po(e,w,r),Po(e,c,r)}initializeLoopVariable(e,t){Io(e,t);let r=this.initialCb();if(!r?.isStrandsNode){const{id:e,dimension:t}=Yo(this.strandsContext,{baseType:Yi,dimension:1},r);r=Uo(e,t,this.strandsContext)}const i=Od(this.strandsContext,[{value:r,blockId:t},{value:r,blockId:t}],"loopVar");return Bo(e),{initialVar:r,phiNode:i}}createLogicalNotNode(e){const t=To({nodeType:Vi.OPERATION,opCode:cn.LOGICAL_NOT,baseType:Ki,dimension:1,dependsOn:[e.id],phiBlocks:[],usedBy:[]});return Uo(So(this.strandsContext.dag,t),1,this.strandsContext)}executeBodyCallback(e,t,r,i){Io(e,r);const n={},s={};Lo(e,t);for(const[e,i]of Object.entries(this.initialVars))if("loopVar"!==e){const a=Od(this.strandsContext,[{value:i,blockId:t},{value:i,blockId:r}],e);s[e]=a,n[e]=Uo(a.id,a.dimension,this.strandsContext)}Bo(e);const a=Uo(i.id,i.dimension,this.strandsContext);this.bodyResults=this.bodyCb(a,n)||{};for(const e in this.bodyResults)this.bodyResults[e]=this.strandsContext.p5.strandsNode(this.bodyResults[e]);this.phiNodesForBody=s,this.finalBodyBlock=e.currentBlock,Bo(e)}loopIsBounded(e,t,r){if(!t)return!1;const i=Fo(this.strandsContext.dag,t.id);if(i.nodeType!==Vi.OPERATION)return!1;if(!i.dependsOn||2!==i.dependsOn.length)return!1;const n=Uo(i.dependsOn[0],1,this.strandsContext),s=Uo(i.dependsOn[1],1,this.strandsContext),a=this.nodeUsesOnlyLiterals(n),o=this.nodeUsesOnlyLiterals(s);return a||o}nodeUsesOnlyLiterals(e){const t=Fo(this.strandsContext.dag,e.id);switch(t.nodeType){case Vi.LITERAL:return!0;case Vi.VARIABLE:case Vi.PHI:return!1;case Vi.OPERATION:if(t.dependsOn)for(const e of t.dependsOn){const t=Uo(e,1,this.strandsContext);if(!this.nodeUsesOnlyLiterals(t))return!1}return!0;default:return!1}}}const Rd={width:{typeInfo:sn.float1,get:e=>e.width},height:{typeInfo:sn.float1,get:e=>e.height},mouseX:{typeInfo:sn.float1,get:e=>e.mouseX},mouseY:{typeInfo:sn.float1,get:e=>e.mouseY},pmouseX:{typeInfo:sn.float1,get:e=>e.pmouseX},pmouseY:{typeInfo:sn.float1,get:e=>e.pmouseY},winMouseX:{typeInfo:sn.float1,get:e=>e.winMouseX},winMouseY:{typeInfo:sn.float1,get:e=>e.winMouseY},pwinMouseX:{typeInfo:sn.float1,get:e=>e.pwinMouseX},pwinMouseY:{typeInfo:sn.float1,get:e=>e.pwinMouseY},frameCount:{typeInfo:sn.float1,get:e=>e.frameCount},deltaTime:{typeInfo:sn.float1,get:e=>e.deltaTime},displayWidth:{typeInfo:sn.float1,get:e=>e.displayWidth},displayHeight:{typeInfo:sn.float1,get:e=>e.displayHeight},windowWidth:{typeInfo:sn.float1,get:e=>e.windowWidth},windowHeight:{typeInfo:sn.float1,get:e=>e.windowHeight},mouseIsPressed:{typeInfo:sn.bool1,get:e=>e.mouseIsPressed}};function Vd(e,t,r,i){const n=function(e){return e._builtinGlobals&&e._builtinGlobals.dag===e.dag||(e._builtinGlobals={dag:e.dag,nodes:new Map,uniformsAdded:new Set}),e._builtinGlobals}(e),s=n.nodes.get(t);if(s)return s;n.uniformsAdded.has(t)||(n.uniformsAdded.add(t),e.uniforms.push({name:t,typeInfo:r,defaultValue:i}));const{id:a,dimension:o}=Go(e,r,t),h=Uo(a,o,e);return n.nodes.set(t,h),h}function Ud(e,t){const r=Rd[t];if(!r)return null;const i=`_p5_global_${t}`,n=e.renderer?._pInst||e.p5?.instance,s=Vd(e,i,r.typeInfo,(()=>n?r.get(n):void 0));return s._originalBuiltinName=t,s}function zd(e,t,r,i){e[r]=i;const n=t?.Graphics?.prototype;n&&(n[r]=i)}function jd(e,t,r,i){t.windowOverrides[r]=window[r],t.fnOverrides[r]=e[r],window[r]=i,e[r]=i;const n=t.p5?.Graphics?.prototype;n&&(t.graphicsOverrides[r]=Object.prototype.hasOwnProperty.call(n,r)?n[r]:void 0,n[r]=i)}function Gd(e,t,r){for(const{name:t,arity:i,opCode:n}of dn)"binary"===i&&(Vo.prototype[t]=function(...e){const{id:t,dimension:i}=Ho(r,this,e,n);return Uo(t,i,r)}),"unary"===i&&(e[t]=function(e){const{id:t,dimension:i}=$o(r,e,n);return Uo(t,i,r)});zd(t,e,"discard",(function(){Jo(r,$i)})),zd(t,e,"break",(function(){Jo(r,Hi)})),e.break=t.break,zd(t,e,"instanceID",(function(){const e=Go(r,{baseType:Zi,dimension:1},r.backend.instanceIdReference());return Uo(e.id,e.dimension,r)})),e.strandsIf=function(e,t){return new Pd(r,e,t)},zd(t,e,"strandsIf",e.strandsIf),e.strandsFor=function(e,t,i,n,s){return new Nd(r,e,t,i,n,s).build()},zd(t,e,"strandsFor",e.strandsFor),e.strandsTernary=function(e,t,i){return function(e,t,r,i){const{dag:n,cfg:s,p5:a}=e,o=t?.isStrandsNode?t:a.strandsNode(t),h=r?.isStrandsNode?r:a.strandsNode(r),u=i?.isStrandsNode?i:a.strandsNode(i);let l=ko(n,h.id),c=ko(n,u.id);l.baseType===en&&c.baseType!==en?(Mo(n,h.id,c.baseType,c.dimension),l=ko(n,h.id)):c.baseType===en&&l.baseType!==en&&(Mo(n,u.id,l.baseType,l.dimension),c=ko(n,u.id)),l.baseType===en||c.baseType===en||l.baseType===c.baseType&&l.dimension===c.dimension||Eo("type error",`The true and false branches of a ternary expression must have the same type. Right now, the true branch is a ${l.baseType}${l.dimension}, and the false branch is a ${c.baseType}${c.dimension}.`);const p=l,d=So(n,To({nodeType:Vi.OPERATION,opCode:pn.TERNARY,dependsOn:[o.id,h.id,u.id],baseType:p.baseType,dimension:p.dimension}));return No(s,s.currentBlock,d),Uo(d,p.dimension,e)}(r,e,t,i)},zd(t,e,"strandsTernary",e.strandsTernary),e.strandsEarlyReturn=function(t){const{dag:i,cfg:n}=r;if(!r.activeHook)throw new Error("strandsEarlyReturn can only be used inside a hook callback");const s=t?.isStrandsNode?t:e.strandsNode(t),a=Oo(n,xn.DEFAULT);Po(n,n.currentBlock,a),Io(n,a);const o=So(i,To({nodeType:Vi.STATEMENT,statementType:qi,dependsOn:void 0!==t?[s.id]:[]}));return No(n,n.currentBlock,o),r.activeHook.earlyReturns.push({earlyReturnID:o,valueNode:s}),Bo(n),s},zd(t,e,"strandsEarlyReturn",e.strandsEarlyReturn),e.strandsNode=function(...e){if(1===e.length&&e[0]instanceof Vo)return e[0];e.length>4&&Eo("type error","It looks like you've tried to construct a p5.strands node implicitly, with more than 4 components. This is currently not supported.");const t=e.flat().filter((e=>null!=e));if(0===t.length){const{id:e,dimension:t}=Yo(r,{baseType:en,dimension:null},[0]);return Uo(e,t,r)}const{id:i,dimension:n}=Yo(r,{baseType:Yi,dimension:null},t);return Uo(i,n,r)};for(const[i,n]of Object.entries(zo)){if(n[0].isp5Function){const n=t[i];zd(t,e,i,(function(...e){if(r.active){const{id:t,dimension:n}=Ko(r,i,e);return Uo(t,n,r)}return n.apply(this,e)}))}else zd(t,e,i,(function(...t){if(r.active){const{id:e,dimension:n}=Ko(r,i,t);return Uo(e,n,r)}e._friendlyError(`It looks like you've called ${i} outside of a shader's modify() function.`)}))}const i=t.lerp;zd(t,e,"lerp",(function(...e){return r.active?this.mix(...e):i.apply(this,e)}));const n=t.map;zd(t,e,"map",(function(...t){if(!r.active)return n.apply(this,t);const[i,s,a,o,h,u]=t,l=e.strandsNode(i),c=e.strandsNode(s),p=e.strandsNode(a),d=l.sub(c).div(p.sub(c)),f=this.mix(o,h,d);return u?this.clamp(f,this.min(o,h),this.max(o,h)):f}));const s=t.color;zd(t,e,"color",(function(...e){if(!r.active)return s.apply(this,e);const t=s.apply(this,e)._getRGBA(),{id:i,dimension:n}=Yo(r,{baseType:Yi,dimension:null},t);return Uo(i,n,r)}));const a=t.lerpColor;zd(t,e,"lerpColor",(function(...e){return r.active?this.mix(...e):a.apply(this,e)}));const o=t.red;zd(t,e,"red",(function(...t){return r.active?e.strandsNode(t[0]).x:o.apply(this,t)}));const h=t.green;zd(t,e,"green",(function(...t){return r.active?e.strandsNode(t[0]).y:h.apply(this,t)}));const u=t.blue;zd(t,e,"blue",(function(...t){return r.active?e.strandsNode(t[0]).z:u.apply(this,t)}));const l=t.alpha;zd(t,e,"alpha",(function(...t){return r.active?e.strandsNode(t[0]).w:l.apply(this,t)}));const c=(t,r)=>{const i=r.x,n=r.y,s=r.z,a=t.max(i,t.max(n,s)),o=t.min(i,t.min(n,s)),h=a.add(o).div(2),u=a.sub(o),l=e.strandsNode(1e-10),c=t.mix(e.strandsNode(0),u.div(e.strandsNode(1).sub(t.abs(h.mult(2).sub(1)))),t.step(l,u)),p=t.mod(n.sub(s).div(u.add(l)),e.strandsNode(6)).div(6),d=s.sub(i).div(u.add(l)).add(2).div(6),f=i.sub(n).div(u.add(l)).add(4).div(6),m=t.step(a.sub(l),i).mult(t.step(i.sub(l),a)),g=t.step(a.sub(l),n).mult(t.step(n.sub(l),a)),y=t.mix(t.mix(f,d,g),p,m);return t.vec3(y,c,h)},p=t.hue;zd(t,e,"hue",(function(...t){if(!r.active)return p.apply(this,t);const i=e.strandsNode(t[0]);return c(this,this.vec3(i.x,i.y,i.z)).x}));const d=t.saturation;zd(t,e,"saturation",(function(...t){if(!r.active)return d.apply(this,t);const i=e.strandsNode(t[0]);return c(this,this.vec3(i.x,i.y,i.z)).y}));const f=t.brightness;zd(t,e,"brightness",(function(...t){if(!r.active)return f.apply(this,t);const i=e.strandsNode(t[0]);return((t,r)=>{const i=r.x,n=r.y,s=r.z,a=t.vec4(0,-1/3,2/3,-1),o=t.mix(t.vec4(s,n,a.w,a.z),t.vec4(n,s,a.x,a.y),t.step(s,n)),h=t.mix(t.vec4(o.x,o.y,o.w,i),t.vec4(i,o.y,o.z,o.x),t.step(o.x,i)),u=h.x.sub(t.min(h.w,h.y)),l=e.strandsNode(1e-10),c=t.abs(h.z.add(h.w.sub(h.y).div(u.mult(6).add(l)))),p=u.div(h.x.add(l));return t.vec3(c,p,h.x)})(this,this.vec3(i.x,i.y,i.z)).z}));const m=t.lightness;zd(t,e,"lightness",(function(...t){if(!r.active)return m.apply(this,t);const i=e.strandsNode(t[0]);return c(this,this.vec3(i.x,i.y,i.z)).z})),zd(t,e,"getTexture",(function(...t){if(r.active){const{id:e,dimension:i}=r.backend.createGetTextureCall(r,t);return Uo(e,i,r)}e._friendlyError("It looks like you've called getTexture outside of a shader's modify() function.")}));const g=t.texture;zd(t,e,"texture",(function(...e){return r.active?this.getTexture(...e):g.apply(this,e)}));const y=t.noise,x=t.noiseDetail,v=t.random,b=t.randomGaussian,_=t.randomSeed,w=t.millis;r._noiseOctaves=null,r._noiseAmpFalloff=null,zd(t,e,"noiseDetail",(function(e,t=.5){if(!r.active)return x.apply(this,arguments);r._noiseOctaves=e,r._noiseAmpFalloff=t})),zd(t,e,"noise",(function(...i){if(!r.active)return y.apply(this,i);const n=r.backend.getNoiseShaderSnippet();r.vertexDeclarations.add(n),r.fragmentDeclarations.add(n),r.computeDeclarations.add(n);const s=i.flat().map((t=>e.strandsNode(t)));let a;3===s.length?a=[t.vec3(s[0],s[1],s[2])]:2===s.length?a=[t.vec3(s[0],s[1],0)]:1===s.length&&s[0].dimension<=3?a=3===s[0].dimension?s:2===s[0].dimension?[t.vec3(s[0],0)]:[t.vec3(s[0],0,0)]:e._friendlyError(`It looks like you've called noise() with ${i.length} arguments. It only supports 1D to 3D input.`);const o=null!==r._noiseOctaves?r._noiseOctaves:t._getNoiseOctaves(),h=null!==r._noiseAmpFalloff?r._noiseAmpFalloff:t._getNoiseAmpFalloff();a.push(o),a.push(h);const{id:u,dimension:l}=Ko(r,"noise",a,{overloads:[{params:[sn.float3,sn.int1,sn.float1],returnType:sn.float1}]});return Uo(u,l,r)})),r._randomSeed=null,zd(t,e,"randomSeed",(function(e){if(!r.active)return _.apply(this,arguments);r._randomSeed=e})),zd(t,e,"random",(function(...t){if(!r.active)return v.apply(this,t);const i=r.backend.getRandomVertexShaderSnippet(),n=r.backend.getRandomFragmentShaderSnippet();if(r.vertexDeclarations.add(i),r.fragmentDeclarations.add(n),r.backend.getRandomComputeShaderSnippet){const e=r.backend.getRandomComputeShaderSnippet();r.computeDeclarations.add(e)}let s;if(null!==r._randomSeed&&r._randomSeed.isStrandsNode)s=r._randomSeed;else{const e=r._randomSeed;s=Vd(r,"_p5_randomSeed",sn.float1,null!==e?()=>e:()=>performance.now())}const a=[s],o=[{params:[sn.float1],returnType:sn.float1}];if(0===t.length){const{id:e,dimension:t}=Ko(r,"random",a,{overloads:o});return Uo(e,t,r)}if(1===t.length){const i=Ko(r,"random",a,{overloads:o});return Uo(i.id,i.dimension,r).mult(e.strandsNode(t[0]))}if(2===t.length){const i=Ko(r,"random",a,{overloads:o}),n=Uo(i.id,i.dimension,r),s=e.strandsNode(t[0]),h=e.strandsNode(t[1]);return n.mult(h.sub(s)).add(s)}e._friendlyError(`It looks like you've called random() with ${t.length} arguments. In strands, random() supports 0, 1, or 2 numeric arguments.`)})),zd(t,e,"randomGaussian",(function(...e){if(!r.active)return b.apply(this,e);const t=e.length>=1?e[0]:0,i=e.length>=2?e[1]:1,n=this.max(this.random(),1e-6),s=this.random();return this.sqrt(this.log(n).mult(-2)).mult(this.cos(s.mult(2*Math.PI))).mult(i).add(t)})),zd(t,e,"millis",(function(...e){if(!r.active)return w.apply(this,e);const t=r.renderer?._pInst||r.p5?.instance;return Vd(r,"_p5_global_millis",sn.float1,(()=>t?t.millis():void 0))}));for(const i in sn){if(i===Qi||i===en||"sampler"===i)continue;const n=sn[i],s=[];let a;/^[ib]vec/.test(n.fnName)?(a=n.fnName.slice(0,2).toUpperCase()+n.fnName.slice(2).toLowerCase(),s.push(a.replace("Vec","Vector"))):(a=n.fnName.charAt(0).toUpperCase()+n.fnName.slice(1),"Sampler2D"===a?s.push("Texture"):/^vec/.test(n.fnName)&&s.push(a.replace("Vec","Vector"))),zd(t,e,`uniform${a}`,(function(e,t){const{id:i,dimension:s}=Go(r,n,e);return r.uniforms.push({name:e,typeInfo:n,defaultValue:t}),Uo(i,s,r)})),zd(t,e,`shared${a}`,(function(e){const{id:t,dimension:i}=Go(r,n,e);return r.sharedVariables||(r.sharedVariables=new Map),r.sharedVariables.set(e,{typeInfo:n,usedInVertex:!1,usedInFragment:!1}),Uo(t,i,r)})),zd(t,e,`varying${a}`,t[`shared${a}`]);for(const r of s)zd(t,e,`uniform${r}`,t[`uniform${a}`]),zd(t,e,`varying${r}`,t[`varying${a}`]),zd(t,e,`shared${r}`,t[`shared${a}`]);const o=t[n.fnName];zd(t,e,n.fnName,(function(...t){if(r.active){if(1===t.length&&t[0].dimension&&t[0].dimension===n.dimension){const{id:e,dimension:i}=Ko(r,r.backend.getTypeName(n.baseType,n.dimension),t,{overloads:[{params:[t[0].typeInfo()],returnType:n}]});return Uo(e,i,r)}{!(n.dimension>1&&1===t.length)||Array.isArray(t[0])||t[0]instanceof Vo&&t[0].dimension>1||n.baseType!==Yi&&n.baseType!==Zi&&n.baseType!==Ki||(t=Array(n.dimension).fill(t[0]));const{id:e,dimension:i}=Yo(r,n,t);return Uo(e,i,r)}}if(o)return o.apply(this,t);e._friendlyError(`It looks like you've called ${n.fnName} outside of a shader's modify() function.`)}))}t.uniformStorage=function(e,t){let i=null,n=null,s=t;"function"==typeof t&&(s=t(),s?._schema&&(n=t)),s?._schema?(i=s._schema,null===n&&(n=s)):s&&"object"==typeof s&&!s._isStorageBuffer?i=r.renderer?._inferStructSchema(s)??null:s?._isStorageBuffer&&(n=t);const{id:a,dimension:o}=Go(r,{baseType:"storage",dimension:1},e);r.uniforms.push({name:e,typeInfo:{baseType:"storage",dimension:1,schema:i},defaultValue:n});const h=Uo(a,o,r);return h._originalIdentifier=e,h._originalBaseType="storage",h._originalDimension=1,h._schema=i,h}}function $d(e,t){const r=[],i=e.dag;for(const n of t)if(on(n.type)){const t=an(n),{id:s,dimension:a}=qo(e,t,`${zi}${n.name}`,[]),o=Uo(s,a,e).withStructProperties(t.properties.map((e=>e.name)));for(let r=0;r{const a=i.dependsOn[o.id].slice();a[r]=s;const h=qo(e,t,`${zi}${n.name}`,a);o.id=h.id}))},set(a){const h=a?.isStrandsNode?a.dimension:Array.isArray(a)?a.length:1;h!==s.dataType.dimension&&1!==h&&Ao(s.dataType.dimension,h,`${n.name}.${s.name}`);const u=[...i.dependsOn[o.id]];let l;if(a?.isStrandsNode)l=a.id;else{l=Yo(e,s.dataType,a).id}u[r]=l;const c=qo(e,t,`${zi}${n.name}`,u);o.id=c.id}})}r.push(o)}else{if("sampler"===n.type.typeName)continue;if(!n.type.dataType)throw new Error(`Missing dataType for parameter ${n.name} of type ${n.type.typeName}`);const t=n.type.dataType,{id:i,dimension:s}=Go(e,t,`${zi}${n.name}`),a=Uo(i,s,e);r.push(a)}return r}function Hd(e,t,r,i){if(!r?.isStrandsNode){return Yo(e,t,r).id}const n=e.dag;let s=r.id;const a=n.baseTypes[s],o=n.dimensions[s];if(o!==t.dimension)if(1!==o){Eo("type error",`You have returned a ${a+(o>1?o:"")} in ${i} when a ${t.baseType+t.dimension} was expected!\n\nMake sure your hook returns the correct type.`)}else{s=Yo(e,t,r).id}else if(a!==t.baseType){s=Yo(e,t,r).id}return s}function qd(e,t,r){!function(e){if(e._builtinGlobalsAccessorsInstalled)return;const t=()=>e.renderer?._pInst||e.p5?.instance;for(const r of Object.keys(Rd)){const i=Rd[r],n=`_strands_${r}`,s=t();s?._isGlobal&&Object.defineProperty(window,r,{get:()=>{if(e.active)return Ud(e,r);const n=t();return i.get(n)},configurable:!0});const a=Object.getOwnPropertyDescriptor(e.p5.prototype,r);Object.defineProperty(e.p5.prototype,r,{get:function(){return e.active?Ud(e,r):Object.prototype.hasOwnProperty.call(this,n)?this[n]:a?.get?a.get.call(this):a?.value},set:function(e){this[n]=e},configurable:!0});const o=e.p5?.Graphics?.prototype;if(o){const t=Object.getOwnPropertyDescriptor(o,r);Object.defineProperty(o,r,{get:function(){return e.active?Ud(e,r):t?.get?t.get.call(this):this[n]},set:function(e){t?.set?t.set.call(this,e):this[n]=e},configurable:!0})}}e._builtinGlobalsAccessorsInstalled=!0}(e),function(e){if(e._instanceIndexAccessorInstalled)return;const t=function(){if(e.active){const t=Go(e,{baseType:Zi,dimension:1},e.backend.instanceIdReference());return Uo(t.id,t.dimension,e)}},r=e.renderer?._pInst||e.p5?.instance;r?._isGlobal&&Object.defineProperty(window,"instanceIndex",{get:t,configurable:!0}),Object.defineProperty(e.p5.prototype,"instanceIndex",{get:t,configurable:!0});const i=e.p5?.Graphics?.prototype;i&&Object.defineProperty(i,"instanceIndex",{get:t,configurable:!0}),e._instanceIndexAccessorInstalled=!0}(e);const i={...Object.fromEntries(Object.entries(r.hooks.vertex).map((([e,t])=>[e,{...t,shaderContext:"vertex"}]))),...Object.fromEntries(Object.entries(r.hooks.fragment).map((([e,t])=>[e,{...t,shaderContext:"fragment"}]))),...Object.fromEntries(Object.entries(r.hooks.compute).map((([e,t])=>[e,{...t,shaderContext:"compute"}])))},n=Object.keys(i).map((e=>r.hookTypes(e))),{cfg:s,dag:a}=e;for(const o of n){const h=function(e){const t=p();h._result=e(...t)??h._result,d()};h.set=function(e){h._result=e},h._active=!1;const u=o.parameters.filter((e=>e.type&&e.type.properties)).length;let l,c=-1;if(1===u&&(c=o.parameters.findIndex((e=>e.type&&e.type.properties))),c>=0){const g=o.parameters[c];if(g.type.properties){const y=/^get([A-Z0-9]\w*)$/.exec(o.name),x=y?y[1][0].toLowerCase()+y[1].slice(1):o.name;for(const v of g.type.properties){const b=v.name;Object.defineProperty(h,b,{get(){return this._active||Eo("scope error",`It looks like you're trying to access "${x}.${b}" outside of its begin()/end() block.\n\nProperties of ${x} are only available between ${x}.begin() and ${x}.end().\n\nTo share data between hooks, use sharedVec3() or sharedFloat() to pass values between them.`),this._args[this._argIdx][b]},set(e){this._active||Eo("scope error",`It looks like you're trying to set "${x}.${b}" outside of its begin()/end() block.`),this._args[this._argIdx][b]=e},enumerable:!0})}}}function p(){e.activeHook=h,l=Oo(s,xn.FUNCTION),Po(s,s.currentBlock,l),Io(s,l);const t=$d(e,o.parameters);h._active=!0,h._args=t,h._argIdx=c,h._properties=[];for(let e=0;e{if(on(r)){const i=an(r);if(t?.isStrandsNode){const r=Fo(e.dag,t.id);if(r.baseType!==i.typeName){const e=r.baseType||"undefined",n=a.dimensions[t.id],s=n>1?`${e}${n}`:e,h=i.properties.map((e=>e.name)).join(", ");Eo("type error",`You have returned a ${s} from ${o.name} when a ${i.typeName} was expected.\n\nThe ${i.typeName} struct has these properties: { ${h} }\n\nInstead of returning a different type, you should modify and return the ${i.typeName} struct that was passed to your hook.\n\nFor example:\n${o.name}((inputs) => {\n // Modify properties of inputs\n inputs.someProperty = ...;\n return inputs; // Return the modified struct\n})`)}const n=r.dependsOn.slice();for(let s=0;se.name)).join(", "),n=Object.keys(t).join(", ");Eo("type error",`You've returned an incomplete ${i.typeName} struct from ${o.name}.\n\nExpected properties: { ${e} }\nReceived properties: { ${n} }\n\nAll properties are required! Make sure to include all properties in the returned struct.`)}const l=h.dataType,c=Hd(e,l,u,o.name);s.push(c)}return Zo(e,i,s).id}}if(r.dataType&&"void"!==r.typeName?.trim()){const i=r.dataType;return Hd(e,i,t,o.name)}return null};for(const{valueNode:e,earlyReturnID:t}of h.earlyReturns){const r=u(e);a.dependsOn[t]=null!==r?[r]:[]}n=t?u(t):void 0;const c=`${o.returnType.typeName} ${o.name}`,p=i[c];e.hooks.push({hookType:o,entryBlockID:l,rootNodeID:n,shaderContext:p?.shaderContext}),Bo(s)}h.begin=p,h.end=d;const f=[o.name];e.baseShader?.hooks?.hookAliases?.[o.name]&&f.push(...e.baseShader.hooks.hookAliases[o.name]);const m=/^get([A-Z0-9]\w*)$/.exec(o.name);if(m){const _=m[1][0].toLowerCase()+m[1].slice(1);t[_]||f.push(_)}for(const w of f)jd(t,e,w,h);h.earlyReturns=[]}}function Wd(e,t){function r(t,r,{active:i=!1,renderer:n=null,baseShader:s=null}={}){t.dag=Do(),t.cfg={blockTypes:[],incomingEdges:[],outgoingEdges:[],blockInstructions:[],nextID:0,blockStack:[],blockOrder:[],blockConditions:{},currentBlock:-1},t.uniforms=[],t.vertexDeclarations=new Set,t.fragmentDeclarations=new Set,t.computeDeclarations=new Set,t.hooks=[],t.backend=r,t.active=i,t.renderer=n,t.baseShader=s,t.previousFES=e.disableFriendlyErrors,t.windowOverrides={},t.fnOverrides={},t.graphicsOverrides={},t._randomSeed=null,i&&(e.disableFriendlyErrors=!0),t.p5=e}t._runStrandsInGlobalMode=!1;const i={};r(i),Gd(e,t,i);const n=e.Shader.prototype.modify;e.Shader.prototype.modify=function(s,a={},o={}){const h={},u={},l={};try{if(s instanceof Function||"string"==typeof s){let c;if(r(i,this._renderer.strandsBackend,{active:!0,renderer:this._renderer,baseShader:this}),qd(i,t,this),o.parser=!0,o.srcLocations=!1,o.parser){const t="string"==typeof s?`(${s})`:`(${s.toString()})`;c=Ld(e,t,o.srcLocations,a)}else c=s;const p=Oo(i.cfg,xn.GLOBAL);if(Io(i.cfg,p),o.hook){i.renderer._pInst[o.hook].begin();for(const r of i.renderer._pInst[o.hook]._properties){const n=i.renderer._pInst[o.hook][r];h[r]=t[r],t[r]=n,u[r]=window[r],window[r]=n,l[r]=e.Graphics.prototype[r],e.Graphics.prototype[r]=n}}i.renderer?._pInst?._runStrandsInGlobalMode?function(e,r){if(e._isGlobal)return r();const i={};for(const r of Object.getOwnPropertyNames(t)){const n=Object.getOwnPropertyDescriptor(t,r);n&&!n.get&&"function"==typeof t[r]&&(i[r]=window[r],window[r]=t[r].bind(e))}try{r()}finally{for(const e in i)window[e]=i[e]}}(i.renderer._pInst,c):c(),o.hook&&i.renderer._pInst[o.hook].end(),Bo(i.cfg);const d=function(e){const{cfg:t,backend:r,vertexDeclarations:i,fragmentDeclarations:n,computeDeclarations:s}=e,a={uniforms:{},storageUniforms:{},varyingVariables:[]};for(const{name:t,typeInfo:i,defaultValue:n}of e.uniforms)if("storage"===i.baseType)null!=n&&(a.storageUniforms[t]=n);else{const e=r.generateHookUniformKey(t,i);null!==e&&(a.uniforms[e]=n)}r.addTextureBindingsToDeclarations&&r.addTextureBindingsToDeclarations(e),r.addStorageBufferBindingsToDeclarations&&r.addStorageBufferBindingsToDeclarations(e);for(const{hookType:i,rootNodeID:n,entryBlockID:s,shaderContext:o}of e.hooks){const h={indent:1,codeLines:[],write(e){this.codeLines.push(" ".repeat(this.indent)+e)},tempNames:{},declarations:[],nextTempID:0,visitedNodes:new Set,shaderContext:o,strandsContext:e},u=Ro(t.outgoingEdges,s);for(const t of u)r.generateBlock(t,e,h);const l=r.hookEntry(i);let c;c=i.returnType.properties?an(i.returnType):i.returnType.dataType&&"void"!==i.returnType.typeName?.trim()?i.returnType.dataType:null,void 0!==n&&r.generateReturnStatement(e,h,n,c),a[`${i.returnType.typeName} ${i.name}`]=[l,...h.codeLines,"}"].join("\n")}if(e.sharedVariables)for(const[t,s]of e.sharedVariables)s.usedInVertex&&s.usedInFragment?a.varyingVariables.push(r.generateVaryingVariable(t,s.typeInfo)):s.usedInVertex?i.add(r.generateLocalDeclaration(t,s.typeInfo)):s.usedInFragment&&n.add(r.generateLocalDeclaration(t,s.typeInfo));return e._instanceIDUsedInFragment&&(a.instanceIDVarying=r.generateInstanceIDVarying()),a.vertexDeclarations=[...i].join("\n"),a.fragmentDeclarations=[...n].join("\n"),a.computeDeclarations=[...s].join("\n"),a}(i);return n.call(this,d)}return n.call(this,s)}finally{for(const e in h)t[e]=h[e];for(const e in u)window[e]=u[e];for(const t in l)e.Graphics[t]=l[t];!function(r){r.dag=Do(),r.cfg={blockTypes:[],incomingEdges:[],outgoingEdges:[],blockInstructions:[],nextID:0,blockStack:[],blockOrder:[],blockConditions:{},currentBlock:-1},r.uniforms=[],r.vertexDeclarations=new Set,r.fragmentDeclarations=new Set,r.computeDeclarations=new Set,r.hooks=[],r.active=!1,r._randomSeed=null,e.disableFriendlyErrors=r.previousFES;for(const e in r.windowOverrides)window[e]=r.windowOverrides[e];for(const e in r.fnOverrides)t[e]=r.fnOverrides[e];const i=e.Graphics?.prototype;if(i)for(const e in r.graphicsOverrides)void 0===r.graphicsOverrides[e]?delete i[e]:i[e]=r.graphicsOverrides[e]}(i)}}}function Xd(e){return Xd="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Xd(e)}function Yd(e){var t=function(e,t){if("object"!=Xd(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t);if("object"!=Xd(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==Xd(t)?t:t+""}function Zd(e,t,r){return(t=Yd(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Kd(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{};Jd(this,e),this.init(t,r)}return ef(e,[{key:"init",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.prefix=t.prefix||"i18next:",this.logger=e||of,this.options=t,this.debug=t.debug}},{key:"setDebug",value:function(e){this.debug=e}},{key:"log",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r1?t-1:0),i=1;i-1?e.replace(/###/g,"."):e}function n(){return!e||"string"==typeof e}for(var s="string"!=typeof t?[].concat(t):t.split(".");s.length>1;){if(n())return{};var a=i(s.shift());!e[a]&&r&&(e[a]=new r),e=Object.prototype.hasOwnProperty.call(e,a)?e[a]:{}}return n()?{}:{obj:e,k:i(s.shift())}}function ff(e,t,r){var i=df(e,t,Object);i.obj[i.k]=r}function mf(e,t){var r=df(e,t),i=r.obj,n=r.k;if(i)return i[n]}function gf(e,t,r){var i=mf(e,r);return void 0!==i?i:mf(t,r)}function yf(e,t,r){for(var i in t)"__proto__"!==i&&"constructor"!==i&&(i in e?"string"==typeof e[i]||e[i]instanceof String||"string"==typeof t[i]||t[i]instanceof String?r&&(e[i]=t[i]):yf(e[i],t[i],r):e[i]=t[i]);return e}function xf(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}var vf={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};function bf(e){return"string"==typeof e?e.replace(/[&<>"'\/]/g,(function(e){return vf[e]})):e}var _f="undefined"!=typeof window&&window.navigator&&window.navigator.userAgent&&window.navigator.userAgent.indexOf("MSIE")>-1,wf=function(e){function t(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{ns:["translation"],defaultNS:"translation"};return Jd(this,t),r=rf(this,nf(t).call(this)),_f&&lf.call(tf(r)),r.data=e||{},r.options=i,void 0===r.options.keySeparator&&(r.options.keySeparator="."),r}return af(t,e),ef(t,[{key:"addNamespaces",value:function(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}},{key:"removeNamespaces",value:function(e){var t=this.options.ns.indexOf(e);t>-1&&this.options.ns.splice(t,1)}},{key:"getResource",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},n=void 0!==i.keySeparator?i.keySeparator:this.options.keySeparator,s=[e,t];return r&&"string"!=typeof r&&(s=s.concat(r)),r&&"string"==typeof r&&(s=s.concat(n?r.split(n):r)),e.indexOf(".")>-1&&(s=e.split(".")),mf(this.data,s)}},{key:"addResource",value:function(e,t,r,i){var n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{silent:!1},s=this.options.keySeparator;void 0===s&&(s=".");var a=[e,t];r&&(a=a.concat(s?r.split(s):r)),e.indexOf(".")>-1&&(i=t,t=(a=e.split("."))[1]),this.addNamespaces(t),ff(this.data,a,i),n.silent||this.emit("added",e,t,r,i)}},{key:"addResources",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{silent:!1};for(var n in r)"string"!=typeof r[n]&&"[object Array]"!==Object.prototype.toString.apply(r[n])||this.addResource(e,t,n,r[n],{silent:!0});i.silent||this.emit("added",e,t,r)}},{key:"addResourceBundle",value:function(e,t,r,i,n){var s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{silent:!1},a=[e,t];e.indexOf(".")>-1&&(i=r,r=t,t=(a=e.split("."))[1]),this.addNamespaces(t);var o=mf(this.data,a)||{};i?yf(o,r,n):o=Kd({},o,r),ff(this.data,a,o),s.silent||this.emit("added",e,t,r)}},{key:"removeResourceBundle",value:function(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit("removed",e,t)}},{key:"hasResourceBundle",value:function(e,t){return void 0!==this.getResource(e,t)}},{key:"getResourceBundle",value:function(e,t){return t||(t=this.options.defaultNS),"v1"===this.options.compatibilityAPI?Kd({},{},this.getResource(e,t)):this.getResource(e,t)}},{key:"getDataByLanguage",value:function(e){return this.data[e]}},{key:"toJSON",value:function(){return this.data}}]),t}(lf),Cf={processors:{},addPostProcessor:function(e){this.processors[e.name]=e},handle:function(e,t,r,i,n){var s=this;return e.forEach((function(e){s.processors[e]&&(t=s.processors[e].process(t,r,i,n))})),t}},Ef={},Af=function(e){function t(e){var r,i,n,s,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Jd(this,t),r=rf(this,nf(t).call(this)),_f&&lf.call(tf(r)),i=["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],n=e,s=tf(r),i.forEach((function(e){n[e]&&(s[e]=n[e])})),r.options=a,void 0===r.options.keySeparator&&(r.options.keySeparator="."),r.logger=uf.create("translator"),r}return af(t,e),ef(t,[{key:"changeLanguage",value:function(e){e&&(this.language=e)}},{key:"exists",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{interpolation:{}},r=this.resolve(e,t);return r&&void 0!==r.res}},{key:"extractFromKey",value:function(e,t){var r=void 0!==t.nsSeparator?t.nsSeparator:this.options.nsSeparator;void 0===r&&(r=":");var i=void 0!==t.keySeparator?t.keySeparator:this.options.keySeparator,n=t.ns||this.options.defaultNS;if(r&&e.indexOf(r)>-1){var s=e.match(this.interpolator.nestingRegexp);if(s&&s.length>0)return{key:e,namespaces:n};var a=e.split(r);(r!==i||r===i&&this.options.ns.indexOf(a[0])>-1)&&(n=a.shift()),e=a.join(i)}return"string"==typeof n&&(n=[n]),{key:e,namespaces:n}}},{key:"translate",value:function(e,r,i){var n=this;if("object"!==Xd(r)&&this.options.overloadTranslationOptionHandler&&(r=this.options.overloadTranslationOptionHandler(arguments)),r||(r={}),null==e)return"";Array.isArray(e)||(e=[String(e)]);var s=void 0!==r.keySeparator?r.keySeparator:this.options.keySeparator,a=this.extractFromKey(e[e.length-1],r),o=a.key,h=a.namespaces,u=h[h.length-1],l=r.lng||this.language,c=r.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(l&&"cimode"===l.toLowerCase()){if(c){var p=r.nsSeparator||this.options.nsSeparator;return u+p+o}return o}var d=this.resolve(e,r),f=d&&d.res,m=d&&d.usedKey||o,g=d&&d.exactUsedKey||o,y=Object.prototype.toString.apply(f),x=void 0!==r.joinArrays?r.joinArrays:this.options.joinArrays,v=!this.i18nFormat||this.i18nFormat.handleAsObject;if(v&&f&&("string"!=typeof f&&"boolean"!=typeof f&&"number"!=typeof f)&&["[object Number]","[object Function]","[object RegExp]"].indexOf(y)<0&&("string"!=typeof x||"[object Array]"!==y)){if(!r.returnObjects&&!this.options.returnObjects)return this.logger.warn("accessing an object - but returnObjects options is not enabled!"),this.options.returnedObjectHandler?this.options.returnedObjectHandler(m,f,r):"key '".concat(o," (").concat(this.language,")' returned an object instead of string.");if(s){var b="[object Array]"===y,_=b?[]:{},w=b?g:m;for(var C in f)if(Object.prototype.hasOwnProperty.call(f,C)){var E="".concat(w).concat(s).concat(C);_[C]=this.translate(E,Kd({},r,{joinArrays:!1,ns:h})),_[C]===E&&(_[C]=f[C])}f=_}}else if(v&&"string"==typeof x&&"[object Array]"===y)(f=f.join(x))&&(f=this.extendTranslation(f,e,r,i));else{var A=!1,D=!1,S=void 0!==r.count&&"string"!=typeof r.count,T=t.hasDefaultValue(r),F=S?this.pluralResolver.getSuffix(l,r.count):"",k=r["defaultValue".concat(F)]||r.defaultValue;!this.isValidLookup(f)&&T&&(A=!0,f=k),this.isValidLookup(f)||(D=!0,f=o);var M=T&&k!==f&&this.options.updateMissing;if(D||A||M){if(this.logger.log(M?"updateKey":"missingKey",l,u,o,M?k:f),s){var I=this.resolve(o,Kd({},r,{keySeparator:!1}));I&&I.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}var B=[],L=this.languageUtils.getFallbackCodes(this.options.fallbackLng,r.lng||this.language);if("fallback"===this.options.saveMissingTo&&L&&L[0])for(var O=0;O1&&void 0!==arguments[1]?arguments[1]:{};return"string"==typeof e&&(e=[e]),e.forEach((function(e){if(!a.isValidLookup(t)){var h=a.extractFromKey(e,o),u=h.key;r=u;var l=h.namespaces;a.options.fallbackNS&&(l=l.concat(a.options.fallbackNS));var c=void 0!==o.count&&"string"!=typeof o.count,p=void 0!==o.context&&"string"==typeof o.context&&""!==o.context,d=o.lngs?o.lngs:a.languageUtils.toResolveHierarchy(o.lng||a.language,o.fallbackLng);l.forEach((function(e){a.isValidLookup(t)||(s=e,!Ef["".concat(d[0],"-").concat(e)]&&a.utils&&a.utils.hasLoadedNamespace&&!a.utils.hasLoadedNamespace(s)&&(Ef["".concat(d[0],"-").concat(e)]=!0,a.logger.warn('key "'.concat(r,'" for languages "').concat(d.join(", "),'" won\'t get resolved as namespace "').concat(s,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),d.forEach((function(r){if(!a.isValidLookup(t)){n=r;var s,h,l=u,d=[l];if(a.i18nFormat&&a.i18nFormat.addLookupKeys)a.i18nFormat.addLookupKeys(d,u,r,e,o);else c&&(s=a.pluralResolver.getSuffix(r,o.count)),c&&p&&d.push(l+s),p&&d.push(l+="".concat(a.options.contextSeparator).concat(o.context)),c&&d.push(l+=s);for(;h=d.pop();)a.isValidLookup(t)||(i=h,t=a.getResource(r,e,h,o))}})))}))}})),{res:t,usedKey:r,exactUsedKey:i,usedLng:n,usedNS:s}}},{key:"isValidLookup",value:function(e){return!(void 0===e||!this.options.returnNull&&null===e||!this.options.returnEmptyString&&""===e)}},{key:"getResource",value:function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(e,t,r,i):this.resourceStore.getResource(e,t,r,i)}}],[{key:"hasDefaultValue",value:function(e){var t="defaultValue";for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&t===r.substring(0,12)&&void 0!==e[r])return!0;return!1}}]),t}(lf);function Df(e){return e.charAt(0).toUpperCase()+e.slice(1)}var Sf=function(){function e(t){Jd(this,e),this.options=t,this.whitelist=this.options.supportedLngs||!1,this.supportedLngs=this.options.supportedLngs||!1,this.logger=uf.create("languageUtils")}return ef(e,[{key:"getScriptPartFromCode",value:function(e){if(!e||e.indexOf("-")<0)return null;var t=e.split("-");return 2===t.length?null:(t.pop(),"x"===t[t.length-1].toLowerCase()?null:this.formatLanguageCode(t.join("-")))}},{key:"getLanguagePartFromCode",value:function(e){if(!e||e.indexOf("-")<0)return e;var t=e.split("-");return this.formatLanguageCode(t[0])}},{key:"formatLanguageCode",value:function(e){if("string"==typeof e&&e.indexOf("-")>-1){var t=["hans","hant","latn","cyrl","cans","mong","arab"],r=e.split("-");return this.options.lowerCaseLng?r=r.map((function(e){return e.toLowerCase()})):2===r.length?(r[0]=r[0].toLowerCase(),r[1]=r[1].toUpperCase(),t.indexOf(r[1].toLowerCase())>-1&&(r[1]=Df(r[1].toLowerCase()))):3===r.length&&(r[0]=r[0].toLowerCase(),2===r[1].length&&(r[1]=r[1].toUpperCase()),"sgn"!==r[0]&&2===r[2].length&&(r[2]=r[2].toUpperCase()),t.indexOf(r[1].toLowerCase())>-1&&(r[1]=Df(r[1].toLowerCase())),t.indexOf(r[2].toLowerCase())>-1&&(r[2]=Df(r[2].toLowerCase()))),r.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}},{key:"isWhitelisted",value:function(e){return this.logger.deprecate("languageUtils.isWhitelisted",'function "isWhitelisted" will be renamed to "isSupportedCode" in the next major - please make sure to rename it\'s usage asap.'),this.isSupportedCode(e)}},{key:"isSupportedCode",value:function(e){return("languageOnly"===this.options.load||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}},{key:"getBestMatchFromCodes",value:function(e){var t,r=this;return e?(e.forEach((function(e){if(!t){var i=r.formatLanguageCode(e);r.options.supportedLngs&&!r.isSupportedCode(i)||(t=i)}})),!t&&this.options.supportedLngs&&e.forEach((function(e){if(!t){var i=r.getLanguagePartFromCode(e);if(r.isSupportedCode(i))return t=i;t=r.options.supportedLngs.find((function(e){if(0===e.indexOf(i))return e}))}})),t||(t=this.getFallbackCodes(this.options.fallbackLng)[0]),t):null}},{key:"getFallbackCodes",value:function(e,t){if(!e)return[];if("function"==typeof e&&(e=e(t)),"string"==typeof e&&(e=[e]),"[object Array]"===Object.prototype.toString.apply(e))return e;if(!t)return e.default||[];var r=e[t];return r||(r=e[this.getScriptPartFromCode(t)]),r||(r=e[this.formatLanguageCode(t)]),r||(r=e[this.getLanguagePartFromCode(t)]),r||(r=e.default),r||[]}},{key:"toResolveHierarchy",value:function(e,t){var r=this,i=this.getFallbackCodes(t||this.options.fallbackLng||[],e),n=[],s=function(e){e&&(r.isSupportedCode(e)?n.push(e):r.logger.warn("rejecting language code not found in supportedLngs: ".concat(e)))};return"string"==typeof e&&e.indexOf("-")>-1?("languageOnly"!==this.options.load&&s(this.formatLanguageCode(e)),"languageOnly"!==this.options.load&&"currentOnly"!==this.options.load&&s(this.getScriptPartFromCode(e)),"currentOnly"!==this.options.load&&s(this.getLanguagePartFromCode(e))):"string"==typeof e&&s(this.formatLanguageCode(e)),i.forEach((function(e){n.indexOf(e)<0&&s(r.formatLanguageCode(e))})),n}}]),e}(),Tf=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","kk","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],Ff={1:function(e){return Number(e>1)},2:function(e){return Number(1!=e)},3:function(e){return 0},4:function(e){return Number(e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2)},5:function(e){return Number(0==e?0:1==e?1:2==e?2:e%100>=3&&e%100<=10?3:e%100>=11?4:5)},6:function(e){return Number(1==e?0:e>=2&&e<=4?1:2)},7:function(e){return Number(1==e?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2)},8:function(e){return Number(1==e?0:2==e?1:8!=e&&11!=e?2:3)},9:function(e){return Number(e>=2)},10:function(e){return Number(1==e?0:2==e?1:e<7?2:e<11?3:4)},11:function(e){return Number(1==e||11==e?0:2==e||12==e?1:e>2&&e<20?2:3)},12:function(e){return Number(e%10!=1||e%100==11)},13:function(e){return Number(0!==e)},14:function(e){return Number(1==e?0:2==e?1:3==e?2:3)},15:function(e){return Number(e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2)},16:function(e){return Number(e%10==1&&e%100!=11?0:0!==e?1:2)},17:function(e){return Number(1==e||e%10==1&&e%100!=11?0:1)},18:function(e){return Number(0==e?0:1==e?1:2)},19:function(e){return Number(1==e?0:0==e||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3)},20:function(e){return Number(1==e?0:0==e||e%100>0&&e%100<20?1:2)},21:function(e){return Number(e%100==1?1:e%100==2?2:e%100==3||e%100==4?3:0)},22:function(e){return Number(1==e?0:2==e?1:(e<0||e>10)&&e%10==0?2:3)}};var kf=function(){function e(t){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Jd(this,e),this.languageUtils=t,this.options=i,this.logger=uf.create("pluralResolver"),this.rules=(r={},Tf.forEach((function(e){e.lngs.forEach((function(t){r[t]={numbers:e.nr,plurals:Ff[e.fc]}}))})),r)}return ef(e,[{key:"addRule",value:function(e,t){this.rules[e]=t}},{key:"getRule",value:function(e){return this.rules[e]||this.rules[this.languageUtils.getLanguagePartFromCode(e)]}},{key:"needsPlural",value:function(e){var t=this.getRule(e);return t&&t.numbers.length>1}},{key:"getPluralFormsOfKey",value:function(e,t){return this.getSuffixes(e).map((function(e){return t+e}))}},{key:"getSuffixes",value:function(e){var t=this,r=this.getRule(e);return r?r.numbers.map((function(r){return t.getSuffix(e,r)})):[]}},{key:"getSuffix",value:function(e,t){var r=this,i=this.getRule(e);if(i){var n=i.noAbs?i.plurals(t):i.plurals(Math.abs(t)),s=i.numbers[n];this.options.simplifyPluralSuffix&&2===i.numbers.length&&1===i.numbers[0]&&(2===s?s="plural":1===s&&(s=""));var a=function(){return r.options.prepend&&s.toString()?r.options.prepend+s.toString():s.toString()};return"v1"===this.options.compatibilityJSON?1===s?"":"number"==typeof s?"_plural_".concat(s.toString()):a():"v2"===this.options.compatibilityJSON||this.options.simplifyPluralSuffix&&2===i.numbers.length&&1===i.numbers[0]?a():this.options.prepend&&n.toString()?this.options.prepend+n.toString():n.toString()}return this.logger.warn("no plural rule found for: ".concat(e)),""}}]),e}(),Mf=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Jd(this,e),this.logger=uf.create("interpolator"),this.options=t,this.format=t.interpolation&&t.interpolation.format||function(e){return e},this.init(t)}return ef(e,[{key:"init",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e.interpolation||(e.interpolation={escapeValue:!0});var t=e.interpolation;this.escape=void 0!==t.escape?t.escape:bf,this.escapeValue=void 0===t.escapeValue||t.escapeValue,this.useRawValueToEscape=void 0!==t.useRawValueToEscape&&t.useRawValueToEscape,this.prefix=t.prefix?xf(t.prefix):t.prefixEscaped||"{{",this.suffix=t.suffix?xf(t.suffix):t.suffixEscaped||"}}",this.formatSeparator=t.formatSeparator?t.formatSeparator:t.formatSeparator||",",this.unescapePrefix=t.unescapeSuffix?"":t.unescapePrefix||"-",this.unescapeSuffix=this.unescapePrefix?"":t.unescapeSuffix||"",this.nestingPrefix=t.nestingPrefix?xf(t.nestingPrefix):t.nestingPrefixEscaped||xf("$t("),this.nestingSuffix=t.nestingSuffix?xf(t.nestingSuffix):t.nestingSuffixEscaped||xf(")"),this.nestingOptionsSeparator=t.nestingOptionsSeparator?t.nestingOptionsSeparator:t.nestingOptionsSeparator||",",this.maxReplaces=t.maxReplaces?t.maxReplaces:1e3,this.alwaysFormat=void 0!==t.alwaysFormat&&t.alwaysFormat,this.resetRegExp()}},{key:"reset",value:function(){this.options&&this.init(this.options)}},{key:"resetRegExp",value:function(){var e="".concat(this.prefix,"(.+?)").concat(this.suffix);this.regexp=new RegExp(e,"g");var t="".concat(this.prefix).concat(this.unescapePrefix,"(.+?)").concat(this.unescapeSuffix).concat(this.suffix);this.regexpUnescape=new RegExp(t,"g");var r="".concat(this.nestingPrefix,"(.+?)").concat(this.nestingSuffix);this.nestingRegexp=new RegExp(r,"g")}},{key:"interpolate",value:function(e,t,r,i){var n,s,a,o=this,h=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{};function u(e){return e.replace(/\$/g,"$$$$")}var l=function(e){if(e.indexOf(o.formatSeparator)<0){var n=gf(t,h,e);return o.alwaysFormat?o.format(n,void 0,r):n}var s=e.split(o.formatSeparator),a=s.shift().trim(),u=s.join(o.formatSeparator).trim();return o.format(gf(t,h,a),u,r,i)};this.resetRegExp();var c=i&&i.missingInterpolationHandler||this.options.missingInterpolationHandler,p=i&&i.interpolation&&i.interpolation.skipOnVariables||this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:function(e){return u(e)}},{regex:this.regexp,safeValue:function(e){return o.escapeValue?u(o.escape(e)):u(e)}}].forEach((function(t){for(a=0;n=t.regex.exec(e);){if(void 0===(s=l(n[1].trim())))if("function"==typeof c){var r=c(e,n,i);s="string"==typeof r?r:""}else{if(p){s=n[0];continue}o.logger.warn("missed to pass in variable ".concat(n[1]," for interpolating ").concat(e)),s=""}else"string"==typeof s||o.useRawValueToEscape||(s=pf(s));if(e=e.replace(n[0],t.safeValue(s)),t.regex.lastIndex=0,++a>=o.maxReplaces)break}})),e}},{key:"nest",value:function(e,t){var r,i,n=this,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=Kd({},s);function o(e,t){var r=this.nestingOptionsSeparator;if(e.indexOf(r)<0)return e;var i=e.split(new RegExp("".concat(r,"[ ]*{"))),n="{".concat(i[1]);e=i[0],n=(n=this.interpolate(n,a)).replace(/'/g,'"');try{a=JSON.parse(n),t&&(a=Kd({},t,a))}catch(t){return this.logger.warn("failed parsing options string in nesting for key ".concat(e),t),"".concat(e).concat(r).concat(n)}return delete a.defaultValue,e}for(a.applyPostProcessor=!1,delete a.defaultValue;r=this.nestingRegexp.exec(e);){var h=[],u=!1;if(r[0].includes(this.formatSeparator)&&!/{.*}/.test(r[1])){var l=r[1].split(this.formatSeparator).map((function(e){return e.trim()}));r[1]=l.shift(),h=l,u=!0}if((i=t(o.call(this,r[1].trim(),a),a))&&r[0]===e&&"string"!=typeof i)return i;"string"!=typeof i&&(i=pf(i)),i||(this.logger.warn("missed to resolve ".concat(r[1]," for nesting ").concat(e)),i=""),u&&(i=h.reduce((function(e,t){return n.format(e,t,s.lng,s)}),i.trim())),e=e.replace(r[0],i),this.regexp.lastIndex=0}return e}}]),e}();var If=function(e){function t(e,r,i){var n,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return Jd(this,t),n=rf(this,nf(t).call(this)),_f&&lf.call(tf(n)),n.backend=e,n.store=r,n.services=i,n.languageUtils=i.languageUtils,n.options=s,n.logger=uf.create("backendConnector"),n.state={},n.queue=[],n.backend&&n.backend.init&&n.backend.init(i,s.backend,s),n}return af(t,e),ef(t,[{key:"queueLoad",value:function(e,t,r,i){var n=this,s=[],a=[],o=[],h=[];return e.forEach((function(e){var i=!0;t.forEach((function(t){var o="".concat(e,"|").concat(t);!r.reload&&n.store.hasResourceBundle(e,t)?n.state[o]=2:n.state[o]<0||(1===n.state[o]?a.indexOf(o)<0&&a.push(o):(n.state[o]=1,i=!1,a.indexOf(o)<0&&a.push(o),s.indexOf(o)<0&&s.push(o),h.indexOf(t)<0&&h.push(t)))})),i||o.push(e)})),(s.length||a.length)&&this.queue.push({pending:a,loaded:{},errors:[],callback:i}),{toLoad:s,pending:a,toLoadLanguages:o,toLoadNamespaces:h}}},{key:"loaded",value:function(e,t,r){var i=e.split("|"),n=i[0],s=i[1];t&&this.emit("failedLoading",n,s,t),r&&this.store.addResourceBundle(n,s,r),this.state[e]=t?-1:2;var a={};this.queue.forEach((function(r){!function(e,t,r){var i=df(e,t,Object),n=i.obj,s=i.k;n[s]=n[s]||[],n[s].push(r)}(r.loaded,[n],s),function(e,t){for(var r=e.indexOf(t);-1!==r;)e.splice(r,1),r=e.indexOf(t)}(r.pending,e),t&&r.errors.push(t),0!==r.pending.length||r.done||(Object.keys(r.loaded).forEach((function(e){a[e]||(a[e]=[]),r.loaded[e].length&&r.loaded[e].forEach((function(t){a[e].indexOf(t)<0&&a[e].push(t)}))})),r.done=!0,r.errors.length?r.callback(r.errors):r.callback())})),this.emit("loaded",a),this.queue=this.queue.filter((function(e){return!e.done}))}},{key:"read",value:function(e,t,r){var i=this,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:350,a=arguments.length>5?arguments[5]:void 0;return e.length?this.backend[r](e,t,(function(o,h){o&&h&&n<5?setTimeout((function(){i.read.call(i,e,t,r,n+1,2*s,a)}),s):a(o,h)})):a(null,{})}},{key:"prepareLoading",value:function(e,t){var r=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),n&&n();"string"==typeof e&&(e=this.languageUtils.toResolveHierarchy(e)),"string"==typeof t&&(t=[t]);var s=this.queueLoad(e,t,i,n);if(!s.toLoad.length)return s.pending.length||n(),null;s.toLoad.forEach((function(e){r.loadOne(e)}))}},{key:"load",value:function(e,t,r){this.prepareLoading(e,t,{},r)}},{key:"reload",value:function(e,t,r){this.prepareLoading(e,t,{reload:!0},r)}},{key:"loadOne",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",i=e.split("|"),n=i[0],s=i[1];this.read(n,s,"read",void 0,void 0,(function(i,a){i&&t.logger.warn("".concat(r,"loading namespace ").concat(s," for language ").concat(n," failed"),i),!i&&a&&t.logger.log("".concat(r,"loaded namespace ").concat(s," for language ").concat(n),a),t.loaded(e,i,a)}))}},{key:"saveMissing",value:function(e,t,r,i,n){var s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(t)?this.logger.warn('did not save key "'.concat(r,'" as the namespace "').concat(t,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!"):null!=r&&""!==r&&(this.backend&&this.backend.create&&this.backend.create(e,t,r,i,null,Kd({},s,{isUpdate:n})),e&&e[0]&&this.store.addResource(e[0],t,r,i))}}]),t}(lf);function Bf(e){return"string"==typeof e.ns&&(e.ns=[e.ns]),"string"==typeof e.fallbackLng&&(e.fallbackLng=[e.fallbackLng]),"string"==typeof e.fallbackNS&&(e.fallbackNS=[e.fallbackNS]),e.whitelist&&(e.whitelist&&e.whitelist.indexOf("cimode")<0&&(e.whitelist=e.whitelist.concat(["cimode"])),e.supportedLngs=e.whitelist),e.nonExplicitWhitelist&&(e.nonExplicitSupportedLngs=e.nonExplicitWhitelist),e.supportedLngs&&e.supportedLngs.indexOf("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),e}function Lf(){}var Of=function(e){function t(){var e,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=arguments.length>1?arguments[1]:void 0;if(Jd(this,t),e=rf(this,nf(t).call(this)),_f&&lf.call(tf(e)),e.options=Bf(r),e.services={},e.logger=uf,e.modules={external:[]},i&&!e.isInitialized&&!r.isClone){if(!e.options.initImmediate)return e.init(r,i),rf(e,tf(e));setTimeout((function(){e.init(r,i)}),0)}return e}return af(t,e),ef(t,[{key:"init",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;function i(e){return e?"function"==typeof e?new e:e:null}if("function"==typeof t&&(r=t,t={}),t.whitelist&&!t.supportedLngs&&this.logger.deprecate("whitelist",'option "whitelist" will be renamed to "supportedLngs" in the next major - please make sure to rename this option asap.'),t.nonExplicitWhitelist&&!t.nonExplicitSupportedLngs&&this.logger.deprecate("whitelist",'options "nonExplicitWhitelist" will be renamed to "nonExplicitSupportedLngs" in the next major - please make sure to rename this option asap.'),this.options=Kd({},{debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,whitelist:!1,nonExplicitWhitelist:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!0,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:function(e){var t={};if("object"===Xd(e[1])&&(t=e[1]),"string"==typeof e[1]&&(t.defaultValue=e[1]),"string"==typeof e[2]&&(t.tDescription=e[2]),"object"===Xd(e[2])||"object"===Xd(e[3])){var r=e[3]||e[2];Object.keys(r).forEach((function(e){t[e]=r[e]}))}return t},interpolation:{escapeValue:!0,format:function(e,t,r,i){return e},prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!1}},this.options,Bf(t)),this.format=this.options.interpolation.format,r||(r=Lf),!this.options.isClone){this.modules.logger?uf.init(i(this.modules.logger),this.options):uf.init(null,this.options);var n=new Sf(this.options);this.store=new wf(this.options.resources,this.options);var s=this.services;s.logger=uf,s.resourceStore=this.store,s.languageUtils=n,s.pluralResolver=new kf(n,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),s.interpolator=new Mf(this.options),s.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},s.backendConnector=new If(i(this.modules.backend),s.resourceStore,s,this.options),s.backendConnector.on("*",(function(t){for(var r=arguments.length,i=new Array(r>1?r-1:0),n=1;n1?r-1:0),n=1;n0&&"dev"!==a[0]&&(this.options.lng=a[0])}this.services.languageDetector||this.options.lng||this.logger.warn("init: no languageDetector is used and no lng is defined");["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach((function(t){e[t]=function(){var r;return(r=e.store)[t].apply(r,arguments)}}));["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach((function(t){e[t]=function(){var r;return(r=e.store)[t].apply(r,arguments),e}}));var o=cf(),h=function(){var t=function(t,i){e.isInitialized&&e.logger.warn("init: i18next is already initialized. You should call init just once!"),e.isInitialized=!0,e.options.isClone||e.logger.log("initialized",e.options),e.emit("initialized",e.options),o.resolve(i),r(t,i)};if(e.languages&&"v1"!==e.options.compatibilityAPI&&!e.isInitialized)return t(null,e.t.bind(e));e.changeLanguage(e.options.lng,t)};return this.options.resources||!this.options.initImmediate?h():setTimeout(h,0),o}},{key:"loadResources",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Lf,i="string"==typeof e?e:this.language;if("function"==typeof e&&(r=e),!this.options.resources||this.options.partialBundledLanguages){if(i&&"cimode"===i.toLowerCase())return r();var n=[],s=function(e){e&&t.services.languageUtils.toResolveHierarchy(e).forEach((function(e){n.indexOf(e)<0&&n.push(e)}))};if(i)s(i);else this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach((function(e){return s(e)}));this.options.preload&&this.options.preload.forEach((function(e){return s(e)})),this.services.backendConnector.load(n,this.options.ns,r)}else r(null)}},{key:"reloadResources",value:function(e,t,r){var i=cf();return e||(e=this.languages),t||(t=this.options.ns),r||(r=Lf),this.services.backendConnector.reload(e,t,(function(e){i.resolve(),r(e)})),i}},{key:"use",value:function(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return"backend"===e.type&&(this.modules.backend=e),("logger"===e.type||e.log&&e.warn&&e.error)&&(this.modules.logger=e),"languageDetector"===e.type&&(this.modules.languageDetector=e),"i18nFormat"===e.type&&(this.modules.i18nFormat=e),"postProcessor"===e.type&&Cf.addPostProcessor(e),"3rdParty"===e.type&&this.modules.external.push(e),this}},{key:"changeLanguage",value:function(e,t){var r=this;this.isLanguageChangingTo=e;var i=cf();this.emit("languageChanging",e);var n=function(e){var n="string"==typeof e?e:r.services.languageUtils.getBestMatchFromCodes(e);n&&(r.language||(r.language=n,r.languages=r.services.languageUtils.toResolveHierarchy(n)),r.translator.language||r.translator.changeLanguage(n),r.services.languageDetector&&r.services.languageDetector.cacheUserLanguage(n)),r.loadResources(n,(function(e){!function(e,n){n?(r.language=n,r.languages=r.services.languageUtils.toResolveHierarchy(n),r.translator.changeLanguage(n),r.isLanguageChangingTo=void 0,r.emit("languageChanged",n),r.logger.log("languageChanged",n)):r.isLanguageChangingTo=void 0,i.resolve((function(){return r.t.apply(r,arguments)})),t&&t(e,(function(){return r.t.apply(r,arguments)}))}(e,n)}))};return e||!this.services.languageDetector||this.services.languageDetector.async?!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect(n):n(e):n(this.services.languageDetector.detect()),i}},{key:"getFixedT",value:function(e,t){var r=this,i=function e(t,i){var n;if("object"!==Xd(i)){for(var s=arguments.length,a=new Array(s>2?s-2:0),o=2;o1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;var i=this.languages[0],n=!!this.options&&this.options.fallbackLng,s=this.languages[this.languages.length-1];if("cimode"===i.toLowerCase())return!0;var a=function(e,r){var i=t.services.backendConnector.state["".concat(e,"|").concat(r)];return-1===i||2===i};if(r.precheck){var o=r.precheck(this,a);if(void 0!==o)return o}return!!this.hasResourceBundle(i,e)||(!this.services.backendConnector.backend||!(!a(i,e)||n&&!a(s,e)))}},{key:"loadNamespaces",value:function(e,t){var r=this,i=cf();return this.options.ns?("string"==typeof e&&(e=[e]),e.forEach((function(e){r.options.ns.indexOf(e)<0&&r.options.ns.push(e)})),this.loadResources((function(e){i.resolve(),t&&t(e)})),i):(t&&t(),Promise.resolve())}},{key:"loadLanguages",value:function(e,t){var r=cf();"string"==typeof e&&(e=[e]);var i=this.options.preload||[],n=e.filter((function(e){return i.indexOf(e)<0}));return n.length?(this.options.preload=i.concat(n),this.loadResources((function(e){r.resolve(),t&&t(e)})),r):(t&&t(),Promise.resolve())}},{key:"dir",value:function(e){if(e||(e=this.languages&&this.languages.length>0?this.languages[0]:this.language),!e)return"rtl";return["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam"].indexOf(this.services.languageUtils.getLanguagePartFromCode(e))>=0?"rtl":"ltr"}},{key:"createInstance",value:function(){return new t(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1?arguments[1]:void 0)}},{key:"cloneInstance",value:function(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Lf,n=Kd({},this.options,r,{isClone:!0}),s=new t(n);return["store","services","language"].forEach((function(t){s[t]=e[t]})),s.services=Kd({},this.services),s.services.utils={hasLoadedNamespace:s.hasLoadedNamespace.bind(s)},s.translator=new Af(s.services,s.options),s.translator.on("*",(function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i4&&void 0!==arguments[4]?arguments[4]:{path:"/"};if(r){var a=new Date;a.setTime(a.getTime()+60*r*1e3),n="; expires="+a.toUTCString()}else n="";i=i?"domain="+i+";":"",s=Object.keys(s).reduce((function(e,t){return e+";"+t.replace(/([A-Z])/g,(function(e){return"-"+e.toLowerCase()}))+"="+s[t]}),""),document.cookie=e+"="+encodeURIComponent(t)+n+";"+i+s},zf=function(e){for(var t=e+"=",r=document.cookie.split(";"),i=0;i0)r[i].substring(0,n)===e.lookupQuerystring&&(t=r[i].substring(n+1))}return t}};try{Vf="undefined"!==window&&null!==window.localStorage;var $f="i18next.translate.boo";window.localStorage.setItem($f,"foo"),window.localStorage.removeItem($f)}catch(e){Vf=!1}var Hf,qf={name:"localStorage",lookup:function(e){var t;if(e.lookupLocalStorage&&Vf){var r=window.localStorage.getItem(e.lookupLocalStorage);r&&(t=r)}return t},cacheUserLanguage:function(e,t){t.lookupLocalStorage&&Vf&&window.localStorage.setItem(t.lookupLocalStorage,e)}};try{Hf="undefined"!==window&&null!==window.sessionStorage;var Wf="i18next.translate.boo";window.sessionStorage.setItem(Wf,"foo"),window.sessionStorage.removeItem(Wf)}catch(e){Hf=!1}var Xf={name:"sessionStorage",lookup:function(e){var t;if(e.lookupsessionStorage&&Hf){var r=window.sessionStorage.getItem(e.lookupsessionStorage);r&&(t=r)}return t},cacheUserLanguage:function(e,t){t.lookupsessionStorage&&Hf&&window.sessionStorage.setItem(t.lookupsessionStorage,e)}},Yf={name:"navigator",lookup:function(e){var t=[];if("undefined"!=typeof navigator){if(navigator.languages)for(var r=0;r0?t:void 0}},Zf={name:"htmlTag",lookup:function(e){var t,r=e.htmlTag||("undefined"!=typeof document?document.documentElement:null);return r&&"function"==typeof r.getAttribute&&(t=r.getAttribute("lang")),t}},Kf={name:"path",lookup:function(e){var t;if("undefined"!=typeof window){var r=window.location.pathname.match(/\/([a-zA-Z-]*)/g);if(r instanceof Array)if("number"==typeof e.lookupFromPathIndex){if("string"!=typeof r[e.lookupFromPathIndex])return;t=r[e.lookupFromPathIndex].replace("/","")}else t=r[0].replace("/","")}return t}},Jf={name:"subdomain",lookup:function(e){var t;if("undefined"!=typeof window){var r=window.location.href.match(/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/gi);r instanceof Array&&(t="number"==typeof e.lookupFromSubdomainIndex?r[e.lookupFromSubdomainIndex].replace("http://","").replace("https://","").replace(".",""):r[0].replace("http://","").replace("https://","").replace(".",""))}return t}};var Qf=function(){function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Jd(this,e),this.type="languageDetector",this.detectors={},this.init(t,r)}return ef(e,[{key:"init",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.services=e,this.options=function(e){return Nf.call(Rf.call(arguments,1),(function(t){if(t)for(var r in t)void 0===e[r]&&(e[r]=t[r])})),e}(t,this.options||{},{order:["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"],lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],checkWhitelist:!0,checkForSimilarInWhitelist:!1}),this.options.checkForSimilarInWhitelist&&(this.options.checkWhitelist=!0),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=r,this.addDetector(jf),this.addDetector(Gf),this.addDetector(qf),this.addDetector(Xf),this.addDetector(Yf),this.addDetector(Zf),this.addDetector(Kf),this.addDetector(Jf)}},{key:"addDetector",value:function(e){this.detectors[e.name]=e}},{key:"detect",value:function(e){var t=this;e||(e=this.options.order);var r,i=[];if(e.forEach((function(e){if(t.detectors[e]){var r=t.detectors[e].lookup(t.options);r&&"string"==typeof r&&(r=[r]),r&&(i=i.concat(r))}})),i.forEach((function(e){if(!r){var i=t.services.languageUtils.formatLanguageCode(e);t.options.checkWhitelist&&!t.services.languageUtils.isWhitelisted(i)||(r=i),!r&&t.options.checkForSimilarInWhitelist&&(r=t.getSimilarInWhitelist(i))}})),!r){var n=this.i18nOptions.fallbackLng;"string"==typeof n&&(n=[n]),n||(n=[]),r="[object Array]"===Object.prototype.toString.apply(n)?n[0]:n[0]||n.default&&n.default[0]}return r}},{key:"cacheUserLanguage",value:function(e,t){var r=this;t||(t=this.options.caches),t&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||t.forEach((function(t){r.detectors[t]&&r.detectors[t].cacheUserLanguage(e,r.options)})))}},{key:"getSimilarInWhitelist",value:function(e){var t=this;if(this.i18nOptions.whitelist){if(e.includes("-")){var r=e.split("-")[0],i=this.services.languageUtils.formatLanguageCode(r);if(this.services.languageUtils.isWhitelisted(i))return i;e=i}var n=this.i18nOptions.whitelist.find((function(r){var i=t.services.languageUtils.formatLanguageCode(r);if(i.startsWith(e))return i}));return n||void 0}}}]),e}();Qf.type="languageDetector";var em={en:{translation:{fes:{autoplay:"The media that tried to play (with '{{src}}') wasn't allowed to by this browser, most likely due to the browser's autoplay policy.\n\n+ More info: {{url}}",checkUserDefinedFns:"It seems that you may have accidentally written {{name}} instead of {{actualName}}. Please correct it if it's not intentional.",fileLoadError:{bytes:"It looks like there was a problem loading your file. {{suggestion}}",font:"It looks like there was a problem loading your font. {{suggestion}}",gif:"There was some trouble loading your GIF. Make sure that your GIF is using 87a or 89a encoding.",image:"It looks like there was a problem loading your image. {{suggestion}}",json:"It looks like there was a problem loading your JSON file. {{suggestion}}",large:"If your large file isn't fetched successfully, we recommend splitting the file into smaller segments and fetching those.",strings:"It looks like there was a problem loading your text file. {{suggestion}}",suggestion:"Try checking if the file path ({{filePath}}) is correct, hosting the file online, or running a local server.\n\n+ More info: {{url}}",table:"It looks like there was a problem loading your table file. {{suggestion}}",xml:"It looks like there was a problem loading your XML file. {{suggestion}}"},friendlyParamError:{type_EMPTY_VAR:"{{location}} {{func}}() was expecting {{formatType}} for the {{position}} parameter, received an empty variable instead. If not intentional, this is often a problem with scope.\n\n+ More info: {{url}}",type_TOO_FEW_ARGUMENTS:"{{location}} {{func}}() was expecting at least {{minParams}} arguments, but received only {{argCount}}.",type_TOO_MANY_ARGUMENTS:"{{location}} {{func}}() was expecting no more than {{maxParams}} arguments, but received {{argCount}}.",type_WRONG_TYPE:"{{location}} {{func}}() was expecting {{formatType}} for the {{position}} parameter, received {{argType}} instead."},globalErrors:{reference:{cannotAccess:'\n{{location}} "{{symbol}}" is used before declaration. Make sure you have declared the variable before using it.\n\n+ More info: {{url}}',notDefined:'\n{{location}} "{{symbol}}" is not defined in the current scope. If you have defined it in your code, you should check its scope, spelling, and letter-casing (JavaScript is case-sensitive).\n\n+ More info: {{url}}'},stackSubseq:"└[{{location}}] \n\t Called from line {{line}} in {{func}}()\n",stackTop:"┌[{{location}}] \n\t Error at line {{line}} in {{func}}()\n",syntax:{badReturnOrYield:"\nSyntax Error - return lies outside of a function. Make sure you’re not missing any brackets, so that return lies inside a function.\n\n+ More info: {{url}}",invalidToken:"\nSyntax Error - Found a symbol that JavaScript doesn't recognize or didn't expect at it's place.\n\n+ More info: {{url}}",missingInitializer:"\nSyntax Error - A const variable is declared but not initialized. In JavaScript, an initializer for a const is required. A value must be specified in the same statement in which the variable is declared. Check the line number in the error and assign the const variable a value.\n\n+ More info: {{url}}",redeclaredVariable:'\nSyntax Error - "{{symbol}}" is being redeclared. JavaScript doesn\'t allow declaring a variable more than once. Check the line number in error for redeclaration of the variable.\n\n+ More info: {{url}}',unexpectedToken:"\nSyntax Error - Symbol present at a place that wasn't expected.\nUsually this is due to a typo. Check the line number in the error for anything missing/extra.\n\n+ More info: {{url}}"},type:{constAssign:"\n{{location}} A const variable is being re-assigned. In javascript, re-assigning a value to a constant is not allowed. If you want to re-assign new values to a variable, make sure it is declared as var or let.\n\n+ More info: {{url}}",notfunc:'\n{{location}} "{{symbol}}" could not be called as a function.\nCheck the spelling, letter-casing (JavaScript is case-sensitive) and its type.\n\n+ More info: {{url}}',notfuncObj:'\n{{location}} "{{symbol}}" could not be called as a function.\nVerify whether "{{obj}}" has "{{symbol}}" in it and check the spelling, letter-casing (JavaScript is case-sensitive) and its type.\n\n+ More info: {{url}}',readFromNull:"\n{{location}} The property of null can't be read. In javascript the value null indicates that an object has no value.\n\n+ More info: {{url}}",readFromUndefined:"\n{{location}} Cannot read property of undefined. Check the line number in error and make sure the variable which is being operated is not undefined.\n\n + More info: {{url}}"}},libraryError:'{{location}} An error with message "{{error}}" occurred inside the p5js library when {{func}} was called. If not stated otherwise, it might be an issue with the arguments passed to {{func}}.',location:"[{{file}}, line {{line}}]",misspelling:'{{location}} It seems that you may have accidentally written "{{name}}" instead of "{{actualName}}". Please correct it to {{actualName}} if you wish to use the {{type}} from p5.js.',misspelling_plural:'{{location}} It seems that you may have accidentally written "{{name}}".\nYou may have meant one of the following: \n{{suggestions}}',misusedTopLevel:"Did you just try to use p5.js's {{symbolName}} {{symbolType}}? If so, you may want to move it into your sketch's setup() function.\n\n+ More info: {{url}}",preloadDisabled:"The preload() function has been removed in p5.js 2.0. Please load assets in setup() using async / await keywords or callbacks instead. See https://github.com/processing/p5.js-compatibility for more information about 2.0 and compatibility, or https://dev.to/limzykenneth/asynchronous-p5js-20-458f for more information about promises and async/await.",positions:{p_1:"first",p_10:"tenth",p_11:"eleventh",p_12:"twelfth",p_2:"second",p_3:"third",p_4:"fourth",p_5:"fifth",p_6:"sixth",p_7:"seventh",p_8:"eighth",p_9:"ninth"},pre:"\n🌸 p5.js says: {{message}}",sketchReaderErrors:{reservedConst:'you have used a p5.js reserved variable "{{symbol}}" make sure you change the variable name to something else.\n\n+ More info: {{url}}',reservedFunc:'you have used a p5.js reserved function "{{symbol}}" make sure you change the function name to something else.\n\n+ More info: {{url}}'},welcome:"Welcome! This is your friendly debugger. To turn me off, switch to using p5.min.js.",wrongPreload:'{{location}} An error with message "{{error}}" occurred inside the p5js library when "{{func}}" was called. If not stated otherwise, it might be due to "{{func}}" being called from preload. Nothing besides load calls (loadImage, loadJSON, loadFont, loadStrings, etc.) should be inside the preload function.'}}}};const tm=["en","es","ko","zh","hi","ja"];class rm{constructor(e,t){this.init(e,t)}fetchWithTimeout(e,t,r=2e3){return Promise.race([fetch(e,t),new Promise(((e,t)=>setTimeout((()=>t(new Error("timeout"))),r)))])}init(e,t={}){this.services=e,this.options=t}read(e,t,r){const i=this.options.loadPath;if(e===this.options.fallback)r(null,em[e][t]);else if(tm.includes(e)){const n=this.services.interpolator.interpolate(i,{lng:e,ns:t});this.loadUrl(n,r)}else r("Not found",!1)}loadUrl(e,t){this.fetchWithTimeout(e).then((t=>{if(!t.ok)throw new Error(`failed loading ${e}`);return t.json()}),(()=>{throw new Error(`failed loading ${e}`)})).then((e=>t(null,e))).catch(t)}}rm.type="backend";const im=Promise.resolve();return function(e){e.registerAddon(bs),e.registerAddon(_s),e.registerAddon(ws),e.registerAddon(Cs),e.registerAddon(ls)}(hh),function(e){e.registerAddon(lh),e.registerAddon(ch),e.registerAddon(ph),e.registerAddon(dh),e.registerAddon(mh)}(hh),function(e){e.registerAddon(Ri),e.registerAddon(Si),e.registerAddon(Es)}(hh),function(e){e._friendlyError=()=>{},e._checkForUserDefinedFunctions=()=>{},e._fesErrorMonitor=()=>{}}(hh),function(e){e.registerAddon(gh)}(hh),function(e){e.registerAddon(yh),e.registerAddon(An),e.registerAddon(xs),e.registerAddon(Cn)}(hh),function(e){e.registerAddon(xh),e.registerAddon(vh),e.registerAddon(bh)}(hh),function(e){e.registerAddon(ks),e.registerAddon(ra),e.registerAddon(Ln),e.registerAddon(ia),e.registerAddon(Wa),e.registerAddon(to)}(hh),function(e){e.registerAddon(Ps),e.registerAddon(wh),e.registerAddon(Eh),e.registerAddon(_n)}(hh),function(e){e.registerAddon(Ah),e.registerAddon(Dh),e.registerAddon(Sh),e.registerAddon(Ka),e.registerAddon(Th),e.registerAddon(Rn),e.registerAddon(Mh)}(hh),function(e){e.registerAddon(Ih),e.registerAddon(Bh),e.registerAddon(Lh)}(hh),function(e){e.registerAddon(ja),e.registerAddon(Sl),e.registerAddon(Ga),e.registerAddon(Oh),e.registerAddon($a),e.registerAddon(Nh),e.registerAddon(Za),e.registerAddon(wl),e.registerAddon(wa),e.registerAddon(ga),e.registerAddon(ua),e.registerAddon(da),e.registerAddon(xa),e.registerAddon(go),e.registerAddon(ca),e.registerAddon(to)}(hh),function(e){e.registerAddon(Oa),e.registerAddon(bl)}(hh),hh.registerAddon(Wa),hh.registerAddon(Wd),Promise.all([(()=>{if("undefined"!=typeof document)return new Promise(((e,t)=>{"complete"===document.readyState?e():window.addEventListener("load",e,!1)}))})(),im]).then((()=>{if("undefined"!=typeof window)if(void 0===window._setupDone){if(!window.mocha){const e=new Event("p5Ready");window.dispatchEvent(e),(window.setup&&"function"==typeof window.setup||window.draw&&"function"==typeof window.draw)&&!hh.instance&&new hh}}else console.warn("p5.js seems to have been imported multiple times. Please remove the duplicate import")})),hh}(); diff --git a/server/__tests__/server.spec.ts b/server/__tests__/server.spec.ts new file mode 100644 index 0000000..70907d4 --- /dev/null +++ b/server/__tests__/server.spec.ts @@ -0,0 +1,138 @@ +// @vitest-environment node +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' + +import { afterEach, describe, expect, it } from 'vitest' +import * as Y from 'yjs' + +import { LoginLimiter, SessionManager, isSameOrigin, readCookie } from '../auth.ts' +import { Storage } from '../db.ts' +import { detectImageType } from '../images.ts' + +describe('SessionManager', () => { + const sessions = new SessionManager('secret', 'password', 30) + + it('签发的令牌可以通过校验', () => { + expect(sessions.verify(sessions.issue())).not.toBeNull() + }) + + it('拒绝被篡改或过期的令牌', () => { + const token = sessions.issue() + const [body, signature] = token.split('.') + expect(sessions.verify(`${body}x.${signature}`)).toBeNull() + expect(sessions.verify(`${body}.${signature}x`)).toBeNull() + expect(sessions.verify('garbage')).toBeNull() + expect(sessions.verify(sessions.issue(Date.now() - 31 * 86_400_000))).toBeNull() + }) + + it('修改口令后旧令牌失效', () => { + const token = sessions.issue() + expect(new SessionManager('secret', 'new-password', 30).verify(token)).toBeNull() + }) + + it('校验口令', () => { + expect(sessions.checkPassword('password')).toBe(true) + expect(sessions.checkPassword('Password')).toBe(false) + expect(sessions.checkPassword(undefined)).toBe(false) + }) + + it('有效期过半时提示续期', () => { + const now = Date.now() + expect(sessions.shouldRenew(sessions.verify(sessions.issue(now))!, now)).toBe(false) + const old = sessions.verify(sessions.issue(now - 20 * 86_400_000), now)! + expect(sessions.shouldRenew(old, now)).toBe(true) + }) +}) + +describe('请求辅助函数', () => { + it('解析 Cookie', () => { + expect(readCookie('a=1; boundless_session=abc%3D; b=2', 'boundless_session')).toBe('abc=') + expect(readCookie(undefined, 'x')).toBeUndefined() + }) + + it('只接受同源请求,并识别反向代理转发的 Host', () => { + expect(isSameOrigin(undefined, ['example.com'])).toBe(true) + expect(isSameOrigin('https://example.com', ['example.com'])).toBe(true) + expect(isSameOrigin('https://evil.com', ['example.com'])).toBe(false) + expect(isSameOrigin('https://board.me', ['board.me', 'localhost:3000'])).toBe(true) + }) + + it('登录失败过多时暂时锁定', () => { + const limiter = new LoginLimiter(3, 1000) + limiter.fail('ip', 0) + limiter.fail('ip', 10) + expect(limiter.isBlocked('ip', 20)).toBe(false) + limiter.fail('ip', 30) + expect(limiter.isBlocked('ip', 40)).toBe(true) + expect(limiter.isBlocked('ip', 2000)).toBe(false) + }) +}) + +describe('detectImageType', () => { + const bytes = (...values: Array) => + new Uint8Array( + values.flatMap((value) => + typeof value === 'string' ? [...value].map((char) => char.charCodeAt(0)) : [value], + ), + ) + + it('根据文件头识别格式', () => { + expect(detectImageType(bytes(0x89, 'PNG\r\n', 0x1a, '\n', 0, 0, 0, 0))).toBe('png') + expect(detectImageType(bytes(0xff, 0xd8, 0xff, 0xe0, 0, 0, 0, 0, 0, 0, 0, 0))).toBe('jpg') + expect(detectImageType(bytes('RIFF', 0, 0, 0, 0, 'WEBP'))).toBe('webp') + expect(detectImageType(bytes(''))).toBe('svg') + }) + + it('拒绝非图片文件', () => { + expect(detectImageType(bytes(' @@ -120,20 +143,21 @@ async function importData(event: Event) { class="space-item-wrapper" :class="{ 'space-item-wrapper--active': store.activeSpaceId === space.id }" > - + {{ space.cardCount }} + @@ -146,35 +170,49 @@ async function importData(event: Event) {