Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: add core runtime and viewer functionalities

nirholaseea3766ea2d1
diff --git a/api/_lib/auth.js b/api/_lib/auth.js
index 94b055f0d..d4d1b23a3 100644
--- a/api/_lib/auth.js
+++ b/api/_lib/auth.js
@@ -4,7 +4,7 @@ import bcrypt from 'bcryptjs';
import { SignJWT, jwtVerify } from 'jose';
import { env } from './env.js';
import { sql } from './db.js';
-import { randomToken, sha256 } from './crypto.js';
+import { randomToken, sha256, hmacSha256, constantTimeEquals } from './crypto.js';
const ACCESS_TTL_SEC = 60 * 60; // 1h access tokens
const REFRESH_TTL_SEC = 60 * 60 * 24 * 30; // 30d refresh tokens
@@ -39,6 +39,7 @@ export async function verifyAccessToken(token, { audience } = {}) {
const { payload } = await jwtVerify(token, jwtKey, {
issuer: env.ISSUER,
audience: audience || env.MCP_RESOURCE,
+ algorithms: ['HS256'],
});
return payload;
}
@@ -55,7 +56,7 @@ export async function issueRefreshToken({ userId, clientId, scope, resource }) {
return { token: secret, id: row.id };
}
-export async function rotateRefreshToken({ oldSecret, clientId }) {
+export async function rotateRefreshToken({ oldSecret, clientId, narrowScope }) {
const hash = await sha256(oldSecret);
const rows = await sql`
select id, user_id, scope, resource, expires_at, revoked_at
@@ -74,10 +75,14 @@ export async function rotateRefreshToken({ oldSecret, clientId }) {
if (new Date(row.expires_at) < new Date()) {
throw Object.assign(new Error('invalid_grant'), { status: 400, code: 'refresh_expired' });
}
- const next = await issueRefreshToken({ userId: row.user_id, clientId, scope: row.scope, resource: row.resource });
+ // Bind the rotated refresh token to the narrowed scope (RFC 6749 §6 allows a
+ // subset). Without this, a caller could re-widen back to the full scope on
+ // the next rotation by omitting `scope`.
+ const effectiveScope = typeof narrowScope === 'function' ? narrowScope(row.scope) : row.scope;
+ const next = await issueRefreshToken({ userId: row.user_id, clientId, scope: effectiveScope, resource: row.resource });
await sql`update oauth_refresh_tokens set revoked_at = now(), replaced_by = ${next.id}, last_used_at = now()
where id = ${row.id}`;
- return { next, userId: row.user_id, scope: row.scope, resource: row.resource };
+ return { next, userId: row.user_id, scope: effectiveScope, resource: row.resource };
}
export async function revokeRefreshToken(secret, clientId) {
@@ -87,7 +92,19 @@ export async function revokeRefreshToken(secret, clientId) {
}
// ── browser sessions (cookie auth for the site itself) ──────────────────────
-const SESSION_COOKIE = 'sid';
+// __Host- prefix requires Path=/; Secure; no Domain — browser enforces cookie
+// can't be set by any subdomain, eliminating subdomain cookie injection.
+const SESSION_COOKIE = '__Host-sid';
+// Tolerate cookies from the legacy name for a single deploy cycle so existing
+// sessions survive the cutover. Read-only — never re-issue under this name.
+const LEGACY_COOKIE = 'sid';
+
+function readSessionCookie(req) {
+ const cookie = req.headers.cookie || '';
+ const m = cookie.match(/(?:^|;\s*)__Host-sid=([^;]+)/)
+ || cookie.match(/(?:^|;\s*)sid=([^;]+)/);
+ return m ? decodeURIComponent(m[1]) : null;
+}
export async function createSession({ userId, userAgent, ip }) {
const secret = randomToken(32);
@@ -100,15 +117,20 @@ export async function createSession({ userId, userAgent, ip }) {
}
export function sessionCookie(token, { clear = false } = {}) {
- if (clear) return `${SESSION_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`;
+ if (clear) {
+ // Clear both the current and legacy cookie names so logout fully drops session.
+ return [
+ `${SESSION_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`,
+ `${LEGACY_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`,
+ ];
+ }
return `${SESSION_COOKIE}=${token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${SESSION_TTL_SEC}`;
}
export async function getSessionUser(req) {
- const cookie = req.headers.cookie || '';
- const m = cookie.match(/(?:^|;\s*)sid=([^;]+)/);
- if (!m) return null;
- const hash = await sha256(decodeURIComponent(m[1]));
+ const token = readSessionCookie(req);
+ if (!token) return null;
+ const hash = await sha256(token);
const rows = await sql`
select s.id as sid, u.id, u.email, u.display_name, u.plan, u.avatar_url
from sessions s join users u on u.id = s.user_id
@@ -116,20 +138,44 @@ export async function getSessionUser(req) {
limit 1
`;
if (!rows[0]) return null;
- // Touch last_seen (best-effort, fire-and-forget at the handler level if needed).
- await sql`update sessions set last_seen_at = now() where id = ${rows[0].sid}`;
+ // Touch last_seen best-effort; don't block the request on a write.
+ sql`update sessions set last_seen_at = now() where id = ${rows[0].sid}`.catch(() => {});
const { sid: _sid, ...user } = rows[0];
return user;
}
export async function destroySession(req) {
- const cookie = req.headers.cookie || '';
- const m = cookie.match(/(?:^|;\s*)sid=([^;]+)/);
- if (!m) return;
- const hash = await sha256(decodeURIComponent(m[1]));
+ const token = readSessionCookie(req);
+ if (!token) return;
+ const hash = await sha256(token);
await sql`update sessions set revoked_at = now() where token_hash = ${hash}`;
}
+// CSRF token bound to the session cookie value. Because the cookie is HttpOnly,
+// an attacker's JS can't read it and therefore can't forge a matching token.
+export async function csrfTokenFor(req) {
+ const token = readSessionCookie(req);
+ if (!token) return null;
+ return hmacSha256(env.JWT_SECRET, `csrf:${token}`);
+}
+
+export async function verifyCsrfToken(req, submitted) {
+ if (!submitted) return false;
+ const expected = await csrfTokenFor(req);
+ if (!expected) return false;
+ return constantTimeEquals(expected, String(submitted));
+}
+
+// Reject cross-site POSTs by requiring Origin (preferred) or Referer to match
+// the configured APP_ORIGIN. Call before honoring state-changing form posts.
+export function isSameSiteOrigin(req) {
+ const origin = req.headers.origin;
+ if (origin) return origin === env.APP_ORIGIN;
+ const referer = req.headers.referer;
+ if (!referer) return false;
+ try { return new URL(referer).origin === env.APP_ORIGIN; } catch { return false; }
+}
+
// ── bearer extraction (OAuth access tokens OR API keys) ─────────────────────
export function extractBearer(req) {
const h = req.headers.authorization || '';
diff --git a/api/_lib/avatars.js b/api/_lib/avatars.js
index ef2a4c22f..59dac7c75 100644
--- a/api/_lib/avatars.js
+++ b/api/_lib/avatars.js
@@ -182,6 +182,16 @@ function decorate(row) {
};
}
+// Hide owner_id from callers who don't own the row. The raw user UUID is the
+// primary segment of R2 storage keys, so leaking it helps an attacker guess
+// object paths in other users' namespaces.
+export function stripOwnerFor(avatar, requesterId) {
+ if (!avatar) return avatar;
+ if (requesterId && avatar.owner_id === requesterId) return avatar;
+ const { owner_id: _o, ...rest } = avatar;
+ return rest;
+}
+
async function generateSlug(userId, name) {
const base = name
.toLowerCase()
diff --git a/api/_lib/crypto.js b/api/_lib/crypto.js
index 31e4b8094..aa5a6b60b 100644
--- a/api/_lib/crypto.js
+++ b/api/_lib/crypto.js
@@ -32,6 +32,18 @@ export function constantTimeEquals(a, b) {
return r === 0;
}
+export async function hmacSha256(secret, message) {
+ const key = await subtle.importKey(
+ 'raw',
+ new TextEncoder().encode(secret),
+ { name: 'HMAC', hash: 'SHA-256' },
+ false,
+ ['sign'],
+ );
+ const sig = await subtle.sign('HMAC', key, new TextEncoder().encode(message));
+ return base64url(new Uint8Array(sig));
+}
+
function hex(u8) {
return Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('');
}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 2c2efa791..e1ae72ee0 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -61,17 +61,21 @@ function parseWindowMs(w) {
export const limits = {
authIp: (ip) => getLimiter('auth:ip', { limit: 30, window: '10 m' }).limit(ip),
registerIp: (ip) => getLimiter('register:ip', { limit: 5, window: '1 h' }).limit(ip),
+ oauthRegisterIp: (ip) => getLimiter('oauth:register:ip', { limit: 10, window: '1 h' }).limit(ip),
mcpUser: (userId) => getLimiter('mcp:user', { limit: 1200, window: '1 m' }).limit(userId),
mcpIp: (ip) => getLimiter('mcp:ip', { limit: 600, window: '1 m' }).limit(ip),
oauthToken: (clientId) => getLimiter('oauth:token', { limit: 120, window: '1 m' }).limit(clientId),
upload: (userId) => getLimiter('upload', { limit: 60, window: '1 h' }).limit(userId),
};
+// Trust only proxy headers that Vercel itself sets and signs. Naively reading
+// X-Forwarded-For lets clients supply it directly on direct invocations, which
+// trivially bypasses per-IP rate limits by rotating the claimed address.
export function clientIp(req) {
- return (
- (req.headers['x-forwarded-for'] || '').split(',')[0].trim() ||
- req.headers['x-real-ip'] ||
- req.socket?.remoteAddress ||
- '0.0.0.0'
- );
+ const vercel = req.headers['x-vercel-forwarded-for'];
+ if (vercel) return String(vercel).split(',')[0].trim();
+ const real = req.headers['x-real-ip'];
+ if (real) return String(real).trim();
+ // Last resort — socket address (only meaningful on direct connections).
+ return req.socket?.remoteAddress || '0.0.0.0';
}
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 7d1f64408..c422cf25a 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -201,3 +201,67 @@ do $$ begin
create trigger oauth_clients_set_updated_at before update on oauth_clients
for each row execute function set_updated_at();
exception when duplicate_object then null; end $$;
+
+-- ── agent_identities — every agent gets a body, a place, an identity ─────────
+create table if not exists agent_identities (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references users(id) on delete cascade,
+ name text not null,
+ description text,
+ avatar_id uuid references avatars(id) on delete set null,
+ home_url text, -- /agent/:id
+ wallet_address text,
+ chain_id int,
+ erc8004_agent_id bigint,
+ erc8004_registry text,
+ registration_cid text,
+ skills text[] not null default '{}',
+ meta jsonb not null default '{}'::jsonb,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ deleted_at timestamptz
+);
+
+create index if not exists agent_identities_user
+ on agent_identities(user_id) where deleted_at is null;
+create index if not exists agent_identities_wallet
+ on agent_identities(wallet_address) where wallet_address is not null;
+
+-- ── agent_memories — the agent's persistent context ──────────────────────────
+create table if not exists agent_memories (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ type text not null check (type in ('user','feedback','project','reference')),
+ content text not null,
+ tags text[] not null default '{}',
+ context jsonb not null default '{}'::jsonb,
+ salience real not null default 0.5,
+ created_at timestamptz not null default now(),
+ expires_at timestamptz
+);
+
+create index if not exists agent_memories_agent_type
+ on agent_memories(agent_id, type, created_at desc)
+ where expires_at is null or expires_at > now();
+
+-- ── agent_actions — append-only signed history ───────────────────────────────
+create table if not exists agent_actions (
+ id bigserial primary key,
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ type text not null,
+ payload jsonb not null default '{}'::jsonb,
+ source_skill text,
+ signature text,
+ signer_address text,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists agent_actions_agent_time
+ on agent_actions(agent_id, created_at desc);
+create index if not exists agent_actions_type_time
+ on agent_actions(type, created_at desc);
+
+do $$ begin
+ create trigger agent_identities_set_updated_at before update on agent_identities
+ for each row execute function set_updated_at();
+exception when duplicate_object then null; end $$;
diff --git a/api/_lib/validate.js b/api/_lib/validate.js
index 7bb78ec1d..2b20b465a 100644
--- a/api/_lib/validate.js
+++ b/api/_lib/validate.js
@@ -14,6 +14,14 @@ export const slug = z
export const avatarVisibility = z.enum(['private', 'unlisted', 'public']);
+// Avatars are GLB/GLTF models. Lock the content-type allowlist here so both
+// the presign URL and the stored object can only ever be model binaries —
+// prevents an attacker uploading HTML/SVG to the public CDN for stored XSS.
+export const avatarContentType = z.enum([
+ 'model/gltf-binary',
+ 'model/gltf+json',
+]);
+
export const registerBody = z.object({
email,
password,
@@ -33,14 +41,14 @@ export const createAvatarBody = z.object({
tags: z.array(z.string().trim().min(1).max(40)).max(20).default([]),
source: z.enum(['upload', 'avaturn', 'import']).default('upload'),
source_meta: z.record(z.any()).default({}),
- content_type: z.string().default('model/gltf-binary'),
+ content_type: avatarContentType.default('model/gltf-binary'),
size_bytes: z.number().int().positive().max(500 * 1024 * 1024),
checksum_sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),
});
export const presignUploadBody = z.object({
size_bytes: z.number().int().positive().max(500 * 1024 * 1024),
- content_type: z.string().default('model/gltf-binary'),
+ content_type: avatarContentType.default('model/gltf-binary'),
checksum_sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),
});
diff --git a/api/agent-actions.js b/api/agent-actions.js
new file mode 100644
index 000000000..9a7d209f1
--- /dev/null
+++ b/api/agent-actions.js
@@ -0,0 +1,122 @@
+/**
+ * Agent Action Log
+ * ----------------
+ * Append-only history of every agent action.
+ * Actions can optionally be signed with ERC-191 for on-chain verifiability.
+ * Once written, actions are never deleted — this is the agent's provenance trail.
+ *
+ * GET /api/agent-actions?agent_id=&limit=&cursor=
+ * POST /api/agent-actions
+ */
+
+import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
+import { sql } from './_lib/db.js';
+import { cors, json, method, readJson, wrap, error } from './_lib/http.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ if (req.method === 'GET') return handleList(req, res);
+ return handleAppend(req, res);
+});
+
+// ── List ──────────────────────────────────────────────────────────────────
+
+async function handleList(req, res) {
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agent_id');
+ const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200);
+ const cursor = url.searchParams.get('cursor'); // bigserial id cursor
+
+ if (!agentId) return error(res, 400, 'validation_error', 'agent_id is required');
+
+ // Verify caller owns this agent
+ const [agentRow] = await sql`
+ SELECT user_id FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!agentRow) return error(res, 404, 'not_found', 'agent not found');
+ if (agentRow.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ const rows = cursor
+ ? await sql`
+ SELECT * FROM agent_actions
+ WHERE agent_id = ${agentId} AND id < ${cursor}
+ ORDER BY id DESC
+ LIMIT ${limit + 1}
+ `
+ : await sql`
+ SELECT * FROM agent_actions
+ WHERE agent_id = ${agentId}
+ ORDER BY id DESC
+ LIMIT ${limit + 1}
+ `;
+
+ const hasMore = rows.length > limit;
+ const actions = hasMore ? rows.slice(0, limit) : rows;
+ const nextCursor = hasMore ? String(actions[actions.length - 1].id) : null;
+
+ return json(res, 200, { actions: actions.map(decorate), next_cursor: nextCursor });
+}
+
+// ── Append ────────────────────────────────────────────────────────────────
+
+async function handleAppend(req, res) {
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const body = await readJson(req);
+
+ if (!body.agent_id) return error(res, 400, 'validation_error', 'agent_id required');
+ if (!body.type) return error(res, 400, 'validation_error', 'type required');
+
+ // Verify ownership
+ const [agentRow] = await sql`
+ SELECT user_id FROM agent_identities
+ WHERE id = ${body.agent_id} AND deleted_at IS NULL
+ `;
+ if (!agentRow) return error(res, 404, 'not_found', 'agent not found');
+ if (agentRow.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ const [action] = await sql`
+ INSERT INTO agent_actions (agent_id, type, payload, source_skill, signature, signer_address)
+ VALUES (
+ ${body.agent_id},
+ ${String(body.type).slice(0, 64)},
+ ${sql.json(body.payload || {})},
+ ${body.source_skill || null},
+ ${body.signature || null},
+ ${body.signer_address || null}
+ )
+ RETURNING *
+ `;
+
+ return json(res, 201, { action: decorate(action) });
+}
+
+// ── Helpers ───────────────────────────────────────────────────────────────
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+function decorate(row) {
+ return {
+ id: String(row.id),
+ agent_id: row.agent_id,
+ type: row.type,
+ payload: row.payload,
+ source_skill: row.source_skill,
+ signature: row.signature,
+ signer_address: row.signer_address,
+ created_at: row.created_at,
+ };
+}
diff --git a/api/agent-memory.js b/api/agent-memory.js
new file mode 100644
index 000000000..c9533f48e
--- /dev/null
+++ b/api/agent-memory.js
@@ -0,0 +1,188 @@
+/**
+ * Agent Memory Sync
+ * -----------------
+ * Backend sync target for agent memories.
+ * LocalStorage is the primary store — this is the durable backup.
+ *
+ * GET /api/agent-memory?agentId= — fetch agent's memories (owner only)
+ * POST /api/agent-memory — store / upsert a memory entry
+ * DELETE /api/agent-memory/:id — forget a memory
+ */
+
+import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
+import { sql } from './_lib/db.js';
+import { cors, json, method, readJson, wrap, error } from './_lib/http.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
+
+ const url = new URL(req.url, 'http://x');
+ const pathId = url.pathname.split('/').pop(); // /api/agent-memory/:id
+
+ // DELETE /api/agent-memory/:id
+ if (req.method === 'DELETE' && pathId && pathId !== 'agent-memory') {
+ return handleDelete(req, res, pathId);
+ }
+
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (req.method === 'GET') return handleList(req, res);
+ return handleUpsert(req, res);
+});
+
+// ── List ──────────────────────────────────────────────────────────────────
+
+async function handleList(req, res) {
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agentId') || url.searchParams.get('agent_id');
+ const type = url.searchParams.get('type');
+ const since = Number(url.searchParams.get('since')) || 0;
+ const limit = Math.min(Number(url.searchParams.get('limit')) || 200, 500);
+
+ if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
+
+ // Verify ownership
+ const [agentRow] = await sql`
+ SELECT user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!agentRow) return error(res, 404, 'not_found', 'agent not found');
+ if (agentRow.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ const rows = type
+ ? await sql`
+ SELECT * FROM agent_memories
+ WHERE agent_id = ${agentId}
+ AND type = ${type}
+ AND (expires_at IS NULL OR expires_at > now())
+ AND created_at > ${new Date(since).toISOString()}
+ ORDER BY salience DESC, created_at DESC
+ LIMIT ${limit}
+ `
+ : await sql`
+ SELECT * FROM agent_memories
+ WHERE agent_id = ${agentId}
+ AND (expires_at IS NULL OR expires_at > now())
+ AND created_at > ${new Date(since).toISOString()}
+ ORDER BY salience DESC, created_at DESC
+ LIMIT ${limit}
+ `;
+
+ return json(res, 200, { entries: rows.map(decorateMemory) });
+}
+
+// ── Upsert ────────────────────────────────────────────────────────────────
+
+async function handleUpsert(req, res) {
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const body = await readJson(req);
+ const agentId = body.agentId || body.agent_id;
+ const entry = body.entry;
+
+ if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
+ if (!entry) return error(res, 400, 'validation_error', 'entry required');
+
+ // Verify ownership
+ const [agentRow] = await sql`
+ SELECT user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!agentRow) return error(res, 404, 'not_found', 'agent not found');
+ if (agentRow.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ const validTypes = ['user', 'feedback', 'project', 'reference'];
+ const memType = validTypes.includes(entry.type) ? entry.type : 'project';
+
+ // Upsert by id (idempotent — local storage may resync the same entry).
+ // The WHERE clause on ON CONFLICT is critical: IDs come from the client,
+ // so without it, user B could write an entry with user A's memory id and
+ // the conflict would overwrite A's content. Constrain updates to rows
+ // belonging to the same agent (ownership already verified above).
+ const [row] = entry.id
+ ? await sql`
+ INSERT INTO agent_memories (id, agent_id, type, content, tags, context, salience, created_at, expires_at)
+ VALUES (
+ ${entry.id},
+ ${agentId},
+ ${memType},
+ ${String(entry.content || '').slice(0, 10000)},
+ ${entry.tags || []},
+ ${sql.json(entry.context || {})},
+ ${entry.salience || 0.5},
+ ${entry.createdAt ? new Date(entry.createdAt).toISOString() : new Date().toISOString()},
+ ${entry.expiresAt ? new Date(entry.expiresAt).toISOString() : null}
+ )
+ ON CONFLICT (id) DO UPDATE SET
+ content = EXCLUDED.content,
+ salience = EXCLUDED.salience,
+ expires_at = EXCLUDED.expires_at
+ WHERE agent_memories.agent_id = EXCLUDED.agent_id
+ RETURNING *
+ `
+ : await sql`
+ INSERT INTO agent_memories (agent_id, type, content, tags, context, salience, expires_at)
+ VALUES (
+ ${agentId},
+ ${memType},
+ ${String(entry.content || '').slice(0, 10000)},
+ ${entry.tags || []},
+ ${sql.json(entry.context || {})},
+ ${entry.salience || 0.5},
+ ${entry.expiresAt ? new Date(entry.expiresAt).toISOString() : null}
+ )
+ RETURNING *
+ `;
+
+ // Empty row means an ID collision with a row owned by another agent was
+ // suppressed by the ON CONFLICT WHERE guard. Report a conflict so the
+ // client generates a new ID instead of silently losing the write.
+ if (!row) return error(res, 409, 'id_conflict', 'memory id already in use');
+
+ return json(res, 201, { entry: decorateMemory(row) });
+}
+
+// ── Delete ────────────────────────────────────────────────────────────────
+
+async function handleDelete(req, res, memoryId) {
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [row] = await sql`
+ SELECT m.id, a.user_id
+ FROM agent_memories m
+ JOIN agent_identities a ON a.id = m.agent_id
+ WHERE m.id = ${memoryId}
+ `;
+
+ if (!row) return error(res, 404, 'not_found', 'memory not found');
+ if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your memory');
+
+ await sql`DELETE FROM agent_memories WHERE id = ${memoryId}`;
+ return json(res, 200, { ok: true });
+}
+
+// ── Helpers ───────────────────────────────────────────────────────────────
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+function decorateMemory(row) {
+ return {
+ id: row.id,
+ agent_id: row.agent_id,
+ type: row.type,
+ content: row.content,
+ tags: row.tags || [],
+ context: row.context || {},
+ salience: row.salience,
+ createdAt: row.created_at ? new Date(row.created_at).getTime() : Date.now(),
+ expiresAt: row.expires_at ? new Date(row.expires_at).getTime() : null,
+ };
+}
diff --git a/api/agents.js b/api/agents.js
new file mode 100644
index 000000000..7d66a83b9
--- /dev/null
+++ b/api/agents.js
@@ -0,0 +1,228 @@
+/**
+ * Agent Identity API
+ * ------------------
+ * GET /api/agents — list caller's agents
+ * GET /api/agents/me — get or auto-create the caller's default agent
+ * POST /api/agents — create a new agent identity
+ * GET /api/agents/:id — get one agent (public fields if not owner)
+ * PUT /api/agents/:id — update agent (owner only)
+ * DELETE /api/agents/:id — soft-delete agent (owner only)
+ * POST /api/agents/:id/wallet — link / update wallet
+ * DELETE /api/agents/:id/wallet — unlink wallet
+ */
+
+import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
+import { sql } from './_lib/db.js';
+import { cors, json, method, readJson, wrap, error } from './_lib/http.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ if (req.method === 'GET') return handleList(req, res);
+ return handleCreate(req, res);
+});
+
+// ── List ───────────────────────────────────────────────────────────────────
+
+async function handleList(req, res) {
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in or provide a bearer token');
+
+ // /api/agents/me — get or create the default agent
+ const url = new URL(req.url, 'http://x');
+ if (url.pathname.endsWith('/me')) {
+ return handleGetOrCreateMe(req, res, auth);
+ }
+
+ const rows = await sql`
+ SELECT * FROM agent_identities
+ WHERE user_id = ${auth.userId}
+ AND deleted_at IS NULL
+ ORDER BY created_at ASC
+ `;
+ return json(res, 200, { agents: rows.map(decorate) });
+}
+
+// ── Get-or-create default agent ───────────────────────────────────────────
+
+async function handleGetOrCreateMe(req, res, auth) {
+ let [agent] = await sql`
+ SELECT * FROM agent_identities
+ WHERE user_id = ${auth.userId}
+ AND deleted_at IS NULL
+ ORDER BY created_at ASC
+ LIMIT 1
+ `;
+
+ if (!agent) {
+ [agent] = await sql`
+ INSERT INTO agent_identities (user_id, name, skills)
+ VALUES (${auth.userId}, ${'Agent'}, ${['greet', 'present-model', 'validate-model', 'remember', 'think']})
+ RETURNING *
+ `;
+ }
+
+ return json(res, 200, { agent: decorate(agent) });
+}
+
+// ── Create ────────────────────────────────────────────────────────────────
+
+async function handleCreate(req, res) {
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in or provide a bearer token');
+
+ const body = await readJson(req);
+ const name = String(body.name || 'Agent').trim().slice(0, 100);
+
+ if (!name) return error(res, 400, 'validation_error', 'name is required');
+
+ const [agent] = await sql`
+ INSERT INTO agent_identities (user_id, name, description, skills, meta)
+ VALUES (
+ ${auth.userId},
+ ${name},
+ ${body.description ? String(body.description).slice(0, 500) : null},
+ ${body.skills || ['greet', 'present-model', 'validate-model', 'remember', 'think']},
+ ${body.meta || {}}
+ )
+ RETURNING *
+ `;
+
+ return json(res, 201, { agent: decorate(agent) });
+}
+
+// ── Get One ───────────────────────────────────────────────────────────────
+
+export async function handleGetOne(req, res, id) {
+ if (cors(req, res, { methods: 'GET,PUT,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PUT', 'DELETE'])) return;
+
+ if (req.method === 'GET') {
+ const auth = await resolveAuth(req);
+ const [row] = await sql`
+ SELECT * FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!row) return error(res, 404, 'not_found', 'agent not found');
+
+ // Public fields if not owner; full record if owner
+ const isOwner = auth?.userId === row.user_id;
+ return json(res, 200, { agent: decorate(row, isOwner) });
+ }
+
+ if (req.method === 'PUT') {
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ return handleUpdate(req, res, id, auth);
+ }
+
+ if (req.method === 'DELETE') {
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ return handleDelete(req, res, id, auth);
+ }
+}
+
+// ── Update ────────────────────────────────────────────────────────────────
+
+async function handleUpdate(req, res, id, auth) {
+ const [existing] = await sql`
+ SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!existing) return error(res, 404, 'not_found', 'agent not found');
+ if (existing.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ const body = await readJson(req);
+ const [updated] = await sql`
+ UPDATE agent_identities SET
+ name = COALESCE(${body.name || null}, name),
+ description = COALESCE(${body.description || null}, description),
+ avatar_id = COALESCE(${body.avatar_id || null}, avatar_id),
+ skills = COALESCE(${body.skills || null}, skills),
+ meta = COALESCE(${body.meta ? sql.json(body.meta) : null}, meta),
+ home_url = COALESCE(${body.home_url || null}, home_url)
+ WHERE id = ${id}
+ RETURNING *
+ `;
+ return json(res, 200, { agent: decorate(updated) });
+}
+
+// ── Delete ────────────────────────────────────────────────────────────────
+
+async function handleDelete(req, res, id, auth) {
+ const [existing] = await sql`
+ SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!existing) return error(res, 404, 'not_found', 'agent not found');
+ if (existing.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ await sql`UPDATE agent_identities SET deleted_at = now() WHERE id = ${id}`;
+ return json(res, 200, { ok: true });
+}
+
+// ── Wallet ────────────────────────────────────────────────────────────────
+
+export async function handleWallet(req, res, id) {
+ if (cors(req, res, { methods: 'POST,DELETE,OPTIONS', credentials: true })) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [existing] = await sql`
+ SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!existing) return error(res, 404, 'not_found', 'agent not found');
+ if (existing.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ if (req.method === 'DELETE') {
+ await sql`UPDATE agent_identities SET wallet_address = null, chain_id = null WHERE id = ${id}`;
+ return json(res, 200, { ok: true });
+ }
+
+ if (!method(req, res, ['POST'])) return;
+ const body = await readJson(req);
+ const address = String(body.wallet_address || '').trim();
+ const chainId = Number(body.chain_id) || null;
+ if (!address) return error(res, 400, 'validation_error', 'wallet_address required');
+
+ const [updated] = await sql`
+ UPDATE agent_identities
+ SET wallet_address = ${address}, chain_id = ${chainId}
+ WHERE id = ${id}
+ RETURNING *
+ `;
+ return json(res, 200, { agent: decorate(updated) });
+}
+
+// ── Helpers ────────────────────────────────────────────────────────────────
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id, source: 'session' };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId, source: 'bearer' };
+ return null;
+}
+
+function decorate(row, isOwner = true) {
+ const base = {
+ id: row.id,
+ name: row.name,
+ description: row.description,
+ avatar_id: row.avatar_id,
+ home_url: row.home_url || `/agent/${row.id}`,
+ skills: row.skills || [],
+ meta: row.meta || {},
+ is_registered: Boolean(row.erc8004_agent_id),
+ created_at: row.created_at,
+ };
+ if (isOwner) {
+ base.wallet_address = row.wallet_address;
+ base.chain_id = row.chain_id;
+ base.user_id = row.user_id;
+ base.erc8004_agent_id = row.erc8004_agent_id;
+ base.erc8004_registry = row.erc8004_registry;
+ base.registration_cid = row.registration_cid;
+ }
+ return base;
+}
diff --git a/api/agents/[id].js b/api/agents/[id].js
new file mode 100644
index 000000000..e0fda6292
--- /dev/null
+++ b/api/agents/[id].js
@@ -0,0 +1,22 @@
+/**
+ * /api/agents/:id and /api/agents/:id/wallet
+ * Routes to the appropriate handler in api/agents.js
+ */
+import { handleGetOne, handleWallet } from '../agents.js';
+import { cors, error } from '../_lib/http.js';
+
+export default async function handler(req, res) {
+ const url = new URL(req.url, 'http://x');
+ const parts = url.pathname.split('/').filter(Boolean);
+ // parts: ['api', 'agents', ':id'] or ['api', 'agents', ':id', 'wallet']
+ const id = parts[2];
+ const sub = parts[3];
+
+ if (!id) {
+ if (cors(req, res)) return;
+ return error(res, 400, 'bad_request', 'missing agent id');
+ }
+
+ if (sub === 'wallet') return handleWallet(req, res, id);
+ return handleGetOne(req, res, id);
+}
diff --git a/api/auth/login.js b/api/auth/login.js
index af6b668a2..465cad564 100644
--- a/api/auth/login.js
+++ b/api/auth/login.js
@@ -1,5 +1,5 @@
import { sql } from '../_lib/db.js';
-import { verifyPassword, createSession, sessionCookie } from '../_lib/auth.js';
+import { verifyPassword, createSession, sessionCookie, destroySession } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { parse, loginBody } from '../_lib/validate.js';
@@ -22,6 +22,10 @@ export default wrap(async (req, res) => {
const ok = user && (await verifyPassword(body.password, user.password_hash));
if (!ok) return error(res, 401, 'invalid_credentials', 'invalid email or password');
+ // Invalidate any pre-existing session tied to the incoming cookie before
+ // minting a new one. Defends against session fixation via planted cookies.
+ await destroySession(req);
+
const token = await createSession({
userId: user.id,
userAgent: req.headers['user-agent'],
diff --git a/api/auth/register.js b/api/auth/register.js
index e07199b24..813d832a5 100644
--- a/api/auth/register.js
+++ b/api/auth/register.js
@@ -1,5 +1,5 @@
import { sql } from '../_lib/db.js';
-import { hashPassword, createSession, sessionCookie } from '../_lib/auth.js';
+import { hashPassword, createSession, sessionCookie, destroySession } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { parse, registerBody } from '../_lib/validate.js';
@@ -24,6 +24,9 @@ export default wrap(async (req, res) => {
returning id, email, display_name, plan, created_at
`;
+ // Kill any pre-existing planted session cookie before issuing the real one.
+ await destroySession(req);
+
const token = await createSession({
userId: user.id,
userAgent: req.headers['user-agent'],
diff --git a/api/avatars/[id].js b/api/avatars/[id].js
index d24909118..ef30c30e5 100644
--- a/api/avatars/[id].js
+++ b/api/avatars/[id].js
@@ -3,7 +3,7 @@
// DELETE /api/avatars/:id — soft-delete (owner only)
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
-import { getAvatar, updateAvatar, deleteAvatar, resolveAvatarUrl } from '../_lib/avatars.js';
+import { getAvatar, updateAvatar, deleteAvatar, resolveAvatarUrl, stripOwnerFor } from '../_lib/avatars.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { recordEvent } from '../_lib/usage.js';
import { z } from 'zod';
@@ -30,7 +30,7 @@ export default wrap(async (req, res) => {
if (!avatar) return error(res, 404, 'not_found', 'avatar not found');
const urlInfo = await resolveAvatarUrl(avatar);
recordEvent({ userId: auth?.userId, clientId: auth?.clientId, apiKeyId: auth?.apiKeyId, avatarId: id, kind: 'avatar_fetch' });
- return json(res, 200, { avatar: { ...avatar, ...urlInfo } });
+ return json(res, 200, { avatar: stripOwnerFor({ ...avatar, ...urlInfo }, auth?.userId) });
}
if (!auth?.userId) return error(res, 401, 'unauthorized', 'authentication required');
diff --git a/api/avatars/index.js b/api/avatars/index.js
index ee96a8ecf..d892f9c07 100644
--- a/api/avatars/index.js
+++ b/api/avatars/index.js
@@ -40,6 +40,14 @@ async function handleCreate(req, res) {
if (!auth) return error(res, 401, 'unauthorized', 'avatars:write scope required');
const body = parse(createWithStorage, await readJson(req));
+ // Storage keys are scoped by userId (see storageKeyFor). Enforce that the
+ // caller can only register objects under their own prefix — otherwise a
+ // user could claim another user's freshly uploaded object.
+ const expectedPrefix = `u/${auth.userId}/`;
+ if (!body.storage_key.startsWith(expectedPrefix) || body.storage_key.includes('..')) {
+ return error(res, 400, 'invalid_storage_key', 'storage_key not owned by caller');
+ }
+
// Verify the object actually exists in R2 and matches the claimed size.
const head = await headObject(body.storage_key);
if (!head) return error(res, 400, 'upload_missing', 'no object at storage_key; upload first');
diff --git a/api/avatars/public.js b/api/avatars/public.js
index 2a461a0ea..a1a08f6a7 100644
--- a/api/avatars/public.js
+++ b/api/avatars/public.js
@@ -1,6 +1,6 @@
// GET /api/avatars/public — browse public avatar gallery (no auth)
-import { searchPublicAvatars } from '../_lib/avatars.js';
+import { searchPublicAvatars, stripOwnerFor } from '../_lib/avatars.js';
import { cors, json, method, wrap } from '../_lib/http.js';
export default wrap(async (req, res) => {
@@ -13,6 +13,8 @@ export default wrap(async (req, res) => {
limit: Number(url.searchParams.get('limit')) || 24,
cursor: url.searchParams.get('cursor') || undefined,
});
+ // Unauthenticated endpoint — never leak raw owner UUIDs (used as R2 path prefix).
+ result.avatars = result.avatars.map((a) => stripOwnerFor(a, null));
res.setHeader('cache-control', 'public, max-age=60, s-maxage=60');
return json(res, 200, result);
});
diff --git a/api/mcp.js b/api/mcp.js
index 2d69e22ba..478f3dc16 100644
--- a/api/mcp.js
+++ b/api/mcp.js
@@ -41,6 +41,11 @@ export default wrap(async (req, res) => {
const body = await readJson(req, 2_000_000);
const batch = Array.isArray(body) ? body : [body];
+ // Per-request batch cap — each message can trigger DB queries, so an
+ // unbounded batch multiplies rate-limited work by N against the user's budget.
+ if (batch.length > 32) {
+ return sendJsonRpcError(res, null, -32600, 'batch too large (max 32)');
+ }
const responses = [];
for (const msg of batch) {
const r = await dispatch(msg, auth, req);
@@ -293,13 +298,13 @@ const TOOLS = {
const html = renderModelViewerHtml({
src: urlInfo.url,
name: avatar.name,
- poster: args.poster,
- background: args.background || 'transparent',
- height: args.height || '480px',
- width: args.width || '100%',
+ poster: safeHttpsUrl(args.poster),
+ background: safeCssValue(args.background, 'transparent'),
+ height: safeCssLength(args.height, '480px'),
+ width: safeCssLength(args.width, '100%'),
autoRotate: args.auto_rotate !== false,
ar: args.ar !== false,
- cameraOrbit: args.camera_orbit,
+ cameraOrbit: safeCssValue(args.camera_orbit, ''),
});
return {
content: [
@@ -415,3 +420,31 @@ function esc(s) {
function attr(s) {
return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
}
+
+// CSS inputs land inside a <style> declaration (`background: <value>`), where
+// HTML attribute-escaping does not defend against `;}body{…}` breakouts. Only
+// allow a strict character class that cannot terminate the declaration/rule.
+function safeCssValue(s, fallback) {
+ if (!s) return fallback;
+ const str = String(s).trim();
+ if (!/^[a-zA-Z0-9 .,%#()\-_/+]+$/.test(str)) return fallback;
+ if (str.length > 120) return fallback;
+ return str;
+}
+
+function safeCssLength(s, fallback) {
+ if (!s) return fallback;
+ const str = String(s).trim();
+ if (!/^[0-9]+(?:\.[0-9]+)?(?:px|em|rem|vh|vw|%)$|^auto$|^100%$/.test(str)) return fallback;
+ return str;
+}
+
+// Posters are rendered as an attribute value that the browser fetches; restrict
+// to https(:) to block `javascript:` and `data:` URLs that could execute code.
+function safeHttpsUrl(s) {
+ if (!s) return undefined;
+ try {
+ const u = new URL(String(s));
+ return u.protocol === 'https:' ? u.toString() : undefined;
+ } catch { return undefined; }
+}
diff --git a/api/oauth/authorize.js b/api/oauth/authorize.js
index 59007e424..bbd2a2bd0 100644
--- a/api/oauth/authorize.js
+++ b/api/oauth/authorize.js
@@ -5,7 +5,7 @@
// PKCE is mandatory (S256). No implicit flow. No password grant.
import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
+import { getSessionUser, csrfTokenFor, verifyCsrfToken, isSameSiteOrigin } from '../_lib/auth.js';
import { randomToken } from '../_lib/crypto.js';
import { cors, method, wrap, error, redirect, readForm } from '../_lib/http.js';
import { env } from '../_lib/env.js';
@@ -50,10 +50,15 @@ export default wrap(async (req, res) => {
if (req.method === 'GET') {
// Render a simple consent page. Kept server-side to avoid shipping extra JS.
- return renderConsent(res, { client, user, params });
+ const csrf = await csrfTokenFor(req);
+ return renderConsent(res, { client, user, params, csrf });
}
- // POST — user confirmed consent.
+ // POST — user confirmed consent. Reject cross-site POSTs (Origin check) and
+ // forged submissions (CSRF token bound to the session cookie).
+ if (!isSameSiteOrigin(req)) return error(res, 403, 'forbidden', 'cross-site request blocked');
+ if (!(await verifyCsrfToken(req, params.csrf))) return error(res, 403, 'forbidden', 'invalid csrf token');
+
if (params.decision !== 'allow') {
const denied = new URL(redirect_uri);
denied.searchParams.set('error', 'access_denied');
@@ -85,10 +90,18 @@ function intersectScopes(requested, allowed) {
return requested.split(/\s+/).filter((s) => a.has(s)).join(' ') || allowed;
}
-function renderConsent(res, { client, user, params }) {
+function renderConsent(res, { client, user, params, csrf }) {
res.statusCode = 200;
res.setHeader('content-type', 'text/html; charset=utf-8');
res.setHeader('cache-control', 'no-store');
+ // Harden the consent page against clickjacking, mixed content, and
+ // extension/CDN script injection. form-action restricts where the form
+ // can POST; frame-ancestors blocks iframing of the consent UI.
+ res.setHeader('content-security-policy', "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'");
+ res.setHeader('x-frame-options', 'DENY');
+ res.setHeader('x-content-type-options', 'nosniff');
+ res.setHeader('referrer-policy', 'strict-origin-when-cross-origin');
+ res.setHeader('strict-transport-security', 'max-age=63072000; includeSubDomains; preload');
const scope = params.scope || client.scope;
const scopeList = scope.split(/\s+/).filter(Boolean);
res.end(`<!doctype html>
@@ -120,7 +133,8 @@ function renderConsent(res, { client, user, params }) {
<div class="who"><div class="dot">${esc((user.display_name || user.email)[0].toUpperCase())}</div><div><div>${esc(user.display_name || user.email)}</div><div style="color:#888;font-size:13px">${esc(user.email)}</div></div></div>
<p style="margin:0 0 4px"><b>${esc(client.name)}</b> will be able to:</p>
<ul>${scopeList.map((s) => `<li>${scopeLabel(s)}</li>`).join('')}</ul>
- ${Object.entries(params).map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`).join('')}
+ <input type="hidden" name="csrf" value="${esc(csrf || '')}">
+ ${Object.entries(params).filter(([k]) => k !== 'csrf' && k !== 'decision').map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`).join('')}
<div class="actions">
<button class="deny" type="submit" name="decision" value="deny">Cancel</button>
<button class="allow" type="submit" name="decision" value="allow">Authorize</button>
diff --git a/api/oauth/introspect.js b/api/oauth/introspect.js
index 4204e3fb5..ca17f24a5 100644
--- a/api/oauth/introspect.js
+++ b/api/oauth/introspect.js
@@ -27,6 +27,12 @@ export default wrap(async (req, res) => {
try {
const payload = await verifyAccessToken(token);
+ // Only the issuing client can introspect its own access tokens. Prevents
+ // any registered client from probing arbitrary tokens for user identity
+ // or scope (especially relevant given open dynamic registration).
+ if (payload.client_id && payload.client_id !== client_id) {
+ return json(res, 200, { active: false });
+ }
return json(res, 200, {
active: true,
scope: payload.scope,
diff --git a/api/oauth/register.js b/api/oauth/register.js
index 9bfd69a23..0ce8aea58 100644
--- a/api/oauth/register.js
+++ b/api/oauth/register.js
@@ -4,6 +4,7 @@
import { sql } from '../_lib/db.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { randomToken, sha256 } from '../_lib/crypto.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
import { z } from 'zod';
import { parse } from '../_lib/validate.js';
@@ -24,6 +25,11 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
if (!method(req, res, ['POST'])) return;
+ // RFC 7591 dynamic registration is unauthenticated by design, so cap per-IP
+ // to deter DB flooding and mass minting of throwaway clients for CSRF / abuse.
+ const rl = await limits.oauthRegisterIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many registrations from this IP');
+
const body = parse(registerSchema, await readJson(req));
// Security: only allow http redirect URIs for localhost (dev), per OAuth 2.1.
diff --git a/api/oauth/token.js b/api/oauth/token.js
index 06b43facb..66398eeb2 100644
--- a/api/oauth/token.js
+++ b/api/oauth/token.js
@@ -91,16 +91,21 @@ async function handleRefresh(res, client, form) {
let result;
try {
- result = await rotateRefreshToken({ oldSecret: refresh_token, clientId: client.client_id });
+ result = await rotateRefreshToken({
+ oldSecret: refresh_token,
+ clientId: client.client_id,
+ // Narrow the rotated refresh token to the requested subset so a caller
+ // can't re-widen back to the full grant on a later refresh.
+ narrowScope: (stored) => (scope ? intersect(scope, stored) : stored),
+ });
} catch (err) {
return error(res, err.status || 400, err.code || 'invalid_grant', err.message);
}
- const finalScope = scope ? intersect(scope, result.scope) : result.scope;
const accessToken = await mintAccessToken({
userId: result.userId,
clientId: client.client_id,
- scope: finalScope,
+ scope: result.scope,
resource: result.resource || env.MCP_RESOURCE,
});
@@ -108,7 +113,7 @@ async function handleRefresh(res, client, form) {
access_token: accessToken,
token_type: 'Bearer',
expires_in: 3600,
- scope: finalScope,
+ scope: result.scope,
refresh_token: result.next.token,
});
}
diff --git a/dist-lib/.well-known/agent-card.json b/dist-lib/.well-known/agent-card.json
new file mode 100644
index 000000000..41dd0b2d3
--- /dev/null
+++ b/dist-lib/.well-known/agent-card.json
@@ -0,0 +1,58 @@
+{
+ "name": "3D Agent",
+ "description": "AI-powered 3D model viewer and validation agent. Load glTF/GLB models, run validation, inspect materials, and manage avatar assets.",
+ "url": "https://3d.irish",
+ "provider": {
+ "organization": "3D Agent",
+ "url": "https://3d.irish"
+ },
+ "version": "1.5.1",
+ "capabilities": {
+ "streaming": false,
+ "pushNotifications": false,
+ "stateTransitionHistory": false
+ },
+ "authentication": {
+ "schemes": ["bearer"],
+ "credentials": null
+ },
+ "defaultInputModes": ["text/plain", "application/json"],
+ "defaultOutputModes": ["text/plain", "application/json"],
+ "skills": [
+ {
+ "id": "list-avatars",
+ "name": "List Avatars",
+ "description": "List all avatars owned by the authenticated user",
+ "tags": ["avatar", "list"],
+ "examples": ["Show me my avatars", "List all my 3D models"]
+ },
+ {
+ "id": "get-avatar",
+ "name": "Get Avatar",
+ "description": "Retrieve details of a specific avatar by ID or slug",
+ "tags": ["avatar", "inspect"],
+ "examples": ["Get avatar details for cz", "Show avatar info"]
+ },
+ {
+ "id": "search-avatars",
+ "name": "Search Public Avatars",
+ "description": "Search public avatar gallery by query",
+ "tags": ["avatar", "search"],
+ "examples": ["Find avatars matching 'robot'", "Search public models"]
+ },
+ {
+ "id": "render-avatar",
+ "name": "Render Avatar",
+ "description": "Get an embeddable HTML model-viewer snippet that renders the given avatar in 3D",
+ "tags": ["avatar", "render", "preview"],
+ "examples": ["Render my avatar in the viewer", "Preview this model"]
+ },
+ {
+ "id": "delete-avatar",
+ "name": "Delete Avatar",
+ "description": "Delete an avatar owned by the authenticated user",
+ "tags": ["avatar", "delete"],
+ "examples": ["Delete my old avatar", "Remove avatar abc123"]
+ }
+ ]
+}
diff --git a/dist-lib/.well-known/agent-registration.json b/dist-lib/.well-known/agent-registration.json
new file mode 100644
index 000000000..4d1eae972
--- /dev/null
+++ b/dist-lib/.well-known/agent-registration.json
@@ -0,0 +1,28 @@
+{
+ "type": "https://eips.ethereum.org/EIPS/eip-8004#registration-v1",
+ "name": "3D Agent",
+ "description": "AI-powered 3D model viewer and validation agent. Drag and drop glTF, GLB, and 3D files to preview instantly in your browser. Supports real-time rendering, model validation, environment maps, and animation playback via Three.js and WebGL.",
+ "image": "https://3d.irish/og-image.png",
+ "active": true,
+ "services": [
+ {
+ "name": "web",
+ "endpoint": "https://3d.irish/"
+ },
+ {
+ "name": "A2A",
+ "endpoint": "https://3d.irish/.well-known/agent-card.json",
+ "version": "0.3.0"
+ },
+ {
+ "name": "MCP",
+ "endpoint": "https://3d.irish/.well-known/openapi.yaml",
+ "version": "2025-06-18"
+ }
+ ],
+ "x402Support": false,
+ "registrations": [],
+ "supportedTrust": [
+ "reputation"
+ ]
+}
diff --git a/dist-lib/.well-known/ai-plugin.json b/dist-lib/.well-known/ai-plugin.json
new file mode 100644
index 000000000..91aa1b05e
--- /dev/null
+++ b/dist-lib/.well-known/ai-plugin.json
@@ -0,0 +1,17 @@
+{
+ "schema_version": "v1",
+ "name_for_human": "3D Agent",
+ "name_for_model": "3d_agent",
+ "description_for_human": "AI-powered 3D model viewer. Drag and drop glTF, GLB, and 3D files to preview instantly in your browser.",
+ "description_for_model": "A web-based 3D model viewer that supports glTF and GLB file formats. Users can drag-and-drop 3D models to preview them with real-time rendering powered by Three.js and WebGL.",
+ "auth": {
+ "type": "none"
+ },
+ "api": {
+ "type": "openapi",
+ "url": "https://3d.irish/.well-known/openapi.yaml"
+ },
+ "logo_url": "https://3d.irish/favicon.ico",
+ "contact_email": "[email protected]",
+ "legal_info_url": "https://3d.irish/"
+}
diff --git a/dist-lib/.well-known/openapi.yaml b/dist-lib/.well-known/openapi.yaml
new file mode 100644
index 000000000..89cdfadb0
--- /dev/null
+++ b/dist-lib/.well-known/openapi.yaml
@@ -0,0 +1,1695 @@
+openapi: 3.0.0
+info:
+ title: 3D Agent API
+ description: >
+ AI-powered 3D avatar management platform. Supports OAuth 2.1 (with PKCE),
+ session cookies, and API keys for authentication. Avatars are stored as
+ glTF/GLB files on Cloudflare R2 and exposed via a Model Context Protocol
+ (MCP) JSON-RPC server for AI tool integrations.
+ version: 1.5.1
+ contact:
+ license:
+ name: MIT
+ url: https://opensource.org/licenses/MIT
+
+servers:
+ - url: https://3d.irish
+
+tags:
+ - name: Auth
+ description: Session-based authentication (register, login, logout)
+ - name: Avatars
+ description: Avatar CRUD and file upload
+ - name: Keys
+ description: API key management
+ - name: OAuth
+ description: OAuth 2.1 authorization server (RFC 6749, 7009, 7591, 7662, 8414)
+ - name: MCP
+ description: Model Context Protocol JSON-RPC tool server
+ - name: Usage
+ description: Account usage and quota statistics
+ - name: Discovery
+ description: Well-known discovery endpoints
+
+# ---------------------------------------------------------------------------
+# Security schemes
+# ---------------------------------------------------------------------------
+components:
+ securitySchemes:
+ cookieAuth:
+ type: apiKey
+ in: cookie
+ name: sid
+ description: HttpOnly session cookie set by /api/auth/login or /api/auth/register.
+
+ bearerAuth:
+ type: http
+ scheme: bearer
+ bearerFormat: JWT
+ description: >
+ OAuth 2.1 access token (JWT, 1 h TTL) obtained from /api/oauth/token,
+ **or** an API key with prefix `sk_live_` / `sk_test_`.
+
+ # -------------------------------------------------------------------------
+ # Reusable schemas
+ # -------------------------------------------------------------------------
+ schemas:
+
+ # -- Users ---------------------------------------------------------------
+ User:
+ type: object
+ properties:
+ id:
+ type: string
+ format: uuid
+ email:
+ type: string
+ format: email
+ display_name:
+ type: string
+ nullable: true
+ avatar_url:
+ type: string
+ format: uri
+ nullable: true
+ plan:
+ type: string
+ enum: [free, pro, team, enterprise]
+ created_at:
+ type: string
+ format: date-time
+ required: [id, email, plan]
+
+ # -- Avatars -------------------------------------------------------------
+ Avatar:
+ type: object
+ properties:
+ id:
+ type: string
+ format: uuid
+ owner_id:
+ type: string
+ format: uuid
+ slug:
+ type: string
+ example: my-hero
+ name:
+ type: string
+ example: My Hero
+ description:
+ type: string
+ nullable: true
+ storage_key:
+ type: string
+ description: R2 object key
+ size_bytes:
+ type: integer
+ content_type:
+ type: string
+ example: model/gltf-binary
+ source:
+ type: string
+ enum: [upload, avaturn, import]
+ source_meta:
+ type: object
+ nullable: true
+ additionalProperties: true
+ thumbnail_key:
+ type: string
+ nullable: true
+ visibility:
+ type: string
+ enum: [private, unlisted, public]
+ tags:
+ type: array
+ items:
+ type: string
+ checksum_sha256:
+ type: string
+ nullable: true
+ description: 64-character hex SHA-256 of the file
+ version:
+ type: integer
+ created_at:
+ type: string
+ format: date-time
+ updated_at:
+ type: string
+ format: date-time
+ deleted_at:
+ type: string
+ format: date-time
+ nullable: true
+ required: [id, owner_id, slug, name, visibility, version, created_at, updated_at]
+
+ AvatarWithUrl:
+ allOf:
+ - $ref: '#/components/schemas/Avatar'
+ - type: object
+ properties:
+ url:
+ type: string
+ format: uri
+ description: Presigned or public CDN URL for the GLB file
+ cdn:
+ type: boolean
+ description: True when the URL is a public CDN URL (no expiry)
+ expires_in:
+ type: integer
+ description: Seconds until the presigned URL expires (omitted for CDN URLs)
+
+ # -- API Keys ------------------------------------------------------------
+ ApiKey:
+ type: object
+ properties:
+ id:
+ type: string
+ format: uuid
+ name:
+ type: string
+ prefix:
+ type: string
+ example: sk_live_Ab3d
+ description: First 12 chars of the key (safe to display)
+ scope:
+ type: string
+ example: avatars:read avatars:write
+ last_used_at:
+ type: string
+ format: date-time
+ nullable: true
+ expires_at:
+ type: string
+ format: date-time
+ nullable: true
+ revoked_at:
+ type: string
+ format: date-time
+ nullable: true
+ created_at:
+ type: string
+ format: date-time
+ required: [id, name, prefix, scope, created_at]
+
+ # -- Usage ---------------------------------------------------------------
+ PlanQuota:
+ type: object
+ properties:
+ plan:
+ type: string
+ enum: [free, pro, team, enterprise]
+ max_avatars:
+ type: integer
+ max_bytes_per_avatar:
+ type: integer
+ max_total_bytes:
+ type: integer
+ mcp_calls_per_day:
+ type: integer
+ required: [plan, max_avatars, max_bytes_per_avatar, max_total_bytes, mcp_calls_per_day]
+
+ UsageCounts:
+ type: object
+ properties:
+ avatars:
+ type: integer
+ bytes:
+ type: integer
+ mcp_calls_24h:
+ type: integer
+ events_30d:
+ type: integer
+ required: [avatars, bytes, mcp_calls_24h, events_30d]
+
+ # -- Pagination ----------------------------------------------------------
+ Cursor:
+ type: string
+ format: date-time
+ description: ISO-8601 timestamp used as an opaque pagination cursor
+
+ # -- Errors --------------------------------------------------------------
+ Error:
+ type: object
+ properties:
+ error:
+ type: string
+ description: Machine-readable error code
+ example: validation_error
+ error_description:
+ type: string
+ description: Human-readable message
+ example: "email is required"
+ required: [error, error_description]
+
+ OAuthError:
+ type: object
+ description: RFC 6749 §5.2 error response
+ properties:
+ error:
+ type: string
+ example: invalid_grant
+ error_description:
+ type: string
+ required: [error]
+
+ # -- JSON-RPC ------------------------------------------------------------
+ JsonRpcRequest:
+ type: object
+ required: [jsonrpc, method]
+ properties:
+ jsonrpc:
+ type: string
+ enum: ["2.0"]
+ id:
+ oneOf:
+ - type: string
+ - type: integer
+ description: Omit for notifications
+ method:
+ type: string
+ params:
+ type: object
+ additionalProperties: true
+
+ JsonRpcResponse:
+ type: object
+ required: [jsonrpc, id]
+ properties:
+ jsonrpc:
+ type: string
+ enum: ["2.0"]
+ id:
+ oneOf:
+ - type: string
+ - type: integer
+ - type: "null"
+ result:
+ description: Present on success
+ error:
+ type: object
+ properties:
+ code:
+ type: integer
+ message:
+ type: string
+ data: {}
+
+ # -------------------------------------------------------------------------
+ # Reusable responses
+ # -------------------------------------------------------------------------
+ responses:
+ Unauthorized:
+ description: Missing or invalid credentials
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+
+ Forbidden:
+ description: Insufficient scope or ownership mismatch
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+
+ NotFound:
+ description: Resource not found
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+
+ TooManyRequests:
+ description: Rate limit exceeded
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ description: Seconds to wait before retrying
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+
+ InternalServerError:
+ description: Unexpected server error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+
+# ==========================================================================
+# Paths
+# ==========================================================================
+paths:
+
+ # --------------------------------------------------------------------------
+ # Root
+ # --------------------------------------------------------------------------
+ /:
+ get:
+ operationId: viewHomepage
+ summary: Load the 3D model viewer interface
+ description: >
+ Returns the main viewer page where users can drag-and-drop glTF/GLB
+ 3D models for instant preview.
+ responses:
+ "200":
+ description: The 3D viewer HTML page.
+
+ # --------------------------------------------------------------------------
+ # Auth
+ # --------------------------------------------------------------------------
+ /api/auth/register:
+ post:
+ operationId: registerUser
+ tags: [Auth]
+ summary: Register a new user account
+ description: >
+ Creates a user account, hashes the password, opens a session, and sets
+ the `sid` cookie. Rate-limited to **5 requests per IP per hour**.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [email, password]
+ properties:
+ email:
+ type: string
+ format: email
+ maxLength: 254
+ password:
+ type: string
+ minLength: 10
+ maxLength: 200
+ display_name:
+ type: string
+ minLength: 1
+ maxLength: 80
+ responses:
+ "201":
+ description: Account created
+ headers:
+ Set-Cookie:
+ description: HttpOnly session cookie (`sid`)
+ schema:
+ type: string
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ user:
+ $ref: '#/components/schemas/User'
+ "400":
+ description: Validation error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ "409":
+ description: Email already registered
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ example:
+ error: email_taken
+ error_description: An account with that email already exists
+ "429":
+ $ref: '#/components/responses/TooManyRequests'
+
+ /api/auth/login:
+ post:
+ operationId: loginUser
+ tags: [Auth]
+ summary: Log in with email and password
+ description: >
+ Verifies credentials, creates a session, and sets the `sid` cookie.
+ Rate-limited to **30 requests per IP per 10 minutes**.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [email, password]
+ properties:
+ email:
+ type: string
+ format: email
+ password:
+ type: string
+ responses:
+ "200":
+ description: Login successful
+ headers:
+ Set-Cookie:
+ description: HttpOnly session cookie (`sid`)
+ schema:
+ type: string
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ user:
+ $ref: '#/components/schemas/User'
+ "401":
+ description: Invalid credentials
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ "429":
+ $ref: '#/components/responses/TooManyRequests'
+
+ /api/auth/me:
+ get:
+ operationId: getCurrentUser
+ tags: [Auth]
+ summary: Get the currently authenticated user
+ security:
+ - cookieAuth: []
+ responses:
+ "200":
+ description: Authenticated user profile
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ user:
+ $ref: '#/components/schemas/User'
+ "401":
+ $ref: '#/components/responses/Unauthorized'
+
+ /api/auth/logout:
+ post:
+ operationId: logoutUser
+ tags: [Auth]
+ summary: Invalidate the current session
+ security:
+ - cookieAuth: []
+ responses:
+ "200":
+ description: Session revoked
+ headers:
+ Set-Cookie:
+ description: Clears the `sid` cookie
+ schema:
+ type: string
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ ok:
+ type: boolean
+ example: true
+ "401":
+ $ref: '#/components/responses/Unauthorized'
+
+ # --------------------------------------------------------------------------
+ # Avatars
+ # --------------------------------------------------------------------------
+ /api/avatars:
+ get:
+ operationId: listAvatars
+ tags: [Avatars]
+ summary: List avatars owned by the authenticated user
+ security:
+ - cookieAuth: []
+ - bearerAuth: []
+ parameters:
+ - name: limit
+ in: query
+ schema:
+ type: integer
+ minimum: 1
+ maximum: 200
+ default: 50
+ - name: cursor
+ in: query
+ description: Pagination cursor (ISO-8601 timestamp from previous `next_cursor`)
+ schema:
+ $ref: '#/components/schemas/Cursor'
+ - name: visibility
+ in: query
+ schema:
+ type: string
+ enum: [private, unlisted, public]
+ - name: include_public
+ in: query
+ description: When `true`, also returns all public avatars
+ schema:
+ type: string
+ enum: ['true', 'false']
+ responses:
+ "200":
+ description: Paginated avatar list
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ avatars:
+ type: array
+ items:
+ $ref: '#/components/schemas/Avatar'
+ next_cursor:
+ $ref: '#/components/schemas/Cursor'
+ "401":
+ $ref: '#/components/responses/Unauthorized'
+
+ post:
+ operationId: createAvatar
+ tags: [Avatars]
+ summary: Create an avatar record after uploading the file to R2
+ description: >
+ Call `POST /api/avatars/presign` first to get a presigned upload URL,
+ upload the GLB file directly to R2, then call this endpoint to register
+ the avatar.
+ security:
+ - cookieAuth: []
+ - bearerAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [name, storage_key, size_bytes]
+ properties:
+ name:
+ type: string
+ minLength: 1
+ maxLength: 120
+ slug:
+ type: string
+ minLength: 1
+ maxLength: 64
+ pattern: '^[a-z0-9_-]+$'
+ description:
+ type: string
+ maxLength: 2000
+ visibility:
+ type: string
+ enum: [private, unlisted, public]
+ default: private
+ tags:
+ type: array
+ maxItems: 20
+ items:
+ type: string
+ maxLength: 40
+ source:
+ type: string
+ enum: [upload, avaturn, import]
+ default: upload
+ source_meta:
+ type: object
+ additionalProperties: true
+ content_type:
+ type: string
+ default: model/gltf-binary
+ size_bytes:
+ type: integer
+ minimum: 1
+ maximum: 524288000
+ description: File size in bytes (max 500 MB)
+ checksum_sha256:
+ type: string
+ pattern: '^[0-9a-f]{64}$'
+ storage_key:
+ type: string
+ description: R2 object key returned by /api/avatars/presign
+ responses:
+ "201":
+ description: Avatar record created
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ avatar:
+ $ref: '#/components/schemas/Avatar'
+ "400":
+ description: Validation error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ "401":
+ $ref: '#/components/responses/Unauthorized'
+ "403":
+ $ref: '#/components/responses/Forbidden'
+ "500":
+ $ref: '#/components/responses/InternalServerError'
+
+ /api/avatars/public:
+ get:
+ operationId: searchPublicAvatars
+ tags: [Avatars]
+ summary: Search public avatars (no authentication required)
+ description: >
+ Full-text search over public avatars. Results are cached for 60 seconds.
+ parameters:
+ - name: q
+ in: query
+ description: Free-text search query
+ schema:
+ type: string
+ - name: tag
+ in: query
+ description: Filter by a single tag
+ schema:
+ type: string
+ - name: limit
+ in: query
+ schema:
+ type: integer
+ minimum: 1
+ maximum: 100
+ default: 24
+ - name: cursor
+ in: query
+ description: Pagination cursor (ISO-8601 timestamp from previous `next_cursor`)
+ schema:
+ $ref: '#/components/schemas/Cursor'
+ responses:
+ "200":
+ description: Paginated public avatar list
+ headers:
+ Cache-Control:
+ schema:
+ type: string
+ example: public, max-age=60
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ avatars:
+ type: array
+ items:
+ $ref: '#/components/schemas/Avatar'
+ next_cursor:
+ $ref: '#/components/schemas/Cursor'
+
+ /api/avatars/presign:
+ post:
+ operationId: presignAvatarUpload
+ tags: [Avatars]
+ summary: Get a presigned URL for uploading a GLB file directly to R2
+ description: >
+ Rate-limited to **60 requests per user per hour**. Use the returned
+ `upload_url` with an HTTP PUT request (include the `content-type`
+ header). After the upload succeeds, call `POST /api/avatars` with
+ the returned `storage_key`.
+ security:
+ - cookieAuth: []
+ - bearerAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [size_bytes]
+ properties:
+ size_bytes:
+ type: integer
+ minimum: 1
+ maximum: 524288000
+ description: File size in bytes (max 500 MB)
+ content_type:
+ type: string
+ default: model/gltf-binary
+ checksum_sha256:
+ type: string
+ pattern: '^[0-9a-f]{64}$'
+ slug:
+ type: string
+ minLength: 1
+ maxLength: 64
+ pattern: '^[a-z0-9_-]+$'
+ responses:
+ "200":
+ description: Presigned upload details
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [storage_key, upload_url, method, headers, expires_in]
+ properties:
+ storage_key:
+ type: string
+ description: R2 object key to pass to POST /api/avatars
+ upload_url:
+ type: string
+ format: uri
+ description: Presigned R2 PUT URL
+ method:
+ type: string
+ enum: [PUT]
+ headers:
+ type: object
+ description: Headers to include in the PUT request
+ additionalProperties:
+ type: string
+ example:
+ content-type: model/gltf-binary
+ expires_in:
+ type: integer
+ example: 300
+ description: Seconds until the presigned URL expires
+ "400":
+ description: Validation error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ "401":
+ $ref: '#/components/responses/Unauthorized'
+ "429":
+ $ref: '#/components/responses/TooManyRequests'
+
+ /api/avatars/{id}:
+ parameters:
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+
+ get:
+ operationId: getAvatar
+ tags: [Avatars]
+ summary: Get a single avatar by ID
+ description: >
+ Returns metadata plus a time-limited (or permanent CDN) URL for the
+ GLB file. Private avatars are only accessible to their owner. Records a
+ `avatar_fetch` usage event.
+ security:
+ - {}
+ - cookieAuth: []
+ - bearerAuth: []
+ responses:
+ "200":
+ description: Avatar details with download URL
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ avatar:
+ $ref: '#/components/schemas/AvatarWithUrl'
+ "401":
+ $ref: '#/components/responses/Unauthorized'
+ "404":
+ $ref: '#/components/responses/NotFound'
+
+ patch:
+ operationId: updateAvatar
+ tags: [Avatars]
+ summary: Update avatar metadata (partial update)
+ security:
+ - cookieAuth: []
+ - bearerAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ name:
+ type: string
+ minLength: 1
+ maxLength: 120
+ description:
+ type: string
+ maxLength: 2000
+ visibility:
+ type: string
+ enum: [private, unlisted, public]
+ tags:
+ type: array
+ maxItems: 20
+ items:
+ type: string
+ maxLength: 40
+ responses:
+ "200":
+ description: Updated avatar
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ avatar:
+ $ref: '#/components/schemas/Avatar'
+ "400":
+ description: Validation error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ "401":
+ $ref: '#/components/responses/Unauthorized'
+ "404":
+ $ref: '#/components/responses/NotFound'
+
+ delete:
+ operationId: deleteAvatar
+ tags: [Avatars]
+ summary: Delete an avatar (soft delete + queued R2 removal)
+ security:
+ - cookieAuth: []
+ - bearerAuth: []
+ responses:
+ "200":
+ description: Avatar deleted
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ ok:
+ type: boolean
+ example: true
+ "401":
+ $ref: '#/components/responses/Unauthorized'
+ "404":
+ $ref: '#/components/responses/NotFound'
+
+ # --------------------------------------------------------------------------
+ # API Keys
+ # --------------------------------------------------------------------------
+ /api/keys:
+ get:
+ operationId: listApiKeys
+ tags: [Keys]
+ summary: List API keys for the authenticated user
+ security:
+ - cookieAuth: []
+ responses:
+ "200":
+ description: List of API keys (secrets never returned after creation)
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ keys:
+ type: array
+ items:
+ $ref: '#/components/schemas/ApiKey'
+ "401":
+ $ref: '#/components/responses/Unauthorized'
+
+ post:
+ operationId: createApiKey
+ tags: [Keys]
+ summary: Create a new API key
+ description: >
+ The `secret` field in the response is the only time the plaintext key
+ is returned — store it immediately.
+ security:
+ - cookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [name]
+ properties:
+ name:
+ type: string
+ minLength: 1
+ maxLength: 80
+ scope:
+ type: string
+ default: "avatars:read avatars:write"
+ description: >
+ Space-separated list of scopes. Valid values:
+ `avatars:read`, `avatars:write`, `avatars:delete`, `profile`.
+ expires_in_days:
+ type: integer
+ minimum: 1
+ maximum: 3650
+ description: Key TTL in days (omit for no expiry)
+ environment:
+ type: string
+ enum: [live, test]
+ default: live
+ responses:
+ "201":
+ description: API key created (secret visible only once)
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ key:
+ allOf:
+ - $ref: '#/components/schemas/ApiKey'
+ - type: object
+ properties:
+ secret:
+ type: string
+ description: >
+ Full plaintext API key (e.g. `sk_live_…`).
+ Only returned on creation.
+ example: sk_live_Ab3dXYZ...
+ "400":
+ description: Validation error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ "401":
+ $ref: '#/components/responses/Unauthorized'
+
+ /api/keys/{id}:
+ delete:
+ operationId: revokeApiKey
+ tags: [Keys]
+ summary: Revoke an API key by ID
+ security:
+ - cookieAuth: []
+ parameters:
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ responses:
+ "200":
+ description: Key revoked
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ ok:
+ type: boolean
+ example: true
+ "401":
+ $ref: '#/components/responses/Unauthorized'
+ "404":
+ $ref: '#/components/responses/NotFound'
+
+ # --------------------------------------------------------------------------
+ # OAuth 2.1
+ # --------------------------------------------------------------------------
+ /api/oauth/register:
+ post:
+ operationId: oauthDynamicClientRegistration
+ tags: [OAuth]
+ summary: Dynamic client registration (RFC 7591)
+ description: >
+ Registers a new OAuth client. Clients with `redirect_uris` pointing to
+ `localhost` or with `token_endpoint_auth_method: none` are treated as
+ **public** clients; all others are **confidential** and receive a
+ `client_secret`.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [redirect_uris]
+ properties:
+ redirect_uris:
+ type: array
+ minItems: 1
+ maxItems: 10
+ items:
+ type: string
+ format: uri
+ client_name:
+ type: string
+ client_uri:
+ type: string
+ format: uri
+ logo_uri:
+ type: string
+ format: uri
+ scope:
+ type: string
+ example: avatars:read avatars:write
+ grant_types:
+ type: array
+ items:
+ type: string
+ enum: [authorization_code, refresh_token]
+ response_types:
+ type: array
+ items:
+ type: string
+ enum: [code]
+ token_endpoint_auth_method:
+ type: string
+ enum: [none, client_secret_basic, client_secret_post]
+ software_id:
+ type: string
+ software_version:
+ type: string
+ responses:
+ "201":
+ description: Client registered
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [client_id, client_id_issued_at, redirect_uris, grant_types, response_types, scope, token_endpoint_auth_method]
+ properties:
+ client_id:
+ type: string
+ example: mcp_Ab3dXYZ
+ client_secret:
+ type: string
+ description: Only present for confidential clients
+ client_id_issued_at:
+ type: integer
+ description: Unix timestamp
+ token_endpoint_auth_method:
+ type: string
+ redirect_uris:
+ type: array
+ items:
+ type: string
+ format: uri
+ grant_types:
+ type: array
+ items:
+ type: string
+ response_types:
+ type: array
+ items:
+ type: string
+ scope:
+ type: string
+ client_name:
+ type: string
+ "400":
+ description: Invalid registration request
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OAuthError'
+
+ /api/oauth/authorize:
+ get:
+ operationId: oauthAuthorize
+ tags: [OAuth]
+ summary: Authorization endpoint — show consent screen
+ description: >
+ If the user is not authenticated they are redirected to the login page.
+ On success, displays an HTML consent form. Requires PKCE with
+ `code_challenge_method=S256`.
+ parameters:
+ - name: response_type
+ in: query
+ required: true
+ schema:
+ type: string
+ enum: [code]
+ - name: client_id
+ in: query
+ required: true
+ schema:
+ type: string
+ - name: redirect_uri
+ in: query
+ required: true
+ schema:
+ type: string
+ format: uri
+ - name: scope
+ in: query
+ schema:
+ type: string
+ example: avatars:read avatars:write
+ - name: state
+ in: query
+ schema:
+ type: string
+ - name: code_challenge
+ in: query
+ required: true
+ schema:
+ type: string
+ description: Base64url-encoded SHA-256 of the code_verifier (PKCE)
+ - name: code_challenge_method
+ in: query
+ required: true
+ schema:
+ type: string
+ enum: [S256]
+ - name: resource
+ in: query
+ schema:
+ type: string
+ format: uri
+ description: RFC 8707 resource indicator
+ responses:
+ "200":
+ description: HTML consent form
+ content:
+ text/html:
+ schema:
+ type: string
+ "302":
+ description: Redirect to login (if unauthenticated) or error redirect
+ headers:
+ Location:
+ schema:
+ type: string
+ "400":
+ description: Invalid authorization request
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OAuthError'
+
+ post:
+ operationId: oauthAuthorizeDecision
+ tags: [OAuth]
+ summary: Submit consent form decision (allow or deny)
+ security:
+ - cookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/x-www-form-urlencoded:
+ schema:
+ type: object
+ required: [decision, client_id, redirect_uri, code_challenge, code_challenge_method]
+ properties:
+ decision:
+ type: string
+ enum: [allow, deny]
+ response_type:
+ type: string
+ enum: [code]
+ client_id:
+ type: string
+ redirect_uri:
+ type: string
+ format: uri
+ scope:
+ type: string
+ state:
+ type: string
+ code_challenge:
+ type: string
+ code_challenge_method:
+ type: string
+ enum: [S256]
+ resource:
+ type: string
+ responses:
+ "302":
+ description: >
+ Redirect to `redirect_uri?code=CODE&state=STATE` (allow) or
+ `redirect_uri?error=access_denied&state=STATE` (deny)
+ headers:
+ Location:
+ schema:
+ type: string
+
+ /api/oauth/token:
+ post:
+ operationId: oauthToken
+ tags: [OAuth]
+ summary: Token endpoint — exchange code or refresh token
+ description: >
+ Supports `authorization_code` and `refresh_token` grant types.
+ Confidential clients authenticate via HTTP Basic (preferred) or
+ `client_id` + `client_secret` form fields.
+ Rate-limited to **120 requests per client per minute**.
+ requestBody:
+ required: true
+ content:
+ application/x-www-form-urlencoded:
+ schema:
+ type: object
+ required: [grant_type]
+ properties:
+ grant_type:
+ type: string
+ enum: [authorization_code, refresh_token]
+ code:
+ type: string
+ description: Required for authorization_code grant
+ redirect_uri:
+ type: string
+ format: uri
+ description: Required for authorization_code grant; must match the authorization request
+ code_verifier:
+ type: string
+ description: PKCE verifier; required for authorization_code grant
+ refresh_token:
+ type: string
+ description: Required for refresh_token grant
+ scope:
+ type: string
+ description: Optional subset scope for refresh_token grant
+ client_id:
+ type: string
+ client_secret:
+ type: string
+ description: Required for confidential clients not using HTTP Basic
+ responses:
+ "200":
+ description: Token response
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [access_token, token_type, expires_in, scope]
+ properties:
+ access_token:
+ type: string
+ description: JWT access token (1 h TTL)
+ token_type:
+ type: string
+ enum: [Bearer]
+ expires_in:
+ type: integer
+ example: 3600
+ scope:
+ type: string
+ refresh_token:
+ type: string
+ description: Opaque refresh token (30 d TTL, rotated on use)
+ "400":
+ description: Invalid request
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OAuthError'
+ "401":
+ description: Invalid client credentials or grant
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OAuthError'
+ "429":
+ $ref: '#/components/responses/TooManyRequests'
+
+ /api/oauth/revoke:
+ post:
+ operationId: oauthRevoke
+ tags: [OAuth]
+ summary: Token revocation endpoint (RFC 7009)
+ description: >
+ Revokes an access token or refresh token. Always returns 200 per the
+ RFC, even if the token is unknown or already revoked.
+ requestBody:
+ required: true
+ content:
+ application/x-www-form-urlencoded:
+ schema:
+ type: object
+ required: [token]
+ properties:
+ token:
+ type: string
+ token_type_hint:
+ type: string
+ enum: [access_token, refresh_token]
+ client_id:
+ type: string
+ client_secret:
+ type: string
+ responses:
+ "200":
+ description: Revocation accepted (per RFC 7009, always 200)
+ content:
+ application/json:
+ schema:
+ type: object
+ example: {}
+
+ /api/oauth/introspect:
+ post:
+ operationId: oauthIntrospect
+ tags: [OAuth]
+ summary: Token introspection endpoint (RFC 7662)
+ description: >
+ Returns metadata about a token. Confidential clients authenticate via
+ HTTP Basic or `client_id`/`client_secret` form fields.
+ requestBody:
+ required: true
+ content:
+ application/x-www-form-urlencoded:
+ schema:
+ type: object
+ required: [token]
+ properties:
+ token:
+ type: string
+ client_id:
+ type: string
+ client_secret:
+ type: string
+ responses:
+ "200":
+ description: Token metadata
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [active]
+ properties:
+ active:
+ type: boolean
+ scope:
+ type: string
+ client_id:
+ type: string
+ sub:
+ type: string
+ format: uuid
+ description: User ID
+ token_type:
+ type: string
+ enum: [Bearer, refresh_token]
+ aud:
+ type: string
+ iss:
+ type: string
+ format: uri
+ exp:
+ type: integer
+ description: Unix expiry timestamp
+ iat:
+ type: integer
+ description: Unix issued-at timestamp
+
+ # --------------------------------------------------------------------------
+ # MCP (Model Context Protocol)
+ # --------------------------------------------------------------------------
+ /api/mcp:
+ post:
+ operationId: mcpJsonRpc
+ tags: [MCP]
+ summary: MCP JSON-RPC 2.0 endpoint
+ description: >
+ Stateless JSON-RPC 2.0 endpoint implementing the [Model Context
+ Protocol](https://modelcontextprotocol.io). Accepts single or batched
+ requests. Authenticated with an OAuth 2.1 access token **or** an API
+ key in the `Authorization: Bearer …` header.
+
+
+ **Supported methods:**
+ `initialize`, `tools/list`, `tools/call`, `ping`,
+ `notifications/initialized`, `resources/list`,
+ `resources/templates/list`, `prompts/list`, `logging/setLevel`.
+
+
+ **Built-in tools** (via `tools/call`):
+ `list_my_avatars`, `get_avatar`, `search_public_avatars`,
+ `render_avatar`, `delete_avatar`.
+
+
+ Rate limits: **600 req/min per IP**, **1 200 req/min per user**.
+ security:
+ - bearerAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ oneOf:
+ - $ref: '#/components/schemas/JsonRpcRequest'
+ - type: array
+ items:
+ $ref: '#/components/schemas/JsonRpcRequest'
+ examples:
+ initialize:
+ summary: initialize
+ value:
+ jsonrpc: "2.0"
+ id: 1
+ method: initialize
+ params:
+ protocolVersion: "2024-11-05"
+ capabilities: {}
+ clientInfo:
+ name: my-client
+ version: "1.0"
+ toolsList:
+ summary: tools/list
+ value:
+ jsonrpc: "2.0"
+ id: 2
+ method: tools/list
+ toolCall:
+ summary: tools/call — render_avatar
+ value:
+ jsonrpc: "2.0"
+ id: 3
+ method: tools/call
+ params:
+ name: render_avatar
+ arguments:
+ id: "550e8400-e29b-41d4-a716-446655440000"
+ responses:
+ "200":
+ description: JSON-RPC response (single or batch)
+ content:
+ application/json:
+ schema:
+ oneOf:
+ - $ref: '#/components/schemas/JsonRpcResponse'
+ - type: array
+ items:
+ $ref: '#/components/schemas/JsonRpcResponse'
+ "401":
+ $ref: '#/components/responses/Unauthorized'
+ "429":
+ $ref: '#/components/responses/TooManyRequests'
+
+ get:
+ operationId: mcpSseStream
+ tags: [MCP]
+ summary: MCP SSE stream (reserved — not yet implemented)
+ security:
+ - bearerAuth: []
+ responses:
+ "405":
+ description: Not yet implemented
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+
+ delete:
+ operationId: mcpTerminateSession
+ tags: [MCP]
+ summary: Terminate MCP session (no-op — server is stateless)
+ security:
+ - bearerAuth: []
+ responses:
+ "204":
+ description: Session terminated (stateless; nothing to tear down)
+
+ # --------------------------------------------------------------------------
+ # Usage
+ # --------------------------------------------------------------------------
+ /api/usage/summary:
+ get:
+ operationId: getUsageSummary
+ tags: [Usage]
+ summary: Get usage statistics and quota limits for the current account
+ security:
+ - cookieAuth: []
+ - bearerAuth: []
+ responses:
+ "200":
+ description: Usage summary
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [plan, counts]
+ properties:
+ plan:
+ $ref: '#/components/schemas/PlanQuota'
+ counts:
+ $ref: '#/components/schemas/UsageCounts'
+ "401":
+ $ref: '#/components/responses/Unauthorized'
+
+ # --------------------------------------------------------------------------
+ # Discovery — well-known endpoints
+ # --------------------------------------------------------------------------
+ /.well-known/oauth-authorization-server:
+ get:
+ operationId: oauthAuthorizationServerMetadata
+ tags: [Discovery]
+ summary: OAuth 2.0 Authorization Server Metadata (RFC 8414)
+ description: Cached for 300 seconds.
+ responses:
+ "200":
+ description: Authorization server metadata
+ headers:
+ Cache-Control:
+ schema:
+ type: string
+ example: public, max-age=300
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ issuer:
+ type: string
+ format: uri
+ authorization_endpoint:
+ type: string
+ format: uri
+ token_endpoint:
+ type: string
+ format: uri
+ registration_endpoint:
+ type: string
+ format: uri
+ revocation_endpoint:
+ type: string
+ format: uri
+ introspection_endpoint:
+ type: string
+ format: uri
+ response_types_supported:
+ type: array
+ items:
+ type: string
+ grant_types_supported:
+ type: array
+ items:
+ type: string
+ code_challenge_methods_supported:
+ type: array
+ items:
+ type: string
+ token_endpoint_auth_methods_supported:
+ type: array
+ items:
+ type: string
+ scopes_supported:
+ type: array
+ items:
+ type: string
+ service_documentation:
+ type: string
+ format: uri
+ ui_locales_supported:
+ type: array
+ items:
+ type: string
+
+ /.well-known/oauth-protected-resource:
+ get:
+ operationId: oauthProtectedResourceMetadata
+ tags: [Discovery]
+ summary: OAuth 2.0 Protected Resource Metadata (RFC 9728)
+ description: Cached for 300 seconds.
+ responses:
+ "200":
+ description: Protected resource metadata
+ headers:
+ Cache-Control:
+ schema:
+ type: string
+ example: public, max-age=300
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ resource:
+ type: string
+ format: uri
+ authorization_servers:
+ type: array
+ items:
+ type: string
+ format: uri
+ bearer_methods_supported:
+ type: array
+ items:
+ type: string
+ resource_documentation:
+ type: string
+ format: uri
+ scopes_supported:
+ type: array
+ items:
+ type: string
+
+ /.well-known/agent-card.json:
+ get:
+ operationId: getAgentCard
+ tags: [Discovery]
+ summary: Agent Card — A2A protocol agent description
+ responses:
+ "200":
+ description: Agent card JSON
+ content:
+ application/json:
+ schema:
+ type: object
+ additionalProperties: true
+
+ /.well-known/agent-registration.json:
+ get:
+ operationId: getAgentRegistration
+ tags: [Discovery]
+ summary: Agent registration manifest
+ responses:
+ "200":
+ description: Agent registration JSON
+ content:
+ application/json:
+ schema:
+ type: object
+ additionalProperties: true
+
+ /.well-known/ai-plugin.json:
+ get:
+ operationId: getAiPlugin
+ tags: [Discovery]
+ summary: AI plugin manifest (ChatGPT / OpenAI plugin format)
+ responses:
+ "200":
+ description: Plugin manifest JSON
+ content:
+ application/json:
+ schema:
+ type: object
+ additionalProperties: true
+
+ /.well-known/openapi.yaml:
+ get:
+ operationId: getOpenApiSpec
+ tags: [Discovery]
+ summary: This OpenAPI specification
+ responses:
+ "200":
+ description: OpenAPI 3.0 YAML document
+ content:
+ application/yaml:
+ schema:
+ type: string
diff --git a/dist-lib/.well-known/security.txt b/dist-lib/.well-known/security.txt
new file mode 100644
index 000000000..1701ce5a9
--- /dev/null
+++ b/dist-lib/.well-known/security.txt
@@ -0,0 +1,7 @@
+# Security policy for 3d.irish
+# https://securitytxt.org/
+
+Contact: mailto:[email protected]
+Preferred-Languages: en
+Canonical: https://3d.irish/.well-known/security.txt
+Expires: 2027-04-14T00:00:00.000Z
diff --git a/dist-lib/3d.png b/dist-lib/3d.png
new file mode 100644
index 000000000..0db6e1c8f
Binary files /dev/null and b/dist-lib/3d.png differ
diff --git a/dist-lib/agent-3d.js b/dist-lib/agent-3d.js
new file mode 100644
index 000000000..a827f87bf
--- /dev/null
+++ b/dist-lib/agent-3d.js
@@ -0,0 +1,34481 @@
+//#region \0rolldown/runtime.js
+var e = Object.defineProperty, t = (t, n) => {
+ let r = {};
+ for (var i in t) e(r, i, {
+ get: t[i],
+ enumerable: !0
+ });
+ return n || e(r, Symbol.toStringTag, { value: "Module" }), r;
+}, n = {
+ LEFT: 0,
+ MIDDLE: 1,
+ RIGHT: 2,
+ ROTATE: 0,
+ DOLLY: 1,
+ PAN: 2
+}, r = {
+ ROTATE: 0,
+ PAN: 1,
+ DOLLY_PAN: 2,
+ DOLLY_ROTATE: 3
+}, i = "attached", a = 1e3, o = 1001, s = 1002, c = 1003, l = 1004, u = 1005, d = 1006, f = 1007, p = 1008, m = 1009, h = 1010, g = 1011, _ = 1012, v = 1013, y = 1014, b = 1015, x = 1016, S = 1017, C = 1018, w = 1020, T = 35902, E = 1021, D = 1022, O = 1023, k = 1026, ee = 1027, A = 1028, te = 1029, ne = 1030, re = 1031, ie = 1033, ae = 33776, oe = 33777, se = 33778, ce = 33779, le = 35840, ue = 35841, de = 35842, fe = 35843, pe = 36196, me = 37492, he = 37496, ge = 37808, _e = 37809, ve = 37810, ye = 37811, be = 37812, j = 37813, xe = 37814, Se = 37815, Ce = 37816, M = 37817, we = 37818, N = 37819, P = 37820, Te = 37821, Ee = 36492, F = 36494, De = 36495, Oe = 36283, ke = 36284, Ae = 36285, je = 36286, Me = 2200, Ne = 2201, Pe = 2202, Fe = 2300, Ie = 2301, Le = 2302, Re = 2400, ze = 2401, Be = 2402, Ve = 2500, He = 2501, Ue = 3200, We = 3201, Ge = "srgb", Ke = "srgb-linear", qe = "linear", Je = "srgb", Ye = 7680, Xe = 35044, Ze = 2e3, Qe = class {
+ addEventListener(e, t) {
+ this._listeners === void 0 && (this._listeners = {});
+ let n = this._listeners;
+ n[e] === void 0 && (n[e] = []), n[e].indexOf(t) === -1 && n[e].push(t);
+ }
+ hasEventListener(e, t) {
+ let n = this._listeners;
+ return n === void 0 ? !1 : n[e] !== void 0 && n[e].indexOf(t) !== -1;
+ }
+ removeEventListener(e, t) {
+ let n = this._listeners;
+ if (n === void 0) return;
+ let r = n[e];
+ if (r !== void 0) {
+ let e = r.indexOf(t);
+ e !== -1 && r.splice(e, 1);
+ }
+ }
+ dispatchEvent(e) {
+ let t = this._listeners;
+ if (t === void 0) return;
+ let n = t[e.type];
+ if (n !== void 0) {
+ e.target = this;
+ let t = n.slice(0);
+ for (let n = 0, r = t.length; n < r; n++) t[n].call(this, e);
+ e.target = null;
+ }
+ }
+}, $e = /* @__PURE__ */ "00.01.02.03.04.05.06.07.08.09.0a.0b.0c.0d.0e.0f.10.11.12.13.14.15.16.17.18.19.1a.1b.1c.1d.1e.1f.20.21.22.23.24.25.26.27.28.29.2a.2b.2c.2d.2e.2f.30.31.32.33.34.35.36.37.38.39.3a.3b.3c.3d.3e.3f.40.41.42.43.44.45.46.47.48.49.4a.4b.4c.4d.4e.4f.50.51.52.53.54.55.56.57.58.59.5a.5b.5c.5d.5e.5f.60.61.62.63.64.65.66.67.68.69.6a.6b.6c.6d.6e.6f.70.71.72.73.74.75.76.77.78.79.7a.7b.7c.7d.7e.7f.80.81.82.83.84.85.86.87.88.89.8a.8b.8c.8d.8e.8f.90.91.92.93.94.95.96.97.98.99.9a.9b.9c.9d.9e.9f.a0.a1.a2.a3.a4.a5.a6.a7.a8.a9.aa.ab.ac.ad.ae.af.b0.b1.b2.b3.b4.b5.b6.b7.b8.b9.ba.bb.bc.bd.be.bf.c0.c1.c2.c3.c4.c5.c6.c7.c8.c9.ca.cb.cc.cd.ce.cf.d0.d1.d2.d3.d4.d5.d6.d7.d8.d9.da.db.dc.dd.de.df.e0.e1.e2.e3.e4.e5.e6.e7.e8.e9.ea.eb.ec.ed.ee.ef.f0.f1.f2.f3.f4.f5.f6.f7.f8.f9.fa.fb.fc.fd.fe.ff".split("."), et = 1234567, tt = Math.PI / 180, nt = 180 / Math.PI;
+function rt() {
+ let e = Math.random() * 4294967295 | 0, t = Math.random() * 4294967295 | 0, n = Math.random() * 4294967295 | 0, r = Math.random() * 4294967295 | 0;
+ return ($e[e & 255] + $e[e >> 8 & 255] + $e[e >> 16 & 255] + $e[e >> 24 & 255] + "-" + $e[t & 255] + $e[t >> 8 & 255] + "-" + $e[t >> 16 & 15 | 64] + $e[t >> 24 & 255] + "-" + $e[n & 63 | 128] + $e[n >> 8 & 255] + "-" + $e[n >> 16 & 255] + $e[n >> 24 & 255] + $e[r & 255] + $e[r >> 8 & 255] + $e[r >> 16 & 255] + $e[r >> 24 & 255]).toLowerCase();
+}
+function I(e, t, n) {
+ return Math.max(t, Math.min(n, e));
+}
+function it(e, t) {
+ return (e % t + t) % t;
+}
+function at(e, t, n, r, i) {
+ return r + (e - t) * (i - r) / (n - t);
+}
+function ot(e, t, n) {
+ return e === t ? 0 : (n - e) / (t - e);
+}
+function st(e, t, n) {
+ return (1 - n) * e + n * t;
+}
+function ct(e, t, n, r) {
+ return st(e, t, 1 - Math.exp(-n * r));
+}
+function lt(e, t = 1) {
+ return t - Math.abs(it(e, t * 2) - t);
+}
+function ut(e, t, n) {
+ return e <= t ? 0 : e >= n ? 1 : (e = (e - t) / (n - t), e * e * (3 - 2 * e));
+}
+function dt(e, t, n) {
+ return e <= t ? 0 : e >= n ? 1 : (e = (e - t) / (n - t), e * e * e * (e * (e * 6 - 15) + 10));
+}
+function ft(e, t) {
+ return e + Math.floor(Math.random() * (t - e + 1));
+}
+function pt(e, t) {
+ return e + Math.random() * (t - e);
+}
+function mt(e) {
+ return e * (.5 - Math.random());
+}
+function ht(e) {
+ e !== void 0 && (et = e);
+ let t = et += 1831565813;
+ return t = Math.imul(t ^ t >>> 15, t | 1), t ^= t + Math.imul(t ^ t >>> 7, t | 61), ((t ^ t >>> 14) >>> 0) / 4294967296;
+}
+function gt(e) {
+ return e * tt;
+}
+function _t(e) {
+ return e * nt;
+}
+function vt(e) {
+ return (e & e - 1) == 0 && e !== 0;
+}
+function yt(e) {
+ return 2 ** Math.ceil(Math.log(e) / Math.LN2);
+}
+function bt(e) {
+ return 2 ** Math.floor(Math.log(e) / Math.LN2);
+}
+function xt(e, t, n, r, i) {
+ let a = Math.cos, o = Math.sin, s = a(n / 2), c = o(n / 2), l = a((t + r) / 2), u = o((t + r) / 2), d = a((t - r) / 2), f = o((t - r) / 2), p = a((r - t) / 2), m = o((r - t) / 2);
+ switch (i) {
+ case "XYX":
+ e.set(s * u, c * d, c * f, s * l);
+ break;
+ case "YZY":
+ e.set(c * f, s * u, c * d, s * l);
+ break;
+ case "ZXZ":
+ e.set(c * d, c * f, s * u, s * l);
+ break;
+ case "XZX":
+ e.set(s * u, c * m, c * p, s * l);
+ break;
+ case "YXY":
+ e.set(c * p, s * u, c * m, s * l);
+ break;
+ case "ZYZ":
+ e.set(c * m, c * p, s * u, s * l);
+ break;
+ default: console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + i);
+ }
+}
+function St(e, t) {
+ switch (t.constructor) {
+ case Float32Array: return e;
+ case Uint32Array: return e / 4294967295;
+ case Uint16Array: return e / 65535;
+ case Uint8Array: return e / 255;
+ case Int32Array: return Math.max(e / 2147483647, -1);
+ case Int16Array: return Math.max(e / 32767, -1);
+ case Int8Array: return Math.max(e / 127, -1);
+ default: throw Error("Invalid component type.");
+ }
+}
+function Ct(e, t) {
+ switch (t.constructor) {
+ case Float32Array: return e;
+ case Uint32Array: return Math.round(e * 4294967295);
+ case Uint16Array: return Math.round(e * 65535);
+ case Uint8Array: return Math.round(e * 255);
+ case Int32Array: return Math.round(e * 2147483647);
+ case Int16Array: return Math.round(e * 32767);
+ case Int8Array: return Math.round(e * 127);
+ default: throw Error("Invalid component type.");
+ }
+}
+var wt = {
+ DEG2RAD: tt,
+ RAD2DEG: nt,
+ generateUUID: rt,
+ clamp: I,
+ euclideanModulo: it,
+ mapLinear: at,
+ inverseLerp: ot,
+ lerp: st,
+ damp: ct,
+ pingpong: lt,
+ smoothstep: ut,
+ smootherstep: dt,
+ randInt: ft,
+ randFloat: pt,
+ randFloatSpread: mt,
+ seededRandom: ht,
+ degToRad: gt,
+ radToDeg: _t,
+ isPowerOfTwo: vt,
+ ceilPowerOfTwo: yt,
+ floorPowerOfTwo: bt,
+ setQuaternionFromProperEuler: xt,
+ normalize: Ct,
+ denormalize: St
+}, L = class e {
+ constructor(t = 0, n = 0) {
+ e.prototype.isVector2 = !0, this.x = t, this.y = n;
+ }
+ get width() {
+ return this.x;
+ }
+ set width(e) {
+ this.x = e;
+ }
+ get height() {
+ return this.y;
+ }
+ set height(e) {
+ this.y = e;
+ }
+ set(e, t) {
+ return this.x = e, this.y = t, this;
+ }
+ setScalar(e) {
+ return this.x = e, this.y = e, this;
+ }
+ setX(e) {
+ return this.x = e, this;
+ }
+ setY(e) {
+ return this.y = e, this;
+ }
+ setComponent(e, t) {
+ switch (e) {
+ case 0:
+ this.x = t;
+ break;
+ case 1:
+ this.y = t;
+ break;
+ default: throw Error("index is out of range: " + e);
+ }
+ return this;
+ }
+ getComponent(e) {
+ switch (e) {
+ case 0: return this.x;
+ case 1: return this.y;
+ default: throw Error("index is out of range: " + e);
+ }
+ }
+ clone() {
+ return new this.constructor(this.x, this.y);
+ }
+ copy(e) {
+ return this.x = e.x, this.y = e.y, this;
+ }
+ add(e) {
+ return this.x += e.x, this.y += e.y, this;
+ }
+ addScalar(e) {
+ return this.x += e, this.y += e, this;
+ }
+ addVectors(e, t) {
+ return this.x = e.x + t.x, this.y = e.y + t.y, this;
+ }
+ addScaledVector(e, t) {
+ return this.x += e.x * t, this.y += e.y * t, this;
+ }
+ sub(e) {
+ return this.x -= e.x, this.y -= e.y, this;
+ }
+ subScalar(e) {
+ return this.x -= e, this.y -= e, this;
+ }
+ subVectors(e, t) {
+ return this.x = e.x - t.x, this.y = e.y - t.y, this;
+ }
+ multiply(e) {
+ return this.x *= e.x, this.y *= e.y, this;
+ }
+ multiplyScalar(e) {
+ return this.x *= e, this.y *= e, this;
+ }
+ divide(e) {
+ return this.x /= e.x, this.y /= e.y, this;
+ }
+ divideScalar(e) {
+ return this.multiplyScalar(1 / e);
+ }
+ applyMatrix3(e) {
+ let t = this.x, n = this.y, r = e.elements;
+ return this.x = r[0] * t + r[3] * n + r[6], this.y = r[1] * t + r[4] * n + r[7], this;
+ }
+ min(e) {
+ return this.x = Math.min(this.x, e.x), this.y = Math.min(this.y, e.y), this;
+ }
+ max(e) {
+ return this.x = Math.max(this.x, e.x), this.y = Math.max(this.y, e.y), this;
+ }
+ clamp(e, t) {
+ return this.x = I(this.x, e.x, t.x), this.y = I(this.y, e.y, t.y), this;
+ }
+ clampScalar(e, t) {
+ return this.x = I(this.x, e, t), this.y = I(this.y, e, t), this;
+ }
+ clampLength(e, t) {
+ let n = this.length();
+ return this.divideScalar(n || 1).multiplyScalar(I(n, e, t));
+ }
+ floor() {
+ return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this;
+ }
+ ceil() {
+ return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this;
+ }
+ round() {
+ return this.x = Math.round(this.x), this.y = Math.round(this.y), this;
+ }
+ roundToZero() {
+ return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this;
+ }
+ negate() {
+ return this.x = -this.x, this.y = -this.y, this;
+ }
+ dot(e) {
+ return this.x * e.x + this.y * e.y;
+ }
+ cross(e) {
+ return this.x * e.y - this.y * e.x;
+ }
+ lengthSq() {
+ return this.x * this.x + this.y * this.y;
+ }
+ length() {
+ return Math.sqrt(this.x * this.x + this.y * this.y);
+ }
+ manhattanLength() {
+ return Math.abs(this.x) + Math.abs(this.y);
+ }
+ normalize() {
+ return this.divideScalar(this.length() || 1);
+ }
+ angle() {
+ return Math.atan2(-this.y, -this.x) + Math.PI;
+ }
+ angleTo(e) {
+ let t = Math.sqrt(this.lengthSq() * e.lengthSq());
+ if (t === 0) return Math.PI / 2;
+ let n = this.dot(e) / t;
+ return Math.acos(I(n, -1, 1));
+ }
+ distanceTo(e) {
+ return Math.sqrt(this.distanceToSquared(e));
+ }
+ distanceToSquared(e) {
+ let t = this.x - e.x, n = this.y - e.y;
+ return t * t + n * n;
+ }
+ manhattanDistanceTo(e) {
+ return Math.abs(this.x - e.x) + Math.abs(this.y - e.y);
+ }
+ setLength(e) {
+ return this.normalize().multiplyScalar(e);
+ }
+ lerp(e, t) {
+ return this.x += (e.x - this.x) * t, this.y += (e.y - this.y) * t, this;
+ }
+ lerpVectors(e, t, n) {
+ return this.x = e.x + (t.x - e.x) * n, this.y = e.y + (t.y - e.y) * n, this;
+ }
+ equals(e) {
+ return e.x === this.x && e.y === this.y;
+ }
+ fromArray(e, t = 0) {
+ return this.x = e[t], this.y = e[t + 1], this;
+ }
+ toArray(e = [], t = 0) {
+ return e[t] = this.x, e[t + 1] = this.y, e;
+ }
+ fromBufferAttribute(e, t) {
+ return this.x = e.getX(t), this.y = e.getY(t), this;
+ }
+ rotateAround(e, t) {
+ let n = Math.cos(t), r = Math.sin(t), i = this.x - e.x, a = this.y - e.y;
+ return this.x = i * n - a * r + e.x, this.y = i * r + a * n + e.y, this;
+ }
+ random() {
+ return this.x = Math.random(), this.y = Math.random(), this;
+ }
+ *[Symbol.iterator]() {
+ yield this.x, yield this.y;
+ }
+}, Tt = class e {
+ constructor(t, n, r, i, a, o, s, c, l) {
+ e.prototype.isMatrix3 = !0, this.elements = [
+ 1,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ 0,
+ 0,
+ 1
+ ], t !== void 0 && this.set(t, n, r, i, a, o, s, c, l);
+ }
+ set(e, t, n, r, i, a, o, s, c) {
+ let l = this.elements;
+ return l[0] = e, l[1] = r, l[2] = o, l[3] = t, l[4] = i, l[5] = s, l[6] = n, l[7] = a, l[8] = c, this;
+ }
+ identity() {
+ return this.set(1, 0, 0, 0, 1, 0, 0, 0, 1), this;
+ }
+ copy(e) {
+ let t = this.elements, n = e.elements;
+ return t[0] = n[0], t[1] = n[1], t[2] = n[2], t[3] = n[3], t[4] = n[4], t[5] = n[5], t[6] = n[6], t[7] = n[7], t[8] = n[8], this;
+ }
+ extractBasis(e, t, n) {
+ return e.setFromMatrix3Column(this, 0), t.setFromMatrix3Column(this, 1), n.setFromMatrix3Column(this, 2), this;
+ }
+ setFromMatrix4(e) {
+ let t = e.elements;
+ return this.set(t[0], t[4], t[8], t[1], t[5], t[9], t[2], t[6], t[10]), this;
+ }
+ multiply(e) {
+ return this.multiplyMatrices(this, e);
+ }
+ premultiply(e) {
+ return this.multiplyMatrices(e, this);
+ }
+ multiplyMatrices(e, t) {
+ let n = e.elements, r = t.elements, i = this.elements, a = n[0], o = n[3], s = n[6], c = n[1], l = n[4], u = n[7], d = n[2], f = n[5], p = n[8], m = r[0], h = r[3], g = r[6], _ = r[1], v = r[4], y = r[7], b = r[2], x = r[5], S = r[8];
+ return i[0] = a * m + o * _ + s * b, i[3] = a * h + o * v + s * x, i[6] = a * g + o * y + s * S, i[1] = c * m + l * _ + u * b, i[4] = c * h + l * v + u * x, i[7] = c * g + l * y + u * S, i[2] = d * m + f * _ + p * b, i[5] = d * h + f * v + p * x, i[8] = d * g + f * y + p * S, this;
+ }
+ multiplyScalar(e) {
+ let t = this.elements;
+ return t[0] *= e, t[3] *= e, t[6] *= e, t[1] *= e, t[4] *= e, t[7] *= e, t[2] *= e, t[5] *= e, t[8] *= e, this;
+ }
+ determinant() {
+ let e = this.elements, t = e[0], n = e[1], r = e[2], i = e[3], a = e[4], o = e[5], s = e[6], c = e[7], l = e[8];
+ return t * a * l - t * o * c - n * i * l + n * o * s + r * i * c - r * a * s;
+ }
+ invert() {
+ let e = this.elements, t = e[0], n = e[1], r = e[2], i = e[3], a = e[4], o = e[5], s = e[6], c = e[7], l = e[8], u = l * a - o * c, d = o * s - l * i, f = c * i - a * s, p = t * u + n * d + r * f;
+ if (p === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
+ let m = 1 / p;
+ return e[0] = u * m, e[1] = (r * c - l * n) * m, e[2] = (o * n - r * a) * m, e[3] = d * m, e[4] = (l * t - r * s) * m, e[5] = (r * i - o * t) * m, e[6] = f * m, e[7] = (n * s - c * t) * m, e[8] = (a * t - n * i) * m, this;
+ }
+ transpose() {
+ let e, t = this.elements;
+ return e = t[1], t[1] = t[3], t[3] = e, e = t[2], t[2] = t[6], t[6] = e, e = t[5], t[5] = t[7], t[7] = e, this;
+ }
+ getNormalMatrix(e) {
+ return this.setFromMatrix4(e).invert().transpose();
+ }
+ transposeIntoArray(e) {
+ let t = this.elements;
+ return e[0] = t[0], e[1] = t[3], e[2] = t[6], e[3] = t[1], e[4] = t[4], e[5] = t[7], e[6] = t[2], e[7] = t[5], e[8] = t[8], this;
+ }
+ setUvTransform(e, t, n, r, i, a, o) {
+ let s = Math.cos(i), c = Math.sin(i);
+ return this.set(n * s, n * c, -n * (s * a + c * o) + a + e, -r * c, r * s, -r * (-c * a + s * o) + o + t, 0, 0, 1), this;
+ }
+ scale(e, t) {
+ return this.premultiply(Et.makeScale(e, t)), this;
+ }
+ rotate(e) {
+ return this.premultiply(Et.makeRotation(-e)), this;
+ }
+ translate(e, t) {
+ return this.premultiply(Et.makeTranslation(e, t)), this;
+ }
+ makeTranslation(e, t) {
+ return e.isVector2 ? this.set(1, 0, e.x, 0, 1, e.y, 0, 0, 1) : this.set(1, 0, e, 0, 1, t, 0, 0, 1), this;
+ }
+ makeRotation(e) {
+ let t = Math.cos(e), n = Math.sin(e);
+ return this.set(t, -n, 0, n, t, 0, 0, 0, 1), this;
+ }
+ makeScale(e, t) {
+ return this.set(e, 0, 0, 0, t, 0, 0, 0, 1), this;
+ }
+ equals(e) {
+ let t = this.elements, n = e.elements;
+ for (let e = 0; e < 9; e++) if (t[e] !== n[e]) return !1;
+ return !0;
+ }
+ fromArray(e, t = 0) {
+ for (let n = 0; n < 9; n++) this.elements[n] = e[n + t];
+ return this;
+ }
+ toArray(e = [], t = 0) {
+ let n = this.elements;
+ return e[t] = n[0], e[t + 1] = n[1], e[t + 2] = n[2], e[t + 3] = n[3], e[t + 4] = n[4], e[t + 5] = n[5], e[t + 6] = n[6], e[t + 7] = n[7], e[t + 8] = n[8], e;
+ }
+ clone() {
+ return new this.constructor().fromArray(this.elements);
+ }
+}, Et = /* @__PURE__ */ new Tt();
+function Dt(e) {
+ for (let t = e.length - 1; t >= 0; --t) if (e[t] >= 65535) return !0;
+ return !1;
+}
+function Ot(e) {
+ return document.createElementNS("http://www.w3.org/1999/xhtml", e);
+}
+function kt() {
+ let e = Ot("canvas");
+ return e.style.display = "block", e;
+}
+var At = {};
+function jt(e) {
+ e in At || (At[e] = !0, console.warn(e));
+}
+function Mt(e, t, n) {
+ return new Promise(function(r, i) {
+ function a() {
+ switch (e.clientWaitSync(t, e.SYNC_FLUSH_COMMANDS_BIT, 0)) {
+ case e.WAIT_FAILED:
+ i();
+ break;
+ case e.TIMEOUT_EXPIRED:
+ setTimeout(a, n);
+ break;
+ default: r();
+ }
+ }
+ setTimeout(a, n);
+ });
+}
+function Nt(e) {
+ let t = e.elements;
+ t[2] = .5 * t[2] + .5 * t[3], t[6] = .5 * t[6] + .5 * t[7], t[10] = .5 * t[10] + .5 * t[11], t[14] = .5 * t[14] + .5 * t[15];
+}
+function Pt(e) {
+ let t = e.elements;
+ t[11] === -1 ? (t[10] = -t[10] - 1, t[14] = -t[14]) : (t[10] = -t[10], t[14] = -t[14] + 1);
+}
+var Ft = /* @__PURE__ */ new Tt().set(.4123908, .3575843, .1804808, .212639, .7151687, .0721923, .0193308, .1191948, .9505322), It = /* @__PURE__ */ new Tt().set(3.2409699, -1.5373832, -.4986108, -.9692436, 1.8759675, .0415551, .0556301, -.203977, 1.0569715);
+function Lt() {
+ let e = {
+ enabled: !0,
+ workingColorSpace: Ke,
+ spaces: {},
+ convert: function(e, t, n) {
+ return this.enabled === !1 || t === n || !t || !n ? e : (this.spaces[t].transfer === "srgb" && (e.r = zt(e.r), e.g = zt(e.g), e.b = zt(e.b)), this.spaces[t].primaries !== this.spaces[n].primaries && (e.applyMatrix3(this.spaces[t].toXYZ), e.applyMatrix3(this.spaces[n].fromXYZ)), this.spaces[n].transfer === "srgb" && (e.r = Bt(e.r), e.g = Bt(e.g), e.b = Bt(e.b)), e);
+ },
+ fromWorkingColorSpace: function(e, t) {
+ return this.convert(e, this.workingColorSpace, t);
+ },
+ toWorkingColorSpace: function(e, t) {
+ return this.convert(e, t, this.workingColorSpace);
+ },
+ getPrimaries: function(e) {
+ return this.spaces[e].primaries;
+ },
+ getTransfer: function(e) {
+ return e === "" ? qe : this.spaces[e].transfer;
+ },
+ getLuminanceCoefficients: function(e, t = this.workingColorSpace) {
+ return e.fromArray(this.spaces[t].luminanceCoefficients);
+ },
+ define: function(e) {
+ Object.assign(this.spaces, e);
+ },
+ _getMatrix: function(e, t, n) {
+ return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ);
+ },
+ _getDrawingBufferColorSpace: function(e) {
+ return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace;
+ },
+ _getUnpackColorSpace: function(e = this.workingColorSpace) {
+ return this.spaces[e].workingColorSpaceConfig.unpackColorSpace;
+ }
+ }, t = [
+ .64,
+ .33,
+ .3,
+ .6,
+ .15,
+ .06
+ ], n = [
+ .2126,
+ .7152,
+ .0722
+ ], r = [.3127, .329];
+ return e.define({
+ [Ke]: {
+ primaries: t,
+ whitePoint: r,
+ transfer: qe,
+ toXYZ: Ft,
+ fromXYZ: It,
+ luminanceCoefficients: n,
+ workingColorSpaceConfig: { unpackColorSpace: Ge },
+ outputColorSpaceConfig: { drawingBufferColorSpace: Ge }
+ },
+ [Ge]: {
+ primaries: t,
+ whitePoint: r,
+ transfer: Je,
+ toXYZ: Ft,
+ fromXYZ: It,
+ luminanceCoefficients: n,
+ outputColorSpaceConfig: { drawingBufferColorSpace: Ge }
+ }
+ }), e;
+}
+var Rt = /* @__PURE__ */ Lt();
+function zt(e) {
+ return e < .04045 ? e * .0773993808 : (e * .9478672986 + .0521327014) ** 2.4;
+}
+function Bt(e) {
+ return e < .0031308 ? e * 12.92 : 1.055 * e ** .41666 - .055;
+}
+var Vt, Ht = class {
+ static getDataURL(e, t = "image/png") {
+ if (/^data:/i.test(e.src) || typeof HTMLCanvasElement > "u") return e.src;
+ let n;
+ if (e instanceof HTMLCanvasElement) n = e;
+ else {
+ Vt === void 0 && (Vt = Ot("canvas")), Vt.width = e.width, Vt.height = e.height;
+ let t = Vt.getContext("2d");
+ e instanceof ImageData ? t.putImageData(e, 0, 0) : t.drawImage(e, 0, 0, e.width, e.height), n = Vt;
+ }
+ return n.toDataURL(t);
+ }
+ static sRGBToLinear(e) {
+ if (typeof HTMLImageElement < "u" && e instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && e instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && e instanceof ImageBitmap) {
+ let t = Ot("canvas");
+ t.width = e.width, t.height = e.height;
+ let n = t.getContext("2d");
+ n.drawImage(e, 0, 0, e.width, e.height);
+ let r = n.getImageData(0, 0, e.width, e.height), i = r.data;
+ for (let e = 0; e < i.length; e++) i[e] = zt(i[e] / 255) * 255;
+ return n.putImageData(r, 0, 0), t;
+ } else if (e.data) {
+ let t = e.data.slice(0);
+ for (let e = 0; e < t.length; e++) t instanceof Uint8Array || t instanceof Uint8ClampedArray ? t[e] = Math.floor(zt(t[e] / 255) * 255) : t[e] = zt(t[e]);
+ return {
+ data: t,
+ width: e.width,
+ height: e.height
+ };
+ } else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."), e;
+ }
+}, Ut = 0, Wt = class {
+ constructor(e = null) {
+ this.isSource = !0, Object.defineProperty(this, "id", { value: Ut++ }), this.uuid = rt(), this.data = e, this.dataReady = !0, this.version = 0;
+ }
+ set needsUpdate(e) {
+ e === !0 && this.version++;
+ }
+ toJSON(e) {
+ let t = e === void 0 || typeof e == "string";
+ if (!t && e.images[this.uuid] !== void 0) return e.images[this.uuid];
+ let n = {
+ uuid: this.uuid,
+ url: ""
+ }, r = this.data;
+ if (r !== null) {
+ let e;
+ if (Array.isArray(r)) {
+ e = [];
+ for (let t = 0, n = r.length; t < n; t++) r[t].isDataTexture ? e.push(Gt(r[t].image)) : e.push(Gt(r[t]));
+ } else e = Gt(r);
+ n.url = e;
+ }
+ return t || (e.images[this.uuid] = n), n;
+ }
+};
+function Gt(e) {
+ return typeof HTMLImageElement < "u" && e instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && e instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && e instanceof ImageBitmap ? Ht.getDataURL(e) : e.data ? {
+ data: Array.from(e.data),
+ width: e.width,
+ height: e.height,
+ type: e.data.constructor.name
+ } : (console.warn("THREE.Texture: Unable to serialize Texture."), {});
+}
+var Kt = 0, qt = class e extends Qe {
+ constructor(t = e.DEFAULT_IMAGE, n = e.DEFAULT_MAPPING, r = o, i = o, a = d, s = p, c = O, l = m, u = e.DEFAULT_ANISOTROPY, f = "") {
+ super(), this.isTexture = !0, Object.defineProperty(this, "id", { value: Kt++ }), this.uuid = rt(), this.name = "", this.source = new Wt(t), this.mipmaps = [], this.mapping = n, this.channel = 0, this.wrapS = r, this.wrapT = i, this.magFilter = a, this.minFilter = s, this.anisotropy = u, this.format = c, this.internalFormat = null, this.type = l, this.offset = new L(0, 0), this.repeat = new L(1, 1), this.center = new L(0, 0), this.rotation = 0, this.matrixAutoUpdate = !0, this.matrix = new Tt(), this.generateMipmaps = !0, this.premultiplyAlpha = !1, this.flipY = !0, this.unpackAlignment = 4, this.colorSpace = f, this.userData = {}, this.version = 0, this.onUpdate = null, this.renderTarget = null, this.isRenderTargetTexture = !1, this.isTextureArray = !1, this.pmremVersion = 0;
+ }
+ get image() {
+ return this.source.data;
+ }
+ set image(e = null) {
+ this.source.data = e;
+ }
+ updateMatrix() {
+ this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
+ }
+ clone() {
+ return new this.constructor().copy(this);
+ }
+ copy(e) {
+ return this.name = e.name, this.source = e.source, this.mipmaps = e.mipmaps.slice(0), this.mapping = e.mapping, this.channel = e.channel, this.wrapS = e.wrapS, this.wrapT = e.wrapT, this.magFilter = e.magFilter, this.minFilter = e.minFilter, this.anisotropy = e.anisotropy, this.format = e.format, this.internalFormat = e.internalFormat, this.type = e.type, this.offset.copy(e.offset), this.repeat.copy(e.repeat), this.center.copy(e.center), this.rotation = e.rotation, this.matrixAutoUpdate = e.matrixAutoUpdate, this.matrix.copy(e.matrix), this.generateMipmaps = e.generateMipmaps, this.premultiplyAlpha = e.premultiplyAlpha, this.flipY = e.flipY, this.unpackAlignment = e.unpackAlignment, this.colorSpace = e.colorSpace, this.renderTarget = e.renderTarget, this.isRenderTargetTexture = e.isRenderTargetTexture, this.isTextureArray = e.isTextureArray, this.userData = JSON.parse(JSON.stringify(e.userData)), this.needsUpdate = !0, this;
+ }
+ toJSON(e) {
+ let t = e === void 0 || typeof e == "string";
+ if (!t && e.textures[this.uuid] !== void 0) return e.textures[this.uuid];
+ let n = {
+ metadata: {
+ version: 4.6,
+ type: "Texture",
+ generator: "Texture.toJSON"
+ },
+ uuid: this.uuid,
+ name: this.name,
+ image: this.source.toJSON(e).uuid,
+ mapping: this.mapping,
+ channel: this.channel,
+ repeat: [this.repeat.x, this.repeat.y],
+ offset: [this.offset.x, this.offset.y],
+ center: [this.center.x, this.center.y],
+ rotation: this.rotation,
+ wrap: [this.wrapS, this.wrapT],
+ format: this.format,
+ internalFormat: this.internalFormat,
+ type: this.type,
+ colorSpace: this.colorSpace,
+ minFilter: this.minFilter,
+ magFilter: this.magFilter,
+ anisotropy: this.anisotropy,
+ flipY: this.flipY,
+ generateMipmaps: this.generateMipmaps,
+ premultiplyAlpha: this.premultiplyAlpha,
+ unpackAlignment: this.unpackAlignment
+ };
+ return Object.keys(this.userData).length > 0 && (n.userData = this.userData), t || (e.textures[this.uuid] = n), n;
+ }
+ dispose() {
+ this.dispatchEvent({ type: "dispose" });
+ }
+ transformUv(e) {
+ if (this.mapping !== 300) return e;
+ if (e.applyMatrix3(this.matrix), e.x < 0 || e.x > 1) switch (this.wrapS) {
+ case a:
+ e.x -= Math.floor(e.x);
+ break;
+ case o:
+ e.x = e.x < 0 ? 0 : 1;
+ break;
+ case s:
+ Math.abs(Math.floor(e.x) % 2) === 1 ? e.x = Math.ceil(e.x) - e.x : e.x -= Math.floor(e.x);
+ break;
+ }
+ if (e.y < 0 || e.y > 1) switch (this.wrapT) {
+ case a:
+ e.y -= Math.floor(e.y);
+ break;
+ case o:
+ e.y = e.y < 0 ? 0 : 1;
+ break;
+ case s:
+ Math.abs(Math.floor(e.y) % 2) === 1 ? e.y = Math.ceil(e.y) - e.y : e.y -= Math.floor(e.y);
+ break;
+ }
+ return this.flipY && (e.y = 1 - e.y), e;
+ }
+ set needsUpdate(e) {
+ e === !0 && (this.version++, this.source.needsUpdate = !0);
+ }
+ set needsPMREMUpdate(e) {
+ e === !0 && this.pmremVersion++;
+ }
+};
+qt.DEFAULT_IMAGE = null, qt.DEFAULT_MAPPING = 300, qt.DEFAULT_ANISOTROPY = 1;
+var Jt = class e {
+ constructor(t = 0, n = 0, r = 0, i = 1) {
+ e.prototype.isVector4 = !0, this.x = t, this.y = n, this.z = r, this.w = i;
+ }
+ get width() {
+ return this.z;
+ }
+ set width(e) {
+ this.z = e;
+ }
+ get height() {
+ return this.w;
+ }
+ set height(e) {
+ this.w = e;
+ }
+ set(e, t, n, r) {
+ return this.x = e, this.y = t, this.z = n, this.w = r, this;
+ }
+ setScalar(e) {
+ return this.x = e, this.y = e, this.z = e, this.w = e, this;
+ }
+ setX(e) {
+ return this.x = e, this;
+ }
+ setY(e) {
+ return this.y = e, this;
+ }
+ setZ(e) {
+ return this.z = e, this;
+ }
+ setW(e) {
+ return this.w = e, this;
+ }
+ setComponent(e, t) {
+ switch (e) {
+ case 0:
+ this.x = t;
+ break;
+ case 1:
+ this.y = t;
+ break;
+ case 2:
+ this.z = t;
+ break;
+ case 3:
+ this.w = t;
+ break;
+ default: throw Error("index is out of range: " + e);
+ }
+ return this;
+ }
+ getComponent(e) {
+ switch (e) {
+ case 0: return this.x;
+ case 1: return this.y;
+ case 2: return this.z;
+ case 3: return this.w;
+ default: throw Error("index is out of range: " + e);
+ }
+ }
+ clone() {
+ return new this.constructor(this.x, this.y, this.z, this.w);
+ }
+ copy(e) {
+ return this.x = e.x, this.y = e.y, this.z = e.z, this.w = e.w === void 0 ? 1 : e.w, this;
+ }
+ add(e) {
+ return this.x += e.x, this.y += e.y, this.z += e.z, this.w += e.w, this;
+ }
+ addScalar(e) {
+ return this.x += e, this.y += e, this.z += e, this.w += e, this;
+ }
+ addVectors(e, t) {
+ return this.x = e.x + t.x, this.y = e.y + t.y, this.z = e.z + t.z, this.w = e.w + t.w, this;
+ }
+ addScaledVector(e, t) {
+ return this.x += e.x * t, this.y += e.y * t, this.z += e.z * t, this.w += e.w * t, this;
+ }
+ sub(e) {
+ return this.x -= e.x, this.y -= e.y, this.z -= e.z, this.w -= e.w, this;
+ }
+ subScalar(e) {
+ return this.x -= e, this.y -= e, this.z -= e, this.w -= e, this;
+ }
+ subVectors(e, t) {
+ return this.x = e.x - t.x, this.y = e.y - t.y, this.z = e.z - t.z, this.w = e.w - t.w, this;
+ }
+ multiply(e) {
+ return this.x *= e.x, this.y *= e.y, this.z *= e.z, this.w *= e.w, this;
+ }
+ multiplyScalar(e) {
+ return this.x *= e, this.y *= e, this.z *= e, this.w *= e, this;
+ }
+ applyMatrix4(e) {
+ let t = this.x, n = this.y, r = this.z, i = this.w, a = e.elements;
+ return this.x = a[0] * t + a[4] * n + a[8] * r + a[12] * i, this.y = a[1] * t + a[5] * n + a[9] * r + a[13] * i, this.z = a[2] * t + a[6] * n + a[10] * r + a[14] * i, this.w = a[3] * t + a[7] * n + a[11] * r + a[15] * i, this;
+ }
+ divide(e) {
+ return this.x /= e.x, this.y /= e.y, this.z /= e.z, this.w /= e.w, this;
+ }
+ divideScalar(e) {
+ return this.multiplyScalar(1 / e);
+ }
+ setAxisAngleFromQuaternion(e) {
+ this.w = 2 * Math.acos(e.w);
+ let t = Math.sqrt(1 - e.w * e.w);
+ return t < 1e-4 ? (this.x = 1, this.y = 0, this.z = 0) : (this.x = e.x / t, this.y = e.y / t, this.z = e.z / t), this;
+ }
+ setAxisAngleFromRotationMatrix(e) {
+ let t, n, r, i, a = .01, o = .1, s = e.elements, c = s[0], l = s[4], u = s[8], d = s[1], f = s[5], p = s[9], m = s[2], h = s[6], g = s[10];
+ if (Math.abs(l - d) < a && Math.abs(u - m) < a && Math.abs(p - h) < a) {
+ if (Math.abs(l + d) < o && Math.abs(u + m) < o && Math.abs(p + h) < o && Math.abs(c + f + g - 3) < o) return this.set(1, 0, 0, 0), this;
+ t = Math.PI;
+ let e = (c + 1) / 2, s = (f + 1) / 2, _ = (g + 1) / 2, v = (l + d) / 4, y = (u + m) / 4, b = (p + h) / 4;
+ return e > s && e > _ ? e < a ? (n = 0, r = .707106781, i = .707106781) : (n = Math.sqrt(e), r = v / n, i = y / n) : s > _ ? s < a ? (n = .707106781, r = 0, i = .707106781) : (r = Math.sqrt(s), n = v / r, i = b / r) : _ < a ? (n = .707106781, r = .707106781, i = 0) : (i = Math.sqrt(_), n = y / i, r = b / i), this.set(n, r, i, t), this;
+ }
+ let _ = Math.sqrt((h - p) * (h - p) + (u - m) * (u - m) + (d - l) * (d - l));
+ return Math.abs(_) < .001 && (_ = 1), this.x = (h - p) / _, this.y = (u - m) / _, this.z = (d - l) / _, this.w = Math.acos((c + f + g - 1) / 2), this;
+ }
+ setFromMatrixPosition(e) {
+ let t = e.elements;
+ return this.x = t[12], this.y = t[13], this.z = t[14], this.w = t[15], this;
+ }
+ min(e) {
+ return this.x = Math.min(this.x, e.x), this.y = Math.min(this.y, e.y), this.z = Math.min(this.z, e.z), this.w = Math.min(this.w, e.w), this;
+ }
+ max(e) {
+ return this.x = Math.max(this.x, e.x), this.y = Math.max(this.y, e.y), this.z = Math.max(this.z, e.z), this.w = Math.max(this.w, e.w), this;
+ }
+ clamp(e, t) {
+ return this.x = I(this.x, e.x, t.x), this.y = I(this.y, e.y, t.y), this.z = I(this.z, e.z, t.z), this.w = I(this.w, e.w, t.w), this;
+ }
+ clampScalar(e, t) {
+ return this.x = I(this.x, e, t), this.y = I(this.y, e, t), this.z = I(this.z, e, t), this.w = I(this.w, e, t), this;
+ }
+ clampLength(e, t) {
+ let n = this.length();
+ return this.divideScalar(n || 1).multiplyScalar(I(n, e, t));
+ }
+ floor() {
+ return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this.z = Math.floor(this.z), this.w = Math.floor(this.w), this;
+ }
+ ceil() {
+ return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this.z = Math.ceil(this.z), this.w = Math.ceil(this.w), this;
+ }
+ round() {
+ return this.x = Math.round(this.x), this.y = Math.round(this.y), this.z = Math.round(this.z), this.w = Math.round(this.w), this;
+ }
+ roundToZero() {
+ return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this.z = Math.trunc(this.z), this.w = Math.trunc(this.w), this;
+ }
+ negate() {
+ return this.x = -this.x, this.y = -this.y, this.z = -this.z, this.w = -this.w, this;
+ }
+ dot(e) {
+ return this.x * e.x + this.y * e.y + this.z * e.z + this.w * e.w;
+ }
+ lengthSq() {
+ return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
+ }
+ length() {
+ return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
+ }
+ manhattanLength() {
+ return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
+ }
+ normalize() {
+ return this.divideScalar(this.length() || 1);
+ }
+ setLength(e) {
+ return this.normalize().multiplyScalar(e);
+ }
+ lerp(e, t) {
+ return this.x += (e.x - this.x) * t, this.y += (e.y - this.y) * t, this.z += (e.z - this.z) * t, this.w += (e.w - this.w) * t, this;
+ }
+ lerpVectors(e, t, n) {
+ return this.x = e.x + (t.x - e.x) * n, this.y = e.y + (t.y - e.y) * n, this.z = e.z + (t.z - e.z) * n, this.w = e.w + (t.w - e.w) * n, this;
+ }
+ equals(e) {
+ return e.x === this.x && e.y === this.y && e.z === this.z && e.w === this.w;
+ }
+ fromArray(e, t = 0) {
+ return this.x = e[t], this.y = e[t + 1], this.z = e[t + 2], this.w = e[t + 3], this;
+ }
+ toArray(e = [], t = 0) {
+ return e[t] = this.x, e[t + 1] = this.y, e[t + 2] = this.z, e[t + 3] = this.w, e;
+ }
+ fromBufferAttribute(e, t) {
+ return this.x = e.getX(t), this.y = e.getY(t), this.z = e.getZ(t), this.w = e.getW(t), this;
+ }
+ random() {
+ return this.x = Math.random(), this.y = Math.random(), this.z = Math.random(), this.w = Math.random(), this;
+ }
+ *[Symbol.iterator]() {
+ yield this.x, yield this.y, yield this.z, yield this.w;
+ }
+}, Yt = class extends Qe {
+ constructor(e = 1, t = 1, n = {}) {
+ super(), this.isRenderTarget = !0, this.width = e, this.height = t, this.depth = n.depth ? n.depth : 1, this.scissor = new Jt(0, 0, e, t), this.scissorTest = !1, this.viewport = new Jt(0, 0, e, t);
+ let r = {
+ width: e,
+ height: t,
+ depth: this.depth
+ };
+ n = Object.assign({
+ generateMipmaps: !1,
+ internalFormat: null,
+ minFilter: d,
+ depthBuffer: !0,
+ stencilBuffer: !1,
+ resolveDepthBuffer: !0,
+ resolveStencilBuffer: !0,
+ depthTexture: null,
+ samples: 0,
+ count: 1,
+ multiview: !1
+ }, n);
+ let i = new qt(r, n.mapping, n.wrapS, n.wrapT, n.magFilter, n.minFilter, n.format, n.type, n.anisotropy, n.colorSpace);
+ i.flipY = !1, i.generateMipmaps = n.generateMipmaps, i.internalFormat = n.internalFormat, this.textures = [];
+ let a = n.count;
+ for (let e = 0; e < a; e++) this.textures[e] = i.clone(), this.textures[e].isRenderTargetTexture = !0, this.textures[e].renderTarget = this;
+ this.depthBuffer = n.depthBuffer, this.stencilBuffer = n.stencilBuffer, this.resolveDepthBuffer = n.resolveDepthBuffer, this.resolveStencilBuffer = n.resolveStencilBuffer, this._depthTexture = null, this.depthTexture = n.depthTexture, this.samples = n.samples, this.multiview = n.multiview;
+ }
+ get texture() {
+ return this.textures[0];
+ }
+ set texture(e) {
+ this.textures[0] = e;
+ }
+ set depthTexture(e) {
+ this._depthTexture !== null && (this._depthTexture.renderTarget = null), e !== null && (e.renderTarget = this), this._depthTexture = e;
+ }
+ get depthTexture() {
+ return this._depthTexture;
+ }
+ setSize(e, t, n = 1) {
+ if (this.width !== e || this.height !== t || this.depth !== n) {
+ this.width = e, this.height = t, this.depth = n;
+ for (let r = 0, i = this.textures.length; r < i; r++) this.textures[r].image.width = e, this.textures[r].image.height = t, this.textures[r].image.depth = n;
+ this.dispose();
+ }
+ this.viewport.set(0, 0, e, t), this.scissor.set(0, 0, e, t);
+ }
+ clone() {
+ return new this.constructor().copy(this);
+ }
+ copy(e) {
+ this.width = e.width, this.height = e.height, this.depth = e.depth, this.scissor.copy(e.scissor), this.scissorTest = e.scissorTest, this.viewport.copy(e.viewport), this.textures.length = 0;
+ for (let t = 0, n = e.textures.length; t < n; t++) {
+ this.textures[t] = e.textures[t].clone(), this.textures[t].isRenderTargetTexture = !0, this.textures[t].renderTarget = this;
+ let n = Object.assign({}, e.textures[t].image);
+ this.textures[t].source = new Wt(n);
+ }
+ return this.depthBuffer = e.depthBuffer, this.stencilBuffer = e.stencilBuffer, this.resolveDepthBuffer = e.resolveDepthBuffer, this.resolveStencilBuffer = e.resolveStencilBuffer, e.depthTexture !== null && (this.depthTexture = e.depthTexture.clone()), this.samples = e.samples, this;
+ }
+ dispose() {
+ this.dispatchEvent({ type: "dispose" });
+ }
+}, Xt = class extends Yt {
+ constructor(e = 1, t = 1, n = {}) {
+ super(e, t, n), this.isWebGLRenderTarget = !0;
+ }
+}, Zt = class extends qt {
+ constructor(e = null, t = 1, n = 1, r = 1) {
+ super(null), this.isDataArrayTexture = !0, this.image = {
+ data: e,
+ width: t,
+ height: n,
+ depth: r
+ }, this.magFilter = c, this.minFilter = c, this.wrapR = o, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1, this.layerUpdates = /* @__PURE__ */ new Set();
+ }
+ addLayerUpdate(e) {
+ this.layerUpdates.add(e);
+ }
+ clearLayerUpdates() {
+ this.layerUpdates.clear();
+ }
+}, Qt = class extends qt {
+ constructor(e = null, t = 1, n = 1, r = 1) {
+ super(null), this.isData3DTexture = !0, this.image = {
+ data: e,
+ width: t,
+ height: n,
+ depth: r
+ }, this.magFilter = c, this.minFilter = c, this.wrapR = o, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1;
+ }
+}, $t = class {
+ constructor(e = 0, t = 0, n = 0, r = 1) {
+ this.isQuaternion = !0, this._x = e, this._y = t, this._z = n, this._w = r;
+ }
+ static slerpFlat(e, t, n, r, i, a, o) {
+ let s = n[r + 0], c = n[r + 1], l = n[r + 2], u = n[r + 3], d = i[a + 0], f = i[a + 1], p = i[a + 2], m = i[a + 3];
+ if (o === 0) {
+ e[t + 0] = s, e[t + 1] = c, e[t + 2] = l, e[t + 3] = u;
+ return;
+ }
+ if (o === 1) {
+ e[t + 0] = d, e[t + 1] = f, e[t + 2] = p, e[t + 3] = m;
+ return;
+ }
+ if (u !== m || s !== d || c !== f || l !== p) {
+ let e = 1 - o, t = s * d + c * f + l * p + u * m, n = t >= 0 ? 1 : -1, r = 1 - t * t;
+ if (r > 2 ** -52) {
+ let i = Math.sqrt(r), a = Math.atan2(i, t * n);
+ e = Math.sin(e * a) / i, o = Math.sin(o * a) / i;
+ }
+ let i = o * n;
+ if (s = s * e + d * i, c = c * e + f * i, l = l * e + p * i, u = u * e + m * i, e === 1 - o) {
+ let e = 1 / Math.sqrt(s * s + c * c + l * l + u * u);
+ s *= e, c *= e, l *= e, u *= e;
+ }
+ }
+ e[t] = s, e[t + 1] = c, e[t + 2] = l, e[t + 3] = u;
+ }
+ static multiplyQuaternionsFlat(e, t, n, r, i, a) {
+ let o = n[r], s = n[r + 1], c = n[r + 2], l = n[r + 3], u = i[a], d = i[a + 1], f = i[a + 2], p = i[a + 3];
+ return e[t] = o * p + l * u + s * f - c * d, e[t + 1] = s * p + l * d + c * u - o * f, e[t + 2] = c * p + l * f + o * d - s * u, e[t + 3] = l * p - o * u - s * d - c * f, e;
+ }
+ get x() {
+ return this._x;
+ }
+ set x(e) {
+ this._x = e, this._onChangeCallback();
+ }
+ get y() {
+ return this._y;
+ }
+ set y(e) {
+ this._y = e, this._onChangeCallback();
+ }
+ get z() {
+ return this._z;
+ }
+ set z(e) {
+ this._z = e, this._onChangeCallback();
+ }
+ get w() {
+ return this._w;
+ }
+ set w(e) {
+ this._w = e, this._onChangeCallback();
+ }
+ set(e, t, n, r) {
+ return this._x = e, this._y = t, this._z = n, this._w = r, this._onChangeCallback(), this;
+ }
+ clone() {
+ return new this.constructor(this._x, this._y, this._z, this._w);
+ }
+ copy(e) {
+ return this._x = e.x, this._y = e.y, this._z = e.z, this._w = e.w, this._onChangeCallback(), this;
+ }
+ setFromEuler(e, t = !0) {
+ let n = e._x, r = e._y, i = e._z, a = e._order, o = Math.cos, s = Math.sin, c = o(n / 2), l = o(r / 2), u = o(i / 2), d = s(n / 2), f = s(r / 2), p = s(i / 2);
+ switch (a) {
+ case "XYZ":
+ this._x = d * l * u + c * f * p, this._y = c * f * u - d * l * p, this._z = c * l * p + d * f * u, this._w = c * l * u - d * f * p;
+ break;
+ case "YXZ":
+ this._x = d * l * u + c * f * p, this._y = c * f * u - d * l * p, this._z = c * l * p - d * f * u, this._w = c * l * u + d * f * p;
+ break;
+ case "ZXY":
+ this._x = d * l * u - c * f * p, this._y = c * f * u + d * l * p, this._z = c * l * p + d * f * u, this._w = c * l * u - d * f * p;
+ break;
+ case "ZYX":
+ this._x = d * l * u - c * f * p, this._y = c * f * u + d * l * p, this._z = c * l * p - d * f * u, this._w = c * l * u + d * f * p;
+ break;
+ case "YZX":
+ this._x = d * l * u + c * f * p, this._y = c * f * u + d * l * p, this._z = c * l * p - d * f * u, this._w = c * l * u - d * f * p;
+ break;
+ case "XZY":
+ this._x = d * l * u - c * f * p, this._y = c * f * u - d * l * p, this._z = c * l * p + d * f * u, this._w = c * l * u + d * f * p;
+ break;
+ default: console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + a);
+ }
+ return t === !0 && this._onChangeCallback(), this;
+ }
+ setFromAxisAngle(e, t) {
+ let n = t / 2, r = Math.sin(n);
+ return this._x = e.x * r, this._y = e.y * r, this._z = e.z * r, this._w = Math.cos(n), this._onChangeCallback(), this;
+ }
+ setFromRotationMatrix(e) {
+ let t = e.elements, n = t[0], r = t[4], i = t[8], a = t[1], o = t[5], s = t[9], c = t[2], l = t[6], u = t[10], d = n + o + u;
+ if (d > 0) {
+ let e = .5 / Math.sqrt(d + 1);
+ this._w = .25 / e, this._x = (l - s) * e, this._y = (i - c) * e, this._z = (a - r) * e;
+ } else if (n > o && n > u) {
+ let e = 2 * Math.sqrt(1 + n - o - u);
+ this._w = (l - s) / e, this._x = .25 * e, this._y = (r + a) / e, this._z = (i + c) / e;
+ } else if (o > u) {
+ let e = 2 * Math.sqrt(1 + o - n - u);
+ this._w = (i - c) / e, this._x = (r + a) / e, this._y = .25 * e, this._z = (s + l) / e;
+ } else {
+ let e = 2 * Math.sqrt(1 + u - n - o);
+ this._w = (a - r) / e, this._x = (i + c) / e, this._y = (s + l) / e, this._z = .25 * e;
+ }
+ return this._onChangeCallback(), this;
+ }
+ setFromUnitVectors(e, t) {
+ let n = e.dot(t) + 1;
+ return n < 2 ** -52 ? (n = 0, Math.abs(e.x) > Math.abs(e.z) ? (this._x = -e.y, this._y = e.x, this._z = 0, this._w = n) : (this._x = 0, this._y = -e.z, this._z = e.y, this._w = n)) : (this._x = e.y * t.z - e.z * t.y, this._y = e.z * t.x - e.x * t.z, this._z = e.x * t.y - e.y * t.x, this._w = n), this.normalize();
+ }
+ angleTo(e) {
+ return 2 * Math.acos(Math.abs(I(this.dot(e), -1, 1)));
+ }
+ rotateTowards(e, t) {
+ let n = this.angleTo(e);
+ if (n === 0) return this;
+ let r = Math.min(1, t / n);
+ return this.slerp(e, r), this;
+ }
+ identity() {
+ return this.set(0, 0, 0, 1);
+ }
+ invert() {
+ return this.conjugate();
+ }
+ conjugate() {
+ return this._x *= -1, this._y *= -1, this._z *= -1, this._onChangeCallback(), this;
+ }
+ dot(e) {
+ return this._x * e._x + this._y * e._y + this._z * e._z + this._w * e._w;
+ }
+ lengthSq() {
+ return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
+ }
+ length() {
+ return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
+ }
+ normalize() {
+ let e = this.length();
+ return e === 0 ? (this._x = 0, this._y = 0, this._z = 0, this._w = 1) : (e = 1 / e, this._x *= e, this._y *= e, this._z *= e, this._w *= e), this._onChangeCallback(), this;
+ }
+ multiply(e) {
+ return this.multiplyQuaternions(this, e);
+ }
+ premultiply(e) {
+ return this.multiplyQuaternions(e, this);
+ }
+ multiplyQuaternions(e, t) {
+ let n = e._x, r = e._y, i = e._z, a = e._w, o = t._x, s = t._y, c = t._z, l = t._w;
+ return this._x = n * l + a * o + r * c - i * s, this._y = r * l + a * s + i * o - n * c, this._z = i * l + a * c + n * s - r * o, this._w = a * l - n * o - r * s - i * c, this._onChangeCallback(), this;
+ }
+ slerp(e, t) {
+ if (t === 0) return this;
+ if (t === 1) return this.copy(e);
+ let n = this._x, r = this._y, i = this._z, a = this._w, o = a * e._w + n * e._x + r * e._y + i * e._z;
+ if (o < 0 ? (this._w = -e._w, this._x = -e._x, this._y = -e._y, this._z = -e._z, o = -o) : this.copy(e), o >= 1) return this._w = a, this._x = n, this._y = r, this._z = i, this;
+ let s = 1 - o * o;
+ if (s <= 2 ** -52) {
+ let e = 1 - t;
+ return this._w = e * a + t * this._w, this._x = e * n + t * this._x, this._y = e * r + t * this._y, this._z = e * i + t * this._z, this.normalize(), this;
+ }
+ let c = Math.sqrt(s), l = Math.atan2(c, o), u = Math.sin((1 - t) * l) / c, d = Math.sin(t * l) / c;
+ return this._w = a * u + this._w * d, this._x = n * u + this._x * d, this._y = r * u + this._y * d, this._z = i * u + this._z * d, this._onChangeCallback(), this;
+ }
+ slerpQuaternions(e, t, n) {
+ return this.copy(e).slerp(t, n);
+ }
+ random() {
+ let e = 2 * Math.PI * Math.random(), t = 2 * Math.PI * Math.random(), n = Math.random(), r = Math.sqrt(1 - n), i = Math.sqrt(n);
+ return this.set(r * Math.sin(e), r * Math.cos(e), i * Math.sin(t), i * Math.cos(t));
+ }
+ equals(e) {
+ return e._x === this._x && e._y === this._y && e._z === this._z && e._w === this._w;
+ }
+ fromArray(e, t = 0) {
+ return this._x = e[t], this._y = e[t + 1], this._z = e[t + 2], this._w = e[t + 3], this._onChangeCallback(), this;
+ }
+ toArray(e = [], t = 0) {
+ return e[t] = this._x, e[t + 1] = this._y, e[t + 2] = this._z, e[t + 3] = this._w, e;
+ }
+ fromBufferAttribute(e, t) {
+ return this._x = e.getX(t), this._y = e.getY(t), this._z = e.getZ(t), this._w = e.getW(t), this._onChangeCallback(), this;
+ }
+ toJSON() {
+ return this.toArray();
+ }
+ _onChange(e) {
+ return this._onChangeCallback = e, this;
+ }
+ _onChangeCallback() {}
+ *[Symbol.iterator]() {
+ yield this._x, yield this._y, yield this._z, yield this._w;
+ }
+}, R = class e {
+ constructor(t = 0, n = 0, r = 0) {
+ e.prototype.isVector3 = !0, this.x = t, this.y = n, this.z = r;
+ }
+ set(e, t, n) {
+ return n === void 0 && (n = this.z), this.x = e, this.y = t, this.z = n, this;
+ }
+ setScalar(e) {
+ return this.x = e, this.y = e, this.z = e, this;
+ }
+ setX(e) {
+ return this.x = e, this;
+ }
+ setY(e) {
+ return this.y = e, this;
+ }
+ setZ(e) {
+ return this.z = e, this;
+ }
+ setComponent(e, t) {
+ switch (e) {
+ case 0:
+ this.x = t;
+ break;
+ case 1:
+ this.y = t;
+ break;
+ case 2:
+ this.z = t;
+ break;
+ default: throw Error("index is out of range: " + e);
+ }
+ return this;
+ }
+ getComponent(e) {
+ switch (e) {
+ case 0: return this.x;
+ case 1: return this.y;
+ case 2: return this.z;
+ default: throw Error("index is out of range: " + e);
+ }
+ }
+ clone() {
+ return new this.constructor(this.x, this.y, this.z);
+ }
+ copy(e) {
+ return this.x = e.x, this.y = e.y, this.z = e.z, this;
+ }
+ add(e) {
+ return this.x += e.x, this.y += e.y, this.z += e.z, this;
+ }
+ addScalar(e) {
+ return this.x += e, this.y += e, this.z += e, this;
+ }
+ addVectors(e, t) {
+ return this.x = e.x + t.x, this.y = e.y + t.y, this.z = e.z + t.z, this;
+ }
+ addScaledVector(e, t) {
+ return this.x += e.x * t, this.y += e.y * t, this.z += e.z * t, this;
+ }
+ sub(e) {
+ return this.x -= e.x, this.y -= e.y, this.z -= e.z, this;
+ }
+ subScalar(e) {
+ return this.x -= e, this.y -= e, this.z -= e, this;
+ }
+ subVectors(e, t) {
+ return this.x = e.x - t.x, this.y = e.y - t.y, this.z = e.z - t.z, this;
+ }
+ multiply(e) {
+ return this.x *= e.x, this.y *= e.y, this.z *= e.z, this;
+ }
+ multiplyScalar(e) {
+ return this.x *= e, this.y *= e, this.z *= e, this;
+ }
+ multiplyVectors(e, t) {
+ return this.x = e.x * t.x, this.y = e.y * t.y, this.z = e.z * t.z, this;
+ }
+ applyEuler(e) {
+ return this.applyQuaternion(tn.setFromEuler(e));
+ }
+ applyAxisAngle(e, t) {
+ return this.applyQuaternion(tn.setFromAxisAngle(e, t));
+ }
+ applyMatrix3(e) {
+ let t = this.x, n = this.y, r = this.z, i = e.elements;
+ return this.x = i[0] * t + i[3] * n + i[6] * r, this.y = i[1] * t + i[4] * n + i[7] * r, this.z = i[2] * t + i[5] * n + i[8] * r, this;
+ }
+ applyNormalMatrix(e) {
+ return this.applyMatrix3(e).normalize();
+ }
+ applyMatrix4(e) {
+ let t = this.x, n = this.y, r = this.z, i = e.elements, a = 1 / (i[3] * t + i[7] * n + i[11] * r + i[15]);
+ return this.x = (i[0] * t + i[4] * n + i[8] * r + i[12]) * a, this.y = (i[1] * t + i[5] * n + i[9] * r + i[13]) * a, this.z = (i[2] * t + i[6] * n + i[10] * r + i[14]) * a, this;
+ }
+ applyQuaternion(e) {
+ let t = this.x, n = this.y, r = this.z, i = e.x, a = e.y, o = e.z, s = e.w, c = 2 * (a * r - o * n), l = 2 * (o * t - i * r), u = 2 * (i * n - a * t);
+ return this.x = t + s * c + a * u - o * l, this.y = n + s * l + o * c - i * u, this.z = r + s * u + i * l - a * c, this;
+ }
+ project(e) {
+ return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix);
+ }
+ unproject(e) {
+ return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld);
+ }
+ transformDirection(e) {
+ let t = this.x, n = this.y, r = this.z, i = e.elements;
+ return this.x = i[0] * t + i[4] * n + i[8] * r, this.y = i[1] * t + i[5] * n + i[9] * r, this.z = i[2] * t + i[6] * n + i[10] * r, this.normalize();
+ }
+ divide(e) {
+ return this.x /= e.x, this.y /= e.y, this.z /= e.z, this;
+ }
+ divideScalar(e) {
+ return this.multiplyScalar(1 / e);
+ }
+ min(e) {
+ return this.x = Math.min(this.x, e.x), this.y = Math.min(this.y, e.y), this.z = Math.min(this.z, e.z), this;
+ }
+ max(e) {
+ return this.x = Math.max(this.x, e.x), this.y = Math.max(this.y, e.y), this.z = Math.max(this.z, e.z), this;
+ }
+ clamp(e, t) {
+ return this.x = I(this.x, e.x, t.x), this.y = I(this.y, e.y, t.y), this.z = I(this.z, e.z, t.z), this;
+ }
+ clampScalar(e, t) {
+ return this.x = I(this.x, e, t), this.y = I(this.y, e, t), this.z = I(this.z, e, t), this;
+ }
+ clampLength(e, t) {
+ let n = this.length();
+ return this.divideScalar(n || 1).multiplyScalar(I(n, e, t));
+ }
+ floor() {
+ return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this.z = Math.floor(this.z), this;
+ }
+ ceil() {
+ return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this.z = Math.ceil(this.z), this;
+ }
+ round() {
+ return this.x = Math.round(this.x), this.y = Math.round(this.y), this.z = Math.round(this.z), this;
+ }
+ roundToZero() {
+ return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this.z = Math.trunc(this.z), this;
+ }
+ negate() {
+ return this.x = -this.x, this.y = -this.y, this.z = -this.z, this;
+ }
+ dot(e) {
+ return this.x * e.x + this.y * e.y + this.z * e.z;
+ }
+ lengthSq() {
+ return this.x * this.x + this.y * this.y + this.z * this.z;
+ }
+ length() {
+ return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
+ }
+ manhattanLength() {
+ return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
+ }
+ normalize() {
+ return this.divideScalar(this.length() || 1);
+ }
+ setLength(e) {
+ return this.normalize().multiplyScalar(e);
+ }
+ lerp(e, t) {
+ return this.x += (e.x - this.x) * t, this.y += (e.y - this.y) * t, this.z += (e.z - this.z) * t, this;
+ }
+ lerpVectors(e, t, n) {
+ return this.x = e.x + (t.x - e.x) * n, this.y = e.y + (t.y - e.y) * n, this.z = e.z + (t.z - e.z) * n, this;
+ }
+ cross(e) {
+ return this.crossVectors(this, e);
+ }
+ crossVectors(e, t) {
+ let n = e.x, r = e.y, i = e.z, a = t.x, o = t.y, s = t.z;
+ return this.x = r * s - i * o, this.y = i * a - n * s, this.z = n * o - r * a, this;
+ }
+ projectOnVector(e) {
+ let t = e.lengthSq();
+ if (t === 0) return this.set(0, 0, 0);
+ let n = e.dot(this) / t;
+ return this.copy(e).multiplyScalar(n);
+ }
+ projectOnPlane(e) {
+ return en.copy(this).projectOnVector(e), this.sub(en);
+ }
+ reflect(e) {
+ return this.sub(en.copy(e).multiplyScalar(2 * this.dot(e)));
+ }
+ angleTo(e) {
+ let t = Math.sqrt(this.lengthSq() * e.lengthSq());
+ if (t === 0) return Math.PI / 2;
+ let n = this.dot(e) / t;
+ return Math.acos(I(n, -1, 1));
+ }
+ distanceTo(e) {
+ return Math.sqrt(this.distanceToSquared(e));
+ }
+ distanceToSquared(e) {
+ let t = this.x - e.x, n = this.y - e.y, r = this.z - e.z;
+ return t * t + n * n + r * r;
+ }
+ manhattanDistanceTo(e) {
+ return Math.abs(this.x - e.x) + Math.abs(this.y - e.y) + Math.abs(this.z - e.z);
+ }
+ setFromSpherical(e) {
+ return this.setFromSphericalCoords(e.radius, e.phi, e.theta);
+ }
+ setFromSphericalCoords(e, t, n) {
+ let r = Math.sin(t) * e;
+ return this.x = r * Math.sin(n), this.y = Math.cos(t) * e, this.z = r * Math.cos(n), this;
+ }
+ setFromCylindrical(e) {
+ return this.setFromCylindricalCoords(e.radius, e.theta, e.y);
+ }
+ setFromCylindricalCoords(e, t, n) {
+ return this.x = e * Math.sin(t), this.y = n, this.z = e * Math.cos(t), this;
+ }
+ setFromMatrixPosition(e) {
+ let t = e.elements;
+ return this.x = t[12], this.y = t[13], this.z = t[14], this;
+ }
+ setFromMatrixScale(e) {
+ let t = this.setFromMatrixColumn(e, 0).length(), n = this.setFromMatrixColumn(e, 1).length(), r = this.setFromMatrixColumn(e, 2).length();
+ return this.x = t, this.y = n, this.z = r, this;
+ }
+ setFromMatrixColumn(e, t) {
+ return this.fromArray(e.elements, t * 4);
+ }
+ setFromMatrix3Column(e, t) {
+ return this.fromArray(e.elements, t * 3);
+ }
+ setFromEuler(e) {
+ return this.x = e._x, this.y = e._y, this.z = e._z, this;
+ }
+ setFromColor(e) {
+ return this.x = e.r, this.y = e.g, this.z = e.b, this;
+ }
+ equals(e) {
+ return e.x === this.x && e.y === this.y && e.z === this.z;
+ }
+ fromArray(e, t = 0) {
+ return this.x = e[t], this.y = e[t + 1], this.z = e[t + 2], this;
+ }
+ toArray(e = [], t = 0) {
+ return e[t] = this.x, e[t + 1] = this.y, e[t + 2] = this.z, e;
+ }
+ fromBufferAttribute(e, t) {
+ return this.x = e.getX(t), this.y = e.getY(t), this.z = e.getZ(t), this;
+ }
+ random() {
+ return this.x = Math.random(), this.y = Math.random(), this.z = Math.random(), this;
+ }
+ randomDirection() {
+ let e = Math.random() * Math.PI * 2, t = Math.random() * 2 - 1, n = Math.sqrt(1 - t * t);
+ return this.x = n * Math.cos(e), this.y = t, this.z = n * Math.sin(e), this;
+ }
+ *[Symbol.iterator]() {
+ yield this.x, yield this.y, yield this.z;
+ }
+}, en = /* @__PURE__ */ new R(), tn = /* @__PURE__ */ new $t(), nn = class {
+ constructor(e = new R(Infinity, Infinity, Infinity), t = new R(-Infinity, -Infinity, -Infinity)) {
+ this.isBox3 = !0, this.min = e, this.max = t;
+ }
+ set(e, t) {
+ return this.min.copy(e), this.max.copy(t), this;
+ }
+ setFromArray(e) {
+ this.makeEmpty();
+ for (let t = 0, n = e.length; t < n; t += 3) this.expandByPoint(an.fromArray(e, t));
+ return this;
+ }
+ setFromBufferAttribute(e) {
+ this.makeEmpty();
+ for (let t = 0, n = e.count; t < n; t++) this.expandByPoint(an.fromBufferAttribute(e, t));
+ return this;
+ }
+ setFromPoints(e) {
+ this.makeEmpty();
+ for (let t = 0, n = e.length; t < n; t++) this.expandByPoint(e[t]);
+ return this;
+ }
+ setFromCenterAndSize(e, t) {
+ let n = an.copy(t).multiplyScalar(.5);
+ return this.min.copy(e).sub(n), this.max.copy(e).add(n), this;
+ }
+ setFromObject(e, t = !1) {
+ return this.makeEmpty(), this.expandByObject(e, t);
+ }
+ clone() {
+ return new this.constructor().copy(this);
+ }
+ copy(e) {
+ return this.min.copy(e.min), this.max.copy(e.max), this;
+ }
+ makeEmpty() {
+ return this.min.x = this.min.y = this.min.z = Infinity, this.max.x = this.max.y = this.max.z = -Infinity, this;
+ }
+ isEmpty() {
+ return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
+ }
+ getCenter(e) {
+ return this.isEmpty() ? e.set(0, 0, 0) : e.addVectors(this.min, this.max).multiplyScalar(.5);
+ }
+ getSize(e) {
+ return this.isEmpty() ? e.set(0, 0, 0) : e.subVectors(this.max, this.min);
+ }
+ expandByPoint(e) {
+ return this.min.min(e), this.max.max(e), this;
+ }
+ expandByVector(e) {
+ return this.min.sub(e), this.max.add(e), this;
+ }
+ expandByScalar(e) {
+ return this.min.addScalar(-e), this.max.addScalar(e), this;
+ }
+ expandByObject(e, t = !1) {
+ e.updateWorldMatrix(!1, !1);
+ let n = e.geometry;
+ if (n !== void 0) {
+ let r = n.getAttribute("position");
+ if (t === !0 && r !== void 0 && e.isInstancedMesh !== !0) for (let t = 0, n = r.count; t < n; t++) e.isMesh === !0 ? e.getVertexPosition(t, an) : an.fromBufferAttribute(r, t), an.applyMatrix4(e.matrixWorld), this.expandByPoint(an);
+ else e.boundingBox === void 0 ? (n.boundingBox === null && n.computeBoundingBox(), on.copy(n.boundingBox)) : (e.boundingBox === null && e.computeBoundingBox(), on.copy(e.boundingBox)), on.applyMatrix4(e.matrixWorld), this.union(on);
+ }
+ let r = e.children;
+ for (let e = 0, n = r.length; e < n; e++) this.expandByObject(r[e], t);
+ return this;
+ }
+ containsPoint(e) {
+ return e.x >= this.min.x && e.x <= this.max.x && e.y >= this.min.y && e.y <= this.max.y && e.z >= this.min.z && e.z <= this.max.z;
+ }
+ containsBox(e) {
+ return this.min.x <= e.min.x && e.max.x <= this.max.x && this.min.y <= e.min.y && e.max.y <= this.max.y && this.min.z <= e.min.z && e.max.z <= this.max.z;
+ }
+ getParameter(e, t) {
+ return t.set((e.x - this.min.x) / (this.max.x - this.min.x), (e.y - this.min.y) / (this.max.y - this.min.y), (e.z - this.min.z) / (this.max.z - this.min.z));
+ }
+ intersectsBox(e) {
+ return e.max.x >= this.min.x && e.min.x <= this.max.x && e.max.y >= this.min.y && e.min.y <= this.max.y && e.max.z >= this.min.z && e.min.z <= this.max.z;
+ }
+ intersectsSphere(e) {
+ return this.clampPoint(e.center, an), an.distanceToSquared(e.center) <= e.radius * e.radius;
+ }
+ intersectsPlane(e) {
+ let t, n;
+ return e.normal.x > 0 ? (t = e.normal.x * this.min.x, n = e.normal.x * this.max.x) : (t = e.normal.x * this.max.x, n = e.normal.x * this.min.x), e.normal.y > 0 ? (t += e.normal.y * this.min.y, n += e.normal.y * this.max.y) : (t += e.normal.y * this.max.y, n += e.normal.y * this.min.y), e.normal.z > 0 ? (t += e.normal.z * this.min.z, n += e.normal.z * this.max.z) : (t += e.normal.z * this.max.z, n += e.normal.z * this.min.z), t <= -e.constant && n >= -e.constant;
+ }
+ intersectsTriangle(e) {
+ if (this.isEmpty()) return !1;
+ this.getCenter(pn), mn.subVectors(this.max, pn), sn.subVectors(e.a, pn), cn.subVectors(e.b, pn), ln.subVectors(e.c, pn), un.subVectors(cn, sn), dn.subVectors(ln, cn), fn.subVectors(sn, ln);
+ let t = [
+ 0,
+ -un.z,
+ un.y,
+ 0,
+ -dn.z,
+ dn.y,
+ 0,
+ -fn.z,
+ fn.y,
+ un.z,
+ 0,
+ -un.x,
+ dn.z,
+ 0,
+ -dn.x,
+ fn.z,
+ 0,
+ -fn.x,
+ -un.y,
+ un.x,
+ 0,
+ -dn.y,
+ dn.x,
+ 0,
+ -fn.y,
+ fn.x,
+ 0
+ ];
+ return !_n(t, sn, cn, ln, mn) || (t = [
+ 1,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ 0,
+ 0,
+ 1
+ ], !_n(t, sn, cn, ln, mn)) ? !1 : (hn.crossVectors(un, dn), t = [
+ hn.x,
+ hn.y,
+ hn.z
+ ], _n(t, sn, cn, ln, mn));
+ }
+ clampPoint(e, t) {
+ return t.copy(e).clamp(this.min, this.max);
+ }
+ distanceToPoint(e) {
+ return this.clampPoint(e, an).distanceTo(e);
+ }
+ getBoundingSphere(e) {
+ return this.isEmpty() ? e.makeEmpty() : (this.getCenter(e.center), e.radius = this.getSize(an).length() * .5), e;
+ }
+ intersect(e) {
+ return this.min.max(e.min), this.max.min(e.max), this.isEmpty() && this.makeEmpty(), this;
+ }
+ union(e) {
+ return this.min.min(e.min), this.max.max(e.max), this;
+ }
+ applyMatrix4(e) {
+ return this.isEmpty() ? this : (rn[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(e), rn[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(e), rn[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(e), rn[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(e), rn[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(e), rn[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(e), rn[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(e), rn[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(e), this.setFromPoints(rn), this);
+ }
+ translate(e) {
+ return this.min.add(e), this.max.add(e), this;
+ }
+ equals(e) {
+ return e.min.equals(this.min) && e.max.equals(this.max);
+ }
+}, rn = [
+ /* @__PURE__ */ new R(),
+ /* @__PURE__ */ new R(),
+ /* @__PURE__ */ new R(),
+ /* @__PURE__ */ new R(),
+ /* @__PURE__ */ new R(),
+ /* @__PURE__ */ new R(),
+ /* @__PURE__ */ new R(),
+ /* @__PURE__ */ new R()
+], an = /* @__PURE__ */ new R(), on = /* @__PURE__ */ new nn(), sn = /* @__PURE__ */ new R(), cn = /* @__PURE__ */ new R(), ln = /* @__PURE__ */ new R(), un = /* @__PURE__ */ new R(), dn = /* @__PURE__ */ new R(), fn = /* @__PURE__ */ new R(), pn = /* @__PURE__ */ new R(), mn = /* @__PURE__ */ new R(), hn = /* @__PURE__ */ new R(), gn = /* @__PURE__ */ new R();
+function _n(e, t, n, r, i) {
+ for (let a = 0, o = e.length - 3; a <= o; a += 3) {
+ gn.fromArray(e, a);
+ let o = i.x * Math.abs(gn.x) + i.y * Math.abs(gn.y) + i.z * Math.abs(gn.z), s = t.dot(gn), c = n.dot(gn), l = r.dot(gn);
+ if (Math.max(-Math.max(s, c, l), Math.min(s, c, l)) > o) return !1;
+ }
+ return !0;
+}
+var vn = /* @__PURE__ */ new nn(), yn = /* @__PURE__ */ new R(), bn = /* @__PURE__ */ new R(), xn = class {
+ constructor(e = new R(), t = -1) {
+ this.isSphere = !0, this.center = e, this.radius = t;
+ }
+ set(e, t) {
+ return this.center.copy(e), this.radius = t, this;
+ }
+ setFromPoints(e, t) {
+ let n = this.center;
+ t === void 0 ? vn.setFromPoints(e).getCenter(n) : n.copy(t);
+ let r = 0;
+ for (let t = 0, i = e.length; t < i; t++) r = Math.max(r, n.distanceToSquared(e[t]));
+ return this.radius = Math.sqrt(r), this;
+ }
+ copy(e) {
+ return this.center.copy(e.center), this.radius = e.radius, this;
+ }
+ isEmpty() {
+ return this.radius < 0;
+ }
+ makeEmpty() {
+ return this.center.set(0, 0, 0), this.radius = -1, this;
+ }
+ containsPoint(e) {
+ return e.distanceToSquared(this.center) <= this.radius * this.radius;
+ }
+ distanceToPoint(e) {
+ return e.distanceTo(this.center) - this.radius;
+ }
+ intersectsSphere(e) {
+ let t = this.radius + e.radius;
+ return e.center.distanceToSquared(this.center) <= t * t;
+ }
+ intersectsBox(e) {
+ return e.intersectsSphere(this);
+ }
+ intersectsPlane(e) {
+ return Math.abs(e.distanceToPoint(this.center)) <= this.radius;
+ }
+ clampPoint(e, t) {
+ let n = this.center.distanceToSquared(e);
+ return t.copy(e), n > this.radius * this.radius && (t.sub(this.center).normalize(), t.multiplyScalar(this.radius).add(this.center)), t;
+ }
+ getBoundingBox(e) {
+ return this.isEmpty() ? (e.makeEmpty(), e) : (e.set(this.center, this.center), e.expandByScalar(this.radius), e);
+ }
+ applyMatrix4(e) {
+ return this.center.applyMatrix4(e), this.radius *= e.getMaxScaleOnAxis(), this;
+ }
+ translate(e) {
+ return this.center.add(e), this;
+ }
+ expandByPoint(e) {
+ if (this.isEmpty()) return this.center.copy(e), this.radius = 0, this;
+ yn.subVectors(e, this.center);
+ let t = yn.lengthSq();
+ if (t > this.radius * this.radius) {
+ let e = Math.sqrt(t), n = (e - this.radius) * .5;
+ this.center.addScaledVector(yn, n / e), this.radius += n;
+ }
+ return this;
+ }
+ union(e) {
+ return e.isEmpty() ? this : this.isEmpty() ? (this.copy(e), this) : (this.center.equals(e.center) === !0 ? this.radius = Math.max(this.radius, e.radius) : (bn.subVectors(e.center, this.center).setLength(e.radius), this.expandByPoint(yn.copy(e.center).add(bn)), this.expandByPoint(yn.copy(e.center).sub(bn))), this);
+ }
+ equals(e) {
+ return e.center.equals(this.center) && e.radius === this.radius;
+ }
+ clone() {
+ return new this.constructor().copy(this);
+ }
+}, Sn = /* @__PURE__ */ new R(), Cn = /* @__PURE__ */ new R(), wn = /* @__PURE__ */ new R(), Tn = /* @__PURE__ */ new R(), En = /* @__PURE__ */ new R(), Dn = /* @__PURE__ */ new R(), On = /* @__PURE__ */ new R(), kn = class {
+ constructor(e = new R(), t = new R(0, 0, -1)) {
+ this.origin = e, this.direction = t;
+ }
+ set(e, t) {
+ return this.origin.copy(e), this.direction.copy(t), this;
+ }
+ copy(e) {
+ return this.origin.copy(e.origin), this.direction.copy(e.direction), this;
+ }
+ at(e, t) {
+ return t.copy(this.origin).addScaledVector(this.direction, e);
+ }
+ lookAt(e) {
+ return this.direction.copy(e).sub(this.origin).normalize(), this;
+ }
+ recast(e) {
+ return this.origin.copy(this.at(e, Sn)), this;
+ }
+ closestPointToPoint(e, t) {
+ t.subVectors(e, this.origin);
+ let n = t.dot(this.direction);
+ return n < 0 ? t.copy(this.origin) : t.copy(this.origin).addScaledVector(this.direction, n);
+ }
+ distanceToPoint(e) {
+ return Math.sqrt(this.distanceSqToPoint(e));
+ }
+ distanceSqToPoint(e) {
+ let t = Sn.subVectors(e, this.origin).dot(this.direction);
+ return t < 0 ? this.origin.distanceToSquared(e) : (Sn.copy(this.origin).addScaledVector(this.direction, t), Sn.distanceToSquared(e));
+ }
+ distanceSqToSegment(e, t, n, r) {
+ Cn.copy(e).add(t).multiplyScalar(.5), wn.copy(t).sub(e).normalize(), Tn.copy(this.origin).sub(Cn);
+ let i = e.distanceTo(t) * .5, a = -this.direction.dot(wn), o = Tn.dot(this.direction), s = -Tn.dot(wn), c = Tn.lengthSq(), l = Math.abs(1 - a * a), u, d, f, p;
+ if (l > 0) if (u = a * s - o, d = a * o - s, p = i * l, u >= 0) if (d >= -p) if (d <= p) {
+ let e = 1 / l;
+ u *= e, d *= e, f = u * (u + a * d + 2 * o) + d * (a * u + d + 2 * s) + c;
+ } else d = i, u = Math.max(0, -(a * d + o)), f = -u * u + d * (d + 2 * s) + c;
+ else d = -i, u = Math.max(0, -(a * d + o)), f = -u * u + d * (d + 2 * s) + c;
+ else d <= -p ? (u = Math.max(0, -(-a * i + o)), d = u > 0 ? -i : Math.min(Math.max(-i, -s), i), f = -u * u + d * (d + 2 * s) + c) : d <= p ? (u = 0, d = Math.min(Math.max(-i, -s), i), f = d * (d + 2 * s) + c) : (u = Math.max(0, -(a * i + o)), d = u > 0 ? i : Math.min(Math.max(-i, -s), i), f = -u * u + d * (d + 2 * s) + c);
+ else d = a > 0 ? -i : i, u = Math.max(0, -(a * d + o)), f = -u * u + d * (d + 2 * s) + c;
+ return n && n.copy(this.origin).addScaledVector(this.direction, u), r && r.copy(Cn).addScaledVector(wn, d), f;
+ }
+ intersectSphere(e, t) {
+ Sn.subVectors(e.center, this.origin);
+ let n = Sn.dot(this.direction), r = Sn.dot(Sn) - n * n, i = e.radius * e.radius;
+ if (r > i) return null;
+ let a = Math.sqrt(i - r), o = n - a, s = n + a;
+ return s < 0 ? null : o < 0 ? this.at(s, t) : this.at(o, t);
+ }
+ intersectsSphere(e) {
+ return this.distanceSqToPoint(e.center) <= e.radius * e.radius;
+ }
+ distanceToPlane(e) {
+ let t = e.normal.dot(this.direction);
+ if (t === 0) return e.distanceToPoint(this.origin) === 0 ? 0 : null;
+ let n = -(this.origin.dot(e.normal) + e.constant) / t;
+ return n >= 0 ? n : null;
+ }
+ intersectPlane(e, t) {
+ let n = this.distanceToPlane(e);
+ return n === null ? null : this.at(n, t);
+ }
+ intersectsPlane(e) {
+ let t = e.distanceToPoint(this.origin);
+ return t === 0 || e.normal.dot(this.direction) * t < 0;
+ }
+ intersectBox(e, t) {
+ let n, r, i, a, o, s, c = 1 / this.direction.x, l = 1 / this.direction.y, u = 1 / this.direction.z, d = this.origin;
+ return c >= 0 ? (n = (e.min.x - d.x) * c, r = (e.max.x - d.x) * c) : (n = (e.max.x - d.x) * c, r = (e.min.x - d.x) * c), l >= 0 ? (i = (e.min.y - d.y) * l, a = (e.max.y - d.y) * l) : (i = (e.max.y - d.y) * l, a = (e.min.y - d.y) * l), n > a || i > r || ((i > n || isNaN(n)) && (n = i), (a < r || isNaN(r)) && (r = a), u >= 0 ? (o = (e.min.z - d.z) * u, s = (e.max.z - d.z) * u) : (o = (e.max.z - d.z) * u, s = (e.min.z - d.z) * u), n > s || o > r) || ((o > n || n !== n) && (n = o), (s < r || r !== r) && (r = s), r < 0) ? null : this.at(n >= 0 ? n : r, t);
+ }
+ intersectsBox(e) {
+ return this.intersectBox(e, Sn) !== null;
+ }
+ intersectTriangle(e, t, n, r, i) {
+ En.subVectors(t, e), Dn.subVectors(n, e), On.crossVectors(En, Dn);
+ let a = this.direction.dot(On), o;
+ if (a > 0) {
+ if (r) return null;
+ o = 1;
+ } else if (a < 0) o = -1, a = -a;
+ else return null;
+ Tn.subVectors(this.origin, e);
+ let s = o * this.direction.dot(Dn.crossVectors(Tn, Dn));
+ if (s < 0) return null;
+ let c = o * this.direction.dot(En.cross(Tn));
+ if (c < 0 || s + c > a) return null;
+ let l = -o * Tn.dot(On);
+ return l < 0 ? null : this.at(l / a, i);
+ }
+ applyMatrix4(e) {
+ return this.origin.applyMatrix4(e), this.direction.transformDirection(e), this;
+ }
+ equals(e) {
+ return e.origin.equals(this.origin) && e.direction.equals(this.direction);
+ }
+ clone() {
+ return new this.constructor().copy(this);
+ }
+}, z = class e {
+ constructor(t, n, r, i, a, o, s, c, l, u, d, f, p, m, h, g) {
+ e.prototype.isMatrix4 = !0, this.elements = [
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1
+ ], t !== void 0 && this.set(t, n, r, i, a, o, s, c, l, u, d, f, p, m, h, g);
+ }
+ set(e, t, n, r, i, a, o, s, c, l, u, d, f, p, m, h) {
+ let g = this.elements;
+ return g[0] = e, g[4] = t, g[8] = n, g[12] = r, g[1] = i, g[5] = a, g[9] = o, g[13] = s, g[2] = c, g[6] = l, g[10] = u, g[14] = d, g[3] = f, g[7] = p, g[11] = m, g[15] = h, this;
+ }
+ identity() {
+ return this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1), this;
+ }
+ clone() {
+ return new e().fromArray(this.elements);
+ }
+ copy(e) {
+ let t = this.elements, n = e.elements;
+ return t[0] = n[0], t[1] = n[1], t[2] = n[2], t[3] = n[3], t[4] = n[4], t[5] = n[5], t[6] = n[6], t[7] = n[7], t[8] = n[8], t[9] = n[9], t[10] = n[10], t[11] = n[11], t[12] = n[12], t[13] = n[13], t[14] = n[14], t[15] = n[15], this;
+ }
+ copyPosition(e) {
+ let t = this.elements, n = e.elements;
+ return t[12] = n[12], t[13] = n[13], t[14] = n[14], this;
+ }
+ setFromMatrix3(e) {
+ let t = e.elements;
+ return this.set(t[0], t[3], t[6], 0, t[1], t[4], t[7], 0, t[2], t[5], t[8], 0, 0, 0, 0, 1), this;
+ }
+ extractBasis(e, t, n) {
+ return e.setFromMatrixColumn(this, 0), t.setFromMatrixColumn(this, 1), n.setFromMatrixColumn(this, 2), this;
+ }
+ makeBasis(e, t, n) {
+ return this.set(e.x, t.x, n.x, 0, e.y, t.y, n.y, 0, e.z, t.z, n.z, 0, 0, 0, 0, 1), this;
+ }
+ extractRotation(e) {
+ let t = this.elements, n = e.elements, r = 1 / An.setFromMatrixColumn(e, 0).length(), i = 1 / An.setFromMatrixColumn(e, 1).length(), a = 1 / An.setFromMatrixColumn(e, 2).length();
+ return t[0] = n[0] * r, t[1] = n[1] * r, t[2] = n[2] * r, t[3] = 0, t[4] = n[4] * i, t[5] = n[5] * i, t[6] = n[6] * i, t[7] = 0, t[8] = n[8] * a, t[9] = n[9] * a, t[10] = n[10] * a, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, this;
+ }
+ makeRotationFromEuler(e) {
+ let t = this.elements, n = e.x, r = e.y, i = e.z, a = Math.cos(n), o = Math.sin(n), s = Math.cos(r), c = Math.sin(r), l = Math.cos(i), u = Math.sin(i);
+ if (e.order === "XYZ") {
+ let e = a * l, n = a * u, r = o * l, i = o * u;
+ t[0] = s * l, t[4] = -s * u, t[8] = c, t[1] = n + r * c, t[5] = e - i * c, t[9] = -o * s, t[2] = i - e * c, t[6] = r + n * c, t[10] = a * s;
+ } else if (e.order === "YXZ") {
+ let e = s * l, n = s * u, r = c * l, i = c * u;
+ t[0] = e + i * o, t[4] = r * o - n, t[8] = a * c, t[1] = a * u, t[5] = a * l, t[9] = -o, t[2] = n * o - r, t[6] = i + e * o, t[10] = a * s;
+ } else if (e.order === "ZXY") {
+ let e = s * l, n = s * u, r = c * l, i = c * u;
+ t[0] = e - i * o, t[4] = -a * u, t[8] = r + n * o, t[1] = n + r * o, t[5] = a * l, t[9] = i - e * o, t[2] = -a * c, t[6] = o, t[10] = a * s;
+ } else if (e.order === "ZYX") {
+ let e = a * l, n = a * u, r = o * l, i = o * u;
+ t[0] = s * l, t[4] = r * c - n, t[8] = e * c + i, t[1] = s * u, t[5] = i * c + e, t[9] = n * c - r, t[2] = -c, t[6] = o * s, t[10] = a * s;
+ } else if (e.order === "YZX") {
+ let e = a * s, n = a * c, r = o * s, i = o * c;
+ t[0] = s * l, t[4] = i - e * u, t[8] = r * u + n, t[1] = u, t[5] = a * l, t[9] = -o * l, t[2] = -c * l, t[6] = n * u + r, t[10] = e - i * u;
+ } else if (e.order === "XZY") {
+ let e = a * s, n = a * c, r = o * s, i = o * c;
+ t[0] = s * l, t[4] = -u, t[8] = c * l, t[1] = e * u + i, t[5] = a * l, t[9] = n * u - r, t[2] = r * u - n, t[6] = o * l, t[10] = i * u + e;
+ }
+ return t[3] = 0, t[7] = 0, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, this;
+ }
+ makeRotationFromQuaternion(e) {
+ return this.compose(Mn, e, Nn);
+ }
+ lookAt(e, t, n) {
+ let r = this.elements;
+ return In.subVectors(e, t), In.lengthSq() === 0 && (In.z = 1), In.normalize(), Pn.crossVectors(n, In), Pn.lengthSq() === 0 && (Math.abs(n.z) === 1 ? In.x += 1e-4 : In.z += 1e-4, In.normalize(), Pn.crossVectors(n, In)), Pn.normalize(), Fn.crossVectors(In, Pn), r[0] = Pn.x, r[4] = Fn.x, r[8] = In.x, r[1] = Pn.y, r[5] = Fn.y, r[9] = In.y, r[2] = Pn.z, r[6] = Fn.z, r[10] = In.z, this;
+ }
+ multiply(e) {
+ return this.multiplyMatrices(this, e);
+ }
+ premultiply(e) {
+ return this.multiplyMatrices(e, this);
+ }
+ multiplyMatrices(e, t) {
+ let n = e.elements, r = t.elements, i = this.elements, a = n[0], o = n[4], s = n[8], c = n[12], l = n[1], u = n[5], d = n[9], f = n[13], p = n[2], m = n[6], h = n[10], g = n[14], _ = n[3], v = n[7], y = n[11], b = n[15], x = r[0], S = r[4], C = r[8], w = r[12], T = r[1], E = r[5], D = r[9], O = r[13], k = r[2], ee = r[6], A = r[10], te = r[14], ne = r[3], re = r[7], ie = r[11], ae = r[15];
+ return i[0] = a * x + o * T + s * k + c * ne, i[4] = a * S + o * E + s * ee + c * re, i[8] = a * C + o * D + s * A + c * ie, i[12] = a * w + o * O + s * te + c * ae, i[1] = l * x + u * T + d * k + f * ne, i[5] = l * S + u * E + d * ee + f * re, i[9] = l * C + u * D + d * A + f * ie, i[13] = l * w + u * O + d * te + f * ae, i[2] = p * x + m * T + h * k + g * ne, i[6] = p * S + m * E + h * ee + g * re, i[10] = p * C + m * D + h * A + g * ie, i[14] = p * w + m * O + h * te + g * ae, i[3] = _ * x + v * T + y * k + b * ne, i[7] = _ * S + v * E + y * ee + b * re, i[11] = _ * C + v * D + y * A + b * ie, i[15] = _ * w + v * O + y * te + b * ae, this;
+ }
+ multiplyScalar(e) {
+ let t = this.elements;
+ return t[0] *= e, t[4] *= e, t[8] *= e, t[12] *= e, t[1] *= e, t[5] *= e, t[9] *= e, t[13] *= e, t[2] *= e, t[6] *= e, t[10] *= e, t[14] *= e, t[3] *= e, t[7] *= e, t[11] *= e, t[15] *= e, this;
+ }
+ determinant() {
+ let e = this.elements, t = e[0], n = e[4], r = e[8], i = e[12], a = e[1], o = e[5], s = e[9], c = e[13], l = e[2], u = e[6], d = e[10], f = e[14], p = e[3], m = e[7], h = e[11], g = e[15];
+ return p * (+i * s * u - r * c * u - i * o * d + n * c * d + r * o * f - n * s * f) + m * (+t * s * f - t * c * d + i * a * d - r * a * f + r * c * l - i * s * l) + h * (+t * c * u - t * o * f - i * a * u + n * a * f + i * o * l - n * c * l) + g * (-r * o * l - t * s * u + t * o * d + r * a * u - n * a * d + n * s * l);
+ }
+ transpose() {
+ let e = this.elements, t;
+ return t = e[1], e[1] = e[4], e[4] = t, t = e[2], e[2] = e[8], e[8] = t, t = e[6], e[6] = e[9], e[9] = t, t = e[3], e[3] = e[12], e[12] = t, t = e[7], e[7] = e[13], e[13] = t, t = e[11], e[11] = e[14], e[14] = t, this;
+ }
+ setPosition(e, t, n) {
+ let r = this.elements;
+ return e.isVector3 ? (r[12] = e.x, r[13] = e.y, r[14] = e.z) : (r[12] = e, r[13] = t, r[14] = n), this;
+ }
+ invert() {
+ let e = this.elements, t = e[0], n = e[1], r = e[2], i = e[3], a = e[4], o = e[5], s = e[6], c = e[7], l = e[8], u = e[9], d = e[10], f = e[11], p = e[12], m = e[13], h = e[14], g = e[15], _ = u * h * c - m * d * c + m * s * f - o * h * f - u * s * g + o * d * g, v = p * d * c - l * h * c - p * s * f + a * h * f + l * s * g - a * d * g, y = l * m * c - p * u * c + p * o * f - a * m * f - l * o * g + a * u * g, b = p * u * s - l * m * s - p * o * d + a * m * d + l * o * h - a * u * h, x = t * _ + n * v + r * y + i * b;
+ if (x === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
+ let S = 1 / x;
+ return e[0] = _ * S, e[1] = (m * d * i - u * h * i - m * r * f + n * h * f + u * r * g - n * d * g) * S, e[2] = (o * h * i - m * s * i + m * r * c - n * h * c - o * r * g + n * s * g) * S, e[3] = (u * s * i - o * d * i - u * r * c + n * d * c + o * r * f - n * s * f) * S, e[4] = v * S, e[5] = (l * h * i - p * d * i + p * r * f - t * h * f - l * r * g + t * d * g) * S, e[6] = (p * s * i - a * h * i - p * r * c + t * h * c + a * r * g - t * s * g) * S, e[7] = (a * d * i - l * s * i + l * r * c - t * d * c - a * r * f + t * s * f) * S, e[8] = y * S, e[9] = (p * u * i - l * m * i - p * n * f + t * m * f + l * n * g - t * u * g) * S, e[10] = (a * m * i - p * o * i + p * n * c - t * m * c - a * n * g + t * o * g) * S, e[11] = (l * o * i - a * u * i - l * n * c + t * u * c + a * n * f - t * o * f) * S, e[12] = b * S, e[13] = (l * m * r - p * u * r + p * n * d - t * m * d - l * n * h + t * u * h) * S, e[14] = (p * o * r - a * m * r - p * n * s + t * m * s + a * n * h - t * o * h) * S, e[15] = (a * u * r - l * o * r + l * n * s - t * u * s - a * n * d + t * o * d) * S, this;
+ }
+ scale(e) {
+ let t = this.elements, n = e.x, r = e.y, i = e.z;
+ return t[0] *= n, t[4] *= r, t[8] *= i, t[1] *= n, t[5] *= r, t[9] *= i, t[2] *= n, t[6] *= r, t[10] *= i, t[3] *= n, t[7] *= r, t[11] *= i, this;
+ }
+ getMaxScaleOnAxis() {
+ let e = this.elements, t = e[0] * e[0] + e[1] * e[1] + e[2] * e[2], n = e[4] * e[4] + e[5] * e[5] + e[6] * e[6], r = e[8] * e[8] + e[9] * e[9] + e[10] * e[10];
+ return Math.sqrt(Math.max(t, n, r));
+ }
+ makeTranslation(e, t, n) {
+ return e.isVector3 ? this.set(1, 0, 0, e.x, 0, 1, 0, e.y, 0, 0, 1, e.z, 0, 0, 0, 1) : this.set(1, 0, 0, e, 0, 1, 0, t, 0, 0, 1, n, 0, 0, 0, 1), this;
+ }
+ makeRotationX(e) {
+ let t = Math.cos(e), n = Math.sin(e);
+ return this.set(1, 0, 0, 0, 0, t, -n, 0, 0, n, t, 0, 0, 0, 0, 1), this;
+ }
+ makeRotationY(e) {
+ let t = Math.cos(e), n = Math.sin(e);
+ return this.set(t, 0, n, 0, 0, 1, 0, 0, -n, 0, t, 0, 0, 0, 0, 1), this;
+ }
+ makeRotationZ(e) {
+ let t = Math.cos(e), n = Math.sin(e);
+ return this.set(t, -n, 0, 0, n, t, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1), this;
+ }
+ makeRotationAxis(e, t) {
+ let n = Math.cos(t), r = Math.sin(t), i = 1 - n, a = e.x, o = e.y, s = e.z, c = i * a, l = i * o;
+ return this.set(c * a + n, c * o - r * s, c * s + r * o, 0, c * o + r * s, l * o + n, l * s - r * a, 0, c * s - r * o, l * s + r * a, i * s * s + n, 0, 0, 0, 0, 1), this;
+ }
+ makeScale(e, t, n) {
+ return this.set(e, 0, 0, 0, 0, t, 0, 0, 0, 0, n, 0, 0, 0, 0, 1), this;
+ }
+ makeShear(e, t, n, r, i, a) {
+ return this.set(1, n, i, 0, e, 1, a, 0, t, r, 1, 0, 0, 0, 0, 1), this;
+ }
+ compose(e, t, n) {
+ let r = this.elements, i = t._x, a = t._y, o = t._z, s = t._w, c = i + i, l = a + a, u = o + o, d = i * c, f = i * l, p = i * u, m = a * l, h = a * u, g = o * u, _ = s * c, v = s * l, y = s * u, b = n.x, x = n.y, S = n.z;
+ return r[0] = (1 - (m + g)) * b, r[1] = (f + y) * b, r[2] = (p - v) * b, r[3] = 0, r[4] = (f - y) * x, r[5] = (1 - (d + g)) * x, r[6] = (h + _) * x, r[7] = 0, r[8] = (p + v) * S, r[9] = (h - _) * S, r[10] = (1 - (d + m)) * S, r[11] = 0, r[12] = e.x, r[13] = e.y, r[14] = e.z, r[15] = 1, this;
+ }
+ decompose(e, t, n) {
+ let r = this.elements, i = An.set(r[0], r[1], r[2]).length(), a = An.set(r[4], r[5], r[6]).length(), o = An.set(r[8], r[9], r[10]).length();
+ this.determinant() < 0 && (i = -i), e.x = r[12], e.y = r[13], e.z = r[14], jn.copy(this);
+ let s = 1 / i, c = 1 / a, l = 1 / o;
+ return jn.elements[0] *= s, jn.elements[1] *= s, jn.elements[2] *= s, jn.elements[4] *= c, jn.elements[5] *= c, jn.elements[6] *= c, jn.elements[8] *= l, jn.elements[9] *= l, jn.elements[10] *= l, t.setFromRotationMatrix(jn), n.x = i, n.y = a, n.z = o, this;
+ }
+ makePerspective(e, t, n, r, i, a, o = Ze) {
+ let s = this.elements, c = 2 * i / (t - e), l = 2 * i / (n - r), u = (t + e) / (t - e), d = (n + r) / (n - r), f, p;
+ if (o === 2e3) f = -(a + i) / (a - i), p = -2 * a * i / (a - i);
+ else if (o === 2001) f = -a / (a - i), p = -a * i / (a - i);
+ else throw Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + o);
+ return s[0] = c, s[4] = 0, s[8] = u, s[12] = 0, s[1] = 0, s[5] = l, s[9] = d, s[13] = 0, s[2] = 0, s[6] = 0, s[10] = f, s[14] = p, s[3] = 0, s[7] = 0, s[11] = -1, s[15] = 0, this;
+ }
+ makeOrthographic(e, t, n, r, i, a, o = Ze) {
+ let s = this.elements, c = 1 / (t - e), l = 1 / (n - r), u = 1 / (a - i), d = (t + e) * c, f = (n + r) * l, p, m;
+ if (o === 2e3) p = (a + i) * u, m = -2 * u;
+ else if (o === 2001) p = i * u, m = -1 * u;
+ else throw Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + o);
+ return s[0] = 2 * c, s[4] = 0, s[8] = 0, s[12] = -d, s[1] = 0, s[5] = 2 * l, s[9] = 0, s[13] = -f, s[2] = 0, s[6] = 0, s[10] = m, s[14] = -p, s[3] = 0, s[7] = 0, s[11] = 0, s[15] = 1, this;
+ }
+ equals(e) {
+ let t = this.elements, n = e.elements;
+ for (let e = 0; e < 16; e++) if (t[e] !== n[e]) return !1;
+ return !0;
+ }
+ fromArray(e, t = 0) {
+ for (let n = 0; n < 16; n++) this.elements[n] = e[n + t];
+ return this;
+ }
+ toArray(e = [], t = 0) {
+ let n = this.elements;
+ return e[t] = n[0], e[t + 1] = n[1], e[t + 2] = n[2], e[t + 3] = n[3], e[t + 4] = n[4], e[t + 5] = n[5], e[t + 6] = n[6], e[t + 7] = n[7], e[t + 8] = n[8], e[t + 9] = n[9], e[t + 10] = n[10], e[t + 11] = n[11], e[t + 12] = n[12], e[t + 13] = n[13], e[t + 14] = n[14], e[t + 15] = n[15], e;
+ }
+}, An = /* @__PURE__ */ new R(), jn = /* @__PURE__ */ new z(), Mn = /* @__PURE__ */ new R(0, 0, 0), Nn = /* @__PURE__ */ new R(1, 1, 1), Pn = /* @__PURE__ */ new R(), Fn = /* @__PURE__ */ new R(), In = /* @__PURE__ */ new R(), Ln = /* @__PURE__ */ new z(), Rn = /* @__PURE__ */ new $t(), zn = class e {
+ constructor(t = 0, n = 0, r = 0, i = e.DEFAULT_ORDER) {
+ this.isEuler = !0, this._x = t, this._y = n, this._z = r, this._order = i;
+ }
+ get x() {
+ return this._x;
+ }
+ set x(e) {
+ this._x = e, this._onChangeCallback();
+ }
+ get y() {
+ return this._y;
+ }
+ set y(e) {
+ this._y = e, this._onChangeCallback();
+ }
+ get z() {
+ return this._z;
+ }
+ set z(e) {
+ this._z = e, this._onChangeCallback();
+ }
+ get order() {
+ return this._order;
+ }
+ set order(e) {
+ this._order = e, this._onChangeCallback();
+ }
+ set(e, t, n, r = this._order) {
+ return this._x = e, this._y = t, this._z = n, this._order = r, this._onChangeCallback(), this;
+ }
+ clone() {
+ return new this.constructor(this._x, this._y, this._z, this._order);
+ }
+ copy(e) {
+ return this._x = e._x, this._y = e._y, this._z = e._z, this._order = e._order, this._onChangeCallback(), this;
+ }
+ setFromRotationMatrix(e, t = this._order, n = !0) {
+ let r = e.elements, i = r[0], a = r[4], o = r[8], s = r[1], c = r[5], l = r[9], u = r[2], d = r[6], f = r[10];
+ switch (t) {
+ case "XYZ":
+ this._y = Math.asin(I(o, -1, 1)), Math.abs(o) < .9999999 ? (this._x = Math.atan2(-l, f), this._z = Math.atan2(-a, i)) : (this._x = Math.atan2(d, c), this._z = 0);
+ break;
+ case "YXZ":
+ this._x = Math.asin(-I(l, -1, 1)), Math.abs(l) < .9999999 ? (this._y = Math.atan2(o, f), this._z = Math.atan2(s, c)) : (this._y = Math.atan2(-u, i), this._z = 0);
+ break;
+ case "ZXY":
+ this._x = Math.asin(I(d, -1, 1)), Math.abs(d) < .9999999 ? (this._y = Math.atan2(-u, f), this._z = Math.atan2(-a, c)) : (this._y = 0, this._z = Math.atan2(s, i));
+ break;
+ case "ZYX":
+ this._y = Math.asin(-I(u, -1, 1)), Math.abs(u) < .9999999 ? (this._x = Math.atan2(d, f), this._z = Math.atan2(s, i)) : (this._x = 0, this._z = Math.atan2(-a, c));
+ break;
+ case "YZX":
+ this._z = Math.asin(I(s, -1, 1)), Math.abs(s) < .9999999 ? (this._x = Math.atan2(-l, c), this._y = Math.atan2(-u, i)) : (this._x = 0, this._y = Math.atan2(o, f));
+ break;
+ case "XZY":
+ this._z = Math.asin(-I(a, -1, 1)), Math.abs(a) < .9999999 ? (this._x = Math.atan2(d, c), this._y = Math.atan2(o, i)) : (this._x = Math.atan2(-l, f), this._y = 0);
+ break;
+ default: console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + t);
+ }
+ return this._order = t, n === !0 && this._onChangeCallback(), this;
+ }
+ setFromQuaternion(e, t, n) {
+ return Ln.makeRotationFromQuaternion(e), this.setFromRotationMatrix(Ln, t, n);
+ }
+ setFromVector3(e, t = this._order) {
+ return this.set(e.x, e.y, e.z, t);
+ }
+ reorder(e) {
+ return Rn.setFromEuler(this), this.setFromQuaternion(Rn, e);
+ }
+ equals(e) {
+ return e._x === this._x && e._y === this._y && e._z === this._z && e._order === this._order;
+ }
+ fromArray(e) {
+ return this._x = e[0], this._y = e[1], this._z = e[2], e[3] !== void 0 && (this._order = e[3]), this._onChangeCallback(), this;
+ }
+ toArray(e = [], t = 0) {
+ return e[t] = this._x, e[t + 1] = this._y, e[t + 2] = this._z, e[t + 3] = this._order, e;
+ }
+ _onChange(e) {
+ return this._onChangeCallback = e, this;
+ }
+ _onChangeCallback() {}
+ *[Symbol.iterator]() {
+ yield this._x, yield this._y, yield this._z, yield this._order;
+ }
+};
+zn.DEFAULT_ORDER = "XYZ";
+var Bn = class {
+ constructor() {
+ this.mask = 1;
+ }
+ set(e) {
+ this.mask = (1 << e | 0) >>> 0;
+ }
+ enable(e) {
+ this.mask |= 1 << e | 0;
+ }
+ enableAll() {
+ this.mask = -1;
+ }
+ toggle(e) {
+ this.mask ^= 1 << e | 0;
+ }
+ disable(e) {
+ this.mask &= ~(1 << e | 0);
+ }
+ disableAll() {
+ this.mask = 0;
+ }
+ test(e) {
+ return (this.mask & e.mask) !== 0;
+ }
+ isEnabled(e) {
+ return (this.mask & (1 << e | 0)) != 0;
+ }
+}, Vn = 0, Hn = /* @__PURE__ */ new R(), Un = /* @__PURE__ */ new $t(), Wn = /* @__PURE__ */ new z(), Gn = /* @__PURE__ */ new R(), Kn = /* @__PURE__ */ new R(), qn = /* @__PURE__ */ new R(), Jn = /* @__PURE__ */ new $t(), Yn = /* @__PURE__ */ new R(1, 0, 0), Xn = /* @__PURE__ */ new R(0, 1, 0), Zn = /* @__PURE__ */ new R(0, 0, 1), Qn = { type: "added" }, $n = { type: "removed" }, er = {
+ type: "childadded",
+ child: null
+}, tr = {
+ type: "childremoved",
+ child: null
+}, nr = class e extends Qe {
+ constructor() {
+ super(), this.isObject3D = !0, Object.defineProperty(this, "id", { value: Vn++ }), this.uuid = rt(), this.name = "", this.type = "Object3D", this.parent = null, this.children = [], this.up = e.DEFAULT_UP.clone();
+ let t = new R(), n = new zn(), r = new $t(), i = new R(1, 1, 1);
+ function a() {
+ r.setFromEuler(n, !1);
+ }
+ function o() {
+ n.setFromQuaternion(r, void 0, !1);
+ }
+ n._onChange(a), r._onChange(o), Object.defineProperties(this, {
+ position: {
+ configurable: !0,
+ enumerable: !0,
+ value: t
+ },
+ rotation: {
+ configurable: !0,
+ enumerable: !0,
+ value: n
+ },
+ quaternion: {
+ configurable: !0,
+ enumerable: !0,
+ value: r
+ },
+ scale: {
+ configurable: !0,
+ enumerable: !0,
+ value: i
+ },
+ modelViewMatrix: { value: new z() },
+ normalMatrix: { value: new Tt() }
+ }), this.matrix = new z(), this.matrixWorld = new z(), this.matrixAutoUpdate = e.DEFAULT_MATRIX_AUTO_UPDATE, this.matrixWorldAutoUpdate = e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE, this.matrixWorldNeedsUpdate = !1, this.layers = new Bn(), this.visible = !0, this.castShadow = !1, this.receiveShadow = !1, this.frustumCulled = !0, this.renderOrder = 0, this.animations = [], this.customDepthMaterial = void 0, this.customDistanceMaterial = void 0, this.userData = {};
+ }
+ onBeforeShadow() {}
+ onAfterShadow() {}
+ onBeforeRender() {}
+ onAfterRender() {}
+ applyMatrix4(e) {
+ this.matrixAutoUpdate && this.updateMatrix(), this.matrix.premultiply(e), this.matrix.decompose(this.position, this.quaternion, this.scale);
+ }
+ applyQuaternion(e) {
+ return this.quaternion.premultiply(e), this;
+ }
+ setRotationFromAxisAngle(e, t) {
+ this.quaternion.setFromAxisAngle(e, t);
+ }
+ setRotationFromEuler(e) {
+ this.quaternion.setFromEuler(e, !0);
+ }
+ setRotationFromMatrix(e) {
+ this.quaternion.setFromRotationMatrix(e);
+ }
+ setRotationFromQuaternion(e) {
+ this.quaternion.copy(e);
+ }
+ rotateOnAxis(e, t) {
+ return Un.setFromAxisAngle(e, t), this.quaternion.multiply(Un), this;
+ }
+ rotateOnWorldAxis(e, t) {
+ return Un.setFromAxisAngle(e, t), this.quaternion.premultiply(Un), this;
+ }
+ rotateX(e) {
+ return this.rotateOnAxis(Yn, e);
+ }
+ rotateY(e) {
+ return this.rotateOnAxis(Xn, e);
+ }
+ rotateZ(e) {
+ return this.rotateOnAxis(Zn, e);
+ }
+ translateOnAxis(e, t) {
+ return Hn.copy(e).applyQuaternion(this.quaternion), this.position.add(Hn.multiplyScalar(t)), this;
+ }
+ translateX(e) {
+ return this.translateOnAxis(Yn, e);
+ }
+ translateY(e) {
+ return this.translateOnAxis(Xn, e);
+ }
+ translateZ(e) {
+ return this.translateOnAxis(Zn, e);
+ }
+ localToWorld(e) {
+ return this.updateWorldMatrix(!0, !1), e.applyMatrix4(this.matrixWorld);
+ }
+ worldToLocal(e) {
+ return this.updateWorldMatrix(!0, !1), e.applyMatrix4(Wn.copy(this.matrixWorld).invert());
+ }
+ lookAt(e, t, n) {
+ e.isVector3 ? Gn.copy(e) : Gn.set(e, t, n);
+ let r = this.parent;
+ this.updateWorldMatrix(!0, !1), Kn.setFromMatrixPosition(this.matrixWorld), this.isCamera || this.isLight ? Wn.lookAt(Kn, Gn, this.up) : Wn.lookAt(Gn, Kn, this.up), this.quaternion.setFromRotationMatrix(Wn), r && (Wn.extractRotation(r.matrixWorld), Un.setFromRotationMatrix(Wn), this.quaternion.premultiply(Un.invert()));
+ }
+ add(e) {
+ if (arguments.length > 1) {
+ for (let e = 0; e < arguments.length; e++) this.add(arguments[e]);
+ return this;
+ }
+ return e === this ? (console.error("THREE.Object3D.add: object can't be added as a child of itself.", e), this) : (e && e.isObject3D ? (e.removeFromParent(), e.parent = this, this.children.push(e), e.dispatchEvent(Qn), er.child = e, this.dispatchEvent(er), er.child = null) : console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", e), this);
+ }
+ remove(e) {
+ if (arguments.length > 1) {
+ for (let e = 0; e < arguments.length; e++) this.remove(arguments[e]);
+ return this;
+ }
+ let t = this.children.indexOf(e);
+ return t !== -1 && (e.parent = null, this.children.splice(t, 1), e.dispatchEvent($n), tr.child = e, this.dispatchEvent(tr), tr.child = null), this;
+ }
+ removeFromParent() {
+ let e = this.parent;
+ return e !== null && e.remove(this), this;
+ }
+ clear() {
+ return this.remove(...this.children);
+ }
+ attach(e) {
+ return this.updateWorldMatrix(!0, !1), Wn.copy(this.matrixWorld).invert(), e.parent !== null && (e.parent.updateWorldMatrix(!0, !1), Wn.multiply(e.parent.matrixWorld)), e.applyMatrix4(Wn), e.removeFromParent(), e.parent = this, this.children.push(e), e.updateWorldMatrix(!1, !0), e.dispatchEvent(Qn), er.child = e, this.dispatchEvent(er), er.child = null, this;
+ }
+ getObjectById(e) {
+ return this.getObjectByProperty("id", e);
+ }
+ getObjectByName(e) {
+ return this.getObjectByProperty("name", e);
+ }
+ getObjectByProperty(e, t) {
+ if (this[e] === t) return this;
+ for (let n = 0, r = this.children.length; n < r; n++) {
+ let r = this.children[n].getObjectByProperty(e, t);
+ if (r !== void 0) return r;
+ }
+ }
+ getObjectsByProperty(e, t, n = []) {
+ this[e] === t && n.push(this);
+ let r = this.children;
+ for (let i = 0, a = r.length; i < a; i++) r[i].getObjectsByProperty(e, t, n);
+ return n;
+ }
+ getWorldPosition(e) {
+ return this.updateWorldMatrix(!0, !1), e.setFromMatrixPosition(this.matrixWorld);
+ }
+ getWorldQuaternion(e) {
+ return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(Kn, e, qn), e;
+ }
+ getWorldScale(e) {
+ return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(Kn, Jn, e), e;
+ }
+ getWorldDirection(e) {
+ this.updateWorldMatrix(!0, !1);
+ let t = this.matrixWorld.elements;
+ return e.set(t[8], t[9], t[10]).normalize();
+ }
+ raycast() {}
+ traverse(e) {
+ e(this);
+ let t = this.children;
+ for (let n = 0, r = t.length; n < r; n++) t[n].traverse(e);
+ }
+ traverseVisible(e) {
+ if (this.visible === !1) return;
+ e(this);
+ let t = this.children;
+ for (let n = 0, r = t.length; n < r; n++) t[n].traverseVisible(e);
+ }
+ traverseAncestors(e) {
+ let t = this.parent;
+ t !== null && (e(t), t.traverseAncestors(e));
+ }
+ updateMatrix() {
+ this.matrix.compose(this.position, this.quaternion, this.scale), this.matrixWorldNeedsUpdate = !0;
+ }
+ updateMatrixWorld(e) {
+ this.matrixAutoUpdate && this.updateMatrix(), (this.matrixWorldNeedsUpdate || e) && (this.matrixWorldAutoUpdate === !0 && (this.parent === null ? this.matrixWorld.copy(this.matrix) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), this.matrixWorldNeedsUpdate = !1, e = !0);
+ let t = this.children;
+ for (let n = 0, r = t.length; n < r; n++) t[n].updateMatrixWorld(e);
+ }
+ updateWorldMatrix(e, t) {
+ let n = this.parent;
+ if (e === !0 && n !== null && n.updateWorldMatrix(!0, !1), this.matrixAutoUpdate && this.updateMatrix(), this.matrixWorldAutoUpdate === !0 && (this.parent === null ? this.matrixWorld.copy(this.matrix) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), t === !0) {
+ let e = this.children;
+ for (let t = 0, n = e.length; t < n; t++) e[t].updateWorldMatrix(!1, !0);
+ }
+ }
+ toJSON(e) {
+ let t = e === void 0 || typeof e == "string", n = {};
+ t && (e = {
+ geometries: {},
+ materials: {},
+ textures: {},
+ images: {},
+ shapes: {},
+ skeletons: {},
+ animations: {},
+ nodes: {}
+ }, n.metadata = {
+ version: 4.6,
+ type: "Object",
+ generator: "Object3D.toJSON"
+ });
+ let r = {};
+ r.uuid = this.uuid, r.type = this.type, this.name !== "" && (r.name = this.name), this.castShadow === !0 && (r.castShadow = !0), this.receiveShadow === !0 && (r.receiveShadow = !0), this.visible === !1 && (r.visible = !1), this.frustumCulled === !1 && (r.frustumCulled = !1), this.renderOrder !== 0 && (r.renderOrder = this.renderOrder), Object.keys(this.userData).length > 0 && (r.userData = this.userData), r.layers = this.layers.mask, r.matrix = this.matrix.toArray(), r.up = this.up.toArray(), this.matrixAutoUpdate === !1 && (r.matrixAutoUpdate = !1), this.isInstancedMesh && (r.type = "InstancedMesh", r.count = this.count, r.instanceMatrix = this.instanceMatrix.toJSON(), this.instanceColor !== null && (r.instanceColor = this.instanceColor.toJSON())), this.isBatchedMesh && (r.type = "BatchedMesh", r.perObjectFrustumCulled = this.perObjectFrustumCulled, r.sortObjects = this.sortObjects, r.drawRanges = this._drawRanges, r.reservedRanges = this._reservedRanges, r.geometryInfo = this._geometryInfo.map((e) => ({
+ ...e,
+ boundingBox: e.boundingBox ? {
+ min: e.boundingBox.min.toArray(),
+ max: e.boundingBox.max.toArray()
+ } : void 0,
+ boundingSphere: e.boundingSphere ? {
+ radius: e.boundingSphere.radius,
+ center: e.boundingSphere.center.toArray()
+ } : void 0
+ })), r.instanceInfo = this._instanceInfo.map((e) => ({ ...e })), r.availableInstanceIds = this._availableInstanceIds.slice(), r.availableGeometryIds = this._availableGeometryIds.slice(), r.nextIndexStart = this._nextIndexStart, r.nextVertexStart = this._nextVertexStart, r.geometryCount = this._geometryCount, r.maxInstanceCount = this._maxInstanceCount, r.maxVertexCount = this._maxVertexCount, r.maxIndexCount = this._maxIndexCount, r.geometryInitialized = this._geometryInitialized, r.matricesTexture = this._matricesTexture.toJSON(e), r.indirectTexture = this._indirectTexture.toJSON(e), this._colorsTexture !== null && (r.colorsTexture = this._colorsTexture.toJSON(e)), this.boundingSphere !== null && (r.boundingSphere = {
+ center: this.boundingSphere.center.toArray(),
+ radius: this.boundingSphere.radius
+ }), this.boundingBox !== null && (r.boundingBox = {
+ min: this.boundingBox.min.toArray(),
+ max: this.boundingBox.max.toArray()
+ }));
+ function i(t, n) {
+ return t[n.uuid] === void 0 && (t[n.uuid] = n.toJSON(e)), n.uuid;
+ }
+ if (this.isScene) this.background && (this.background.isColor ? r.background = this.background.toJSON() : this.background.isTexture && (r.background = this.background.toJSON(e).uuid)), this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== !0 && (r.environment = this.environment.toJSON(e).uuid);
+ else if (this.isMesh || this.isLine || this.isPoints) {
+ r.geometry = i(e.geometries, this.geometry);
+ let t = this.geometry.parameters;
+ if (t !== void 0 && t.shapes !== void 0) {
+ let n = t.shapes;
+ if (Array.isArray(n)) for (let t = 0, r = n.length; t < r; t++) {
+ let r = n[t];
+ i(e.shapes, r);
+ }
+ else i(e.shapes, n);
+ }
+ }
+ if (this.isSkinnedMesh && (r.bindMode = this.bindMode, r.bindMatrix = this.bindMatrix.toArray(), this.skeleton !== void 0 && (i(e.skeletons, this.skeleton), r.skeleton = this.skeleton.uuid)), this.material !== void 0) if (Array.isArray(this.material)) {
+ let t = [];
+ for (let n = 0, r = this.material.length; n < r; n++) t.push(i(e.materials, this.material[n]));
+ r.material = t;
+ } else r.material = i(e.materials, this.material);
+ if (this.children.length > 0) {
+ r.children = [];
+ for (let t = 0; t < this.children.length; t++) r.children.push(this.children[t].toJSON(e).object);
+ }
+ if (this.animations.length > 0) {
+ r.animations = [];
+ for (let t = 0; t < this.animations.length; t++) {
+ let n = this.animations[t];
+ r.animations.push(i(e.animations, n));
+ }
+ }
+ if (t) {
+ let t = a(e.geometries), r = a(e.materials), i = a(e.textures), o = a(e.images), s = a(e.shapes), c = a(e.skeletons), l = a(e.animations), u = a(e.nodes);
+ t.length > 0 && (n.geometries = t), r.length > 0 && (n.materials = r), i.length > 0 && (n.textures = i), o.length > 0 && (n.images = o), s.length > 0 && (n.shapes = s), c.length > 0 && (n.skeletons = c), l.length > 0 && (n.animations = l), u.length > 0 && (n.nodes = u);
+ }
+ return n.object = r, n;
+ function a(e) {
+ let t = [];
+ for (let n in e) {
+ let r = e[n];
+ delete r.metadata, t.push(r);
+ }
+ return t;
+ }
+ }
+ clone(e) {
+ return new this.constructor().copy(this, e);
+ }
+ copy(e, t = !0) {
+ if (this.name = e.name, this.up.copy(e.up), this.position.copy(e.position), this.rotation.order = e.rotation.order, this.quaternion.copy(e.quaternion), this.scale.copy(e.scale), this.matrix.copy(e.matrix), this.matrixWorld.copy(e.matrixWorld), this.matrixAutoUpdate = e.matrixAutoUpdate, this.matrixWorldAutoUpdate = e.matrixWorldAutoUpdate, this.matrixWorldNeedsUpdate = e.matrixWorldNeedsUpdate, this.layers.mask = e.layers.mask, this.visible = e.visible, this.castShadow = e.castShadow, this.receiveShadow = e.receiveShadow, this.frustumCulled = e.frustumCulled, this.renderOrder = e.renderOrder, this.animations = e.animations.slice(), this.userData = JSON.parse(JSON.stringify(e.userData)), t === !0) for (let t = 0; t < e.children.length; t++) {
+ let n = e.children[t];
+ this.add(n.clone());
+ }
+ return this;
+ }
+};
+nr.DEFAULT_UP = /* @__PURE__ */ new R(0, 1, 0), nr.DEFAULT_MATRIX_AUTO_UPDATE = !0, nr.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = !0;
+var rr = /* @__PURE__ */ new R(), ir = /* @__PURE__ */ new R(), ar = /* @__PURE__ */ new R(), or = /* @__PURE__ */ new R(), sr = /* @__PURE__ */ new R(), cr = /* @__PURE__ */ new R(), lr = /* @__PURE__ */ new R(), ur = /* @__PURE__ */ new R(), dr = /* @__PURE__ */ new R(), fr = /* @__PURE__ */ new R(), pr = /* @__PURE__ */ new Jt(), mr = /* @__PURE__ */ new Jt(), hr = /* @__PURE__ */ new Jt(), gr = class e {
+ constructor(e = new R(), t = new R(), n = new R()) {
+ this.a = e, this.b = t, this.c = n;
+ }
+ static getNormal(e, t, n, r) {
+ r.subVectors(n, t), rr.subVectors(e, t), r.cross(rr);
+ let i = r.lengthSq();
+ return i > 0 ? r.multiplyScalar(1 / Math.sqrt(i)) : r.set(0, 0, 0);
+ }
+ static getBarycoord(e, t, n, r, i) {
+ rr.subVectors(r, t), ir.subVectors(n, t), ar.subVectors(e, t);
+ let a = rr.dot(rr), o = rr.dot(ir), s = rr.dot(ar), c = ir.dot(ir), l = ir.dot(ar), u = a * c - o * o;
+ if (u === 0) return i.set(0, 0, 0), null;
+ let d = 1 / u, f = (c * s - o * l) * d, p = (a * l - o * s) * d;
+ return i.set(1 - f - p, p, f);
+ }
+ static containsPoint(e, t, n, r) {
+ return this.getBarycoord(e, t, n, r, or) === null ? !1 : or.x >= 0 && or.y >= 0 && or.x + or.y <= 1;
+ }
+ static getInterpolation(e, t, n, r, i, a, o, s) {
+ return this.getBarycoord(e, t, n, r, or) === null ? (s.x = 0, s.y = 0, "z" in s && (s.z = 0), "w" in s && (s.w = 0), null) : (s.setScalar(0), s.addScaledVector(i, or.x), s.addScaledVector(a, or.y), s.addScaledVector(o, or.z), s);
+ }
+ static getInterpolatedAttribute(e, t, n, r, i, a) {
+ return pr.setScalar(0), mr.setScalar(0), hr.setScalar(0), pr.fromBufferAttribute(e, t), mr.fromBufferAttribute(e, n), hr.fromBufferAttribute(e, r), a.setScalar(0), a.addScaledVector(pr, i.x), a.addScaledVector(mr, i.y), a.addScaledVector(hr, i.z), a;
+ }
+ static isFrontFacing(e, t, n, r) {
+ return rr.subVectors(n, t), ir.subVectors(e, t), rr.cross(ir).dot(r) < 0;
+ }
+ set(e, t, n) {
+ return this.a.copy(e), this.b.copy(t), this.c.copy(n), this;
+ }
+ setFromPointsAndIndices(e, t, n, r) {
+ return this.a.copy(e[t]), this.b.copy(e[n]), this.c.copy(e[r]), this;
+ }
+ setFromAttributeAndIndices(e, t, n, r) {
+ return this.a.fromBufferAttribute(e, t), this.b.fromBufferAttribute(e, n), this.c.fromBufferAttribute(e, r), this;
+ }
+ clone() {
+ return new this.constructor().copy(this);
+ }
+ copy(e) {
+ return this.a.copy(e.a), this.b.copy(e.b), this.c.copy(e.c), this;
+ }
+ getArea() {
+ return rr.subVectors(this.c, this.b), ir.subVectors(this.a, this.b), rr.cross(ir).length() * .5;
+ }
+ getMidpoint(e) {
+ return e.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
+ }
+ getNormal(t) {
+ return e.getNormal(this.a, this.b, this.c, t);
+ }
+ getPlane(e) {
+ return e.setFromCoplanarPoints(this.a, this.b, this.c);
+ }
+ getBarycoord(t, n) {
+ return e.getBarycoord(t, this.a, this.b, this.c, n);
+ }
+ getInterpolation(t, n, r, i, a) {
+ return e.getInterpolation(t, this.a, this.b, this.c, n, r, i, a);
+ }
+ containsPoint(t) {
+ return e.containsPoint(t, this.a, this.b, this.c);
+ }
+ isFrontFacing(t) {
+ return e.isFrontFacing(this.a, this.b, this.c, t);
+ }
+ intersectsBox(e) {
+ return e.intersectsTriangle(this);
+ }
+ closestPointToPoint(e, t) {
+ let n = this.a, r = this.b, i = this.c, a, o;
+ sr.subVectors(r, n), cr.subVectors(i, n), ur.subVectors(e, n);
+ let s = sr.dot(ur), c = cr.dot(ur);
+ if (s <= 0 && c <= 0) return t.copy(n);
+ dr.subVectors(e, r);
+ let l = sr.dot(dr), u = cr.dot(dr);
+ if (l >= 0 && u <= l) return t.copy(r);
+ let d = s * u - l * c;
+ if (d <= 0 && s >= 0 && l <= 0) return a = s / (s - l), t.copy(n).addScaledVector(sr, a);
+ fr.subVectors(e, i);
+ let f = sr.dot(fr), p = cr.dot(fr);
+ if (p >= 0 && f <= p) return t.copy(i);
+ let m = f * c - s * p;
+ if (m <= 0 && c >= 0 && p <= 0) return o = c / (c - p), t.copy(n).addScaledVector(cr, o);
+ let h = l * p - f * u;
+ if (h <= 0 && u - l >= 0 && f - p >= 0) return lr.subVectors(i, r), o = (u - l) / (u - l + (f - p)), t.copy(r).addScaledVector(lr, o);
+ let g = 1 / (h + m + d);
+ return a = m * g, o = d * g, t.copy(n).addScaledVector(sr, a).addScaledVector(cr, o);
+ }
+ equals(e) {
+ return e.a.equals(this.a) && e.b.equals(this.b) && e.c.equals(this.c);
+ }
+}, _r = {
+ aliceblue: 15792383,
+ antiquewhite: 16444375,
+ aqua: 65535,
+ aquamarine: 8388564,
+ azure: 15794175,
+ beige: 16119260,
+ bisque: 16770244,
+ black: 0,
+ blanchedalmond: 16772045,
+ blue: 255,
+ blueviolet: 9055202,
+ brown: 10824234,
+ burlywood: 14596231,
+ cadetblue: 6266528,
+ chartreuse: 8388352,
+ chocolate: 13789470,
+ coral: 16744272,
+ cornflowerblue: 6591981,
+ cornsilk: 16775388,
+ crimson: 14423100,
+ cyan: 65535,
+ darkblue: 139,
+ darkcyan: 35723,
+ darkgoldenrod: 12092939,
+ darkgray: 11119017,
+ darkgreen: 25600,
+ darkgrey: 11119017,
+ darkkhaki: 12433259,
+ darkmagenta: 9109643,
+ darkolivegreen: 5597999,
+ darkorange: 16747520,
+ darkorchid: 10040012,
+ darkred: 9109504,
+ darksalmon: 15308410,
+ darkseagreen: 9419919,
+ darkslateblue: 4734347,
+ darkslategray: 3100495,
+ darkslategrey: 3100495,
+ darkturquoise: 52945,
+ darkviolet: 9699539,
+ deeppink: 16716947,
+ deepskyblue: 49151,
+ dimgray: 6908265,
+ dimgrey: 6908265,
+ dodgerblue: 2003199,
+ firebrick: 11674146,
+ floralwhite: 16775920,
+ forestgreen: 2263842,
+ fuchsia: 16711935,
+ gainsboro: 14474460,
+ ghostwhite: 16316671,
+ gold: 16766720,
+ goldenrod: 14329120,
+ gray: 8421504,
+ green: 32768,
+ greenyellow: 11403055,
+ grey: 8421504,
+ honeydew: 15794160,
+ hotpink: 16738740,
+ indianred: 13458524,
+ indigo: 4915330,
+ ivory: 16777200,
+ khaki: 15787660,
+ lavender: 15132410,
+ lavenderblush: 16773365,
+ lawngreen: 8190976,
+ lemonchiffon: 16775885,
+ lightblue: 11393254,
+ lightcoral: 15761536,
+ lightcyan: 14745599,
+ lightgoldenrodyellow: 16448210,
+ lightgray: 13882323,
+ lightgreen: 9498256,
+ lightgrey: 13882323,
+ lightpink: 16758465,
+ lightsalmon: 16752762,
+ lightseagreen: 2142890,
+ lightskyblue: 8900346,
+ lightslategray: 7833753,
+ lightslategrey: 7833753,
+ lightsteelblue: 11584734,
+ lightyellow: 16777184,
+ lime: 65280,
+ limegreen: 3329330,
+ linen: 16445670,
+ magenta: 16711935,
+ maroon: 8388608,
+ mediumaquamarine: 6737322,
+ mediumblue: 205,
+ mediumorchid: 12211667,
+ mediumpurple: 9662683,
+ mediumseagreen: 3978097,
+ mediumslateblue: 8087790,
+ mediumspringgreen: 64154,
+ mediumturquoise: 4772300,
+ mediumvioletred: 13047173,
+ midnightblue: 1644912,
+ mintcream: 16121850,
+ mistyrose: 16770273,
+ moccasin: 16770229,
+ navajowhite: 16768685,
+ navy: 128,
+ oldlace: 16643558,
+ olive: 8421376,
+ olivedrab: 7048739,
+ orange: 16753920,
+ orangered: 16729344,
+ orchid: 14315734,
+ palegoldenrod: 15657130,
+ palegreen: 10025880,
+ paleturquoise: 11529966,
+ palevioletred: 14381203,
+ papayawhip: 16773077,
+ peachpuff: 16767673,
+ peru: 13468991,
+ pink: 16761035,
+ plum: 14524637,
+ powderblue: 11591910,
+ purple: 8388736,
+ rebeccapurple: 6697881,
+ red: 16711680,
+ rosybrown: 12357519,
+ royalblue: 4286945,
+ saddlebrown: 9127187,
+ salmon: 16416882,
+ sandybrown: 16032864,
+ seagreen: 3050327,
+ seashell: 16774638,
+ sienna: 10506797,
+ silver: 12632256,
+ skyblue: 8900331,
+ slateblue: 6970061,
+ slategray: 7372944,
+ slategrey: 7372944,
+ snow: 16775930,
+ springgreen: 65407,
+ steelblue: 4620980,
+ tan: 13808780,
+ teal: 32896,
+ thistle: 14204888,
+ tomato: 16737095,
+ turquoise: 4251856,
+ violet: 15631086,
+ wheat: 16113331,
+ white: 16777215,
+ whitesmoke: 16119285,
+ yellow: 16776960,
+ yellowgreen: 10145074
+}, vr = {
+ h: 0,
+ s: 0,
+ l: 0
+}, yr = {
+ h: 0,
+ s: 0,
+ l: 0
+};
+function br(e, t, n) {
+ return n < 0 && (n += 1), n > 1 && --n, n < 1 / 6 ? e + (t - e) * 6 * n : n < 1 / 2 ? t : n < 2 / 3 ? e + (t - e) * 6 * (2 / 3 - n) : e;
+}
+var B = class {
+ constructor(e, t, n) {
+ return this.isColor = !0, this.r = 1, this.g = 1, this.b = 1, this.set(e, t, n);
+ }
+ set(e, t, n) {
+ if (t === void 0 && n === void 0) {
+ let t = e;
+ t && t.isColor ? this.copy(t) : typeof t == "number" ? this.setHex(t) : typeof t == "string" && this.setStyle(t);
+ } else this.setRGB(e, t, n);
+ return this;
+ }
+ setScalar(e) {
+ return this.r = e, this.g = e, this.b = e, this;
+ }
+ setHex(e, t = Ge) {
+ return e = Math.floor(e), this.r = (e >> 16 & 255) / 255, this.g = (e >> 8 & 255) / 255, this.b = (e & 255) / 255, Rt.toWorkingColorSpace(this, t), this;
+ }
+ setRGB(e, t, n, r = Rt.workingColorSpace) {
+ return this.r = e, this.g = t, this.b = n, Rt.toWorkingColorSpace(this, r), this;
+ }
+ setHSL(e, t, n, r = Rt.workingColorSpace) {
+ if (e = it(e, 1), t = I(t, 0, 1), n = I(n, 0, 1), t === 0) this.r = this.g = this.b = n;
+ else {
+ let r = n <= .5 ? n * (1 + t) : n + t - n * t, i = 2 * n - r;
+ this.r = br(i, r, e + 1 / 3), this.g = br(i, r, e), this.b = br(i, r, e - 1 / 3);
+ }
+ return Rt.toWorkingColorSpace(this, r), this;
+ }
+ setStyle(e, t = Ge) {
+ function n(t) {
+ t !== void 0 && parseFloat(t) < 1 && console.warn("THREE.Color: Alpha component of " + e + " will be ignored.");
+ }
+ let r;
+ if (r = /^(\w+)\(([^\)]*)\)/.exec(e)) {
+ let i, a = r[1], o = r[2];
+ switch (a) {
+ case "rgb":
+ case "rgba":
+ if (i = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o)) return n(i[4]), this.setRGB(Math.min(255, parseInt(i[1], 10)) / 255, Math.min(255, parseInt(i[2], 10)) / 255, Math.min(255, parseInt(i[3], 10)) / 255, t);
+ if (i = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o)) return n(i[4]), this.setRGB(Math.min(100, parseInt(i[1], 10)) / 100, Math.min(100, parseInt(i[2], 10)) / 100, Math.min(100, parseInt(i[3], 10)) / 100, t);
+ break;
+ case "hsl":
+ case "hsla":
+ if (i = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o)) return n(i[4]), this.setHSL(parseFloat(i[1]) / 360, parseFloat(i[2]) / 100, parseFloat(i[3]) / 100, t);
+ break;
+ default: console.warn("THREE.Color: Unknown color model " + e);
+ }
+ } else if (r = /^\#([A-Fa-f\d]+)$/.exec(e)) {
+ let n = r[1], i = n.length;
+ if (i === 3) return this.setRGB(parseInt(n.charAt(0), 16) / 15, parseInt(n.charAt(1), 16) / 15, parseInt(n.charAt(2), 16) / 15, t);
+ if (i === 6) return this.setHex(parseInt(n, 16), t);
+ console.warn("THREE.Color: Invalid hex color " + e);
+ } else if (e && e.length > 0) return this.setColorName(e, t);
+ return this;
+ }
+ setColorName(e, t = Ge) {
+ let n = _r[e.toLowerCase()];
+ return n === void 0 ? console.warn("THREE.Color: Unknown color " + e) : this.setHex(n, t), this;
+ }
+ clone() {
+ return new this.constructor(this.r, this.g, this.b);
+ }
+ copy(e) {
+ return this.r = e.r, this.g = e.g, this.b = e.b, this;
+ }
+ copySRGBToLinear(e) {
+ return this.r = zt(e.r), this.g = zt(e.g), this.b = zt(e.b), this;
+ }
+ copyLinearToSRGB(e) {
+ return this.r = Bt(e.r), this.g = Bt(e.g), this.b = Bt(e.b), this;
+ }
+ convertSRGBToLinear() {
+ return this.copySRGBToLinear(this), this;
+ }
+ convertLinearToSRGB() {
+ return this.copyLinearToSRGB(this), this;
+ }
+ getHex(e = Ge) {
+ return Rt.fromWorkingColorSpace(xr.copy(this), e), Math.round(I(xr.r * 255, 0, 255)) * 65536 + Math.round(I(xr.g * 255, 0, 255)) * 256 + Math.round(I(xr.b * 255, 0, 255));
+ }
+ getHexString(e = Ge) {
+ return ("000000" + this.getHex(e).toString(16)).slice(-6);
+ }
+ getHSL(e, t = Rt.workingColorSpace) {
+ Rt.fromWorkingColorSpace(xr.copy(this), t);
+ let n = xr.r, r = xr.g, i = xr.b, a = Math.max(n, r, i), o = Math.min(n, r, i), s, c, l = (o + a) / 2;
+ if (o === a) s = 0, c = 0;
+ else {
+ let e = a - o;
+ switch (c = l <= .5 ? e / (a + o) : e / (2 - a - o), a) {
+ case n:
+ s = (r - i) / e + (r < i ? 6 : 0);
+ break;
+ case r:
+ s = (i - n) / e + 2;
+ break;
+ case i:
+ s = (n - r) / e + 4;
+ break;
+ }
+ s /= 6;
+ }
+ return e.h = s, e.s = c, e.l = l, e;
+ }
+ getRGB(e, t = Rt.workingColorSpace) {
+ return Rt.fromWorkingColorSpace(xr.copy(this), t), e.r = xr.r, e.g = xr.g, e.b = xr.b, e;
+ }
+ getStyle(e = Ge) {
+ Rt.fromWorkingColorSpace(xr.copy(this), e);
+ let t = xr.r, n = xr.g, r = xr.b;
+ return e === "srgb" ? `rgb(${Math.round(t * 255)},${Math.round(n * 255)},${Math.round(r * 255)})` : `color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`;
+ }
+ offsetHSL(e, t, n) {
+ return this.getHSL(vr), this.setHSL(vr.h + e, vr.s + t, vr.l + n);
+ }
+ add(e) {
+ return this.r += e.r, this.g += e.g, this.b += e.b, this;
+ }
+ addColors(e, t) {
+ return this.r = e.r + t.r, this.g = e.g + t.g, this.b = e.b + t.b, this;
+ }
+ addScalar(e) {
+ return this.r += e, this.g += e, this.b += e, this;
+ }
+ sub(e) {
+ return this.r = Math.max(0, this.r - e.r), this.g = Math.max(0, this.g - e.g), this.b = Math.max(0, this.b - e.b), this;
+ }
+ multiply(e) {
+ return this.r *= e.r, this.g *= e.g, this.b *= e.b, this;
+ }
+ multiplyScalar(e) {
+ return this.r *= e, this.g *= e, this.b *= e, this;
+ }
+ lerp(e, t) {
+ return this.r += (e.r - this.r) * t, this.g += (e.g - this.g) * t, this.b += (e.b - this.b) * t, this;
+ }
+ lerpColors(e, t, n) {
+ return this.r = e.r + (t.r - e.r) * n, this.g = e.g + (t.g - e.g) * n, this.b = e.b + (t.b - e.b) * n, this;
+ }
+ lerpHSL(e, t) {
+ this.getHSL(vr), e.getHSL(yr);
+ let n = st(vr.h, yr.h, t), r = st(vr.s, yr.s, t), i = st(vr.l, yr.l, t);
+ return this.setHSL(n, r, i), this;
+ }
+ setFromVector3(e) {
+ return this.r = e.x, this.g = e.y, this.b = e.z, this;
+ }
+ applyMatrix3(e) {
+ let t = this.r, n = this.g, r = this.b, i = e.elements;
+ return this.r = i[0] * t + i[3] * n + i[6] * r, this.g = i[1] * t + i[4] * n + i[7] * r, this.b = i[2] * t + i[5] * n + i[8] * r, this;
+ }
+ equals(e) {
+ return e.r === this.r && e.g === this.g && e.b === this.b;
+ }
+ fromArray(e, t = 0) {
+ return this.r = e[t], this.g = e[t + 1], this.b = e[t + 2], this;
+ }
+ toArray(e = [], t = 0) {
+ return e[t] = this.r, e[t + 1] = this.g, e[t + 2] = this.b, e;
+ }
+ fromBufferAttribute(e, t) {
+ return this.r = e.getX(t), this.g = e.getY(t), this.b = e.getZ(t), this;
+ }
+ toJSON() {
+ return this.getHex();
+ }
+ *[Symbol.iterator]() {
+ yield this.r, yield this.g, yield this.b;
+ }
+}, xr = /* @__PURE__ */ new B();
+B.NAMES = _r;
+var Sr = 0, Cr = class extends Qe {
+ constructor() {
+ super(), this.isMaterial = !0, Object.defineProperty(this, "id", { value: Sr++ }), this.uuid = rt(), this.name = "", this.type = "Material", this.blending = 1, this.side = 0, this.vertexColors = !1, this.opacity = 1, this.transparent = !1, this.alphaHash = !1, this.blendSrc = 204, this.blendDst = 205, this.blendEquation = 100, this.blendSrcAlpha = null, this.blendDstAlpha = null, this.blendEquationAlpha = null, this.blendColor = new B(0, 0, 0), this.blendAlpha = 0, this.depthFunc = 3, this.depthTest = !0, this.depthWrite = !0, this.stencilWriteMask = 255, this.stencilFunc = 519, this.stencilRef = 0, this.stencilFuncMask = 255, this.stencilFail = Ye, this.stencilZFail = Ye, this.stencilZPass = Ye, this.stencilWrite = !1, this.clippingPlanes = null, this.clipIntersection = !1, this.clipShadows = !1, this.shadowSide = null, this.colorWrite = !0, this.precision = null, this.polygonOffset = !1, this.polygonOffsetFactor = 0, this.polygonOffsetUnits = 0, this.dithering = !1, this.alphaToCoverage = !1, this.premultipliedAlpha = !1, this.forceSinglePass = !1, this.allowOverride = !0, this.visible = !0, this.toneMapped = !0, this.userData = {}, this.version = 0, this._alphaTest = 0;
+ }
+ get alphaTest() {
+ return this._alphaTest;
+ }
+ set alphaTest(e) {
+ this._alphaTest > 0 != e > 0 && this.version++, this._alphaTest = e;
+ }
+ onBeforeRender() {}
+ onBeforeCompile() {}
+ customProgramCacheKey() {
+ return this.onBeforeCompile.toString();
+ }
+ setValues(e) {
+ if (e !== void 0) for (let t in e) {
+ let n = e[t];
+ if (n === void 0) {
+ console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);
+ continue;
+ }
+ let r = this[t];
+ if (r === void 0) {
+ console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);
+ continue;
+ }
+ r && r.isColor ? r.set(n) : r && r.isVector3 && n && n.isVector3 ? r.copy(n) : this[t] = n;
+ }
+ }
+ toJSON(e) {
+ let t = e === void 0 || typeof e == "string";
+ t && (e = {
+ textures: {},
+ images: {}
+ });
+ let n = { metadata: {
+ version: 4.6,
+ type: "Material",
+ generator: "Material.toJSON"
+ } };
+ n.uuid = this.uuid, n.type = this.type, this.name !== "" && (n.name = this.name), this.color && this.color.isColor && (n.color = this.color.getHex()), this.roughness !== void 0 && (n.roughness = this.roughness), this.metalness !== void 0 && (n.metalness = this.metalness), this.sheen !== void 0 && (n.sheen = this.sheen), this.sheenColor && this.sheenColor.isColor && (n.sheenColor = this.sheenColor.getHex()), this.sheenRoughness !== void 0 && (n.sheenRoughness = this.sheenRoughness), this.emissive && this.emissive.isColor && (n.emissive = this.emissive.getHex()), this.emissiveIntensity !== void 0 && this.emissiveIntensity !== 1 && (n.emissiveIntensity = this.emissiveIntensity), this.specular && this.specular.isColor && (n.specular = this.specular.getHex()), this.specularIntensity !== void 0 && (n.specularIntensity = this.specularIntensity), this.specularColor && this.specularColor.isColor && (n.specularColor = this.specularColor.getHex()), this.shininess !== void 0 && (n.shininess = this.shininess), this.clearcoat !== void 0 && (n.clearcoat = this.clearcoat), this.clearcoatRoughness !== void 0 && (n.clearcoatRoughness = this.clearcoatRoughness), this.clearcoatMap && this.clearcoatMap.isTexture && (n.clearcoatMap = this.clearcoatMap.toJSON(e).uuid), this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture && (n.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(e).uuid), this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture && (n.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(e).uuid, n.clearcoatNormalScale = this.clearcoatNormalScale.toArray()), this.dispersion !== void 0 && (n.dispersion = this.dispersion), this.iridescence !== void 0 && (n.iridescence = this.iridescence), this.iridescenceIOR !== void 0 && (n.iridescenceIOR = this.iridescenceIOR), this.iridescenceThicknessRange !== void 0 && (n.iridescenceThicknessRange = this.iridescenceThicknessRange), this.iridescenceMap && this.iridescenceMap.isTexture && (n.iridescenceMap = this.iridescenceMap.toJSON(e).uuid), this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture && (n.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(e).uuid), this.anisotropy !== void 0 && (n.anisotropy = this.anisotropy), this.anisotropyRotation !== void 0 && (n.anisotropyRotation = this.anisotropyRotation), this.anisotropyMap && this.anisotropyMap.isTexture && (n.anisotropyMap = this.anisotropyMap.toJSON(e).uuid), this.map && this.map.isTexture && (n.map = this.map.toJSON(e).uuid), this.matcap && this.matcap.isTexture && (n.matcap = this.matcap.toJSON(e).uuid), this.alphaMap && this.alphaMap.isTexture && (n.alphaMap = this.alphaMap.toJSON(e).uuid), this.lightMap && this.lightMap.isTexture && (n.lightMap = this.lightMap.toJSON(e).uuid, n.lightMapIntensity = this.lightMapIntensity), this.aoMap && this.aoMap.isTexture && (n.aoMap = this.aoMap.toJSON(e).uuid, n.aoMapIntensity = this.aoMapIntensity), this.bumpMap && this.bumpMap.isTexture && (n.bumpMap = this.bumpMap.toJSON(e).uuid, n.bumpScale = this.bumpScale), this.normalMap && this.normalMap.isTexture && (n.normalMap = this.normalMap.toJSON(e).uuid, n.normalMapType = this.normalMapType, n.normalScale = this.normalScale.toArray()), this.displacementMap && this.displacementMap.isTexture && (n.displacementMap = this.displacementMap.toJSON(e).uuid, n.displacementScale = this.displacementScale, n.displacementBias = this.displacementBias), this.roughnessMap && this.roughnessMap.isTexture && (n.roughnessMap = this.roughnessMap.toJSON(e).uuid), this.metalnessMap && this.metalnessMap.isTexture && (n.metalnessMap = this.metalnessMap.toJSON(e).uuid), this.emissiveMap && this.emissiveMap.isTexture && (n.emissiveMap = this.emissiveMap.toJSON(e).uuid), this.specularMap && this.specularMap.isTexture && (n.specularMap = this.specularMap.toJSON(e).uuid), this.specularIntensityMap && this.specularIntensityMap.isTexture && (n.specularIntensityMap = this.specularIntensityMap.toJSON(e).uuid), this.specularColorMap && this.specularColorMap.isTexture && (n.specularColorMap = this.specularColorMap.toJSON(e).uuid), this.envMap && this.envMap.isTexture && (n.envMap = this.envMap.toJSON(e).uuid, this.combine !== void 0 && (n.combine = this.combine)), this.envMapRotation !== void 0 && (n.envMapRotation = this.envMapRotation.toArray()), this.envMapIntensity !== void 0 && (n.envMapIntensity = this.envMapIntensity), this.reflectivity !== void 0 && (n.reflectivity = this.reflectivity), this.refractionRatio !== void 0 && (n.refractionRatio = this.refractionRatio), this.gradientMap && this.gradientMap.isTexture && (n.gradientMap = this.gradientMap.toJSON(e).uuid), this.transmission !== void 0 && (n.transmission = this.transmission), this.transmissionMap && this.transmissionMap.isTexture && (n.transmissionMap = this.transmissionMap.toJSON(e).uuid), this.thickness !== void 0 && (n.thickness = this.thickness), this.thicknessMap && this.thicknessMap.isTexture && (n.thicknessMap = this.thicknessMap.toJSON(e).uuid), this.attenuationDistance !== void 0 && this.attenuationDistance !== Infinity && (n.attenuationDistance = this.attenuationDistance), this.attenuationColor !== void 0 && (n.attenuationColor = this.attenuationColor.getHex()), this.size !== void 0 && (n.size = this.size), this.shadowSide !== null && (n.shadowSide = this.shadowSide), this.sizeAttenuation !== void 0 && (n.sizeAttenuation = this.sizeAttenuation), this.blending !== 1 && (n.blending = this.blending), this.side !== 0 && (n.side = this.side), this.vertexColors === !0 && (n.vertexColors = !0), this.opacity < 1 && (n.opacity = this.opacity), this.transparent === !0 && (n.transparent = !0), this.blendSrc !== 204 && (n.blendSrc = this.blendSrc), this.blendDst !== 205 && (n.blendDst = this.blendDst), this.blendEquation !== 100 && (n.blendEquation = this.blendEquation), this.blendSrcAlpha !== null && (n.blendSrcAlpha = this.blendSrcAlpha), this.blendDstAlpha !== null && (n.blendDstAlpha = this.blendDstAlpha), this.blendEquationAlpha !== null && (n.blendEquationAlpha = this.blendEquationAlpha), this.blendColor && this.blendColor.isColor && (n.blendColor = this.blendColor.getHex()), this.blendAlpha !== 0 && (n.blendAlpha = this.blendAlpha), this.depthFunc !== 3 && (n.depthFunc = this.depthFunc), this.depthTest === !1 && (n.depthTest = this.depthTest), this.depthWrite === !1 && (n.depthWrite = this.depthWrite), this.colorWrite === !1 && (n.colorWrite = this.colorWrite), this.stencilWriteMask !== 255 && (n.stencilWriteMask = this.stencilWriteMask), this.stencilFunc !== 519 && (n.stencilFunc = this.stencilFunc), this.stencilRef !== 0 && (n.stencilRef = this.stencilRef), this.stencilFuncMask !== 255 && (n.stencilFuncMask = this.stencilFuncMask), this.stencilFail !== 7680 && (n.stencilFail = this.stencilFail), this.stencilZFail !== 7680 && (n.stencilZFail = this.stencilZFail), this.stencilZPass !== 7680 && (n.stencilZPass = this.stencilZPass), this.stencilWrite === !0 && (n.stencilWrite = this.stencilWrite), this.rotation !== void 0 && this.rotation !== 0 && (n.rotation = this.rotation), this.polygonOffset === !0 && (n.polygonOffset = !0), this.polygonOffsetFactor !== 0 && (n.polygonOffsetFactor = this.polygonOffsetFactor), this.polygonOffsetUnits !== 0 && (n.polygonOffsetUnits = this.polygonOffsetUnits), this.linewidth !== void 0 && this.linewidth !== 1 && (n.linewidth = this.linewidth), this.dashSize !== void 0 && (n.dashSize = this.dashSize), this.gapSize !== void 0 && (n.gapSize = this.gapSize), this.scale !== void 0 && (n.scale = this.scale), this.dithering === !0 && (n.dithering = !0), this.alphaTest > 0 && (n.alphaTest = this.alphaTest), this.alphaHash === !0 && (n.alphaHash = !0), this.alphaToCoverage === !0 && (n.alphaToCoverage = !0), this.premultipliedAlpha === !0 && (n.premultipliedAlpha = !0), this.forceSinglePass === !0 && (n.forceSinglePass = !0), this.wireframe === !0 && (n.wireframe = !0), this.wireframeLinewidth > 1 && (n.wireframeLinewidth = this.wireframeLinewidth), this.wireframeLinecap !== "round" && (n.wireframeLinecap = this.wireframeLinecap), this.wireframeLinejoin !== "round" && (n.wireframeLinejoin = this.wireframeLinejoin), this.flatShading === !0 && (n.flatShading = !0), this.visible === !1 && (n.visible = !1), this.toneMapped === !1 && (n.toneMapped = !1), this.fog === !1 && (n.fog = !1), Object.keys(this.userData).length > 0 && (n.userData = this.userData);
+ function r(e) {
+ let t = [];
+ for (let n in e) {
+ let r = e[n];
+ delete r.metadata, t.push(r);
+ }
+ return t;
+ }
+ if (t) {
+ let t = r(e.textures), i = r(e.images);
+ t.length > 0 && (n.textures = t), i.length > 0 && (n.images = i);
+ }
+ return n;
+ }
+ clone() {
+ return new this.constructor().copy(this);
+ }
+ copy(e) {
+ this.name = e.name, this.blending = e.blending, this.side = e.side, this.vertexColors = e.vertexColors, this.opacity = e.opacity, this.transparent = e.transparent, this.blendSrc = e.blendSrc, this.blendDst = e.blendDst, this.blendEquation = e.blendEquation, this.blendSrcAlpha = e.blendSrcAlpha, this.blendDstAlpha = e.blendDstAlpha, this.blendEquationAlpha = e.blendEquationAlpha, this.blendColor.copy(e.blendColor), this.blendAlpha = e.blendAlpha, this.depthFunc = e.depthFunc, this.depthTest = e.depthTest, this.depthWrite = e.depthWrite, this.stencilWriteMask = e.stencilWriteMask, this.stencilFunc = e.stencilFunc, this.stencilRef = e.stencilRef, this.stencilFuncMask = e.stencilFuncMask, this.stencilFail = e.stencilFail, this.stencilZFail = e.stencilZFail, this.stencilZPass = e.stencilZPass, this.stencilWrite = e.stencilWrite;
+ let t = e.clippingPlanes, n = null;
+ if (t !== null) {
+ let e = t.length;
+ n = Array(e);
+ for (let r = 0; r !== e; ++r) n[r] = t[r].clone();
+ }
+ return this.clippingPlanes = n, this.clipIntersection = e.clipIntersection, this.clipShadows = e.clipShadows, this.shadowSide = e.shadowSide, this.colorWrite = e.colorWrite, this.precision = e.precision, this.polygonOffset = e.polygonOffset, this.polygonOffsetFactor = e.polygonOffsetFactor, this.polygonOffsetUnits = e.polygonOffsetUnits, this.dithering = e.dithering, this.alphaTest = e.alphaTest, this.alphaHash = e.alphaHash, this.alphaToCoverage = e.alphaToCoverage, this.premultipliedAlpha = e.premultipliedAlpha, this.forceSinglePass = e.forceSinglePass, this.visible = e.visible, this.toneMapped = e.toneMapped, this.userData = JSON.parse(JSON.stringify(e.userData)), this;
+ }
+ dispose() {
+ this.dispatchEvent({ type: "dispose" });
+ }
+ set needsUpdate(e) {
+ e === !0 && this.version++;
+ }
+}, wr = class extends Cr {
+ constructor(e) {
+ super(), this.isMeshBasicMaterial = !0, this.type = "MeshBasicMaterial", this.color = new B(16777215), this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.specularMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new zn(), this.combine = 0, this.reflectivity = 1, this.refractionRatio = .98, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.fog = !0, this.setValues(e);
+ }
+ copy(e) {
+ return super.copy(e), this.color.copy(e.color), this.map = e.map, this.lightMap = e.lightMap, this.lightMapIntensity = e.lightMapIntensity, this.aoMap = e.aoMap, this.aoMapIntensity = e.aoMapIntensity, this.specularMap = e.specularMap, this.alphaMap = e.alphaMap, this.envMap = e.envMap, this.envMapRotation.copy(e.envMapRotation), this.combine = e.combine, this.reflectivity = e.reflectivity, this.refractionRatio = e.refractionRatio, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.wireframeLinecap = e.wireframeLinecap, this.wireframeLinejoin = e.wireframeLinejoin, this.fog = e.fog, this;
+ }
+}, Tr = /* @__PURE__ */ Er();
+function Er() {
+ let e = /* @__PURE__ */ new ArrayBuffer(4), t = new Float32Array(e), n = new Uint32Array(e), r = new Uint32Array(512), i = new Uint32Array(512);
+ for (let e = 0; e < 256; ++e) {
+ let t = e - 127;
+ t < -27 ? (r[e] = 0, r[e | 256] = 32768, i[e] = 24, i[e | 256] = 24) : t < -14 ? (r[e] = 1024 >> -t - 14, r[e | 256] = 1024 >> -t - 14 | 32768, i[e] = -t - 1, i[e | 256] = -t - 1) : t <= 15 ? (r[e] = t + 15 << 10, r[e | 256] = t + 15 << 10 | 32768, i[e] = 13, i[e | 256] = 13) : t < 128 ? (r[e] = 31744, r[e | 256] = 64512, i[e] = 24, i[e | 256] = 24) : (r[e] = 31744, r[e | 256] = 64512, i[e] = 13, i[e | 256] = 13);
+ }
+ let a = new Uint32Array(2048), o = new Uint32Array(64), s = new Uint32Array(64);
+ for (let e = 1; e < 1024; ++e) {
+ let t = e << 13, n = 0;
+ for (; !(t & 8388608);) t <<= 1, n -= 8388608;
+ t &= -8388609, n += 947912704, a[e] = t | n;
+ }
+ for (let e = 1024; e < 2048; ++e) a[e] = 939524096 + (e - 1024 << 13);
+ for (let e = 1; e < 31; ++e) o[e] = e << 23;
+ o[31] = 1199570944, o[32] = 2147483648;
+ for (let e = 33; e < 63; ++e) o[e] = 2147483648 + (e - 32 << 23);
+ o[63] = 3347054592;
+ for (let e = 1; e < 64; ++e) e !== 32 && (s[e] = 1024);
+ return {
+ floatView: t,
+ uint32View: n,
+ baseTable: r,
+ shiftTable: i,
+ mantissaTable: a,
+ exponentTable: o,
+ offsetTable: s
+ };
+}
+function Dr(e) {
+ Math.abs(e) > 65504 && console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."), e = I(e, -65504, 65504), Tr.floatView[0] = e;
+ let t = Tr.uint32View[0], n = t >> 23 & 511;
+ return Tr.baseTable[n] + ((t & 8388607) >> Tr.shiftTable[n]);
+}
+function Or(e) {
+ let t = e >> 10;
+ return Tr.uint32View[0] = Tr.mantissaTable[Tr.offsetTable[t] + (e & 1023)] + Tr.exponentTable[t], Tr.floatView[0];
+}
+var kr = class {
+ static toHalfFloat(e) {
+ return Dr(e);
+ }
+ static fromHalfFloat(e) {
+ return Or(e);
+ }
+}, Ar = /* @__PURE__ */ new R(), jr = /* @__PURE__ */ new L(), Mr = 0, Nr = class {
+ constructor(e, t, n = !1) {
+ if (Array.isArray(e)) throw TypeError("THREE.BufferAttribute: array should be a Typed Array.");
+ this.isBufferAttribute = !0, Object.defineProperty(this, "id", { value: Mr++ }), this.name = "", this.array = e, this.itemSize = t, this.count = e === void 0 ? 0 : e.length / t, this.normalized = n, this.usage = Xe, this.updateRanges = [], this.gpuType = b, this.version = 0;
+ }
+ onUploadCallback() {}
+ set needsUpdate(e) {
+ e === !0 && this.version++;
+ }
+ setUsage(e) {
+ return this.usage = e, this;
+ }
+ addUpdateRange(e, t) {
+ this.updateRanges.push({
+ start: e,
+ count: t
+ });
+ }
+ clearUpdateRanges() {
+ this.updateRanges.length = 0;
+ }
+ copy(e) {
+ return this.name = e.name, this.array = new e.array.constructor(e.array), this.itemSize = e.itemSize, this.count = e.count, this.normalized = e.normalized, this.usage = e.usage, this.gpuType = e.gpuType, this;
+ }
+ copyAt(e, t, n) {
+ e *= this.itemSize, n *= t.itemSize;
+ for (let r = 0, i = this.itemSize; r < i; r++) this.array[e + r] = t.array[n + r];
+ return this;
+ }
+ copyArray(e) {
+ return this.array.set(e), this;
+ }
+ applyMatrix3(e) {
+ if (this.itemSize === 2) for (let t = 0, n = this.count; t < n; t++) jr.fromBufferAttribute(this, t), jr.applyMatrix3(e), this.setXY(t, jr.x, jr.y);
+ else if (this.itemSize === 3) for (let t = 0, n = this.count; t < n; t++) Ar.fromBufferAttribute(this, t), Ar.applyMatrix3(e), this.setXYZ(t, Ar.x, Ar.y, Ar.z);
+ return this;
+ }
+ applyMatrix4(e) {
+ for (let t = 0, n = this.count; t < n; t++) Ar.fromBufferAttribute(this, t), Ar.applyMatrix4(e), this.setXYZ(t, Ar.x, Ar.y, Ar.z);
+ return this;
+ }
+ applyNormalMatrix(e) {
+ for (let t = 0, n = this.count; t < n; t++) Ar.fromBufferAttribute(this, t), Ar.applyNormalMatrix(e), this.setXYZ(t, Ar.x, Ar.y, Ar.z);
+ return this;
+ }
+ transformDirection(e) {
+ for (let t = 0, n = this.count; t < n; t++) Ar.fromBufferAttribute(this, t), Ar.transformDirection(e), this.setXYZ(t, Ar.x, Ar.y, Ar.z);
+ return this;
+ }
+ set(e, t = 0) {
+ return this.array.set(e, t), this;
+ }
+ getComponent(e, t) {
+ let n = this.array[e * this.itemSize + t];
+ return this.normalized && (n = St(n, this.array)), n;
+ }
+ setComponent(e, t, n) {
+ return this.normalized && (n = Ct(n, this.array)), this.array[e * this.itemSize + t] = n, this;
+ }
+ getX(e) {
+ let t = this.array[e * this.itemSize];
+ return this.normalized && (t = St(t, this.array)), t;
+ }
+ setX(e, t) {
+ return this.normalized && (t = Ct(t, this.array)), this.array[e * this.itemSize] = t, this;
+ }
+ getY(e) {
+ let t = this.array[e * this.itemSize + 1];
+ return this.normalized && (t = St(t, this.array)), t;
+ }
+ setY(e, t) {
+ return this.normalized && (t = Ct(t, this.array)), this.array[e * this.itemSize + 1] = t, this;
+ }
+ getZ(e) {
+ let t = this.array[e * this.itemSize + 2];
+ return this.normalized && (t = St(t, this.array)), t;
+ }
+ setZ(e, t) {
+ return this.normalized && (t = Ct(t, this.array)), this.array[e * this.itemSize + 2] = t, this;
+ }
+ getW(e) {
+ let t = this.array[e * this.itemSize + 3];
+ return this.normalized && (t = St(t, this.array)), t;
+ }
+ setW(e, t) {
+ return this.normalized && (t = Ct(t, this.array)), this.array[e * this.itemSize + 3] = t, this;
+ }
+ setXY(e, t, n) {
+ return e *= this.itemSize, this.normalized && (t = Ct(t, this.array), n = Ct(n, this.array)), this.array[e + 0] = t, this.array[e + 1] = n, this;
+ }
+ setXYZ(e, t, n, r) {
+ return e *= this.itemSize, this.normalized && (t = Ct(t, this.array), n = Ct(n, this.array), r = Ct(r, this.array)), this.array[e + 0] = t, this.array[e + 1] = n, this.array[e + 2] = r, this;
+ }
+ setXYZW(e, t, n, r, i) {
+ return e *= this.itemSize, this.normalized && (t = Ct(t, this.array), n = Ct(n, this.array), r = Ct(r, this.array), i = Ct(i, this.array)), this.array[e + 0] = t, this.array[e + 1] = n, this.array[e + 2] = r, this.array[e + 3] = i, this;
+ }
+ onUpload(e) {
+ return this.onUploadCallback = e, this;
+ }
+ clone() {
+ return new this.constructor(this.array, this.itemSize).copy(this);
+ }
+ toJSON() {
+ let e = {
+ itemSize: this.itemSize,
+ type: this.array.constructor.name,
+ array: Array.from(this.array),
+ normalized: this.normalized
+ };
+ return this.name !== "" && (e.name = this.name), this.usage !== 35044 && (e.usage = this.usage), e;
+ }
+}, Pr = class extends Nr {
+ constructor(e, t, n) {
+ super(new Uint16Array(e), t, n);
+ }
+}, Fr = class extends Nr {
+ constructor(e, t, n) {
+ super(new Uint32Array(e), t, n);
+ }
+}, Ir = class extends Nr {
+ constructor(e, t, n) {
+ super(new Float32Array(e), t, n);
+ }
+}, Lr = 0, Rr = /* @__PURE__ */ new z(), zr = /* @__PURE__ */ new nr(), Br = /* @__PURE__ */ new R(), Vr = /* @__PURE__ */ new nn(), Hr = /* @__PURE__ */ new nn(), Ur = /* @__PURE__ */ new R(), Wr = class e extends Qe {
+ constructor() {
+ super(), this.isBufferGeometry = !0, Object.defineProperty(this, "id", { value: Lr++ }), this.uuid = rt(), this.name = "", this.type = "BufferGeometry", this.index = null, this.indirect = null, this.attributes = {}, this.morphAttributes = {}, this.morphTargetsRelative = !1, this.groups = [], this.boundingBox = null, this.boundingSphere = null, this.drawRange = {
+ start: 0,
+ count: Infinity
+ }, this.userData = {};
+ }
+ getIndex() {
+ return this.index;
+ }
+ setIndex(e) {
+ return Array.isArray(e) ? this.index = new (Dt(e) ? Fr : Pr)(e, 1) : this.index = e, this;
+ }
+ setIndirect(e) {
+ return this.indirect = e, this;
+ }
+ getIndirect() {
+ return this.indirect;
+ }
+ getAttribute(e) {
+ return this.attributes[e];
+ }
+ setAttribute(e, t) {
+ return this.attributes[e] = t, this;
+ }
+ deleteAttribute(e) {
+ return delete this.attributes[e], this;
+ }
+ hasAttribute(e) {
+ return this.attributes[e] !== void 0;
+ }
+ addGroup(e, t, n = 0) {
+ this.groups.push({
+ start: e,
+ count: t,
+ materialIndex: n
+ });
+ }
+ clearGroups() {
+ this.groups = [];
+ }
+ setDrawRange(e, t) {
+ this.drawRange.start = e, this.drawRange.count = t;
+ }
+ applyMatrix4(e) {
+ let t = this.attributes.position;
+ t !== void 0 && (t.applyMatrix4(e), t.needsUpdate = !0);
+ let n = this.attributes.normal;
+ if (n !== void 0) {
+ let t = new Tt().getNormalMatrix(e);
+ n.applyNormalMatrix(t), n.needsUpdate = !0;
+ }
+ let r = this.attributes.tangent;
+ return r !== void 0 && (r.transformDirection(e), r.needsUpdate = !0), this.boundingBox !== null && this.computeBoundingBox(), this.boundingSphere !== null && this.computeBoundingSphere(), this;
+ }
+ applyQuaternion(e) {
+ return Rr.makeRotationFromQuaternion(e), this.applyMatrix4(Rr), this;
+ }
+ rotateX(e) {
+ return Rr.makeRotationX(e), this.applyMatrix4(Rr), this;
+ }
+ rotateY(e) {
+ return Rr.makeRotationY(e), this.applyMatrix4(Rr), this;
+ }
+ rotateZ(e) {
+ return Rr.makeRotationZ(e), this.applyMatrix4(Rr), this;
+ }
+ translate(e, t, n) {
+ return Rr.makeTranslation(e, t, n), this.applyMatrix4(Rr), this;
+ }
+ scale(e, t, n) {
+ return Rr.makeScale(e, t, n), this.applyMatrix4(Rr), this;
+ }
+ lookAt(e) {
+ return zr.lookAt(e), zr.updateMatrix(), this.applyMatrix4(zr.matrix), this;
+ }
+ center() {
+ return this.computeBoundingBox(), this.boundingBox.getCenter(Br).negate(), this.translate(Br.x, Br.y, Br.z), this;
+ }
+ setFromPoints(e) {
+ let t = this.getAttribute("position");
+ if (t === void 0) {
+ let t = [];
+ for (let n = 0, r = e.length; n < r; n++) {
+ let r = e[n];
+ t.push(r.x, r.y, r.z || 0);
+ }
+ this.setAttribute("position", new Ir(t, 3));
+ } else {
+ let n = Math.min(e.length, t.count);
+ for (let r = 0; r < n; r++) {
+ let n = e[r];
+ t.setXYZ(r, n.x, n.y, n.z || 0);
+ }
+ e.length > t.count && console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."), t.needsUpdate = !0;
+ }
+ return this;
+ }
+ computeBoundingBox() {
+ this.boundingBox === null && (this.boundingBox = new nn());
+ let e = this.attributes.position, t = this.morphAttributes.position;
+ if (e && e.isGLBufferAttribute) {
+ console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this), this.boundingBox.set(new R(-Infinity, -Infinity, -Infinity), new R(Infinity, Infinity, Infinity));
+ return;
+ }
+ if (e !== void 0) {
+ if (this.boundingBox.setFromBufferAttribute(e), t) for (let e = 0, n = t.length; e < n; e++) {
+ let n = t[e];
+ Vr.setFromBufferAttribute(n), this.morphTargetsRelative ? (Ur.addVectors(this.boundingBox.min, Vr.min), this.boundingBox.expandByPoint(Ur), Ur.addVectors(this.boundingBox.max, Vr.max), this.boundingBox.expandByPoint(Ur)) : (this.boundingBox.expandByPoint(Vr.min), this.boundingBox.expandByPoint(Vr.max));
+ }
+ } else this.boundingBox.makeEmpty();
+ (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) && console.error("THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The \"position\" attribute is likely to have NaN values.", this);
+ }
+ computeBoundingSphere() {
+ this.boundingSphere === null && (this.boundingSphere = new xn());
+ let e = this.attributes.position, t = this.morphAttributes.position;
+ if (e && e.isGLBufferAttribute) {
+ console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this), this.boundingSphere.set(new R(), Infinity);
+ return;
+ }
+ if (e) {
+ let n = this.boundingSphere.center;
+ if (Vr.setFromBufferAttribute(e), t) for (let e = 0, n = t.length; e < n; e++) {
+ let n = t[e];
+ Hr.setFromBufferAttribute(n), this.morphTargetsRelative ? (Ur.addVectors(Vr.min, Hr.min), Vr.expandByPoint(Ur), Ur.addVectors(Vr.max, Hr.max), Vr.expandByPoint(Ur)) : (Vr.expandByPoint(Hr.min), Vr.expandByPoint(Hr.max));
+ }
+ Vr.getCenter(n);
+ let r = 0;
+ for (let t = 0, i = e.count; t < i; t++) Ur.fromBufferAttribute(e, t), r = Math.max(r, n.distanceToSquared(Ur));
+ if (t) for (let i = 0, a = t.length; i < a; i++) {
+ let a = t[i], o = this.morphTargetsRelative;
+ for (let t = 0, i = a.count; t < i; t++) Ur.fromBufferAttribute(a, t), o && (Br.fromBufferAttribute(e, t), Ur.add(Br)), r = Math.max(r, n.distanceToSquared(Ur));
+ }
+ this.boundingSphere.radius = Math.sqrt(r), isNaN(this.boundingSphere.radius) && console.error("THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The \"position\" attribute is likely to have NaN values.", this);
+ }
+ }
+ computeTangents() {
+ let e = this.index, t = this.attributes;
+ if (e === null || t.position === void 0 || t.normal === void 0 || t.uv === void 0) {
+ console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");
+ return;
+ }
+ let n = t.position, r = t.normal, i = t.uv;
+ this.hasAttribute("tangent") === !1 && this.setAttribute("tangent", new Nr(new Float32Array(4 * n.count), 4));
+ let a = this.getAttribute("tangent"), o = [], s = [];
+ for (let e = 0; e < n.count; e++) o[e] = new R(), s[e] = new R();
+ let c = new R(), l = new R(), u = new R(), d = new L(), f = new L(), p = new L(), m = new R(), h = new R();
+ function g(e, t, r) {
+ c.fromBufferAttribute(n, e), l.fromBufferAttribute(n, t), u.fromBufferAttribute(n, r), d.fromBufferAttribute(i, e), f.fromBufferAttribute(i, t), p.fromBufferAttribute(i, r), l.sub(c), u.sub(c), f.sub(d), p.sub(d);
+ let a = 1 / (f.x * p.y - p.x * f.y);
+ isFinite(a) && (m.copy(l).multiplyScalar(p.y).addScaledVector(u, -f.y).multiplyScalar(a), h.copy(u).multiplyScalar(f.x).addScaledVector(l, -p.x).multiplyScalar(a), o[e].add(m), o[t].add(m), o[r].add(m), s[e].add(h), s[t].add(h), s[r].add(h));
+ }
+ let _ = this.groups;
+ _.length === 0 && (_ = [{
+ start: 0,
+ count: e.count
+ }]);
+ for (let t = 0, n = _.length; t < n; ++t) {
+ let n = _[t], r = n.start, i = n.count;
+ for (let t = r, n = r + i; t < n; t += 3) g(e.getX(t + 0), e.getX(t + 1), e.getX(t + 2));
+ }
+ let v = new R(), y = new R(), b = new R(), x = new R();
+ function S(e) {
+ b.fromBufferAttribute(r, e), x.copy(b);
+ let t = o[e];
+ v.copy(t), v.sub(b.multiplyScalar(b.dot(t))).normalize(), y.crossVectors(x, t);
+ let n = y.dot(s[e]) < 0 ? -1 : 1;
+ a.setXYZW(e, v.x, v.y, v.z, n);
+ }
+ for (let t = 0, n = _.length; t < n; ++t) {
+ let n = _[t], r = n.start, i = n.count;
+ for (let t = r, n = r + i; t < n; t += 3) S(e.getX(t + 0)), S(e.getX(t + 1)), S(e.getX(t + 2));
+ }
+ }
+ computeVertexNormals() {
+ let e = this.index, t = this.getAttribute("position");
+ if (t !== void 0) {
+ let n = this.getAttribute("normal");
+ if (n === void 0) n = new Nr(new Float32Array(t.count * 3), 3), this.setAttribute("normal", n);
+ else for (let e = 0, t = n.count; e < t; e++) n.setXYZ(e, 0, 0, 0);
+ let r = new R(), i = new R(), a = new R(), o = new R(), s = new R(), c = new R(), l = new R(), u = new R();
+ if (e) for (let d = 0, f = e.count; d < f; d += 3) {
+ let f = e.getX(d + 0), p = e.getX(d + 1), m = e.getX(d + 2);
+ r.fromBufferAttribute(t, f), i.fromBufferAttribute(t, p), a.fromBufferAttribute(t, m), l.subVectors(a, i), u.subVectors(r, i), l.cross(u), o.fromBufferAttribute(n, f), s.fromBufferAttribute(n, p), c.fromBufferAttribute(n, m), o.add(l), s.add(l), c.add(l), n.setXYZ(f, o.x, o.y, o.z), n.setXYZ(p, s.x, s.y, s.z), n.setXYZ(m, c.x, c.y, c.z);
+ }
+ else for (let e = 0, o = t.count; e < o; e += 3) r.fromBufferAttribute(t, e + 0), i.fromBufferAttribute(t, e + 1), a.fromBufferAttribute(t, e + 2), l.subVectors(a, i), u.subVectors(r, i), l.cross(u), n.setXYZ(e + 0, l.x, l.y, l.z), n.setXYZ(e + 1, l.x, l.y, l.z), n.setXYZ(e + 2, l.x, l.y, l.z);
+ this.normalizeNormals(), n.needsUpdate = !0;
+ }
+ }
+ normalizeNormals() {
+ let e = this.attributes.normal;
+ for (let t = 0, n = e.count; t < n; t++) Ur.fromBufferAttribute(e, t), Ur.normalize(), e.setXYZ(t, Ur.x, Ur.y, Ur.z);
+ }
+ toNonIndexed() {
+ function t(e, t) {
+ let n = e.array, r = e.itemSize, i = e.normalized, a = new n.constructor(t.length * r), o = 0, s = 0;
+ for (let i = 0, c = t.length; i < c; i++) {
+ o = e.isInterleavedBufferAttribute ? t[i] * e.data.stride + e.offset : t[i] * r;
+ for (let e = 0; e < r; e++) a[s++] = n[o++];
+ }
+ return new Nr(a, r, i);
+ }
+ if (this.index === null) return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."), this;
+ let n = new e(), r = this.index.array, i = this.attributes;
+ for (let e in i) {
+ let a = i[e], o = t(a, r);
+ n.setAttribute(e, o);
+ }
+ let a = this.morphAttributes;
+ for (let e in a) {
+ let i = [], o = a[e];
+ for (let e = 0, n = o.length; e < n; e++) {
+ let n = o[e], a = t(n, r);
+ i.push(a);
+ }
+ n.morphAttributes[e] = i;
+ }
+ n.morphTargetsRelative = this.morphTargetsRelative;
+ let o = this.groups;
+ for (let e = 0, t = o.length; e < t; e++) {
+ let t = o[e];
+ n.addGroup(t.start, t.count, t.materialIndex);
+ }
+ return n;
+ }
+ toJSON() {
+ let e = { metadata: {
+ version: 4.6,
+ type: "BufferGeometry",
+ generator: "BufferGeometry.toJSON"
+ } };
+ if (e.uuid = this.uuid, e.type = this.type, this.name !== "" && (e.name = this.name), Object.keys(this.userData).length > 0 && (e.userData = this.userData), this.parameters !== void 0) {
+ let t = this.parameters;
+ for (let n in t) t[n] !== void 0 && (e[n] = t[n]);
+ return e;
+ }
+ e.data = { attributes: {} };
+ let t = this.index;
+ t !== null && (e.data.index = {
+ type: t.array.constructor.name,
+ array: Array.prototype.slice.call(t.array)
+ });
+ let n = this.attributes;
+ for (let t in n) {
+ let r = n[t];
+ e.data.attributes[t] = r.toJSON(e.data);
+ }
+ let r = {}, i = !1;
+ for (let t in this.morphAttributes) {
+ let n = this.morphAttributes[t], a = [];
+ for (let t = 0, r = n.length; t < r; t++) {
+ let r = n[t];
+ a.push(r.toJSON(e.data));
+ }
+ a.length > 0 && (r[t] = a, i = !0);
+ }
+ i && (e.data.morphAttributes = r, e.data.morphTargetsRelative = this.morphTargetsRelative);
+ let a = this.groups;
+ a.length > 0 && (e.data.groups = JSON.parse(JSON.stringify(a)));
+ let o = this.boundingSphere;
+ return o !== null && (e.data.boundingSphere = {
+ center: o.center.toArray(),
+ radius: o.radius
+ }), e;
+ }
+ clone() {
+ return new this.constructor().copy(this);
+ }
+ copy(e) {
+ this.index = null, this.attributes = {}, this.morphAttributes = {}, this.groups = [], this.boundingBox = null, this.boundingSphere = null;
+ let t = {};
+ this.name = e.name;
+ let n = e.index;
+ n !== null && this.setIndex(n.clone());
+ let r = e.attributes;
+ for (let e in r) {
+ let n = r[e];
+ this.setAttribute(e, n.clone(t));
+ }
+ let i = e.morphAttributes;
+ for (let e in i) {
+ let n = [], r = i[e];
+ for (let e = 0, i = r.length; e < i; e++) n.push(r[e].clone(t));
+ this.morphAttributes[e] = n;
+ }
+ this.morphTargetsRelative = e.morphTargetsRelative;
+ let a = e.groups;
+ for (let e = 0, t = a.length; e < t; e++) {
+ let t = a[e];
+ this.addGroup(t.start, t.count, t.materialIndex);
+ }
+ let o = e.boundingBox;
+ o !== null && (this.boundingBox = o.clone());
+ let s = e.boundingSphere;
+ return s !== null && (this.boundingSphere = s.clone()), this.drawRange.start = e.drawRange.start, this.drawRange.count = e.drawRange.count, this.userData = e.userData, this;
+ }
+ dispose() {
+ this.dispatchEvent({ type: "dispose" });
+ }
+}, Gr = /* @__PURE__ */ new z(), Kr = /* @__PURE__ */ new kn(), qr = /* @__PURE__ */ new xn(), Jr = /* @__PURE__ */ new R(), Yr = /* @__PURE__ */ new R(), Xr = /* @__PURE__ */ new R(), Zr = /* @__PURE__ */ new R(), Qr = /* @__PURE__ */ new R(), $r = /* @__PURE__ */ new R(), ei = /* @__PURE__ */ new R(), ti = /* @__PURE__ */ new R(), ni = class extends nr {
+ constructor(e = new Wr(), t = new wr()) {
+ super(), this.isMesh = !0, this.type = "Mesh", this.geometry = e, this.material = t, this.morphTargetDictionary = void 0, this.morphTargetInfluences = void 0, this.updateMorphTargets();
+ }
+ copy(e, t) {
+ return super.copy(e, t), e.morphTargetInfluences !== void 0 && (this.morphTargetInfluences = e.morphTargetInfluences.slice()), e.morphTargetDictionary !== void 0 && (this.morphTargetDictionary = Object.assign({}, e.morphTargetDictionary)), this.material = Array.isArray(e.material) ? e.material.slice() : e.material, this.geometry = e.geometry, this;
+ }
+ updateMorphTargets() {
+ let e = this.geometry.morphAttributes, t = Object.keys(e);
+ if (t.length > 0) {
+ let n = e[t[0]];
+ if (n !== void 0) {
+ this.morphTargetInfluences = [], this.morphTargetDictionary = {};
+ for (let e = 0, t = n.length; e < t; e++) {
+ let t = n[e].name || String(e);
+ this.morphTargetInfluences.push(0), this.morphTargetDictionary[t] = e;
+ }
+ }
+ }
+ }
+ getVertexPosition(e, t) {
+ let n = this.geometry, r = n.attributes.position, i = n.morphAttributes.position, a = n.morphTargetsRelative;
+ t.fromBufferAttribute(r, e);
+ let o = this.morphTargetInfluences;
+ if (i && o) {
+ $r.set(0, 0, 0);
+ for (let n = 0, r = i.length; n < r; n++) {
+ let r = o[n], s = i[n];
+ r !== 0 && (Qr.fromBufferAttribute(s, e), a ? $r.addScaledVector(Qr, r) : $r.addScaledVector(Qr.sub(t), r));
+ }
+ t.add($r);
+ }
+ return t;
+ }
+ raycast(e, t) {
+ let n = this.geometry, r = this.material, i = this.matrixWorld;
+ r !== void 0 && (n.boundingSphere === null && n.computeBoundingSphere(), qr.copy(n.boundingSphere), qr.applyMatrix4(i), Kr.copy(e.ray).recast(e.near), !(qr.containsPoint(Kr.origin) === !1 && (Kr.intersectSphere(qr, Jr) === null || Kr.origin.distanceToSquared(Jr) > (e.far - e.near) ** 2)) && (Gr.copy(i).invert(), Kr.copy(e.ray).applyMatrix4(Gr), !(n.boundingBox !== null && Kr.intersectsBox(n.boundingBox) === !1) && this._computeIntersections(e, t, Kr)));
+ }
+ _computeIntersections(e, t, n) {
+ let r, i = this.geometry, a = this.material, o = i.index, s = i.attributes.position, c = i.attributes.uv, l = i.attributes.uv1, u = i.attributes.normal, d = i.groups, f = i.drawRange;
+ if (o !== null) if (Array.isArray(a)) for (let i = 0, s = d.length; i < s; i++) {
+ let s = d[i], p = a[s.materialIndex], m = Math.max(s.start, f.start), h = Math.min(o.count, Math.min(s.start + s.count, f.start + f.count));
+ for (let i = m, a = h; i < a; i += 3) {
+ let a = o.getX(i), d = o.getX(i + 1), f = o.getX(i + 2);
+ r = ii(this, p, e, n, c, l, u, a, d, f), r && (r.faceIndex = Math.floor(i / 3), r.face.materialIndex = s.materialIndex, t.push(r));
+ }
+ }
+ else {
+ let i = Math.max(0, f.start), s = Math.min(o.count, f.start + f.count);
+ for (let d = i, f = s; d < f; d += 3) {
+ let i = o.getX(d), s = o.getX(d + 1), f = o.getX(d + 2);
+ r = ii(this, a, e, n, c, l, u, i, s, f), r && (r.faceIndex = Math.floor(d / 3), t.push(r));
+ }
+ }
+ else if (s !== void 0) if (Array.isArray(a)) for (let i = 0, o = d.length; i < o; i++) {
+ let o = d[i], p = a[o.materialIndex], m = Math.max(o.start, f.start), h = Math.min(s.count, Math.min(o.start + o.count, f.start + f.count));
+ for (let i = m, a = h; i < a; i += 3) {
+ let a = i, s = i + 1, d = i + 2;
+ r = ii(this, p, e, n, c, l, u, a, s, d), r && (r.faceIndex = Math.floor(i / 3), r.face.materialIndex = o.materialIndex, t.push(r));
+ }
+ }
+ else {
+ let i = Math.max(0, f.start), o = Math.min(s.count, f.start + f.count);
+ for (let s = i, d = o; s < d; s += 3) {
+ let i = s, o = s + 1, d = s + 2;
+ r = ii(this, a, e, n, c, l, u, i, o, d), r && (r.faceIndex = Math.floor(s / 3), t.push(r));
+ }
+ }
+ }
+};
+function ri(e, t, n, r, i, a, o, s) {
+ let c;
+ if (c = t.side === 1 ? r.intersectTriangle(o, a, i, !0, s) : r.intersectTriangle(i, a, o, t.side === 0, s), c === null) return null;
+ ti.copy(s), ti.applyMatrix4(e.matrixWorld);
+ let l = n.ray.origin.distanceTo(ti);
+ return l < n.near || l > n.far ? null : {
+ distance: l,
+ point: ti.clone(),
+ object: e
+ };
+}
+function ii(e, t, n, r, i, a, o, s, c, l) {
+ e.getVertexPosition(s, Yr), e.getVertexPosition(c, Xr), e.getVertexPosition(l, Zr);
+ let u = ri(e, t, n, r, Yr, Xr, Zr, ei);
+ if (u) {
+ let e = new R();
+ gr.getBarycoord(ei, Yr, Xr, Zr, e), i && (u.uv = gr.getInterpolatedAttribute(i, s, c, l, e, new L())), a && (u.uv1 = gr.getInterpolatedAttribute(a, s, c, l, e, new L())), o && (u.normal = gr.getInterpolatedAttribute(o, s, c, l, e, new R()), u.normal.dot(r.direction) > 0 && u.normal.multiplyScalar(-1));
+ let t = {
+ a: s,
+ b: c,
+ c: l,
+ normal: new R(),
+ materialIndex: 0
+ };
+ gr.getNormal(Yr, Xr, Zr, t.normal), u.face = t, u.barycoord = e;
+ }
+ return u;
+}
+var ai = class e extends Wr {
+ constructor(e = 1, t = 1, n = 1, r = 1, i = 1, a = 1) {
+ super(), this.type = "BoxGeometry", this.parameters = {
+ width: e,
+ height: t,
+ depth: n,
+ widthSegments: r,
+ heightSegments: i,
+ depthSegments: a
+ };
+ let o = this;
+ r = Math.floor(r), i = Math.floor(i), a = Math.floor(a);
+ let s = [], c = [], l = [], u = [], d = 0, f = 0;
+ p("z", "y", "x", -1, -1, n, t, e, a, i, 0), p("z", "y", "x", 1, -1, n, t, -e, a, i, 1), p("x", "z", "y", 1, 1, e, n, t, r, a, 2), p("x", "z", "y", 1, -1, e, n, -t, r, a, 3), p("x", "y", "z", 1, -1, e, t, n, r, i, 4), p("x", "y", "z", -1, -1, e, t, -n, r, i, 5), this.setIndex(s), this.setAttribute("position", new Ir(c, 3)), this.setAttribute("normal", new Ir(l, 3)), this.setAttribute("uv", new Ir(u, 2));
+ function p(e, t, n, r, i, a, p, m, h, g, _) {
+ let v = a / h, y = p / g, b = a / 2, x = p / 2, S = m / 2, C = h + 1, w = g + 1, T = 0, E = 0, D = new R();
+ for (let a = 0; a < w; a++) {
+ let o = a * y - x;
+ for (let s = 0; s < C; s++) D[e] = (s * v - b) * r, D[t] = o * i, D[n] = S, c.push(D.x, D.y, D.z), D[e] = 0, D[t] = 0, D[n] = m > 0 ? 1 : -1, l.push(D.x, D.y, D.z), u.push(s / h), u.push(1 - a / g), T += 1;
+ }
+ for (let e = 0; e < g; e++) for (let t = 0; t < h; t++) {
+ let n = d + t + C * e, r = d + t + C * (e + 1), i = d + (t + 1) + C * (e + 1), a = d + (t + 1) + C * e;
+ s.push(n, r, a), s.push(r, i, a), E += 6;
+ }
+ o.addGroup(f, E, _), f += E, d += T;
+ }
+ }
+ copy(e) {
+ return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
+ }
+ static fromJSON(t) {
+ return new e(t.width, t.height, t.depth, t.widthSegments, t.heightSegments, t.depthSegments);
+ }
+};
+function oi(e) {
+ let t = {};
+ for (let n in e) {
+ t[n] = {};
+ for (let r in e[n]) {
+ let i = e[n][r];
+ i && (i.isColor || i.isMatrix3 || i.isMatrix4 || i.isVector2 || i.isVector3 || i.isVector4 || i.isTexture || i.isQuaternion) ? i.isRenderTargetTexture ? (console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."), t[n][r] = null) : t[n][r] = i.clone() : Array.isArray(i) ? t[n][r] = i.slice() : t[n][r] = i;
+ }
+ }
+ return t;
+}
+function si(e) {
+ let t = {};
+ for (let n = 0; n < e.length; n++) {
+ let r = oi(e[n]);
+ for (let e in r) t[e] = r[e];
+ }
+ return t;
+}
+function ci(e) {
+ let t = [];
+ for (let n = 0; n < e.length; n++) t.push(e[n].clone());
+ return t;
+}
+function li(e) {
+ let t = e.getRenderTarget();
+ return t === null ? e.outputColorSpace : t.isXRRenderTarget === !0 ? t.texture.colorSpace : Rt.workingColorSpace;
+}
+var ui = {
+ clone: oi,
+ merge: si
+}, di = "void main() {\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}", fi = "void main() {\n gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}", pi = class extends Cr {
+ constructor(e) {
+ super(), this.isShaderMaterial = !0, this.type = "ShaderMaterial", this.defines = {}, this.uniforms = {}, this.uniformsGroups = [], this.vertexShader = di, this.fragmentShader = fi, this.linewidth = 1, this.wireframe = !1, this.wireframeLinewidth = 1, this.fog = !1, this.lights = !1, this.clipping = !1, this.forceSinglePass = !0, this.extensions = {
+ clipCullDistance: !1,
+ multiDraw: !1
+ }, this.defaultAttributeValues = {
+ color: [
+ 1,
+ 1,
+ 1
+ ],
+ uv: [0, 0],
+ uv1: [0, 0]
+ }, this.index0AttributeName = void 0, this.uniformsNeedUpdate = !1, this.glslVersion = null, e !== void 0 && this.setValues(e);
+ }
+ copy(e) {
+ return super.copy(e), this.fragmentShader = e.fragmentShader, this.vertexShader = e.vertexShader, this.uniforms = oi(e.uniforms), this.uniformsGroups = ci(e.uniformsGroups), this.defines = Object.assign({}, e.defines), this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.fog = e.fog, this.lights = e.lights, this.clipping = e.clipping, this.extensions = Object.assign({}, e.extensions), this.glslVersion = e.glslVersion, this;
+ }
+ toJSON(e) {
+ let t = super.toJSON(e);
+ t.glslVersion = this.glslVersion, t.uniforms = {};
+ for (let n in this.uniforms) {
+ let r = this.uniforms[n].value;
+ r && r.isTexture ? t.uniforms[n] = {
+ type: "t",
+ value: r.toJSON(e).uuid
+ } : r && r.isColor ? t.uniforms[n] = {
+ type: "c",
+ value: r.getHex()
+ } : r && r.isVector2 ? t.uniforms[n] = {
+ type: "v2",
+ value: r.toArray()
+ } : r && r.isVector3 ? t.uniforms[n] = {
+ type: "v3",
+ value: r.toArray()
+ } : r && r.isVector4 ? t.uniforms[n] = {
+ type: "v4",
+ value: r.toArray()
+ } : r && r.isMatrix3 ? t.uniforms[n] = {
+ type: "m3",
+ value: r.toArray()
+ } : r && r.isMatrix4 ? t.uniforms[n] = {
+ type: "m4",
+ value: r.toArray()
+ } : t.uniforms[n] = { value: r };
+ }
+ Object.keys(this.defines).length > 0 && (t.defines = this.defines), t.vertexShader = this.vertexShader, t.fragmentShader = this.fragmentShader, t.lights = this.lights, t.clipping = this.clipping;
+ let n = {};
+ for (let e in this.extensions) this.extensions[e] === !0 && (n[e] = !0);
+ return Object.keys(n).length > 0 && (t.extensions = n), t;
+ }
+}, mi = class extends nr {
+ constructor() {
+ super(), this.isCamera = !0, this.type = "Camera", this.matrixWorldInverse = new z(), this.projectionMatrix = new z(), this.projectionMatrixInverse = new z(), this.coordinateSystem = Ze;
+ }
+ copy(e, t) {
+ return super.copy(e, t), this.matrixWorldInverse.copy(e.matrixWorldInverse), this.projectionMatrix.copy(e.projectionMatrix), this.projectionMatrixInverse.copy(e.projectionMatrixInverse), this.coordinateSystem = e.coordinateSystem, this;
+ }
+ getWorldDirection(e) {
+ return super.getWorldDirection(e).negate();
+ }
+ updateMatrixWorld(e) {
+ super.updateMatrixWorld(e), this.matrixWorldInverse.copy(this.matrixWorld).invert();
+ }
+ updateWorldMatrix(e, t) {
+ super.updateWorldMatrix(e, t), this.matrixWorldInverse.copy(this.matrixWorld).invert();
+ }
+ clone() {
+ return new this.constructor().copy(this);
+ }
+}, hi = /* @__PURE__ */ new R(), gi = /* @__PURE__ */ new L(), _i = /* @__PURE__ */ new L(), vi = class extends mi {
+ constructor(e = 50, t = 1, n = .1, r = 2e3) {
+ super(), this.isPerspectiveCamera = !0, this.type = "PerspectiveCamera", this.fov = e, this.zoom = 1, this.near = n, this.far = r, this.focus = 10, this.aspect = t, this.view = null, this.filmGauge = 35, this.filmOffset = 0, this.updateProjectionMatrix();
+ }
+ copy(e, t) {
+ return super.copy(e, t), this.fov = e.fov, this.zoom = e.zoom, this.near = e.near, this.far = e.far, this.focus = e.focus, this.aspect = e.aspect, this.view = e.view === null ? null : Object.assign({}, e.view), this.filmGauge = e.filmGauge, this.filmOffset = e.filmOffset, this;
+ }
+ setFocalLength(e) {
+ let t = .5 * this.getFilmHeight() / e;
+ this.fov = nt * 2 * Math.atan(t), this.updateProjectionMatrix();
+ }
+ getFocalLength() {
+ let e = Math.tan(tt * .5 * this.fov);
+ return .5 * this.getFilmHeight() / e;
+ }
+ getEffectiveFOV() {
+ return nt * 2 * Math.atan(Math.tan(tt * .5 * this.fov) / this.zoom);
+ }
+ getFilmWidth() {
+ return this.filmGauge * Math.min(this.aspect, 1);
+ }
+ getFilmHeight() {
+ return this.filmGauge / Math.max(this.aspect, 1);
+ }
+ getViewBounds(e, t, n) {
+ hi.set(-1, -1, .5).applyMatrix4(this.projectionMatrixInverse), t.set(hi.x, hi.y).multiplyScalar(-e / hi.z), hi.set(1, 1, .5).applyMatrix4(this.projectionMatrixInverse), n.set(hi.x, hi.y).multiplyScalar(-e / hi.z);
+ }
+ getViewSize(e, t) {
+ return this.getViewBounds(e, gi, _i), t.subVectors(_i, gi);
+ }
+ setViewOffset(e, t, n, r, i, a) {
+ this.aspect = e / t, this.view === null && (this.view = {
+ enabled: !0,
+ fullWidth: 1,
+ fullHeight: 1,
+ offsetX: 0,
+ offsetY: 0,
+ width: 1,
+ height: 1
+ }), this.view.enabled = !0, this.view.fullWidth = e, this.view.fullHeight = t, this.view.offsetX = n, this.view.offsetY = r, this.view.width = i, this.view.height = a, this.updateProjectionMatrix();
+ }
+ clearViewOffset() {
+ this.view !== null && (this.view.enabled = !1), this.updateProjectionMatrix();
+ }
+ updateProjectionMatrix() {
+ let e = this.near, t = e * Math.tan(tt * .5 * this.fov) / this.zoom, n = 2 * t, r = this.aspect * n, i = -.5 * r, a = this.view;
+ if (this.view !== null && this.view.enabled) {
+ let e = a.fullWidth, o = a.fullHeight;
+ i += a.offsetX * r / e, t -= a.offsetY * n / o, r *= a.width / e, n *= a.height / o;
+ }
+ let o = this.filmOffset;
+ o !== 0 && (i += e * o / this.getFilmWidth()), this.projectionMatrix.makePerspective(i, i + r, t, t - n, e, this.far, this.coordinateSystem), this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
+ }
+ toJSON(e) {
+ let t = super.toJSON(e);
+ return t.object.fov = this.fov, t.object.zoom = this.zoom, t.object.near = this.near, t.object.far = this.far, t.object.focus = this.focus, t.object.aspect = this.aspect, this.view !== null && (t.object.view = Object.assign({}, this.view)), t.object.filmGauge = this.filmGauge, t.object.filmOffset = this.filmOffset, t;
+ }
+}, yi = -90, bi = 1, xi = class extends nr {
+ constructor(e, t, n) {
+ super(), this.type = "CubeCamera", this.renderTarget = n, this.coordinateSystem = null, this.activeMipmapLevel = 0;
+ let r = new vi(yi, bi, e, t);
+ r.layers = this.layers, this.add(r);
+ let i = new vi(yi, bi, e, t);
+ i.layers = this.layers, this.add(i);
+ let a = new vi(yi, bi, e, t);
+ a.layers = this.layers, this.add(a);
+ let o = new vi(yi, bi, e, t);
+ o.layers = this.layers, this.add(o);
+ let s = new vi(yi, bi, e, t);
+ s.layers = this.layers, this.add(s);
+ let c = new vi(yi, bi, e, t);
+ c.layers = this.layers, this.add(c);
+ }
+ updateCoordinateSystem() {
+ let e = this.coordinateSystem, t = this.children.concat(), [n, r, i, a, o, s] = t;
+ for (let e of t) this.remove(e);
+ if (e === 2e3) n.up.set(0, 1, 0), n.lookAt(1, 0, 0), r.up.set(0, 1, 0), r.lookAt(-1, 0, 0), i.up.set(0, 0, -1), i.lookAt(0, 1, 0), a.up.set(0, 0, 1), a.lookAt(0, -1, 0), o.up.set(0, 1, 0), o.lookAt(0, 0, 1), s.up.set(0, 1, 0), s.lookAt(0, 0, -1);
+ else if (e === 2001) n.up.set(0, -1, 0), n.lookAt(-1, 0, 0), r.up.set(0, -1, 0), r.lookAt(1, 0, 0), i.up.set(0, 0, 1), i.lookAt(0, 1, 0), a.up.set(0, 0, -1), a.lookAt(0, -1, 0), o.up.set(0, -1, 0), o.lookAt(0, 0, 1), s.up.set(0, -1, 0), s.lookAt(0, 0, -1);
+ else throw Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: " + e);
+ for (let e of t) this.add(e), e.updateMatrixWorld();
+ }
+ update(e, t) {
+ this.parent === null && this.updateMatrixWorld();
+ let { renderTarget: n, activeMipmapLevel: r } = this;
+ this.coordinateSystem !== e.coordinateSystem && (this.coordinateSystem = e.coordinateSystem, this.updateCoordinateSystem());
+ let [i, a, o, s, c, l] = this.children, u = e.getRenderTarget(), d = e.getActiveCubeFace(), f = e.getActiveMipmapLevel(), p = e.xr.enabled;
+ e.xr.enabled = !1;
+ let m = n.texture.generateMipmaps;
+ n.texture.generateMipmaps = !1, e.setRenderTarget(n, 0, r), e.render(t, i), e.setRenderTarget(n, 1, r), e.render(t, a), e.setRenderTarget(n, 2, r), e.render(t, o), e.setRenderTarget(n, 3, r), e.render(t, s), e.setRenderTarget(n, 4, r), e.render(t, c), n.texture.generateMipmaps = m, e.setRenderTarget(n, 5, r), e.render(t, l), e.setRenderTarget(u, d, f), e.xr.enabled = p, n.texture.needsPMREMUpdate = !0;
+ }
+}, Si = class extends qt {
+ constructor(e = [], t = 301, n, r, i, a, o, s, c, l) {
+ super(e, t, n, r, i, a, o, s, c, l), this.isCubeTexture = !0, this.flipY = !1;
+ }
+ get images() {
+ return this.image;
+ }
+ set images(e) {
+ this.image = e;
+ }
+}, Ci = class extends Xt {
+ constructor(e = 1, t = {}) {
+ super(e, e, t), this.isWebGLCubeRenderTarget = !0;
+ let n = {
+ width: e,
+ height: e,
+ depth: 1
+ };
+ this.texture = new Si([
+ n,
+ n,
+ n,
+ n,
+ n,
+ n
+ ], t.mapping, t.wrapS, t.wrapT, t.magFilter, t.minFilter, t.format, t.type, t.anisotropy, t.colorSpace), this.texture.isRenderTargetTexture = !0, this.texture.generateMipmaps = t.generateMipmaps === void 0 ? !1 : t.generateMipmaps, this.texture.minFilter = t.minFilter === void 0 ? d : t.minFilter;
+ }
+ fromEquirectangularTexture(e, t) {
+ this.texture.type = t.type, this.texture.colorSpace = t.colorSpace, this.texture.generateMipmaps = t.generateMipmaps, this.texture.minFilter = t.minFilter, this.texture.magFilter = t.magFilter;
+ let n = {
+ uniforms: { tEquirect: { value: null } },
+ vertexShader: "\n\n varying vec3 vWorldDirection;\n\n vec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n }\n\n void main() {\n\n vWorldDirection = transformDirection( position, modelMatrix );\n\n #include <begin_vertex>\n #include <project_vertex>\n\n }\n ",
+ fragmentShader: "\n\n uniform sampler2D tEquirect;\n\n varying vec3 vWorldDirection;\n\n #include <common>\n\n void main() {\n\n vec3 direction = normalize( vWorldDirection );\n\n vec2 sampleUV = equirectUv( direction );\n\n gl_FragColor = texture2D( tEquirect, sampleUV );\n\n }\n "
+ }, r = new ai(5, 5, 5), i = new pi({
+ name: "CubemapFromEquirect",
+ uniforms: oi(n.uniforms),
+ vertexShader: n.vertexShader,
+ fragmentShader: n.fragmentShader,
+ side: 1,
+ blending: 0
+ });
+ i.uniforms.tEquirect.value = t;
+ let a = new ni(r, i), o = t.minFilter;
+ return t.minFilter === 1008 && (t.minFilter = d), new xi(1, 10, this).update(e, a), t.minFilter = o, a.geometry.dispose(), a.material.dispose(), this;
+ }
+ clear(e, t = !0, n = !0, r = !0) {
+ let i = e.getRenderTarget();
+ for (let i = 0; i < 6; i++) e.setRenderTarget(this, i), e.clear(t, n, r);
+ e.setRenderTarget(i);
+ }
+}, wi = class extends nr {
+ constructor() {
+ super(), this.isGroup = !0, this.type = "Group";
+ }
+}, Ti = { type: "move" }, Ei = class {
+ constructor() {
+ this._targetRay = null, this._grip = null, this._hand = null;
+ }
+ getHandSpace() {
+ return this._hand === null && (this._hand = new wi(), this._hand.matrixAutoUpdate = !1, this._hand.visible = !1, this._hand.joints = {}, this._hand.inputState = { pinching: !1 }), this._hand;
+ }
+ getTargetRaySpace() {
+ return this._targetRay === null && (this._targetRay = new wi(), this._targetRay.matrixAutoUpdate = !1, this._targetRay.visible = !1, this._targetRay.hasLinearVelocity = !1, this._targetRay.linearVelocity = new R(), this._targetRay.hasAngularVelocity = !1, this._targetRay.angularVelocity = new R()), this._targetRay;
+ }
+ getGripSpace() {
+ return this._grip === null && (this._grip = new wi(), this._grip.matrixAutoUpdate = !1, this._grip.visible = !1, this._grip.hasLinearVelocity = !1, this._grip.linearVelocity = new R(), this._grip.hasAngularVelocity = !1, this._grip.angularVelocity = new R()), this._grip;
+ }
+ dispatchEvent(e) {
+ return this._targetRay !== null && this._targetRay.dispatchEvent(e), this._grip !== null && this._grip.dispatchEvent(e), this._hand !== null && this._hand.dispatchEvent(e), this;
+ }
+ connect(e) {
+ if (e && e.hand) {
+ let t = this._hand;
+ if (t) for (let n of e.hand.values()) this._getHandJoint(t, n);
+ }
+ return this.dispatchEvent({
+ type: "connected",
+ data: e
+ }), this;
+ }
+ disconnect(e) {
+ return this.dispatchEvent({
+ type: "disconnected",
+ data: e
+ }), this._targetRay !== null && (this._targetRay.visible = !1), this._grip !== null && (this._grip.visible = !1), this._hand !== null && (this._hand.visible = !1), this;
+ }
+ update(e, t, n) {
+ let r = null, i = null, a = null, o = this._targetRay, s = this._grip, c = this._hand;
+ if (e && t.session.visibilityState !== "visible-blurred") {
+ if (c && e.hand) {
+ a = !0;
+ for (let r of e.hand.values()) {
+ let e = t.getJointPose(r, n), i = this._getHandJoint(c, r);
+ e !== null && (i.matrix.fromArray(e.transform.matrix), i.matrix.decompose(i.position, i.rotation, i.scale), i.matrixWorldNeedsUpdate = !0, i.jointRadius = e.radius), i.visible = e !== null;
+ }
+ let r = c.joints["index-finger-tip"], i = c.joints["thumb-tip"], o = r.position.distanceTo(i.position), s = .02, l = .005;
+ c.inputState.pinching && o > s + l ? (c.inputState.pinching = !1, this.dispatchEvent({
+ type: "pinchend",
+ handedness: e.handedness,
+ target: this
+ })) : !c.inputState.pinching && o <= s - l && (c.inputState.pinching = !0, this.dispatchEvent({
+ type: "pinchstart",
+ handedness: e.handedness,
+ target: this
+ }));
+ } else s !== null && e.gripSpace && (i = t.getPose(e.gripSpace, n), i !== null && (s.matrix.fromArray(i.transform.matrix), s.matrix.decompose(s.position, s.rotation, s.scale), s.matrixWorldNeedsUpdate = !0, i.linearVelocity ? (s.hasLinearVelocity = !0, s.linearVelocity.copy(i.linearVelocity)) : s.hasLinearVelocity = !1, i.angularVelocity ? (s.hasAngularVelocity = !0, s.angularVelocity.copy(i.angularVelocity)) : s.hasAngularVelocity = !1));
+ o !== null && (r = t.getPose(e.targetRaySpace, n), r === null && i !== null && (r = i), r !== null && (o.matrix.fromArray(r.transform.matrix), o.matrix.decompose(o.position, o.rotation, o.scale), o.matrixWorldNeedsUpdate = !0, r.linearVelocity ? (o.hasLinearVelocity = !0, o.linearVelocity.copy(r.linearVelocity)) : o.hasLinearVelocity = !1, r.angularVelocity ? (o.hasAngularVelocity = !0, o.angularVelocity.copy(r.angularVelocity)) : o.hasAngularVelocity = !1, this.dispatchEvent(Ti)));
+ }
+ return o !== null && (o.visible = r !== null), s !== null && (s.visible = i !== null), c !== null && (c.visible = a !== null), this;
+ }
+ _getHandJoint(e, t) {
+ if (e.joints[t.jointName] === void 0) {
+ let n = new wi();
+ n.matrixAutoUpdate = !1, n.visible = !1, e.joints[t.jointName] = n, e.add(n);
+ }
+ return e.joints[t.jointName];
+ }
+}, Di = class extends nr {
+ constructor() {
+ super(), this.isScene = !0, this.type = "Scene", this.background = null, this.environment = null, this.fog = null, this.backgroundBlurriness = 0, this.backgroundIntensity = 1, this.backgroundRotation = new zn(), this.environmentIntensity = 1, this.environmentRotation = new zn(), this.overrideMaterial = null, typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this }));
+ }
+ copy(e, t) {
+ return super.copy(e, t), e.background !== null && (this.background = e.background.clone()), e.environment !== null && (this.environment = e.environment.clone()), e.fog !== null && (this.fog = e.fog.clone()), this.backgroundBlurriness = e.backgroundBlurriness, this.backgroundIntensity = e.backgroundIntensity, this.backgroundRotation.copy(e.backgroundRotation), this.environmentIntensity = e.environmentIntensity, this.environmentRotation.copy(e.environmentRotation), e.overrideMaterial !== null && (this.overrideMaterial = e.overrideMaterial.clone()), this.matrixAutoUpdate = e.matrixAutoUpdate, this;
+ }
+ toJSON(e) {
+ let t = super.toJSON(e);
+ return this.fog !== null && (t.object.fog = this.fog.toJSON()), this.backgroundBlurriness > 0 && (t.object.backgroundBlurriness = this.backgroundBlurriness), this.backgroundIntensity !== 1 && (t.object.backgroundIntensity = this.backgroundIntensity), t.object.backgroundRotation = this.backgroundRotation.toArray(), this.environmentIntensity !== 1 && (t.object.environmentIntensity = this.environmentIntensity), t.object.environmentRotation = this.environmentRotation.toArray(), t;
+ }
+}, Oi = class {
+ constructor(e, t) {
+ this.isInterleavedBuffer = !0, this.array = e, this.stride = t, this.count = e === void 0 ? 0 : e.length / t, this.usage = Xe, this.updateRanges = [], this.version = 0, this.uuid = rt();
+ }
+ onUploadCallback() {}
+ set needsUpdate(e) {
+ e === !0 && this.version++;
+ }
+ setUsage(e) {
+ return this.usage = e, this;
+ }
+ addUpdateRange(e, t) {
+ this.updateRanges.push({
+ start: e,
+ count: t
+ });
+ }
+ clearUpdateRanges() {
+ this.updateRanges.length = 0;
+ }
+ copy(e) {
+ return this.array = new e.array.constructor(e.array), this.count = e.count, this.stride = e.stride, this.usage = e.usage, this;
+ }
+ copyAt(e, t, n) {
+ e *= this.stride, n *= t.stride;
+ for (let r = 0, i = this.stride; r < i; r++) this.array[e + r] = t.array[n + r];
+ return this;
+ }
+ set(e, t = 0) {
+ return this.array.set(e, t), this;
+ }
+ clone(e) {
+ e.arrayBuffers === void 0 && (e.arrayBuffers = {}), this.array.buffer._uuid === void 0 && (this.array.buffer._uuid = rt()), e.arrayBuffers[this.array.buffer._uuid] === void 0 && (e.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer);
+ let t = new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]), n = new this.constructor(t, this.stride);
+ return n.setUsage(this.usage), n;
+ }
+ onUpload(e) {
+ return this.onUploadCallback = e, this;
+ }
+ toJSON(e) {
+ return e.arrayBuffers === void 0 && (e.arrayBuffers = {}), this.array.buffer._uuid === void 0 && (this.array.buffer._uuid = rt()), e.arrayBuffers[this.array.buffer._uuid] === void 0 && (e.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer))), {
+ uuid: this.uuid,
+ buffer: this.array.buffer._uuid,
+ type: this.array.constructor.name,
+ stride: this.stride
+ };
+ }
+}, ki = /* @__PURE__ */ new R(), Ai = class e {
+ constructor(e, t, n, r = !1) {
+ this.isInterleavedBufferAttribute = !0, this.name = "", this.data = e, this.itemSize = t, this.offset = n, this.normalized = r;
+ }
+ get count() {
+ return this.data.count;
+ }
+ get array() {
+ return this.data.array;
+ }
+ set needsUpdate(e) {
+ this.data.needsUpdate = e;
+ }
+ applyMatrix4(e) {
+ for (let t = 0, n = this.data.count; t < n; t++) ki.fromBufferAttribute(this, t), ki.applyMatrix4(e), this.setXYZ(t, ki.x, ki.y, ki.z);
+ return this;
+ }
+ applyNormalMatrix(e) {
+ for (let t = 0, n = this.count; t < n; t++) ki.fromBufferAttribute(this, t), ki.applyNormalMatrix(e), this.setXYZ(t, ki.x, ki.y, ki.z);
+ return this;
+ }
+ transformDirection(e) {
+ for (let t = 0, n = this.count; t < n; t++) ki.fromBufferAttribute(this, t), ki.transformDirection(e), this.setXYZ(t, ki.x, ki.y, ki.z);
+ return this;
+ }
+ getComponent(e, t) {
+ let n = this.array[e * this.data.stride + this.offset + t];
+ return this.normalized && (n = St(n, this.array)), n;
+ }
+ setComponent(e, t, n) {
+ return this.normalized && (n = Ct(n, this.array)), this.data.array[e * this.data.stride + this.offset + t] = n, this;
+ }
+ setX(e, t) {
+ return this.normalized && (t = Ct(t, this.array)), this.data.array[e * this.data.stride + this.offset] = t, this;
+ }
+ setY(e, t) {
+ return this.normalized && (t = Ct(t, this.array)), this.data.array[e * this.data.stride + this.offset + 1] = t, this;
+ }
+ setZ(e, t) {
+ return this.normalized && (t = Ct(t, this.array)), this.data.array[e * this.data.stride + this.offset + 2] = t, this;
+ }
+ setW(e, t) {
+ return this.normalized && (t = Ct(t, this.array)), this.data.array[e * this.data.stride + this.offset + 3] = t, this;
+ }
+ getX(e) {
+ let t = this.data.array[e * this.data.stride + this.offset];
+ return this.normalized && (t = St(t, this.array)), t;
+ }
+ getY(e) {
+ let t = this.data.array[e * this.data.stride + this.offset + 1];
+ return this.normalized && (t = St(t, this.array)), t;
+ }
+ getZ(e) {
+ let t = this.data.array[e * this.data.stride + this.offset + 2];
+ return this.normalized && (t = St(t, this.array)), t;
+ }
+ getW(e) {
+ let t = this.data.array[e * this.data.stride + this.offset + 3];
+ return this.normalized && (t = St(t, this.array)), t;
+ }
+ setXY(e, t, n) {
+ return e = e * this.data.stride + this.offset, this.normalized && (t = Ct(t, this.array), n = Ct(n, this.array)), this.data.array[e + 0] = t, this.data.array[e + 1] = n, this;
+ }
+ setXYZ(e, t, n, r) {
+ return e = e * this.data.stride + this.offset, this.normalized && (t = Ct(t, this.array), n = Ct(n, this.array), r = Ct(r, this.array)), this.data.array[e + 0] = t, this.data.array[e + 1] = n, this.data.array[e + 2] = r, this;
+ }
+ setXYZW(e, t, n, r, i) {
+ return e = e * this.data.stride + this.offset, this.normalized && (t = Ct(t, this.array), n = Ct(n, this.array), r = Ct(r, this.array), i = Ct(i, this.array)), this.data.array[e + 0] = t, this.data.array[e + 1] = n, this.data.array[e + 2] = r, this.data.array[e + 3] = i, this;
+ }
+ clone(t) {
+ if (t === void 0) {
+ console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");
+ let e = [];
+ for (let t = 0; t < this.count; t++) {
+ let n = t * this.data.stride + this.offset;
+ for (let t = 0; t < this.itemSize; t++) e.push(this.data.array[n + t]);
+ }
+ return new Nr(new this.array.constructor(e), this.itemSize, this.normalized);
+ } else return t.interleavedBuffers === void 0 && (t.interleavedBuffers = {}), t.interleavedBuffers[this.data.uuid] === void 0 && (t.interleavedBuffers[this.data.uuid] = this.data.clone(t)), new e(t.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
+ }
+ toJSON(e) {
+ if (e === void 0) {
+ console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");
+ let e = [];
+ for (let t = 0; t < this.count; t++) {
+ let n = t * this.data.stride + this.offset;
+ for (let t = 0; t < this.itemSize; t++) e.push(this.data.array[n + t]);
+ }
+ return {
+ itemSize: this.itemSize,
+ type: this.array.constructor.name,
+ array: e,
+ normalized: this.normalized
+ };
+ } else return e.interleavedBuffers === void 0 && (e.interleavedBuffers = {}), e.interleavedBuffers[this.data.uuid] === void 0 && (e.interleavedBuffers[this.data.uuid] = this.data.toJSON(e)), {
+ isInterleavedBufferAttribute: !0,
+ itemSize: this.itemSize,
+ data: this.data.uuid,
+ offset: this.offset,
+ normalized: this.normalized
+ };
+ }
+}, ji = /* @__PURE__ */ new R(), Mi = /* @__PURE__ */ new Jt(), Ni = /* @__PURE__ */ new Jt(), Pi = /* @__PURE__ */ new R(), Fi = /* @__PURE__ */ new z(), Ii = /* @__PURE__ */ new R(), Li = /* @__PURE__ */ new xn(), Ri = /* @__PURE__ */ new z(), zi = /* @__PURE__ */ new kn(), Bi = class extends ni {
+ constructor(e, t) {
+ super(e, t), this.isSkinnedMesh = !0, this.type = "SkinnedMesh", this.bindMode = i, this.bindMatrix = new z(), this.bindMatrixInverse = new z(), this.boundingBox = null, this.boundingSphere = null;
+ }
+ computeBoundingBox() {
+ let e = this.geometry;
+ this.boundingBox === null && (this.boundingBox = new nn()), this.boundingBox.makeEmpty();
+ let t = e.getAttribute("position");
+ for (let e = 0; e < t.count; e++) this.getVertexPosition(e, Ii), this.boundingBox.expandByPoint(Ii);
+ }
+ computeBoundingSphere() {
+ let e = this.geometry;
+ this.boundingSphere === null && (this.boundingSphere = new xn()), this.boundingSphere.makeEmpty();
+ let t = e.getAttribute("position");
+ for (let e = 0; e < t.count; e++) this.getVertexPosition(e, Ii), this.boundingSphere.expandByPoint(Ii);
+ }
+ copy(e, t) {
+ return super.copy(e, t), this.bindMode = e.bindMode, this.bindMatrix.copy(e.bindMatrix), this.bindMatrixInverse.copy(e.bindMatrixInverse), this.skeleton = e.skeleton, e.boundingBox !== null && (this.boundingBox = e.boundingBox.clone()), e.boundingSphere !== null && (this.boundingSphere = e.boundingSphere.clone()), this;
+ }
+ raycast(e, t) {
+ let n = this.material, r = this.matrixWorld;
+ n !== void 0 && (this.boundingSphere === null && this.computeBoundingSphere(), Li.copy(this.boundingSphere), Li.applyMatrix4(r), e.ray.intersectsSphere(Li) !== !1 && (Ri.copy(r).invert(), zi.copy(e.ray).applyMatrix4(Ri), !(this.boundingBox !== null && zi.intersectsBox(this.boundingBox) === !1) && this._computeIntersections(e, t, zi)));
+ }
+ getVertexPosition(e, t) {
+ return super.getVertexPosition(e, t), this.applyBoneTransform(e, t), t;
+ }
+ bind(e, t) {
+ this.skeleton = e, t === void 0 && (this.updateMatrixWorld(!0), this.skeleton.calculateInverses(), t = this.matrixWorld), this.bindMatrix.copy(t), this.bindMatrixInverse.copy(t).invert();
+ }
+ pose() {
+ this.skeleton.pose();
+ }
+ normalizeSkinWeights() {
+ let e = new Jt(), t = this.geometry.attributes.skinWeight;
+ for (let n = 0, r = t.count; n < r; n++) {
+ e.fromBufferAttribute(t, n);
+ let r = 1 / e.manhattanLength();
+ r === Infinity ? e.set(1, 0, 0, 0) : e.multiplyScalar(r), t.setXYZW(n, e.x, e.y, e.z, e.w);
+ }
+ }
+ updateMatrixWorld(e) {
+ super.updateMatrixWorld(e), this.bindMode === "attached" ? this.bindMatrixInverse.copy(this.matrixWorld).invert() : this.bindMode === "detached" ? this.bindMatrixInverse.copy(this.bindMatrix).invert() : console.warn("THREE.SkinnedMesh: Unrecognized bindMode: " + this.bindMode);
+ }
+ applyBoneTransform(e, t) {
+ let n = this.skeleton, r = this.geometry;
+ Mi.fromBufferAttribute(r.attributes.skinIndex, e), Ni.fromBufferAttribute(r.attributes.skinWeight, e), ji.copy(t).applyMatrix4(this.bindMatrix), t.set(0, 0, 0);
+ for (let e = 0; e < 4; e++) {
+ let r = Ni.getComponent(e);
+ if (r !== 0) {
+ let i = Mi.getComponent(e);
+ Fi.multiplyMatrices(n.bones[i].matrixWorld, n.boneInverses[i]), t.addScaledVector(Pi.copy(ji).applyMatrix4(Fi), r);
+ }
+ }
+ return t.applyMatrix4(this.bindMatrixInverse);
+ }
+}, Vi = class extends nr {
+ constructor() {
+ super(), this.isBone = !0, this.type = "Bone";
+ }
+}, Hi = class extends qt {
+ constructor(e = null, t = 1, n = 1, r, i, a, o, s, l = c, u = c, d, f) {
+ super(null, a, o, s, l, u, r, i, d, f), this.isDataTexture = !0, this.image = {
+ data: e,
+ width: t,
+ height: n
+ }, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1;
+ }
+}, Ui = /* @__PURE__ */ new z(), Wi = /* @__PURE__ */ new z(), Gi = class e {
+ constructor(e = [], t = []) {
+ this.uuid = rt(), this.bones = e.slice(0), this.boneInverses = t, this.boneMatrices = null, this.boneTexture = null, this.init();
+ }
+ init() {
+ let e = this.bones, t = this.boneInverses;
+ if (this.boneMatrices = new Float32Array(e.length * 16), t.length === 0) this.calculateInverses();
+ else if (e.length !== t.length) {
+ console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."), this.boneInverses = [];
+ for (let e = 0, t = this.bones.length; e < t; e++) this.boneInverses.push(new z());
+ }
+ }
+ calculateInverses() {
+ this.boneInverses.length = 0;
+ for (let e = 0, t = this.bones.length; e < t; e++) {
+ let t = new z();
+ this.bones[e] && t.copy(this.bones[e].matrixWorld).invert(), this.boneInverses.push(t);
+ }
+ }
+ pose() {
+ for (let e = 0, t = this.bones.length; e < t; e++) {
+ let t = this.bones[e];
+ t && t.matrixWorld.copy(this.boneInverses[e]).invert();
+ }
+ for (let e = 0, t = this.bones.length; e < t; e++) {
+ let t = this.bones[e];
+ t && (t.parent && t.parent.isBone ? (t.matrix.copy(t.parent.matrixWorld).invert(), t.matrix.multiply(t.matrixWorld)) : t.matrix.copy(t.matrixWorld), t.matrix.decompose(t.position, t.quaternion, t.scale));
+ }
+ }
+ update() {
+ let e = this.bones, t = this.boneInverses, n = this.boneMatrices, r = this.boneTexture;
+ for (let r = 0, i = e.length; r < i; r++) {
+ let i = e[r] ? e[r].matrixWorld : Wi;
+ Ui.multiplyMatrices(i, t[r]), Ui.toArray(n, r * 16);
+ }
+ r !== null && (r.needsUpdate = !0);
+ }
+ clone() {
+ return new e(this.bones, this.boneInverses);
+ }
+ computeBoneTexture() {
+ let e = Math.sqrt(this.bones.length * 4);
+ e = Math.ceil(e / 4) * 4, e = Math.max(e, 4);
+ let t = new Float32Array(e * e * 4);
+ t.set(this.boneMatrices);
+ let n = new Hi(t, e, e, O, b);
+ return n.needsUpdate = !0, this.boneMatrices = t, this.boneTexture = n, this;
+ }
+ getBoneByName(e) {
+ for (let t = 0, n = this.bones.length; t < n; t++) {
+ let n = this.bones[t];
+ if (n.name === e) return n;
+ }
+ }
+ dispose() {
+ this.boneTexture !== null && (this.boneTexture.dispose(), this.boneTexture = null);
+ }
+ fromJSON(e, t) {
+ this.uuid = e.uuid;
+ for (let n = 0, r = e.bones.length; n < r; n++) {
+ let r = e.bones[n], i = t[r];
+ i === void 0 && (console.warn("THREE.Skeleton: No bone found with UUID:", r), i = new Vi()), this.bones.push(i), this.boneInverses.push(new z().fromArray(e.boneInverses[n]));
+ }
+ return this.init(), this;
+ }
+ toJSON() {
+ let e = {
+ metadata: {
+ version: 4.6,
+ type: "Skeleton",
+ generator: "Skeleton.toJSON"
+ },
+ bones: [],
+ boneInverses: []
+ };
+ e.uuid = this.uuid;
+ let t = this.bones, n = this.boneInverses;
+ for (let r = 0, i = t.length; r < i; r++) {
+ let i = t[r];
+ e.bones.push(i.uuid);
+ let a = n[r];
+ e.boneInverses.push(a.toArray());
+ }
+ return e;
+ }
+}, Ki = class extends Nr {
+ constructor(e, t, n, r = 1) {
+ super(e, t, n), this.isInstancedBufferAttribute = !0, this.meshPerAttribute = r;
+ }
+ copy(e) {
+ return super.copy(e), this.meshPerAttribute = e.meshPerAttribute, this;
+ }
+ toJSON() {
+ let e = super.toJSON();
+ return e.meshPerAttribute = this.meshPerAttribute, e.isInstancedBufferAttribute = !0, e;
+ }
+}, qi = /* @__PURE__ */ new z(), Ji = /* @__PURE__ */ new z(), Yi = [], Xi = /* @__PURE__ */ new nn(), Zi = /* @__PURE__ */ new z(), Qi = /* @__PURE__ */ new ni(), $i = /* @__PURE__ */ new xn(), ea = class extends ni {
+ constructor(e, t, n) {
+ super(e, t), this.isInstancedMesh = !0, this.instanceMatrix = new Ki(new Float32Array(n * 16), 16), this.instanceColor = null, this.morphTexture = null, this.count = n, this.boundingBox = null, this.boundingSphere = null;
+ for (let e = 0; e < n; e++) this.setMatrixAt(e, Zi);
+ }
+ computeBoundingBox() {
+ let e = this.geometry, t = this.count;
+ this.boundingBox === null && (this.boundingBox = new nn()), e.boundingBox === null && e.computeBoundingBox(), this.boundingBox.makeEmpty();
+ for (let n = 0; n < t; n++) this.getMatrixAt(n, qi), Xi.copy(e.boundingBox).applyMatrix4(qi), this.boundingBox.union(Xi);
+ }
+ computeBoundingSphere() {
+ let e = this.geometry, t = this.count;
+ this.boundingSphere === null && (this.boundingSphere = new xn()), e.boundingSphere === null && e.computeBoundingSphere(), this.boundingSphere.makeEmpty();
+ for (let n = 0; n < t; n++) this.getMatrixAt(n, qi), $i.copy(e.boundingSphere).applyMatrix4(qi), this.boundingSphere.union($i);
+ }
+ copy(e, t) {
+ return super.copy(e, t), this.instanceMatrix.copy(e.instanceMatrix), e.morphTexture !== null && (this.morphTexture = e.morphTexture.clone()), e.instanceColor !== null && (this.instanceColor = e.instanceColor.clone()), this.count = e.count, e.boundingBox !== null && (this.boundingBox = e.boundingBox.clone()), e.boundingSphere !== null && (this.boundingSphere = e.boundingSphere.clone()), this;
+ }
+ getColorAt(e, t) {
+ t.fromArray(this.instanceColor.array, e * 3);
+ }
+ getMatrixAt(e, t) {
+ t.fromArray(this.instanceMatrix.array, e * 16);
+ }
+ getMorphAt(e, t) {
+ let n = t.morphTargetInfluences, r = this.morphTexture.source.data.data, i = e * (n.length + 1) + 1;
+ for (let e = 0; e < n.length; e++) n[e] = r[i + e];
+ }
+ raycast(e, t) {
+ let n = this.matrixWorld, r = this.count;
+ if (Qi.geometry = this.geometry, Qi.material = this.material, Qi.material !== void 0 && (this.boundingSphere === null && this.computeBoundingSphere(), $i.copy(this.boundingSphere), $i.applyMatrix4(n), e.ray.intersectsSphere($i) !== !1)) for (let i = 0; i < r; i++) {
+ this.getMatrixAt(i, qi), Ji.multiplyMatrices(n, qi), Qi.matrixWorld = Ji, Qi.raycast(e, Yi);
+ for (let e = 0, n = Yi.length; e < n; e++) {
+ let n = Yi[e];
+ n.instanceId = i, n.object = this, t.push(n);
+ }
+ Yi.length = 0;
+ }
+ }
+ setColorAt(e, t) {
+ this.instanceColor === null && (this.instanceColor = new Ki(new Float32Array(this.instanceMatrix.count * 3).fill(1), 3)), t.toArray(this.instanceColor.array, e * 3);
+ }
+ setMatrixAt(e, t) {
+ t.toArray(this.instanceMatrix.array, e * 16);
+ }
+ setMorphAt(e, t) {
+ let n = t.morphTargetInfluences, r = n.length + 1;
+ this.morphTexture === null && (this.morphTexture = new Hi(new Float32Array(r * this.count), r, this.count, A, b));
+ let i = this.morphTexture.source.data.data, a = 0;
+ for (let e = 0; e < n.length; e++) a += n[e];
+ let o = this.geometry.morphTargetsRelative ? 1 : 1 - a, s = r * e;
+ i[s] = o, i.set(n, s + 1);
+ }
+ updateMorphTargets() {}
+ dispose() {
+ this.dispatchEvent({ type: "dispose" }), this.morphTexture !== null && (this.morphTexture.dispose(), this.morphTexture = null);
+ }
+}, ta = /* @__PURE__ */ new R(), na = /* @__PURE__ */ new R(), ra = /* @__PURE__ */ new Tt(), ia = class {
+ constructor(e = new R(1, 0, 0), t = 0) {
+ this.isPlane = !0, this.normal = e, this.constant = t;
+ }
+ set(e, t) {
+ return this.normal.copy(e), this.constant = t, this;
+ }
+ setComponents(e, t, n, r) {
+ return this.normal.set(e, t, n), this.constant = r, this;
+ }
+ setFromNormalAndCoplanarPoint(e, t) {
+ return this.normal.copy(e), this.constant = -t.dot(this.normal), this;
+ }
+ setFromCoplanarPoints(e, t, n) {
+ let r = ta.subVectors(n, t).cross(na.subVectors(e, t)).normalize();
+ return this.setFromNormalAndCoplanarPoint(r, e), this;
+ }
+ copy(e) {
+ return this.normal.copy(e.normal), this.constant = e.constant, this;
+ }
+ normalize() {
+ let e = 1 / this.normal.length();
+ return this.normal.multiplyScalar(e), this.constant *= e, this;
+ }
+ negate() {
+ return this.constant *= -1, this.normal.negate(), this;
+ }
+ distanceToPoint(e) {
+ return this.normal.dot(e) + this.constant;
+ }
+ distanceToSphere(e) {
+ return this.distanceToPoint(e.center) - e.radius;
+ }
+ projectPoint(e, t) {
+ return t.copy(e).addScaledVector(this.normal, -this.distanceToPoint(e));
+ }
+ intersectLine(e, t) {
+ let n = e.delta(ta), r = this.normal.dot(n);
+ if (r === 0) return this.distanceToPoint(e.start) === 0 ? t.copy(e.start) : null;
+ let i = -(e.start.dot(this.normal) + this.constant) / r;
+ return i < 0 || i > 1 ? null : t.copy(e.start).addScaledVector(n, i);
+ }
+ intersectsLine(e) {
+ let t = this.distanceToPoint(e.start), n = this.distanceToPoint(e.end);
+ return t < 0 && n > 0 || n < 0 && t > 0;
+ }
+ intersectsBox(e) {
+ return e.intersectsPlane(this);
+ }
+ intersectsSphere(e) {
+ return e.intersectsPlane(this);
+ }
+ coplanarPoint(e) {
+ return e.copy(this.normal).multiplyScalar(-this.constant);
+ }
+ applyMatrix4(e, t) {
+ let n = t || ra.getNormalMatrix(e), r = this.coplanarPoint(ta).applyMatrix4(e), i = this.normal.applyMatrix3(n).normalize();
+ return this.constant = -r.dot(i), this;
+ }
+ translate(e) {
+ return this.constant -= e.dot(this.normal), this;
+ }
+ equals(e) {
+ return e.normal.equals(this.normal) && e.constant === this.constant;
+ }
+ clone() {
+ return new this.constructor().copy(this);
+ }
+}, aa = /* @__PURE__ */ new xn(), oa = /* @__PURE__ */ new R(), sa = class {
+ constructor(e = new ia(), t = new ia(), n = new ia(), r = new ia(), i = new ia(), a = new ia()) {
+ this.planes = [
+ e,
+ t,
+ n,
+ r,
+ i,
+ a
+ ];
+ }
+ set(e, t, n, r, i, a) {
+ let o = this.planes;
+ return o[0].copy(e), o[1].copy(t), o[2].copy(n), o[3].copy(r), o[4].copy(i), o[5].copy(a), this;
+ }
+ copy(e) {
+ let t = this.planes;
+ for (let n = 0; n < 6; n++) t[n].copy(e.planes[n]);
+ return this;
+ }
+ setFromProjectionMatrix(e, t = Ze) {
+ let n = this.planes, r = e.elements, i = r[0], a = r[1], o = r[2], s = r[3], c = r[4], l = r[5], u = r[6], d = r[7], f = r[8], p = r[9], m = r[10], h = r[11], g = r[12], _ = r[13], v = r[14], y = r[15];
+ if (n[0].setComponents(s - i, d - c, h - f, y - g).normalize(), n[1].setComponents(s + i, d + c, h + f, y + g).normalize(), n[2].setComponents(s + a, d + l, h + p, y + _).normalize(), n[3].setComponents(s - a, d - l, h - p, y - _).normalize(), n[4].setComponents(s - o, d - u, h - m, y - v).normalize(), t === 2e3) n[5].setComponents(s + o, d + u, h + m, y + v).normalize();
+ else if (t === 2001) n[5].setComponents(o, u, m, v).normalize();
+ else throw Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: " + t);
+ return this;
+ }
+ intersectsObject(e) {
+ if (e.boundingSphere !== void 0) e.boundingSphere === null && e.computeBoundingSphere(), aa.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);
+ else {
+ let t = e.geometry;
+ t.boundingSphere === null && t.computeBoundingSphere(), aa.copy(t.boundingSphere).applyMatrix4(e.matrixWorld);
+ }
+ return this.intersectsSphere(aa);
+ }
+ intersectsSprite(e) {
+ return aa.center.set(0, 0, 0), aa.radius = .7071067811865476, aa.applyMatrix4(e.matrixWorld), this.intersectsSphere(aa);
+ }
+ intersectsSphere(e) {
+ let t = this.planes, n = e.center, r = -e.radius;
+ for (let e = 0; e < 6; e++) if (t[e].distanceToPoint(n) < r) return !1;
+ return !0;
+ }
+ intersectsBox(e) {
+ let t = this.planes;
+ for (let n = 0; n < 6; n++) {
+ let r = t[n];
+ if (oa.x = r.normal.x > 0 ? e.max.x : e.min.x, oa.y = r.normal.y > 0 ? e.max.y : e.min.y, oa.z = r.normal.z > 0 ? e.max.z : e.min.z, r.distanceToPoint(oa) < 0) return !1;
+ }
+ return !0;
+ }
+ containsPoint(e) {
+ let t = this.planes;
+ for (let n = 0; n < 6; n++) if (t[n].distanceToPoint(e) < 0) return !1;
+ return !0;
+ }
+ clone() {
+ return new this.constructor().copy(this);
+ }
+}, ca = class extends Cr {
+ constructor(e) {
+ super(), this.isLineBasicMaterial = !0, this.type = "LineBasicMaterial", this.color = new B(16777215), this.map = null, this.linewidth = 1, this.linecap = "round", this.linejoin = "round", this.fog = !0, this.setValues(e);
+ }
+ copy(e) {
+ return super.copy(e), this.color.copy(e.color), this.map = e.map, this.linewidth = e.linewidth, this.linecap = e.linecap, this.linejoin = e.linejoin, this.fog = e.fog, this;
+ }
+}, la = /* @__PURE__ */ new R(), ua = /* @__PURE__ */ new R(), da = /* @__PURE__ */ new z(), fa = /* @__PURE__ */ new kn(), pa = /* @__PURE__ */ new xn(), ma = /* @__PURE__ */ new R(), ha = /* @__PURE__ */ new R(), ga = class extends nr {
+ constructor(e = new Wr(), t = new ca()) {
+ super(), this.isLine = !0, this.type = "Line", this.geometry = e, this.material = t, this.morphTargetDictionary = void 0, this.morphTargetInfluences = void 0, this.updateMorphTargets();
+ }
+ copy(e, t) {
+ return super.copy(e, t), this.material = Array.isArray(e.material) ? e.material.slice() : e.material, this.geometry = e.geometry, this;
+ }
+ computeLineDistances() {
+ let e = this.geometry;
+ if (e.index === null) {
+ let t = e.attributes.position, n = [0];
+ for (let e = 1, r = t.count; e < r; e++) la.fromBufferAttribute(t, e - 1), ua.fromBufferAttribute(t, e), n[e] = n[e - 1], n[e] += la.distanceTo(ua);
+ e.setAttribute("lineDistance", new Ir(n, 1));
+ } else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");
+ return this;
+ }
+ raycast(e, t) {
+ let n = this.geometry, r = this.matrixWorld, i = e.params.Line.threshold, a = n.drawRange;
+ if (n.boundingSphere === null && n.computeBoundingSphere(), pa.copy(n.boundingSphere), pa.applyMatrix4(r), pa.radius += i, e.ray.intersectsSphere(pa) === !1) return;
+ da.copy(r).invert(), fa.copy(e.ray).applyMatrix4(da);
+ let o = i / ((this.scale.x + this.scale.y + this.scale.z) / 3), s = o * o, c = this.isLineSegments ? 2 : 1, l = n.index, u = n.attributes.position;
+ if (l !== null) {
+ let n = Math.max(0, a.start), r = Math.min(l.count, a.start + a.count);
+ for (let i = n, a = r - 1; i < a; i += c) {
+ let n = l.getX(i), r = l.getX(i + 1), a = _a(this, e, fa, s, n, r, i);
+ a && t.push(a);
+ }
+ if (this.isLineLoop) {
+ let i = l.getX(r - 1), a = l.getX(n), o = _a(this, e, fa, s, i, a, r - 1);
+ o && t.push(o);
+ }
+ } else {
+ let n = Math.max(0, a.start), r = Math.min(u.count, a.start + a.count);
+ for (let i = n, a = r - 1; i < a; i += c) {
+ let n = _a(this, e, fa, s, i, i + 1, i);
+ n && t.push(n);
+ }
+ if (this.isLineLoop) {
+ let i = _a(this, e, fa, s, r - 1, n, r - 1);
+ i && t.push(i);
+ }
+ }
+ }
+ updateMorphTargets() {
+ let e = this.geometry.morphAttributes, t = Object.keys(e);
+ if (t.length > 0) {
+ let n = e[t[0]];
+ if (n !== void 0) {
+ this.morphTargetInfluences = [], this.morphTargetDictionary = {};
+ for (let e = 0, t = n.length; e < t; e++) {
+ let t = n[e].name || String(e);
+ this.morphTargetInfluences.push(0), this.morphTargetDictionary[t] = e;
+ }
+ }
+ }
+ }
+};
+function _a(e, t, n, r, i, a, o) {
+ let s = e.geometry.attributes.position;
+ if (la.fromBufferAttribute(s, i), ua.fromBufferAttribute(s, a), n.distanceSqToSegment(la, ua, ma, ha) > r) return;
+ ma.applyMatrix4(e.matrixWorld);
+ let c = t.ray.origin.distanceTo(ma);
+ if (!(c < t.near || c > t.far)) return {
+ distance: c,
+ point: ha.clone().applyMatrix4(e.matrixWorld),
+ index: o,
+ face: null,
+ faceIndex: null,
+ barycoord: null,
+ object: e
+ };
+}
+var va = /* @__PURE__ */ new R(), ya = /* @__PURE__ */ new R(), ba = class extends ga {
+ constructor(e, t) {
+ super(e, t), this.isLineSegments = !0, this.type = "LineSegments";
+ }
+ computeLineDistances() {
+ let e = this.geometry;
+ if (e.index === null) {
+ let t = e.attributes.position, n = [];
+ for (let e = 0, r = t.count; e < r; e += 2) va.fromBufferAttribute(t, e), ya.fromBufferAttribute(t, e + 1), n[e] = e === 0 ? 0 : n[e - 1], n[e + 1] = n[e] + va.distanceTo(ya);
+ e.setAttribute("lineDistance", new Ir(n, 1));
+ } else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");
+ return this;
+ }
+}, xa = class extends ga {
+ constructor(e, t) {
+ super(e, t), this.isLineLoop = !0, this.type = "LineLoop";
+ }
+}, Sa = class extends Cr {
+ constructor(e) {
+ super(), this.isPointsMaterial = !0, this.type = "PointsMaterial", this.color = new B(16777215), this.map = null, this.alphaMap = null, this.size = 1, this.sizeAttenuation = !0, this.fog = !0, this.setValues(e);
+ }
+ copy(e) {
+ return super.copy(e), this.color.copy(e.color), this.map = e.map, this.alphaMap = e.alphaMap, this.size = e.size, this.sizeAttenuation = e.sizeAttenuation, this.fog = e.fog, this;
+ }
+}, Ca = /* @__PURE__ */ new z(), wa = /* @__PURE__ */ new kn(), Ta = /* @__PURE__ */ new xn(), Ea = /* @__PURE__ */ new R(), Da = class extends nr {
+ constructor(e = new Wr(), t = new Sa()) {
+ super(), this.isPoints = !0, this.type = "Points", this.geometry = e, this.material = t, this.morphTargetDictionary = void 0, this.morphTargetInfluences = void 0, this.updateMorphTargets();
+ }
+ copy(e, t) {
+ return super.copy(e, t), this.material = Array.isArray(e.material) ? e.material.slice() : e.material, this.geometry = e.geometry, this;
+ }
+ raycast(e, t) {
+ let n = this.geometry, r = this.matrixWorld, i = e.params.Points.threshold, a = n.drawRange;
+ if (n.boundingSphere === null && n.computeBoundingSphere(), Ta.copy(n.boundingSphere), Ta.applyMatrix4(r), Ta.radius += i, e.ray.intersectsSphere(Ta) === !1) return;
+ Ca.copy(r).invert(), wa.copy(e.ray).applyMatrix4(Ca);
+ let o = i / ((this.scale.x + this.scale.y + this.scale.z) / 3), s = o * o, c = n.index, l = n.attributes.position;
+ if (c !== null) {
+ let n = Math.max(0, a.start), i = Math.min(c.count, a.start + a.count);
+ for (let a = n, o = i; a < o; a++) {
+ let n = c.getX(a);
+ Ea.fromBufferAttribute(l, n), Oa(Ea, n, s, r, e, t, this);
+ }
+ } else {
+ let n = Math.max(0, a.start), i = Math.min(l.count, a.start + a.count);
+ for (let a = n, o = i; a < o; a++) Ea.fromBufferAttribute(l, a), Oa(Ea, a, s, r, e, t, this);
+ }
+ }
+ updateMorphTargets() {
+ let e = this.geometry.morphAttributes, t = Object.keys(e);
+ if (t.length > 0) {
+ let n = e[t[0]];
+ if (n !== void 0) {
+ this.morphTargetInfluences = [], this.morphTargetDictionary = {};
+ for (let e = 0, t = n.length; e < t; e++) {
+ let t = n[e].name || String(e);
+ this.morphTargetInfluences.push(0), this.morphTargetDictionary[t] = e;
+ }
+ }
+ }
+ }
+};
+function Oa(e, t, n, r, i, a, o) {
+ let s = wa.distanceSqToPoint(e);
+ if (s < n) {
+ let n = new R();
+ wa.closestPointToPoint(e, n), n.applyMatrix4(r);
+ let c = i.ray.origin.distanceTo(n);
+ if (c < i.near || c > i.far) return;
+ a.push({
+ distance: c,
+ distanceToRay: Math.sqrt(s),
+ point: n,
+ index: t,
+ face: null,
+ faceIndex: null,
+ barycoord: null,
+ object: o
+ });
+ }
+}
+var ka = class extends qt {
+ constructor(e, t, n, r, i, a, o, s, c, l, u, d) {
+ super(null, a, o, s, c, l, r, i, u, d), this.isCompressedTexture = !0, this.image = {
+ width: t,
+ height: n
+ }, this.mipmaps = e, this.flipY = !1, this.generateMipmaps = !1;
+ }
+}, Aa = class extends ka {
+ constructor(e, t, n, r, i, a) {
+ super(e, t, n, i, a), this.isCompressedArrayTexture = !0, this.image.depth = r, this.wrapR = o, this.layerUpdates = /* @__PURE__ */ new Set();
+ }
+ addLayerUpdate(e) {
+ this.layerUpdates.add(e);
+ }
+ clearLayerUpdates() {
+ this.layerUpdates.clear();
+ }
+}, ja = class extends ka {
+ constructor(e, t, n) {
+ super(void 0, e[0].width, e[0].height, t, n, 301), this.isCompressedCubeTexture = !0, this.isCubeTexture = !0, this.image = e;
+ }
+}, Ma = class extends qt {
+ constructor(e, t, n = y, r, i, a, o = c, s = c, l, u = k) {
+ if (u !== 1026 && u !== 1027) throw Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");
+ super(null, r, i, a, o, s, u, n, l), this.isDepthTexture = !0, this.image = {
+ width: e,
+ height: t
+ }, this.flipY = !1, this.generateMipmaps = !1, this.compareFunction = null;
+ }
+ copy(e) {
+ return super.copy(e), this.source = new Wt(Object.assign({}, e.image)), this.compareFunction = e.compareFunction, this;
+ }
+ toJSON(e) {
+ let t = super.toJSON(e);
+ return this.compareFunction !== null && (t.compareFunction = this.compareFunction), t;
+ }
+}, Na = class e extends Wr {
+ constructor(e = 1, t = 1, n = 1, r = 1) {
+ super(), this.type = "PlaneGeometry", this.parameters = {
+ width: e,
+ height: t,
+ widthSegments: n,
+ heightSegments: r
+ };
+ let i = e / 2, a = t / 2, o = Math.floor(n), s = Math.floor(r), c = o + 1, l = s + 1, u = e / o, d = t / s, f = [], p = [], m = [], h = [];
+ for (let e = 0; e < l; e++) {
+ let t = e * d - a;
+ for (let n = 0; n < c; n++) {
+ let r = n * u - i;
+ p.push(r, -t, 0), m.push(0, 0, 1), h.push(n / o), h.push(1 - e / s);
+ }
+ }
+ for (let e = 0; e < s; e++) for (let t = 0; t < o; t++) {
+ let n = t + c * e, r = t + c * (e + 1), i = t + 1 + c * (e + 1), a = t + 1 + c * e;
+ f.push(n, r, a), f.push(r, i, a);
+ }
+ this.setIndex(f), this.setAttribute("position", new Ir(p, 3)), this.setAttribute("normal", new Ir(m, 3)), this.setAttribute("uv", new Ir(h, 2));
+ }
+ copy(e) {
+ return super.copy(e), this.parameters = Object.assign({}, e.parameters), this;
+ }
+ static fromJSON(t) {
+ return new e(t.width, t.height, t.widthSegments, t.heightSegments);
+ }
+}, Pa = class extends Cr {
+ constructor(e) {
+ super(), this.isMeshStandardMaterial = !0, this.type = "MeshStandardMaterial", this.defines = { STANDARD: "" }, this.color = new B(16777215), this.roughness = 1, this.metalness = 0, this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.emissive = new B(0), this.emissiveIntensity = 1, this.emissiveMap = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = 0, this.normalScale = new L(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.roughnessMap = null, this.metalnessMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new zn(), this.envMapIntensity = 1, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.flatShading = !1, this.fog = !0, this.setValues(e);
+ }
+ copy(e) {
+ return super.copy(e), this.defines = { STANDARD: "" }, this.color.copy(e.color), this.roughness = e.roughness, this.metalness = e.metalness, this.map = e.map, this.lightMap = e.lightMap, this.lightMapIntensity = e.lightMapIntensity, this.aoMap = e.aoMap, this.aoMapIntensity = e.aoMapIntensity, this.emissive.copy(e.emissive), this.emissiveMap = e.emissiveMap, this.emissiveIntensity = e.emissiveIntensity, this.bumpMap = e.bumpMap, this.bumpScale = e.bumpScale, this.normalMap = e.normalMap, this.normalMapType = e.normalMapType, this.normalScale.copy(e.normalScale), this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.roughnessMap = e.roughnessMap, this.metalnessMap = e.metalnessMap, this.alphaMap = e.alphaMap, this.envMap = e.envMap, this.envMapRotation.copy(e.envMapRotation), this.envMapIntensity = e.envMapIntensity, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.wireframeLinecap = e.wireframeLinecap, this.wireframeLinejoin = e.wireframeLinejoin, this.flatShading = e.flatShading, this.fog = e.fog, this;
+ }
+}, Fa = class extends Pa {
+ constructor(e) {
+ super(), this.isMeshPhysicalMaterial = !0, this.defines = {
+ STANDARD: "",
+ PHYSICAL: ""
+ }, this.type = "MeshPhysicalMaterial", this.anisotropyRotation = 0, this.anisotropyMap = null, this.clearcoatMap = null, this.clearcoatRoughness = 0, this.clearcoatRoughnessMap = null, this.clearcoatNormalScale = new L(1, 1), this.clearcoatNormalMap = null, this.ior = 1.5, Object.defineProperty(this, "reflectivity", {
+ get: function() {
+ return I(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
+ },
+ set: function(e) {
+ this.ior = (1 + .4 * e) / (1 - .4 * e);
+ }
+ }), this.iridescenceMap = null, this.iridescenceIOR = 1.3, this.iridescenceThicknessRange = [100, 400], this.iridescenceThicknessMap = null, this.sheenColor = new B(0), this.sheenColorMap = null, this.sheenRoughness = 1, this.sheenRoughnessMap = null, this.transmissionMap = null, this.thickness = 0, this.thicknessMap = null, this.attenuationDistance = Infinity, this.attenuationColor = new B(1, 1, 1), this.specularIntensity = 1, this.specularIntensityMap = null, this.specularColor = new B(1, 1, 1), this.specularColorMap = null, this._anisotropy = 0, this._clearcoat = 0, this._dispersion = 0, this._iridescence = 0, this._sheen = 0, this._transmission = 0, this.setValues(e);
+ }
+ get anisotropy() {
+ return this._anisotropy;
+ }
+ set anisotropy(e) {
+ this._anisotropy > 0 != e > 0 && this.version++, this._anisotropy = e;
+ }
+ get clearcoat() {
+ return this._clearcoat;
+ }
+ set clearcoat(e) {
+ this._clearcoat > 0 != e > 0 && this.version++, this._clearcoat = e;
+ }
+ get iridescence() {
+ return this._iridescence;
+ }
+ set iridescence(e) {
+ this._iridescence > 0 != e > 0 && this.version++, this._iridescence = e;
+ }
+ get dispersion() {
+ return this._dispersion;
+ }
+ set dispersion(e) {
+ this._dispersion > 0 != e > 0 && this.version++, this._dispersion = e;
+ }
+ get sheen() {
+ return this._sheen;
+ }
+ set sheen(e) {
+ this._sheen > 0 != e > 0 && this.version++, this._sheen = e;
+ }
+ get transmission() {
+ return this._transmission;
+ }
+ set transmission(e) {
+ this._transmission > 0 != e > 0 && this.version++, this._transmission = e;
+ }
+ copy(e) {
+ return super.copy(e), this.defines = {
+ STANDARD: "",
+ PHYSICAL: ""
+ }, this.anisotropy = e.anisotropy, this.anisotropyRotation = e.anisotropyRotation, this.anisotropyMap = e.anisotropyMap, this.clearcoat = e.clearcoat, this.clearcoatMap = e.clearcoatMap, this.clearcoatRoughness = e.clearcoatRoughness, this.clearcoatRoughnessMap = e.clearcoatRoughnessMap, this.clearcoatNormalMap = e.clearcoatNormalMap, this.clearcoatNormalScale.copy(e.clearcoatNormalScale), this.dispersion = e.dispersion, this.ior = e.ior, this.iridescence = e.iridescence, this.iridescenceMap = e.iridescenceMap, this.iridescenceIOR = e.iridescenceIOR, this.iridescenceThicknessRange = [...e.iridescenceThicknessRange], this.iridescenceThicknessMap = e.iridescenceThicknessMap, this.sheen = e.sheen, this.sheenColor.copy(e.sheenColor), this.sheenColorMap = e.sheenColorMap, this.sheenRoughness = e.sheenRoughness, this.sheenRoughnessMap = e.sheenRoughnessMap, this.transmission = e.transmission, this.transmissionMap = e.transmissionMap, this.thickness = e.thickness, this.thicknessMap = e.thicknessMap, this.attenuationDistance = e.attenuationDistance, this.attenuationColor.copy(e.attenuationColor), this.specularIntensity = e.specularIntensity, this.specularIntensityMap = e.specularIntensityMap, this.specularColor.copy(e.specularColor), this.specularColorMap = e.specularColorMap, this;
+ }
+}, Ia = class extends Cr {
+ constructor(e) {
+ super(), this.isMeshDepthMaterial = !0, this.type = "MeshDepthMaterial", this.depthPacking = Ue, this.map = null, this.alphaMap = null, this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.wireframe = !1, this.wireframeLinewidth = 1, this.setValues(e);
+ }
+ copy(e) {
+ return super.copy(e), this.depthPacking = e.depthPacking, this.map = e.map, this.alphaMap = e.alphaMap, this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this;
+ }
+}, La = class extends Cr {
+ constructor(e) {
+ super(), this.isMeshDistanceMaterial = !0, this.type = "MeshDistanceMaterial", this.map = null, this.alphaMap = null, this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.setValues(e);
+ }
+ copy(e) {
+ return super.copy(e), this.map = e.map, this.alphaMap = e.alphaMap, this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this;
+ }
+};
+function Ra(e, t) {
+ return !e || e.constructor === t ? e : typeof t.BYTES_PER_ELEMENT == "number" ? new t(e) : Array.prototype.slice.call(e);
+}
+function za(e) {
+ return ArrayBuffer.isView(e) && !(e instanceof DataView);
+}
+function Ba(e) {
+ function t(t, n) {
+ return e[t] - e[n];
+ }
+ let n = e.length, r = Array(n);
+ for (let e = 0; e !== n; ++e) r[e] = e;
+ return r.sort(t), r;
+}
+function Va(e, t, n) {
+ let r = e.length, i = new e.constructor(r);
+ for (let a = 0, o = 0; o !== r; ++a) {
+ let r = n[a] * t;
+ for (let n = 0; n !== t; ++n) i[o++] = e[r + n];
+ }
+ return i;
+}
+function Ha(e, t, n, r) {
+ let i = 1, a = e[0];
+ for (; a !== void 0 && a[r] === void 0;) a = e[i++];
+ if (a === void 0) return;
+ let o = a[r];
+ if (o !== void 0) if (Array.isArray(o)) do
+ o = a[r], o !== void 0 && (t.push(a.time), n.push(...o)), a = e[i++];
+ while (a !== void 0);
+ else if (o.toArray !== void 0) do
+ o = a[r], o !== void 0 && (t.push(a.time), o.toArray(n, n.length)), a = e[i++];
+ while (a !== void 0);
+ else do
+ o = a[r], o !== void 0 && (t.push(a.time), n.push(o)), a = e[i++];
+ while (a !== void 0);
+}
+var Ua = class {
+ constructor(e, t, n, r) {
+ this.parameterPositions = e, this._cachedIndex = 0, this.resultBuffer = r === void 0 ? new t.constructor(n) : r, this.sampleValues = t, this.valueSize = n, this.settings = null, this.DefaultSettings_ = {};
+ }
+ evaluate(e) {
+ let t = this.parameterPositions, n = this._cachedIndex, r = t[n], i = t[n - 1];
+ validate_interval: {
+ seek: {
+ let a;
+ linear_scan: {
+ forward_scan: if (!(e < r)) {
+ for (let a = n + 2;;) {
+ if (r === void 0) {
+ if (e < i) break forward_scan;
+ return n = t.length, this._cachedIndex = n, this.copySampleValue_(n - 1);
+ }
+ if (n === a) break;
+ if (i = r, r = t[++n], e < r) break seek;
+ }
+ a = t.length;
+ break linear_scan;
+ }
+ if (!(e >= i)) {
+ let o = t[1];
+ e < o && (n = 2, i = o);
+ for (let a = n - 2;;) {
+ if (i === void 0) return this._cachedIndex = 0, this.copySampleValue_(0);
+ if (n === a) break;
+ if (r = i, i = t[--n - 1], e >= i) break seek;
+ }
+ a = n, n = 0;
+ break linear_scan;
+ }
+ break validate_interval;
+ }
+ for (; n < a;) {
+ let r = n + a >>> 1;
+ e < t[r] ? a = r : n = r + 1;
+ }
+ if (r = t[n], i = t[n - 1], i === void 0) return this._cachedIndex = 0, this.copySampleValue_(0);
+ if (r === void 0) return n = t.length, this._cachedIndex = n, this.copySampleValue_(n - 1);
+ }
+ this._cachedIndex = n, this.intervalChanged_(n, i, r);
+ }
+ return this.interpolate_(n, i, e, r);
+ }
+ getSettings_() {
+ return this.settings || this.DefaultSettings_;
+ }
+ copySampleValue_(e) {
+ let t = this.resultBuffer, n = this.sampleValues, r = this.valueSize, i = e * r;
+ for (let e = 0; e !== r; ++e) t[e] = n[i + e];
+ return t;
+ }
+ interpolate_() {
+ throw Error("call to abstract method");
+ }
+ intervalChanged_() {}
+}, Wa = class extends Ua {
+ constructor(e, t, n, r) {
+ super(e, t, n, r), this._weightPrev = -0, this._offsetPrev = -0, this._weightNext = -0, this._offsetNext = -0, this.DefaultSettings_ = {
+ endingStart: Re,
+ endingEnd: Re
+ };
+ }
+ intervalChanged_(e, t, n) {
+ let r = this.parameterPositions, i = e - 2, a = e + 1, o = r[i], s = r[a];
+ if (o === void 0) switch (this.getSettings_().endingStart) {
+ case ze:
+ i = e, o = 2 * t - n;
+ break;
+ case Be:
+ i = r.length - 2, o = t + r[i] - r[i + 1];
+ break;
+ default: i = e, o = n;
+ }
+ if (s === void 0) switch (this.getSettings_().endingEnd) {
+ case ze:
+ a = e, s = 2 * n - t;
+ break;
+ case Be:
+ a = 1, s = n + r[1] - r[0];
+ break;
+ default: a = e - 1, s = t;
+ }
+ let c = (n - t) * .5, l = this.valueSize;
+ this._weightPrev = c / (t - o), this._weightNext = c / (s - n), this._offsetPrev = i * l, this._offsetNext = a * l;
+ }
+ interpolate_(e, t, n, r) {
+ let i = this.resultBuffer, a = this.sampleValues, o = this.valueSize, s = e * o, c = s - o, l = this._offsetPrev, u = this._offsetNext, d = this._weightPrev, f = this._weightNext, p = (n - t) / (r - t), m = p * p, h = m * p, g = -d * h + 2 * d * m - d * p, _ = (1 + d) * h + (-1.5 - 2 * d) * m + (-.5 + d) * p + 1, v = (-1 - f) * h + (1.5 + f) * m + .5 * p, y = f * h - f * m;
+ for (let e = 0; e !== o; ++e) i[e] = g * a[l + e] + _ * a[c + e] + v * a[s + e] + y * a[u + e];
+ return i;
+ }
+}, Ga = class extends Ua {
+ constructor(e, t, n, r) {
+ super(e, t, n, r);
+ }
+ interpolate_(e, t, n, r) {
+ let i = this.resultBuffer, a = this.sampleValues, o = this.valueSize, s = e * o, c = s - o, l = (n - t) / (r - t), u = 1 - l;
+ for (let e = 0; e !== o; ++e) i[e] = a[c + e] * u + a[s + e] * l;
+ return i;
+ }
+}, Ka = class extends Ua {
+ constructor(e, t, n, r) {
+ super(e, t, n, r);
+ }
+ interpolate_(e) {
+ return this.copySampleValue_(e - 1);
+ }
+}, qa = class {
+ constructor(e, t, n, r) {
+ if (e === void 0) throw Error("THREE.KeyframeTrack: track name is undefined");
+ if (t === void 0 || t.length === 0) throw Error("THREE.KeyframeTrack: no keyframes in track named " + e);
+ this.name = e, this.times = Ra(t, this.TimeBufferType), this.values = Ra(n, this.ValueBufferType), this.setInterpolation(r || this.DefaultInterpolation);
+ }
+ static toJSON(e) {
+ let t = e.constructor, n;
+ if (t.toJSON !== this.toJSON) n = t.toJSON(e);
+ else {
+ n = {
+ name: e.name,
+ times: Ra(e.times, Array),
+ values: Ra(e.values, Array)
+ };
+ let t = e.getInterpolation();
+ t !== e.DefaultInterpolation && (n.interpolation = t);
+ }
+ return n.type = e.ValueTypeName, n;
+ }
+ InterpolantFactoryMethodDiscrete(e) {
+ return new Ka(this.times, this.values, this.getValueSize(), e);
+ }
+ InterpolantFactoryMethodLinear(e) {
+ return new Ga(this.times, this.values, this.getValueSize(), e);
+ }
+ InterpolantFactoryMethodSmooth(e) {
+ return new Wa(this.times, this.values, this.getValueSize(), e);
+ }
+ setInterpolation(e) {
+ let t;
+ switch (e) {
+ case Fe:
+ t = this.InterpolantFactoryMethodDiscrete;
+ break;
+ case Ie:
+ t = this.InterpolantFactoryMethodLinear;
+ break;
+ case Le:
+ t = this.InterpolantFactoryMethodSmooth;
+ break;
+ }
+ if (t === void 0) {
+ let t = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
+ if (this.createInterpolant === void 0) if (e !== this.DefaultInterpolation) this.setInterpolation(this.DefaultInterpolation);
+ else throw Error(t);
+ return console.warn("THREE.KeyframeTrack:", t), this;
+ }
+ return this.createInterpolant = t, this;
+ }
+ getInterpolation() {
+ switch (this.createInterpolant) {
+ case this.InterpolantFactoryMethodDiscrete: return Fe;
+ case this.InterpolantFactoryMethodLinear: return Ie;
+ case this.InterpolantFactoryMethodSmooth: return Le;
+ }
+ }
+ getValueSize() {
+ return this.values.length / this.times.length;
+ }
+ shift(e) {
+ if (e !== 0) {
+ let t = this.times;
+ for (let n = 0, r = t.length; n !== r; ++n) t[n] += e;
+ }
+ return this;
+ }
+ scale(e) {
+ if (e !== 1) {
+ let t = this.times;
+ for (let n = 0, r = t.length; n !== r; ++n) t[n] *= e;
+ }
+ return this;
+ }
+ trim(e, t) {
+ let n = this.times, r = n.length, i = 0, a = r - 1;
+ for (; i !== r && n[i] < e;) ++i;
+ for (; a !== -1 && n[a] > t;) --a;
+ if (++a, i !== 0 || a !== r) {
+ i >= a && (a = Math.max(a, 1), i = a - 1);
+ let e = this.getValueSize();
+ this.times = n.slice(i, a), this.values = this.values.slice(i * e, a * e);
+ }
+ return this;
+ }
+ validate() {
+ let e = !0, t = this.getValueSize();
+ t - Math.floor(t) !== 0 && (console.error("THREE.KeyframeTrack: Invalid value size in track.", this), e = !1);
+ let n = this.times, r = this.values, i = n.length;
+ i === 0 && (console.error("THREE.KeyframeTrack: Track is empty.", this), e = !1);
+ let a = null;
+ for (let t = 0; t !== i; t++) {
+ let r = n[t];
+ if (typeof r == "number" && isNaN(r)) {
+ console.error("THREE.KeyframeTrack: Time is not a valid number.", this, t, r), e = !1;
+ break;
+ }
+ if (a !== null && a > r) {
+ console.error("THREE.KeyframeTrack: Out of order keys.", this, t, r, a), e = !1;
+ break;
+ }
+ a = r;
+ }
+ if (r !== void 0 && za(r)) for (let t = 0, n = r.length; t !== n; ++t) {
+ let n = r[t];
+ if (isNaN(n)) {
+ console.error("THREE.KeyframeTrack: Value is not a valid number.", this, t, n), e = !1;
+ break;
+ }
+ }
+ return e;
+ }
+ optimize() {
+ let e = this.times.slice(), t = this.values.slice(), n = this.getValueSize(), r = this.getInterpolation() === Le, i = e.length - 1, a = 1;
+ for (let o = 1; o < i; ++o) {
+ let i = !1, s = e[o];
+ if (s !== e[o + 1] && (o !== 1 || s !== e[0])) if (r) i = !0;
+ else {
+ let e = o * n, r = e - n, a = e + n;
+ for (let o = 0; o !== n; ++o) {
+ let n = t[e + o];
+ if (n !== t[r + o] || n !== t[a + o]) {
+ i = !0;
+ break;
+ }
+ }
+ }
+ if (i) {
+ if (o !== a) {
+ e[a] = e[o];
+ let r = o * n, i = a * n;
+ for (let e = 0; e !== n; ++e) t[i + e] = t[r + e];
+ }
+ ++a;
+ }
+ }
+ if (i > 0) {
+ e[a] = e[i];
+ for (let e = i * n, r = a * n, o = 0; o !== n; ++o) t[r + o] = t[e + o];
+ ++a;
+ }
+ return a === e.length ? (this.times = e, this.values = t) : (this.times = e.slice(0, a), this.values = t.slice(0, a * n)), this;
+ }
+ clone() {
+ let e = this.times.slice(), t = this.values.slice(), n = this.constructor, r = new n(this.name, e, t);
+ return r.createInterpolant = this.createInterpolant, r;
+ }
+};
+qa.prototype.ValueTypeName = "", qa.prototype.TimeBufferType = Float32Array, qa.prototype.ValueBufferType = Float32Array, qa.prototype.DefaultInterpolation = Ie;
+var Ja = class extends qa {
+ constructor(e, t, n) {
+ super(e, t, n);
+ }
+};
+Ja.prototype.ValueTypeName = "bool", Ja.prototype.ValueBufferType = Array, Ja.prototype.DefaultInterpolation = Fe, Ja.prototype.InterpolantFactoryMethodLinear = void 0, Ja.prototype.InterpolantFactoryMethodSmooth = void 0;
+var Ya = class extends qa {
+ constructor(e, t, n, r) {
+ super(e, t, n, r);
+ }
+};
+Ya.prototype.ValueTypeName = "color";
+var Xa = class extends qa {
+ constructor(e, t, n, r) {
+ super(e, t, n, r);
+ }
+};
+Xa.prototype.ValueTypeName = "number";
+var Za = class extends Ua {
+ constructor(e, t, n, r) {
+ super(e, t, n, r);
+ }
+ interpolate_(e, t, n, r) {
+ let i = this.resultBuffer, a = this.sampleValues, o = this.valueSize, s = (n - t) / (r - t), c = e * o;
+ for (let e = c + o; c !== e; c += 4) $t.slerpFlat(i, 0, a, c - o, a, c, s);
+ return i;
+ }
+}, Qa = class extends qa {
+ constructor(e, t, n, r) {
+ super(e, t, n, r);
+ }
+ InterpolantFactoryMethodLinear(e) {
+ return new Za(this.times, this.values, this.getValueSize(), e);
+ }
+};
+Qa.prototype.ValueTypeName = "quaternion", Qa.prototype.InterpolantFactoryMethodSmooth = void 0;
+var $a = class extends qa {
+ constructor(e, t, n) {
+ super(e, t, n);
+ }
+};
+$a.prototype.ValueTypeName = "string", $a.prototype.ValueBufferType = Array, $a.prototype.DefaultInterpolation = Fe, $a.prototype.InterpolantFactoryMethodLinear = void 0, $a.prototype.InterpolantFactoryMethodSmooth = void 0;
+var eo = class extends qa {
+ constructor(e, t, n, r) {
+ super(e, t, n, r);
+ }
+};
+eo.prototype.ValueTypeName = "vector";
+var to = class {
+ constructor(e = "", t = -1, n = [], r = Ve) {
+ this.name = e, this.tracks = n, this.duration = t, this.blendMode = r, this.uuid = rt(), this.duration < 0 && this.resetDuration();
+ }
+ static parse(e) {
+ let t = [], n = e.tracks, r = 1 / (e.fps || 1);
+ for (let e = 0, i = n.length; e !== i; ++e) t.push(ro(n[e]).scale(r));
+ let i = new this(e.name, e.duration, t, e.blendMode);
+ return i.uuid = e.uuid, i;
+ }
+ static toJSON(e) {
+ let t = [], n = e.tracks, r = {
+ name: e.name,
+ duration: e.duration,
+ tracks: t,
+ uuid: e.uuid,
+ blendMode: e.blendMode
+ };
+ for (let e = 0, r = n.length; e !== r; ++e) t.push(qa.toJSON(n[e]));
+ return r;
+ }
+ static CreateFromMorphTargetSequence(e, t, n, r) {
+ let i = t.length, a = [];
+ for (let e = 0; e < i; e++) {
+ let o = [], s = [];
+ o.push((e + i - 1) % i, e, (e + 1) % i), s.push(0, 1, 0);
+ let c = Ba(o);
+ o = Va(o, 1, c), s = Va(s, 1, c), !r && o[0] === 0 && (o.push(i), s.push(s[0])), a.push(new Xa(".morphTargetInfluences[" + t[e].name + "]", o, s).scale(1 / n));
+ }
+ return new this(e, -1, a);
+ }
+ static findByName(e, t) {
+ let n = e;
+ if (!Array.isArray(e)) {
+ let t = e;
+ n = t.geometry && t.geometry.animations || t.animations;
+ }
+ for (let e = 0; e < n.length; e++) if (n[e].name === t) return n[e];
+ return null;
+ }
+ static CreateClipsFromMorphTargetSequences(e, t, n) {
+ let r = {}, i = /^([\w-]*?)([\d]+)$/;
+ for (let t = 0, n = e.length; t < n; t++) {
+ let n = e[t], a = n.name.match(i);
+ if (a && a.length > 1) {
+ let e = a[1], t = r[e];
+ t || (r[e] = t = []), t.push(n);
+ }
+ }
+ let a = [];
+ for (let e in r) a.push(this.CreateFromMorphTargetSequence(e, r[e], t, n));
+ return a;
+ }
+ static parseAnimation(e, t) {
+ if (console.warn("THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185"), !e) return console.error("THREE.AnimationClip: No animation in JSONLoader data."), null;
+ let n = function(e, t, n, r, i) {
+ if (n.length !== 0) {
+ let a = [], o = [];
+ Ha(n, a, o, r), a.length !== 0 && i.push(new e(t, a, o));
+ }
+ }, r = [], i = e.name || "default", a = e.fps || 30, o = e.blendMode, s = e.length || -1, c = e.hierarchy || [];
+ for (let e = 0; e < c.length; e++) {
+ let i = c[e].keys;
+ if (!(!i || i.length === 0)) if (i[0].morphTargets) {
+ let e = {}, t;
+ for (t = 0; t < i.length; t++) if (i[t].morphTargets) for (let n = 0; n < i[t].morphTargets.length; n++) e[i[t].morphTargets[n]] = -1;
+ for (let n in e) {
+ let e = [], a = [];
+ for (let r = 0; r !== i[t].morphTargets.length; ++r) {
+ let r = i[t];
+ e.push(r.time), a.push(+(r.morphTarget === n));
+ }
+ r.push(new Xa(".morphTargetInfluence[" + n + "]", e, a));
+ }
+ s = e.length * a;
+ } else {
+ let a = ".bones[" + t[e].name + "]";
+ n(eo, a + ".position", i, "pos", r), n(Qa, a + ".quaternion", i, "rot", r), n(eo, a + ".scale", i, "scl", r);
+ }
+ }
+ return r.length === 0 ? null : new this(i, s, r, o);
+ }
+ resetDuration() {
+ let e = this.tracks, t = 0;
+ for (let n = 0, r = e.length; n !== r; ++n) {
+ let e = this.tracks[n];
+ t = Math.max(t, e.times[e.times.length - 1]);
+ }
+ return this.duration = t, this;
+ }
+ trim() {
+ for (let e = 0; e < this.tracks.length; e++) this.tracks[e].trim(0, this.duration);
+ return this;
+ }
+ validate() {
+ let e = !0;
+ for (let t = 0; t < this.tracks.length; t++) e &&= this.tracks[t].validate();
+ return e;
+ }
+ optimize() {
+ for (let e = 0; e < this.tracks.length; e++) this.tracks[e].optimize();
+ return this;
+ }
+ clone() {
+ let e = [];
+ for (let t = 0; t < this.tracks.length; t++) e.push(this.tracks[t].clone());
+ return new this.constructor(this.name, this.duration, e, this.blendMode);
+ }
+ toJSON() {
+ return this.constructor.toJSON(this);
+ }
+};
+function no(e) {
+ switch (e.toLowerCase()) {
+ case "scalar":
+ case "double":
+ case "float":
+ case "number":
+ case "integer": return Xa;
+ case "vector":
+ case "vector2":
+ case "vector3":
+ case "vector4": return eo;
+ case "color": return Ya;
+ case "quaternion": return Qa;
+ case "bool":
+ case "boolean": return Ja;
+ case "string": return $a;
+ }
+ throw Error("THREE.KeyframeTrack: Unsupported typeName: " + e);
+}
+function ro(e) {
+ if (e.type === void 0) throw Error("THREE.KeyframeTrack: track type undefined, can not parse");
+ let t = no(e.type);
+ if (e.times === void 0) {
+ let t = [], n = [];
+ Ha(e.keys, t, n, "value"), e.times = t, e.values = n;
+ }
+ return t.parse === void 0 ? new t(e.name, e.times, e.values, e.interpolation) : t.parse(e);
+}
+var io = {
+ enabled: !1,
+ files: {},
+ add: function(e, t) {
+ this.enabled !== !1 && (this.files[e] = t);
+ },
+ get: function(e) {
+ if (this.enabled !== !1) return this.files[e];
+ },
+ remove: function(e) {
+ delete this.files[e];
+ },
+ clear: function() {
+ this.files = {};
+ }
+}, ao = class {
+ constructor(e, t, n) {
+ let r = this, i = !1, a = 0, o = 0, s, c = [];
+ this.onStart = void 0, this.onLoad = e, this.onProgress = t, this.onError = n, this.itemStart = function(e) {
+ o++, i === !1 && r.onStart !== void 0 && r.onStart(e, a, o), i = !0;
+ }, this.itemEnd = function(e) {
+ a++, r.onProgress !== void 0 && r.onProgress(e, a, o), a === o && (i = !1, r.onLoad !== void 0 && r.onLoad());
+ }, this.itemError = function(e) {
+ r.onError !== void 0 && r.onError(e);
+ }, this.resolveURL = function(e) {
+ return s ? s(e) : e;
+ }, this.setURLModifier = function(e) {
+ return s = e, this;
+ }, this.addHandler = function(e, t) {
+ return c.push(e, t), this;
+ }, this.removeHandler = function(e) {
+ let t = c.indexOf(e);
+ return t !== -1 && c.splice(t, 2), this;
+ }, this.getHandler = function(e) {
+ for (let t = 0, n = c.length; t < n; t += 2) {
+ let n = c[t], r = c[t + 1];
+ if (n.global && (n.lastIndex = 0), n.test(e)) return r;
+ }
+ return null;
+ };
+ }
+}, oo = /* @__PURE__ */ new ao(), so = class {
+ constructor(e) {
+ this.manager = e === void 0 ? oo : e, this.crossOrigin = "anonymous", this.withCredentials = !1, this.path = "", this.resourcePath = "", this.requestHeader = {};
+ }
+ load() {}
+ loadAsync(e, t) {
+ let n = this;
+ return new Promise(function(r, i) {
+ n.load(e, r, t, i);
+ });
+ }
+ parse() {}
+ setCrossOrigin(e) {
+ return this.crossOrigin = e, this;
+ }
+ setWithCredentials(e) {
+ return this.withCredentials = e, this;
+ }
+ setPath(e) {
+ return this.path = e, this;
+ }
+ setResourcePath(e) {
+ return this.resourcePath = e, this;
+ }
+ setRequestHeader(e) {
+ return this.requestHeader = e, this;
+ }
+};
+so.DEFAULT_MATERIAL_NAME = "__DEFAULT";
+var co = {}, lo = class extends Error {
+ constructor(e, t) {
+ super(e), this.response = t;
+ }
+}, uo = class extends so {
+ constructor(e) {
+ super(e), this.mimeType = "", this.responseType = "";
+ }
+ load(e, t, n, r) {
+ e === void 0 && (e = ""), this.path !== void 0 && (e = this.path + e), e = this.manager.resolveURL(e);
+ let i = io.get(e);
+ if (i !== void 0) return this.manager.itemStart(e), setTimeout(() => {
+ t && t(i), this.manager.itemEnd(e);
+ }, 0), i;
+ if (co[e] !== void 0) {
+ co[e].push({
+ onLoad: t,
+ onProgress: n,
+ onError: r
+ });
+ return;
+ }
+ co[e] = [], co[e].push({
+ onLoad: t,
+ onProgress: n,
+ onError: r
+ });
+ let a = new Request(e, {
+ headers: new Headers(this.requestHeader),
+ credentials: this.withCredentials ? "include" : "same-origin"
+ }), o = this.mimeType, s = this.responseType;
+ fetch(a).then((t) => {
+ if (t.status === 200 || t.status === 0) {
+ if (t.status === 0 && console.warn("THREE.FileLoader: HTTP Status 0 received."), typeof ReadableStream > "u" || t.body === void 0 || t.body.getReader === void 0) return t;
+ let n = co[e], r = t.body.getReader(), i = t.headers.get("X-File-Size") || t.headers.get("Content-Length"), a = i ? parseInt(i) : 0, o = a !== 0, s = 0, c = new ReadableStream({ start(e) {
+ t();
+ function t() {
+ r.read().then(({ done: r, value: i }) => {
+ if (r) e.close();
+ else {
+ s += i.byteLength;
+ let r = new ProgressEvent("progress", {
+ lengthComputable: o,
+ loaded: s,
+ total: a
+ });
+ for (let e = 0, t = n.length; e < t; e++) {
+ let t = n[e];
+ t.onProgress && t.onProgress(r);
+ }
+ e.enqueue(i), t();
+ }
+ }, (t) => {
+ e.error(t);
+ });
+ }
+ } });
+ return new Response(c);
+ } else throw new lo(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`, t);
+ }).then((e) => {
+ switch (s) {
+ case "arraybuffer": return e.arrayBuffer();
+ case "blob": return e.blob();
+ case "document": return e.text().then((e) => new DOMParser().parseFromString(e, o));
+ case "json": return e.json();
+ default:
+ if (o === "") return e.text();
+ {
+ let t = /charset="?([^;"\s]*)"?/i.exec(o), n = t && t[1] ? t[1].toLowerCase() : void 0, r = new TextDecoder(n);
+ return e.arrayBuffer().then((e) => r.decode(e));
+ }
+ }
+ }).then((t) => {
+ io.add(e, t);
+ let n = co[e];
+ delete co[e];
+ for (let e = 0, r = n.length; e < r; e++) {
+ let r = n[e];
+ r.onLoad && r.onLoad(t);
+ }
+ }).catch((t) => {
+ let n = co[e];
+ if (n === void 0) throw this.manager.itemError(e), t;
+ delete co[e];
+ for (let e = 0, r = n.length; e < r; e++) {
+ let r = n[e];
+ r.onError && r.onError(t);
+ }
+ this.manager.itemError(e);
+ }).finally(() => {
+ this.manager.itemEnd(e);
+ }), this.manager.itemStart(e);
+ }
+ setResponseType(e) {
+ return this.responseType = e, this;
+ }
+ setMimeType(e) {
+ return this.mimeType = e, this;
+ }
+}, fo = class extends so {
+ constructor(e) {
+ super(e);
+ }
+ load(e, t, n, r) {
+ this.path !== void 0 && (e = this.path + e), e = this.manager.resolveURL(e);
+ let i = this, a = io.get(e);
+ if (a !== void 0) return i.manager.itemStart(e), setTimeout(function() {
+ t && t(a), i.manager.itemEnd(e);
+ }, 0), a;
+ let o = Ot("img");
+ function s() {
+ l(), io.add(e, this), t && t(this), i.manager.itemEnd(e);
+ }
+ function c(t) {
+ l(), r && r(t), i.manager.itemError(e), i.manager.itemEnd(e);
+ }
+ function l() {
+ o.removeEventListener("load", s, !1), o.removeEventListener("error", c, !1);
+ }
+ return o.addEventListener("load", s, !1), o.addEventListener("error", c, !1), e.slice(0, 5) !== "data:" && this.crossOrigin !== void 0 && (o.crossOrigin = this.crossOrigin), i.manager.itemStart(e), o.src = e, o;
+ }
+}, po = class extends so {
+ constructor(e) {
+ super(e);
+ }
+ load(e, t, n, r) {
+ let i = this, a = new Hi(), s = new uo(this.manager);
+ return s.setResponseType("arraybuffer"), s.setRequestHeader(this.requestHeader), s.setPath(this.path), s.setWithCredentials(i.withCredentials), s.load(e, function(e) {
+ let n;
+ try {
+ n = i.parse(e);
+ } catch (e) {
+ if (r !== void 0) r(e);
+ else {
+ console.error(e);
+ return;
+ }
+ }
+ n.image === void 0 ? n.data !== void 0 && (a.image.width = n.width, a.image.height = n.height, a.image.data = n.data) : a.image = n.image, a.wrapS = n.wrapS === void 0 ? o : n.wrapS, a.wrapT = n.wrapT === void 0 ? o : n.wrapT, a.magFilter = n.magFilter === void 0 ? d : n.magFilter, a.minFilter = n.minFilter === void 0 ? d : n.minFilter, a.anisotropy = n.anisotropy === void 0 ? 1 : n.anisotropy, n.colorSpace !== void 0 && (a.colorSpace = n.colorSpace), n.flipY !== void 0 && (a.flipY = n.flipY), n.format !== void 0 && (a.format = n.format), n.type !== void 0 && (a.type = n.type), n.mipmaps !== void 0 && (a.mipmaps = n.mipmaps, a.minFilter = p), n.mipmapCount === 1 && (a.minFilter = d), n.generateMipmaps !== void 0 && (a.generateMipmaps = n.generateMipmaps), a.needsUpdate = !0, t && t(a, n);
+ }, n, r), a;
+ }
+}, mo = class extends so {
+ constructor(e) {
+ super(e);
+ }
+ load(e, t, n, r) {
+ let i = new qt(), a = new fo(this.manager);
+ return a.setCrossOrigin(this.crossOrigin), a.setPath(this.path), a.load(e, function(e) {
+ i.image = e, i.needsUpdate = !0, t !== void 0 && t(i);
+ }, n, r), i;
+ }
+}, ho = class extends nr {
+ constructor(e, t = 1) {
+ super(), this.isLight = !0, this.type = "Light", this.color = new B(e), this.intensity = t;
+ }
+ dispose() {}
+ copy(e, t) {
+ return super.copy(e, t), this.color.copy(e.color), this.intensity = e.intensity, this;
+ }
+ toJSON(e) {
+ let t = super.toJSON(e);
+ return t.object.color = this.color.getHex(), t.object.intensity = this.intensity, this.groundColor !== void 0 && (t.object.groundColor = this.groundColor.getHex()), this.distance !== void 0 && (t.object.distance = this.distance), this.angle !== void 0 && (t.object.angle = this.angle), this.decay !== void 0 && (t.object.decay = this.decay), this.penumbra !== void 0 && (t.object.penumbra = this.penumbra), this.shadow !== void 0 && (t.object.shadow = this.shadow.toJSON()), this.target !== void 0 && (t.object.target = this.target.uuid), t;
+ }
+}, go = class extends ho {
+ constructor(e, t, n) {
+ super(e, n), this.isHemisphereLight = !0, this.type = "HemisphereLight", this.position.copy(nr.DEFAULT_UP), this.updateMatrix(), this.groundColor = new B(t);
+ }
+ copy(e, t) {
+ return super.copy(e, t), this.groundColor.copy(e.groundColor), this;
+ }
+}, _o = /* @__PURE__ */ new z(), vo = /* @__PURE__ */ new R(), yo = /* @__PURE__ */ new R(), bo = class {
+ constructor(e) {
+ this.camera = e, this.intensity = 1, this.bias = 0, this.normalBias = 0, this.radius = 1, this.blurSamples = 8, this.mapSize = new L(512, 512), this.mapType = m, this.map = null, this.mapPass = null, this.matrix = new z(), this.autoUpdate = !0, this.needsUpdate = !1, this._frustum = new sa(), this._frameExtents = new L(1, 1), this._viewportCount = 1, this._viewports = [new Jt(0, 0, 1, 1)];
+ }
+ getViewportCount() {
+ return this._viewportCount;
+ }
+ getFrustum() {
+ return this._frustum;
+ }
+ updateMatrices(e) {
+ let t = this.camera, n = this.matrix;
+ vo.setFromMatrixPosition(e.matrixWorld), t.position.copy(vo), yo.setFromMatrixPosition(e.target.matrixWorld), t.lookAt(yo), t.updateMatrixWorld(), _o.multiplyMatrices(t.projectionMatrix, t.matrixWorldInverse), this._frustum.setFromProjectionMatrix(_o), n.set(.5, 0, 0, .5, 0, .5, 0, .5, 0, 0, .5, .5, 0, 0, 0, 1), n.multiply(_o);
+ }
+ getViewport(e) {
+ return this._viewports[e];
+ }
+ getFrameExtents() {
+ return this._frameExtents;
+ }
+ dispose() {
+ this.map && this.map.dispose(), this.mapPass && this.mapPass.dispose();
+ }
+ copy(e) {
+ return this.camera = e.camera.clone(), this.intensity = e.intensity, this.bias = e.bias, this.radius = e.radius, this.autoUpdate = e.autoUpdate, this.needsUpdate = e.needsUpdate, this.normalBias = e.normalBias, this.blurSamples = e.blurSamples, this.mapSize.copy(e.mapSize), this;
+ }
+ clone() {
+ return new this.constructor().copy(this);
+ }
+ toJSON() {
+ let e = {};
+ return this.intensity !== 1 && (e.intensity = this.intensity), this.bias !== 0 && (e.bias = this.bias), this.normalBias !== 0 && (e.normalBias = this.normalBias), this.radius !== 1 && (e.radius = this.radius), (this.mapSize.x !== 512 || this.mapSize.y !== 512) && (e.mapSize = this.mapSize.toArray()), e.camera = this.camera.toJSON(!1).object, delete e.camera.matrix, e;
+ }
+}, xo = class extends bo {
+ constructor() {
+ super(new vi(50, 1, .5, 500)), this.isSpotLightShadow = !0, this.focus = 1;
+ }
+ updateMatrices(e) {
+ let t = this.camera, n = nt * 2 * e.angle * this.focus, r = this.mapSize.width / this.mapSize.height, i = e.distance || t.far;
+ (n !== t.fov || r !== t.aspect || i !== t.far) && (t.fov = n, t.aspect = r, t.far = i, t.updateProjectionMatrix()), super.updateMatrices(e);
+ }
+ copy(e) {
+ return super.copy(e), this.focus = e.focus, this;
+ }
+}, So = class extends ho {
+ constructor(e, t, n = 0, r = Math.PI / 3, i = 0, a = 2) {
+ super(e, t), this.isSpotLight = !0, this.type = "SpotLight", this.position.copy(nr.DEFAULT_UP), this.updateMatrix(), this.target = new nr(), this.distance = n, this.angle = r, this.penumbra = i, this.decay = a, this.map = null, this.shadow = new xo();
+ }
+ get power() {
+ return this.intensity * Math.PI;
+ }
+ set power(e) {
+ this.intensity = e / Math.PI;
+ }
+ dispose() {
+ this.shadow.dispose();
+ }
+ copy(e, t) {
+ return super.copy(e, t), this.distance = e.distance, this.angle = e.angle, this.penumbra = e.penumbra, this.decay = e.decay, this.target = e.target.clone(), this.shadow = e.shadow.clone(), this;
+ }
+}, Co = /* @__PURE__ */ new z(), wo = /* @__PURE__ */ new R(), To = /* @__PURE__ */ new R(), Eo = class extends bo {
+ constructor() {
+ super(new vi(90, 1, .5, 500)), this.isPointLightShadow = !0, this._frameExtents = new L(4, 2), this._viewportCount = 6, this._viewports = [
+ new Jt(2, 1, 1, 1),
+ new Jt(0, 1, 1, 1),
+ new Jt(3, 1, 1, 1),
+ new Jt(1, 1, 1, 1),
+ new Jt(3, 0, 1, 1),
+ new Jt(1, 0, 1, 1)
+ ], this._cubeDirections = [
+ new R(1, 0, 0),
+ new R(-1, 0, 0),
+ new R(0, 0, 1),
+ new R(0, 0, -1),
+ new R(0, 1, 0),
+ new R(0, -1, 0)
+ ], this._cubeUps = [
+ new R(0, 1, 0),
+ new R(0, 1, 0),
+ new R(0, 1, 0),
+ new R(0, 1, 0),
+ new R(0, 0, 1),
+ new R(0, 0, -1)
+ ];
+ }
+ updateMatrices(e, t = 0) {
+ let n = this.camera, r = this.matrix, i = e.distance || n.far;
+ i !== n.far && (n.far = i, n.updateProjectionMatrix()), wo.setFromMatrixPosition(e.matrixWorld), n.position.copy(wo), To.copy(n.position), To.add(this._cubeDirections[t]), n.up.copy(this._cubeUps[t]), n.lookAt(To), n.updateMatrixWorld(), r.makeTranslation(-wo.x, -wo.y, -wo.z), Co.multiplyMatrices(n.projectionMatrix, n.matrixWorldInverse), this._frustum.setFromProjectionMatrix(Co);
+ }
+}, Do = class extends ho {
+ constructor(e, t, n = 0, r = 2) {
+ super(e, t), this.isPointLight = !0, this.type = "PointLight", this.distance = n, this.decay = r, this.shadow = new Eo();
+ }
+ get power() {
+ return this.intensity * 4 * Math.PI;
+ }
+ set power(e) {
+ this.intensity = e / (4 * Math.PI);
+ }
+ dispose() {
+ this.shadow.dispose();
+ }
+ copy(e, t) {
+ return super.copy(e, t), this.distance = e.distance, this.decay = e.decay, this.shadow = e.shadow.clone(), this;
+ }
+}, Oo = class extends mi {
+ constructor(e = -1, t = 1, n = 1, r = -1, i = .1, a = 2e3) {
+ super(), this.isOrthographicCamera = !0, this.type = "OrthographicCamera", this.zoom = 1, this.view = null, this.left = e, this.right = t, this.top = n, this.bottom = r, this.near = i, this.far = a, this.updateProjectionMatrix();
+ }
+ copy(e, t) {
+ return super.copy(e, t), this.left = e.left, this.right = e.right, this.top = e.top, this.bottom = e.bottom, this.near = e.near, this.far = e.far, this.zoom = e.zoom, this.view = e.view === null ? null : Object.assign({}, e.view), this;
+ }
+ setViewOffset(e, t, n, r, i, a) {
+ this.view === null && (this.view = {
+ enabled: !0,
+ fullWidth: 1,
+ fullHeight: 1,
+ offsetX: 0,
+ offsetY: 0,
+ width: 1,
+ height: 1
+ }), this.view.enabled = !0, this.view.fullWidth = e, this.view.fullHeight = t, this.view.offsetX = n, this.view.offsetY = r, this.view.width = i, this.view.height = a, this.updateProjectionMatrix();
+ }
+ clearViewOffset() {
+ this.view !== null && (this.view.enabled = !1), this.updateProjectionMatrix();
+ }
+ updateProjectionMatrix() {
+ let e = (this.right - this.left) / (2 * this.zoom), t = (this.top - this.bottom) / (2 * this.zoom), n = (this.right + this.left) / 2, r = (this.top + this.bottom) / 2, i = n - e, a = n + e, o = r + t, s = r - t;
+ if (this.view !== null && this.view.enabled) {
+ let e = (this.right - this.left) / this.view.fullWidth / this.zoom, t = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
+ i += e * this.view.offsetX, a = i + e * this.view.width, o -= t * this.view.offsetY, s = o - t * this.view.height;
+ }
+ this.projectionMatrix.makeOrthographic(i, a, o, s, this.near, this.far, this.coordinateSystem), this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
+ }
+ toJSON(e) {
+ let t = super.toJSON(e);
+ return t.object.zoom = this.zoom, t.object.left = this.left, t.object.right = this.right, t.object.top = this.top, t.object.bottom = this.bottom, t.object.near = this.near, t.object.far = this.far, this.view !== null && (t.object.view = Object.assign({}, this.view)), t;
+ }
+}, ko = class extends bo {
+ constructor() {
+ super(new Oo(-5, 5, 5, -5, .5, 500)), this.isDirectionalLightShadow = !0;
+ }
+}, Ao = class extends ho {
+ constructor(e, t) {
+ super(e, t), this.isDirectionalLight = !0, this.type = "DirectionalLight", this.position.copy(nr.DEFAULT_UP), this.updateMatrix(), this.target = new nr(), this.shadow = new ko();
+ }
+ dispose() {
+ this.shadow.dispose();
+ }
+ copy(e) {
+ return super.copy(e), this.target = e.target.clone(), this.shadow = e.shadow.clone(), this;
+ }
+}, jo = class extends ho {
+ constructor(e, t) {
+ super(e, t), this.isAmbientLight = !0, this.type = "AmbientLight";
+ }
+}, Mo = class {
+ static extractUrlBase(e) {
+ let t = e.lastIndexOf("/");
+ return t === -1 ? "./" : e.slice(0, t + 1);
+ }
+ static resolveURL(e, t) {
+ return typeof e != "string" || e === "" ? "" : (/^https?:\/\//i.test(t) && /^\//.test(e) && (t = t.replace(/(^https?:\/\/[^\/]+).*/i, "$1")), /^(https?:)?\/\//i.test(e) || /^data:.*,.*$/i.test(e) || /^blob:.*$/i.test(e) ? e : t + e);
+ }
+}, No = class extends so {
+ constructor(e) {
+ super(e), this.isImageBitmapLoader = !0, typeof createImageBitmap > "u" && console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."), typeof fetch > "u" && console.warn("THREE.ImageBitmapLoader: fetch() not supported."), this.options = { premultiplyAlpha: "none" };
+ }
+ setOptions(e) {
+ return this.options = e, this;
+ }
+ load(e, t, n, r) {
+ e === void 0 && (e = ""), this.path !== void 0 && (e = this.path + e), e = this.manager.resolveURL(e);
+ let i = this, a = io.get(e);
+ if (a !== void 0) {
+ if (i.manager.itemStart(e), a.then) {
+ a.then((n) => {
+ t && t(n), i.manager.itemEnd(e);
+ }).catch((e) => {
+ r && r(e);
+ });
+ return;
+ }
+ return setTimeout(function() {
+ t && t(a), i.manager.itemEnd(e);
+ }, 0), a;
+ }
+ let o = {};
+ o.credentials = this.crossOrigin === "anonymous" ? "same-origin" : "include", o.headers = this.requestHeader;
+ let s = fetch(e, o).then(function(e) {
+ return e.blob();
+ }).then(function(e) {
+ return createImageBitmap(e, Object.assign(i.options, { colorSpaceConversion: "none" }));
+ }).then(function(n) {
+ return io.add(e, n), t && t(n), i.manager.itemEnd(e), n;
+ }).catch(function(t) {
+ r && r(t), io.remove(e), i.manager.itemError(e), i.manager.itemEnd(e);
+ });
+ io.add(e, s), i.manager.itemStart(e);
+ }
+}, Po = class extends vi {
+ constructor(e = []) {
+ super(), this.isArrayCamera = !0, this.isMultiViewCamera = !1, this.cameras = e;
+ }
+}, Fo = class {
+ constructor(e, t, n) {
+ this.binding = e, this.valueSize = n;
+ let r, i, a;
+ switch (t) {
+ case "quaternion":
+ r = this._slerp, i = this._slerpAdditive, a = this._setAdditiveIdentityQuaternion, this.buffer = new Float64Array(n * 6), this._workIndex = 5;
+ break;
+ case "string":
+ case "bool":
+ r = this._select, i = this._select, a = this._setAdditiveIdentityOther, this.buffer = Array(n * 5);
+ break;
+ default: r = this._lerp, i = this._lerpAdditive, a = this._setAdditiveIdentityNumeric, this.buffer = new Float64Array(n * 5);
+ }
+ this._mixBufferRegion = r, this._mixBufferRegionAdditive = i, this._setIdentity = a, this._origIndex = 3, this._addIndex = 4, this.cumulativeWeight = 0, this.cumulativeWeightAdditive = 0, this.useCount = 0, this.referenceCount = 0;
+ }
+ accumulate(e, t) {
+ let n = this.buffer, r = this.valueSize, i = e * r + r, a = this.cumulativeWeight;
+ if (a === 0) {
+ for (let e = 0; e !== r; ++e) n[i + e] = n[e];
+ a = t;
+ } else {
+ a += t;
+ let e = t / a;
+ this._mixBufferRegion(n, i, 0, e, r);
+ }
+ this.cumulativeWeight = a;
+ }
+ accumulateAdditive(e) {
+ let t = this.buffer, n = this.valueSize, r = n * this._addIndex;
+ this.cumulativeWeightAdditive === 0 && this._setIdentity(), this._mixBufferRegionAdditive(t, r, 0, e, n), this.cumulativeWeightAdditive += e;
+ }
+ apply(e) {
+ let t = this.valueSize, n = this.buffer, r = e * t + t, i = this.cumulativeWeight, a = this.cumulativeWeightAdditive, o = this.binding;
+ if (this.cumulativeWeight = 0, this.cumulativeWeightAdditive = 0, i < 1) {
+ let e = t * this._origIndex;
+ this._mixBufferRegion(n, r, e, 1 - i, t);
+ }
+ a > 0 && this._mixBufferRegionAdditive(n, r, this._addIndex * t, 1, t);
+ for (let e = t, i = t + t; e !== i; ++e) if (n[e] !== n[e + t]) {
+ o.setValue(n, r);
+ break;
+ }
+ }
+ saveOriginalState() {
+ let e = this.binding, t = this.buffer, n = this.valueSize, r = n * this._origIndex;
+ e.getValue(t, r);
+ for (let e = n, i = r; e !== i; ++e) t[e] = t[r + e % n];
+ this._setIdentity(), this.cumulativeWeight = 0, this.cumulativeWeightAdditive = 0;
+ }
+ restoreOriginalState() {
+ let e = this.valueSize * 3;
+ this.binding.setValue(this.buffer, e);
+ }
+ _setAdditiveIdentityNumeric() {
+ let e = this._addIndex * this.valueSize, t = e + this.valueSize;
+ for (let n = e; n < t; n++) this.buffer[n] = 0;
+ }
+ _setAdditiveIdentityQuaternion() {
+ this._setAdditiveIdentityNumeric(), this.buffer[this._addIndex * this.valueSize + 3] = 1;
+ }
+ _setAdditiveIdentityOther() {
+ let e = this._origIndex * this.valueSize, t = this._addIndex * this.valueSize;
+ for (let n = 0; n < this.valueSize; n++) this.buffer[t + n] = this.buffer[e + n];
+ }
+ _select(e, t, n, r, i) {
+ if (r >= .5) for (let r = 0; r !== i; ++r) e[t + r] = e[n + r];
+ }
+ _slerp(e, t, n, r) {
+ $t.slerpFlat(e, t, e, t, e, n, r);
+ }
+ _slerpAdditive(e, t, n, r, i) {
+ let a = this._workIndex * i;
+ $t.multiplyQuaternionsFlat(e, a, e, t, e, n), $t.slerpFlat(e, t, e, t, e, a, r);
+ }
+ _lerp(e, t, n, r, i) {
+ let a = 1 - r;
+ for (let o = 0; o !== i; ++o) {
+ let i = t + o;
+ e[i] = e[i] * a + e[n + o] * r;
+ }
+ }
+ _lerpAdditive(e, t, n, r, i) {
+ for (let a = 0; a !== i; ++a) {
+ let i = t + a;
+ e[i] = e[i] + e[n + a] * r;
+ }
+ }
+}, Io = "\\[\\]\\.:\\/", Lo = RegExp("[" + Io + "]", "g"), Ro = "[^" + Io + "]", zo = "[^" + Io.replace("\\.", "") + "]", Bo = /* @__PURE__ */ "((?:WC+[\\/:])*)".replace("WC", Ro), Vo = /* @__PURE__ */ "(WCOD+)?".replace("WCOD", zo), Ho = /* @__PURE__ */ "(?:\\.(WC+)(?:\\[(.+)\\])?)?".replace("WC", Ro), Uo = /* @__PURE__ */ "\\.(WC+)(?:\\[(.+)\\])?".replace("WC", Ro), Wo = RegExp("^" + Bo + Vo + Ho + Uo + "$"), Go = [
+ "material",
+ "materials",
+ "bones",
+ "map"
+], Ko = class {
+ constructor(e, t, n) {
+ let r = n || qo.parseTrackName(t);
+ this._targetGroup = e, this._bindings = e.subscribe_(t, r);
+ }
+ getValue(e, t) {
+ this.bind();
+ let n = this._targetGroup.nCachedObjects_, r = this._bindings[n];
+ r !== void 0 && r.getValue(e, t);
+ }
+ setValue(e, t) {
+ let n = this._bindings;
+ for (let r = this._targetGroup.nCachedObjects_, i = n.length; r !== i; ++r) n[r].setValue(e, t);
+ }
+ bind() {
+ let e = this._bindings;
+ for (let t = this._targetGroup.nCachedObjects_, n = e.length; t !== n; ++t) e[t].bind();
+ }
+ unbind() {
+ let e = this._bindings;
+ for (let t = this._targetGroup.nCachedObjects_, n = e.length; t !== n; ++t) e[t].unbind();
+ }
+}, qo = class e {
+ constructor(t, n, r) {
+ this.path = n, this.parsedPath = r || e.parseTrackName(n), this.node = e.findNode(t, this.parsedPath.nodeName), this.rootNode = t, this.getValue = this._getValue_unbound, this.setValue = this._setValue_unbound;
+ }
+ static create(t, n, r) {
+ return t && t.isAnimationObjectGroup ? new e.Composite(t, n, r) : new e(t, n, r);
+ }
+ static sanitizeNodeName(e) {
+ return e.replace(/\s/g, "_").replace(Lo, "");
+ }
+ static parseTrackName(e) {
+ let t = Wo.exec(e);
+ if (t === null) throw Error("PropertyBinding: Cannot parse trackName: " + e);
+ let n = {
+ nodeName: t[2],
+ objectName: t[3],
+ objectIndex: t[4],
+ propertyName: t[5],
+ propertyIndex: t[6]
+ }, r = n.nodeName && n.nodeName.lastIndexOf(".");
+ if (r !== void 0 && r !== -1) {
+ let e = n.nodeName.substring(r + 1);
+ Go.indexOf(e) !== -1 && (n.nodeName = n.nodeName.substring(0, r), n.objectName = e);
+ }
+ if (n.propertyName === null || n.propertyName.length === 0) throw Error("PropertyBinding: can not parse propertyName from trackName: " + e);
+ return n;
+ }
+ static findNode(e, t) {
+ if (t === void 0 || t === "" || t === "." || t === -1 || t === e.name || t === e.uuid) return e;
+ if (e.skeleton) {
+ let n = e.skeleton.getBoneByName(t);
+ if (n !== void 0) return n;
+ }
+ if (e.children) {
+ let n = function(e) {
+ for (let r = 0; r < e.length; r++) {
+ let i = e[r];
+ if (i.name === t || i.uuid === t) return i;
+ let a = n(i.children);
+ if (a) return a;
+ }
+ return null;
+ }, r = n(e.children);
+ if (r) return r;
+ }
+ return null;
+ }
+ _getValue_unavailable() {}
+ _setValue_unavailable() {}
+ _getValue_direct(e, t) {
+ e[t] = this.targetObject[this.propertyName];
+ }
+ _getValue_array(e, t) {
+ let n = this.resolvedProperty;
+ for (let r = 0, i = n.length; r !== i; ++r) e[t++] = n[r];
+ }
+ _getValue_arrayElement(e, t) {
+ e[t] = this.resolvedProperty[this.propertyIndex];
+ }
+ _getValue_toArray(e, t) {
+ this.resolvedProperty.toArray(e, t);
+ }
+ _setValue_direct(e, t) {
+ this.targetObject[this.propertyName] = e[t];
+ }
+ _setValue_direct_setNeedsUpdate(e, t) {
+ this.targetObject[this.propertyName] = e[t], this.targetObject.needsUpdate = !0;
+ }
+ _setValue_direct_setMatrixWorldNeedsUpdate(e, t) {
+ this.targetObject[this.propertyName] = e[t], this.targetObject.matrixWorldNeedsUpdate = !0;
+ }
+ _setValue_array(e, t) {
+ let n = this.resolvedProperty;
+ for (let r = 0, i = n.length; r !== i; ++r) n[r] = e[t++];
+ }
+ _setValue_array_setNeedsUpdate(e, t) {
+ let n = this.resolvedProperty;
+ for (let r = 0, i = n.length; r !== i; ++r) n[r] = e[t++];
+ this.targetObject.needsUpdate = !0;
+ }
+ _setValue_array_setMatrixWorldNeedsUpdate(e, t) {
+ let n = this.resolvedProperty;
+ for (let r = 0, i = n.length; r !== i; ++r) n[r] = e[t++];
+ this.targetObject.matrixWorldNeedsUpdate = !0;
+ }
+ _setValue_arrayElement(e, t) {
+ this.resolvedProperty[this.propertyIndex] = e[t];
+ }
+ _setValue_arrayElement_setNeedsUpdate(e, t) {
+ this.resolvedProperty[this.propertyIndex] = e[t], this.targetObject.needsUpdate = !0;
+ }
+ _setValue_arrayElement_setMatrixWorldNeedsUpdate(e, t) {
+ this.resolvedProperty[this.propertyIndex] = e[t], this.targetObject.matrixWorldNeedsUpdate = !0;
+ }
+ _setValue_fromArray(e, t) {
+ this.resolvedProperty.fromArray(e, t);
+ }
+ _setValue_fromArray_setNeedsUpdate(e, t) {
+ this.resolvedProperty.fromArray(e, t), this.targetObject.needsUpdate = !0;
+ }
+ _setValue_fromArray_setMatrixWorldNeedsUpdate(e, t) {
+ this.resolvedProperty.fromArray(e, t), this.targetObject.matrixWorldNeedsUpdate = !0;
+ }
+ _getValue_unbound(e, t) {
+ this.bind(), this.getValue(e, t);
+ }
+ _setValue_unbound(e, t) {
+ this.bind(), this.setValue(e, t);
+ }
+ bind() {
+ let t = this.node, n = this.parsedPath, r = n.objectName, i = n.propertyName, a = n.propertyIndex;
+ if (t || (t = e.findNode(this.rootNode, n.nodeName), this.node = t), this.getValue = this._getValue_unavailable, this.setValue = this._setValue_unavailable, !t) {
+ console.warn("THREE.PropertyBinding: No target node found for track: " + this.path + ".");
+ return;
+ }
+ if (r) {
+ let e = n.objectIndex;
+ switch (r) {
+ case "materials":
+ if (!t.material) {
+ console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this);
+ return;
+ }
+ if (!t.material.materials) {
+ console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this);
+ return;
+ }
+ t = t.material.materials;
+ break;
+ case "bones":
+ if (!t.skeleton) {
+ console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.", this);
+ return;
+ }
+ t = t.skeleton.bones;
+ for (let n = 0; n < t.length; n++) if (t[n].name === e) {
+ e = n;
+ break;
+ }
+ break;
+ case "map":
+ if ("map" in t) {
+ t = t.map;
+ break;
+ }
+ if (!t.material) {
+ console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this);
+ return;
+ }
+ if (!t.material.map) {
+ console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.", this);
+ return;
+ }
+ t = t.material.map;
+ break;
+ default:
+ if (t[r] === void 0) {
+ console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.", this);
+ return;
+ }
+ t = t[r];
+ }
+ if (e !== void 0) {
+ if (t[e] === void 0) {
+ console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, t);
+ return;
+ }
+ t = t[e];
+ }
+ }
+ let o = t[i];
+ if (o === void 0) {
+ let e = n.nodeName;
+ console.error("THREE.PropertyBinding: Trying to update property for track: " + e + "." + i + " but it wasn't found.", t);
+ return;
+ }
+ let s = this.Versioning.None;
+ this.targetObject = t, t.isMaterial === !0 ? s = this.Versioning.NeedsUpdate : t.isObject3D === !0 && (s = this.Versioning.MatrixWorldNeedsUpdate);
+ let c = this.BindingType.Direct;
+ if (a !== void 0) {
+ if (i === "morphTargetInfluences") {
+ if (!t.geometry) {
+ console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this);
+ return;
+ }
+ if (!t.geometry.morphAttributes) {
+ console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this);
+ return;
+ }
+ t.morphTargetDictionary[a] !== void 0 && (a = t.morphTargetDictionary[a]);
+ }
+ c = this.BindingType.ArrayElement, this.resolvedProperty = o, this.propertyIndex = a;
+ } else o.fromArray !== void 0 && o.toArray !== void 0 ? (c = this.BindingType.HasFromToArray, this.resolvedProperty = o) : Array.isArray(o) ? (c = this.BindingType.EntireArray, this.resolvedProperty = o) : this.propertyName = i;
+ this.getValue = this.GetterByBindingType[c], this.setValue = this.SetterByBindingTypeAndVersioning[c][s];
+ }
+ unbind() {
+ this.node = null, this.getValue = this._getValue_unbound, this.setValue = this._setValue_unbound;
+ }
+};
+qo.Composite = Ko, qo.prototype.BindingType = {
+ Direct: 0,
+ EntireArray: 1,
+ ArrayElement: 2,
+ HasFromToArray: 3
+}, qo.prototype.Versioning = {
+ None: 0,
+ NeedsUpdate: 1,
+ MatrixWorldNeedsUpdate: 2
+}, qo.prototype.GetterByBindingType = [
+ qo.prototype._getValue_direct,
+ qo.prototype._getValue_array,
+ qo.prototype._getValue_arrayElement,
+ qo.prototype._getValue_toArray
+], qo.prototype.SetterByBindingTypeAndVersioning = [
+ [
+ qo.prototype._setValue_direct,
+ qo.prototype._setValue_direct_setNeedsUpdate,
+ qo.prototype._setValue_direct_setMatrixWorldNeedsUpdate
+ ],
+ [
+ qo.prototype._setValue_array,
+ qo.prototype._setValue_array_setNeedsUpdate,
+ qo.prototype._setValue_array_setMatrixWorldNeedsUpdate
+ ],
+ [
+ qo.prototype._setValue_arrayElement,
+ qo.prototype._setValue_arrayElement_setNeedsUpdate,
+ qo.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate
+ ],
+ [
+ qo.prototype._setValue_fromArray,
+ qo.prototype._setValue_fromArray_setNeedsUpdate,
+ qo.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate
+ ]
+];
+var Jo = class {
+ constructor(e, t, n = null, r = t.blendMode) {
+ this._mixer = e, this._clip = t, this._localRoot = n, this.blendMode = r;
+ let i = t.tracks, a = i.length, o = Array(a), s = {
+ endingStart: Re,
+ endingEnd: Re
+ };
+ for (let e = 0; e !== a; ++e) {
+ let t = i[e].createInterpolant(null);
+ o[e] = t, t.settings = s;
+ }
+ this._interpolantSettings = s, this._interpolants = o, this._propertyBindings = Array(a), this._cacheIndex = null, this._byClipCacheIndex = null, this._timeScaleInterpolant = null, this._weightInterpolant = null, this.loop = Ne, this._loopCount = -1, this._startTime = null, this.time = 0, this.timeScale = 1, this._effectiveTimeScale = 1, this.weight = 1, this._effectiveWeight = 1, this.repetitions = Infinity, this.paused = !1, this.enabled = !0, this.clampWhenFinished = !1, this.zeroSlopeAtStart = !0, this.zeroSlopeAtEnd = !0;
+ }
+ play() {
+ return this._mixer._activateAction(this), this;
+ }
+ stop() {
+ return this._mixer._deactivateAction(this), this.reset();
+ }
+ reset() {
+ return this.paused = !1, this.enabled = !0, this.time = 0, this._loopCount = -1, this._startTime = null, this.stopFading().stopWarping();
+ }
+ isRunning() {
+ return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
+ }
+ isScheduled() {
+ return this._mixer._isActiveAction(this);
+ }
+ startAt(e) {
+ return this._startTime = e, this;
+ }
+ setLoop(e, t) {
+ return this.loop = e, this.repetitions = t, this;
+ }
+ setEffectiveWeight(e) {
+ return this.weight = e, this._effectiveWeight = this.enabled ? e : 0, this.stopFading();
+ }
+ getEffectiveWeight() {
+ return this._effectiveWeight;
+ }
+ fadeIn(e) {
+ return this._scheduleFading(e, 0, 1);
+ }
+ fadeOut(e) {
+ return this._scheduleFading(e, 1, 0);
+ }
+ crossFadeFrom(e, t, n = !1) {
+ if (e.fadeOut(t), this.fadeIn(t), n === !0) {
+ let n = this._clip.duration, r = e._clip.duration, i = r / n, a = n / r;
+ e.warp(1, i, t), this.warp(a, 1, t);
+ }
+ return this;
+ }
+ crossFadeTo(e, t, n = !1) {
+ return e.crossFadeFrom(this, t, n);
+ }
+ stopFading() {
+ let e = this._weightInterpolant;
+ return e !== null && (this._weightInterpolant = null, this._mixer._takeBackControlInterpolant(e)), this;
+ }
+ setEffectiveTimeScale(e) {
+ return this.timeScale = e, this._effectiveTimeScale = this.paused ? 0 : e, this.stopWarping();
+ }
+ getEffectiveTimeScale() {
+ return this._effectiveTimeScale;
+ }
+ setDuration(e) {
+ return this.timeScale = this._clip.duration / e, this.stopWarping();
+ }
+ syncWith(e) {
+ return this.time = e.time, this.timeScale = e.timeScale, this.stopWarping();
+ }
+ halt(e) {
+ return this.warp(this._effectiveTimeScale, 0, e);
+ }
+ warp(e, t, n) {
+ let r = this._mixer, i = r.time, a = this.timeScale, o = this._timeScaleInterpolant;
+ o === null && (o = r._lendControlInterpolant(), this._timeScaleInterpolant = o);
+ let s = o.parameterPositions, c = o.sampleValues;
+ return s[0] = i, s[1] = i + n, c[0] = e / a, c[1] = t / a, this;
+ }
+ stopWarping() {
+ let e = this._timeScaleInterpolant;
+ return e !== null && (this._timeScaleInterpolant = null, this._mixer._takeBackControlInterpolant(e)), this;
+ }
+ getMixer() {
+ return this._mixer;
+ }
+ getClip() {
+ return this._clip;
+ }
+ getRoot() {
+ return this._localRoot || this._mixer._root;
+ }
+ _update(e, t, n, r) {
+ if (!this.enabled) {
+ this._updateWeight(e);
+ return;
+ }
+ let i = this._startTime;
+ if (i !== null) {
+ let r = (e - i) * n;
+ r < 0 || n === 0 ? t = 0 : (this._startTime = null, t = n * r);
+ }
+ t *= this._updateTimeScale(e);
+ let a = this._updateTime(t), o = this._updateWeight(e);
+ if (o > 0) {
+ let e = this._interpolants, t = this._propertyBindings;
+ switch (this.blendMode) {
+ case He:
+ for (let n = 0, r = e.length; n !== r; ++n) e[n].evaluate(a), t[n].accumulateAdditive(o);
+ break;
+ case Ve:
+ default: for (let n = 0, i = e.length; n !== i; ++n) e[n].evaluate(a), t[n].accumulate(r, o);
+ }
+ }
+ }
+ _updateWeight(e) {
+ let t = 0;
+ if (this.enabled) {
+ t = this.weight;
+ let n = this._weightInterpolant;
+ if (n !== null) {
+ let r = n.evaluate(e)[0];
+ t *= r, e > n.parameterPositions[1] && (this.stopFading(), r === 0 && (this.enabled = !1));
+ }
+ }
+ return this._effectiveWeight = t, t;
+ }
+ _updateTimeScale(e) {
+ let t = 0;
+ if (!this.paused) {
+ t = this.timeScale;
+ let n = this._timeScaleInterpolant;
+ if (n !== null) {
+ let r = n.evaluate(e)[0];
+ t *= r, e > n.parameterPositions[1] && (this.stopWarping(), t === 0 ? this.paused = !0 : this.timeScale = t);
+ }
+ }
+ return this._effectiveTimeScale = t, t;
+ }
+ _updateTime(e) {
+ let t = this._clip.duration, n = this.loop, r = this.time + e, i = this._loopCount, a = n === Pe;
+ if (e === 0) return i === -1 ? r : a && (i & 1) == 1 ? t - r : r;
+ if (n === 2200) {
+ i === -1 && (this._loopCount = 0, this._setEndings(!0, !0, !1));
+ handle_stop: {
+ if (r >= t) r = t;
+ else if (r < 0) r = 0;
+ else {
+ this.time = r;
+ break handle_stop;
+ }
+ this.clampWhenFinished ? this.paused = !0 : this.enabled = !1, this.time = r, this._mixer.dispatchEvent({
+ type: "finished",
+ action: this,
+ direction: e < 0 ? -1 : 1
+ });
+ }
+ } else {
+ if (i === -1 && (e >= 0 ? (i = 0, this._setEndings(!0, this.repetitions === 0, a)) : this._setEndings(this.repetitions === 0, !0, a)), r >= t || r < 0) {
+ let n = Math.floor(r / t);
+ r -= t * n, i += Math.abs(n);
+ let o = this.repetitions - i;
+ if (o <= 0) this.clampWhenFinished ? this.paused = !0 : this.enabled = !1, r = e > 0 ? t : 0, this.time = r, this._mixer.dispatchEvent({
+ type: "finished",
+ action: this,
+ direction: e > 0 ? 1 : -1
+ });
+ else {
+ if (o === 1) {
+ let t = e < 0;
+ this._setEndings(t, !t, a);
+ } else this._setEndings(!1, !1, a);
+ this._loopCount = i, this.time = r, this._mixer.dispatchEvent({
+ type: "loop",
+ action: this,
+ loopDelta: n
+ });
+ }
+ } else this.time = r;
+ if (a && (i & 1) == 1) return t - r;
+ }
+ return r;
+ }
+ _setEndings(e, t, n) {
+ let r = this._interpolantSettings;
+ n ? (r.endingStart = ze, r.endingEnd = ze) : (e ? r.endingStart = this.zeroSlopeAtStart ? ze : Re : r.endingStart = Be, t ? r.endingEnd = this.zeroSlopeAtEnd ? ze : Re : r.endingEnd = Be);
+ }
+ _scheduleFading(e, t, n) {
+ let r = this._mixer, i = r.time, a = this._weightInterpolant;
+ a === null && (a = r._lendControlInterpolant(), this._weightInterpolant = a);
+ let o = a.parameterPositions, s = a.sampleValues;
+ return o[0] = i, s[0] = t, o[1] = i + e, s[1] = n, this;
+ }
+}, Yo = new Float32Array(1), Xo = class extends Qe {
+ constructor(e) {
+ super(), this._root = e, this._initMemoryManager(), this._accuIndex = 0, this.time = 0, this.timeScale = 1;
+ }
+ _bindAction(e, t) {
+ let n = e._localRoot || this._root, r = e._clip.tracks, i = r.length, a = e._propertyBindings, o = e._interpolants, s = n.uuid, c = this._bindingsByRootAndName, l = c[s];
+ l === void 0 && (l = {}, c[s] = l);
+ for (let e = 0; e !== i; ++e) {
+ let i = r[e], c = i.name, u = l[c];
+ if (u !== void 0) ++u.referenceCount, a[e] = u;
+ else {
+ if (u = a[e], u !== void 0) {
+ u._cacheIndex === null && (++u.referenceCount, this._addInactiveBinding(u, s, c));
+ continue;
+ }
+ let r = t && t._propertyBindings[e].binding.parsedPath;
+ u = new Fo(qo.create(n, c, r), i.ValueTypeName, i.getValueSize()), ++u.referenceCount, this._addInactiveBinding(u, s, c), a[e] = u;
+ }
+ o[e].resultBuffer = u.buffer;
+ }
+ }
+ _activateAction(e) {
+ if (!this._isActiveAction(e)) {
+ if (e._cacheIndex === null) {
+ let t = (e._localRoot || this._root).uuid, n = e._clip.uuid, r = this._actionsByClip[n];
+ this._bindAction(e, r && r.knownActions[0]), this._addInactiveAction(e, n, t);
+ }
+ let t = e._propertyBindings;
+ for (let e = 0, n = t.length; e !== n; ++e) {
+ let n = t[e];
+ n.useCount++ === 0 && (this._lendBinding(n), n.saveOriginalState());
+ }
+ this._lendAction(e);
+ }
+ }
+ _deactivateAction(e) {
+ if (this._isActiveAction(e)) {
+ let t = e._propertyBindings;
+ for (let e = 0, n = t.length; e !== n; ++e) {
+ let n = t[e];
+ --n.useCount === 0 && (n.restoreOriginalState(), this._takeBackBinding(n));
+ }
+ this._takeBackAction(e);
+ }
+ }
+ _initMemoryManager() {
+ this._actions = [], this._nActiveActions = 0, this._actionsByClip = {}, this._bindings = [], this._nActiveBindings = 0, this._bindingsByRootAndName = {}, this._controlInterpolants = [], this._nActiveControlInterpolants = 0;
+ let e = this;
+ this.stats = {
+ actions: {
+ get total() {
+ return e._actions.length;
+ },
+ get inUse() {
+ return e._nActiveActions;
+ }
+ },
+ bindings: {
+ get total() {
+ return e._bindings.length;
+ },
+ get inUse() {
+ return e._nActiveBindings;
+ }
+ },
+ controlInterpolants: {
+ get total() {
+ return e._controlInterpolants.length;
+ },
+ get inUse() {
+ return e._nActiveControlInterpolants;
+ }
+ }
+ };
+ }
+ _isActiveAction(e) {
+ let t = e._cacheIndex;
+ return t !== null && t < this._nActiveActions;
+ }
+ _addInactiveAction(e, t, n) {
+ let r = this._actions, i = this._actionsByClip, a = i[t];
+ if (a === void 0) a = {
+ knownActions: [e],
+ actionByRoot: {}
+ }, e._byClipCacheIndex = 0, i[t] = a;
+ else {
+ let t = a.knownActions;
+ e._byClipCacheIndex = t.length, t.push(e);
+ }
+ e._cacheIndex = r.length, r.push(e), a.actionByRoot[n] = e;
+ }
+ _removeInactiveAction(e) {
+ let t = this._actions, n = t[t.length - 1], r = e._cacheIndex;
+ n._cacheIndex = r, t[r] = n, t.pop(), e._cacheIndex = null;
+ let i = e._clip.uuid, a = this._actionsByClip, o = a[i], s = o.knownActions, c = s[s.length - 1], l = e._byClipCacheIndex;
+ c._byClipCacheIndex = l, s[l] = c, s.pop(), e._byClipCacheIndex = null;
+ let u = o.actionByRoot, d = (e._localRoot || this._root).uuid;
+ delete u[d], s.length === 0 && delete a[i], this._removeInactiveBindingsForAction(e);
+ }
+ _removeInactiveBindingsForAction(e) {
+ let t = e._propertyBindings;
+ for (let e = 0, n = t.length; e !== n; ++e) {
+ let n = t[e];
+ --n.referenceCount === 0 && this._removeInactiveBinding(n);
+ }
+ }
+ _lendAction(e) {
+ let t = this._actions, n = e._cacheIndex, r = this._nActiveActions++, i = t[r];
+ e._cacheIndex = r, t[r] = e, i._cacheIndex = n, t[n] = i;
+ }
+ _takeBackAction(e) {
+ let t = this._actions, n = e._cacheIndex, r = --this._nActiveActions, i = t[r];
+ e._cacheIndex = r, t[r] = e, i._cacheIndex = n, t[n] = i;
+ }
+ _addInactiveBinding(e, t, n) {
+ let r = this._bindingsByRootAndName, i = this._bindings, a = r[t];
+ a === void 0 && (a = {}, r[t] = a), a[n] = e, e._cacheIndex = i.length, i.push(e);
+ }
+ _removeInactiveBinding(e) {
+ let t = this._bindings, n = e.binding, r = n.rootNode.uuid, i = n.path, a = this._bindingsByRootAndName, o = a[r], s = t[t.length - 1], c = e._cacheIndex;
+ s._cacheIndex = c, t[c] = s, t.pop(), delete o[i], Object.keys(o).length === 0 && delete a[r];
+ }
+ _lendBinding(e) {
+ let t = this._bindings, n = e._cacheIndex, r = this._nActiveBindings++, i = t[r];
+ e._cacheIndex = r, t[r] = e, i._cacheIndex = n, t[n] = i;
+ }
+ _takeBackBinding(e) {
+ let t = this._bindings, n = e._cacheIndex, r = --this._nActiveBindings, i = t[r];
+ e._cacheIndex = r, t[r] = e, i._cacheIndex = n, t[n] = i;
+ }
+ _lendControlInterpolant() {
+ let e = this._controlInterpolants, t = this._nActiveControlInterpolants++, n = e[t];
+ return n === void 0 && (n = new Ga(new Float32Array(2), new Float32Array(2), 1, Yo), n.__cacheIndex = t, e[t] = n), n;
+ }
+ _takeBackControlInterpolant(e) {
+ let t = this._controlInterpolants, n = e.__cacheIndex, r = --this._nActiveControlInterpolants, i = t[r];
+ e.__cacheIndex = r, t[r] = e, i.__cacheIndex = n, t[n] = i;
+ }
+ clipAction(e, t, n) {
+ let r = t || this._root, i = r.uuid, a = typeof e == "string" ? to.findByName(r, e) : e, o = a === null ? e : a.uuid, s = this._actionsByClip[o], c = null;
+ if (n === void 0 && (n = a === null ? Ve : a.blendMode), s !== void 0) {
+ let e = s.actionByRoot[i];
+ if (e !== void 0 && e.blendMode === n) return e;
+ c = s.knownActions[0], a === null && (a = c._clip);
+ }
+ if (a === null) return null;
+ let l = new Jo(this, a, t, n);
+ return this._bindAction(l, c), this._addInactiveAction(l, o, i), l;
+ }
+ existingAction(e, t) {
+ let n = t || this._root, r = n.uuid, i = typeof e == "string" ? to.findByName(n, e) : e, a = i ? i.uuid : e, o = this._actionsByClip[a];
+ return o === void 0 ? null : o.actionByRoot[r] || null;
+ }
+ stopAllAction() {
+ let e = this._actions, t = this._nActiveActions;
+ for (let n = t - 1; n >= 0; --n) e[n].stop();
+ return this;
+ }
+ update(e) {
+ e *= this.timeScale;
+ let t = this._actions, n = this._nActiveActions, r = this.time += e, i = Math.sign(e), a = this._accuIndex ^= 1;
+ for (let o = 0; o !== n; ++o) t[o]._update(r, e, i, a);
+ let o = this._bindings, s = this._nActiveBindings;
+ for (let e = 0; e !== s; ++e) o[e].apply(a);
+ return this;
+ }
+ setTime(e) {
+ this.time = 0;
+ for (let e = 0; e < this._actions.length; e++) this._actions[e].time = 0;
+ return this.update(e);
+ }
+ getRoot() {
+ return this._root;
+ }
+ uncacheClip(e) {
+ let t = this._actions, n = e.uuid, r = this._actionsByClip, i = r[n];
+ if (i !== void 0) {
+ let e = i.knownActions;
+ for (let n = 0, r = e.length; n !== r; ++n) {
+ let r = e[n];
+ this._deactivateAction(r);
+ let i = r._cacheIndex, a = t[t.length - 1];
+ r._cacheIndex = null, r._byClipCacheIndex = null, a._cacheIndex = i, t[i] = a, t.pop(), this._removeInactiveBindingsForAction(r);
+ }
+ delete r[n];
+ }
+ }
+ uncacheRoot(e) {
+ let t = e.uuid, n = this._actionsByClip;
+ for (let e in n) {
+ let r = n[e].actionByRoot[t];
+ r !== void 0 && (this._deactivateAction(r), this._removeInactiveAction(r));
+ }
+ let r = this._bindingsByRootAndName[t];
+ if (r !== void 0) for (let e in r) {
+ let t = r[e];
+ t.restoreOriginalState(), this._removeInactiveBinding(t);
+ }
+ }
+ uncacheAction(e, t) {
+ let n = this.existingAction(e, t);
+ n !== null && (this._deactivateAction(n), this._removeInactiveAction(n));
+ }
+}, Zo = class {
+ constructor(e = 1, t = 0, n = 0) {
+ this.radius = e, this.phi = t, this.theta = n;
+ }
+ set(e, t, n) {
+ return this.radius = e, this.phi = t, this.theta = n, this;
+ }
+ copy(e) {
+ return this.radius = e.radius, this.phi = e.phi, this.theta = e.theta, this;
+ }
+ makeSafe() {
+ let e = 1e-6;
+ return this.phi = I(this.phi, e, Math.PI - e), this;
+ }
+ setFromVector3(e) {
+ return this.setFromCartesianCoords(e.x, e.y, e.z);
+ }
+ setFromCartesianCoords(e, t, n) {
+ return this.radius = Math.sqrt(e * e + t * t + n * n), this.radius === 0 ? (this.theta = 0, this.phi = 0) : (this.theta = Math.atan2(e, n), this.phi = Math.acos(I(t / this.radius, -1, 1))), this;
+ }
+ clone() {
+ return new this.constructor().copy(this);
+ }
+}, Qo = /* @__PURE__ */ new R(), $o = /* @__PURE__ */ new z(), es = /* @__PURE__ */ new z(), ts = class extends ba {
+ constructor(e) {
+ let t = ns(e), n = new Wr(), r = [], i = [], a = new B(0, 0, 1), o = new B(0, 1, 0);
+ for (let e = 0; e < t.length; e++) {
+ let n = t[e];
+ n.parent && n.parent.isBone && (r.push(0, 0, 0), r.push(0, 0, 0), i.push(a.r, a.g, a.b), i.push(o.r, o.g, o.b));
+ }
+ n.setAttribute("position", new Ir(r, 3)), n.setAttribute("color", new Ir(i, 3));
+ let s = new ca({
+ vertexColors: !0,
+ depthTest: !1,
+ depthWrite: !1,
+ toneMapped: !1,
+ transparent: !0
+ });
+ super(n, s), this.isSkeletonHelper = !0, this.type = "SkeletonHelper", this.root = e, this.bones = t, this.matrix = e.matrixWorld, this.matrixAutoUpdate = !1;
+ }
+ updateMatrixWorld(e) {
+ let t = this.bones, n = this.geometry, r = n.getAttribute("position");
+ es.copy(this.root.matrixWorld).invert();
+ for (let e = 0, n = 0; e < t.length; e++) {
+ let i = t[e];
+ i.parent && i.parent.isBone && ($o.multiplyMatrices(es, i.matrixWorld), Qo.setFromMatrixPosition($o), r.setXYZ(n, Qo.x, Qo.y, Qo.z), $o.multiplyMatrices(es, i.parent.matrixWorld), Qo.setFromMatrixPosition($o), r.setXYZ(n + 1, Qo.x, Qo.y, Qo.z), n += 2);
+ }
+ n.getAttribute("position").needsUpdate = !0, super.updateMatrixWorld(e);
+ }
+ dispose() {
+ this.geometry.dispose(), this.material.dispose();
+ }
+};
+function ns(e) {
+ let t = [];
+ e.isBone === !0 && t.push(e);
+ for (let n = 0; n < e.children.length; n++) t.push(...ns(e.children[n]));
+ return t;
+}
+var rs = class extends ba {
+ constructor(e = 10, t = 10, n = 4473924, r = 8947848) {
+ n = new B(n), r = new B(r);
+ let i = t / 2, a = e / t, o = e / 2, s = [], c = [];
+ for (let e = 0, l = 0, u = -o; e <= t; e++, u += a) {
+ s.push(-o, 0, u, o, 0, u), s.push(u, 0, -o, u, 0, o);
+ let t = e === i ? n : r;
+ t.toArray(c, l), l += 3, t.toArray(c, l), l += 3, t.toArray(c, l), l += 3, t.toArray(c, l), l += 3;
+ }
+ let l = new Wr();
+ l.setAttribute("position", new Ir(s, 3)), l.setAttribute("color", new Ir(c, 3));
+ let u = new ca({
+ vertexColors: !0,
+ toneMapped: !1
+ });
+ super(l, u), this.type = "GridHelper";
+ }
+ dispose() {
+ this.geometry.dispose(), this.material.dispose();
+ }
+}, is = class extends ba {
+ constructor(e = 1) {
+ let t = [
+ 0,
+ 0,
+ 0,
+ e,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ e,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ e
+ ], n = [
+ 1,
+ 0,
+ 0,
+ 1,
+ .6,
+ 0,
+ 0,
+ 1,
+ 0,
+ .6,
+ 1,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ .6,
+ 1
+ ], r = new Wr();
+ r.setAttribute("position", new Ir(t, 3)), r.setAttribute("color", new Ir(n, 3));
+ let i = new ca({
+ vertexColors: !0,
+ toneMapped: !1
+ });
+ super(r, i), this.type = "AxesHelper";
+ }
+ setColors(e, t, n) {
+ let r = new B(), i = this.geometry.attributes.color.array;
+ return r.set(e), r.toArray(i, 0), r.toArray(i, 3), r.set(t), r.toArray(i, 6), r.toArray(i, 9), r.set(n), r.toArray(i, 12), r.toArray(i, 15), this.geometry.attributes.color.needsUpdate = !0, this;
+ }
+ dispose() {
+ this.geometry.dispose(), this.material.dispose();
+ }
+}, as = class extends Qe {
+ constructor(e, t = null) {
+ super(), this.object = e, this.domElement = t, this.enabled = !0, this.state = -1, this.keys = {}, this.mouseButtons = {
+ LEFT: null,
+ MIDDLE: null,
+ RIGHT: null
+ }, this.touches = {
+ ONE: null,
+ TWO: null
+ };
+ }
+ connect(e) {
+ if (e === void 0) {
+ console.warn("THREE.Controls: connect() now requires an element.");
+ return;
+ }
+ this.domElement !== null && this.disconnect(), this.domElement = e;
+ }
+ disconnect() {}
+ dispose() {}
+ update() {}
+};
+function os(e, t, n, r) {
+ let i = ss(r);
+ switch (n) {
+ case E: return e * t;
+ case A: return e * t / i.components * i.byteLength;
+ case te: return e * t / i.components * i.byteLength;
+ case ne: return e * t * 2 / i.components * i.byteLength;
+ case re: return e * t * 2 / i.components * i.byteLength;
+ case D: return e * t * 3 / i.components * i.byteLength;
+ case O: return e * t * 4 / i.components * i.byteLength;
+ case ie: return e * t * 4 / i.components * i.byteLength;
+ case ae:
+ case oe: return Math.floor((e + 3) / 4) * Math.floor((t + 3) / 4) * 8;
+ case se:
+ case ce: return Math.floor((e + 3) / 4) * Math.floor((t + 3) / 4) * 16;
+ case ue:
+ case fe: return Math.max(e, 16) * Math.max(t, 8) / 4;
+ case le:
+ case de: return Math.max(e, 8) * Math.max(t, 8) / 2;
+ case pe:
+ case me: return Math.floor((e + 3) / 4) * Math.floor((t + 3) / 4) * 8;
+ case he: return Math.floor((e + 3) / 4) * Math.floor((t + 3) / 4) * 16;
+ case ge: return Math.floor((e + 3) / 4) * Math.floor((t + 3) / 4) * 16;
+ case _e: return Math.floor((e + 4) / 5) * Math.floor((t + 3) / 4) * 16;
+ case ve: return Math.floor((e + 4) / 5) * Math.floor((t + 4) / 5) * 16;
+ case ye: return Math.floor((e + 5) / 6) * Math.floor((t + 4) / 5) * 16;
+ case be: return Math.floor((e + 5) / 6) * Math.floor((t + 5) / 6) * 16;
+ case j: return Math.floor((e + 7) / 8) * Math.floor((t + 4) / 5) * 16;
+ case xe: return Math.floor((e + 7) / 8) * Math.floor((t + 5) / 6) * 16;
+ case Se: return Math.floor((e + 7) / 8) * Math.floor((t + 7) / 8) * 16;
+ case Ce: return Math.floor((e + 9) / 10) * Math.floor((t + 4) / 5) * 16;
+ case M: return Math.floor((e + 9) / 10) * Math.floor((t + 5) / 6) * 16;
+ case we: return Math.floor((e + 9) / 10) * Math.floor((t + 7) / 8) * 16;
+ case N: return Math.floor((e + 9) / 10) * Math.floor((t + 9) / 10) * 16;
+ case P: return Math.floor((e + 11) / 12) * Math.floor((t + 9) / 10) * 16;
+ case Te: return Math.floor((e + 11) / 12) * Math.floor((t + 11) / 12) * 16;
+ case Ee:
+ case F:
+ case De: return Math.ceil(e / 4) * Math.ceil(t / 4) * 16;
+ case Oe:
+ case ke: return Math.ceil(e / 4) * Math.ceil(t / 4) * 8;
+ case Ae:
+ case je: return Math.ceil(e / 4) * Math.ceil(t / 4) * 16;
+ }
+ throw Error(`Unable to determine texture byte length for ${n} format.`);
+}
+function ss(e) {
+ switch (e) {
+ case m:
+ case h: return {
+ byteLength: 1,
+ components: 1
+ };
+ case _:
+ case g:
+ case x: return {
+ byteLength: 2,
+ components: 1
+ };
+ case S:
+ case C: return {
+ byteLength: 2,
+ components: 4
+ };
+ case y:
+ case v:
+ case b: return {
+ byteLength: 4,
+ components: 1
+ };
+ case T: return {
+ byteLength: 4,
+ components: 3
+ };
+ }
+ throw Error(`Unknown texture type ${e}.`);
+}
+typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: { revision: "176" } })), typeof window < "u" && (window.__THREE__ ? console.warn("WARNING: Multiple instances of Three.js being imported.") : window.__THREE__ = "176");
+//#endregion
+//#region node_modules/three/build/three.module.js
+function cs() {
+ let e = null, t = !1, n = null, r = null;
+ function i(t, a) {
+ n(t, a), r = e.requestAnimationFrame(i);
+ }
+ return {
+ start: function() {
+ t !== !0 && n !== null && (r = e.requestAnimationFrame(i), t = !0);
+ },
+ stop: function() {
+ e.cancelAnimationFrame(r), t = !1;
+ },
+ setAnimationLoop: function(e) {
+ n = e;
+ },
+ setContext: function(t) {
+ e = t;
+ }
+ };
+}
+function ls(e) {
+ let t = /* @__PURE__ */ new WeakMap();
+ function n(t, n) {
+ let r = t.array, i = t.usage, a = r.byteLength, o = e.createBuffer();
+ e.bindBuffer(n, o), e.bufferData(n, r, i), t.onUploadCallback();
+ let s;
+ if (r instanceof Float32Array) s = e.FLOAT;
+ else if (r instanceof Uint16Array) s = t.isFloat16BufferAttribute ? e.HALF_FLOAT : e.UNSIGNED_SHORT;
+ else if (r instanceof Int16Array) s = e.SHORT;
+ else if (r instanceof Uint32Array) s = e.UNSIGNED_INT;
+ else if (r instanceof Int32Array) s = e.INT;
+ else if (r instanceof Int8Array) s = e.BYTE;
+ else if (r instanceof Uint8Array) s = e.UNSIGNED_BYTE;
+ else if (r instanceof Uint8ClampedArray) s = e.UNSIGNED_BYTE;
+ else throw Error("THREE.WebGLAttributes: Unsupported buffer data format: " + r);
+ return {
+ buffer: o,
+ type: s,
+ bytesPerElement: r.BYTES_PER_ELEMENT,
+ version: t.version,
+ size: a
+ };
+ }
+ function r(t, n, r) {
+ let i = n.array, a = n.updateRanges;
+ if (e.bindBuffer(r, t), a.length === 0) e.bufferSubData(r, 0, i);
+ else {
+ a.sort((e, t) => e.start - t.start);
+ let t = 0;
+ for (let e = 1; e < a.length; e++) {
+ let n = a[t], r = a[e];
+ r.start <= n.start + n.count + 1 ? n.count = Math.max(n.count, r.start + r.count - n.start) : (++t, a[t] = r);
+ }
+ a.length = t + 1;
+ for (let t = 0, n = a.length; t < n; t++) {
+ let n = a[t];
+ e.bufferSubData(r, n.start * i.BYTES_PER_ELEMENT, i, n.start, n.count);
+ }
+ n.clearUpdateRanges();
+ }
+ n.onUploadCallback();
+ }
+ function i(e) {
+ return e.isInterleavedBufferAttribute && (e = e.data), t.get(e);
+ }
+ function a(n) {
+ n.isInterleavedBufferAttribute && (n = n.data);
+ let r = t.get(n);
+ r && (e.deleteBuffer(r.buffer), t.delete(n));
+ }
+ function o(e, i) {
+ if (e.isInterleavedBufferAttribute && (e = e.data), e.isGLBufferAttribute) {
+ let n = t.get(e);
+ (!n || n.version < e.version) && t.set(e, {
+ buffer: e.buffer,
+ type: e.type,
+ bytesPerElement: e.elementSize,
+ version: e.version
+ });
+ return;
+ }
+ let a = t.get(e);
+ if (a === void 0) t.set(e, n(e, i));
+ else if (a.version < e.version) {
+ if (a.size !== e.array.byteLength) throw Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");
+ r(a.buffer, e, i), a.version = e.version;
+ }
+ }
+ return {
+ get: i,
+ remove: a,
+ update: o
+ };
+}
+var V = {
+ alphahash_fragment: "#ifdef USE_ALPHAHASH\n if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif",
+ alphahash_pars_fragment: "#ifdef USE_ALPHAHASH\n const float ALPHA_HASH_SCALE = 0.05;\n float hash2D( vec2 value ) {\n return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n }\n float hash3D( vec3 value ) {\n return hash2D( vec2( hash2D( value.xy ), value.z ) );\n }\n float getAlphaHashThreshold( vec3 position ) {\n float maxDeriv = max(\n length( dFdx( position.xyz ) ),\n length( dFdy( position.xyz ) )\n );\n float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n vec2 pixScales = vec2(\n exp2( floor( log2( pixScale ) ) ),\n exp2( ceil( log2( pixScale ) ) )\n );\n vec2 alpha = vec2(\n hash3D( floor( pixScales.x * position.xyz ) ),\n hash3D( floor( pixScales.y * position.xyz ) )\n );\n float lerpFactor = fract( log2( pixScale ) );\n float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n float a = min( lerpFactor, 1.0 - lerpFactor );\n vec3 cases = vec3(\n x * x / ( 2.0 * a * ( 1.0 - a ) ),\n ( x - 0.5 * a ) / ( 1.0 - a ),\n 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n );\n float threshold = ( x < ( 1.0 - a ) )\n ? ( ( x < a ) ? cases.x : cases.y )\n : cases.z;\n return clamp( threshold , 1.0e-6, 1.0 );\n }\n#endif",
+ alphamap_fragment: "#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif",
+ alphamap_pars_fragment: "#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif",
+ alphatest_fragment: "#ifdef USE_ALPHATEST\n #ifdef ALPHA_TO_COVERAGE\n diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n if ( diffuseColor.a == 0.0 ) discard;\n #else\n if ( diffuseColor.a < alphaTest ) discard;\n #endif\n#endif",
+ alphatest_pars_fragment: "#ifdef USE_ALPHATEST\n uniform float alphaTest;\n#endif",
+ aomap_fragment: "#ifdef USE_AOMAP\n float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n reflectedLight.indirectDiffuse *= ambientOcclusion;\n #if defined( USE_CLEARCOAT ) \n clearcoatSpecularIndirect *= ambientOcclusion;\n #endif\n #if defined( USE_SHEEN ) \n sheenSpecularIndirect *= ambientOcclusion;\n #endif\n #if defined( USE_ENVMAP ) && defined( STANDARD )\n float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n #endif\n#endif",
+ aomap_pars_fragment: "#ifdef USE_AOMAP\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n#endif",
+ batching_pars_vertex: "#ifdef USE_BATCHING\n #if ! defined( GL_ANGLE_multi_draw )\n #define gl_DrawID _gl_DrawID\n uniform int _gl_DrawID;\n #endif\n uniform highp sampler2D batchingTexture;\n uniform highp usampler2D batchingIdTexture;\n mat4 getBatchingMatrix( const in float i ) {\n int size = textureSize( batchingTexture, 0 ).x;\n int j = int( i ) * 4;\n int x = j % size;\n int y = j / size;\n vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n return mat4( v1, v2, v3, v4 );\n }\n float getIndirectIndex( const in int i ) {\n int size = textureSize( batchingIdTexture, 0 ).x;\n int x = i % size;\n int y = i / size;\n return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n }\n#endif\n#ifdef USE_BATCHING_COLOR\n uniform sampler2D batchingColorTexture;\n vec3 getBatchingColor( const in float i ) {\n int size = textureSize( batchingColorTexture, 0 ).x;\n int j = int( i );\n int x = j % size;\n int y = j / size;\n return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;\n }\n#endif",
+ batching_vertex: "#ifdef USE_BATCHING\n mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif",
+ begin_vertex: "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n vPosition = vec3( position );\n#endif",
+ beginnormal_vertex: "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n vec3 objectTangent = vec3( tangent.xyz );\n#endif",
+ bsdfs: "float G_BlinnPhong_Implicit( ) {\n return 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotVH = saturate( dot( viewDir, halfDir ) );\n vec3 F = F_Schlick( specularColor, 1.0, dotVH );\n float G = G_BlinnPhong_Implicit( );\n float D = D_BlinnPhong( shininess, dotNH );\n return F * ( G * D );\n} // validated",
+ iridescence_fragment: "#ifdef USE_IRIDESCENCE\n const mat3 XYZ_TO_REC709 = mat3(\n 3.2404542, -0.9692660, 0.0556434,\n -1.5371385, 1.8760108, -0.2040259,\n -0.4985314, 0.0415560, 1.0572252\n );\n vec3 Fresnel0ToIor( vec3 fresnel0 ) {\n vec3 sqrtF0 = sqrt( fresnel0 );\n return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n }\n vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n }\n float IorToFresnel0( float transmittedIor, float incidentIor ) {\n return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n }\n vec3 evalSensitivity( float OPD, vec3 shift ) {\n float phase = 2.0 * PI * OPD * 1.0e-9;\n vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n xyz /= 1.0685e-7;\n vec3 rgb = XYZ_TO_REC709 * xyz;\n return rgb;\n }\n vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n vec3 I;\n float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n float cosTheta2Sq = 1.0 - sinTheta2Sq;\n if ( cosTheta2Sq < 0.0 ) {\n return vec3( 1.0 );\n }\n float cosTheta2 = sqrt( cosTheta2Sq );\n float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n float R12 = F_Schlick( R0, 1.0, cosTheta1 );\n float T121 = 1.0 - R12;\n float phi12 = 0.0;\n if ( iridescenceIOR < outsideIOR ) phi12 = PI;\n float phi21 = PI - phi12;\n vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n vec3 phi23 = vec3( 0.0 );\n if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n vec3 phi = vec3( phi21 ) + phi23;\n vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n vec3 r123 = sqrt( R123 );\n vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n vec3 C0 = R12 + Rs;\n I = C0;\n vec3 Cm = Rs - T121;\n for ( int m = 1; m <= 2; ++ m ) {\n Cm *= r123;\n vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n I += Cm * Sm;\n }\n return max( I, vec3( 0.0 ) );\n }\n#endif",
+ bumpmap_pars_fragment: "#ifdef USE_BUMPMAP\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n vec2 dHdxy_fwd() {\n vec2 dSTdx = dFdx( vBumpMapUv );\n vec2 dSTdy = dFdy( vBumpMapUv );\n float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n return vec2( dBx, dBy );\n }\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n vec3 vN = surf_norm;\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n float fDet = dot( vSigmaX, R1 ) * faceDirection;\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n }\n#endif",
+ clipping_planes_fragment: "#if NUM_CLIPPING_PLANES > 0\n vec4 plane;\n #ifdef ALPHA_TO_COVERAGE\n float distanceToPlane, distanceGradient;\n float clipOpacity = 1.0;\n #pragma unroll_loop_start\n for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n plane = clippingPlanes[ i ];\n distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n distanceGradient = fwidth( distanceToPlane ) / 2.0;\n clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n if ( clipOpacity == 0.0 ) discard;\n }\n #pragma unroll_loop_end\n #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n float unionClipOpacity = 1.0;\n #pragma unroll_loop_start\n for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n plane = clippingPlanes[ i ];\n distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n distanceGradient = fwidth( distanceToPlane ) / 2.0;\n unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n }\n #pragma unroll_loop_end\n clipOpacity *= 1.0 - unionClipOpacity;\n #endif\n diffuseColor.a *= clipOpacity;\n if ( diffuseColor.a == 0.0 ) discard;\n #else\n #pragma unroll_loop_start\n for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n plane = clippingPlanes[ i ];\n if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n }\n #pragma unroll_loop_end\n #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n bool clipped = true;\n #pragma unroll_loop_start\n for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n plane = clippingPlanes[ i ];\n clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n }\n #pragma unroll_loop_end\n if ( clipped ) discard;\n #endif\n #endif\n#endif",
+ clipping_planes_pars_fragment: "#if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",
+ clipping_planes_pars_vertex: "#if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n#endif",
+ clipping_planes_vertex: "#if NUM_CLIPPING_PLANES > 0\n vClipPosition = - mvPosition.xyz;\n#endif",
+ color_fragment: "#if defined( USE_COLOR_ALPHA )\n diffuseColor *= vColor;\n#elif defined( USE_COLOR )\n diffuseColor.rgb *= vColor;\n#endif",
+ color_pars_fragment: "#if defined( USE_COLOR_ALPHA )\n varying vec4 vColor;\n#elif defined( USE_COLOR )\n varying vec3 vColor;\n#endif",
+ color_pars_vertex: "#if defined( USE_COLOR_ALPHA )\n varying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n varying vec3 vColor;\n#endif",
+ color_vertex: "#if defined( USE_COLOR_ALPHA )\n vColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n vColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n vColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n vColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n vColor.xyz *= batchingColor.xyz;\n#endif",
+ common: "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n float precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n float precisionSafeLength( vec3 v ) {\n float maxComponent = max3( abs( v ) );\n return length( v / maxComponent ) * maxComponent;\n }\n#endif\nstruct IncidentLight {\n vec3 color;\n vec3 direction;\n bool visible;\n};\nstruct ReflectedLight {\n vec3 directDiffuse;\n vec3 directSpecular;\n vec3 indirectDiffuse;\n vec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n varying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n mat3 tmp;\n tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n return tmp;\n}\nbool isPerspectiveMatrix( mat4 m ) {\n return m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n return vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n return RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",
+ cube_uv_reflection_fragment: "#ifdef ENVMAP_TYPE_CUBE_UV\n #define cubeUV_minMipLevel 4.0\n #define cubeUV_minTileSize 16.0\n float getFace( vec3 direction ) {\n vec3 absDirection = abs( direction );\n float face = - 1.0;\n if ( absDirection.x > absDirection.z ) {\n if ( absDirection.x > absDirection.y )\n face = direction.x > 0.0 ? 0.0 : 3.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n } else {\n if ( absDirection.z > absDirection.y )\n face = direction.z > 0.0 ? 2.0 : 5.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n }\n return face;\n }\n vec2 getUV( vec3 direction, float face ) {\n vec2 uv;\n if ( face == 0.0 ) {\n uv = vec2( direction.z, direction.y ) / abs( direction.x );\n } else if ( face == 1.0 ) {\n uv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n } else if ( face == 2.0 ) {\n uv = vec2( - direction.x, direction.y ) / abs( direction.z );\n } else if ( face == 3.0 ) {\n uv = vec2( - direction.z, direction.y ) / abs( direction.x );\n } else if ( face == 4.0 ) {\n uv = vec2( - direction.x, direction.z ) / abs( direction.y );\n } else {\n uv = vec2( direction.x, direction.y ) / abs( direction.z );\n }\n return 0.5 * ( uv + 1.0 );\n }\n vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n float face = getFace( direction );\n float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n mipInt = max( mipInt, cubeUV_minMipLevel );\n float faceSize = exp2( mipInt );\n highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n if ( face > 2.0 ) {\n uv.y += faceSize;\n face -= 3.0;\n }\n uv.x += face * faceSize;\n uv.x += filterInt * 3.0 * cubeUV_minTileSize;\n uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n uv.x *= CUBEUV_TEXEL_WIDTH;\n uv.y *= CUBEUV_TEXEL_HEIGHT;\n #ifdef texture2DGradEXT\n return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n #else\n return texture2D( envMap, uv ).rgb;\n #endif\n }\n #define cubeUV_r0 1.0\n #define cubeUV_m0 - 2.0\n #define cubeUV_r1 0.8\n #define cubeUV_m1 - 1.0\n #define cubeUV_r4 0.4\n #define cubeUV_m4 2.0\n #define cubeUV_r5 0.305\n #define cubeUV_m5 3.0\n #define cubeUV_r6 0.21\n #define cubeUV_m6 4.0\n float roughnessToMip( float roughness ) {\n float mip = 0.0;\n if ( roughness >= cubeUV_r1 ) {\n mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n } else if ( roughness >= cubeUV_r4 ) {\n mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n } else if ( roughness >= cubeUV_r5 ) {\n mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n } else if ( roughness >= cubeUV_r6 ) {\n mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n } else {\n mip = - 2.0 * log2( 1.16 * roughness ); }\n return mip;\n }\n vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n float mipF = fract( mip );\n float mipInt = floor( mip );\n vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n if ( mipF == 0.0 ) {\n return vec4( color0, 1.0 );\n } else {\n vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n return vec4( mix( color0, color1, mipF ), 1.0 );\n }\n }\n#endif",
+ defaultnormal_vertex: "vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n vec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n mat3 bm = mat3( batchingMatrix );\n transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n transformedNormal = bm * transformedNormal;\n #ifdef USE_TANGENT\n transformedTangent = bm * transformedTangent;\n #endif\n#endif\n#ifdef USE_INSTANCING\n mat3 im = mat3( instanceMatrix );\n transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n transformedNormal = im * transformedNormal;\n #ifdef USE_TANGENT\n transformedTangent = im * transformedTangent;\n #endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n transformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n #ifdef FLIP_SIDED\n transformedTangent = - transformedTangent;\n #endif\n#endif",
+ displacementmap_pars_vertex: "#ifdef USE_DISPLACEMENTMAP\n uniform sampler2D displacementMap;\n uniform float displacementScale;\n uniform float displacementBias;\n#endif",
+ displacementmap_vertex: "#ifdef USE_DISPLACEMENTMAP\n transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",
+ emissivemap_fragment: "#ifdef USE_EMISSIVEMAP\n vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n emissiveColor = sRGBTransferEOTF( emissiveColor );\n #endif\n totalEmissiveRadiance *= emissiveColor.rgb;\n#endif",
+ emissivemap_pars_fragment: "#ifdef USE_EMISSIVEMAP\n uniform sampler2D emissiveMap;\n#endif",
+ colorspace_fragment: "gl_FragColor = linearToOutputTexel( gl_FragColor );",
+ colorspace_pars_fragment: "vec4 LinearTransferOETF( in vec4 value ) {\n return value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}",
+ envmap_fragment: "#ifdef USE_ENVMAP\n #ifdef ENV_WORLDPOS\n vec3 cameraToFrag;\n if ( isOrthographic ) {\n cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n } else {\n cameraToFrag = normalize( vWorldPosition - cameraPosition );\n }\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( cameraToFrag, worldNormal );\n #else\n vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n #endif\n #else\n vec3 reflectVec = vReflect;\n #endif\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n #else\n vec4 envColor = vec4( 0.0 );\n #endif\n #ifdef ENVMAP_BLENDING_MULTIPLY\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_MIX )\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_ADD )\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n #endif\n#endif",
+ envmap_common_pars_fragment: "#ifdef USE_ENVMAP\n uniform float envMapIntensity;\n uniform float flipEnvMap;\n uniform mat3 envMapRotation;\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n \n#endif",
+ envmap_pars_fragment: "#ifdef USE_ENVMAP\n uniform float reflectivity;\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n #define ENV_WORLDPOS\n #endif\n #ifdef ENV_WORLDPOS\n varying vec3 vWorldPosition;\n uniform float refractionRatio;\n #else\n varying vec3 vReflect;\n #endif\n#endif",
+ envmap_pars_vertex: "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n #define ENV_WORLDPOS\n #endif\n #ifdef ENV_WORLDPOS\n \n varying vec3 vWorldPosition;\n #else\n varying vec3 vReflect;\n uniform float refractionRatio;\n #endif\n#endif",
+ envmap_physical_pars_fragment: "#ifdef USE_ENVMAP\n vec3 getIBLIrradiance( const in vec3 normal ) {\n #ifdef ENVMAP_TYPE_CUBE_UV\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n return PI * envMapColor.rgb * envMapIntensity;\n #else\n return vec3( 0.0 );\n #endif\n }\n vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n #ifdef ENVMAP_TYPE_CUBE_UV\n vec3 reflectVec = reflect( - viewDir, normal );\n reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n reflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n return envMapColor.rgb * envMapIntensity;\n #else\n return vec3( 0.0 );\n #endif\n }\n #ifdef USE_ANISOTROPY\n vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n #ifdef ENVMAP_TYPE_CUBE_UV\n vec3 bentNormal = cross( bitangent, viewDir );\n bentNormal = normalize( cross( bentNormal, bitangent ) );\n bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n return getIBLRadiance( viewDir, bentNormal, roughness );\n #else\n return vec3( 0.0 );\n #endif\n }\n #endif\n#endif",
+ envmap_vertex: "#ifdef USE_ENVMAP\n #ifdef ENV_WORLDPOS\n vWorldPosition = worldPosition.xyz;\n #else\n vec3 cameraToVertex;\n if ( isOrthographic ) {\n cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n } else {\n cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n }\n vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vReflect = reflect( cameraToVertex, worldNormal );\n #else\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n #endif\n#endif",
+ fog_vertex: "#ifdef USE_FOG\n vFogDepth = - mvPosition.z;\n#endif",
+ fog_pars_vertex: "#ifdef USE_FOG\n varying float vFogDepth;\n#endif",
+ fog_fragment: "#ifdef USE_FOG\n #ifdef FOG_EXP2\n float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n #else\n float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n #endif\n gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",
+ fog_pars_fragment: "#ifdef USE_FOG\n uniform vec3 fogColor;\n varying float vFogDepth;\n #ifdef FOG_EXP2\n uniform float fogDensity;\n #else\n uniform float fogNear;\n uniform float fogFar;\n #endif\n#endif",
+ gradientmap_pars_fragment: "#ifdef USE_GRADIENTMAP\n uniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n float dotNL = dot( normal, lightDirection );\n vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n #ifdef USE_GRADIENTMAP\n return vec3( texture2D( gradientMap, coord ).r );\n #else\n vec2 fw = fwidth( coord ) * 0.5;\n return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n #endif\n}",
+ lightmap_pars_fragment: "#ifdef USE_LIGHTMAP\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n#endif",
+ lights_lambert_fragment: "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",
+ lights_lambert_pars_fragment: "varying vec3 vViewPosition;\nstruct LambertMaterial {\n vec3 diffuseColor;\n float specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_Lambert\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert",
+ lights_pars_begin: "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n uniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n float x = normal.x, y = normal.y, z = normal.z;\n vec3 result = shCoefficients[ 0 ] * 0.886227;\n result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n return result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n return irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n vec3 irradiance = ambientLightColor;\n return irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n if ( cutoffDistance > 0.0 ) {\n distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n }\n return distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n return smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n struct DirectionalLight {\n vec3 direction;\n vec3 color;\n };\n uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n light.color = directionalLight.color;\n light.direction = directionalLight.direction;\n light.visible = true;\n }\n#endif\n#if NUM_POINT_LIGHTS > 0\n struct PointLight {\n vec3 position;\n vec3 color;\n float distance;\n float decay;\n };\n uniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n vec3 lVector = pointLight.position - geometryPosition;\n light.direction = normalize( lVector );\n float lightDistance = length( lVector );\n light.color = pointLight.color;\n light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n light.visible = ( light.color != vec3( 0.0 ) );\n }\n#endif\n#if NUM_SPOT_LIGHTS > 0\n struct SpotLight {\n vec3 position;\n vec3 direction;\n vec3 color;\n float distance;\n float decay;\n float coneCos;\n float penumbraCos;\n };\n uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n vec3 lVector = spotLight.position - geometryPosition;\n light.direction = normalize( lVector );\n float angleCos = dot( light.direction, spotLight.direction );\n float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n if ( spotAttenuation > 0.0 ) {\n float lightDistance = length( lVector );\n light.color = spotLight.color * spotAttenuation;\n light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n light.visible = ( light.color != vec3( 0.0 ) );\n } else {\n light.color = vec3( 0.0 );\n light.visible = false;\n }\n }\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n struct RectAreaLight {\n vec3 color;\n vec3 position;\n vec3 halfWidth;\n vec3 halfHeight;\n };\n uniform sampler2D ltc_1; uniform sampler2D ltc_2;\n uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n struct HemisphereLight {\n vec3 direction;\n vec3 skyColor;\n vec3 groundColor;\n };\n uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n float dotNL = dot( normal, hemiLight.direction );\n float hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n return irradiance;\n }\n#endif",
+ lights_toon_fragment: "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",
+ lights_toon_pars_fragment: "varying vec3 vViewPosition;\nstruct ToonMaterial {\n vec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_Toon\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon",
+ lights_phong_fragment: "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",
+ lights_phong_pars_fragment: "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n vec3 diffuseColor;\n vec3 specularColor;\n float specularShininess;\n float specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_BlinnPhong\n#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong",
+ lights_physical_fragment: "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n material.ior = ior;\n #ifdef USE_SPECULAR\n float specularIntensityFactor = specularIntensity;\n vec3 specularColorFactor = specularColor;\n #ifdef USE_SPECULAR_COLORMAP\n specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n #endif\n #ifdef USE_SPECULAR_INTENSITYMAP\n specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n #endif\n material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n #else\n float specularIntensityFactor = 1.0;\n vec3 specularColorFactor = vec3( 1.0 );\n material.specularF90 = 1.0;\n #endif\n material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n material.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n material.clearcoat = clearcoat;\n material.clearcoatRoughness = clearcoatRoughness;\n material.clearcoatF0 = vec3( 0.04 );\n material.clearcoatF90 = 1.0;\n #ifdef USE_CLEARCOATMAP\n material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n #endif\n #ifdef USE_CLEARCOAT_ROUGHNESSMAP\n material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n #endif\n material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n material.clearcoatRoughness += geometryRoughness;\n material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n material.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n material.iridescence = iridescence;\n material.iridescenceIOR = iridescenceIOR;\n #ifdef USE_IRIDESCENCEMAP\n material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n #endif\n #ifdef USE_IRIDESCENCE_THICKNESSMAP\n material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n #else\n material.iridescenceThickness = iridescenceThicknessMaximum;\n #endif\n#endif\n#ifdef USE_SHEEN\n material.sheenColor = sheenColor;\n #ifdef USE_SHEEN_COLORMAP\n material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n #endif\n material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n #ifdef USE_SHEEN_ROUGHNESSMAP\n material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n #endif\n#endif\n#ifdef USE_ANISOTROPY\n #ifdef USE_ANISOTROPYMAP\n mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n #else\n vec2 anisotropyV = anisotropyVector;\n #endif\n material.anisotropy = length( anisotropyV );\n if( material.anisotropy == 0.0 ) {\n anisotropyV = vec2( 1.0, 0.0 );\n } else {\n anisotropyV /= material.anisotropy;\n material.anisotropy = saturate( material.anisotropy );\n }\n material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif",
+ lights_physical_pars_fragment: "struct PhysicalMaterial {\n vec3 diffuseColor;\n float roughness;\n vec3 specularColor;\n float specularF90;\n float dispersion;\n #ifdef USE_CLEARCOAT\n float clearcoat;\n float clearcoatRoughness;\n vec3 clearcoatF0;\n float clearcoatF90;\n #endif\n #ifdef USE_IRIDESCENCE\n float iridescence;\n float iridescenceIOR;\n float iridescenceThickness;\n vec3 iridescenceFresnel;\n vec3 iridescenceF0;\n #endif\n #ifdef USE_SHEEN\n vec3 sheenColor;\n float sheenRoughness;\n #endif\n #ifdef IOR\n float ior;\n #endif\n #ifdef USE_TRANSMISSION\n float transmission;\n float transmissionAlpha;\n float thickness;\n float attenuationDistance;\n vec3 attenuationColor;\n #endif\n #ifdef USE_ANISOTROPY\n float anisotropy;\n float alphaT;\n vec3 anisotropyT;\n vec3 anisotropyB;\n #endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n float a2 = pow2( alpha );\n float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n return 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n float a2 = pow2( alpha );\n float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n return RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n float v = 0.5 / ( gv + gl );\n return saturate(v);\n }\n float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n float a2 = alphaT * alphaB;\n highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n highp float v2 = dot( v, v );\n float w2 = a2 / v2;\n return RECIPROCAL_PI * a2 * pow2 ( w2 );\n }\n#endif\n#ifdef USE_CLEARCOAT\n vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n vec3 f0 = material.clearcoatF0;\n float f90 = material.clearcoatF90;\n float roughness = material.clearcoatRoughness;\n float alpha = pow2( roughness );\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNL = saturate( dot( normal, lightDir ) );\n float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotVH = saturate( dot( viewDir, halfDir ) );\n vec3 F = F_Schlick( f0, f90, dotVH );\n float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n float D = D_GGX( alpha, dotNH );\n return F * ( V * D );\n }\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n vec3 f0 = material.specularColor;\n float f90 = material.specularF90;\n float roughness = material.roughness;\n float alpha = pow2( roughness );\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNL = saturate( dot( normal, lightDir ) );\n float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotVH = saturate( dot( viewDir, halfDir ) );\n vec3 F = F_Schlick( f0, f90, dotVH );\n #ifdef USE_IRIDESCENCE\n F = mix( F, material.iridescenceFresnel, material.iridescence );\n #endif\n #ifdef USE_ANISOTROPY\n float dotTL = dot( material.anisotropyT, lightDir );\n float dotTV = dot( material.anisotropyT, viewDir );\n float dotTH = dot( material.anisotropyT, halfDir );\n float dotBL = dot( material.anisotropyB, lightDir );\n float dotBV = dot( material.anisotropyB, viewDir );\n float dotBH = dot( material.anisotropyB, halfDir );\n float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n #else\n float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n float D = D_GGX( alpha, dotNH );\n #endif\n return F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n const float LUT_SIZE = 64.0;\n const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n const float LUT_BIAS = 0.5 / LUT_SIZE;\n float dotNV = saturate( dot( N, V ) );\n vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n uv = uv * LUT_SCALE + LUT_BIAS;\n return uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n float l = length( f );\n return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n float x = dot( v1, v2 );\n float y = abs( x );\n float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n float b = 3.4175940 + ( 4.1616724 + y ) * y;\n float v = a / b;\n float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n return cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n vec3 lightNormal = cross( v1, v2 );\n if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n vec3 T1, T2;\n T1 = normalize( V - N * dot( V, N ) );\n T2 = - cross( N, T1 );\n mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n vec3 coords[ 4 ];\n coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n coords[ 0 ] = normalize( coords[ 0 ] );\n coords[ 1 ] = normalize( coords[ 1 ] );\n coords[ 2 ] = normalize( coords[ 2 ] );\n coords[ 3 ] = normalize( coords[ 3 ] );\n vec3 vectorFormFactor = vec3( 0.0 );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n float result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n return vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n float alpha = pow2( roughness );\n float invAlpha = 1.0 / alpha;\n float cos2h = dotNH * dotNH;\n float sin2h = max( 1.0 - cos2h, 0.0078125 );\n return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNL = saturate( dot( normal, lightDir ) );\n float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float D = D_Charlie( sheenRoughness, dotNH );\n float V = V_Neubelt( dotNV, dotNL );\n return sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n float dotNV = saturate( dot( normal, viewDir ) );\n float r2 = roughness * roughness;\n float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n return saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n float dotNV = saturate( dot( normal, viewDir ) );\n const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n return fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n vec2 fab = DFGApprox( normal, viewDir, roughness );\n return specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n vec2 fab = DFGApprox( normal, viewDir, roughness );\n #ifdef USE_IRIDESCENCE\n vec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n #else\n vec3 Fr = specularColor;\n #endif\n vec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n float Ess = fab.x + fab.y;\n float Ems = 1.0 - Ess;\n vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n singleScatter += FssEss;\n multiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 normal = geometryNormal;\n vec3 viewDir = geometryViewDir;\n vec3 position = geometryPosition;\n vec3 lightPos = rectAreaLight.position;\n vec3 halfWidth = rectAreaLight.halfWidth;\n vec3 halfHeight = rectAreaLight.halfHeight;\n vec3 lightColor = rectAreaLight.color;\n float roughness = material.roughness;\n vec3 rectCoords[ 4 ];\n rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n vec2 uv = LTC_Uv( normal, viewDir, roughness );\n vec4 t1 = texture2D( ltc_1, uv );\n vec4 t2 = texture2D( ltc_2, uv );\n mat3 mInv = mat3(\n vec3( t1.x, 0, t1.y ),\n vec3( 0, 1, 0 ),\n vec3( t1.z, 0, t1.w )\n );\n vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n }\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n #ifdef USE_CLEARCOAT\n float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n vec3 ccIrradiance = dotNLcc * directLight.color;\n clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n #endif\n #ifdef USE_SHEEN\n sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n #endif\n reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n #ifdef USE_CLEARCOAT\n clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n #endif\n #ifdef USE_SHEEN\n sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n #endif\n vec3 singleScattering = vec3( 0.0 );\n vec3 multiScattering = vec3( 0.0 );\n vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n #ifdef USE_IRIDESCENCE\n computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n #else\n computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n #endif\n vec3 totalScattering = singleScattering + multiScattering;\n vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n reflectedLight.indirectSpecular += radiance * singleScattering;\n reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct RE_Direct_Physical\n#define RE_Direct_RectArea RE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular RE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",
+ lights_fragment_begin: "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n geometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n float dotNVi = saturate( dot( normal, geometryViewDir ) );\n if ( material.iridescenceThickness == 0.0 ) {\n material.iridescence = 0.0;\n } else {\n material.iridescence = saturate( material.iridescence );\n }\n if ( material.iridescence > 0.0 ) {\n material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n }\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n PointLight pointLight;\n #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n PointLightShadow pointLightShadow;\n #endif\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n pointLight = pointLights[ i ];\n getPointLightInfo( pointLight, geometryPosition, directLight );\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n pointLightShadow = pointLightShadows[ i ];\n directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n #endif\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n SpotLight spotLight;\n vec4 spotColor;\n vec3 spotLightCoord;\n bool inSpotLightMap;\n #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n SpotLightShadow spotLightShadow;\n #endif\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n spotLight = spotLights[ i ];\n getSpotLightInfo( spotLight, geometryPosition, directLight );\n #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n #else\n #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n #endif\n #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n #endif\n #undef SPOT_LIGHT_MAP_INDEX\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n spotLightShadow = spotLightShadows[ i ];\n directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n DirectionalLight directionalLight;\n #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow directionalLightShadow;\n #endif\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n directionalLight = directionalLights[ i ];\n getDirectionalLightInfo( directionalLight, directLight );\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n directionalLightShadow = directionalLightShadows[ i ];\n directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n RectAreaLight rectAreaLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n rectAreaLight = rectAreaLights[ i ];\n RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n vec3 iblIrradiance = vec3( 0.0 );\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n #if defined( USE_LIGHT_PROBES )\n irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n #endif\n #if ( NUM_HEMI_LIGHTS > 0 )\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n }\n #pragma unroll_loop_end\n #endif\n#endif\n#if defined( RE_IndirectSpecular )\n vec3 radiance = vec3( 0.0 );\n vec3 clearcoatRadiance = vec3( 0.0 );\n#endif",
+ lights_fragment_maps: "#if defined( RE_IndirectDiffuse )\n #ifdef USE_LIGHTMAP\n vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n irradiance += lightMapIrradiance;\n #endif\n #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n iblIrradiance += getIBLIrradiance( geometryNormal );\n #endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n #ifdef USE_ANISOTROPY\n radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n #else\n radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n #endif\n #ifdef USE_CLEARCOAT\n clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n #endif\n#endif",
+ lights_fragment_end: "#if defined( RE_IndirectDiffuse )\n RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",
+ logdepthbuf_fragment: "#if defined( USE_LOGDEPTHBUF )\n gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",
+ logdepthbuf_pars_fragment: "#if defined( USE_LOGDEPTHBUF )\n uniform float logDepthBufFC;\n varying float vFragDepth;\n varying float vIsPerspective;\n#endif",
+ logdepthbuf_pars_vertex: "#ifdef USE_LOGDEPTHBUF\n varying float vFragDepth;\n varying float vIsPerspective;\n#endif",
+ logdepthbuf_vertex: "#ifdef USE_LOGDEPTHBUF\n vFragDepth = 1.0 + gl_Position.w;\n vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif",
+ map_fragment: "#ifdef USE_MAP\n vec4 sampledDiffuseColor = texture2D( map, vMapUv );\n #ifdef DECODE_VIDEO_TEXTURE\n sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n #endif\n diffuseColor *= sampledDiffuseColor;\n#endif",
+ map_pars_fragment: "#ifdef USE_MAP\n uniform sampler2D map;\n#endif",
+ map_particle_fragment: "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n #if defined( USE_POINTS_UV )\n vec2 uv = vUv;\n #else\n vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n #endif\n#endif\n#ifdef USE_MAP\n diffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",
+ map_particle_pars_fragment: "#if defined( USE_POINTS_UV )\n varying vec2 vUv;\n#else\n #if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n uniform mat3 uvTransform;\n #endif\n#endif\n#ifdef USE_MAP\n uniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif",
+ metalnessmap_fragment: "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n metalnessFactor *= texelMetalness.b;\n#endif",
+ metalnessmap_pars_fragment: "#ifdef USE_METALNESSMAP\n uniform sampler2D metalnessMap;\n#endif",
+ morphinstance_vertex: "#ifdef USE_INSTANCING_MORPH\n float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n }\n#endif",
+ morphcolor_vertex: "#if defined( USE_MORPHCOLORS )\n vColor *= morphTargetBaseInfluence;\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n #if defined( USE_COLOR_ALPHA )\n if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n #elif defined( USE_COLOR )\n if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n #endif\n }\n#endif",
+ morphnormal_vertex: "#ifdef USE_MORPHNORMALS\n objectNormal *= morphTargetBaseInfluence;\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n }\n#endif",
+ morphtarget_pars_vertex: "#ifdef USE_MORPHTARGETS\n #ifndef USE_INSTANCING_MORPH\n uniform float morphTargetBaseInfluence;\n uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n #endif\n uniform sampler2DArray morphTargetsTexture;\n uniform ivec2 morphTargetsTextureSize;\n vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n int y = texelIndex / morphTargetsTextureSize.x;\n int x = texelIndex - y * morphTargetsTextureSize.x;\n ivec3 morphUV = ivec3( x, y, morphTargetIndex );\n return texelFetch( morphTargetsTexture, morphUV, 0 );\n }\n#endif",
+ morphtarget_vertex: "#ifdef USE_MORPHTARGETS\n transformed *= morphTargetBaseInfluence;\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n }\n#endif",
+ normal_fragment_begin: "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n#else\n vec3 normal = normalize( vNormal );\n #ifdef DOUBLE_SIDED\n normal *= faceDirection;\n #endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n #ifdef USE_TANGENT\n mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n #else\n mat3 tbn = getTangentFrame( - vViewPosition, normal,\n #if defined( USE_NORMALMAP )\n vNormalMapUv\n #elif defined( USE_CLEARCOAT_NORMALMAP )\n vClearcoatNormalMapUv\n #else\n vUv\n #endif\n );\n #endif\n #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n tbn[0] *= faceDirection;\n tbn[1] *= faceDirection;\n #endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n #ifdef USE_TANGENT\n mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n #else\n mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n #endif\n #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n tbn2[0] *= faceDirection;\n tbn2[1] *= faceDirection;\n #endif\n#endif\nvec3 nonPerturbedNormal = normal;",
+ normal_fragment_maps: "#ifdef USE_NORMALMAP_OBJECTSPACE\n normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n #ifdef FLIP_SIDED\n normal = - normal;\n #endif\n #ifdef DOUBLE_SIDED\n normal = normal * faceDirection;\n #endif\n normal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n mapN.xy *= normalScale;\n normal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",
+ normal_pars_fragment: "#ifndef FLAT_SHADED\n varying vec3 vNormal;\n #ifdef USE_TANGENT\n varying vec3 vTangent;\n varying vec3 vBitangent;\n #endif\n#endif",
+ normal_pars_vertex: "#ifndef FLAT_SHADED\n varying vec3 vNormal;\n #ifdef USE_TANGENT\n varying vec3 vTangent;\n varying vec3 vBitangent;\n #endif\n#endif",
+ normal_vertex: "#ifndef FLAT_SHADED\n vNormal = normalize( transformedNormal );\n #ifdef USE_TANGENT\n vTangent = normalize( transformedTangent );\n vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n #endif\n#endif",
+ normalmap_pars_fragment: "#ifdef USE_NORMALMAP\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n uniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n vec3 N = surf_norm;\n vec3 q1perp = cross( q1, N );\n vec3 q0perp = cross( N, q0 );\n vec3 T = q1perp * st0.x + q0perp * st1.x;\n vec3 B = q1perp * st0.y + q0perp * st1.y;\n float det = max( dot( T, T ), dot( B, B ) );\n float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n return mat3( T * scale, B * scale, N );\n }\n#endif",
+ clearcoat_normal_fragment_begin: "#ifdef USE_CLEARCOAT\n vec3 clearcoatNormal = nonPerturbedNormal;\n#endif",
+ clearcoat_normal_fragment_maps: "#ifdef USE_CLEARCOAT_NORMALMAP\n vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n clearcoatMapN.xy *= clearcoatNormalScale;\n clearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",
+ clearcoat_pars_fragment: "#ifdef USE_CLEARCOATMAP\n uniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n uniform sampler2D clearcoatNormalMap;\n uniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n uniform sampler2D clearcoatRoughnessMap;\n#endif",
+ iridescence_pars_fragment: "#ifdef USE_IRIDESCENCEMAP\n uniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n uniform sampler2D iridescenceThicknessMap;\n#endif",
+ opaque_fragment: "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",
+ packing: "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n if( v <= 0.0 )\n return vec4( 0., 0., 0., 0. );\n if( v >= 1.0 )\n return vec4( 1., 1., 1., 1. );\n float vuf;\n float af = modf( v * PackFactors.a, vuf );\n float bf = modf( vuf * ShiftRight8, vuf );\n float gf = modf( vuf * ShiftRight8, vuf );\n return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n if( v <= 0.0 )\n return vec3( 0., 0., 0. );\n if( v >= 1.0 )\n return vec3( 1., 1., 1. );\n float vuf;\n float bf = modf( v * PackFactors.b, vuf );\n float gf = modf( vuf * ShiftRight8, vuf );\n return vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n if( v <= 0.0 )\n return vec2( 0., 0. );\n if( v >= 1.0 )\n return vec2( 1., 1. );\n float vuf;\n float gf = modf( v * 256., vuf );\n return vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n return dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n return dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n return depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * depth - far );\n}",
+ premultiplied_alpha_fragment: "#ifdef PREMULTIPLIED_ALPHA\n gl_FragColor.rgb *= gl_FragColor.a;\n#endif",
+ project_vertex: "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n mvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n mvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",
+ dithering_fragment: "#ifdef DITHERING\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",
+ dithering_pars_fragment: "#ifdef DITHERING\n vec3 dithering( vec3 color ) {\n float grid_position = rand( gl_FragCoord.xy );\n vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n return color + dither_shift_RGB;\n }\n#endif",
+ roughnessmap_fragment: "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n roughnessFactor *= texelRoughness.g;\n#endif",
+ roughnessmap_pars_fragment: "#ifdef USE_ROUGHNESSMAP\n uniform sampler2D roughnessMap;\n#endif",
+ shadowmap_pars_fragment: "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHT_SHADOWS > 0\n uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n struct DirectionalLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n #endif\n #if NUM_SPOT_LIGHT_SHADOWS > 0\n uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n struct SpotLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n struct PointLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n float shadowCameraNear;\n float shadowCameraFar;\n };\n uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n #endif\n float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n }\n vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n return unpackRGBATo2Half( texture2D( shadow, uv ) );\n }\n float VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n float occlusion = 1.0;\n vec2 distribution = texture2DDistribution( shadow, uv );\n float hard_shadow = step( compare , distribution.x );\n if (hard_shadow != 1.0 ) {\n float distance = compare - distribution.x ;\n float variance = max( 0.00000, distribution.y * distribution.y );\n float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n }\n return occlusion;\n }\n float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n float shadow = 1.0;\n shadowCoord.xyz /= shadowCoord.w;\n shadowCoord.z += shadowBias;\n bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n bool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n if ( frustumTest ) {\n #if defined( SHADOWMAP_TYPE_PCF )\n vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n float dx0 = - texelSize.x * shadowRadius;\n float dy0 = - texelSize.y * shadowRadius;\n float dx1 = + texelSize.x * shadowRadius;\n float dy1 = + texelSize.y * shadowRadius;\n float dx2 = dx0 / 2.0;\n float dy2 = dy0 / 2.0;\n float dx3 = dx1 / 2.0;\n float dy3 = dy1 / 2.0;\n shadow = (\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n ) * ( 1.0 / 17.0 );\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n float dx = texelSize.x;\n float dy = texelSize.y;\n vec2 uv = shadowCoord.xy;\n vec2 f = fract( uv * shadowMapSize + 0.5 );\n uv -= f * texelSize;\n shadow = (\n texture2DCompare( shadowMap, uv, shadowCoord.z ) +\n texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n f.x ) +\n mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n f.x ) +\n mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n f.y ) +\n mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n f.y ) +\n mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n f.x ),\n mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n f.x ),\n f.y )\n ) * ( 1.0 / 9.0 );\n #elif defined( SHADOWMAP_TYPE_VSM )\n shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n #else\n shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n #endif\n }\n return mix( 1.0, shadow, shadowIntensity );\n }\n vec2 cubeToUV( vec3 v, float texelSizeY ) {\n vec3 absV = abs( v );\n float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n absV *= scaleToCube;\n v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n vec2 planar = v.xy;\n float almostATexel = 1.5 * texelSizeY;\n float almostOne = 1.0 - almostATexel;\n if ( absV.z >= almostOne ) {\n if ( v.z > 0.0 )\n planar.x = 4.0 - v.x;\n } else if ( absV.x >= almostOne ) {\n float signX = sign( v.x );\n planar.x = v.z * signX + 2.0 * signX;\n } else if ( absV.y >= almostOne ) {\n float signY = sign( v.y );\n planar.x = v.x + 2.0 * signY + 2.0;\n planar.y = v.z * signY - 2.0;\n }\n return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n }\n float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n float shadow = 1.0;\n vec3 lightToPosition = shadowCoord.xyz;\n \n float lightToPositionLength = length( lightToPosition );\n if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias;\n vec3 bd3D = normalize( lightToPosition );\n vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n shadow = (\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n ) * ( 1.0 / 9.0 );\n #else\n shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n #endif\n }\n return mix( 1.0, shadow, shadowIntensity );\n }\n#endif",
+ shadowmap_pars_vertex: "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHT_SHADOWS > 0\n uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n struct DirectionalLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n #endif\n #if NUM_SPOT_LIGHT_SHADOWS > 0\n struct SpotLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n struct PointLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n float shadowCameraNear;\n float shadowCameraFar;\n };\n uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n #endif\n#endif",
+ shadowmap_vertex: "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n vec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n #if NUM_DIR_LIGHT_SHADOWS > 0\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n }\n #pragma unroll_loop_end\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n }\n #pragma unroll_loop_end\n #endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n shadowWorldPosition = worldPosition;\n #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n #endif\n vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n }\n #pragma unroll_loop_end\n#endif",
+ shadowmask_pars_fragment: "float getShadowMask() {\n float shadow = 1.0;\n #ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow directionalLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n directionalLight = directionalLightShadows[ i ];\n shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n }\n #pragma unroll_loop_end\n #endif\n #if NUM_SPOT_LIGHT_SHADOWS > 0\n SpotLightShadow spotLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n spotLight = spotLightShadows[ i ];\n shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n }\n #pragma unroll_loop_end\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n PointLightShadow pointLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n pointLight = pointLightShadows[ i ];\n shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n }\n #pragma unroll_loop_end\n #endif\n #endif\n return shadow;\n}",
+ skinbase_vertex: "#ifdef USE_SKINNING\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",
+ skinning_pars_vertex: "#ifdef USE_SKINNING\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n uniform highp sampler2D boneTexture;\n mat4 getBoneMatrix( const in float i ) {\n int size = textureSize( boneTexture, 0 ).x;\n int j = int( i ) * 4;\n int x = j % size;\n int y = j / size;\n vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n return mat4( v1, v2, v3, v4 );\n }\n#endif",
+ skinning_vertex: "#ifdef USE_SKINNING\n vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n transformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",
+ skinnormal_vertex: "#ifdef USE_SKINNING\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n #ifdef USE_TANGENT\n objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n #endif\n#endif",
+ specularmap_fragment: "float specularStrength;\n#ifdef USE_SPECULARMAP\n vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n specularStrength = texelSpecular.r;\n#else\n specularStrength = 1.0;\n#endif",
+ specularmap_pars_fragment: "#ifdef USE_SPECULARMAP\n uniform sampler2D specularMap;\n#endif",
+ tonemapping_fragment: "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",
+ tonemapping_pars_fragment: "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n return saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n vec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n return a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n const mat3 ACESInputMat = mat3(\n vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),\n vec3( 0.04823, 0.01566, 0.83777 )\n );\n const mat3 ACESOutputMat = mat3(\n vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),\n vec3( -0.07367, -0.00605, 1.07602 )\n );\n color *= toneMappingExposure / 0.6;\n color = ACESInputMat * color;\n color = RRTAndODTFit( color );\n color = ACESOutputMat * color;\n return saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n vec3( 1.6605, - 0.1246, - 0.0182 ),\n vec3( - 0.5876, 1.1329, - 0.1006 ),\n vec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n vec3( 0.6274, 0.0691, 0.0164 ),\n vec3( 0.3293, 0.9195, 0.0880 ),\n vec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n vec3 x2 = x * x;\n vec3 x4 = x2 * x2;\n return + 15.5 * x4 * x2\n - 40.14 * x4 * x\n + 31.96 * x4\n - 6.868 * x2 * x\n + 0.4298 * x2\n + 0.1191 * x\n - 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n const mat3 AgXInsetMatrix = mat3(\n vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n );\n const mat3 AgXOutsetMatrix = mat3(\n vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n );\n const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069;\n color *= toneMappingExposure;\n color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n color = AgXInsetMatrix * color;\n color = max( color, 1e-10 ); color = log2( color );\n color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n color = clamp( color, 0.0, 1.0 );\n color = agxDefaultContrastApprox( color );\n color = AgXOutsetMatrix * color;\n color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n color = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n color = clamp( color, 0.0, 1.0 );\n return color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n const float StartCompression = 0.8 - 0.04;\n const float Desaturation = 0.15;\n color *= toneMappingExposure;\n float x = min( color.r, min( color.g, color.b ) );\n float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n color -= offset;\n float peak = max( color.r, max( color.g, color.b ) );\n if ( peak < StartCompression ) return color;\n float d = 1. - StartCompression;\n float newPeak = 1. - d * d / ( peak + d - StartCompression );\n color *= newPeak / peak;\n float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n return mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",
+ transmission_fragment: "#ifdef USE_TRANSMISSION\n material.transmission = transmission;\n material.transmissionAlpha = 1.0;\n material.thickness = thickness;\n material.attenuationDistance = attenuationDistance;\n material.attenuationColor = attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n #endif\n #ifdef USE_THICKNESSMAP\n material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n #endif\n vec3 pos = vWorldPosition;\n vec3 v = normalize( cameraPosition - pos );\n vec3 n = inverseTransformDirection( normal, viewMatrix );\n vec4 transmitted = getIBLVolumeRefraction(\n n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n material.attenuationColor, material.attenuationDistance );\n material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",
+ transmission_pars_fragment: "#ifdef USE_TRANSMISSION\n uniform float transmission;\n uniform float thickness;\n uniform float attenuationDistance;\n uniform vec3 attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n uniform sampler2D transmissionMap;\n #endif\n #ifdef USE_THICKNESSMAP\n uniform sampler2D thicknessMap;\n #endif\n uniform vec2 transmissionSamplerSize;\n uniform sampler2D transmissionSamplerMap;\n uniform mat4 modelMatrix;\n uniform mat4 projectionMatrix;\n varying vec3 vWorldPosition;\n float w0( float a ) {\n return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n }\n float w1( float a ) {\n return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n }\n float w2( float a ){\n return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n }\n float w3( float a ) {\n return ( 1.0 / 6.0 ) * ( a * a * a );\n }\n float g0( float a ) {\n return w0( a ) + w1( a );\n }\n float g1( float a ) {\n return w2( a ) + w3( a );\n }\n float h0( float a ) {\n return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n }\n float h1( float a ) {\n return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n }\n vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n uv = uv * texelSize.zw + 0.5;\n vec2 iuv = floor( uv );\n vec2 fuv = fract( uv );\n float g0x = g0( fuv.x );\n float g1x = g1( fuv.x );\n float h0x = h0( fuv.x );\n float h1x = h1( fuv.x );\n float h0y = h0( fuv.y );\n float h1y = h1( fuv.y );\n vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n }\n vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n vec2 fLodSizeInv = 1.0 / fLodSize;\n vec2 cLodSizeInv = 1.0 / cLodSize;\n vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n return mix( fSample, cSample, fract( lod ) );\n }\n vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n vec3 modelScale;\n modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n return normalize( refractionVector ) * thickness * modelScale;\n }\n float applyIorToRoughness( const in float roughness, const in float ior ) {\n return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n }\n vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n }\n vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n if ( isinf( attenuationDistance ) ) {\n return vec3( 1.0 );\n } else {\n vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;\n }\n }\n vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n const in vec3 attenuationColor, const in float attenuationDistance ) {\n vec4 transmittedLight;\n vec3 transmittance;\n #ifdef USE_DISPERSION\n float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n for ( int i = 0; i < 3; i ++ ) {\n vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n vec3 refractedRayExit = position + transmissionRay;\n vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n vec2 refractionCoords = ndcPos.xy / ndcPos.w;\n refractionCoords += 1.0;\n refractionCoords /= 2.0;\n vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n transmittedLight[ i ] = transmissionSample[ i ];\n transmittedLight.a += transmissionSample.a;\n transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n }\n transmittedLight.a /= 3.0;\n #else\n vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n vec3 refractedRayExit = position + transmissionRay;\n vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n vec2 refractionCoords = ndcPos.xy / ndcPos.w;\n refractionCoords += 1.0;\n refractionCoords /= 2.0;\n transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n #endif\n vec3 attenuatedColor = transmittance * transmittedLight.rgb;\n vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n }\n#endif",
+ uv_pars_fragment: "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n varying vec2 vUv;\n#endif\n#ifdef USE_MAP\n varying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n varying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n varying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n varying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n varying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n varying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n varying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n varying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n varying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n varying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n varying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n varying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n varying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n varying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n varying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n varying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n varying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n varying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n varying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n varying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n uniform mat3 transmissionMapTransform;\n varying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n uniform mat3 thicknessMapTransform;\n varying vec2 vThicknessMapUv;\n#endif",
+ uv_pars_vertex: "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n varying vec2 vUv;\n#endif\n#ifdef USE_MAP\n uniform mat3 mapTransform;\n varying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n uniform mat3 alphaMapTransform;\n varying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n uniform mat3 lightMapTransform;\n varying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n uniform mat3 aoMapTransform;\n varying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n uniform mat3 bumpMapTransform;\n varying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n uniform mat3 normalMapTransform;\n varying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n uniform mat3 displacementMapTransform;\n varying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n uniform mat3 emissiveMapTransform;\n varying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n uniform mat3 metalnessMapTransform;\n varying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n uniform mat3 roughnessMapTransform;\n varying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n uniform mat3 anisotropyMapTransform;\n varying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n uniform mat3 clearcoatMapTransform;\n varying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n uniform mat3 clearcoatNormalMapTransform;\n varying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n uniform mat3 clearcoatRoughnessMapTransform;\n varying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n uniform mat3 sheenColorMapTransform;\n varying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n uniform mat3 sheenRoughnessMapTransform;\n varying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n uniform mat3 iridescenceMapTransform;\n varying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n uniform mat3 iridescenceThicknessMapTransform;\n varying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n uniform mat3 specularMapTransform;\n varying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n uniform mat3 specularColorMapTransform;\n varying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n uniform mat3 specularIntensityMapTransform;\n varying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n uniform mat3 transmissionMapTransform;\n varying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n uniform mat3 thicknessMapTransform;\n varying vec2 vThicknessMapUv;\n#endif",
+ uv_vertex: "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n vUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",
+ worldpos_vertex: "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n vec4 worldPosition = vec4( transformed, 1.0 );\n #ifdef USE_BATCHING\n worldPosition = batchingMatrix * worldPosition;\n #endif\n #ifdef USE_INSTANCING\n worldPosition = instanceMatrix * worldPosition;\n #endif\n worldPosition = modelMatrix * worldPosition;\n#endif",
+ background_vert: "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n vUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n gl_Position = vec4( position.xy, 1.0, 1.0 );\n}",
+ background_frag: "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n vec4 texColor = texture2D( t2D, vUv );\n #ifdef DECODE_VIDEO_TEXTURE\n texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n #endif\n texColor.rgb *= backgroundIntensity;\n gl_FragColor = texColor;\n #include <tonemapping_fragment>\n #include <colorspace_fragment>\n}",
+ backgroundCube_vert: "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n vWorldDirection = transformDirection( position, modelMatrix );\n #include <begin_vertex>\n #include <project_vertex>\n gl_Position.z = gl_Position.w;\n}",
+ backgroundCube_frag: "#ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n uniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n #ifdef ENVMAP_TYPE_CUBE\n vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n #elif defined( ENVMAP_TYPE_CUBE_UV )\n vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n #else\n vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n #endif\n texColor.rgb *= backgroundIntensity;\n gl_FragColor = texColor;\n #include <tonemapping_fragment>\n #include <colorspace_fragment>\n}",
+ cube_vert: "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n vWorldDirection = transformDirection( position, modelMatrix );\n #include <begin_vertex>\n #include <project_vertex>\n gl_Position.z = gl_Position.w;\n}",
+ cube_frag: "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n gl_FragColor = texColor;\n gl_FragColor.a *= opacity;\n #include <tonemapping_fragment>\n #include <colorspace_fragment>\n}",
+ depth_vert: "#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n #include <uv_vertex>\n #include <batching_vertex>\n #include <skinbase_vertex>\n #include <morphinstance_vertex>\n #ifdef USE_DISPLACEMENTMAP\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinnormal_vertex>\n #endif\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <displacementmap_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n vHighPrecisionZW = gl_Position.zw;\n}",
+ depth_frag: "#if DEPTH_PACKING == 3200\n uniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n vec4 diffuseColor = vec4( 1.0 );\n #include <clipping_planes_fragment>\n #if DEPTH_PACKING == 3200\n diffuseColor.a = opacity;\n #endif\n #include <map_fragment>\n #include <alphamap_fragment>\n #include <alphatest_fragment>\n #include <alphahash_fragment>\n #include <logdepthbuf_fragment>\n float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n #if DEPTH_PACKING == 3200\n gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n #elif DEPTH_PACKING == 3201\n gl_FragColor = packDepthToRGBA( fragCoordZ );\n #elif DEPTH_PACKING == 3202\n gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n #elif DEPTH_PACKING == 3203\n gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n #endif\n}",
+ distanceRGBA_vert: "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <uv_vertex>\n #include <batching_vertex>\n #include <skinbase_vertex>\n #include <morphinstance_vertex>\n #ifdef USE_DISPLACEMENTMAP\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinnormal_vertex>\n #endif\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <displacementmap_vertex>\n #include <project_vertex>\n #include <worldpos_vertex>\n #include <clipping_planes_vertex>\n vWorldPosition = worldPosition.xyz;\n}",
+ distanceRGBA_frag: "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n vec4 diffuseColor = vec4( 1.0 );\n #include <clipping_planes_fragment>\n #include <map_fragment>\n #include <alphamap_fragment>\n #include <alphatest_fragment>\n #include <alphahash_fragment>\n float dist = length( vWorldPosition - referencePosition );\n dist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n dist = saturate( dist );\n gl_FragColor = packDepthToRGBA( dist );\n}",
+ equirect_vert: "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n vWorldDirection = transformDirection( position, modelMatrix );\n #include <begin_vertex>\n #include <project_vertex>\n}",
+ equirect_frag: "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n vec3 direction = normalize( vWorldDirection );\n vec2 sampleUV = equirectUv( direction );\n gl_FragColor = texture2D( tEquirect, sampleUV );\n #include <tonemapping_fragment>\n #include <colorspace_fragment>\n}",
+ linedashed_vert: "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n vLineDistance = scale * lineDistance;\n #include <uv_vertex>\n #include <color_vertex>\n #include <morphinstance_vertex>\n #include <morphcolor_vertex>\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n #include <fog_vertex>\n}",
+ linedashed_frag: "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include <clipping_planes_fragment>\n if ( mod( vLineDistance, totalSize ) > dashSize ) {\n discard;\n }\n vec3 outgoingLight = vec3( 0.0 );\n #include <logdepthbuf_fragment>\n #include <map_fragment>\n #include <color_fragment>\n outgoingLight = diffuseColor.rgb;\n #include <opaque_fragment>\n #include <tonemapping_fragment>\n #include <colorspace_fragment>\n #include <fog_fragment>\n #include <premultiplied_alpha_fragment>\n}",
+ meshbasic_vert: "#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <uv_vertex>\n #include <color_vertex>\n #include <morphinstance_vertex>\n #include <morphcolor_vertex>\n #include <batching_vertex>\n #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n #include <defaultnormal_vertex>\n #endif\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n #include <worldpos_vertex>\n #include <envmap_vertex>\n #include <fog_vertex>\n}",
+ meshbasic_frag: "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include <clipping_planes_fragment>\n #include <logdepthbuf_fragment>\n #include <map_fragment>\n #include <color_fragment>\n #include <alphamap_fragment>\n #include <alphatest_fragment>\n #include <alphahash_fragment>\n #include <specularmap_fragment>\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n #ifdef USE_LIGHTMAP\n vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n #else\n reflectedLight.indirectDiffuse += vec3( 1.0 );\n #endif\n #include <aomap_fragment>\n reflectedLight.indirectDiffuse *= diffuseColor.rgb;\n vec3 outgoingLight = reflectedLight.indirectDiffuse;\n #include <envmap_fragment>\n #include <opaque_fragment>\n #include <tonemapping_fragment>\n #include <colorspace_fragment>\n #include <fog_fragment>\n #include <premultiplied_alpha_fragment>\n #include <dithering_fragment>\n}",
+ meshlambert_vert: "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <uv_vertex>\n #include <color_vertex>\n #include <morphinstance_vertex>\n #include <morphcolor_vertex>\n #include <batching_vertex>\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n #include <defaultnormal_vertex>\n #include <normal_vertex>\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <displacementmap_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n vViewPosition = - mvPosition.xyz;\n #include <worldpos_vertex>\n #include <envmap_vertex>\n #include <shadowmap_vertex>\n #include <fog_vertex>\n}",
+ meshlambert_frag: "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include <clipping_planes_fragment>\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include <logdepthbuf_fragment>\n #include <map_fragment>\n #include <color_fragment>\n #include <alphamap_fragment>\n #include <alphatest_fragment>\n #include <alphahash_fragment>\n #include <specularmap_fragment>\n #include <normal_fragment_begin>\n #include <normal_fragment_maps>\n #include <emissivemap_fragment>\n #include <lights_lambert_fragment>\n #include <lights_fragment_begin>\n #include <lights_fragment_maps>\n #include <lights_fragment_end>\n #include <aomap_fragment>\n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n #include <envmap_fragment>\n #include <opaque_fragment>\n #include <tonemapping_fragment>\n #include <colorspace_fragment>\n #include <fog_fragment>\n #include <premultiplied_alpha_fragment>\n #include <dithering_fragment>\n}",
+ meshmatcap_vert: "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <uv_vertex>\n #include <color_vertex>\n #include <morphinstance_vertex>\n #include <morphcolor_vertex>\n #include <batching_vertex>\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n #include <defaultnormal_vertex>\n #include <normal_vertex>\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <displacementmap_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n #include <fog_vertex>\n vViewPosition = - mvPosition.xyz;\n}",
+ meshmatcap_frag: "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include <clipping_planes_fragment>\n #include <logdepthbuf_fragment>\n #include <map_fragment>\n #include <color_fragment>\n #include <alphamap_fragment>\n #include <alphatest_fragment>\n #include <alphahash_fragment>\n #include <normal_fragment_begin>\n #include <normal_fragment_maps>\n vec3 viewDir = normalize( vViewPosition );\n vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n vec3 y = cross( viewDir, x );\n vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n #ifdef USE_MATCAP\n vec4 matcapColor = texture2D( matcap, uv );\n #else\n vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n #endif\n vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n #include <opaque_fragment>\n #include <tonemapping_fragment>\n #include <colorspace_fragment>\n #include <fog_fragment>\n #include <premultiplied_alpha_fragment>\n #include <dithering_fragment>\n}",
+ meshnormal_vert: "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n varying vec3 vViewPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <uv_vertex>\n #include <batching_vertex>\n #include <beginnormal_vertex>\n #include <morphinstance_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n #include <defaultnormal_vertex>\n #include <normal_vertex>\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <displacementmap_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n vViewPosition = - mvPosition.xyz;\n#endif\n}",
+ meshnormal_frag: "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n varying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n #include <clipping_planes_fragment>\n #include <logdepthbuf_fragment>\n #include <normal_fragment_begin>\n #include <normal_fragment_maps>\n gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );\n #ifdef OPAQUE\n gl_FragColor.a = 1.0;\n #endif\n}",
+ meshphong_vert: "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <uv_vertex>\n #include <color_vertex>\n #include <morphcolor_vertex>\n #include <batching_vertex>\n #include <beginnormal_vertex>\n #include <morphinstance_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n #include <defaultnormal_vertex>\n #include <normal_vertex>\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <displacementmap_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n vViewPosition = - mvPosition.xyz;\n #include <worldpos_vertex>\n #include <envmap_vertex>\n #include <shadowmap_vertex>\n #include <fog_vertex>\n}",
+ meshphong_frag: "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include <clipping_planes_fragment>\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include <logdepthbuf_fragment>\n #include <map_fragment>\n #include <color_fragment>\n #include <alphamap_fragment>\n #include <alphatest_fragment>\n #include <alphahash_fragment>\n #include <specularmap_fragment>\n #include <normal_fragment_begin>\n #include <normal_fragment_maps>\n #include <emissivemap_fragment>\n #include <lights_phong_fragment>\n #include <lights_fragment_begin>\n #include <lights_fragment_maps>\n #include <lights_fragment_end>\n #include <aomap_fragment>\n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n #include <envmap_fragment>\n #include <opaque_fragment>\n #include <tonemapping_fragment>\n #include <colorspace_fragment>\n #include <fog_fragment>\n #include <premultiplied_alpha_fragment>\n #include <dithering_fragment>\n}",
+ meshphysical_vert: "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n varying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <uv_vertex>\n #include <color_vertex>\n #include <morphinstance_vertex>\n #include <morphcolor_vertex>\n #include <batching_vertex>\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n #include <defaultnormal_vertex>\n #include <normal_vertex>\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <displacementmap_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n vViewPosition = - mvPosition.xyz;\n #include <worldpos_vertex>\n #include <shadowmap_vertex>\n #include <fog_vertex>\n#ifdef USE_TRANSMISSION\n vWorldPosition = worldPosition.xyz;\n#endif\n}",
+ meshphysical_frag: "#define STANDARD\n#ifdef PHYSICAL\n #define IOR\n #define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n uniform float ior;\n#endif\n#ifdef USE_SPECULAR\n uniform float specularIntensity;\n uniform vec3 specularColor;\n #ifdef USE_SPECULAR_COLORMAP\n uniform sampler2D specularColorMap;\n #endif\n #ifdef USE_SPECULAR_INTENSITYMAP\n uniform sampler2D specularIntensityMap;\n #endif\n#endif\n#ifdef USE_CLEARCOAT\n uniform float clearcoat;\n uniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n uniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n uniform float iridescence;\n uniform float iridescenceIOR;\n uniform float iridescenceThicknessMinimum;\n uniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n uniform vec3 sheenColor;\n uniform float sheenRoughness;\n #ifdef USE_SHEEN_COLORMAP\n uniform sampler2D sheenColorMap;\n #endif\n #ifdef USE_SHEEN_ROUGHNESSMAP\n uniform sampler2D sheenRoughnessMap;\n #endif\n#endif\n#ifdef USE_ANISOTROPY\n uniform vec2 anisotropyVector;\n #ifdef USE_ANISOTROPYMAP\n uniform sampler2D anisotropyMap;\n #endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include <clipping_planes_fragment>\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include <logdepthbuf_fragment>\n #include <map_fragment>\n #include <color_fragment>\n #include <alphamap_fragment>\n #include <alphatest_fragment>\n #include <alphahash_fragment>\n #include <roughnessmap_fragment>\n #include <metalnessmap_fragment>\n #include <normal_fragment_begin>\n #include <normal_fragment_maps>\n #include <clearcoat_normal_fragment_begin>\n #include <clearcoat_normal_fragment_maps>\n #include <emissivemap_fragment>\n #include <lights_physical_fragment>\n #include <lights_fragment_begin>\n #include <lights_fragment_maps>\n #include <lights_fragment_end>\n #include <aomap_fragment>\n vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n #include <transmission_fragment>\n vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n #ifdef USE_SHEEN\n float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n #endif\n #ifdef USE_CLEARCOAT\n float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n #endif\n #include <opaque_fragment>\n #include <tonemapping_fragment>\n #include <colorspace_fragment>\n #include <fog_fragment>\n #include <premultiplied_alpha_fragment>\n #include <dithering_fragment>\n}",
+ meshtoon_vert: "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <uv_vertex>\n #include <color_vertex>\n #include <morphinstance_vertex>\n #include <morphcolor_vertex>\n #include <batching_vertex>\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n #include <defaultnormal_vertex>\n #include <normal_vertex>\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <displacementmap_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n vViewPosition = - mvPosition.xyz;\n #include <worldpos_vertex>\n #include <shadowmap_vertex>\n #include <fog_vertex>\n}",
+ meshtoon_frag: "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include <clipping_planes_fragment>\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include <logdepthbuf_fragment>\n #include <map_fragment>\n #include <color_fragment>\n #include <alphamap_fragment>\n #include <alphatest_fragment>\n #include <alphahash_fragment>\n #include <normal_fragment_begin>\n #include <normal_fragment_maps>\n #include <emissivemap_fragment>\n #include <lights_toon_fragment>\n #include <lights_fragment_begin>\n #include <lights_fragment_maps>\n #include <lights_fragment_end>\n #include <aomap_fragment>\n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n #include <opaque_fragment>\n #include <tonemapping_fragment>\n #include <colorspace_fragment>\n #include <fog_fragment>\n #include <premultiplied_alpha_fragment>\n #include <dithering_fragment>\n}",
+ points_vert: "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\n varying vec2 vUv;\n uniform mat3 uvTransform;\n#endif\nvoid main() {\n #ifdef USE_POINTS_UV\n vUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n #endif\n #include <color_vertex>\n #include <morphinstance_vertex>\n #include <morphcolor_vertex>\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <project_vertex>\n gl_PointSize = size;\n #ifdef USE_SIZEATTENUATION\n bool isPerspective = isPerspectiveMatrix( projectionMatrix );\n if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n #endif\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n #include <worldpos_vertex>\n #include <fog_vertex>\n}",
+ points_frag: "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include <clipping_planes_fragment>\n vec3 outgoingLight = vec3( 0.0 );\n #include <logdepthbuf_fragment>\n #include <map_particle_fragment>\n #include <color_fragment>\n #include <alphatest_fragment>\n #include <alphahash_fragment>\n outgoingLight = diffuseColor.rgb;\n #include <opaque_fragment>\n #include <tonemapping_fragment>\n #include <colorspace_fragment>\n #include <fog_fragment>\n #include <premultiplied_alpha_fragment>\n}",
+ shadow_vert: "#include <common>\n#include <batching_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n #include <batching_vertex>\n #include <beginnormal_vertex>\n #include <morphinstance_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n #include <defaultnormal_vertex>\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <worldpos_vertex>\n #include <shadowmap_vertex>\n #include <fog_vertex>\n}",
+ shadow_frag: "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n #include <logdepthbuf_fragment>\n gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n #include <tonemapping_fragment>\n #include <colorspace_fragment>\n #include <fog_fragment>\n}",
+ sprite_vert: "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <uv_vertex>\n vec4 mvPosition = modelViewMatrix[ 3 ];\n vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n #ifndef USE_SIZEATTENUATION\n bool isPerspective = isPerspectiveMatrix( projectionMatrix );\n if ( isPerspective ) scale *= - mvPosition.z;\n #endif\n vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n vec2 rotatedPosition;\n rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n mvPosition.xy += rotatedPosition;\n gl_Position = projectionMatrix * mvPosition;\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n #include <fog_vertex>\n}",
+ sprite_frag: "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include <clipping_planes_fragment>\n vec3 outgoingLight = vec3( 0.0 );\n #include <logdepthbuf_fragment>\n #include <map_fragment>\n #include <alphamap_fragment>\n #include <alphatest_fragment>\n #include <alphahash_fragment>\n outgoingLight = diffuseColor.rgb;\n #include <opaque_fragment>\n #include <tonemapping_fragment>\n #include <colorspace_fragment>\n #include <fog_fragment>\n}"
+}, H = {
+ common: {
+ diffuse: { value: /* @__PURE__ */ new B(16777215) },
+ opacity: { value: 1 },
+ map: { value: null },
+ mapTransform: { value: /* @__PURE__ */ new Tt() },
+ alphaMap: { value: null },
+ alphaMapTransform: { value: /* @__PURE__ */ new Tt() },
+ alphaTest: { value: 0 }
+ },
+ specularmap: {
+ specularMap: { value: null },
+ specularMapTransform: { value: /* @__PURE__ */ new Tt() }
+ },
+ envmap: {
+ envMap: { value: null },
+ envMapRotation: { value: /* @__PURE__ */ new Tt() },
+ flipEnvMap: { value: -1 },
+ reflectivity: { value: 1 },
+ ior: { value: 1.5 },
+ refractionRatio: { value: .98 }
+ },
+ aomap: {
+ aoMap: { value: null },
+ aoMapIntensity: { value: 1 },
+ aoMapTransform: { value: /* @__PURE__ */ new Tt() }
+ },
+ lightmap: {
+ lightMap: { value: null },
+ lightMapIntensity: { value: 1 },
+ lightMapTransform: { value: /* @__PURE__ */ new Tt() }
+ },
+ bumpmap: {
+ bumpMap: { value: null },
+ bumpMapTransform: { value: /* @__PURE__ */ new Tt() },
+ bumpScale: { value: 1 }
+ },
+ normalmap: {
+ normalMap: { value: null },
+ normalMapTransform: { value: /* @__PURE__ */ new Tt() },
+ normalScale: { value: /* @__PURE__ */ new L(1, 1) }
+ },
+ displacementmap: {
+ displacementMap: { value: null },
+ displacementMapTransform: { value: /* @__PURE__ */ new Tt() },
+ displacementScale: { value: 1 },
+ displacementBias: { value: 0 }
+ },
+ emissivemap: {
+ emissiveMap: { value: null },
+ emissiveMapTransform: { value: /* @__PURE__ */ new Tt() }
+ },
+ metalnessmap: {
+ metalnessMap: { value: null },
+ metalnessMapTransform: { value: /* @__PURE__ */ new Tt() }
+ },
+ roughnessmap: {
+ roughnessMap: { value: null },
+ roughnessMapTransform: { value: /* @__PURE__ */ new Tt() }
+ },
+ gradientmap: { gradientMap: { value: null } },
+ fog: {
+ fogDensity: { value: 25e-5 },
+ fogNear: { value: 1 },
+ fogFar: { value: 2e3 },
+ fogColor: { value: /* @__PURE__ */ new B(16777215) }
+ },
+ lights: {
+ ambientLightColor: { value: [] },
+ lightProbe: { value: [] },
+ directionalLights: {
+ value: [],
+ properties: {
+ direction: {},
+ color: {}
+ }
+ },
+ directionalLightShadows: {
+ value: [],
+ properties: {
+ shadowIntensity: 1,
+ shadowBias: {},
+ shadowNormalBias: {},
+ shadowRadius: {},
+ shadowMapSize: {}
+ }
+ },
+ directionalShadowMap: { value: [] },
+ directionalShadowMatrix: { value: [] },
+ spotLights: {
+ value: [],
+ properties: {
+ color: {},
+ position: {},
+ direction: {},
+ distance: {},
+ coneCos: {},
+ penumbraCos: {},
+ decay: {}
+ }
+ },
+ spotLightShadows: {
+ value: [],
+ properties: {
+ shadowIntensity: 1,
+ shadowBias: {},
+ shadowNormalBias: {},
+ shadowRadius: {},
+ shadowMapSize: {}
+ }
+ },
+ spotLightMap: { value: [] },
+ spotShadowMap: { value: [] },
+ spotLightMatrix: { value: [] },
+ pointLights: {
+ value: [],
+ properties: {
+ color: {},
+ position: {},
+ decay: {},
+ distance: {}
+ }
+ },
+ pointLightShadows: {
+ value: [],
+ properties: {
+ shadowIntensity: 1,
+ shadowBias: {},
+ shadowNormalBias: {},
+ shadowRadius: {},
+ shadowMapSize: {},
+ shadowCameraNear: {},
+ shadowCameraFar: {}
+ }
+ },
+ pointShadowMap: { value: [] },
+ pointShadowMatrix: { value: [] },
+ hemisphereLights: {
+ value: [],
+ properties: {
+ direction: {},
+ skyColor: {},
+ groundColor: {}
+ }
+ },
+ rectAreaLights: {
+ value: [],
+ properties: {
+ color: {},
+ position: {},
+ width: {},
+ height: {}
+ }
+ },
+ ltc_1: { value: null },
+ ltc_2: { value: null }
+ },
+ points: {
+ diffuse: { value: /* @__PURE__ */ new B(16777215) },
+ opacity: { value: 1 },
+ size: { value: 1 },
+ scale: { value: 1 },
+ map: { value: null },
+ alphaMap: { value: null },
+ alphaMapTransform: { value: /* @__PURE__ */ new Tt() },
+ alphaTest: { value: 0 },
+ uvTransform: { value: /* @__PURE__ */ new Tt() }
+ },
+ sprite: {
+ diffuse: { value: /* @__PURE__ */ new B(16777215) },
+ opacity: { value: 1 },
+ center: { value: /* @__PURE__ */ new L(.5, .5) },
+ rotation: { value: 0 },
+ map: { value: null },
+ mapTransform: { value: /* @__PURE__ */ new Tt() },
+ alphaMap: { value: null },
+ alphaMapTransform: { value: /* @__PURE__ */ new Tt() },
+ alphaTest: { value: 0 }
+ }
+}, us = {
+ basic: {
+ uniforms: /* @__PURE__ */ si([
+ H.common,
+ H.specularmap,
+ H.envmap,
+ H.aomap,
+ H.lightmap,
+ H.fog
+ ]),
+ vertexShader: V.meshbasic_vert,
+ fragmentShader: V.meshbasic_frag
+ },
+ lambert: {
+ uniforms: /* @__PURE__ */ si([
+ H.common,
+ H.specularmap,
+ H.envmap,
+ H.aomap,
+ H.lightmap,
+ H.emissivemap,
+ H.bumpmap,
+ H.normalmap,
+ H.displacementmap,
+ H.fog,
+ H.lights,
+ { emissive: { value: /* @__PURE__ */ new B(0) } }
+ ]),
+ vertexShader: V.meshlambert_vert,
+ fragmentShader: V.meshlambert_frag
+ },
+ phong: {
+ uniforms: /* @__PURE__ */ si([
+ H.common,
+ H.specularmap,
+ H.envmap,
+ H.aomap,
+ H.lightmap,
+ H.emissivemap,
+ H.bumpmap,
+ H.normalmap,
+ H.displacementmap,
+ H.fog,
+ H.lights,
+ {
+ emissive: { value: /* @__PURE__ */ new B(0) },
+ specular: { value: /* @__PURE__ */ new B(1118481) },
+ shininess: { value: 30 }
+ }
+ ]),
+ vertexShader: V.meshphong_vert,
+ fragmentShader: V.meshphong_frag
+ },
+ standard: {
+ uniforms: /* @__PURE__ */ si([
+ H.common,
+ H.envmap,
+ H.aomap,
+ H.lightmap,
+ H.emissivemap,
+ H.bumpmap,
+ H.normalmap,
+ H.displacementmap,
+ H.roughnessmap,
+ H.metalnessmap,
+ H.fog,
+ H.lights,
+ {
+ emissive: { value: /* @__PURE__ */ new B(0) },
+ roughness: { value: 1 },
+ metalness: { value: 0 },
+ envMapIntensity: { value: 1 }
+ }
+ ]),
+ vertexShader: V.meshphysical_vert,
+ fragmentShader: V.meshphysical_frag
+ },
+ toon: {
+ uniforms: /* @__PURE__ */ si([
+ H.common,
+ H.aomap,
+ H.lightmap,
+ H.emissivemap,
+ H.bumpmap,
+ H.normalmap,
+ H.displacementmap,
+ H.gradientmap,
+ H.fog,
+ H.lights,
+ { emissive: { value: /* @__PURE__ */ new B(0) } }
+ ]),
+ vertexShader: V.meshtoon_vert,
+ fragmentShader: V.meshtoon_frag
+ },
+ matcap: {
+ uniforms: /* @__PURE__ */ si([
+ H.common,
+ H.bumpmap,
+ H.normalmap,
+ H.displacementmap,
+ H.fog,
+ { matcap: { value: null } }
+ ]),
+ vertexShader: V.meshmatcap_vert,
+ fragmentShader: V.meshmatcap_frag
+ },
+ points: {
+ uniforms: /* @__PURE__ */ si([H.points, H.fog]),
+ vertexShader: V.points_vert,
+ fragmentShader: V.points_frag
+ },
+ dashed: {
+ uniforms: /* @__PURE__ */ si([
+ H.common,
+ H.fog,
+ {
+ scale: { value: 1 },
+ dashSize: { value: 1 },
+ totalSize: { value: 2 }
+ }
+ ]),
+ vertexShader: V.linedashed_vert,
+ fragmentShader: V.linedashed_frag
+ },
+ depth: {
+ uniforms: /* @__PURE__ */ si([H.common, H.displacementmap]),
+ vertexShader: V.depth_vert,
+ fragmentShader: V.depth_frag
+ },
+ normal: {
+ uniforms: /* @__PURE__ */ si([
+ H.common,
+ H.bumpmap,
+ H.normalmap,
+ H.displacementmap,
+ { opacity: { value: 1 } }
+ ]),
+ vertexShader: V.meshnormal_vert,
+ fragmentShader: V.meshnormal_frag
+ },
+ sprite: {
+ uniforms: /* @__PURE__ */ si([H.sprite, H.fog]),
+ vertexShader: V.sprite_vert,
+ fragmentShader: V.sprite_frag
+ },
+ background: {
+ uniforms: {
+ uvTransform: { value: /* @__PURE__ */ new Tt() },
+ t2D: { value: null },
+ backgroundIntensity: { value: 1 }
+ },
+ vertexShader: V.background_vert,
+ fragmentShader: V.background_frag
+ },
+ backgroundCube: {
+ uniforms: {
+ envMap: { value: null },
+ flipEnvMap: { value: -1 },
+ backgroundBlurriness: { value: 0 },
+ backgroundIntensity: { value: 1 },
+ backgroundRotation: { value: /* @__PURE__ */ new Tt() }
+ },
+ vertexShader: V.backgroundCube_vert,
+ fragmentShader: V.backgroundCube_frag
+ },
+ cube: {
+ uniforms: {
+ tCube: { value: null },
+ tFlip: { value: -1 },
+ opacity: { value: 1 }
+ },
+ vertexShader: V.cube_vert,
+ fragmentShader: V.cube_frag
+ },
+ equirect: {
+ uniforms: { tEquirect: { value: null } },
+ vertexShader: V.equirect_vert,
+ fragmentShader: V.equirect_frag
+ },
+ distanceRGBA: {
+ uniforms: /* @__PURE__ */ si([
+ H.common,
+ H.displacementmap,
+ {
+ referencePosition: { value: /* @__PURE__ */ new R() },
+ nearDistance: { value: 1 },
+ farDistance: { value: 1e3 }
+ }
+ ]),
+ vertexShader: V.distanceRGBA_vert,
+ fragmentShader: V.distanceRGBA_frag
+ },
+ shadow: {
+ uniforms: /* @__PURE__ */ si([
+ H.lights,
+ H.fog,
+ {
+ color: { value: /* @__PURE__ */ new B(0) },
+ opacity: { value: 1 }
+ }
+ ]),
+ vertexShader: V.shadow_vert,
+ fragmentShader: V.shadow_frag
+ }
+};
+us.physical = {
+ uniforms: /* @__PURE__ */ si([us.standard.uniforms, {
+ clearcoat: { value: 0 },
+ clearcoatMap: { value: null },
+ clearcoatMapTransform: { value: /* @__PURE__ */ new Tt() },
+ clearcoatNormalMap: { value: null },
+ clearcoatNormalMapTransform: { value: /* @__PURE__ */ new Tt() },
+ clearcoatNormalScale: { value: /* @__PURE__ */ new L(1, 1) },
+ clearcoatRoughness: { value: 0 },
+ clearcoatRoughnessMap: { value: null },
+ clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new Tt() },
+ dispersion: { value: 0 },
+ iridescence: { value: 0 },
+ iridescenceMap: { value: null },
+ iridescenceMapTransform: { value: /* @__PURE__ */ new Tt() },
+ iridescenceIOR: { value: 1.3 },
+ iridescenceThicknessMinimum: { value: 100 },
+ iridescenceThicknessMaximum: { value: 400 },
+ iridescenceThicknessMap: { value: null },
+ iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new Tt() },
+ sheen: { value: 0 },
+ sheenColor: { value: /* @__PURE__ */ new B(0) },
+ sheenColorMap: { value: null },
+ sheenColorMapTransform: { value: /* @__PURE__ */ new Tt() },
+ sheenRoughness: { value: 1 },
+ sheenRoughnessMap: { value: null },
+ sheenRoughnessMapTransform: { value: /* @__PURE__ */ new Tt() },
+ transmission: { value: 0 },
+ transmissionMap: { value: null },
+ transmissionMapTransform: { value: /* @__PURE__ */ new Tt() },
+ transmissionSamplerSize: { value: /* @__PURE__ */ new L() },
+ transmissionSamplerMap: { value: null },
+ thickness: { value: 0 },
+ thicknessMap: { value: null },
+ thicknessMapTransform: { value: /* @__PURE__ */ new Tt() },
+ attenuationDistance: { value: 0 },
+ attenuationColor: { value: /* @__PURE__ */ new B(0) },
+ specularColor: { value: /* @__PURE__ */ new B(1, 1, 1) },
+ specularColorMap: { value: null },
+ specularColorMapTransform: { value: /* @__PURE__ */ new Tt() },
+ specularIntensity: { value: 1 },
+ specularIntensityMap: { value: null },
+ specularIntensityMapTransform: { value: /* @__PURE__ */ new Tt() },
+ anisotropyVector: { value: /* @__PURE__ */ new L() },
+ anisotropyMap: { value: null },
+ anisotropyMapTransform: { value: /* @__PURE__ */ new Tt() }
+ }]),
+ vertexShader: V.meshphysical_vert,
+ fragmentShader: V.meshphysical_frag
+};
+var ds = {
+ r: 0,
+ b: 0,
+ g: 0
+}, fs = /* @__PURE__ */ new zn(), ps = /* @__PURE__ */ new z();
+function ms(e, t, n, r, i, a, o) {
+ let s = new B(0), c = a === !0 ? 0 : 1, l, u, d = null, f = 0, p = null;
+ function m(e) {
+ let r = e.isScene === !0 ? e.background : null;
+ return r && r.isTexture && (r = (e.backgroundBlurriness > 0 ? n : t).get(r)), r;
+ }
+ function h(t) {
+ let n = !1, i = m(t);
+ i === null ? _(s, c) : i && i.isColor && (_(i, 1), n = !0);
+ let a = e.xr.getEnvironmentBlendMode();
+ a === "additive" ? r.buffers.color.setClear(0, 0, 0, 1, o) : a === "alpha-blend" && r.buffers.color.setClear(0, 0, 0, 0, o), (e.autoClear || n) && (r.buffers.depth.setTest(!0), r.buffers.depth.setMask(!0), r.buffers.color.setMask(!0), e.clear(e.autoClearColor, e.autoClearDepth, e.autoClearStencil));
+ }
+ function g(t, n) {
+ let r = m(n);
+ r && (r.isCubeTexture || r.mapping === 306) ? (u === void 0 && (u = new ni(new ai(1, 1, 1), new pi({
+ name: "BackgroundCubeMaterial",
+ uniforms: oi(us.backgroundCube.uniforms),
+ vertexShader: us.backgroundCube.vertexShader,
+ fragmentShader: us.backgroundCube.fragmentShader,
+ side: 1,
+ depthTest: !1,
+ depthWrite: !1,
+ fog: !1,
+ allowOverride: !1
+ })), u.geometry.deleteAttribute("normal"), u.geometry.deleteAttribute("uv"), u.onBeforeRender = function(e, t, n) {
+ this.matrixWorld.copyPosition(n.matrixWorld);
+ }, Object.defineProperty(u.material, "envMap", { get: function() {
+ return this.uniforms.envMap.value;
+ } }), i.update(u)), fs.copy(n.backgroundRotation), fs.x *= -1, fs.y *= -1, fs.z *= -1, r.isCubeTexture && r.isRenderTargetTexture === !1 && (fs.y *= -1, fs.z *= -1), u.material.uniforms.envMap.value = r, u.material.uniforms.flipEnvMap.value = r.isCubeTexture && r.isRenderTargetTexture === !1 ? -1 : 1, u.material.uniforms.backgroundBlurriness.value = n.backgroundBlurriness, u.material.uniforms.backgroundIntensity.value = n.backgroundIntensity, u.material.uniforms.backgroundRotation.value.setFromMatrix4(ps.makeRotationFromEuler(fs)), u.material.toneMapped = Rt.getTransfer(r.colorSpace) !== Je, (d !== r || f !== r.version || p !== e.toneMapping) && (u.material.needsUpdate = !0, d = r, f = r.version, p = e.toneMapping), u.layers.enableAll(), t.unshift(u, u.geometry, u.material, 0, 0, null)) : r && r.isTexture && (l === void 0 && (l = new ni(new Na(2, 2), new pi({
+ name: "BackgroundMaterial",
+ uniforms: oi(us.background.uniforms),
+ vertexShader: us.background.vertexShader,
+ fragmentShader: us.background.fragmentShader,
+ side: 0,
+ depthTest: !1,
+ depthWrite: !1,
+ fog: !1,
+ allowOverride: !1
+ })), l.geometry.deleteAttribute("normal"), Object.defineProperty(l.material, "map", { get: function() {
+ return this.uniforms.t2D.value;
+ } }), i.update(l)), l.material.uniforms.t2D.value = r, l.material.uniforms.backgroundIntensity.value = n.backgroundIntensity, l.material.toneMapped = Rt.getTransfer(r.colorSpace) !== Je, r.matrixAutoUpdate === !0 && r.updateMatrix(), l.material.uniforms.uvTransform.value.copy(r.matrix), (d !== r || f !== r.version || p !== e.toneMapping) && (l.material.needsUpdate = !0, d = r, f = r.version, p = e.toneMapping), l.layers.enableAll(), t.unshift(l, l.geometry, l.material, 0, 0, null));
+ }
+ function _(t, n) {
+ t.getRGB(ds, li(e)), r.buffers.color.setClear(ds.r, ds.g, ds.b, n, o);
+ }
+ function v() {
+ u !== void 0 && (u.geometry.dispose(), u.material.dispose(), u = void 0), l !== void 0 && (l.geometry.dispose(), l.material.dispose(), l = void 0);
+ }
+ return {
+ getClearColor: function() {
+ return s;
+ },
+ setClearColor: function(e, t = 1) {
+ s.set(e), c = t, _(s, c);
+ },
+ getClearAlpha: function() {
+ return c;
+ },
+ setClearAlpha: function(e) {
+ c = e, _(s, c);
+ },
+ render: h,
+ addToRenderList: g,
+ dispose: v
+ };
+}
+function hs(e, t) {
+ let n = e.getParameter(e.MAX_VERTEX_ATTRIBS), r = {}, i = f(null), a = i, o = !1;
+ function s(n, r, i, s, c) {
+ let u = !1, f = d(s, i, r);
+ a !== f && (a = f, l(a.object)), u = p(n, s, i, c), u && m(n, s, i, c), c !== null && t.update(c, e.ELEMENT_ARRAY_BUFFER), (u || o) && (o = !1, b(n, r, i, s), c !== null && e.bindBuffer(e.ELEMENT_ARRAY_BUFFER, t.get(c).buffer));
+ }
+ function c() {
+ return e.createVertexArray();
+ }
+ function l(t) {
+ return e.bindVertexArray(t);
+ }
+ function u(t) {
+ return e.deleteVertexArray(t);
+ }
+ function d(e, t, n) {
+ let i = n.wireframe === !0, a = r[e.id];
+ a === void 0 && (a = {}, r[e.id] = a);
+ let o = a[t.id];
+ o === void 0 && (o = {}, a[t.id] = o);
+ let s = o[i];
+ return s === void 0 && (s = f(c()), o[i] = s), s;
+ }
+ function f(e) {
+ let t = [], r = [], i = [];
+ for (let e = 0; e < n; e++) t[e] = 0, r[e] = 0, i[e] = 0;
+ return {
+ geometry: null,
+ program: null,
+ wireframe: !1,
+ newAttributes: t,
+ enabledAttributes: r,
+ attributeDivisors: i,
+ object: e,
+ attributes: {},
+ index: null
+ };
+ }
+ function p(e, t, n, r) {
+ let i = a.attributes, o = t.attributes, s = 0, c = n.getAttributes();
+ for (let t in c) if (c[t].location >= 0) {
+ let n = i[t], r = o[t];
+ if (r === void 0 && (t === "instanceMatrix" && e.instanceMatrix && (r = e.instanceMatrix), t === "instanceColor" && e.instanceColor && (r = e.instanceColor)), n === void 0 || n.attribute !== r || r && n.data !== r.data) return !0;
+ s++;
+ }
+ return a.attributesNum !== s || a.index !== r;
+ }
+ function m(e, t, n, r) {
+ let i = {}, o = t.attributes, s = 0, c = n.getAttributes();
+ for (let t in c) if (c[t].location >= 0) {
+ let n = o[t];
+ n === void 0 && (t === "instanceMatrix" && e.instanceMatrix && (n = e.instanceMatrix), t === "instanceColor" && e.instanceColor && (n = e.instanceColor));
+ let r = {};
+ r.attribute = n, n && n.data && (r.data = n.data), i[t] = r, s++;
+ }
+ a.attributes = i, a.attributesNum = s, a.index = r;
+ }
+ function h() {
+ let e = a.newAttributes;
+ for (let t = 0, n = e.length; t < n; t++) e[t] = 0;
+ }
+ function g(e) {
+ _(e, 0);
+ }
+ function _(t, n) {
+ let r = a.newAttributes, i = a.enabledAttributes, o = a.attributeDivisors;
+ r[t] = 1, i[t] === 0 && (e.enableVertexAttribArray(t), i[t] = 1), o[t] !== n && (e.vertexAttribDivisor(t, n), o[t] = n);
+ }
+ function v() {
+ let t = a.newAttributes, n = a.enabledAttributes;
+ for (let r = 0, i = n.length; r < i; r++) n[r] !== t[r] && (e.disableVertexAttribArray(r), n[r] = 0);
+ }
+ function y(t, n, r, i, a, o, s) {
+ s === !0 ? e.vertexAttribIPointer(t, n, r, a, o) : e.vertexAttribPointer(t, n, r, i, a, o);
+ }
+ function b(n, r, i, a) {
+ h();
+ let o = a.attributes, s = i.getAttributes(), c = r.defaultAttributeValues;
+ for (let r in s) {
+ let i = s[r];
+ if (i.location >= 0) {
+ let s = o[r];
+ if (s === void 0 && (r === "instanceMatrix" && n.instanceMatrix && (s = n.instanceMatrix), r === "instanceColor" && n.instanceColor && (s = n.instanceColor)), s !== void 0) {
+ let r = s.normalized, o = s.itemSize, c = t.get(s);
+ if (c === void 0) continue;
+ let l = c.buffer, u = c.type, d = c.bytesPerElement, f = u === e.INT || u === e.UNSIGNED_INT || s.gpuType === 1013;
+ if (s.isInterleavedBufferAttribute) {
+ let t = s.data, c = t.stride, p = s.offset;
+ if (t.isInstancedInterleavedBuffer) {
+ for (let e = 0; e < i.locationSize; e++) _(i.location + e, t.meshPerAttribute);
+ n.isInstancedMesh !== !0 && a._maxInstanceCount === void 0 && (a._maxInstanceCount = t.meshPerAttribute * t.count);
+ } else for (let e = 0; e < i.locationSize; e++) g(i.location + e);
+ e.bindBuffer(e.ARRAY_BUFFER, l);
+ for (let e = 0; e < i.locationSize; e++) y(i.location + e, o / i.locationSize, u, r, c * d, (p + o / i.locationSize * e) * d, f);
+ } else {
+ if (s.isInstancedBufferAttribute) {
+ for (let e = 0; e < i.locationSize; e++) _(i.location + e, s.meshPerAttribute);
+ n.isInstancedMesh !== !0 && a._maxInstanceCount === void 0 && (a._maxInstanceCount = s.meshPerAttribute * s.count);
+ } else for (let e = 0; e < i.locationSize; e++) g(i.location + e);
+ e.bindBuffer(e.ARRAY_BUFFER, l);
+ for (let e = 0; e < i.locationSize; e++) y(i.location + e, o / i.locationSize, u, r, o * d, o / i.locationSize * e * d, f);
+ }
+ } else if (c !== void 0) {
+ let t = c[r];
+ if (t !== void 0) switch (t.length) {
+ case 2:
+ e.vertexAttrib2fv(i.location, t);
+ break;
+ case 3:
+ e.vertexAttrib3fv(i.location, t);
+ break;
+ case 4:
+ e.vertexAttrib4fv(i.location, t);
+ break;
+ default: e.vertexAttrib1fv(i.location, t);
+ }
+ }
+ }
+ }
+ v();
+ }
+ function x() {
+ w();
+ for (let e in r) {
+ let t = r[e];
+ for (let e in t) {
+ let n = t[e];
+ for (let e in n) u(n[e].object), delete n[e];
+ delete t[e];
+ }
+ delete r[e];
+ }
+ }
+ function S(e) {
+ if (r[e.id] === void 0) return;
+ let t = r[e.id];
+ for (let e in t) {
+ let n = t[e];
+ for (let e in n) u(n[e].object), delete n[e];
+ delete t[e];
+ }
+ delete r[e.id];
+ }
+ function C(e) {
+ for (let t in r) {
+ let n = r[t];
+ if (n[e.id] === void 0) continue;
+ let i = n[e.id];
+ for (let e in i) u(i[e].object), delete i[e];
+ delete n[e.id];
+ }
+ }
+ function w() {
+ T(), o = !0, a !== i && (a = i, l(a.object));
+ }
+ function T() {
+ i.geometry = null, i.program = null, i.wireframe = !1;
+ }
+ return {
+ setup: s,
+ reset: w,
+ resetDefaultState: T,
+ dispose: x,
+ releaseStatesOfGeometry: S,
+ releaseStatesOfProgram: C,
+ initAttributes: h,
+ enableAttribute: g,
+ disableUnusedAttributes: v
+ };
+}
+function gs(e, t, n) {
+ let r;
+ function i(e) {
+ r = e;
+ }
+ function a(t, i) {
+ e.drawArrays(r, t, i), n.update(i, r, 1);
+ }
+ function o(t, i, a) {
+ a !== 0 && (e.drawArraysInstanced(r, t, i, a), n.update(i, r, a));
+ }
+ function s(e, i, a) {
+ if (a === 0) return;
+ t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(r, e, 0, i, 0, a);
+ let o = 0;
+ for (let e = 0; e < a; e++) o += i[e];
+ n.update(o, r, 1);
+ }
+ function c(e, i, a, s) {
+ if (a === 0) return;
+ let c = t.get("WEBGL_multi_draw");
+ if (c === null) for (let t = 0; t < e.length; t++) o(e[t], i[t], s[t]);
+ else {
+ c.multiDrawArraysInstancedWEBGL(r, e, 0, i, 0, s, 0, a);
+ let t = 0;
+ for (let e = 0; e < a; e++) t += i[e] * s[e];
+ n.update(t, r, 1);
+ }
+ }
+ this.setMode = i, this.render = a, this.renderInstances = o, this.renderMultiDraw = s, this.renderMultiDrawInstances = c;
+}
+function _s(e, t, n, r) {
+ let i;
+ function a() {
+ if (i !== void 0) return i;
+ if (t.has("EXT_texture_filter_anisotropic") === !0) {
+ let n = t.get("EXT_texture_filter_anisotropic");
+ i = e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
+ } else i = 0;
+ return i;
+ }
+ function o(t) {
+ return !(t !== 1023 && r.convert(t) !== e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT));
+ }
+ function s(n) {
+ let i = n === 1016 && (t.has("EXT_color_buffer_half_float") || t.has("EXT_color_buffer_float"));
+ return !(n !== 1009 && r.convert(n) !== e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE) && n !== 1015 && !i);
+ }
+ function c(t) {
+ if (t === "highp") {
+ if (e.getShaderPrecisionFormat(e.VERTEX_SHADER, e.HIGH_FLOAT).precision > 0 && e.getShaderPrecisionFormat(e.FRAGMENT_SHADER, e.HIGH_FLOAT).precision > 0) return "highp";
+ t = "mediump";
+ }
+ return t === "mediump" && e.getShaderPrecisionFormat(e.VERTEX_SHADER, e.MEDIUM_FLOAT).precision > 0 && e.getShaderPrecisionFormat(e.FRAGMENT_SHADER, e.MEDIUM_FLOAT).precision > 0 ? "mediump" : "lowp";
+ }
+ let l = n.precision === void 0 ? "highp" : n.precision, u = c(l);
+ u !== l && (console.warn("THREE.WebGLRenderer:", l, "not supported, using", u, "instead."), l = u);
+ let d = n.logarithmicDepthBuffer === !0, f = n.reverseDepthBuffer === !0 && t.has("EXT_clip_control"), p = e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS), m = e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS), h = e.getParameter(e.MAX_TEXTURE_SIZE), g = e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE), _ = e.getParameter(e.MAX_VERTEX_ATTRIBS), v = e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS), y = e.getParameter(e.MAX_VARYING_VECTORS), b = e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS), x = m > 0, S = e.getParameter(e.MAX_SAMPLES);
+ return {
+ isWebGL2: !0,
+ getMaxAnisotropy: a,
+ getMaxPrecision: c,
+ textureFormatReadable: o,
+ textureTypeReadable: s,
+ precision: l,
+ logarithmicDepthBuffer: d,
+ reverseDepthBuffer: f,
+ maxTextures: p,
+ maxVertexTextures: m,
+ maxTextureSize: h,
+ maxCubemapSize: g,
+ maxAttributes: _,
+ maxVertexUniforms: v,
+ maxVaryings: y,
+ maxFragmentUniforms: b,
+ vertexTextures: x,
+ maxSamples: S
+ };
+}
+function vs(e) {
+ let t = this, n = null, r = 0, i = !1, a = !1, o = new ia(), s = new Tt(), c = {
+ value: null,
+ needsUpdate: !1
+ };
+ this.uniform = c, this.numPlanes = 0, this.numIntersection = 0, this.init = function(e, t) {
+ let n = e.length !== 0 || t || r !== 0 || i;
+ return i = t, r = e.length, n;
+ }, this.beginShadows = function() {
+ a = !0, u(null);
+ }, this.endShadows = function() {
+ a = !1;
+ }, this.setGlobalState = function(e, t) {
+ n = u(e, t, 0);
+ }, this.setState = function(t, o, s) {
+ let d = t.clippingPlanes, f = t.clipIntersection, p = t.clipShadows, m = e.get(t);
+ if (!i || d === null || d.length === 0 || a && !p) a ? u(null) : l();
+ else {
+ let e = a ? 0 : r, t = e * 4, i = m.clippingState || null;
+ c.value = i, i = u(d, o, t, s);
+ for (let e = 0; e !== t; ++e) i[e] = n[e];
+ m.clippingState = i, this.numIntersection = f ? this.numPlanes : 0, this.numPlanes += e;
+ }
+ };
+ function l() {
+ c.value !== n && (c.value = n, c.needsUpdate = r > 0), t.numPlanes = r, t.numIntersection = 0;
+ }
+ function u(e, n, r, i) {
+ let a = e === null ? 0 : e.length, l = null;
+ if (a !== 0) {
+ if (l = c.value, i !== !0 || l === null) {
+ let t = r + a * 4, i = n.matrixWorldInverse;
+ s.getNormalMatrix(i), (l === null || l.length < t) && (l = new Float32Array(t));
+ for (let t = 0, n = r; t !== a; ++t, n += 4) o.copy(e[t]).applyMatrix4(i, s), o.normal.toArray(l, n), l[n + 3] = o.constant;
+ }
+ c.value = l, c.needsUpdate = !0;
+ }
+ return t.numPlanes = a, t.numIntersection = 0, l;
+ }
+}
+function ys(e) {
+ let t = /* @__PURE__ */ new WeakMap();
+ function n(e, t) {
+ return t === 303 ? e.mapping = 301 : t === 304 && (e.mapping = 302), e;
+ }
+ function r(r) {
+ if (r && r.isTexture) {
+ let a = r.mapping;
+ if (a === 303 || a === 304) if (t.has(r)) {
+ let e = t.get(r).texture;
+ return n(e, r.mapping);
+ } else {
+ let a = r.image;
+ if (a && a.height > 0) {
+ let o = new Ci(a.height);
+ return o.fromEquirectangularTexture(e, r), t.set(r, o), r.addEventListener("dispose", i), n(o.texture, r.mapping);
+ } else return null;
+ }
+ }
+ return r;
+ }
+ function i(e) {
+ let n = e.target;
+ n.removeEventListener("dispose", i);
+ let r = t.get(n);
+ r !== void 0 && (t.delete(n), r.dispose());
+ }
+ function a() {
+ t = /* @__PURE__ */ new WeakMap();
+ }
+ return {
+ get: r,
+ dispose: a
+ };
+}
+var bs = 4, xs = [
+ .125,
+ .215,
+ .35,
+ .446,
+ .526,
+ .582
+], Ss = 20, Cs = /* @__PURE__ */ new Oo(), ws = /* @__PURE__ */ new B(), Ts = null, Es = 0, Ds = 0, Os = !1, ks = (1 + Math.sqrt(5)) / 2, As = 1 / ks, js = [
+ /* @__PURE__ */ new R(-ks, As, 0),
+ /* @__PURE__ */ new R(ks, As, 0),
+ /* @__PURE__ */ new R(-As, 0, ks),
+ /* @__PURE__ */ new R(As, 0, ks),
+ /* @__PURE__ */ new R(0, ks, -As),
+ /* @__PURE__ */ new R(0, ks, As),
+ /* @__PURE__ */ new R(-1, 1, -1),
+ /* @__PURE__ */ new R(1, 1, -1),
+ /* @__PURE__ */ new R(-1, 1, 1),
+ /* @__PURE__ */ new R(1, 1, 1)
+], Ms = /* @__PURE__ */ new R(), Ns = class {
+ constructor(e) {
+ this._renderer = e, this._pingPongRenderTarget = null, this._lodMax = 0, this._cubeSize = 0, this._lodPlanes = [], this._sizeLods = [], this._sigmas = [], this._blurMaterial = null, this._cubemapMaterial = null, this._equirectMaterial = null, this._compileMaterial(this._blurMaterial);
+ }
+ fromScene(e, t = 0, n = .1, r = 100, i = {}) {
+ let { size: a = 256, position: o = Ms } = i;
+ Ts = this._renderer.getRenderTarget(), Es = this._renderer.getActiveCubeFace(), Ds = this._renderer.getActiveMipmapLevel(), Os = this._renderer.xr.enabled, this._renderer.xr.enabled = !1, this._setSize(a);
+ let s = this._allocateTargets();
+ return s.depthBuffer = !0, this._sceneToCubeUV(e, n, r, s, o), t > 0 && this._blur(s, 0, 0, t), this._applyPMREM(s), this._cleanup(s), s;
+ }
+ fromEquirectangular(e, t = null) {
+ return this._fromTexture(e, t);
+ }
+ fromCubemap(e, t = null) {
+ return this._fromTexture(e, t);
+ }
+ compileCubemapShader() {
+ this._cubemapMaterial === null && (this._cubemapMaterial = zs(), this._compileMaterial(this._cubemapMaterial));
+ }
+ compileEquirectangularShader() {
+ this._equirectMaterial === null && (this._equirectMaterial = Rs(), this._compileMaterial(this._equirectMaterial));
+ }
+ dispose() {
+ this._dispose(), this._cubemapMaterial !== null && this._cubemapMaterial.dispose(), this._equirectMaterial !== null && this._equirectMaterial.dispose();
+ }
+ _setSize(e) {
+ this._lodMax = Math.floor(Math.log2(e)), this._cubeSize = 2 ** this._lodMax;
+ }
+ _dispose() {
+ this._blurMaterial !== null && this._blurMaterial.dispose(), this._pingPongRenderTarget !== null && this._pingPongRenderTarget.dispose();
+ for (let e = 0; e < this._lodPlanes.length; e++) this._lodPlanes[e].dispose();
+ }
+ _cleanup(e) {
+ this._renderer.setRenderTarget(Ts, Es, Ds), this._renderer.xr.enabled = Os, e.scissorTest = !1, Is(e, 0, 0, e.width, e.height);
+ }
+ _fromTexture(e, t) {
+ e.mapping === 301 || e.mapping === 302 ? this._setSize(e.image.length === 0 ? 16 : e.image[0].width || e.image[0].image.width) : this._setSize(e.image.width / 4), Ts = this._renderer.getRenderTarget(), Es = this._renderer.getActiveCubeFace(), Ds = this._renderer.getActiveMipmapLevel(), Os = this._renderer.xr.enabled, this._renderer.xr.enabled = !1;
+ let n = t || this._allocateTargets();
+ return this._textureToCubeUV(e, n), this._applyPMREM(n), this._cleanup(n), n;
+ }
+ _allocateTargets() {
+ let e = 3 * Math.max(this._cubeSize, 112), t = 4 * this._cubeSize, n = {
+ magFilter: d,
+ minFilter: d,
+ generateMipmaps: !1,
+ type: x,
+ format: O,
+ colorSpace: Ke,
+ depthBuffer: !1
+ }, r = Fs(e, t, n);
+ if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== e || this._pingPongRenderTarget.height !== t) {
+ this._pingPongRenderTarget !== null && this._dispose(), this._pingPongRenderTarget = Fs(e, t, n);
+ let { _lodMax: r } = this;
+ ({sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas} = Ps(r)), this._blurMaterial = Ls(r, e, t);
+ }
+ return r;
+ }
+ _compileMaterial(e) {
+ let t = new ni(this._lodPlanes[0], e);
+ this._renderer.compile(t, Cs);
+ }
+ _sceneToCubeUV(e, t, n, r, i) {
+ let a = new vi(90, 1, t, n), o = [
+ 1,
+ -1,
+ 1,
+ 1,
+ 1,
+ 1
+ ], s = [
+ 1,
+ 1,
+ 1,
+ -1,
+ -1,
+ -1
+ ], c = this._renderer, l = c.autoClear, u = c.toneMapping;
+ c.getClearColor(ws), c.toneMapping = 0, c.autoClear = !1;
+ let d = new wr({
+ name: "PMREM.Background",
+ side: 1,
+ depthWrite: !1,
+ depthTest: !1
+ }), f = new ni(new ai(), d), p = !1, m = e.background;
+ m ? m.isColor && (d.color.copy(m), e.background = null, p = !0) : (d.color.copy(ws), p = !0);
+ for (let t = 0; t < 6; t++) {
+ let n = t % 3;
+ n === 0 ? (a.up.set(0, o[t], 0), a.position.set(i.x, i.y, i.z), a.lookAt(i.x + s[t], i.y, i.z)) : n === 1 ? (a.up.set(0, 0, o[t]), a.position.set(i.x, i.y, i.z), a.lookAt(i.x, i.y + s[t], i.z)) : (a.up.set(0, o[t], 0), a.position.set(i.x, i.y, i.z), a.lookAt(i.x, i.y, i.z + s[t]));
+ let l = this._cubeSize;
+ Is(r, n * l, t > 2 ? l : 0, l, l), c.setRenderTarget(r), p && c.render(f, a), c.render(e, a);
+ }
+ f.geometry.dispose(), f.material.dispose(), c.toneMapping = u, c.autoClear = l, e.background = m;
+ }
+ _textureToCubeUV(e, t) {
+ let n = this._renderer, r = e.mapping === 301 || e.mapping === 302;
+ r ? (this._cubemapMaterial === null && (this._cubemapMaterial = zs()), this._cubemapMaterial.uniforms.flipEnvMap.value = e.isRenderTargetTexture === !1 ? -1 : 1) : this._equirectMaterial === null && (this._equirectMaterial = Rs());
+ let i = r ? this._cubemapMaterial : this._equirectMaterial, a = new ni(this._lodPlanes[0], i), o = i.uniforms;
+ o.envMap.value = e;
+ let s = this._cubeSize;
+ Is(t, 0, 0, 3 * s, 2 * s), n.setRenderTarget(t), n.render(a, Cs);
+ }
+ _applyPMREM(e) {
+ let t = this._renderer, n = t.autoClear;
+ t.autoClear = !1;
+ let r = this._lodPlanes.length;
+ for (let t = 1; t < r; t++) {
+ let n = Math.sqrt(this._sigmas[t] * this._sigmas[t] - this._sigmas[t - 1] * this._sigmas[t - 1]), i = js[(r - t - 1) % js.length];
+ this._blur(e, t - 1, t, n, i);
+ }
+ t.autoClear = n;
+ }
+ _blur(e, t, n, r, i) {
+ let a = this._pingPongRenderTarget;
+ this._halfBlur(e, a, t, n, r, "latitudinal", i), this._halfBlur(a, e, n, n, r, "longitudinal", i);
+ }
+ _halfBlur(e, t, n, r, i, a, o) {
+ let s = this._renderer, c = this._blurMaterial;
+ a !== "latitudinal" && a !== "longitudinal" && console.error("blur direction must be either latitudinal or longitudinal!");
+ let l = new ni(this._lodPlanes[r], c), u = c.uniforms, d = this._sizeLods[n] - 1, f = isFinite(i) ? Math.PI / (2 * d) : 2 * Math.PI / (2 * Ss - 1), p = i / f, m = isFinite(i) ? 1 + Math.floor(3 * p) : Ss;
+ m > Ss && console.warn(`sigmaRadians, ${i}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Ss}`);
+ let h = [], g = 0;
+ for (let e = 0; e < Ss; ++e) {
+ let t = e / p, n = Math.exp(-t * t / 2);
+ h.push(n), e === 0 ? g += n : e < m && (g += 2 * n);
+ }
+ for (let e = 0; e < h.length; e++) h[e] = h[e] / g;
+ u.envMap.value = e.texture, u.samples.value = m, u.weights.value = h, u.latitudinal.value = a === "latitudinal", o && (u.poleAxis.value = o);
+ let { _lodMax: _ } = this;
+ u.dTheta.value = f, u.mipInt.value = _ - n;
+ let v = this._sizeLods[r];
+ Is(t, 3 * v * (r > _ - bs ? r - _ + bs : 0), 4 * (this._cubeSize - v), 3 * v, 2 * v), s.setRenderTarget(t), s.render(l, Cs);
+ }
+};
+function Ps(e) {
+ let t = [], n = [], r = [], i = e, a = e - bs + 1 + xs.length;
+ for (let o = 0; o < a; o++) {
+ let a = 2 ** i;
+ n.push(a);
+ let s = 1 / a;
+ o > e - bs ? s = xs[o - e + bs - 1] : o === 0 && (s = 0), r.push(s);
+ let c = 1 / (a - 2), l = -c, u = 1 + c, d = [
+ l,
+ l,
+ u,
+ l,
+ u,
+ u,
+ l,
+ l,
+ u,
+ u,
+ l,
+ u
+ ], f = new Float32Array(108), p = new Float32Array(72), m = new Float32Array(36);
+ for (let e = 0; e < 6; e++) {
+ let t = e % 3 * 2 / 3 - 1, n = e > 2 ? 0 : -1, r = [
+ t,
+ n,
+ 0,
+ t + 2 / 3,
+ n,
+ 0,
+ t + 2 / 3,
+ n + 1,
+ 0,
+ t,
+ n,
+ 0,
+ t + 2 / 3,
+ n + 1,
+ 0,
+ t,
+ n + 1,
+ 0
+ ];
+ f.set(r, 18 * e), p.set(d, 12 * e);
+ let i = [
+ e,
+ e,
+ e,
+ e,
+ e,
+ e
+ ];
+ m.set(i, 6 * e);
+ }
+ let h = new Wr();
+ h.setAttribute("position", new Nr(f, 3)), h.setAttribute("uv", new Nr(p, 2)), h.setAttribute("faceIndex", new Nr(m, 1)), t.push(h), i > bs && i--;
+ }
+ return {
+ lodPlanes: t,
+ sizeLods: n,
+ sigmas: r
+ };
+}
+function Fs(e, t, n) {
+ let r = new Xt(e, t, n);
+ return r.texture.mapping = 306, r.texture.name = "PMREM.cubeUv", r.scissorTest = !0, r;
+}
+function Is(e, t, n, r, i) {
+ e.viewport.set(t, n, r, i), e.scissor.set(t, n, r, i);
+}
+function Ls(e, t, n) {
+ let r = new Float32Array(Ss), i = new R(0, 1, 0);
+ return new pi({
+ name: "SphericalGaussianBlur",
+ defines: {
+ n: Ss,
+ CUBEUV_TEXEL_WIDTH: 1 / t,
+ CUBEUV_TEXEL_HEIGHT: 1 / n,
+ CUBEUV_MAX_MIP: `${e}.0`
+ },
+ uniforms: {
+ envMap: { value: null },
+ samples: { value: 1 },
+ weights: { value: r },
+ latitudinal: { value: !1 },
+ dTheta: { value: 0 },
+ mipInt: { value: 0 },
+ poleAxis: { value: i }
+ },
+ vertexShader: Bs(),
+ fragmentShader: "\n\n precision mediump float;\n precision mediump int;\n\n varying vec3 vOutputDirection;\n\n uniform sampler2D envMap;\n uniform int samples;\n uniform float weights[ n ];\n uniform bool latitudinal;\n uniform float dTheta;\n uniform float mipInt;\n uniform vec3 poleAxis;\n\n #define ENVMAP_TYPE_CUBE_UV\n #include <cube_uv_reflection_fragment>\n\n vec3 getSample( float theta, vec3 axis ) {\n\n float cosTheta = cos( theta );\n // Rodrigues' axis-angle rotation\n vec3 sampleDirection = vOutputDirection * cosTheta\n + cross( axis, vOutputDirection ) * sin( theta )\n + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n return bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n }\n\n void main() {\n\n vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n if ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n }\n\n axis = normalize( axis );\n\n gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n for ( int i = 1; i < n; i++ ) {\n\n if ( i >= samples ) {\n\n break;\n\n }\n\n float theta = dTheta * float( i );\n gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n }\n\n }\n ",
+ blending: 0,
+ depthTest: !1,
+ depthWrite: !1
+ });
+}
+function Rs() {
+ return new pi({
+ name: "EquirectangularToCubeUV",
+ uniforms: { envMap: { value: null } },
+ vertexShader: Bs(),
+ fragmentShader: "\n\n precision mediump float;\n precision mediump int;\n\n varying vec3 vOutputDirection;\n\n uniform sampler2D envMap;\n\n #include <common>\n\n void main() {\n\n vec3 outputDirection = normalize( vOutputDirection );\n vec2 uv = equirectUv( outputDirection );\n\n gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n }\n ",
+ blending: 0,
+ depthTest: !1,
+ depthWrite: !1
+ });
+}
+function zs() {
+ return new pi({
+ name: "CubemapToCubeUV",
+ uniforms: {
+ envMap: { value: null },
+ flipEnvMap: { value: -1 }
+ },
+ vertexShader: Bs(),
+ fragmentShader: "\n\n precision mediump float;\n precision mediump int;\n\n uniform float flipEnvMap;\n\n varying vec3 vOutputDirection;\n\n uniform samplerCube envMap;\n\n void main() {\n\n gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n }\n ",
+ blending: 0,
+ depthTest: !1,
+ depthWrite: !1
+ });
+}
+function Bs() {
+ return "\n\n precision mediump float;\n precision mediump int;\n\n attribute float faceIndex;\n\n varying vec3 vOutputDirection;\n\n // RH coordinate system; PMREM face-indexing convention\n vec3 getDirection( vec2 uv, float face ) {\n\n uv = 2.0 * uv - 1.0;\n\n vec3 direction = vec3( uv, 1.0 );\n\n if ( face == 0.0 ) {\n\n direction = direction.zyx; // ( 1, v, u ) pos x\n\n } else if ( face == 1.0 ) {\n\n direction = direction.xzy;\n direction.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n } else if ( face == 2.0 ) {\n\n direction.x *= -1.0; // ( -u, v, 1 ) pos z\n\n } else if ( face == 3.0 ) {\n\n direction = direction.zyx;\n direction.xz *= -1.0; // ( -1, v, -u ) neg x\n\n } else if ( face == 4.0 ) {\n\n direction = direction.xzy;\n direction.xy *= -1.0; // ( -u, -1, v ) neg y\n\n } else if ( face == 5.0 ) {\n\n direction.z *= -1.0; // ( u, v, -1 ) neg z\n\n }\n\n return direction;\n\n }\n\n void main() {\n\n vOutputDirection = getDirection( uv, faceIndex );\n gl_Position = vec4( position, 1.0 );\n\n }\n ";
+}
+function Vs(e) {
+ let t = /* @__PURE__ */ new WeakMap(), n = null;
+ function r(r) {
+ if (r && r.isTexture) {
+ let o = r.mapping, s = o === 303 || o === 304, c = o === 301 || o === 302;
+ if (s || c) {
+ let o = t.get(r), l = o === void 0 ? 0 : o.texture.pmremVersion;
+ if (r.isRenderTargetTexture && r.pmremVersion !== l) return n === null && (n = new Ns(e)), o = s ? n.fromEquirectangular(r, o) : n.fromCubemap(r, o), o.texture.pmremVersion = r.pmremVersion, t.set(r, o), o.texture;
+ if (o !== void 0) return o.texture;
+ {
+ let l = r.image;
+ return s && l && l.height > 0 || c && l && i(l) ? (n === null && (n = new Ns(e)), o = s ? n.fromEquirectangular(r) : n.fromCubemap(r), o.texture.pmremVersion = r.pmremVersion, t.set(r, o), r.addEventListener("dispose", a), o.texture) : null;
+ }
+ }
+ }
+ return r;
+ }
+ function i(e) {
+ let t = 0;
+ for (let n = 0; n < 6; n++) e[n] !== void 0 && t++;
+ return t === 6;
+ }
+ function a(e) {
+ let n = e.target;
+ n.removeEventListener("dispose", a);
+ let r = t.get(n);
+ r !== void 0 && (t.delete(n), r.dispose());
+ }
+ function o() {
+ t = /* @__PURE__ */ new WeakMap(), n !== null && (n.dispose(), n = null);
+ }
+ return {
+ get: r,
+ dispose: o
+ };
+}
+function Hs(e) {
+ let t = {};
+ function n(n) {
+ if (t[n] !== void 0) return t[n];
+ let r;
+ switch (n) {
+ case "WEBGL_depth_texture":
+ r = e.getExtension("WEBGL_depth_texture") || e.getExtension("MOZ_WEBGL_depth_texture") || e.getExtension("WEBKIT_WEBGL_depth_texture");
+ break;
+ case "EXT_texture_filter_anisotropic":
+ r = e.getExtension("EXT_texture_filter_anisotropic") || e.getExtension("MOZ_EXT_texture_filter_anisotropic") || e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");
+ break;
+ case "WEBGL_compressed_texture_s3tc":
+ r = e.getExtension("WEBGL_compressed_texture_s3tc") || e.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");
+ break;
+ case "WEBGL_compressed_texture_pvrtc":
+ r = e.getExtension("WEBGL_compressed_texture_pvrtc") || e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");
+ break;
+ default: r = e.getExtension(n);
+ }
+ return t[n] = r, r;
+ }
+ return {
+ has: function(e) {
+ return n(e) !== null;
+ },
+ init: function() {
+ n("EXT_color_buffer_float"), n("WEBGL_clip_cull_distance"), n("OES_texture_float_linear"), n("EXT_color_buffer_half_float"), n("WEBGL_multisampled_render_to_texture"), n("WEBGL_render_shared_exponent");
+ },
+ get: function(e) {
+ let t = n(e);
+ return t === null && jt("THREE.WebGLRenderer: " + e + " extension not supported."), t;
+ }
+ };
+}
+function Us(e, t, n, r) {
+ let i = {}, a = /* @__PURE__ */ new WeakMap();
+ function o(e) {
+ let s = e.target;
+ s.index !== null && t.remove(s.index);
+ for (let e in s.attributes) t.remove(s.attributes[e]);
+ s.removeEventListener("dispose", o), delete i[s.id];
+ let c = a.get(s);
+ c && (t.remove(c), a.delete(s)), r.releaseStatesOfGeometry(s), s.isInstancedBufferGeometry === !0 && delete s._maxInstanceCount, n.memory.geometries--;
+ }
+ function s(e, t) {
+ return i[t.id] === !0 ? t : (t.addEventListener("dispose", o), i[t.id] = !0, n.memory.geometries++, t);
+ }
+ function c(n) {
+ let r = n.attributes;
+ for (let n in r) t.update(r[n], e.ARRAY_BUFFER);
+ }
+ function l(e) {
+ let n = [], r = e.index, i = e.attributes.position, o = 0;
+ if (r !== null) {
+ let e = r.array;
+ o = r.version;
+ for (let t = 0, r = e.length; t < r; t += 3) {
+ let r = e[t + 0], i = e[t + 1], a = e[t + 2];
+ n.push(r, i, i, a, a, r);
+ }
+ } else if (i !== void 0) {
+ let e = i.array;
+ o = i.version;
+ for (let t = 0, r = e.length / 3 - 1; t < r; t += 3) {
+ let e = t + 0, r = t + 1, i = t + 2;
+ n.push(e, r, r, i, i, e);
+ }
+ } else return;
+ let s = new (Dt(n) ? Fr : Pr)(n, 1);
+ s.version = o;
+ let c = a.get(e);
+ c && t.remove(c), a.set(e, s);
+ }
+ function u(e) {
+ let t = a.get(e);
+ if (t) {
+ let n = e.index;
+ n !== null && t.version < n.version && l(e);
+ } else l(e);
+ return a.get(e);
+ }
+ return {
+ get: s,
+ update: c,
+ getWireframeAttribute: u
+ };
+}
+function Ws(e, t, n) {
+ let r;
+ function i(e) {
+ r = e;
+ }
+ let a, o;
+ function s(e) {
+ a = e.type, o = e.bytesPerElement;
+ }
+ function c(t, i) {
+ e.drawElements(r, i, a, t * o), n.update(i, r, 1);
+ }
+ function l(t, i, s) {
+ s !== 0 && (e.drawElementsInstanced(r, i, a, t * o, s), n.update(i, r, s));
+ }
+ function u(e, i, o) {
+ if (o === 0) return;
+ t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(r, i, 0, a, e, 0, o);
+ let s = 0;
+ for (let e = 0; e < o; e++) s += i[e];
+ n.update(s, r, 1);
+ }
+ function d(e, i, s, c) {
+ if (s === 0) return;
+ let u = t.get("WEBGL_multi_draw");
+ if (u === null) for (let t = 0; t < e.length; t++) l(e[t] / o, i[t], c[t]);
+ else {
+ u.multiDrawElementsInstancedWEBGL(r, i, 0, a, e, 0, c, 0, s);
+ let t = 0;
+ for (let e = 0; e < s; e++) t += i[e] * c[e];
+ n.update(t, r, 1);
+ }
+ }
+ this.setMode = i, this.setIndex = s, this.render = c, this.renderInstances = l, this.renderMultiDraw = u, this.renderMultiDrawInstances = d;
+}
+function Gs(e) {
+ let t = {
+ geometries: 0,
+ textures: 0
+ }, n = {
+ frame: 0,
+ calls: 0,
+ triangles: 0,
+ points: 0,
+ lines: 0
+ };
+ function r(t, r, i) {
+ switch (n.calls++, r) {
+ case e.TRIANGLES:
+ n.triangles += t / 3 * i;
+ break;
+ case e.LINES:
+ n.lines += t / 2 * i;
+ break;
+ case e.LINE_STRIP:
+ n.lines += i * (t - 1);
+ break;
+ case e.LINE_LOOP:
+ n.lines += i * t;
+ break;
+ case e.POINTS:
+ n.points += i * t;
+ break;
+ default:
+ console.error("THREE.WebGLInfo: Unknown draw mode:", r);
+ break;
+ }
+ }
+ function i() {
+ n.calls = 0, n.triangles = 0, n.points = 0, n.lines = 0;
+ }
+ return {
+ memory: t,
+ render: n,
+ programs: null,
+ autoReset: !0,
+ reset: i,
+ update: r
+ };
+}
+function Ks(e, t, n) {
+ let r = /* @__PURE__ */ new WeakMap(), i = new Jt();
+ function a(a, o, s) {
+ let c = a.morphTargetInfluences, l = o.morphAttributes.position || o.morphAttributes.normal || o.morphAttributes.color, u = l === void 0 ? 0 : l.length, d = r.get(o);
+ if (d === void 0 || d.count !== u) {
+ d !== void 0 && d.texture.dispose();
+ let e = o.morphAttributes.position !== void 0, n = o.morphAttributes.normal !== void 0, a = o.morphAttributes.color !== void 0, s = o.morphAttributes.position || [], c = o.morphAttributes.normal || [], l = o.morphAttributes.color || [], f = 0;
+ e === !0 && (f = 1), n === !0 && (f = 2), a === !0 && (f = 3);
+ let p = o.attributes.position.count * f, m = 1;
+ p > t.maxTextureSize && (m = Math.ceil(p / t.maxTextureSize), p = t.maxTextureSize);
+ let h = new Float32Array(p * m * 4 * u), g = new Zt(h, p, m, u);
+ g.type = b, g.needsUpdate = !0;
+ let _ = f * 4;
+ for (let t = 0; t < u; t++) {
+ let r = s[t], o = c[t], u = l[t], d = p * m * 4 * t;
+ for (let t = 0; t < r.count; t++) {
+ let s = t * _;
+ e === !0 && (i.fromBufferAttribute(r, t), h[d + s + 0] = i.x, h[d + s + 1] = i.y, h[d + s + 2] = i.z, h[d + s + 3] = 0), n === !0 && (i.fromBufferAttribute(o, t), h[d + s + 4] = i.x, h[d + s + 5] = i.y, h[d + s + 6] = i.z, h[d + s + 7] = 0), a === !0 && (i.fromBufferAttribute(u, t), h[d + s + 8] = i.x, h[d + s + 9] = i.y, h[d + s + 10] = i.z, h[d + s + 11] = u.itemSize === 4 ? i.w : 1);
+ }
+ }
+ d = {
+ count: u,
+ texture: g,
+ size: new L(p, m)
+ }, r.set(o, d);
+ function v() {
+ g.dispose(), r.delete(o), o.removeEventListener("dispose", v);
+ }
+ o.addEventListener("dispose", v);
+ }
+ if (a.isInstancedMesh === !0 && a.morphTexture !== null) s.getUniforms().setValue(e, "morphTexture", a.morphTexture, n);
+ else {
+ let t = 0;
+ for (let e = 0; e < c.length; e++) t += c[e];
+ let n = o.morphTargetsRelative ? 1 : 1 - t;
+ s.getUniforms().setValue(e, "morphTargetBaseInfluence", n), s.getUniforms().setValue(e, "morphTargetInfluences", c);
+ }
+ s.getUniforms().setValue(e, "morphTargetsTexture", d.texture, n), s.getUniforms().setValue(e, "morphTargetsTextureSize", d.size);
+ }
+ return { update: a };
+}
+function qs(e, t, n, r) {
+ let i = /* @__PURE__ */ new WeakMap();
+ function a(a) {
+ let o = r.render.frame, c = a.geometry, l = t.get(a, c);
+ if (i.get(l) !== o && (t.update(l), i.set(l, o)), a.isInstancedMesh && (a.hasEventListener("dispose", s) === !1 && a.addEventListener("dispose", s), i.get(a) !== o && (n.update(a.instanceMatrix, e.ARRAY_BUFFER), a.instanceColor !== null && n.update(a.instanceColor, e.ARRAY_BUFFER), i.set(a, o))), a.isSkinnedMesh) {
+ let e = a.skeleton;
+ i.get(e) !== o && (e.update(), i.set(e, o));
+ }
+ return l;
+ }
+ function o() {
+ i = /* @__PURE__ */ new WeakMap();
+ }
+ function s(e) {
+ let t = e.target;
+ t.removeEventListener("dispose", s), n.remove(t.instanceMatrix), t.instanceColor !== null && n.remove(t.instanceColor);
+ }
+ return {
+ update: a,
+ dispose: o
+ };
+}
+var Js = /* @__PURE__ */ new qt(), Ys = /* @__PURE__ */ new Ma(1, 1), Xs = /* @__PURE__ */ new Zt(), Zs = /* @__PURE__ */ new Qt(), Qs = /* @__PURE__ */ new Si(), $s = [], ec = [], tc = new Float32Array(16), nc = new Float32Array(9), rc = new Float32Array(4);
+function ic(e, t, n) {
+ let r = e[0];
+ if (r <= 0 || r > 0) return e;
+ let i = t * n, a = $s[i];
+ if (a === void 0 && (a = new Float32Array(i), $s[i] = a), t !== 0) {
+ r.toArray(a, 0);
+ for (let r = 1, i = 0; r !== t; ++r) i += n, e[r].toArray(a, i);
+ }
+ return a;
+}
+function ac(e, t) {
+ if (e.length !== t.length) return !1;
+ for (let n = 0, r = e.length; n < r; n++) if (e[n] !== t[n]) return !1;
+ return !0;
+}
+function oc(e, t) {
+ for (let n = 0, r = t.length; n < r; n++) e[n] = t[n];
+}
+function sc(e, t) {
+ let n = ec[t];
+ n === void 0 && (n = new Int32Array(t), ec[t] = n);
+ for (let r = 0; r !== t; ++r) n[r] = e.allocateTextureUnit();
+ return n;
+}
+function cc(e, t) {
+ let n = this.cache;
+ n[0] !== t && (e.uniform1f(this.addr, t), n[0] = t);
+}
+function lc(e, t) {
+ let n = this.cache;
+ if (t.x !== void 0) (n[0] !== t.x || n[1] !== t.y) && (e.uniform2f(this.addr, t.x, t.y), n[0] = t.x, n[1] = t.y);
+ else {
+ if (ac(n, t)) return;
+ e.uniform2fv(this.addr, t), oc(n, t);
+ }
+}
+function uc(e, t) {
+ let n = this.cache;
+ if (t.x !== void 0) (n[0] !== t.x || n[1] !== t.y || n[2] !== t.z) && (e.uniform3f(this.addr, t.x, t.y, t.z), n[0] = t.x, n[1] = t.y, n[2] = t.z);
+ else if (t.r !== void 0) (n[0] !== t.r || n[1] !== t.g || n[2] !== t.b) && (e.uniform3f(this.addr, t.r, t.g, t.b), n[0] = t.r, n[1] = t.g, n[2] = t.b);
+ else {
+ if (ac(n, t)) return;
+ e.uniform3fv(this.addr, t), oc(n, t);
+ }
+}
+function dc(e, t) {
+ let n = this.cache;
+ if (t.x !== void 0) (n[0] !== t.x || n[1] !== t.y || n[2] !== t.z || n[3] !== t.w) && (e.uniform4f(this.addr, t.x, t.y, t.z, t.w), n[0] = t.x, n[1] = t.y, n[2] = t.z, n[3] = t.w);
+ else {
+ if (ac(n, t)) return;
+ e.uniform4fv(this.addr, t), oc(n, t);
+ }
+}
+function fc(e, t) {
+ let n = this.cache, r = t.elements;
+ if (r === void 0) {
+ if (ac(n, t)) return;
+ e.uniformMatrix2fv(this.addr, !1, t), oc(n, t);
+ } else {
+ if (ac(n, r)) return;
+ rc.set(r), e.uniformMatrix2fv(this.addr, !1, rc), oc(n, r);
+ }
+}
+function pc(e, t) {
+ let n = this.cache, r = t.elements;
+ if (r === void 0) {
+ if (ac(n, t)) return;
+ e.uniformMatrix3fv(this.addr, !1, t), oc(n, t);
+ } else {
+ if (ac(n, r)) return;
+ nc.set(r), e.uniformMatrix3fv(this.addr, !1, nc), oc(n, r);
+ }
+}
+function mc(e, t) {
+ let n = this.cache, r = t.elements;
+ if (r === void 0) {
+ if (ac(n, t)) return;
+ e.uniformMatrix4fv(this.addr, !1, t), oc(n, t);
+ } else {
+ if (ac(n, r)) return;
+ tc.set(r), e.uniformMatrix4fv(this.addr, !1, tc), oc(n, r);
+ }
+}
+function hc(e, t) {
+ let n = this.cache;
+ n[0] !== t && (e.uniform1i(this.addr, t), n[0] = t);
+}
+function gc(e, t) {
+ let n = this.cache;
+ if (t.x !== void 0) (n[0] !== t.x || n[1] !== t.y) && (e.uniform2i(this.addr, t.x, t.y), n[0] = t.x, n[1] = t.y);
+ else {
+ if (ac(n, t)) return;
+ e.uniform2iv(this.addr, t), oc(n, t);
+ }
+}
+function _c(e, t) {
+ let n = this.cache;
+ if (t.x !== void 0) (n[0] !== t.x || n[1] !== t.y || n[2] !== t.z) && (e.uniform3i(this.addr, t.x, t.y, t.z), n[0] = t.x, n[1] = t.y, n[2] = t.z);
+ else {
+ if (ac(n, t)) return;
+ e.uniform3iv(this.addr, t), oc(n, t);
+ }
+}
+function vc(e, t) {
+ let n = this.cache;
+ if (t.x !== void 0) (n[0] !== t.x || n[1] !== t.y || n[2] !== t.z || n[3] !== t.w) && (e.uniform4i(this.addr, t.x, t.y, t.z, t.w), n[0] = t.x, n[1] = t.y, n[2] = t.z, n[3] = t.w);
+ else {
+ if (ac(n, t)) return;
+ e.uniform4iv(this.addr, t), oc(n, t);
+ }
+}
+function yc(e, t) {
+ let n = this.cache;
+ n[0] !== t && (e.uniform1ui(this.addr, t), n[0] = t);
+}
+function bc(e, t) {
+ let n = this.cache;
+ if (t.x !== void 0) (n[0] !== t.x || n[1] !== t.y) && (e.uniform2ui(this.addr, t.x, t.y), n[0] = t.x, n[1] = t.y);
+ else {
+ if (ac(n, t)) return;
+ e.uniform2uiv(this.addr, t), oc(n, t);
+ }
+}
+function xc(e, t) {
+ let n = this.cache;
+ if (t.x !== void 0) (n[0] !== t.x || n[1] !== t.y || n[2] !== t.z) && (e.uniform3ui(this.addr, t.x, t.y, t.z), n[0] = t.x, n[1] = t.y, n[2] = t.z);
+ else {
+ if (ac(n, t)) return;
+ e.uniform3uiv(this.addr, t), oc(n, t);
+ }
+}
+function Sc(e, t) {
+ let n = this.cache;
+ if (t.x !== void 0) (n[0] !== t.x || n[1] !== t.y || n[2] !== t.z || n[3] !== t.w) && (e.uniform4ui(this.addr, t.x, t.y, t.z, t.w), n[0] = t.x, n[1] = t.y, n[2] = t.z, n[3] = t.w);
+ else {
+ if (ac(n, t)) return;
+ e.uniform4uiv(this.addr, t), oc(n, t);
+ }
+}
+function Cc(e, t, n) {
+ let r = this.cache, i = n.allocateTextureUnit();
+ r[0] !== i && (e.uniform1i(this.addr, i), r[0] = i);
+ let a;
+ this.type === e.SAMPLER_2D_SHADOW ? (Ys.compareFunction = 515, a = Ys) : a = Js, n.setTexture2D(t || a, i);
+}
+function wc(e, t, n) {
+ let r = this.cache, i = n.allocateTextureUnit();
+ r[0] !== i && (e.uniform1i(this.addr, i), r[0] = i), n.setTexture3D(t || Zs, i);
+}
+function Tc(e, t, n) {
+ let r = this.cache, i = n.allocateTextureUnit();
+ r[0] !== i && (e.uniform1i(this.addr, i), r[0] = i), n.setTextureCube(t || Qs, i);
+}
+function Ec(e, t, n) {
+ let r = this.cache, i = n.allocateTextureUnit();
+ r[0] !== i && (e.uniform1i(this.addr, i), r[0] = i), n.setTexture2DArray(t || Xs, i);
+}
+function Dc(e) {
+ switch (e) {
+ case 5126: return cc;
+ case 35664: return lc;
+ case 35665: return uc;
+ case 35666: return dc;
+ case 35674: return fc;
+ case 35675: return pc;
+ case 35676: return mc;
+ case 5124:
+ case 35670: return hc;
+ case 35667:
+ case 35671: return gc;
+ case 35668:
+ case 35672: return _c;
+ case 35669:
+ case 35673: return vc;
+ case 5125: return yc;
+ case 36294: return bc;
+ case 36295: return xc;
+ case 36296: return Sc;
+ case 35678:
+ case 36198:
+ case 36298:
+ case 36306:
+ case 35682: return Cc;
+ case 35679:
+ case 36299:
+ case 36307: return wc;
+ case 35680:
+ case 36300:
+ case 36308:
+ case 36293: return Tc;
+ case 36289:
+ case 36303:
+ case 36311:
+ case 36292: return Ec;
+ }
+}
+function Oc(e, t) {
+ e.uniform1fv(this.addr, t);
+}
+function kc(e, t) {
+ let n = ic(t, this.size, 2);
+ e.uniform2fv(this.addr, n);
+}
+function Ac(e, t) {
+ let n = ic(t, this.size, 3);
+ e.uniform3fv(this.addr, n);
+}
+function jc(e, t) {
+ let n = ic(t, this.size, 4);
+ e.uniform4fv(this.addr, n);
+}
+function Mc(e, t) {
+ let n = ic(t, this.size, 4);
+ e.uniformMatrix2fv(this.addr, !1, n);
+}
+function Nc(e, t) {
+ let n = ic(t, this.size, 9);
+ e.uniformMatrix3fv(this.addr, !1, n);
+}
+function Pc(e, t) {
+ let n = ic(t, this.size, 16);
+ e.uniformMatrix4fv(this.addr, !1, n);
+}
+function Fc(e, t) {
+ e.uniform1iv(this.addr, t);
+}
+function Ic(e, t) {
+ e.uniform2iv(this.addr, t);
+}
+function Lc(e, t) {
+ e.uniform3iv(this.addr, t);
+}
+function Rc(e, t) {
+ e.uniform4iv(this.addr, t);
+}
+function zc(e, t) {
+ e.uniform1uiv(this.addr, t);
+}
+function Bc(e, t) {
+ e.uniform2uiv(this.addr, t);
+}
+function Vc(e, t) {
+ e.uniform3uiv(this.addr, t);
+}
+function Hc(e, t) {
+ e.uniform4uiv(this.addr, t);
+}
+function Uc(e, t, n) {
+ let r = this.cache, i = t.length, a = sc(n, i);
+ ac(r, a) || (e.uniform1iv(this.addr, a), oc(r, a));
+ for (let e = 0; e !== i; ++e) n.setTexture2D(t[e] || Js, a[e]);
+}
+function Wc(e, t, n) {
+ let r = this.cache, i = t.length, a = sc(n, i);
+ ac(r, a) || (e.uniform1iv(this.addr, a), oc(r, a));
+ for (let e = 0; e !== i; ++e) n.setTexture3D(t[e] || Zs, a[e]);
+}
+function Gc(e, t, n) {
+ let r = this.cache, i = t.length, a = sc(n, i);
+ ac(r, a) || (e.uniform1iv(this.addr, a), oc(r, a));
+ for (let e = 0; e !== i; ++e) n.setTextureCube(t[e] || Qs, a[e]);
+}
+function Kc(e, t, n) {
+ let r = this.cache, i = t.length, a = sc(n, i);
+ ac(r, a) || (e.uniform1iv(this.addr, a), oc(r, a));
+ for (let e = 0; e !== i; ++e) n.setTexture2DArray(t[e] || Xs, a[e]);
+}
+function qc(e) {
+ switch (e) {
+ case 5126: return Oc;
+ case 35664: return kc;
+ case 35665: return Ac;
+ case 35666: return jc;
+ case 35674: return Mc;
+ case 35675: return Nc;
+ case 35676: return Pc;
+ case 5124:
+ case 35670: return Fc;
+ case 35667:
+ case 35671: return Ic;
+ case 35668:
+ case 35672: return Lc;
+ case 35669:
+ case 35673: return Rc;
+ case 5125: return zc;
+ case 36294: return Bc;
+ case 36295: return Vc;
+ case 36296: return Hc;
+ case 35678:
+ case 36198:
+ case 36298:
+ case 36306:
+ case 35682: return Uc;
+ case 35679:
+ case 36299:
+ case 36307: return Wc;
+ case 35680:
+ case 36300:
+ case 36308:
+ case 36293: return Gc;
+ case 36289:
+ case 36303:
+ case 36311:
+ case 36292: return Kc;
+ }
+}
+var Jc = class {
+ constructor(e, t, n) {
+ this.id = e, this.addr = n, this.cache = [], this.type = t.type, this.setValue = Dc(t.type);
+ }
+}, Yc = class {
+ constructor(e, t, n) {
+ this.id = e, this.addr = n, this.cache = [], this.type = t.type, this.size = t.size, this.setValue = qc(t.type);
+ }
+}, Xc = class {
+ constructor(e) {
+ this.id = e, this.seq = [], this.map = {};
+ }
+ setValue(e, t, n) {
+ let r = this.seq;
+ for (let i = 0, a = r.length; i !== a; ++i) {
+ let a = r[i];
+ a.setValue(e, t[a.id], n);
+ }
+ }
+}, Zc = /(\w+)(\])?(\[|\.)?/g;
+function Qc(e, t) {
+ e.seq.push(t), e.map[t.id] = t;
+}
+function $c(e, t, n) {
+ let r = e.name, i = r.length;
+ for (Zc.lastIndex = 0;;) {
+ let a = Zc.exec(r), o = Zc.lastIndex, s = a[1], c = a[2] === "]", l = a[3];
+ if (c && (s |= 0), l === void 0 || l === "[" && o + 2 === i) {
+ Qc(n, l === void 0 ? new Jc(s, e, t) : new Yc(s, e, t));
+ break;
+ } else {
+ let e = n.map[s];
+ e === void 0 && (e = new Xc(s), Qc(n, e)), n = e;
+ }
+ }
+}
+var el = class {
+ constructor(e, t) {
+ this.seq = [], this.map = {};
+ let n = e.getProgramParameter(t, e.ACTIVE_UNIFORMS);
+ for (let r = 0; r < n; ++r) {
+ let n = e.getActiveUniform(t, r);
+ $c(n, e.getUniformLocation(t, n.name), this);
+ }
+ }
+ setValue(e, t, n, r) {
+ let i = this.map[t];
+ i !== void 0 && i.setValue(e, n, r);
+ }
+ setOptional(e, t, n) {
+ let r = t[n];
+ r !== void 0 && this.setValue(e, n, r);
+ }
+ static upload(e, t, n, r) {
+ for (let i = 0, a = t.length; i !== a; ++i) {
+ let a = t[i], o = n[a.id];
+ o.needsUpdate !== !1 && a.setValue(e, o.value, r);
+ }
+ }
+ static seqWithValue(e, t) {
+ let n = [];
+ for (let r = 0, i = e.length; r !== i; ++r) {
+ let i = e[r];
+ i.id in t && n.push(i);
+ }
+ return n;
+ }
+};
+function tl(e, t, n) {
+ let r = e.createShader(t);
+ return e.shaderSource(r, n), e.compileShader(r), r;
+}
+var nl = 37297, rl = 0;
+function il(e, t) {
+ let n = e.split("\n"), r = [], i = Math.max(t - 6, 0), a = Math.min(t + 6, n.length);
+ for (let e = i; e < a; e++) {
+ let i = e + 1;
+ r.push(`${i === t ? ">" : " "} ${i}: ${n[e]}`);
+ }
+ return r.join("\n");
+}
+var al = /* @__PURE__ */ new Tt();
+function ol(e) {
+ Rt._getMatrix(al, Rt.workingColorSpace, e);
+ let t = `mat3( ${al.elements.map((e) => e.toFixed(4))} )`;
+ switch (Rt.getTransfer(e)) {
+ case qe: return [t, "LinearTransferOETF"];
+ case Je: return [t, "sRGBTransferOETF"];
+ default: return console.warn("THREE.WebGLProgram: Unsupported color space: ", e), [t, "LinearTransferOETF"];
+ }
+}
+function sl(e, t, n) {
+ let r = e.getShaderParameter(t, e.COMPILE_STATUS), i = e.getShaderInfoLog(t).trim();
+ if (r && i === "") return "";
+ let a = /ERROR: 0:(\d+)/.exec(i);
+ if (a) {
+ let r = parseInt(a[1]);
+ return n.toUpperCase() + "\n\n" + i + "\n\n" + il(e.getShaderSource(t), r);
+ } else return i;
+}
+function cl(e, t) {
+ let n = ol(t);
+ return [
+ `vec4 ${e}( vec4 value ) {`,
+ ` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,
+ "}"
+ ].join("\n");
+}
+function ll(e, t) {
+ let n;
+ switch (t) {
+ case 1:
+ n = "Linear";
+ break;
+ case 2:
+ n = "Reinhard";
+ break;
+ case 3:
+ n = "Cineon";
+ break;
+ case 4:
+ n = "ACESFilmic";
+ break;
+ case 6:
+ n = "AgX";
+ break;
+ case 7:
+ n = "Neutral";
+ break;
+ case 5:
+ n = "Custom";
+ break;
+ default: console.warn("THREE.WebGLProgram: Unsupported toneMapping:", t), n = "Linear";
+ }
+ return "vec3 " + e + "( vec3 color ) { return " + n + "ToneMapping( color ); }";
+}
+var ul = /* @__PURE__ */ new R();
+function dl() {
+ return Rt.getLuminanceCoefficients(ul), [
+ "float luminance( const in vec3 rgb ) {",
+ ` const vec3 weights = vec3( ${ul.x.toFixed(4)}, ${ul.y.toFixed(4)}, ${ul.z.toFixed(4)} );`,
+ " return dot( weights, rgb );",
+ "}"
+ ].join("\n");
+}
+function fl(e) {
+ return [e.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "", e.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : ""].filter(hl).join("\n");
+}
+function pl(e) {
+ let t = [];
+ for (let n in e) {
+ let r = e[n];
+ r !== !1 && t.push("#define " + n + " " + r);
+ }
+ return t.join("\n");
+}
+function ml(e, t) {
+ let n = {}, r = e.getProgramParameter(t, e.ACTIVE_ATTRIBUTES);
+ for (let i = 0; i < r; i++) {
+ let r = e.getActiveAttrib(t, i), a = r.name, o = 1;
+ r.type === e.FLOAT_MAT2 && (o = 2), r.type === e.FLOAT_MAT3 && (o = 3), r.type === e.FLOAT_MAT4 && (o = 4), n[a] = {
+ type: r.type,
+ location: e.getAttribLocation(t, a),
+ locationSize: o
+ };
+ }
+ return n;
+}
+function hl(e) {
+ return e !== "";
+}
+function gl(e, t) {
+ let n = t.numSpotLightShadows + t.numSpotLightMaps - t.numSpotLightShadowsWithMaps;
+ return e.replace(/NUM_DIR_LIGHTS/g, t.numDirLights).replace(/NUM_SPOT_LIGHTS/g, t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, n).replace(/NUM_RECT_AREA_LIGHTS/g, t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, t.numPointLights).replace(/NUM_HEMI_LIGHTS/g, t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, t.numPointLightShadows);
+}
+function _l(e, t) {
+ return e.replace(/NUM_CLIPPING_PLANES/g, t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, t.numClippingPlanes - t.numClipIntersection);
+}
+var vl = /^[ \t]*#include +<([\w\d./]+)>/gm;
+function yl(e) {
+ return e.replace(vl, xl);
+}
+var bl = /* @__PURE__ */ new Map();
+function xl(e, t) {
+ let n = V[t];
+ if (n === void 0) {
+ let e = bl.get(t);
+ if (e !== void 0) n = V[e], console.warn("THREE.WebGLRenderer: Shader chunk \"%s\" has been deprecated. Use \"%s\" instead.", t, e);
+ else throw Error("Can not resolve #include <" + t + ">");
+ }
+ return yl(n);
+}
+var Sl = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
+function Cl(e) {
+ return e.replace(Sl, wl);
+}
+function wl(e, t, n, r) {
+ let i = "";
+ for (let e = parseInt(t); e < parseInt(n); e++) i += r.replace(/\[\s*i\s*\]/g, "[ " + e + " ]").replace(/UNROLLED_LOOP_INDEX/g, e);
+ return i;
+}
+function Tl(e) {
+ let t = `precision ${e.precision} float;
+ precision ${e.precision} int;
+ precision ${e.precision} sampler2D;
+ precision ${e.precision} samplerCube;
+ precision ${e.precision} sampler3D;
+ precision ${e.precision} sampler2DArray;
+ precision ${e.precision} sampler2DShadow;
+ precision ${e.precision} samplerCubeShadow;
+ precision ${e.precision} sampler2DArrayShadow;
+ precision ${e.precision} isampler2D;
+ precision ${e.precision} isampler3D;
+ precision ${e.precision} isamplerCube;
+ precision ${e.precision} isampler2DArray;
+ precision ${e.precision} usampler2D;
+ precision ${e.precision} usampler3D;
+ precision ${e.precision} usamplerCube;
+ precision ${e.precision} usampler2DArray;
+ `;
+ return e.precision === "highp" ? t += "\n#define HIGH_PRECISION" : e.precision === "mediump" ? t += "\n#define MEDIUM_PRECISION" : e.precision === "lowp" && (t += "\n#define LOW_PRECISION"), t;
+}
+function El(e) {
+ let t = "SHADOWMAP_TYPE_BASIC";
+ return e.shadowMapType === 1 ? t = "SHADOWMAP_TYPE_PCF" : e.shadowMapType === 2 ? t = "SHADOWMAP_TYPE_PCF_SOFT" : e.shadowMapType === 3 && (t = "SHADOWMAP_TYPE_VSM"), t;
+}
+function Dl(e) {
+ let t = "ENVMAP_TYPE_CUBE";
+ if (e.envMap) switch (e.envMapMode) {
+ case 301:
+ case 302:
+ t = "ENVMAP_TYPE_CUBE";
+ break;
+ case 306:
+ t = "ENVMAP_TYPE_CUBE_UV";
+ break;
+ }
+ return t;
+}
+function Ol(e) {
+ let t = "ENVMAP_MODE_REFLECTION";
+ if (e.envMap) switch (e.envMapMode) {
+ case 302:
+ t = "ENVMAP_MODE_REFRACTION";
+ break;
+ }
+ return t;
+}
+function kl(e) {
+ let t = "ENVMAP_BLENDING_NONE";
+ if (e.envMap) switch (e.combine) {
+ case 0:
+ t = "ENVMAP_BLENDING_MULTIPLY";
+ break;
+ case 1:
+ t = "ENVMAP_BLENDING_MIX";
+ break;
+ case 2:
+ t = "ENVMAP_BLENDING_ADD";
+ break;
+ }
+ return t;
+}
+function Al(e) {
+ let t = e.envMapCubeUVHeight;
+ if (t === null) return null;
+ let n = Math.log2(t) - 2, r = 1 / t;
+ return {
+ texelWidth: 1 / (3 * Math.max(2 ** n, 112)),
+ texelHeight: r,
+ maxMip: n
+ };
+}
+function jl(e, t, n, r) {
+ let i = e.getContext(), a = n.defines, o = n.vertexShader, s = n.fragmentShader, c = El(n), l = Dl(n), u = Ol(n), d = kl(n), f = Al(n), p = fl(n), m = pl(a), h = i.createProgram(), g, _, v = n.glslVersion ? "#version " + n.glslVersion + "\n" : "";
+ n.isRawShaderMaterial ? (g = [
+ "#define SHADER_TYPE " + n.shaderType,
+ "#define SHADER_NAME " + n.shaderName,
+ m
+ ].filter(hl).join("\n"), g.length > 0 && (g += "\n"), _ = [
+ "#define SHADER_TYPE " + n.shaderType,
+ "#define SHADER_NAME " + n.shaderName,
+ m
+ ].filter(hl).join("\n"), _.length > 0 && (_ += "\n")) : (g = [
+ Tl(n),
+ "#define SHADER_TYPE " + n.shaderType,
+ "#define SHADER_NAME " + n.shaderName,
+ m,
+ n.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "",
+ n.batching ? "#define USE_BATCHING" : "",
+ n.batchingColor ? "#define USE_BATCHING_COLOR" : "",
+ n.instancing ? "#define USE_INSTANCING" : "",
+ n.instancingColor ? "#define USE_INSTANCING_COLOR" : "",
+ n.instancingMorph ? "#define USE_INSTANCING_MORPH" : "",
+ n.useFog && n.fog ? "#define USE_FOG" : "",
+ n.useFog && n.fogExp2 ? "#define FOG_EXP2" : "",
+ n.map ? "#define USE_MAP" : "",
+ n.envMap ? "#define USE_ENVMAP" : "",
+ n.envMap ? "#define " + u : "",
+ n.lightMap ? "#define USE_LIGHTMAP" : "",
+ n.aoMap ? "#define USE_AOMAP" : "",
+ n.bumpMap ? "#define USE_BUMPMAP" : "",
+ n.normalMap ? "#define USE_NORMALMAP" : "",
+ n.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "",
+ n.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "",
+ n.displacementMap ? "#define USE_DISPLACEMENTMAP" : "",
+ n.emissiveMap ? "#define USE_EMISSIVEMAP" : "",
+ n.anisotropy ? "#define USE_ANISOTROPY" : "",
+ n.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "",
+ n.clearcoatMap ? "#define USE_CLEARCOATMAP" : "",
+ n.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "",
+ n.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "",
+ n.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "",
+ n.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "",
+ n.specularMap ? "#define USE_SPECULARMAP" : "",
+ n.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "",
+ n.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "",
+ n.roughnessMap ? "#define USE_ROUGHNESSMAP" : "",
+ n.metalnessMap ? "#define USE_METALNESSMAP" : "",
+ n.alphaMap ? "#define USE_ALPHAMAP" : "",
+ n.alphaHash ? "#define USE_ALPHAHASH" : "",
+ n.transmission ? "#define USE_TRANSMISSION" : "",
+ n.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "",
+ n.thicknessMap ? "#define USE_THICKNESSMAP" : "",
+ n.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "",
+ n.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "",
+ n.mapUv ? "#define MAP_UV " + n.mapUv : "",
+ n.alphaMapUv ? "#define ALPHAMAP_UV " + n.alphaMapUv : "",
+ n.lightMapUv ? "#define LIGHTMAP_UV " + n.lightMapUv : "",
+ n.aoMapUv ? "#define AOMAP_UV " + n.aoMapUv : "",
+ n.emissiveMapUv ? "#define EMISSIVEMAP_UV " + n.emissiveMapUv : "",
+ n.bumpMapUv ? "#define BUMPMAP_UV " + n.bumpMapUv : "",
+ n.normalMapUv ? "#define NORMALMAP_UV " + n.normalMapUv : "",
+ n.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + n.displacementMapUv : "",
+ n.metalnessMapUv ? "#define METALNESSMAP_UV " + n.metalnessMapUv : "",
+ n.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + n.roughnessMapUv : "",
+ n.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + n.anisotropyMapUv : "",
+ n.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + n.clearcoatMapUv : "",
+ n.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + n.clearcoatNormalMapUv : "",
+ n.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + n.clearcoatRoughnessMapUv : "",
+ n.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + n.iridescenceMapUv : "",
+ n.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + n.iridescenceThicknessMapUv : "",
+ n.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + n.sheenColorMapUv : "",
+ n.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + n.sheenRoughnessMapUv : "",
+ n.specularMapUv ? "#define SPECULARMAP_UV " + n.specularMapUv : "",
+ n.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + n.specularColorMapUv : "",
+ n.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + n.specularIntensityMapUv : "",
+ n.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + n.transmissionMapUv : "",
+ n.thicknessMapUv ? "#define THICKNESSMAP_UV " + n.thicknessMapUv : "",
+ n.vertexTangents && n.flatShading === !1 ? "#define USE_TANGENT" : "",
+ n.vertexColors ? "#define USE_COLOR" : "",
+ n.vertexAlphas ? "#define USE_COLOR_ALPHA" : "",
+ n.vertexUv1s ? "#define USE_UV1" : "",
+ n.vertexUv2s ? "#define USE_UV2" : "",
+ n.vertexUv3s ? "#define USE_UV3" : "",
+ n.pointsUvs ? "#define USE_POINTS_UV" : "",
+ n.flatShading ? "#define FLAT_SHADED" : "",
+ n.skinning ? "#define USE_SKINNING" : "",
+ n.morphTargets ? "#define USE_MORPHTARGETS" : "",
+ n.morphNormals && n.flatShading === !1 ? "#define USE_MORPHNORMALS" : "",
+ n.morphColors ? "#define USE_MORPHCOLORS" : "",
+ n.morphTargetsCount > 0 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + n.morphTextureStride : "",
+ n.morphTargetsCount > 0 ? "#define MORPHTARGETS_COUNT " + n.morphTargetsCount : "",
+ n.doubleSided ? "#define DOUBLE_SIDED" : "",
+ n.flipSided ? "#define FLIP_SIDED" : "",
+ n.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
+ n.shadowMapEnabled ? "#define " + c : "",
+ n.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
+ n.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "",
+ n.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
+ n.reverseDepthBuffer ? "#define USE_REVERSEDEPTHBUF" : "",
+ "uniform mat4 modelMatrix;",
+ "uniform mat4 modelViewMatrix;",
+ "uniform mat4 projectionMatrix;",
+ "uniform mat4 viewMatrix;",
+ "uniform mat3 normalMatrix;",
+ "uniform vec3 cameraPosition;",
+ "uniform bool isOrthographic;",
+ "#ifdef USE_INSTANCING",
+ " attribute mat4 instanceMatrix;",
+ "#endif",
+ "#ifdef USE_INSTANCING_COLOR",
+ " attribute vec3 instanceColor;",
+ "#endif",
+ "#ifdef USE_INSTANCING_MORPH",
+ " uniform sampler2D morphTexture;",
+ "#endif",
+ "attribute vec3 position;",
+ "attribute vec3 normal;",
+ "attribute vec2 uv;",
+ "#ifdef USE_UV1",
+ " attribute vec2 uv1;",
+ "#endif",
+ "#ifdef USE_UV2",
+ " attribute vec2 uv2;",
+ "#endif",
+ "#ifdef USE_UV3",
+ " attribute vec2 uv3;",
+ "#endif",
+ "#ifdef USE_TANGENT",
+ " attribute vec4 tangent;",
+ "#endif",
+ "#if defined( USE_COLOR_ALPHA )",
+ " attribute vec4 color;",
+ "#elif defined( USE_COLOR )",
+ " attribute vec3 color;",
+ "#endif",
+ "#ifdef USE_SKINNING",
+ " attribute vec4 skinIndex;",
+ " attribute vec4 skinWeight;",
+ "#endif",
+ "\n"
+ ].filter(hl).join("\n"), _ = [
+ Tl(n),
+ "#define SHADER_TYPE " + n.shaderType,
+ "#define SHADER_NAME " + n.shaderName,
+ m,
+ n.useFog && n.fog ? "#define USE_FOG" : "",
+ n.useFog && n.fogExp2 ? "#define FOG_EXP2" : "",
+ n.alphaToCoverage ? "#define ALPHA_TO_COVERAGE" : "",
+ n.map ? "#define USE_MAP" : "",
+ n.matcap ? "#define USE_MATCAP" : "",
+ n.envMap ? "#define USE_ENVMAP" : "",
+ n.envMap ? "#define " + l : "",
+ n.envMap ? "#define " + u : "",
+ n.envMap ? "#define " + d : "",
+ f ? "#define CUBEUV_TEXEL_WIDTH " + f.texelWidth : "",
+ f ? "#define CUBEUV_TEXEL_HEIGHT " + f.texelHeight : "",
+ f ? "#define CUBEUV_MAX_MIP " + f.maxMip + ".0" : "",
+ n.lightMap ? "#define USE_LIGHTMAP" : "",
+ n.aoMap ? "#define USE_AOMAP" : "",
+ n.bumpMap ? "#define USE_BUMPMAP" : "",
+ n.normalMap ? "#define USE_NORMALMAP" : "",
+ n.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "",
+ n.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "",
+ n.emissiveMap ? "#define USE_EMISSIVEMAP" : "",
+ n.anisotropy ? "#define USE_ANISOTROPY" : "",
+ n.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "",
+ n.clearcoat ? "#define USE_CLEARCOAT" : "",
+ n.clearcoatMap ? "#define USE_CLEARCOATMAP" : "",
+ n.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "",
+ n.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "",
+ n.dispersion ? "#define USE_DISPERSION" : "",
+ n.iridescence ? "#define USE_IRIDESCENCE" : "",
+ n.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "",
+ n.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "",
+ n.specularMap ? "#define USE_SPECULARMAP" : "",
+ n.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "",
+ n.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "",
+ n.roughnessMap ? "#define USE_ROUGHNESSMAP" : "",
+ n.metalnessMap ? "#define USE_METALNESSMAP" : "",
+ n.alphaMap ? "#define USE_ALPHAMAP" : "",
+ n.alphaTest ? "#define USE_ALPHATEST" : "",
+ n.alphaHash ? "#define USE_ALPHAHASH" : "",
+ n.sheen ? "#define USE_SHEEN" : "",
+ n.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "",
+ n.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "",
+ n.transmission ? "#define USE_TRANSMISSION" : "",
+ n.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "",
+ n.thicknessMap ? "#define USE_THICKNESSMAP" : "",
+ n.vertexTangents && n.flatShading === !1 ? "#define USE_TANGENT" : "",
+ n.vertexColors || n.instancingColor || n.batchingColor ? "#define USE_COLOR" : "",
+ n.vertexAlphas ? "#define USE_COLOR_ALPHA" : "",
+ n.vertexUv1s ? "#define USE_UV1" : "",
+ n.vertexUv2s ? "#define USE_UV2" : "",
+ n.vertexUv3s ? "#define USE_UV3" : "",
+ n.pointsUvs ? "#define USE_POINTS_UV" : "",
+ n.gradientMap ? "#define USE_GRADIENTMAP" : "",
+ n.flatShading ? "#define FLAT_SHADED" : "",
+ n.doubleSided ? "#define DOUBLE_SIDED" : "",
+ n.flipSided ? "#define FLIP_SIDED" : "",
+ n.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
+ n.shadowMapEnabled ? "#define " + c : "",
+ n.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "",
+ n.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "",
+ n.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "",
+ n.decodeVideoTextureEmissive ? "#define DECODE_VIDEO_TEXTURE_EMISSIVE" : "",
+ n.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
+ n.reverseDepthBuffer ? "#define USE_REVERSEDEPTHBUF" : "",
+ "uniform mat4 viewMatrix;",
+ "uniform vec3 cameraPosition;",
+ "uniform bool isOrthographic;",
+ n.toneMapping === 0 ? "" : "#define TONE_MAPPING",
+ n.toneMapping === 0 ? "" : V.tonemapping_pars_fragment,
+ n.toneMapping === 0 ? "" : ll("toneMapping", n.toneMapping),
+ n.dithering ? "#define DITHERING" : "",
+ n.opaque ? "#define OPAQUE" : "",
+ V.colorspace_pars_fragment,
+ cl("linearToOutputTexel", n.outputColorSpace),
+ dl(),
+ n.useDepthPacking ? "#define DEPTH_PACKING " + n.depthPacking : "",
+ "\n"
+ ].filter(hl).join("\n")), o = yl(o), o = gl(o, n), o = _l(o, n), s = yl(s), s = gl(s, n), s = _l(s, n), o = Cl(o), s = Cl(s), n.isRawShaderMaterial !== !0 && (v = "#version 300 es\n", g = [
+ p,
+ "#define attribute in",
+ "#define varying out",
+ "#define texture2D texture"
+ ].join("\n") + "\n" + g, _ = [
+ "#define varying in",
+ n.glslVersion === "300 es" ? "" : "layout(location = 0) out highp vec4 pc_fragColor;",
+ n.glslVersion === "300 es" ? "" : "#define gl_FragColor pc_fragColor",
+ "#define gl_FragDepthEXT gl_FragDepth",
+ "#define texture2D texture",
+ "#define textureCube texture",
+ "#define texture2DProj textureProj",
+ "#define texture2DLodEXT textureLod",
+ "#define texture2DProjLodEXT textureProjLod",
+ "#define textureCubeLodEXT textureLod",
+ "#define texture2DGradEXT textureGrad",
+ "#define texture2DProjGradEXT textureProjGrad",
+ "#define textureCubeGradEXT textureGrad"
+ ].join("\n") + "\n" + _);
+ let y = v + g + o, b = v + _ + s, x = tl(i, i.VERTEX_SHADER, y), S = tl(i, i.FRAGMENT_SHADER, b);
+ i.attachShader(h, x), i.attachShader(h, S), n.index0AttributeName === void 0 ? n.morphTargets === !0 && i.bindAttribLocation(h, 0, "position") : i.bindAttribLocation(h, 0, n.index0AttributeName), i.linkProgram(h);
+ function C(t) {
+ if (e.debug.checkShaderErrors) {
+ let n = i.getProgramInfoLog(h).trim(), r = i.getShaderInfoLog(x).trim(), a = i.getShaderInfoLog(S).trim(), o = !0, s = !0;
+ if (i.getProgramParameter(h, i.LINK_STATUS) === !1) if (o = !1, typeof e.debug.onShaderError == "function") e.debug.onShaderError(i, h, x, S);
+ else {
+ let e = sl(i, x, "vertex"), r = sl(i, S, "fragment");
+ console.error("THREE.WebGLProgram: Shader Error " + i.getError() + " - VALIDATE_STATUS " + i.getProgramParameter(h, i.VALIDATE_STATUS) + "\n\nMaterial Name: " + t.name + "\nMaterial Type: " + t.type + "\n\nProgram Info Log: " + n + "\n" + e + "\n" + r);
+ }
+ else n === "" ? (r === "" || a === "") && (s = !1) : console.warn("THREE.WebGLProgram: Program Info Log:", n);
+ s && (t.diagnostics = {
+ runnable: o,
+ programLog: n,
+ vertexShader: {
+ log: r,
+ prefix: g
+ },
+ fragmentShader: {
+ log: a,
+ prefix: _
+ }
+ });
+ }
+ i.deleteShader(x), i.deleteShader(S), w = new el(i, h), T = ml(i, h);
+ }
+ let w;
+ this.getUniforms = function() {
+ return w === void 0 && C(this), w;
+ };
+ let T;
+ this.getAttributes = function() {
+ return T === void 0 && C(this), T;
+ };
+ let E = n.rendererExtensionParallelShaderCompile === !1;
+ return this.isReady = function() {
+ return E === !1 && (E = i.getProgramParameter(h, nl)), E;
+ }, this.destroy = function() {
+ r.releaseStatesOfProgram(this), i.deleteProgram(h), this.program = void 0;
+ }, this.type = n.shaderType, this.name = n.shaderName, this.id = rl++, this.cacheKey = t, this.usedTimes = 1, this.program = h, this.vertexShader = x, this.fragmentShader = S, this;
+}
+var Ml = 0, Nl = class {
+ constructor() {
+ this.shaderCache = /* @__PURE__ */ new Map(), this.materialCache = /* @__PURE__ */ new Map();
+ }
+ update(e) {
+ let t = e.vertexShader, n = e.fragmentShader, r = this._getShaderStage(t), i = this._getShaderStage(n), a = this._getShaderCacheForMaterial(e);
+ return a.has(r) === !1 && (a.add(r), r.usedTimes++), a.has(i) === !1 && (a.add(i), i.usedTimes++), this;
+ }
+ remove(e) {
+ let t = this.materialCache.get(e);
+ for (let e of t) e.usedTimes--, e.usedTimes === 0 && this.shaderCache.delete(e.code);
+ return this.materialCache.delete(e), this;
+ }
+ getVertexShaderID(e) {
+ return this._getShaderStage(e.vertexShader).id;
+ }
+ getFragmentShaderID(e) {
+ return this._getShaderStage(e.fragmentShader).id;
+ }
+ dispose() {
+ this.shaderCache.clear(), this.materialCache.clear();
+ }
+ _getShaderCacheForMaterial(e) {
+ let t = this.materialCache, n = t.get(e);
+ return n === void 0 && (n = /* @__PURE__ */ new Set(), t.set(e, n)), n;
+ }
+ _getShaderStage(e) {
+ let t = this.shaderCache, n = t.get(e);
+ return n === void 0 && (n = new Pl(e), t.set(e, n)), n;
+ }
+}, Pl = class {
+ constructor(e) {
+ this.id = Ml++, this.code = e, this.usedTimes = 0;
+ }
+};
+function Fl(e, t, n, r, i, a, o) {
+ let s = new Bn(), c = new Nl(), l = /* @__PURE__ */ new Set(), u = [], d = i.logarithmicDepthBuffer, f = i.vertexTextures, p = i.precision, m = {
+ MeshDepthMaterial: "depth",
+ MeshDistanceMaterial: "distanceRGBA",
+ MeshNormalMaterial: "normal",
+ MeshBasicMaterial: "basic",
+ MeshLambertMaterial: "lambert",
+ MeshPhongMaterial: "phong",
+ MeshToonMaterial: "toon",
+ MeshStandardMaterial: "physical",
+ MeshPhysicalMaterial: "physical",
+ MeshMatcapMaterial: "matcap",
+ LineBasicMaterial: "basic",
+ LineDashedMaterial: "dashed",
+ PointsMaterial: "points",
+ ShadowMaterial: "shadow",
+ SpriteMaterial: "sprite"
+ };
+ function h(e) {
+ return l.add(e), e === 0 ? "uv" : `uv${e}`;
+ }
+ function g(a, s, u, g, _) {
+ let v = g.fog, y = _.geometry, b = a.isMeshStandardMaterial ? g.environment : null, x = (a.isMeshStandardMaterial ? n : t).get(a.envMap || b), S = x && x.mapping === 306 ? x.image.height : null, C = m[a.type];
+ a.precision !== null && (p = i.getMaxPrecision(a.precision), p !== a.precision && console.warn("THREE.WebGLProgram.getParameters:", a.precision, "not supported, using", p, "instead."));
+ let w = y.morphAttributes.position || y.morphAttributes.normal || y.morphAttributes.color, T = w === void 0 ? 0 : w.length, E = 0;
+ y.morphAttributes.position !== void 0 && (E = 1), y.morphAttributes.normal !== void 0 && (E = 2), y.morphAttributes.color !== void 0 && (E = 3);
+ let D, O, k, ee;
+ if (C) {
+ let e = us[C];
+ D = e.vertexShader, O = e.fragmentShader;
+ } else D = a.vertexShader, O = a.fragmentShader, c.update(a), k = c.getVertexShaderID(a), ee = c.getFragmentShaderID(a);
+ let A = e.getRenderTarget(), te = e.state.buffers.depth.getReversed(), ne = _.isInstancedMesh === !0, re = _.isBatchedMesh === !0, ie = !!a.map, ae = !!a.matcap, oe = !!x, se = !!a.aoMap, ce = !!a.lightMap, le = !!a.bumpMap, ue = !!a.normalMap, de = !!a.displacementMap, fe = !!a.emissiveMap, pe = !!a.metalnessMap, me = !!a.roughnessMap, he = a.anisotropy > 0, ge = a.clearcoat > 0, _e = a.dispersion > 0, ve = a.iridescence > 0, ye = a.sheen > 0, be = a.transmission > 0, j = he && !!a.anisotropyMap, xe = ge && !!a.clearcoatMap, Se = ge && !!a.clearcoatNormalMap, Ce = ge && !!a.clearcoatRoughnessMap, M = ve && !!a.iridescenceMap, we = ve && !!a.iridescenceThicknessMap, N = ye && !!a.sheenColorMap, P = ye && !!a.sheenRoughnessMap, Te = !!a.specularMap, Ee = !!a.specularColorMap, F = !!a.specularIntensityMap, De = be && !!a.transmissionMap, Oe = be && !!a.thicknessMap, ke = !!a.gradientMap, Ae = !!a.alphaMap, je = a.alphaTest > 0, Me = !!a.alphaHash, Ne = !!a.extensions, Pe = 0;
+ a.toneMapped && (A === null || A.isXRRenderTarget === !0) && (Pe = e.toneMapping);
+ let Fe = {
+ shaderID: C,
+ shaderType: a.type,
+ shaderName: a.name,
+ vertexShader: D,
+ fragmentShader: O,
+ defines: a.defines,
+ customVertexShaderID: k,
+ customFragmentShaderID: ee,
+ isRawShaderMaterial: a.isRawShaderMaterial === !0,
+ glslVersion: a.glslVersion,
+ precision: p,
+ batching: re,
+ batchingColor: re && _._colorsTexture !== null,
+ instancing: ne,
+ instancingColor: ne && _.instanceColor !== null,
+ instancingMorph: ne && _.morphTexture !== null,
+ supportsVertexTextures: f,
+ outputColorSpace: A === null ? e.outputColorSpace : A.isXRRenderTarget === !0 ? A.texture.colorSpace : Ke,
+ alphaToCoverage: !!a.alphaToCoverage,
+ map: ie,
+ matcap: ae,
+ envMap: oe,
+ envMapMode: oe && x.mapping,
+ envMapCubeUVHeight: S,
+ aoMap: se,
+ lightMap: ce,
+ bumpMap: le,
+ normalMap: ue,
+ displacementMap: f && de,
+ emissiveMap: fe,
+ normalMapObjectSpace: ue && a.normalMapType === 1,
+ normalMapTangentSpace: ue && a.normalMapType === 0,
+ metalnessMap: pe,
+ roughnessMap: me,
+ anisotropy: he,
+ anisotropyMap: j,
+ clearcoat: ge,
+ clearcoatMap: xe,
+ clearcoatNormalMap: Se,
+ clearcoatRoughnessMap: Ce,
+ dispersion: _e,
+ iridescence: ve,
+ iridescenceMap: M,
+ iridescenceThicknessMap: we,
+ sheen: ye,
+ sheenColorMap: N,
+ sheenRoughnessMap: P,
+ specularMap: Te,
+ specularColorMap: Ee,
+ specularIntensityMap: F,
+ transmission: be,
+ transmissionMap: De,
+ thicknessMap: Oe,
+ gradientMap: ke,
+ opaque: a.transparent === !1 && a.blending === 1 && a.alphaToCoverage === !1,
+ alphaMap: Ae,
+ alphaTest: je,
+ alphaHash: Me,
+ combine: a.combine,
+ mapUv: ie && h(a.map.channel),
+ aoMapUv: se && h(a.aoMap.channel),
+ lightMapUv: ce && h(a.lightMap.channel),
+ bumpMapUv: le && h(a.bumpMap.channel),
+ normalMapUv: ue && h(a.normalMap.channel),
+ displacementMapUv: de && h(a.displacementMap.channel),
+ emissiveMapUv: fe && h(a.emissiveMap.channel),
+ metalnessMapUv: pe && h(a.metalnessMap.channel),
+ roughnessMapUv: me && h(a.roughnessMap.channel),
+ anisotropyMapUv: j && h(a.anisotropyMap.channel),
+ clearcoatMapUv: xe && h(a.clearcoatMap.channel),
+ clearcoatNormalMapUv: Se && h(a.clearcoatNormalMap.channel),
+ clearcoatRoughnessMapUv: Ce && h(a.clearcoatRoughnessMap.channel),
+ iridescenceMapUv: M && h(a.iridescenceMap.channel),
+ iridescenceThicknessMapUv: we && h(a.iridescenceThicknessMap.channel),
+ sheenColorMapUv: N && h(a.sheenColorMap.channel),
+ sheenRoughnessMapUv: P && h(a.sheenRoughnessMap.channel),
+ specularMapUv: Te && h(a.specularMap.channel),
+ specularColorMapUv: Ee && h(a.specularColorMap.channel),
+ specularIntensityMapUv: F && h(a.specularIntensityMap.channel),
+ transmissionMapUv: De && h(a.transmissionMap.channel),
+ thicknessMapUv: Oe && h(a.thicknessMap.channel),
+ alphaMapUv: Ae && h(a.alphaMap.channel),
+ vertexTangents: !!y.attributes.tangent && (ue || he),
+ vertexColors: a.vertexColors,
+ vertexAlphas: a.vertexColors === !0 && !!y.attributes.color && y.attributes.color.itemSize === 4,
+ pointsUvs: _.isPoints === !0 && !!y.attributes.uv && (ie || Ae),
+ fog: !!v,
+ useFog: a.fog === !0,
+ fogExp2: !!v && v.isFogExp2,
+ flatShading: a.flatShading === !0,
+ sizeAttenuation: a.sizeAttenuation === !0,
+ logarithmicDepthBuffer: d,
+ reverseDepthBuffer: te,
+ skinning: _.isSkinnedMesh === !0,
+ morphTargets: y.morphAttributes.position !== void 0,
+ morphNormals: y.morphAttributes.normal !== void 0,
+ morphColors: y.morphAttributes.color !== void 0,
+ morphTargetsCount: T,
+ morphTextureStride: E,
+ numDirLights: s.directional.length,
+ numPointLights: s.point.length,
+ numSpotLights: s.spot.length,
+ numSpotLightMaps: s.spotLightMap.length,
+ numRectAreaLights: s.rectArea.length,
+ numHemiLights: s.hemi.length,
+ numDirLightShadows: s.directionalShadowMap.length,
+ numPointLightShadows: s.pointShadowMap.length,
+ numSpotLightShadows: s.spotShadowMap.length,
+ numSpotLightShadowsWithMaps: s.numSpotLightShadowsWithMaps,
+ numLightProbes: s.numLightProbes,
+ numClippingPlanes: o.numPlanes,
+ numClipIntersection: o.numIntersection,
+ dithering: a.dithering,
+ shadowMapEnabled: e.shadowMap.enabled && u.length > 0,
+ shadowMapType: e.shadowMap.type,
+ toneMapping: Pe,
+ decodeVideoTexture: ie && a.map.isVideoTexture === !0 && Rt.getTransfer(a.map.colorSpace) === "srgb",
+ decodeVideoTextureEmissive: fe && a.emissiveMap.isVideoTexture === !0 && Rt.getTransfer(a.emissiveMap.colorSpace) === "srgb",
+ premultipliedAlpha: a.premultipliedAlpha,
+ doubleSided: a.side === 2,
+ flipSided: a.side === 1,
+ useDepthPacking: a.depthPacking >= 0,
+ depthPacking: a.depthPacking || 0,
+ index0AttributeName: a.index0AttributeName,
+ extensionClipCullDistance: Ne && a.extensions.clipCullDistance === !0 && r.has("WEBGL_clip_cull_distance"),
+ extensionMultiDraw: (Ne && a.extensions.multiDraw === !0 || re) && r.has("WEBGL_multi_draw"),
+ rendererExtensionParallelShaderCompile: r.has("KHR_parallel_shader_compile"),
+ customProgramCacheKey: a.customProgramCacheKey()
+ };
+ return Fe.vertexUv1s = l.has(1), Fe.vertexUv2s = l.has(2), Fe.vertexUv3s = l.has(3), l.clear(), Fe;
+ }
+ function _(t) {
+ let n = [];
+ if (t.shaderID ? n.push(t.shaderID) : (n.push(t.customVertexShaderID), n.push(t.customFragmentShaderID)), t.defines !== void 0) for (let e in t.defines) n.push(e), n.push(t.defines[e]);
+ return t.isRawShaderMaterial === !1 && (v(n, t), y(n, t), n.push(e.outputColorSpace)), n.push(t.customProgramCacheKey), n.join();
+ }
+ function v(e, t) {
+ e.push(t.precision), e.push(t.outputColorSpace), e.push(t.envMapMode), e.push(t.envMapCubeUVHeight), e.push(t.mapUv), e.push(t.alphaMapUv), e.push(t.lightMapUv), e.push(t.aoMapUv), e.push(t.bumpMapUv), e.push(t.normalMapUv), e.push(t.displacementMapUv), e.push(t.emissiveMapUv), e.push(t.metalnessMapUv), e.push(t.roughnessMapUv), e.push(t.anisotropyMapUv), e.push(t.clearcoatMapUv), e.push(t.clearcoatNormalMapUv), e.push(t.clearcoatRoughnessMapUv), e.push(t.iridescenceMapUv), e.push(t.iridescenceThicknessMapUv), e.push(t.sheenColorMapUv), e.push(t.sheenRoughnessMapUv), e.push(t.specularMapUv), e.push(t.specularColorMapUv), e.push(t.specularIntensityMapUv), e.push(t.transmissionMapUv), e.push(t.thicknessMapUv), e.push(t.combine), e.push(t.fogExp2), e.push(t.sizeAttenuation), e.push(t.morphTargetsCount), e.push(t.morphAttributeCount), e.push(t.numDirLights), e.push(t.numPointLights), e.push(t.numSpotLights), e.push(t.numSpotLightMaps), e.push(t.numHemiLights), e.push(t.numRectAreaLights), e.push(t.numDirLightShadows), e.push(t.numPointLightShadows), e.push(t.numSpotLightShadows), e.push(t.numSpotLightShadowsWithMaps), e.push(t.numLightProbes), e.push(t.shadowMapType), e.push(t.toneMapping), e.push(t.numClippingPlanes), e.push(t.numClipIntersection), e.push(t.depthPacking);
+ }
+ function y(e, t) {
+ s.disableAll(), t.supportsVertexTextures && s.enable(0), t.instancing && s.enable(1), t.instancingColor && s.enable(2), t.instancingMorph && s.enable(3), t.matcap && s.enable(4), t.envMap && s.enable(5), t.normalMapObjectSpace && s.enable(6), t.normalMapTangentSpace && s.enable(7), t.clearcoat && s.enable(8), t.iridescence && s.enable(9), t.alphaTest && s.enable(10), t.vertexColors && s.enable(11), t.vertexAlphas && s.enable(12), t.vertexUv1s && s.enable(13), t.vertexUv2s && s.enable(14), t.vertexUv3s && s.enable(15), t.vertexTangents && s.enable(16), t.anisotropy && s.enable(17), t.alphaHash && s.enable(18), t.batching && s.enable(19), t.dispersion && s.enable(20), t.batchingColor && s.enable(21), e.push(s.mask), s.disableAll(), t.fog && s.enable(0), t.useFog && s.enable(1), t.flatShading && s.enable(2), t.logarithmicDepthBuffer && s.enable(3), t.reverseDepthBuffer && s.enable(4), t.skinning && s.enable(5), t.morphTargets && s.enable(6), t.morphNormals && s.enable(7), t.morphColors && s.enable(8), t.premultipliedAlpha && s.enable(9), t.shadowMapEnabled && s.enable(10), t.doubleSided && s.enable(11), t.flipSided && s.enable(12), t.useDepthPacking && s.enable(13), t.dithering && s.enable(14), t.transmission && s.enable(15), t.sheen && s.enable(16), t.opaque && s.enable(17), t.pointsUvs && s.enable(18), t.decodeVideoTexture && s.enable(19), t.decodeVideoTextureEmissive && s.enable(20), t.alphaToCoverage && s.enable(21), e.push(s.mask);
+ }
+ function b(e) {
+ let t = m[e.type], n;
+ if (t) {
+ let e = us[t];
+ n = ui.clone(e.uniforms);
+ } else n = e.uniforms;
+ return n;
+ }
+ function x(t, n) {
+ let r;
+ for (let e = 0, t = u.length; e < t; e++) {
+ let t = u[e];
+ if (t.cacheKey === n) {
+ r = t, ++r.usedTimes;
+ break;
+ }
+ }
+ return r === void 0 && (r = new jl(e, n, t, a), u.push(r)), r;
+ }
+ function S(e) {
+ if (--e.usedTimes === 0) {
+ let t = u.indexOf(e);
+ u[t] = u[u.length - 1], u.pop(), e.destroy();
+ }
+ }
+ function C(e) {
+ c.remove(e);
+ }
+ function w() {
+ c.dispose();
+ }
+ return {
+ getParameters: g,
+ getProgramCacheKey: _,
+ getUniforms: b,
+ acquireProgram: x,
+ releaseProgram: S,
+ releaseShaderCache: C,
+ programs: u,
+ dispose: w
+ };
+}
+function Il() {
+ let e = /* @__PURE__ */ new WeakMap();
+ function t(t) {
+ return e.has(t);
+ }
+ function n(t) {
+ let n = e.get(t);
+ return n === void 0 && (n = {}, e.set(t, n)), n;
+ }
+ function r(t) {
+ e.delete(t);
+ }
+ function i(t, n, r) {
+ e.get(t)[n] = r;
+ }
+ function a() {
+ e = /* @__PURE__ */ new WeakMap();
+ }
+ return {
+ has: t,
+ get: n,
+ remove: r,
+ update: i,
+ dispose: a
+ };
+}
+function Ll(e, t) {
+ return e.groupOrder === t.groupOrder ? e.renderOrder === t.renderOrder ? e.material.id === t.material.id ? e.z === t.z ? e.id - t.id : e.z - t.z : e.material.id - t.material.id : e.renderOrder - t.renderOrder : e.groupOrder - t.groupOrder;
+}
+function Rl(e, t) {
+ return e.groupOrder === t.groupOrder ? e.renderOrder === t.renderOrder ? e.z === t.z ? e.id - t.id : t.z - e.z : e.renderOrder - t.renderOrder : e.groupOrder - t.groupOrder;
+}
+function zl() {
+ let e = [], t = 0, n = [], r = [], i = [];
+ function a() {
+ t = 0, n.length = 0, r.length = 0, i.length = 0;
+ }
+ function o(n, r, i, a, o, s) {
+ let c = e[t];
+ return c === void 0 ? (c = {
+ id: n.id,
+ object: n,
+ geometry: r,
+ material: i,
+ groupOrder: a,
+ renderOrder: n.renderOrder,
+ z: o,
+ group: s
+ }, e[t] = c) : (c.id = n.id, c.object = n, c.geometry = r, c.material = i, c.groupOrder = a, c.renderOrder = n.renderOrder, c.z = o, c.group = s), t++, c;
+ }
+ function s(e, t, a, s, c, l) {
+ let u = o(e, t, a, s, c, l);
+ a.transmission > 0 ? r.push(u) : a.transparent === !0 ? i.push(u) : n.push(u);
+ }
+ function c(e, t, a, s, c, l) {
+ let u = o(e, t, a, s, c, l);
+ a.transmission > 0 ? r.unshift(u) : a.transparent === !0 ? i.unshift(u) : n.unshift(u);
+ }
+ function l(e, t) {
+ n.length > 1 && n.sort(e || Ll), r.length > 1 && r.sort(t || Rl), i.length > 1 && i.sort(t || Rl);
+ }
+ function u() {
+ for (let n = t, r = e.length; n < r; n++) {
+ let t = e[n];
+ if (t.id === null) break;
+ t.id = null, t.object = null, t.geometry = null, t.material = null, t.group = null;
+ }
+ }
+ return {
+ opaque: n,
+ transmissive: r,
+ transparent: i,
+ init: a,
+ push: s,
+ unshift: c,
+ finish: u,
+ sort: l
+ };
+}
+function Bl() {
+ let e = /* @__PURE__ */ new WeakMap();
+ function t(t, n) {
+ let r = e.get(t), i;
+ return r === void 0 ? (i = new zl(), e.set(t, [i])) : n >= r.length ? (i = new zl(), r.push(i)) : i = r[n], i;
+ }
+ function n() {
+ e = /* @__PURE__ */ new WeakMap();
+ }
+ return {
+ get: t,
+ dispose: n
+ };
+}
+function Vl() {
+ let e = {};
+ return { get: function(t) {
+ if (e[t.id] !== void 0) return e[t.id];
+ let n;
+ switch (t.type) {
+ case "DirectionalLight":
+ n = {
+ direction: new R(),
+ color: new B()
+ };
+ break;
+ case "SpotLight":
+ n = {
+ position: new R(),
+ direction: new R(),
+ color: new B(),
+ distance: 0,
+ coneCos: 0,
+ penumbraCos: 0,
+ decay: 0
+ };
+ break;
+ case "PointLight":
+ n = {
+ position: new R(),
+ color: new B(),
+ distance: 0,
+ decay: 0
+ };
+ break;
+ case "HemisphereLight":
+ n = {
+ direction: new R(),
+ skyColor: new B(),
+ groundColor: new B()
+ };
+ break;
+ case "RectAreaLight":
+ n = {
+ color: new B(),
+ position: new R(),
+ halfWidth: new R(),
+ halfHeight: new R()
+ };
+ break;
+ }
+ return e[t.id] = n, n;
+ } };
+}
+function Hl() {
+ let e = {};
+ return { get: function(t) {
+ if (e[t.id] !== void 0) return e[t.id];
+ let n;
+ switch (t.type) {
+ case "DirectionalLight":
+ n = {
+ shadowIntensity: 1,
+ shadowBias: 0,
+ shadowNormalBias: 0,
+ shadowRadius: 1,
+ shadowMapSize: new L()
+ };
+ break;
+ case "SpotLight":
+ n = {
+ shadowIntensity: 1,
+ shadowBias: 0,
+ shadowNormalBias: 0,
+ shadowRadius: 1,
+ shadowMapSize: new L()
+ };
+ break;
+ case "PointLight":
+ n = {
+ shadowIntensity: 1,
+ shadowBias: 0,
+ shadowNormalBias: 0,
+ shadowRadius: 1,
+ shadowMapSize: new L(),
+ shadowCameraNear: 1,
+ shadowCameraFar: 1e3
+ };
+ break;
+ }
+ return e[t.id] = n, n;
+ } };
+}
+var Ul = 0;
+function Wl(e, t) {
+ return (t.castShadow ? 2 : 0) - (e.castShadow ? 2 : 0) + +!!t.map - !!e.map;
+}
+function Gl(e) {
+ let t = new Vl(), n = Hl(), r = {
+ version: 0,
+ hash: {
+ directionalLength: -1,
+ pointLength: -1,
+ spotLength: -1,
+ rectAreaLength: -1,
+ hemiLength: -1,
+ numDirectionalShadows: -1,
+ numPointShadows: -1,
+ numSpotShadows: -1,
+ numSpotMaps: -1,
+ numLightProbes: -1
+ },
+ ambient: [
+ 0,
+ 0,
+ 0
+ ],
+ probe: [],
+ directional: [],
+ directionalShadow: [],
+ directionalShadowMap: [],
+ directionalShadowMatrix: [],
+ spot: [],
+ spotLightMap: [],
+ spotShadow: [],
+ spotShadowMap: [],
+ spotLightMatrix: [],
+ rectArea: [],
+ rectAreaLTC1: null,
+ rectAreaLTC2: null,
+ point: [],
+ pointShadow: [],
+ pointShadowMap: [],
+ pointShadowMatrix: [],
+ hemi: [],
+ numSpotLightShadowsWithMaps: 0,
+ numLightProbes: 0
+ };
+ for (let e = 0; e < 9; e++) r.probe.push(new R());
+ let i = new R(), a = new z(), o = new z();
+ function s(i) {
+ let a = 0, o = 0, s = 0;
+ for (let e = 0; e < 9; e++) r.probe[e].set(0, 0, 0);
+ let c = 0, l = 0, u = 0, d = 0, f = 0, p = 0, m = 0, h = 0, g = 0, _ = 0, v = 0;
+ i.sort(Wl);
+ for (let e = 0, y = i.length; e < y; e++) {
+ let y = i[e], b = y.color, x = y.intensity, S = y.distance, C = y.shadow && y.shadow.map ? y.shadow.map.texture : null;
+ if (y.isAmbientLight) a += b.r * x, o += b.g * x, s += b.b * x;
+ else if (y.isLightProbe) {
+ for (let e = 0; e < 9; e++) r.probe[e].addScaledVector(y.sh.coefficients[e], x);
+ v++;
+ } else if (y.isDirectionalLight) {
+ let e = t.get(y);
+ if (e.color.copy(y.color).multiplyScalar(y.intensity), y.castShadow) {
+ let e = y.shadow, t = n.get(y);
+ t.shadowIntensity = e.intensity, t.shadowBias = e.bias, t.shadowNormalBias = e.normalBias, t.shadowRadius = e.radius, t.shadowMapSize = e.mapSize, r.directionalShadow[c] = t, r.directionalShadowMap[c] = C, r.directionalShadowMatrix[c] = y.shadow.matrix, p++;
+ }
+ r.directional[c] = e, c++;
+ } else if (y.isSpotLight) {
+ let e = t.get(y);
+ e.position.setFromMatrixPosition(y.matrixWorld), e.color.copy(b).multiplyScalar(x), e.distance = S, e.coneCos = Math.cos(y.angle), e.penumbraCos = Math.cos(y.angle * (1 - y.penumbra)), e.decay = y.decay, r.spot[u] = e;
+ let i = y.shadow;
+ if (y.map && (r.spotLightMap[g] = y.map, g++, i.updateMatrices(y), y.castShadow && _++), r.spotLightMatrix[u] = i.matrix, y.castShadow) {
+ let e = n.get(y);
+ e.shadowIntensity = i.intensity, e.shadowBias = i.bias, e.shadowNormalBias = i.normalBias, e.shadowRadius = i.radius, e.shadowMapSize = i.mapSize, r.spotShadow[u] = e, r.spotShadowMap[u] = C, h++;
+ }
+ u++;
+ } else if (y.isRectAreaLight) {
+ let e = t.get(y);
+ e.color.copy(b).multiplyScalar(x), e.halfWidth.set(y.width * .5, 0, 0), e.halfHeight.set(0, y.height * .5, 0), r.rectArea[d] = e, d++;
+ } else if (y.isPointLight) {
+ let e = t.get(y);
+ if (e.color.copy(y.color).multiplyScalar(y.intensity), e.distance = y.distance, e.decay = y.decay, y.castShadow) {
+ let e = y.shadow, t = n.get(y);
+ t.shadowIntensity = e.intensity, t.shadowBias = e.bias, t.shadowNormalBias = e.normalBias, t.shadowRadius = e.radius, t.shadowMapSize = e.mapSize, t.shadowCameraNear = e.camera.near, t.shadowCameraFar = e.camera.far, r.pointShadow[l] = t, r.pointShadowMap[l] = C, r.pointShadowMatrix[l] = y.shadow.matrix, m++;
+ }
+ r.point[l] = e, l++;
+ } else if (y.isHemisphereLight) {
+ let e = t.get(y);
+ e.skyColor.copy(y.color).multiplyScalar(x), e.groundColor.copy(y.groundColor).multiplyScalar(x), r.hemi[f] = e, f++;
+ }
+ }
+ d > 0 && (e.has("OES_texture_float_linear") === !0 ? (r.rectAreaLTC1 = H.LTC_FLOAT_1, r.rectAreaLTC2 = H.LTC_FLOAT_2) : (r.rectAreaLTC1 = H.LTC_HALF_1, r.rectAreaLTC2 = H.LTC_HALF_2)), r.ambient[0] = a, r.ambient[1] = o, r.ambient[2] = s;
+ let y = r.hash;
+ (y.directionalLength !== c || y.pointLength !== l || y.spotLength !== u || y.rectAreaLength !== d || y.hemiLength !== f || y.numDirectionalShadows !== p || y.numPointShadows !== m || y.numSpotShadows !== h || y.numSpotMaps !== g || y.numLightProbes !== v) && (r.directional.length = c, r.spot.length = u, r.rectArea.length = d, r.point.length = l, r.hemi.length = f, r.directionalShadow.length = p, r.directionalShadowMap.length = p, r.pointShadow.length = m, r.pointShadowMap.length = m, r.spotShadow.length = h, r.spotShadowMap.length = h, r.directionalShadowMatrix.length = p, r.pointShadowMatrix.length = m, r.spotLightMatrix.length = h + g - _, r.spotLightMap.length = g, r.numSpotLightShadowsWithMaps = _, r.numLightProbes = v, y.directionalLength = c, y.pointLength = l, y.spotLength = u, y.rectAreaLength = d, y.hemiLength = f, y.numDirectionalShadows = p, y.numPointShadows = m, y.numSpotShadows = h, y.numSpotMaps = g, y.numLightProbes = v, r.version = Ul++);
+ }
+ function c(e, t) {
+ let n = 0, s = 0, c = 0, l = 0, u = 0, d = t.matrixWorldInverse;
+ for (let t = 0, f = e.length; t < f; t++) {
+ let f = e[t];
+ if (f.isDirectionalLight) {
+ let e = r.directional[n];
+ e.direction.setFromMatrixPosition(f.matrixWorld), i.setFromMatrixPosition(f.target.matrixWorld), e.direction.sub(i), e.direction.transformDirection(d), n++;
+ } else if (f.isSpotLight) {
+ let e = r.spot[c];
+ e.position.setFromMatrixPosition(f.matrixWorld), e.position.applyMatrix4(d), e.direction.setFromMatrixPosition(f.matrixWorld), i.setFromMatrixPosition(f.target.matrixWorld), e.direction.sub(i), e.direction.transformDirection(d), c++;
+ } else if (f.isRectAreaLight) {
+ let e = r.rectArea[l];
+ e.position.setFromMatrixPosition(f.matrixWorld), e.position.applyMatrix4(d), o.identity(), a.copy(f.matrixWorld), a.premultiply(d), o.extractRotation(a), e.halfWidth.set(f.width * .5, 0, 0), e.halfHeight.set(0, f.height * .5, 0), e.halfWidth.applyMatrix4(o), e.halfHeight.applyMatrix4(o), l++;
+ } else if (f.isPointLight) {
+ let e = r.point[s];
+ e.position.setFromMatrixPosition(f.matrixWorld), e.position.applyMatrix4(d), s++;
+ } else if (f.isHemisphereLight) {
+ let e = r.hemi[u];
+ e.direction.setFromMatrixPosition(f.matrixWorld), e.direction.transformDirection(d), u++;
+ }
+ }
+ }
+ return {
+ setup: s,
+ setupView: c,
+ state: r
+ };
+}
+function Kl(e) {
+ let t = new Gl(e), n = [], r = [];
+ function i(e) {
+ l.camera = e, n.length = 0, r.length = 0;
+ }
+ function a(e) {
+ n.push(e);
+ }
+ function o(e) {
+ r.push(e);
+ }
+ function s() {
+ t.setup(n);
+ }
+ function c(e) {
+ t.setupView(n, e);
+ }
+ let l = {
+ lightsArray: n,
+ shadowsArray: r,
+ camera: null,
+ lights: t,
+ transmissionRenderTarget: {}
+ };
+ return {
+ init: i,
+ state: l,
+ setupLights: s,
+ setupLightsView: c,
+ pushLight: a,
+ pushShadow: o
+ };
+}
+function ql(e) {
+ let t = /* @__PURE__ */ new WeakMap();
+ function n(n, r = 0) {
+ let i = t.get(n), a;
+ return i === void 0 ? (a = new Kl(e), t.set(n, [a])) : r >= i.length ? (a = new Kl(e), i.push(a)) : a = i[r], a;
+ }
+ function r() {
+ t = /* @__PURE__ */ new WeakMap();
+ }
+ return {
+ get: n,
+ dispose: r
+ };
+}
+var Jl = "void main() {\n gl_Position = vec4( position, 1.0 );\n}", Yl = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n const float samples = float( VSM_SAMPLES );\n float mean = 0.0;\n float squared_mean = 0.0;\n float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n float uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n for ( float i = 0.0; i < samples; i ++ ) {\n float uvOffset = uvStart + i * uvStride;\n #ifdef HORIZONTAL_PASS\n vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n #else\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n #endif\n }\n mean = mean / samples;\n squared_mean = squared_mean / samples;\n float std_dev = sqrt( squared_mean - mean * mean );\n gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
+function Xl(e, t, n) {
+ let r = new sa(), i = new L(), a = new L(), o = new Jt(), s = new Ia({ depthPacking: We }), l = new La(), u = {}, d = n.maxTextureSize, f = {
+ 0: 1,
+ 1: 0,
+ 2: 2
+ }, p = new pi({
+ defines: { VSM_SAMPLES: 8 },
+ uniforms: {
+ shadow_pass: { value: null },
+ resolution: { value: new L() },
+ radius: { value: 4 }
+ },
+ vertexShader: Jl,
+ fragmentShader: Yl
+ }), m = p.clone();
+ m.defines.HORIZONTAL_PASS = 1;
+ let h = new Wr();
+ h.setAttribute("position", new Nr(new Float32Array([
+ -1,
+ -1,
+ .5,
+ 3,
+ -1,
+ .5,
+ -1,
+ 3,
+ .5
+ ]), 3));
+ let g = new ni(h, p), _ = this;
+ this.enabled = !1, this.autoUpdate = !0, this.needsUpdate = !1, this.type = 1;
+ let v = this.type;
+ this.render = function(t, n, s) {
+ if (_.enabled === !1 || _.autoUpdate === !1 && _.needsUpdate === !1 || t.length === 0) return;
+ let l = e.getRenderTarget(), u = e.getActiveCubeFace(), f = e.getActiveMipmapLevel(), p = e.state;
+ p.setBlending(0), p.buffers.color.setClear(1, 1, 1, 1), p.buffers.depth.setTest(!0), p.setScissorTest(!1);
+ let m = v !== 3 && this.type === 3, h = v === 3 && this.type !== 3;
+ for (let l = 0, u = t.length; l < u; l++) {
+ let u = t[l], f = u.shadow;
+ if (f === void 0) {
+ console.warn("THREE.WebGLShadowMap:", u, "has no shadow.");
+ continue;
+ }
+ if (f.autoUpdate === !1 && f.needsUpdate === !1) continue;
+ i.copy(f.mapSize);
+ let g = f.getFrameExtents();
+ if (i.multiply(g), a.copy(f.mapSize), (i.x > d || i.y > d) && (i.x > d && (a.x = Math.floor(d / g.x), i.x = a.x * g.x, f.mapSize.x = a.x), i.y > d && (a.y = Math.floor(d / g.y), i.y = a.y * g.y, f.mapSize.y = a.y)), f.map === null || m === !0 || h === !0) {
+ let e = this.type === 3 ? {} : {
+ minFilter: c,
+ magFilter: c
+ };
+ f.map !== null && f.map.dispose(), f.map = new Xt(i.x, i.y, e), f.map.texture.name = u.name + ".shadowMap", f.camera.updateProjectionMatrix();
+ }
+ e.setRenderTarget(f.map), e.clear();
+ let _ = f.getViewportCount();
+ for (let e = 0; e < _; e++) {
+ let t = f.getViewport(e);
+ o.set(a.x * t.x, a.y * t.y, a.x * t.z, a.y * t.w), p.viewport(o), f.updateMatrices(u, e), r = f.getFrustum(), x(n, s, f.camera, u, this.type);
+ }
+ f.isPointLightShadow !== !0 && this.type === 3 && y(f, s), f.needsUpdate = !1;
+ }
+ v = this.type, _.needsUpdate = !1, e.setRenderTarget(l, u, f);
+ };
+ function y(n, r) {
+ let a = t.update(g);
+ p.defines.VSM_SAMPLES !== n.blurSamples && (p.defines.VSM_SAMPLES = n.blurSamples, m.defines.VSM_SAMPLES = n.blurSamples, p.needsUpdate = !0, m.needsUpdate = !0), n.mapPass === null && (n.mapPass = new Xt(i.x, i.y)), p.uniforms.shadow_pass.value = n.map.texture, p.uniforms.resolution.value = n.mapSize, p.uniforms.radius.value = n.radius, e.setRenderTarget(n.mapPass), e.clear(), e.renderBufferDirect(r, null, a, p, g, null), m.uniforms.shadow_pass.value = n.mapPass.texture, m.uniforms.resolution.value = n.mapSize, m.uniforms.radius.value = n.radius, e.setRenderTarget(n.map), e.clear(), e.renderBufferDirect(r, null, a, m, g, null);
+ }
+ function b(t, n, r, i) {
+ let a = null, o = r.isPointLight === !0 ? t.customDistanceMaterial : t.customDepthMaterial;
+ if (o !== void 0) a = o;
+ else if (a = r.isPointLight === !0 ? l : s, e.localClippingEnabled && n.clipShadows === !0 && Array.isArray(n.clippingPlanes) && n.clippingPlanes.length !== 0 || n.displacementMap && n.displacementScale !== 0 || n.alphaMap && n.alphaTest > 0 || n.map && n.alphaTest > 0 || n.alphaToCoverage === !0) {
+ let e = a.uuid, t = n.uuid, r = u[e];
+ r === void 0 && (r = {}, u[e] = r);
+ let i = r[t];
+ i === void 0 && (i = a.clone(), r[t] = i, n.addEventListener("dispose", S)), a = i;
+ }
+ if (a.visible = n.visible, a.wireframe = n.wireframe, i === 3 ? a.side = n.shadowSide === null ? n.side : n.shadowSide : a.side = n.shadowSide === null ? f[n.side] : n.shadowSide, a.alphaMap = n.alphaMap, a.alphaTest = n.alphaToCoverage === !0 ? .5 : n.alphaTest, a.map = n.map, a.clipShadows = n.clipShadows, a.clippingPlanes = n.clippingPlanes, a.clipIntersection = n.clipIntersection, a.displacementMap = n.displacementMap, a.displacementScale = n.displacementScale, a.displacementBias = n.displacementBias, a.wireframeLinewidth = n.wireframeLinewidth, a.linewidth = n.linewidth, r.isPointLight === !0 && a.isMeshDistanceMaterial === !0) {
+ let t = e.properties.get(a);
+ t.light = r;
+ }
+ return a;
+ }
+ function x(n, i, a, o, s) {
+ if (n.visible === !1) return;
+ if (n.layers.test(i.layers) && (n.isMesh || n.isLine || n.isPoints) && (n.castShadow || n.receiveShadow && s === 3) && (!n.frustumCulled || r.intersectsObject(n))) {
+ n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse, n.matrixWorld);
+ let r = t.update(n), c = n.material;
+ if (Array.isArray(c)) {
+ let t = r.groups;
+ for (let l = 0, u = t.length; l < u; l++) {
+ let u = t[l], d = c[u.materialIndex];
+ if (d && d.visible) {
+ let t = b(n, d, o, s);
+ n.onBeforeShadow(e, n, i, a, r, t, u), e.renderBufferDirect(a, null, r, t, n, u), n.onAfterShadow(e, n, i, a, r, t, u);
+ }
+ }
+ } else if (c.visible) {
+ let t = b(n, c, o, s);
+ n.onBeforeShadow(e, n, i, a, r, t, null), e.renderBufferDirect(a, null, r, t, n, null), n.onAfterShadow(e, n, i, a, r, t, null);
+ }
+ }
+ let c = n.children;
+ for (let e = 0, t = c.length; e < t; e++) x(c[e], i, a, o, s);
+ }
+ function S(e) {
+ e.target.removeEventListener("dispose", S);
+ for (let t in u) {
+ let n = u[t], r = e.target.uuid;
+ r in n && (n[r].dispose(), delete n[r]);
+ }
+ }
+}
+var Zl = {
+ 0: 1,
+ 2: 6,
+ 4: 7,
+ 3: 5,
+ 1: 0,
+ 6: 2,
+ 7: 4,
+ 5: 3
+};
+function Ql(e, t) {
+ function n() {
+ let t = !1, n = new Jt(), r = null, i = new Jt(0, 0, 0, 0);
+ return {
+ setMask: function(n) {
+ r !== n && !t && (e.colorMask(n, n, n, n), r = n);
+ },
+ setLocked: function(e) {
+ t = e;
+ },
+ setClear: function(t, r, a, o, s) {
+ s === !0 && (t *= o, r *= o, a *= o), n.set(t, r, a, o), i.equals(n) === !1 && (e.clearColor(t, r, a, o), i.copy(n));
+ },
+ reset: function() {
+ t = !1, r = null, i.set(-1, 0, 0, 0);
+ }
+ };
+ }
+ function r() {
+ let n = !1, r = !1, i = null, a = null, o = null;
+ return {
+ setReversed: function(e) {
+ if (r !== e) {
+ let n = t.get("EXT_clip_control");
+ e ? n.clipControlEXT(n.LOWER_LEFT_EXT, n.ZERO_TO_ONE_EXT) : n.clipControlEXT(n.LOWER_LEFT_EXT, n.NEGATIVE_ONE_TO_ONE_EXT), r = e;
+ let i = o;
+ o = null, this.setClear(i);
+ }
+ },
+ getReversed: function() {
+ return r;
+ },
+ setTest: function(t) {
+ t ? fe(e.DEPTH_TEST) : pe(e.DEPTH_TEST);
+ },
+ setMask: function(t) {
+ i !== t && !n && (e.depthMask(t), i = t);
+ },
+ setFunc: function(t) {
+ if (r && (t = Zl[t]), a !== t) {
+ switch (t) {
+ case 0:
+ e.depthFunc(e.NEVER);
+ break;
+ case 1:
+ e.depthFunc(e.ALWAYS);
+ break;
+ case 2:
+ e.depthFunc(e.LESS);
+ break;
+ case 3:
+ e.depthFunc(e.LEQUAL);
+ break;
+ case 4:
+ e.depthFunc(e.EQUAL);
+ break;
+ case 5:
+ e.depthFunc(e.GEQUAL);
+ break;
+ case 6:
+ e.depthFunc(e.GREATER);
+ break;
+ case 7:
+ e.depthFunc(e.NOTEQUAL);
+ break;
+ default: e.depthFunc(e.LEQUAL);
+ }
+ a = t;
+ }
+ },
+ setLocked: function(e) {
+ n = e;
+ },
+ setClear: function(t) {
+ o !== t && (r && (t = 1 - t), e.clearDepth(t), o = t);
+ },
+ reset: function() {
+ n = !1, i = null, a = null, o = null, r = !1;
+ }
+ };
+ }
+ function i() {
+ let t = !1, n = null, r = null, i = null, a = null, o = null, s = null, c = null, l = null;
+ return {
+ setTest: function(n) {
+ t || (n ? fe(e.STENCIL_TEST) : pe(e.STENCIL_TEST));
+ },
+ setMask: function(r) {
+ n !== r && !t && (e.stencilMask(r), n = r);
+ },
+ setFunc: function(t, n, o) {
+ (r !== t || i !== n || a !== o) && (e.stencilFunc(t, n, o), r = t, i = n, a = o);
+ },
+ setOp: function(t, n, r) {
+ (o !== t || s !== n || c !== r) && (e.stencilOp(t, n, r), o = t, s = n, c = r);
+ },
+ setLocked: function(e) {
+ t = e;
+ },
+ setClear: function(t) {
+ l !== t && (e.clearStencil(t), l = t);
+ },
+ reset: function() {
+ t = !1, n = null, r = null, i = null, a = null, o = null, s = null, c = null, l = null;
+ }
+ };
+ }
+ let a = new n(), o = new r(), s = new i(), c = /* @__PURE__ */ new WeakMap(), l = /* @__PURE__ */ new WeakMap(), u = {}, d = {}, f = /* @__PURE__ */ new WeakMap(), p = [], m = null, h = !1, g = null, _ = null, v = null, y = null, b = null, x = null, S = null, C = new B(0, 0, 0), w = 0, T = !1, E = null, D = null, O = null, k = null, ee = null, A = e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS), te = !1, ne = 0, re = e.getParameter(e.VERSION);
+ re.indexOf("WebGL") === -1 ? re.indexOf("OpenGL ES") !== -1 && (ne = parseFloat(/^OpenGL ES (\d)/.exec(re)[1]), te = ne >= 2) : (ne = parseFloat(/^WebGL (\d)/.exec(re)[1]), te = ne >= 1);
+ let ie = null, ae = {}, oe = e.getParameter(e.SCISSOR_BOX), se = e.getParameter(e.VIEWPORT), ce = new Jt().fromArray(oe), le = new Jt().fromArray(se);
+ function ue(t, n, r, i) {
+ let a = new Uint8Array(4), o = e.createTexture();
+ e.bindTexture(t, o), e.texParameteri(t, e.TEXTURE_MIN_FILTER, e.NEAREST), e.texParameteri(t, e.TEXTURE_MAG_FILTER, e.NEAREST);
+ for (let o = 0; o < r; o++) t === e.TEXTURE_3D || t === e.TEXTURE_2D_ARRAY ? e.texImage3D(n, 0, e.RGBA, 1, 1, i, 0, e.RGBA, e.UNSIGNED_BYTE, a) : e.texImage2D(n + o, 0, e.RGBA, 1, 1, 0, e.RGBA, e.UNSIGNED_BYTE, a);
+ return o;
+ }
+ let de = {};
+ de[e.TEXTURE_2D] = ue(e.TEXTURE_2D, e.TEXTURE_2D, 1), de[e.TEXTURE_CUBE_MAP] = ue(e.TEXTURE_CUBE_MAP, e.TEXTURE_CUBE_MAP_POSITIVE_X, 6), de[e.TEXTURE_2D_ARRAY] = ue(e.TEXTURE_2D_ARRAY, e.TEXTURE_2D_ARRAY, 1, 1), de[e.TEXTURE_3D] = ue(e.TEXTURE_3D, e.TEXTURE_3D, 1, 1), a.setClear(0, 0, 0, 1), o.setClear(1), s.setClear(0), fe(e.DEPTH_TEST), o.setFunc(3), j(!1), xe(1), fe(e.CULL_FACE), ye(0);
+ function fe(t) {
+ u[t] !== !0 && (e.enable(t), u[t] = !0);
+ }
+ function pe(t) {
+ u[t] !== !1 && (e.disable(t), u[t] = !1);
+ }
+ function me(t, n) {
+ return d[t] === n ? !1 : (e.bindFramebuffer(t, n), d[t] = n, t === e.DRAW_FRAMEBUFFER && (d[e.FRAMEBUFFER] = n), t === e.FRAMEBUFFER && (d[e.DRAW_FRAMEBUFFER] = n), !0);
+ }
+ function he(t, n) {
+ let r = p, i = !1;
+ if (t) {
+ r = f.get(n), r === void 0 && (r = [], f.set(n, r));
+ let a = t.textures;
+ if (r.length !== a.length || r[0] !== e.COLOR_ATTACHMENT0) {
+ for (let t = 0, n = a.length; t < n; t++) r[t] = e.COLOR_ATTACHMENT0 + t;
+ r.length = a.length, i = !0;
+ }
+ } else r[0] !== e.BACK && (r[0] = e.BACK, i = !0);
+ i && e.drawBuffers(r);
+ }
+ function ge(t) {
+ return m === t ? !1 : (e.useProgram(t), m = t, !0);
+ }
+ let _e = {
+ 100: e.FUNC_ADD,
+ 101: e.FUNC_SUBTRACT,
+ 102: e.FUNC_REVERSE_SUBTRACT
+ };
+ _e[103] = e.MIN, _e[104] = e.MAX;
+ let ve = {
+ 200: e.ZERO,
+ 201: e.ONE,
+ 202: e.SRC_COLOR,
+ 204: e.SRC_ALPHA,
+ 210: e.SRC_ALPHA_SATURATE,
+ 208: e.DST_COLOR,
+ 206: e.DST_ALPHA,
+ 203: e.ONE_MINUS_SRC_COLOR,
+ 205: e.ONE_MINUS_SRC_ALPHA,
+ 209: e.ONE_MINUS_DST_COLOR,
+ 207: e.ONE_MINUS_DST_ALPHA,
+ 211: e.CONSTANT_COLOR,
+ 212: e.ONE_MINUS_CONSTANT_COLOR,
+ 213: e.CONSTANT_ALPHA,
+ 214: e.ONE_MINUS_CONSTANT_ALPHA
+ };
+ function ye(t, n, r, i, a, o, s, c, l, u) {
+ if (t === 0) {
+ h === !0 && (pe(e.BLEND), h = !1);
+ return;
+ }
+ if (h === !1 && (fe(e.BLEND), h = !0), t !== 5) {
+ if (t !== g || u !== T) {
+ if ((_ !== 100 || b !== 100) && (e.blendEquation(e.FUNC_ADD), _ = 100, b = 100), u) switch (t) {
+ case 1:
+ e.blendFuncSeparate(e.ONE, e.ONE_MINUS_SRC_ALPHA, e.ONE, e.ONE_MINUS_SRC_ALPHA);
+ break;
+ case 2:
+ e.blendFunc(e.ONE, e.ONE);
+ break;
+ case 3:
+ e.blendFuncSeparate(e.ZERO, e.ONE_MINUS_SRC_COLOR, e.ZERO, e.ONE);
+ break;
+ case 4:
+ e.blendFuncSeparate(e.ZERO, e.SRC_COLOR, e.ZERO, e.SRC_ALPHA);
+ break;
+ default:
+ console.error("THREE.WebGLState: Invalid blending: ", t);
+ break;
+ }
+ else switch (t) {
+ case 1:
+ e.blendFuncSeparate(e.SRC_ALPHA, e.ONE_MINUS_SRC_ALPHA, e.ONE, e.ONE_MINUS_SRC_ALPHA);
+ break;
+ case 2:
+ e.blendFunc(e.SRC_ALPHA, e.ONE);
+ break;
+ case 3:
+ e.blendFuncSeparate(e.ZERO, e.ONE_MINUS_SRC_COLOR, e.ZERO, e.ONE);
+ break;
+ case 4:
+ e.blendFunc(e.ZERO, e.SRC_COLOR);
+ break;
+ default:
+ console.error("THREE.WebGLState: Invalid blending: ", t);
+ break;
+ }
+ v = null, y = null, x = null, S = null, C.set(0, 0, 0), w = 0, g = t, T = u;
+ }
+ return;
+ }
+ a ||= n, o ||= r, s ||= i, (n !== _ || a !== b) && (e.blendEquationSeparate(_e[n], _e[a]), _ = n, b = a), (r !== v || i !== y || o !== x || s !== S) && (e.blendFuncSeparate(ve[r], ve[i], ve[o], ve[s]), v = r, y = i, x = o, S = s), (c.equals(C) === !1 || l !== w) && (e.blendColor(c.r, c.g, c.b, l), C.copy(c), w = l), g = t, T = !1;
+ }
+ function be(t, n) {
+ t.side === 2 ? pe(e.CULL_FACE) : fe(e.CULL_FACE);
+ let r = t.side === 1;
+ n && (r = !r), j(r), t.blending === 1 && t.transparent === !1 ? ye(0) : ye(t.blending, t.blendEquation, t.blendSrc, t.blendDst, t.blendEquationAlpha, t.blendSrcAlpha, t.blendDstAlpha, t.blendColor, t.blendAlpha, t.premultipliedAlpha), o.setFunc(t.depthFunc), o.setTest(t.depthTest), o.setMask(t.depthWrite), a.setMask(t.colorWrite);
+ let i = t.stencilWrite;
+ s.setTest(i), i && (s.setMask(t.stencilWriteMask), s.setFunc(t.stencilFunc, t.stencilRef, t.stencilFuncMask), s.setOp(t.stencilFail, t.stencilZFail, t.stencilZPass)), Ce(t.polygonOffset, t.polygonOffsetFactor, t.polygonOffsetUnits), t.alphaToCoverage === !0 ? fe(e.SAMPLE_ALPHA_TO_COVERAGE) : pe(e.SAMPLE_ALPHA_TO_COVERAGE);
+ }
+ function j(t) {
+ E !== t && (t ? e.frontFace(e.CW) : e.frontFace(e.CCW), E = t);
+ }
+ function xe(t) {
+ t === 0 ? pe(e.CULL_FACE) : (fe(e.CULL_FACE), t !== D && (t === 1 ? e.cullFace(e.BACK) : t === 2 ? e.cullFace(e.FRONT) : e.cullFace(e.FRONT_AND_BACK))), D = t;
+ }
+ function Se(t) {
+ t !== O && (te && e.lineWidth(t), O = t);
+ }
+ function Ce(t, n, r) {
+ t ? (fe(e.POLYGON_OFFSET_FILL), (k !== n || ee !== r) && (e.polygonOffset(n, r), k = n, ee = r)) : pe(e.POLYGON_OFFSET_FILL);
+ }
+ function M(t) {
+ t ? fe(e.SCISSOR_TEST) : pe(e.SCISSOR_TEST);
+ }
+ function we(t) {
+ t === void 0 && (t = e.TEXTURE0 + A - 1), ie !== t && (e.activeTexture(t), ie = t);
+ }
+ function N(t, n, r) {
+ r === void 0 && (r = ie === null ? e.TEXTURE0 + A - 1 : ie);
+ let i = ae[r];
+ i === void 0 && (i = {
+ type: void 0,
+ texture: void 0
+ }, ae[r] = i), (i.type !== t || i.texture !== n) && (ie !== r && (e.activeTexture(r), ie = r), e.bindTexture(t, n || de[t]), i.type = t, i.texture = n);
+ }
+ function P() {
+ let t = ae[ie];
+ t !== void 0 && t.type !== void 0 && (e.bindTexture(t.type, null), t.type = void 0, t.texture = void 0);
+ }
+ function Te() {
+ try {
+ e.compressedTexImage2D(...arguments);
+ } catch (e) {
+ console.error("THREE.WebGLState:", e);
+ }
+ }
+ function Ee() {
+ try {
+ e.compressedTexImage3D(...arguments);
+ } catch (e) {
+ console.error("THREE.WebGLState:", e);
+ }
+ }
+ function F() {
+ try {
+ e.texSubImage2D(...arguments);
+ } catch (e) {
+ console.error("THREE.WebGLState:", e);
+ }
+ }
+ function De() {
+ try {
+ e.texSubImage3D(...arguments);
+ } catch (e) {
+ console.error("THREE.WebGLState:", e);
+ }
+ }
+ function Oe() {
+ try {
+ e.compressedTexSubImage2D(...arguments);
+ } catch (e) {
+ console.error("THREE.WebGLState:", e);
+ }
+ }
+ function ke() {
+ try {
+ e.compressedTexSubImage3D(...arguments);
+ } catch (e) {
+ console.error("THREE.WebGLState:", e);
+ }
+ }
+ function Ae() {
+ try {
+ e.texStorage2D(...arguments);
+ } catch (e) {
+ console.error("THREE.WebGLState:", e);
+ }
+ }
+ function je() {
+ try {
+ e.texStorage3D(...arguments);
+ } catch (e) {
+ console.error("THREE.WebGLState:", e);
+ }
+ }
+ function Me() {
+ try {
+ e.texImage2D(...arguments);
+ } catch (e) {
+ console.error("THREE.WebGLState:", e);
+ }
+ }
+ function Ne() {
+ try {
+ e.texImage3D(...arguments);
+ } catch (e) {
+ console.error("THREE.WebGLState:", e);
+ }
+ }
+ function Pe(t) {
+ ce.equals(t) === !1 && (e.scissor(t.x, t.y, t.z, t.w), ce.copy(t));
+ }
+ function Fe(t) {
+ le.equals(t) === !1 && (e.viewport(t.x, t.y, t.z, t.w), le.copy(t));
+ }
+ function Ie(t, n) {
+ let r = l.get(n);
+ r === void 0 && (r = /* @__PURE__ */ new WeakMap(), l.set(n, r));
+ let i = r.get(t);
+ i === void 0 && (i = e.getUniformBlockIndex(n, t.name), r.set(t, i));
+ }
+ function Le(t, n) {
+ let r = l.get(n).get(t);
+ c.get(n) !== r && (e.uniformBlockBinding(n, r, t.__bindingPointIndex), c.set(n, r));
+ }
+ function Re() {
+ e.disable(e.BLEND), e.disable(e.CULL_FACE), e.disable(e.DEPTH_TEST), e.disable(e.POLYGON_OFFSET_FILL), e.disable(e.SCISSOR_TEST), e.disable(e.STENCIL_TEST), e.disable(e.SAMPLE_ALPHA_TO_COVERAGE), e.blendEquation(e.FUNC_ADD), e.blendFunc(e.ONE, e.ZERO), e.blendFuncSeparate(e.ONE, e.ZERO, e.ONE, e.ZERO), e.blendColor(0, 0, 0, 0), e.colorMask(!0, !0, !0, !0), e.clearColor(0, 0, 0, 0), e.depthMask(!0), e.depthFunc(e.LESS), o.setReversed(!1), e.clearDepth(1), e.stencilMask(4294967295), e.stencilFunc(e.ALWAYS, 0, 4294967295), e.stencilOp(e.KEEP, e.KEEP, e.KEEP), e.clearStencil(0), e.cullFace(e.BACK), e.frontFace(e.CCW), e.polygonOffset(0, 0), e.activeTexture(e.TEXTURE0), e.bindFramebuffer(e.FRAMEBUFFER, null), e.bindFramebuffer(e.DRAW_FRAMEBUFFER, null), e.bindFramebuffer(e.READ_FRAMEBUFFER, null), e.useProgram(null), e.lineWidth(1), e.scissor(0, 0, e.canvas.width, e.canvas.height), e.viewport(0, 0, e.canvas.width, e.canvas.height), u = {}, ie = null, ae = {}, d = {}, f = /* @__PURE__ */ new WeakMap(), p = [], m = null, h = !1, g = null, _ = null, v = null, y = null, b = null, x = null, S = null, C = new B(0, 0, 0), w = 0, T = !1, E = null, D = null, O = null, k = null, ee = null, ce.set(0, 0, e.canvas.width, e.canvas.height), le.set(0, 0, e.canvas.width, e.canvas.height), a.reset(), o.reset(), s.reset();
+ }
+ return {
+ buffers: {
+ color: a,
+ depth: o,
+ stencil: s
+ },
+ enable: fe,
+ disable: pe,
+ bindFramebuffer: me,
+ drawBuffers: he,
+ useProgram: ge,
+ setBlending: ye,
+ setMaterial: be,
+ setFlipSided: j,
+ setCullFace: xe,
+ setLineWidth: Se,
+ setPolygonOffset: Ce,
+ setScissorTest: M,
+ activeTexture: we,
+ bindTexture: N,
+ unbindTexture: P,
+ compressedTexImage2D: Te,
+ compressedTexImage3D: Ee,
+ texImage2D: Me,
+ texImage3D: Ne,
+ updateUBOMapping: Ie,
+ uniformBlockBinding: Le,
+ texStorage2D: Ae,
+ texStorage3D: je,
+ texSubImage2D: F,
+ texSubImage3D: De,
+ compressedTexSubImage2D: Oe,
+ compressedTexSubImage3D: ke,
+ scissor: Pe,
+ viewport: Fe,
+ reset: Re
+ };
+}
+function $l(e, t, n, r, i, m, h) {
+ let g = t.has("WEBGL_multisampled_render_to_texture") ? t.get("WEBGL_multisampled_render_to_texture") : null, _ = typeof navigator > "u" ? !1 : /OculusBrowser/g.test(navigator.userAgent), v = new L(), y = /* @__PURE__ */ new WeakMap(), b, x = /* @__PURE__ */ new WeakMap(), S = !1;
+ try {
+ S = typeof OffscreenCanvas < "u" && new OffscreenCanvas(1, 1).getContext("2d") !== null;
+ } catch {}
+ function C(e, t) {
+ return S ? new OffscreenCanvas(e, t) : Ot("canvas");
+ }
+ function w(e, t, n) {
+ let r = 1, i = Ae(e);
+ if ((i.width > n || i.height > n) && (r = n / Math.max(i.width, i.height)), r < 1) if (typeof HTMLImageElement < "u" && e instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && e instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && e instanceof ImageBitmap || typeof VideoFrame < "u" && e instanceof VideoFrame) {
+ let n = Math.floor(r * i.width), a = Math.floor(r * i.height);
+ b === void 0 && (b = C(n, a));
+ let o = t ? C(n, a) : b;
+ return o.width = n, o.height = a, o.getContext("2d").drawImage(e, 0, 0, n, a), console.warn("THREE.WebGLRenderer: Texture has been resized from (" + i.width + "x" + i.height + ") to (" + n + "x" + a + ")."), o;
+ } else return "data" in e && console.warn("THREE.WebGLRenderer: Image in DataTexture is too big (" + i.width + "x" + i.height + ")."), e;
+ return e;
+ }
+ function T(e) {
+ return e.generateMipmaps;
+ }
+ function E(t) {
+ e.generateMipmap(t);
+ }
+ function D(t) {
+ return t.isWebGLCubeRenderTarget ? e.TEXTURE_CUBE_MAP : t.isWebGL3DRenderTarget ? e.TEXTURE_3D : t.isWebGLArrayRenderTarget || t.isCompressedArrayTexture ? e.TEXTURE_2D_ARRAY : e.TEXTURE_2D;
+ }
+ function O(n, r, i, a, o = !1) {
+ if (n !== null) {
+ if (e[n] !== void 0) return e[n];
+ console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '" + n + "'");
+ }
+ let s = r;
+ if (r === e.RED && (i === e.FLOAT && (s = e.R32F), i === e.HALF_FLOAT && (s = e.R16F), i === e.UNSIGNED_BYTE && (s = e.R8)), r === e.RED_INTEGER && (i === e.UNSIGNED_BYTE && (s = e.R8UI), i === e.UNSIGNED_SHORT && (s = e.R16UI), i === e.UNSIGNED_INT && (s = e.R32UI), i === e.BYTE && (s = e.R8I), i === e.SHORT && (s = e.R16I), i === e.INT && (s = e.R32I)), r === e.RG && (i === e.FLOAT && (s = e.RG32F), i === e.HALF_FLOAT && (s = e.RG16F), i === e.UNSIGNED_BYTE && (s = e.RG8)), r === e.RG_INTEGER && (i === e.UNSIGNED_BYTE && (s = e.RG8UI), i === e.UNSIGNED_SHORT && (s = e.RG16UI), i === e.UNSIGNED_INT && (s = e.RG32UI), i === e.BYTE && (s = e.RG8I), i === e.SHORT && (s = e.RG16I), i === e.INT && (s = e.RG32I)), r === e.RGB_INTEGER && (i === e.UNSIGNED_BYTE && (s = e.RGB8UI), i === e.UNSIGNED_SHORT && (s = e.RGB16UI), i === e.UNSIGNED_INT && (s = e.RGB32UI), i === e.BYTE && (s = e.RGB8I), i === e.SHORT && (s = e.RGB16I), i === e.INT && (s = e.RGB32I)), r === e.RGBA_INTEGER && (i === e.UNSIGNED_BYTE && (s = e.RGBA8UI), i === e.UNSIGNED_SHORT && (s = e.RGBA16UI), i === e.UNSIGNED_INT && (s = e.RGBA32UI), i === e.BYTE && (s = e.RGBA8I), i === e.SHORT && (s = e.RGBA16I), i === e.INT && (s = e.RGBA32I)), r === e.RGB && i === e.UNSIGNED_INT_5_9_9_9_REV && (s = e.RGB9_E5), r === e.RGBA) {
+ let t = o ? qe : Rt.getTransfer(a);
+ i === e.FLOAT && (s = e.RGBA32F), i === e.HALF_FLOAT && (s = e.RGBA16F), i === e.UNSIGNED_BYTE && (s = t === "srgb" ? e.SRGB8_ALPHA8 : e.RGBA8), i === e.UNSIGNED_SHORT_4_4_4_4 && (s = e.RGBA4), i === e.UNSIGNED_SHORT_5_5_5_1 && (s = e.RGB5_A1);
+ }
+ return (s === e.R16F || s === e.R32F || s === e.RG16F || s === e.RG32F || s === e.RGBA16F || s === e.RGBA32F) && t.get("EXT_color_buffer_float"), s;
+ }
+ function k(t, n) {
+ let r;
+ return t ? n === null || n === 1014 || n === 1020 ? r = e.DEPTH24_STENCIL8 : n === 1015 ? r = e.DEPTH32F_STENCIL8 : n === 1012 && (r = e.DEPTH24_STENCIL8, console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")) : n === null || n === 1014 || n === 1020 ? r = e.DEPTH_COMPONENT24 : n === 1015 ? r = e.DEPTH_COMPONENT32F : n === 1012 && (r = e.DEPTH_COMPONENT16), r;
+ }
+ function A(e, t) {
+ return T(e) === !0 || e.isFramebufferTexture && e.minFilter !== 1003 && e.minFilter !== 1006 ? Math.log2(Math.max(t.width, t.height)) + 1 : e.mipmaps !== void 0 && e.mipmaps.length > 0 ? e.mipmaps.length : e.isCompressedTexture && Array.isArray(e.image) ? t.mipmaps.length : 1;
+ }
+ function te(e) {
+ let t = e.target;
+ t.removeEventListener("dispose", te), re(t), t.isVideoTexture && y.delete(t);
+ }
+ function ne(e) {
+ let t = e.target;
+ t.removeEventListener("dispose", ne), ae(t);
+ }
+ function re(e) {
+ let t = r.get(e);
+ if (t.__webglInit === void 0) return;
+ let n = e.source, i = x.get(n);
+ if (i) {
+ let r = i[t.__cacheKey];
+ r.usedTimes--, r.usedTimes === 0 && ie(e), Object.keys(i).length === 0 && x.delete(n);
+ }
+ r.remove(e);
+ }
+ function ie(t) {
+ let n = r.get(t);
+ e.deleteTexture(n.__webglTexture);
+ let i = t.source, a = x.get(i);
+ delete a[n.__cacheKey], h.memory.textures--;
+ }
+ function ae(t) {
+ let n = r.get(t);
+ if (t.depthTexture && (t.depthTexture.dispose(), r.remove(t.depthTexture)), t.isWebGLCubeRenderTarget) for (let t = 0; t < 6; t++) {
+ if (Array.isArray(n.__webglFramebuffer[t])) for (let r = 0; r < n.__webglFramebuffer[t].length; r++) e.deleteFramebuffer(n.__webglFramebuffer[t][r]);
+ else e.deleteFramebuffer(n.__webglFramebuffer[t]);
+ n.__webglDepthbuffer && e.deleteRenderbuffer(n.__webglDepthbuffer[t]);
+ }
+ else {
+ if (Array.isArray(n.__webglFramebuffer)) for (let t = 0; t < n.__webglFramebuffer.length; t++) e.deleteFramebuffer(n.__webglFramebuffer[t]);
+ else e.deleteFramebuffer(n.__webglFramebuffer);
+ if (n.__webglDepthbuffer && e.deleteRenderbuffer(n.__webglDepthbuffer), n.__webglMultisampledFramebuffer && e.deleteFramebuffer(n.__webglMultisampledFramebuffer), n.__webglColorRenderbuffer) for (let t = 0; t < n.__webglColorRenderbuffer.length; t++) n.__webglColorRenderbuffer[t] && e.deleteRenderbuffer(n.__webglColorRenderbuffer[t]);
+ n.__webglDepthRenderbuffer && e.deleteRenderbuffer(n.__webglDepthRenderbuffer);
+ }
+ let i = t.textures;
+ for (let t = 0, n = i.length; t < n; t++) {
+ let n = r.get(i[t]);
+ n.__webglTexture && (e.deleteTexture(n.__webglTexture), h.memory.textures--), r.remove(i[t]);
+ }
+ r.remove(t);
+ }
+ let oe = 0;
+ function se() {
+ oe = 0;
+ }
+ function ce() {
+ let e = oe;
+ return e >= i.maxTextures && console.warn("THREE.WebGLTextures: Trying to use " + e + " texture units while this GPU supports only " + i.maxTextures), oe += 1, e;
+ }
+ function le(e) {
+ let t = [];
+ return t.push(e.wrapS), t.push(e.wrapT), t.push(e.wrapR || 0), t.push(e.magFilter), t.push(e.minFilter), t.push(e.anisotropy), t.push(e.internalFormat), t.push(e.format), t.push(e.type), t.push(e.generateMipmaps), t.push(e.premultiplyAlpha), t.push(e.flipY), t.push(e.unpackAlignment), t.push(e.colorSpace), t.join();
+ }
+ function ue(t, i) {
+ let a = r.get(t);
+ if (t.isVideoTexture && Oe(t), t.isRenderTargetTexture === !1 && t.version > 0 && a.__version !== t.version) {
+ let e = t.image;
+ if (e === null) console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");
+ else if (e.complete === !1) console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");
+ else {
+ ye(a, t, i);
+ return;
+ }
+ }
+ n.bindTexture(e.TEXTURE_2D, a.__webglTexture, e.TEXTURE0 + i);
+ }
+ function de(t, i) {
+ let a = r.get(t);
+ if (t.version > 0 && a.__version !== t.version) {
+ ye(a, t, i);
+ return;
+ }
+ n.bindTexture(e.TEXTURE_2D_ARRAY, a.__webglTexture, e.TEXTURE0 + i);
+ }
+ function fe(t, i) {
+ let a = r.get(t);
+ if (t.version > 0 && a.__version !== t.version) {
+ ye(a, t, i);
+ return;
+ }
+ n.bindTexture(e.TEXTURE_3D, a.__webglTexture, e.TEXTURE0 + i);
+ }
+ function pe(t, i) {
+ let a = r.get(t);
+ if (t.version > 0 && a.__version !== t.version) {
+ be(a, t, i);
+ return;
+ }
+ n.bindTexture(e.TEXTURE_CUBE_MAP, a.__webglTexture, e.TEXTURE0 + i);
+ }
+ let me = {
+ [a]: e.REPEAT,
+ [o]: e.CLAMP_TO_EDGE,
+ [s]: e.MIRRORED_REPEAT
+ }, he = {
+ [c]: e.NEAREST,
+ [l]: e.NEAREST_MIPMAP_NEAREST,
+ [u]: e.NEAREST_MIPMAP_LINEAR,
+ [d]: e.LINEAR,
+ [f]: e.LINEAR_MIPMAP_NEAREST,
+ [p]: e.LINEAR_MIPMAP_LINEAR
+ }, ge = {
+ 512: e.NEVER,
+ 519: e.ALWAYS,
+ 513: e.LESS,
+ 515: e.LEQUAL,
+ 514: e.EQUAL,
+ 518: e.GEQUAL,
+ 516: e.GREATER,
+ 517: e.NOTEQUAL
+ };
+ function _e(n, a) {
+ if (a.type === 1015 && t.has("OES_texture_float_linear") === !1 && (a.magFilter === 1006 || a.magFilter === 1007 || a.magFilter === 1005 || a.magFilter === 1008 || a.minFilter === 1006 || a.minFilter === 1007 || a.minFilter === 1005 || a.minFilter === 1008) && console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."), e.texParameteri(n, e.TEXTURE_WRAP_S, me[a.wrapS]), e.texParameteri(n, e.TEXTURE_WRAP_T, me[a.wrapT]), (n === e.TEXTURE_3D || n === e.TEXTURE_2D_ARRAY) && e.texParameteri(n, e.TEXTURE_WRAP_R, me[a.wrapR]), e.texParameteri(n, e.TEXTURE_MAG_FILTER, he[a.magFilter]), e.texParameteri(n, e.TEXTURE_MIN_FILTER, he[a.minFilter]), a.compareFunction && (e.texParameteri(n, e.TEXTURE_COMPARE_MODE, e.COMPARE_REF_TO_TEXTURE), e.texParameteri(n, e.TEXTURE_COMPARE_FUNC, ge[a.compareFunction])), t.has("EXT_texture_filter_anisotropic") === !0) {
+ if (a.magFilter === 1003 || a.minFilter !== 1005 && a.minFilter !== 1008 || a.type === 1015 && t.has("OES_texture_float_linear") === !1) return;
+ if (a.anisotropy > 1 || r.get(a).__currentAnisotropy) {
+ let o = t.get("EXT_texture_filter_anisotropic");
+ e.texParameterf(n, o.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(a.anisotropy, i.getMaxAnisotropy())), r.get(a).__currentAnisotropy = a.anisotropy;
+ }
+ }
+ }
+ function ve(t, n) {
+ let r = !1;
+ t.__webglInit === void 0 && (t.__webglInit = !0, n.addEventListener("dispose", te));
+ let i = n.source, a = x.get(i);
+ a === void 0 && (a = {}, x.set(i, a));
+ let o = le(n);
+ if (o !== t.__cacheKey) {
+ a[o] === void 0 && (a[o] = {
+ texture: e.createTexture(),
+ usedTimes: 0
+ }, h.memory.textures++, r = !0), a[o].usedTimes++;
+ let i = a[t.__cacheKey];
+ i !== void 0 && (a[t.__cacheKey].usedTimes--, i.usedTimes === 0 && ie(n)), t.__cacheKey = o, t.__webglTexture = a[o].texture;
+ }
+ return r;
+ }
+ function ye(t, a, o) {
+ let s = e.TEXTURE_2D;
+ (a.isDataArrayTexture || a.isCompressedArrayTexture) && (s = e.TEXTURE_2D_ARRAY), a.isData3DTexture && (s = e.TEXTURE_3D);
+ let c = ve(t, a), l = a.source;
+ n.bindTexture(s, t.__webglTexture, e.TEXTURE0 + o);
+ let u = r.get(l);
+ if (l.version !== u.__version || c === !0) {
+ n.activeTexture(e.TEXTURE0 + o);
+ let t = Rt.getPrimaries(Rt.workingColorSpace), r = a.colorSpace === "" ? null : Rt.getPrimaries(a.colorSpace), d = a.colorSpace === "" || t === r ? e.NONE : e.BROWSER_DEFAULT_WEBGL;
+ e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL, a.flipY), e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL, a.premultiplyAlpha), e.pixelStorei(e.UNPACK_ALIGNMENT, a.unpackAlignment), e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL, d);
+ let f = w(a.image, !1, i.maxTextureSize);
+ f = ke(a, f);
+ let p = m.convert(a.format, a.colorSpace), h = m.convert(a.type), g = O(a.internalFormat, p, h, a.colorSpace, a.isVideoTexture);
+ _e(s, a);
+ let _, v = a.mipmaps, y = a.isVideoTexture !== !0, b = u.__version === void 0 || c === !0, x = l.dataReady, S = A(a, f);
+ if (a.isDepthTexture) g = k(a.format === ee, a.type), b && (y ? n.texStorage2D(e.TEXTURE_2D, 1, g, f.width, f.height) : n.texImage2D(e.TEXTURE_2D, 0, g, f.width, f.height, 0, p, h, null));
+ else if (a.isDataTexture) if (v.length > 0) {
+ y && b && n.texStorage2D(e.TEXTURE_2D, S, g, v[0].width, v[0].height);
+ for (let t = 0, r = v.length; t < r; t++) _ = v[t], y ? x && n.texSubImage2D(e.TEXTURE_2D, t, 0, 0, _.width, _.height, p, h, _.data) : n.texImage2D(e.TEXTURE_2D, t, g, _.width, _.height, 0, p, h, _.data);
+ a.generateMipmaps = !1;
+ } else y ? (b && n.texStorage2D(e.TEXTURE_2D, S, g, f.width, f.height), x && n.texSubImage2D(e.TEXTURE_2D, 0, 0, 0, f.width, f.height, p, h, f.data)) : n.texImage2D(e.TEXTURE_2D, 0, g, f.width, f.height, 0, p, h, f.data);
+ else if (a.isCompressedTexture) if (a.isCompressedArrayTexture) {
+ y && b && n.texStorage3D(e.TEXTURE_2D_ARRAY, S, g, v[0].width, v[0].height, f.depth);
+ for (let t = 0, r = v.length; t < r; t++) if (_ = v[t], a.format !== 1023) if (p !== null) if (y) {
+ if (x) if (a.layerUpdates.size > 0) {
+ let r = os(_.width, _.height, a.format, a.type);
+ for (let i of a.layerUpdates) {
+ let a = _.data.subarray(i * r / _.data.BYTES_PER_ELEMENT, (i + 1) * r / _.data.BYTES_PER_ELEMENT);
+ n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY, t, 0, 0, i, _.width, _.height, 1, p, a);
+ }
+ a.clearLayerUpdates();
+ } else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY, t, 0, 0, 0, _.width, _.height, f.depth, p, _.data);
+ } else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY, t, g, _.width, _.height, f.depth, 0, _.data, 0, 0);
+ else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");
+ else y ? x && n.texSubImage3D(e.TEXTURE_2D_ARRAY, t, 0, 0, 0, _.width, _.height, f.depth, p, h, _.data) : n.texImage3D(e.TEXTURE_2D_ARRAY, t, g, _.width, _.height, f.depth, 0, p, h, _.data);
+ } else {
+ y && b && n.texStorage2D(e.TEXTURE_2D, S, g, v[0].width, v[0].height);
+ for (let t = 0, r = v.length; t < r; t++) _ = v[t], a.format === 1023 ? y ? x && n.texSubImage2D(e.TEXTURE_2D, t, 0, 0, _.width, _.height, p, h, _.data) : n.texImage2D(e.TEXTURE_2D, t, g, _.width, _.height, 0, p, h, _.data) : p === null ? console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()") : y ? x && n.compressedTexSubImage2D(e.TEXTURE_2D, t, 0, 0, _.width, _.height, p, _.data) : n.compressedTexImage2D(e.TEXTURE_2D, t, g, _.width, _.height, 0, _.data);
+ }
+ else if (a.isDataArrayTexture) if (y) {
+ if (b && n.texStorage3D(e.TEXTURE_2D_ARRAY, S, g, f.width, f.height, f.depth), x) if (a.layerUpdates.size > 0) {
+ let t = os(f.width, f.height, a.format, a.type);
+ for (let r of a.layerUpdates) {
+ let i = f.data.subarray(r * t / f.data.BYTES_PER_ELEMENT, (r + 1) * t / f.data.BYTES_PER_ELEMENT);
+ n.texSubImage3D(e.TEXTURE_2D_ARRAY, 0, 0, 0, r, f.width, f.height, 1, p, h, i);
+ }
+ a.clearLayerUpdates();
+ } else n.texSubImage3D(e.TEXTURE_2D_ARRAY, 0, 0, 0, 0, f.width, f.height, f.depth, p, h, f.data);
+ } else n.texImage3D(e.TEXTURE_2D_ARRAY, 0, g, f.width, f.height, f.depth, 0, p, h, f.data);
+ else if (a.isData3DTexture) y ? (b && n.texStorage3D(e.TEXTURE_3D, S, g, f.width, f.height, f.depth), x && n.texSubImage3D(e.TEXTURE_3D, 0, 0, 0, 0, f.width, f.height, f.depth, p, h, f.data)) : n.texImage3D(e.TEXTURE_3D, 0, g, f.width, f.height, f.depth, 0, p, h, f.data);
+ else if (a.isFramebufferTexture) {
+ if (b) if (y) n.texStorage2D(e.TEXTURE_2D, S, g, f.width, f.height);
+ else {
+ let t = f.width, r = f.height;
+ for (let i = 0; i < S; i++) n.texImage2D(e.TEXTURE_2D, i, g, t, r, 0, p, h, null), t >>= 1, r >>= 1;
+ }
+ } else if (v.length > 0) {
+ if (y && b) {
+ let t = Ae(v[0]);
+ n.texStorage2D(e.TEXTURE_2D, S, g, t.width, t.height);
+ }
+ for (let t = 0, r = v.length; t < r; t++) _ = v[t], y ? x && n.texSubImage2D(e.TEXTURE_2D, t, 0, 0, p, h, _) : n.texImage2D(e.TEXTURE_2D, t, g, p, h, _);
+ a.generateMipmaps = !1;
+ } else if (y) {
+ if (b) {
+ let t = Ae(f);
+ n.texStorage2D(e.TEXTURE_2D, S, g, t.width, t.height);
+ }
+ x && n.texSubImage2D(e.TEXTURE_2D, 0, 0, 0, p, h, f);
+ } else n.texImage2D(e.TEXTURE_2D, 0, g, p, h, f);
+ T(a) && E(s), u.__version = l.version, a.onUpdate && a.onUpdate(a);
+ }
+ t.__version = a.version;
+ }
+ function be(t, a, o) {
+ if (a.image.length !== 6) return;
+ let s = ve(t, a), c = a.source;
+ n.bindTexture(e.TEXTURE_CUBE_MAP, t.__webglTexture, e.TEXTURE0 + o);
+ let l = r.get(c);
+ if (c.version !== l.__version || s === !0) {
+ n.activeTexture(e.TEXTURE0 + o);
+ let t = Rt.getPrimaries(Rt.workingColorSpace), r = a.colorSpace === "" ? null : Rt.getPrimaries(a.colorSpace), u = a.colorSpace === "" || t === r ? e.NONE : e.BROWSER_DEFAULT_WEBGL;
+ e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL, a.flipY), e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL, a.premultiplyAlpha), e.pixelStorei(e.UNPACK_ALIGNMENT, a.unpackAlignment), e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL, u);
+ let d = a.isCompressedTexture || a.image[0].isCompressedTexture, f = a.image[0] && a.image[0].isDataTexture, p = [];
+ for (let e = 0; e < 6; e++) !d && !f ? p[e] = w(a.image[e], !0, i.maxCubemapSize) : p[e] = f ? a.image[e].image : a.image[e], p[e] = ke(a, p[e]);
+ let h = p[0], g = m.convert(a.format, a.colorSpace), _ = m.convert(a.type), v = O(a.internalFormat, g, _, a.colorSpace), y = a.isVideoTexture !== !0, b = l.__version === void 0 || s === !0, x = c.dataReady, S = A(a, h);
+ _e(e.TEXTURE_CUBE_MAP, a);
+ let C;
+ if (d) {
+ y && b && n.texStorage2D(e.TEXTURE_CUBE_MAP, S, v, h.width, h.height);
+ for (let t = 0; t < 6; t++) {
+ C = p[t].mipmaps;
+ for (let r = 0; r < C.length; r++) {
+ let i = C[r];
+ a.format === 1023 ? y ? x && n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X + t, r, 0, 0, i.width, i.height, g, _, i.data) : n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X + t, r, v, i.width, i.height, 0, g, _, i.data) : g === null ? console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()") : y ? x && n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X + t, r, 0, 0, i.width, i.height, g, i.data) : n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X + t, r, v, i.width, i.height, 0, i.data);
+ }
+ }
+ } else {
+ if (C = a.mipmaps, y && b) {
+ C.length > 0 && S++;
+ let t = Ae(p[0]);
+ n.texStorage2D(e.TEXTURE_CUBE_MAP, S, v, t.width, t.height);
+ }
+ for (let t = 0; t < 6; t++) if (f) {
+ y ? x && n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X + t, 0, 0, 0, p[t].width, p[t].height, g, _, p[t].data) : n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X + t, 0, v, p[t].width, p[t].height, 0, g, _, p[t].data);
+ for (let r = 0; r < C.length; r++) {
+ let i = C[r].image[t].image;
+ y ? x && n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X + t, r + 1, 0, 0, i.width, i.height, g, _, i.data) : n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X + t, r + 1, v, i.width, i.height, 0, g, _, i.data);
+ }
+ } else {
+ y ? x && n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X + t, 0, 0, 0, g, _, p[t]) : n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X + t, 0, v, g, _, p[t]);
+ for (let r = 0; r < C.length; r++) {
+ let i = C[r];
+ y ? x && n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X + t, r + 1, 0, 0, g, _, i.image[t]) : n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X + t, r + 1, v, g, _, i.image[t]);
+ }
+ }
+ }
+ T(a) && E(e.TEXTURE_CUBE_MAP), l.__version = c.version, a.onUpdate && a.onUpdate(a);
+ }
+ t.__version = a.version;
+ }
+ function j(t, i, a, o, s, c) {
+ let l = m.convert(a.format, a.colorSpace), u = m.convert(a.type), d = O(a.internalFormat, l, u, a.colorSpace), f = r.get(i), p = r.get(a);
+ if (p.__renderTarget = i, !f.__hasExternalTextures) {
+ let t = Math.max(1, i.width >> c), r = Math.max(1, i.height >> c);
+ s === e.TEXTURE_3D || s === e.TEXTURE_2D_ARRAY ? n.texImage3D(s, c, d, t, r, i.depth, 0, l, u, null) : n.texImage2D(s, c, d, t, r, 0, l, u, null);
+ }
+ n.bindFramebuffer(e.FRAMEBUFFER, t), De(i) ? g.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER, o, s, p.__webglTexture, 0, F(i)) : (s === e.TEXTURE_2D || s >= e.TEXTURE_CUBE_MAP_POSITIVE_X && s <= e.TEXTURE_CUBE_MAP_NEGATIVE_Z) && e.framebufferTexture2D(e.FRAMEBUFFER, o, s, p.__webglTexture, c), n.bindFramebuffer(e.FRAMEBUFFER, null);
+ }
+ function xe(t, n, r) {
+ if (e.bindRenderbuffer(e.RENDERBUFFER, t), n.depthBuffer) {
+ let i = n.depthTexture, a = i && i.isDepthTexture ? i.type : null, o = k(n.stencilBuffer, a), s = n.stencilBuffer ? e.DEPTH_STENCIL_ATTACHMENT : e.DEPTH_ATTACHMENT, c = F(n);
+ De(n) ? g.renderbufferStorageMultisampleEXT(e.RENDERBUFFER, c, o, n.width, n.height) : r ? e.renderbufferStorageMultisample(e.RENDERBUFFER, c, o, n.width, n.height) : e.renderbufferStorage(e.RENDERBUFFER, o, n.width, n.height), e.framebufferRenderbuffer(e.FRAMEBUFFER, s, e.RENDERBUFFER, t);
+ } else {
+ let t = n.textures;
+ for (let i = 0; i < t.length; i++) {
+ let a = t[i], o = m.convert(a.format, a.colorSpace), s = m.convert(a.type), c = O(a.internalFormat, o, s, a.colorSpace), l = F(n);
+ r && De(n) === !1 ? e.renderbufferStorageMultisample(e.RENDERBUFFER, l, c, n.width, n.height) : De(n) ? g.renderbufferStorageMultisampleEXT(e.RENDERBUFFER, l, c, n.width, n.height) : e.renderbufferStorage(e.RENDERBUFFER, c, n.width, n.height);
+ }
+ }
+ e.bindRenderbuffer(e.RENDERBUFFER, null);
+ }
+ function Se(t, i) {
+ if (i && i.isWebGLCubeRenderTarget) throw Error("Depth Texture with cube render targets is not supported");
+ if (n.bindFramebuffer(e.FRAMEBUFFER, t), !(i.depthTexture && i.depthTexture.isDepthTexture)) throw Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");
+ let a = r.get(i.depthTexture);
+ a.__renderTarget = i, (!a.__webglTexture || i.depthTexture.image.width !== i.width || i.depthTexture.image.height !== i.height) && (i.depthTexture.image.width = i.width, i.depthTexture.image.height = i.height, i.depthTexture.needsUpdate = !0), ue(i.depthTexture, 0);
+ let o = a.__webglTexture, s = F(i);
+ if (i.depthTexture.format === 1026) De(i) ? g.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER, e.DEPTH_ATTACHMENT, e.TEXTURE_2D, o, 0, s) : e.framebufferTexture2D(e.FRAMEBUFFER, e.DEPTH_ATTACHMENT, e.TEXTURE_2D, o, 0);
+ else if (i.depthTexture.format === 1027) De(i) ? g.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER, e.DEPTH_STENCIL_ATTACHMENT, e.TEXTURE_2D, o, 0, s) : e.framebufferTexture2D(e.FRAMEBUFFER, e.DEPTH_STENCIL_ATTACHMENT, e.TEXTURE_2D, o, 0);
+ else throw Error("Unknown depthTexture format");
+ }
+ function Ce(t) {
+ let i = r.get(t), a = t.isWebGLCubeRenderTarget === !0;
+ if (i.__boundDepthTexture !== t.depthTexture) {
+ let e = t.depthTexture;
+ if (i.__depthDisposeCallback && i.__depthDisposeCallback(), e) {
+ let t = () => {
+ delete i.__boundDepthTexture, delete i.__depthDisposeCallback, e.removeEventListener("dispose", t);
+ };
+ e.addEventListener("dispose", t), i.__depthDisposeCallback = t;
+ }
+ i.__boundDepthTexture = e;
+ }
+ if (t.depthTexture && !i.__autoAllocateDepthBuffer) {
+ if (a) throw Error("target.depthTexture not supported in Cube render targets");
+ let e = t.texture.mipmaps;
+ e && e.length > 0 ? Se(i.__webglFramebuffer[0], t) : Se(i.__webglFramebuffer, t);
+ } else if (a) {
+ i.__webglDepthbuffer = [];
+ for (let r = 0; r < 6; r++) if (n.bindFramebuffer(e.FRAMEBUFFER, i.__webglFramebuffer[r]), i.__webglDepthbuffer[r] === void 0) i.__webglDepthbuffer[r] = e.createRenderbuffer(), xe(i.__webglDepthbuffer[r], t, !1);
+ else {
+ let n = t.stencilBuffer ? e.DEPTH_STENCIL_ATTACHMENT : e.DEPTH_ATTACHMENT, a = i.__webglDepthbuffer[r];
+ e.bindRenderbuffer(e.RENDERBUFFER, a), e.framebufferRenderbuffer(e.FRAMEBUFFER, n, e.RENDERBUFFER, a);
+ }
+ } else {
+ let r = t.texture.mipmaps;
+ if (r && r.length > 0 ? n.bindFramebuffer(e.FRAMEBUFFER, i.__webglFramebuffer[0]) : n.bindFramebuffer(e.FRAMEBUFFER, i.__webglFramebuffer), i.__webglDepthbuffer === void 0) i.__webglDepthbuffer = e.createRenderbuffer(), xe(i.__webglDepthbuffer, t, !1);
+ else {
+ let n = t.stencilBuffer ? e.DEPTH_STENCIL_ATTACHMENT : e.DEPTH_ATTACHMENT, r = i.__webglDepthbuffer;
+ e.bindRenderbuffer(e.RENDERBUFFER, r), e.framebufferRenderbuffer(e.FRAMEBUFFER, n, e.RENDERBUFFER, r);
+ }
+ }
+ n.bindFramebuffer(e.FRAMEBUFFER, null);
+ }
+ function M(t, n, i) {
+ let a = r.get(t);
+ n !== void 0 && j(a.__webglFramebuffer, t, t.texture, e.COLOR_ATTACHMENT0, e.TEXTURE_2D, 0), i !== void 0 && Ce(t);
+ }
+ function we(t) {
+ let i = t.texture, a = r.get(t), o = r.get(i);
+ t.addEventListener("dispose", ne);
+ let s = t.textures, c = t.isWebGLCubeRenderTarget === !0, l = s.length > 1;
+ if (l || (o.__webglTexture === void 0 && (o.__webglTexture = e.createTexture()), o.__version = i.version, h.memory.textures++), c) {
+ a.__webglFramebuffer = [];
+ for (let t = 0; t < 6; t++) if (i.mipmaps && i.mipmaps.length > 0) {
+ a.__webglFramebuffer[t] = [];
+ for (let n = 0; n < i.mipmaps.length; n++) a.__webglFramebuffer[t][n] = e.createFramebuffer();
+ } else a.__webglFramebuffer[t] = e.createFramebuffer();
+ } else {
+ if (i.mipmaps && i.mipmaps.length > 0) {
+ a.__webglFramebuffer = [];
+ for (let t = 0; t < i.mipmaps.length; t++) a.__webglFramebuffer[t] = e.createFramebuffer();
+ } else a.__webglFramebuffer = e.createFramebuffer();
+ if (l) for (let t = 0, n = s.length; t < n; t++) {
+ let n = r.get(s[t]);
+ n.__webglTexture === void 0 && (n.__webglTexture = e.createTexture(), h.memory.textures++);
+ }
+ if (t.samples > 0 && De(t) === !1) {
+ a.__webglMultisampledFramebuffer = e.createFramebuffer(), a.__webglColorRenderbuffer = [], n.bindFramebuffer(e.FRAMEBUFFER, a.__webglMultisampledFramebuffer);
+ for (let n = 0; n < s.length; n++) {
+ let r = s[n];
+ a.__webglColorRenderbuffer[n] = e.createRenderbuffer(), e.bindRenderbuffer(e.RENDERBUFFER, a.__webglColorRenderbuffer[n]);
+ let i = m.convert(r.format, r.colorSpace), o = m.convert(r.type), c = O(r.internalFormat, i, o, r.colorSpace, t.isXRRenderTarget === !0), l = F(t);
+ e.renderbufferStorageMultisample(e.RENDERBUFFER, l, c, t.width, t.height), e.framebufferRenderbuffer(e.FRAMEBUFFER, e.COLOR_ATTACHMENT0 + n, e.RENDERBUFFER, a.__webglColorRenderbuffer[n]);
+ }
+ e.bindRenderbuffer(e.RENDERBUFFER, null), t.depthBuffer && (a.__webglDepthRenderbuffer = e.createRenderbuffer(), xe(a.__webglDepthRenderbuffer, t, !0)), n.bindFramebuffer(e.FRAMEBUFFER, null);
+ }
+ }
+ if (c) {
+ n.bindTexture(e.TEXTURE_CUBE_MAP, o.__webglTexture), _e(e.TEXTURE_CUBE_MAP, i);
+ for (let n = 0; n < 6; n++) if (i.mipmaps && i.mipmaps.length > 0) for (let r = 0; r < i.mipmaps.length; r++) j(a.__webglFramebuffer[n][r], t, i, e.COLOR_ATTACHMENT0, e.TEXTURE_CUBE_MAP_POSITIVE_X + n, r);
+ else j(a.__webglFramebuffer[n], t, i, e.COLOR_ATTACHMENT0, e.TEXTURE_CUBE_MAP_POSITIVE_X + n, 0);
+ T(i) && E(e.TEXTURE_CUBE_MAP), n.unbindTexture();
+ } else if (l) {
+ for (let i = 0, o = s.length; i < o; i++) {
+ let o = s[i], c = r.get(o);
+ n.bindTexture(e.TEXTURE_2D, c.__webglTexture), _e(e.TEXTURE_2D, o), j(a.__webglFramebuffer, t, o, e.COLOR_ATTACHMENT0 + i, e.TEXTURE_2D, 0), T(o) && E(e.TEXTURE_2D);
+ }
+ n.unbindTexture();
+ } else {
+ let r = e.TEXTURE_2D;
+ if ((t.isWebGL3DRenderTarget || t.isWebGLArrayRenderTarget) && (r = t.isWebGL3DRenderTarget ? e.TEXTURE_3D : e.TEXTURE_2D_ARRAY), n.bindTexture(r, o.__webglTexture), _e(r, i), i.mipmaps && i.mipmaps.length > 0) for (let n = 0; n < i.mipmaps.length; n++) j(a.__webglFramebuffer[n], t, i, e.COLOR_ATTACHMENT0, r, n);
+ else j(a.__webglFramebuffer, t, i, e.COLOR_ATTACHMENT0, r, 0);
+ T(i) && E(r), n.unbindTexture();
+ }
+ t.depthBuffer && Ce(t);
+ }
+ function N(e) {
+ let t = e.textures;
+ for (let i = 0, a = t.length; i < a; i++) {
+ let a = t[i];
+ if (T(a)) {
+ let t = D(e), i = r.get(a).__webglTexture;
+ n.bindTexture(t, i), E(t), n.unbindTexture();
+ }
+ }
+ }
+ let P = [], Te = [];
+ function Ee(t) {
+ if (t.samples > 0) {
+ if (De(t) === !1) {
+ let i = t.textures, a = t.width, o = t.height, s = e.COLOR_BUFFER_BIT, c = t.stencilBuffer ? e.DEPTH_STENCIL_ATTACHMENT : e.DEPTH_ATTACHMENT, l = r.get(t), u = i.length > 1;
+ if (u) for (let t = 0; t < i.length; t++) n.bindFramebuffer(e.FRAMEBUFFER, l.__webglMultisampledFramebuffer), e.framebufferRenderbuffer(e.FRAMEBUFFER, e.COLOR_ATTACHMENT0 + t, e.RENDERBUFFER, null), n.bindFramebuffer(e.FRAMEBUFFER, l.__webglFramebuffer), e.framebufferTexture2D(e.DRAW_FRAMEBUFFER, e.COLOR_ATTACHMENT0 + t, e.TEXTURE_2D, null, 0);
+ n.bindFramebuffer(e.READ_FRAMEBUFFER, l.__webglMultisampledFramebuffer);
+ let d = t.texture.mipmaps;
+ d && d.length > 0 ? n.bindFramebuffer(e.DRAW_FRAMEBUFFER, l.__webglFramebuffer[0]) : n.bindFramebuffer(e.DRAW_FRAMEBUFFER, l.__webglFramebuffer);
+ for (let n = 0; n < i.length; n++) {
+ if (t.resolveDepthBuffer && (t.depthBuffer && (s |= e.DEPTH_BUFFER_BIT), t.stencilBuffer && t.resolveStencilBuffer && (s |= e.STENCIL_BUFFER_BIT)), u) {
+ e.framebufferRenderbuffer(e.READ_FRAMEBUFFER, e.COLOR_ATTACHMENT0, e.RENDERBUFFER, l.__webglColorRenderbuffer[n]);
+ let t = r.get(i[n]).__webglTexture;
+ e.framebufferTexture2D(e.DRAW_FRAMEBUFFER, e.COLOR_ATTACHMENT0, e.TEXTURE_2D, t, 0);
+ }
+ e.blitFramebuffer(0, 0, a, o, 0, 0, a, o, s, e.NEAREST), _ === !0 && (P.length = 0, Te.length = 0, P.push(e.COLOR_ATTACHMENT0 + n), t.depthBuffer && t.resolveDepthBuffer === !1 && (P.push(c), Te.push(c), e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER, Te)), e.invalidateFramebuffer(e.READ_FRAMEBUFFER, P));
+ }
+ if (n.bindFramebuffer(e.READ_FRAMEBUFFER, null), n.bindFramebuffer(e.DRAW_FRAMEBUFFER, null), u) for (let t = 0; t < i.length; t++) {
+ n.bindFramebuffer(e.FRAMEBUFFER, l.__webglMultisampledFramebuffer), e.framebufferRenderbuffer(e.FRAMEBUFFER, e.COLOR_ATTACHMENT0 + t, e.RENDERBUFFER, l.__webglColorRenderbuffer[t]);
+ let a = r.get(i[t]).__webglTexture;
+ n.bindFramebuffer(e.FRAMEBUFFER, l.__webglFramebuffer), e.framebufferTexture2D(e.DRAW_FRAMEBUFFER, e.COLOR_ATTACHMENT0 + t, e.TEXTURE_2D, a, 0);
+ }
+ n.bindFramebuffer(e.DRAW_FRAMEBUFFER, l.__webglMultisampledFramebuffer);
+ } else if (t.depthBuffer && t.resolveDepthBuffer === !1 && _) {
+ let n = t.stencilBuffer ? e.DEPTH_STENCIL_ATTACHMENT : e.DEPTH_ATTACHMENT;
+ e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER, [n]);
+ }
+ }
+ }
+ function F(e) {
+ return Math.min(i.maxSamples, e.samples);
+ }
+ function De(e) {
+ let n = r.get(e);
+ return e.samples > 0 && t.has("WEBGL_multisampled_render_to_texture") === !0 && n.__useRenderToTexture !== !1;
+ }
+ function Oe(e) {
+ let t = h.render.frame;
+ y.get(e) !== t && (y.set(e, t), e.update());
+ }
+ function ke(e, t) {
+ let n = e.colorSpace, r = e.format, i = e.type;
+ return e.isCompressedTexture === !0 || e.isVideoTexture === !0 || n !== "srgb-linear" && n !== "" && (Rt.getTransfer(n) === "srgb" ? (r !== 1023 || i !== 1009) && console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.") : console.error("THREE.WebGLTextures: Unsupported texture color space:", n)), t;
+ }
+ function Ae(e) {
+ return typeof HTMLImageElement < "u" && e instanceof HTMLImageElement ? (v.width = e.naturalWidth || e.width, v.height = e.naturalHeight || e.height) : typeof VideoFrame < "u" && e instanceof VideoFrame ? (v.width = e.displayWidth, v.height = e.displayHeight) : (v.width = e.width, v.height = e.height), v;
+ }
+ this.allocateTextureUnit = ce, this.resetTextureUnits = se, this.setTexture2D = ue, this.setTexture2DArray = de, this.setTexture3D = fe, this.setTextureCube = pe, this.rebindTextures = M, this.setupRenderTarget = we, this.updateRenderTargetMipmap = N, this.updateMultisampleRenderTarget = Ee, this.setupDepthRenderbuffer = Ce, this.setupFrameBufferTexture = j, this.useMultisampledRTT = De;
+}
+function eu(e, t) {
+ function n(n, r = "") {
+ let i, a = Rt.getTransfer(r);
+ if (n === 1009) return e.UNSIGNED_BYTE;
+ if (n === 1017) return e.UNSIGNED_SHORT_4_4_4_4;
+ if (n === 1018) return e.UNSIGNED_SHORT_5_5_5_1;
+ if (n === 35902) return e.UNSIGNED_INT_5_9_9_9_REV;
+ if (n === 1010) return e.BYTE;
+ if (n === 1011) return e.SHORT;
+ if (n === 1012) return e.UNSIGNED_SHORT;
+ if (n === 1013) return e.INT;
+ if (n === 1014) return e.UNSIGNED_INT;
+ if (n === 1015) return e.FLOAT;
+ if (n === 1016) return e.HALF_FLOAT;
+ if (n === 1021) return e.ALPHA;
+ if (n === 1022) return e.RGB;
+ if (n === 1023) return e.RGBA;
+ if (n === 1026) return e.DEPTH_COMPONENT;
+ if (n === 1027) return e.DEPTH_STENCIL;
+ if (n === 1028) return e.RED;
+ if (n === 1029) return e.RED_INTEGER;
+ if (n === 1030) return e.RG;
+ if (n === 1031) return e.RG_INTEGER;
+ if (n === 1033) return e.RGBA_INTEGER;
+ if (n === 33776 || n === 33777 || n === 33778 || n === 33779) if (a === "srgb") if (i = t.get("WEBGL_compressed_texture_s3tc_srgb"), i !== null) {
+ if (n === 33776) return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;
+ if (n === 33777) return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
+ if (n === 33778) return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
+ if (n === 33779) return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
+ } else return null;
+ else if (i = t.get("WEBGL_compressed_texture_s3tc"), i !== null) {
+ if (n === 33776) return i.COMPRESSED_RGB_S3TC_DXT1_EXT;
+ if (n === 33777) return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;
+ if (n === 33778) return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;
+ if (n === 33779) return i.COMPRESSED_RGBA_S3TC_DXT5_EXT;
+ } else return null;
+ if (n === 35840 || n === 35841 || n === 35842 || n === 35843) if (i = t.get("WEBGL_compressed_texture_pvrtc"), i !== null) {
+ if (n === 35840) return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
+ if (n === 35841) return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
+ if (n === 35842) return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
+ if (n === 35843) return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
+ } else return null;
+ if (n === 36196 || n === 37492 || n === 37496) if (i = t.get("WEBGL_compressed_texture_etc"), i !== null) {
+ if (n === 36196 || n === 37492) return a === "srgb" ? i.COMPRESSED_SRGB8_ETC2 : i.COMPRESSED_RGB8_ETC2;
+ if (n === 37496) return a === "srgb" ? i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : i.COMPRESSED_RGBA8_ETC2_EAC;
+ } else return null;
+ if (n === 37808 || n === 37809 || n === 37810 || n === 37811 || n === 37812 || n === 37813 || n === 37814 || n === 37815 || n === 37816 || n === 37817 || n === 37818 || n === 37819 || n === 37820 || n === 37821) if (i = t.get("WEBGL_compressed_texture_astc"), i !== null) {
+ if (n === 37808) return a === "srgb" ? i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : i.COMPRESSED_RGBA_ASTC_4x4_KHR;
+ if (n === 37809) return a === "srgb" ? i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : i.COMPRESSED_RGBA_ASTC_5x4_KHR;
+ if (n === 37810) return a === "srgb" ? i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : i.COMPRESSED_RGBA_ASTC_5x5_KHR;
+ if (n === 37811) return a === "srgb" ? i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : i.COMPRESSED_RGBA_ASTC_6x5_KHR;
+ if (n === 37812) return a === "srgb" ? i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : i.COMPRESSED_RGBA_ASTC_6x6_KHR;
+ if (n === 37813) return a === "srgb" ? i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : i.COMPRESSED_RGBA_ASTC_8x5_KHR;
+ if (n === 37814) return a === "srgb" ? i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : i.COMPRESSED_RGBA_ASTC_8x6_KHR;
+ if (n === 37815) return a === "srgb" ? i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : i.COMPRESSED_RGBA_ASTC_8x8_KHR;
+ if (n === 37816) return a === "srgb" ? i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : i.COMPRESSED_RGBA_ASTC_10x5_KHR;
+ if (n === 37817) return a === "srgb" ? i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : i.COMPRESSED_RGBA_ASTC_10x6_KHR;
+ if (n === 37818) return a === "srgb" ? i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : i.COMPRESSED_RGBA_ASTC_10x8_KHR;
+ if (n === 37819) return a === "srgb" ? i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : i.COMPRESSED_RGBA_ASTC_10x10_KHR;
+ if (n === 37820) return a === "srgb" ? i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : i.COMPRESSED_RGBA_ASTC_12x10_KHR;
+ if (n === 37821) return a === "srgb" ? i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : i.COMPRESSED_RGBA_ASTC_12x12_KHR;
+ } else return null;
+ if (n === 36492 || n === 36494 || n === 36495) if (i = t.get("EXT_texture_compression_bptc"), i !== null) {
+ if (n === 36492) return a === "srgb" ? i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : i.COMPRESSED_RGBA_BPTC_UNORM_EXT;
+ if (n === 36494) return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
+ if (n === 36495) return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
+ } else return null;
+ if (n === 36283 || n === 36284 || n === 36285 || n === 36286) if (i = t.get("EXT_texture_compression_rgtc"), i !== null) {
+ if (n === 36492) return i.COMPRESSED_RED_RGTC1_EXT;
+ if (n === 36284) return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;
+ if (n === 36285) return i.COMPRESSED_RED_GREEN_RGTC2_EXT;
+ if (n === 36286) return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
+ } else return null;
+ return n === 1020 ? e.UNSIGNED_INT_24_8 : e[n] === void 0 ? null : e[n];
+ }
+ return { convert: n };
+}
+var tu = "\nvoid main() {\n\n gl_Position = vec4( position, 1.0 );\n\n}", nu = "\nuniform sampler2DArray depthColor;\nuniform float depthWidth;\nuniform float depthHeight;\n\nvoid main() {\n\n vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );\n\n if ( coord.x >= 1.0 ) {\n\n gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;\n\n } else {\n\n gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;\n\n }\n\n}", ru = class {
+ constructor() {
+ this.texture = null, this.mesh = null, this.depthNear = 0, this.depthFar = 0;
+ }
+ init(e, t, n) {
+ if (this.texture === null) {
+ let r = new qt(), i = e.properties.get(r);
+ i.__webglTexture = t.texture, (t.depthNear !== n.depthNear || t.depthFar !== n.depthFar) && (this.depthNear = t.depthNear, this.depthFar = t.depthFar), this.texture = r;
+ }
+ }
+ getMesh(e) {
+ if (this.texture !== null && this.mesh === null) {
+ let t = e.cameras[0].viewport, n = new pi({
+ vertexShader: tu,
+ fragmentShader: nu,
+ uniforms: {
+ depthColor: { value: this.texture },
+ depthWidth: { value: t.z },
+ depthHeight: { value: t.w }
+ }
+ });
+ this.mesh = new ni(new Na(20, 20), n);
+ }
+ return this.mesh;
+ }
+ reset() {
+ this.texture = null, this.mesh = null;
+ }
+ getDepthTexture() {
+ return this.texture;
+ }
+}, iu = class extends Qe {
+ constructor(e, t) {
+ super();
+ let n = this, r = null, i = 1, a = null, o = "local-floor", s = 1, c = null, l = null, u = null, d = null, f = null, p = null, h = new ru(), g = t.getContextAttributes(), _ = null, v = null, b = [], x = [], S = new L(), C = null, T = new vi();
+ T.viewport = new Jt();
+ let E = new vi();
+ E.viewport = new Jt();
+ let D = [T, E], A = new Po(), te = null, ne = null;
+ this.cameraAutoUpdate = !0, this.enabled = !1, this.isPresenting = !1, this.getController = function(e) {
+ let t = b[e];
+ return t === void 0 && (t = new Ei(), b[e] = t), t.getTargetRaySpace();
+ }, this.getControllerGrip = function(e) {
+ let t = b[e];
+ return t === void 0 && (t = new Ei(), b[e] = t), t.getGripSpace();
+ }, this.getHand = function(e) {
+ let t = b[e];
+ return t === void 0 && (t = new Ei(), b[e] = t), t.getHandSpace();
+ };
+ function re(e) {
+ let t = x.indexOf(e.inputSource);
+ if (t === -1) return;
+ let n = b[t];
+ n !== void 0 && (n.update(e.inputSource, e.frame, c || a), n.dispatchEvent({
+ type: e.type,
+ data: e.inputSource
+ }));
+ }
+ function ie() {
+ r.removeEventListener("select", re), r.removeEventListener("selectstart", re), r.removeEventListener("selectend", re), r.removeEventListener("squeeze", re), r.removeEventListener("squeezestart", re), r.removeEventListener("squeezeend", re), r.removeEventListener("end", ie), r.removeEventListener("inputsourceschange", ae);
+ for (let e = 0; e < b.length; e++) {
+ let t = x[e];
+ t !== null && (x[e] = null, b[e].disconnect(t));
+ }
+ te = null, ne = null, h.reset(), e.setRenderTarget(_), f = null, d = null, u = null, r = null, v = null, pe.stop(), n.isPresenting = !1, e.setPixelRatio(C), e.setSize(S.width, S.height, !1), n.dispatchEvent({ type: "sessionend" });
+ }
+ this.setFramebufferScaleFactor = function(e) {
+ i = e, n.isPresenting === !0 && console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.");
+ }, this.setReferenceSpaceType = function(e) {
+ o = e, n.isPresenting === !0 && console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.");
+ }, this.getReferenceSpace = function() {
+ return c || a;
+ }, this.setReferenceSpace = function(e) {
+ c = e;
+ }, this.getBaseLayer = function() {
+ return d === null ? f : d;
+ }, this.getBinding = function() {
+ return u;
+ }, this.getFrame = function() {
+ return p;
+ }, this.getSession = function() {
+ return r;
+ }, this.setSession = async function(l) {
+ if (r = l, r !== null) {
+ if (_ = e.getRenderTarget(), r.addEventListener("select", re), r.addEventListener("selectstart", re), r.addEventListener("selectend", re), r.addEventListener("squeeze", re), r.addEventListener("squeezestart", re), r.addEventListener("squeezeend", re), r.addEventListener("end", ie), r.addEventListener("inputsourceschange", ae), g.xrCompatible !== !0 && await t.makeXRCompatible(), C = e.getPixelRatio(), e.getSize(S), typeof XRWebGLBinding < "u" && "createProjectionLayer" in XRWebGLBinding.prototype) {
+ let n = null, a = null, o = null;
+ g.depth && (o = g.stencil ? t.DEPTH24_STENCIL8 : t.DEPTH_COMPONENT24, n = g.stencil ? ee : k, a = g.stencil ? w : y);
+ let s = {
+ colorFormat: t.RGBA8,
+ depthFormat: o,
+ scaleFactor: i
+ };
+ u = new XRWebGLBinding(r, t), d = u.createProjectionLayer(s), r.updateRenderState({ layers: [d] }), e.setPixelRatio(1), e.setSize(d.textureWidth, d.textureHeight, !1), v = new Xt(d.textureWidth, d.textureHeight, {
+ format: O,
+ type: m,
+ depthTexture: new Ma(d.textureWidth, d.textureHeight, a, void 0, void 0, void 0, void 0, void 0, void 0, n),
+ stencilBuffer: g.stencil,
+ colorSpace: e.outputColorSpace,
+ samples: g.antialias ? 4 : 0,
+ resolveDepthBuffer: d.ignoreDepthValues === !1,
+ resolveStencilBuffer: d.ignoreDepthValues === !1
+ });
+ } else {
+ let n = {
+ antialias: g.antialias,
+ alpha: !0,
+ depth: g.depth,
+ stencil: g.stencil,
+ framebufferScaleFactor: i
+ };
+ f = new XRWebGLLayer(r, t, n), r.updateRenderState({ baseLayer: f }), e.setPixelRatio(1), e.setSize(f.framebufferWidth, f.framebufferHeight, !1), v = new Xt(f.framebufferWidth, f.framebufferHeight, {
+ format: O,
+ type: m,
+ colorSpace: e.outputColorSpace,
+ stencilBuffer: g.stencil,
+ resolveDepthBuffer: f.ignoreDepthValues === !1,
+ resolveStencilBuffer: f.ignoreDepthValues === !1
+ });
+ }
+ v.isXRRenderTarget = !0, this.setFoveation(s), c = null, a = await r.requestReferenceSpace(o), pe.setContext(r), pe.start(), n.isPresenting = !0, n.dispatchEvent({ type: "sessionstart" });
+ }
+ }, this.getEnvironmentBlendMode = function() {
+ if (r !== null) return r.environmentBlendMode;
+ }, this.getDepthTexture = function() {
+ return h.getDepthTexture();
+ };
+ function ae(e) {
+ for (let t = 0; t < e.removed.length; t++) {
+ let n = e.removed[t], r = x.indexOf(n);
+ r >= 0 && (x[r] = null, b[r].disconnect(n));
+ }
+ for (let t = 0; t < e.added.length; t++) {
+ let n = e.added[t], r = x.indexOf(n);
+ if (r === -1) {
+ for (let e = 0; e < b.length; e++) if (e >= x.length) {
+ x.push(n), r = e;
+ break;
+ } else if (x[e] === null) {
+ x[e] = n, r = e;
+ break;
+ }
+ if (r === -1) break;
+ }
+ let i = b[r];
+ i && i.connect(n);
+ }
+ }
+ let oe = new R(), se = new R();
+ function ce(e, t, n) {
+ oe.setFromMatrixPosition(t.matrixWorld), se.setFromMatrixPosition(n.matrixWorld);
+ let r = oe.distanceTo(se), i = t.projectionMatrix.elements, a = n.projectionMatrix.elements, o = i[14] / (i[10] - 1), s = i[14] / (i[10] + 1), c = (i[9] + 1) / i[5], l = (i[9] - 1) / i[5], u = (i[8] - 1) / i[0], d = (a[8] + 1) / a[0], f = o * u, p = o * d, m = r / (-u + d), h = m * -u;
+ if (t.matrixWorld.decompose(e.position, e.quaternion, e.scale), e.translateX(h), e.translateZ(m), e.matrixWorld.compose(e.position, e.quaternion, e.scale), e.matrixWorldInverse.copy(e.matrixWorld).invert(), i[10] === -1) e.projectionMatrix.copy(t.projectionMatrix), e.projectionMatrixInverse.copy(t.projectionMatrixInverse);
+ else {
+ let t = o + m, n = s + m, i = f - h, a = p + (r - h), u = c * s / n * t, d = l * s / n * t;
+ e.projectionMatrix.makePerspective(i, a, u, d, t, n), e.projectionMatrixInverse.copy(e.projectionMatrix).invert();
+ }
+ }
+ function le(e, t) {
+ t === null ? e.matrixWorld.copy(e.matrix) : e.matrixWorld.multiplyMatrices(t.matrixWorld, e.matrix), e.matrixWorldInverse.copy(e.matrixWorld).invert();
+ }
+ this.updateCamera = function(e) {
+ if (r === null) return;
+ let t = e.near, n = e.far;
+ h.texture !== null && (h.depthNear > 0 && (t = h.depthNear), h.depthFar > 0 && (n = h.depthFar)), A.near = E.near = T.near = t, A.far = E.far = T.far = n, (te !== A.near || ne !== A.far) && (r.updateRenderState({
+ depthNear: A.near,
+ depthFar: A.far
+ }), te = A.near, ne = A.far), T.layers.mask = e.layers.mask | 2, E.layers.mask = e.layers.mask | 4, A.layers.mask = T.layers.mask | E.layers.mask;
+ let i = e.parent, a = A.cameras;
+ le(A, i);
+ for (let e = 0; e < a.length; e++) le(a[e], i);
+ a.length === 2 ? ce(A, T, E) : A.projectionMatrix.copy(T.projectionMatrix), ue(e, A, i);
+ };
+ function ue(e, t, n) {
+ n === null ? e.matrix.copy(t.matrixWorld) : (e.matrix.copy(n.matrixWorld), e.matrix.invert(), e.matrix.multiply(t.matrixWorld)), e.matrix.decompose(e.position, e.quaternion, e.scale), e.updateMatrixWorld(!0), e.projectionMatrix.copy(t.projectionMatrix), e.projectionMatrixInverse.copy(t.projectionMatrixInverse), e.isPerspectiveCamera && (e.fov = nt * 2 * Math.atan(1 / e.projectionMatrix.elements[5]), e.zoom = 1);
+ }
+ this.getCamera = function() {
+ return A;
+ }, this.getFoveation = function() {
+ if (!(d === null && f === null)) return s;
+ }, this.setFoveation = function(e) {
+ s = e, d !== null && (d.fixedFoveation = e), f !== null && f.fixedFoveation !== void 0 && (f.fixedFoveation = e);
+ }, this.hasDepthSensing = function() {
+ return h.texture !== null;
+ }, this.getDepthSensingMesh = function() {
+ return h.getMesh(A);
+ };
+ let de = null;
+ function fe(t, i) {
+ if (l = i.getViewerPose(c || a), p = i, l !== null) {
+ let t = l.views;
+ f !== null && (e.setRenderTargetFramebuffer(v, f.framebuffer), e.setRenderTarget(v));
+ let n = !1;
+ t.length !== A.cameras.length && (A.cameras.length = 0, n = !0);
+ for (let r = 0; r < t.length; r++) {
+ let i = t[r], a = null;
+ if (f !== null) a = f.getViewport(i);
+ else {
+ let t = u.getViewSubImage(d, i);
+ a = t.viewport, r === 0 && (e.setRenderTargetTextures(v, t.colorTexture, t.depthStencilTexture), e.setRenderTarget(v));
+ }
+ let o = D[r];
+ o === void 0 && (o = new vi(), o.layers.enable(r), o.viewport = new Jt(), D[r] = o), o.matrix.fromArray(i.transform.matrix), o.matrix.decompose(o.position, o.quaternion, o.scale), o.projectionMatrix.fromArray(i.projectionMatrix), o.projectionMatrixInverse.copy(o.projectionMatrix).invert(), o.viewport.set(a.x, a.y, a.width, a.height), r === 0 && (A.matrix.copy(o.matrix), A.matrix.decompose(A.position, A.quaternion, A.scale)), n === !0 && A.cameras.push(o);
+ }
+ let i = r.enabledFeatures;
+ if (i && i.includes("depth-sensing") && r.depthUsage == "gpu-optimized" && u) {
+ let n = u.getDepthInformation(t[0]);
+ n && n.isValid && n.texture && h.init(e, n, r.renderState);
+ }
+ }
+ for (let e = 0; e < b.length; e++) {
+ let t = x[e], n = b[e];
+ t !== null && n !== void 0 && n.update(t, i, c || a);
+ }
+ de && de(t, i), i.detectedPlanes && n.dispatchEvent({
+ type: "planesdetected",
+ data: i
+ }), p = null;
+ }
+ let pe = new cs();
+ pe.setAnimationLoop(fe), this.setAnimationLoop = function(e) {
+ de = e;
+ }, this.dispose = function() {};
+ }
+}, au = /* @__PURE__ */ new zn(), ou = /* @__PURE__ */ new z();
+function su(e, t) {
+ function n(e, t) {
+ e.matrixAutoUpdate === !0 && e.updateMatrix(), t.value.copy(e.matrix);
+ }
+ function r(t, n) {
+ n.color.getRGB(t.fogColor.value, li(e)), n.isFog ? (t.fogNear.value = n.near, t.fogFar.value = n.far) : n.isFogExp2 && (t.fogDensity.value = n.density);
+ }
+ function i(e, t, n, r, i) {
+ t.isMeshBasicMaterial || t.isMeshLambertMaterial ? a(e, t) : t.isMeshToonMaterial ? (a(e, t), d(e, t)) : t.isMeshPhongMaterial ? (a(e, t), u(e, t)) : t.isMeshStandardMaterial ? (a(e, t), f(e, t), t.isMeshPhysicalMaterial && p(e, t, i)) : t.isMeshMatcapMaterial ? (a(e, t), m(e, t)) : t.isMeshDepthMaterial ? a(e, t) : t.isMeshDistanceMaterial ? (a(e, t), h(e, t)) : t.isMeshNormalMaterial ? a(e, t) : t.isLineBasicMaterial ? (o(e, t), t.isLineDashedMaterial && s(e, t)) : t.isPointsMaterial ? c(e, t, n, r) : t.isSpriteMaterial ? l(e, t) : t.isShadowMaterial ? (e.color.value.copy(t.color), e.opacity.value = t.opacity) : t.isShaderMaterial && (t.uniformsNeedUpdate = !1);
+ }
+ function a(e, r) {
+ e.opacity.value = r.opacity, r.color && e.diffuse.value.copy(r.color), r.emissive && e.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity), r.map && (e.map.value = r.map, n(r.map, e.mapTransform)), r.alphaMap && (e.alphaMap.value = r.alphaMap, n(r.alphaMap, e.alphaMapTransform)), r.bumpMap && (e.bumpMap.value = r.bumpMap, n(r.bumpMap, e.bumpMapTransform), e.bumpScale.value = r.bumpScale, r.side === 1 && (e.bumpScale.value *= -1)), r.normalMap && (e.normalMap.value = r.normalMap, n(r.normalMap, e.normalMapTransform), e.normalScale.value.copy(r.normalScale), r.side === 1 && e.normalScale.value.negate()), r.displacementMap && (e.displacementMap.value = r.displacementMap, n(r.displacementMap, e.displacementMapTransform), e.displacementScale.value = r.displacementScale, e.displacementBias.value = r.displacementBias), r.emissiveMap && (e.emissiveMap.value = r.emissiveMap, n(r.emissiveMap, e.emissiveMapTransform)), r.specularMap && (e.specularMap.value = r.specularMap, n(r.specularMap, e.specularMapTransform)), r.alphaTest > 0 && (e.alphaTest.value = r.alphaTest);
+ let i = t.get(r), a = i.envMap, o = i.envMapRotation;
+ a && (e.envMap.value = a, au.copy(o), au.x *= -1, au.y *= -1, au.z *= -1, a.isCubeTexture && a.isRenderTargetTexture === !1 && (au.y *= -1, au.z *= -1), e.envMapRotation.value.setFromMatrix4(ou.makeRotationFromEuler(au)), e.flipEnvMap.value = a.isCubeTexture && a.isRenderTargetTexture === !1 ? -1 : 1, e.reflectivity.value = r.reflectivity, e.ior.value = r.ior, e.refractionRatio.value = r.refractionRatio), r.lightMap && (e.lightMap.value = r.lightMap, e.lightMapIntensity.value = r.lightMapIntensity, n(r.lightMap, e.lightMapTransform)), r.aoMap && (e.aoMap.value = r.aoMap, e.aoMapIntensity.value = r.aoMapIntensity, n(r.aoMap, e.aoMapTransform));
+ }
+ function o(e, t) {
+ e.diffuse.value.copy(t.color), e.opacity.value = t.opacity, t.map && (e.map.value = t.map, n(t.map, e.mapTransform));
+ }
+ function s(e, t) {
+ e.dashSize.value = t.dashSize, e.totalSize.value = t.dashSize + t.gapSize, e.scale.value = t.scale;
+ }
+ function c(e, t, r, i) {
+ e.diffuse.value.copy(t.color), e.opacity.value = t.opacity, e.size.value = t.size * r, e.scale.value = i * .5, t.map && (e.map.value = t.map, n(t.map, e.uvTransform)), t.alphaMap && (e.alphaMap.value = t.alphaMap, n(t.alphaMap, e.alphaMapTransform)), t.alphaTest > 0 && (e.alphaTest.value = t.alphaTest);
+ }
+ function l(e, t) {
+ e.diffuse.value.copy(t.color), e.opacity.value = t.opacity, e.rotation.value = t.rotation, t.map && (e.map.value = t.map, n(t.map, e.mapTransform)), t.alphaMap && (e.alphaMap.value = t.alphaMap, n(t.alphaMap, e.alphaMapTransform)), t.alphaTest > 0 && (e.alphaTest.value = t.alphaTest);
+ }
+ function u(e, t) {
+ e.specular.value.copy(t.specular), e.shininess.value = Math.max(t.shininess, 1e-4);
+ }
+ function d(e, t) {
+ t.gradientMap && (e.gradientMap.value = t.gradientMap);
+ }
+ function f(e, t) {
+ e.metalness.value = t.metalness, t.metalnessMap && (e.metalnessMap.value = t.metalnessMap, n(t.metalnessMap, e.metalnessMapTransform)), e.roughness.value = t.roughness, t.roughnessMap && (e.roughnessMap.value = t.roughnessMap, n(t.roughnessMap, e.roughnessMapTransform)), t.envMap && (e.envMapIntensity.value = t.envMapIntensity);
+ }
+ function p(e, t, r) {
+ e.ior.value = t.ior, t.sheen > 0 && (e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen), e.sheenRoughness.value = t.sheenRoughness, t.sheenColorMap && (e.sheenColorMap.value = t.sheenColorMap, n(t.sheenColorMap, e.sheenColorMapTransform)), t.sheenRoughnessMap && (e.sheenRoughnessMap.value = t.sheenRoughnessMap, n(t.sheenRoughnessMap, e.sheenRoughnessMapTransform))), t.clearcoat > 0 && (e.clearcoat.value = t.clearcoat, e.clearcoatRoughness.value = t.clearcoatRoughness, t.clearcoatMap && (e.clearcoatMap.value = t.clearcoatMap, n(t.clearcoatMap, e.clearcoatMapTransform)), t.clearcoatRoughnessMap && (e.clearcoatRoughnessMap.value = t.clearcoatRoughnessMap, n(t.clearcoatRoughnessMap, e.clearcoatRoughnessMapTransform)), t.clearcoatNormalMap && (e.clearcoatNormalMap.value = t.clearcoatNormalMap, n(t.clearcoatNormalMap, e.clearcoatNormalMapTransform), e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale), t.side === 1 && e.clearcoatNormalScale.value.negate())), t.dispersion > 0 && (e.dispersion.value = t.dispersion), t.iridescence > 0 && (e.iridescence.value = t.iridescence, e.iridescenceIOR.value = t.iridescenceIOR, e.iridescenceThicknessMinimum.value = t.iridescenceThicknessRange[0], e.iridescenceThicknessMaximum.value = t.iridescenceThicknessRange[1], t.iridescenceMap && (e.iridescenceMap.value = t.iridescenceMap, n(t.iridescenceMap, e.iridescenceMapTransform)), t.iridescenceThicknessMap && (e.iridescenceThicknessMap.value = t.iridescenceThicknessMap, n(t.iridescenceThicknessMap, e.iridescenceThicknessMapTransform))), t.transmission > 0 && (e.transmission.value = t.transmission, e.transmissionSamplerMap.value = r.texture, e.transmissionSamplerSize.value.set(r.width, r.height), t.transmissionMap && (e.transmissionMap.value = t.transmissionMap, n(t.transmissionMap, e.transmissionMapTransform)), e.thickness.value = t.thickness, t.thicknessMap && (e.thicknessMap.value = t.thicknessMap, n(t.thicknessMap, e.thicknessMapTransform)), e.attenuationDistance.value = t.attenuationDistance, e.attenuationColor.value.copy(t.attenuationColor)), t.anisotropy > 0 && (e.anisotropyVector.value.set(t.anisotropy * Math.cos(t.anisotropyRotation), t.anisotropy * Math.sin(t.anisotropyRotation)), t.anisotropyMap && (e.anisotropyMap.value = t.anisotropyMap, n(t.anisotropyMap, e.anisotropyMapTransform))), e.specularIntensity.value = t.specularIntensity, e.specularColor.value.copy(t.specularColor), t.specularColorMap && (e.specularColorMap.value = t.specularColorMap, n(t.specularColorMap, e.specularColorMapTransform)), t.specularIntensityMap && (e.specularIntensityMap.value = t.specularIntensityMap, n(t.specularIntensityMap, e.specularIntensityMapTransform));
+ }
+ function m(e, t) {
+ t.matcap && (e.matcap.value = t.matcap);
+ }
+ function h(e, n) {
+ let r = t.get(n).light;
+ e.referencePosition.value.setFromMatrixPosition(r.matrixWorld), e.nearDistance.value = r.shadow.camera.near, e.farDistance.value = r.shadow.camera.far;
+ }
+ return {
+ refreshFogUniforms: r,
+ refreshMaterialUniforms: i
+ };
+}
+function cu(e, t, n, r) {
+ let i = {}, a = {}, o = [], s = e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);
+ function c(e, t) {
+ let n = t.program;
+ r.uniformBlockBinding(e, n);
+ }
+ function l(e, n) {
+ let o = i[e.id];
+ o === void 0 && (m(e), o = u(e), i[e.id] = o, e.addEventListener("dispose", g));
+ let s = n.program;
+ r.updateUBOMapping(e, s);
+ let c = t.render.frame;
+ a[e.id] !== c && (f(e), a[e.id] = c);
+ }
+ function u(t) {
+ let n = d();
+ t.__bindingPointIndex = n;
+ let r = e.createBuffer(), i = t.__size, a = t.usage;
+ return e.bindBuffer(e.UNIFORM_BUFFER, r), e.bufferData(e.UNIFORM_BUFFER, i, a), e.bindBuffer(e.UNIFORM_BUFFER, null), e.bindBufferBase(e.UNIFORM_BUFFER, n, r), r;
+ }
+ function d() {
+ for (let e = 0; e < s; e++) if (o.indexOf(e) === -1) return o.push(e), e;
+ return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."), 0;
+ }
+ function f(t) {
+ let n = i[t.id], r = t.uniforms, a = t.__cache;
+ e.bindBuffer(e.UNIFORM_BUFFER, n);
+ for (let t = 0, n = r.length; t < n; t++) {
+ let n = Array.isArray(r[t]) ? r[t] : [r[t]];
+ for (let r = 0, i = n.length; r < i; r++) {
+ let i = n[r];
+ if (p(i, t, r, a) === !0) {
+ let t = i.__offset, n = Array.isArray(i.value) ? i.value : [i.value], r = 0;
+ for (let a = 0; a < n.length; a++) {
+ let o = n[a], s = h(o);
+ typeof o == "number" || typeof o == "boolean" ? (i.__data[0] = o, e.bufferSubData(e.UNIFORM_BUFFER, t + r, i.__data)) : o.isMatrix3 ? (i.__data[0] = o.elements[0], i.__data[1] = o.elements[1], i.__data[2] = o.elements[2], i.__data[3] = 0, i.__data[4] = o.elements[3], i.__data[5] = o.elements[4], i.__data[6] = o.elements[5], i.__data[7] = 0, i.__data[8] = o.elements[6], i.__data[9] = o.elements[7], i.__data[10] = o.elements[8], i.__data[11] = 0) : (o.toArray(i.__data, r), r += s.storage / Float32Array.BYTES_PER_ELEMENT);
+ }
+ e.bufferSubData(e.UNIFORM_BUFFER, t, i.__data);
+ }
+ }
+ }
+ e.bindBuffer(e.UNIFORM_BUFFER, null);
+ }
+ function p(e, t, n, r) {
+ let i = e.value, a = t + "_" + n;
+ if (r[a] === void 0) return typeof i == "number" || typeof i == "boolean" ? r[a] = i : r[a] = i.clone(), !0;
+ {
+ let e = r[a];
+ if (typeof i == "number" || typeof i == "boolean") {
+ if (e !== i) return r[a] = i, !0;
+ } else if (e.equals(i) === !1) return e.copy(i), !0;
+ }
+ return !1;
+ }
+ function m(e) {
+ let t = e.uniforms, n = 0;
+ for (let e = 0, r = t.length; e < r; e++) {
+ let r = Array.isArray(t[e]) ? t[e] : [t[e]];
+ for (let e = 0, t = r.length; e < t; e++) {
+ let t = r[e], i = Array.isArray(t.value) ? t.value : [t.value];
+ for (let e = 0, r = i.length; e < r; e++) {
+ let r = i[e], a = h(r), o = n % 16, s = o % a.boundary, c = o + s;
+ n += s, c !== 0 && 16 - c < a.storage && (n += 16 - c), t.__data = new Float32Array(a.storage / Float32Array.BYTES_PER_ELEMENT), t.__offset = n, n += a.storage;
+ }
+ }
+ }
+ let r = n % 16;
+ return r > 0 && (n += 16 - r), e.__size = n, e.__cache = {}, this;
+ }
+ function h(e) {
+ let t = {
+ boundary: 0,
+ storage: 0
+ };
+ return typeof e == "number" || typeof e == "boolean" ? (t.boundary = 4, t.storage = 4) : e.isVector2 ? (t.boundary = 8, t.storage = 8) : e.isVector3 || e.isColor ? (t.boundary = 16, t.storage = 12) : e.isVector4 ? (t.boundary = 16, t.storage = 16) : e.isMatrix3 ? (t.boundary = 48, t.storage = 48) : e.isMatrix4 ? (t.boundary = 64, t.storage = 64) : e.isTexture ? console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.") : console.warn("THREE.WebGLRenderer: Unsupported uniform value type.", e), t;
+ }
+ function g(t) {
+ let n = t.target;
+ n.removeEventListener("dispose", g);
+ let r = o.indexOf(n.__bindingPointIndex);
+ o.splice(r, 1), e.deleteBuffer(i[n.id]), delete i[n.id], delete a[n.id];
+ }
+ function _() {
+ for (let t in i) e.deleteBuffer(i[t]);
+ o = [], i = {}, a = {};
+ }
+ return {
+ bind: c,
+ update: l,
+ dispose: _
+ };
+}
+var lu = class {
+ constructor(e = {}) {
+ let { canvas: t = kt(), context: n = null, depth: r = !0, stencil: i = !1, alpha: a = !1, antialias: o = !1, premultipliedAlpha: s = !0, preserveDrawingBuffer: c = !1, powerPreference: l = "default", failIfMajorPerformanceCaveat: u = !1, reverseDepthBuffer: d = !1 } = e;
+ this.isWebGLRenderer = !0;
+ let f;
+ if (n !== null) {
+ if (typeof WebGLRenderingContext < "u" && n instanceof WebGLRenderingContext) throw Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");
+ f = n.getContextAttributes().alpha;
+ } else f = a;
+ let h = new Uint32Array(4), g = new Int32Array(4), _ = null, v = null, y = [], b = [];
+ this.domElement = t, this.debug = {
+ checkShaderErrors: !0,
+ onShaderError: null
+ }, this.autoClear = !0, this.autoClearColor = !0, this.autoClearDepth = !0, this.autoClearStencil = !0, this.sortObjects = !0, this.clippingPlanes = [], this.localClippingEnabled = !1, this.toneMapping = 0, this.toneMappingExposure = 1, this.transmissionResolutionScale = 1;
+ let S = this, C = !1;
+ this._outputColorSpace = Ge;
+ let w = 0, T = 0, E = null, D = -1, O = null, k = new Jt(), ee = new Jt(), A = null, te = new B(0), ne = 0, re = t.width, ie = t.height, ae = 1, oe = null, se = null, ce = new Jt(0, 0, re, ie), le = new Jt(0, 0, re, ie), ue = !1, de = new sa(), fe = !1, pe = !1, me = new z(), he = new z(), ge = new R(), _e = new Jt(), ve = {
+ background: null,
+ fog: null,
+ environment: null,
+ overrideMaterial: null,
+ isScene: !0
+ }, ye = !1;
+ function be() {
+ return E === null ? ae : 1;
+ }
+ let j = n;
+ function xe(e, n) {
+ return t.getContext(e, n);
+ }
+ try {
+ let e = {
+ alpha: !0,
+ depth: r,
+ stencil: i,
+ antialias: o,
+ premultipliedAlpha: s,
+ preserveDrawingBuffer: c,
+ powerPreference: l,
+ failIfMajorPerformanceCaveat: u
+ };
+ if ("setAttribute" in t && t.setAttribute("data-engine", "three.js r176"), t.addEventListener("webglcontextlost", We, !1), t.addEventListener("webglcontextrestored", qe, !1), t.addEventListener("webglcontextcreationerror", Je, !1), j === null) {
+ let t = "webgl2";
+ if (j = xe(t, e), j === null) throw xe(t) ? Error("Error creating WebGL context with your selected attributes.") : Error("Error creating WebGL context.");
+ }
+ } catch (e) {
+ throw console.error("THREE.WebGLRenderer: " + e.message), e;
+ }
+ let Se, Ce, M, we, N, P, Te, Ee, F, De, Oe, ke, Ae, je, Me, Ne, Pe, Fe, Ie, Le, Re, ze, Be, Ve;
+ function He() {
+ Se = new Hs(j), Se.init(), ze = new eu(j, Se), Ce = new _s(j, Se, e, ze), M = new Ql(j, Se), Ce.reverseDepthBuffer && d && M.buffers.depth.setReversed(!0), we = new Gs(j), N = new Il(), P = new $l(j, Se, M, N, Ce, ze, we), Te = new ys(S), Ee = new Vs(S), F = new ls(j), Be = new hs(j, F), De = new Us(j, F, we, Be), Oe = new qs(j, De, F, we), Ie = new Ks(j, Ce, P), Ne = new vs(N), ke = new Fl(S, Te, Ee, Se, Ce, Be, Ne), Ae = new su(S, N), je = new Bl(), Me = new ql(Se), Fe = new ms(S, Te, Ee, M, Oe, f, s), Pe = new Xl(S, Oe, Ce), Ve = new cu(j, we, Ce, M), Le = new gs(j, Se, we), Re = new Ws(j, Se, we), we.programs = ke.programs, S.capabilities = Ce, S.extensions = Se, S.properties = N, S.renderLists = je, S.shadowMap = Pe, S.state = M, S.info = we;
+ }
+ He();
+ let Ue = new iu(S, j);
+ this.xr = Ue, this.getContext = function() {
+ return j;
+ }, this.getContextAttributes = function() {
+ return j.getContextAttributes();
+ }, this.forceContextLoss = function() {
+ let e = Se.get("WEBGL_lose_context");
+ e && e.loseContext();
+ }, this.forceContextRestore = function() {
+ let e = Se.get("WEBGL_lose_context");
+ e && e.restoreContext();
+ }, this.getPixelRatio = function() {
+ return ae;
+ }, this.setPixelRatio = function(e) {
+ e !== void 0 && (ae = e, this.setSize(re, ie, !1));
+ }, this.getSize = function(e) {
+ return e.set(re, ie);
+ }, this.setSize = function(e, n, r = !0) {
+ if (Ue.isPresenting) {
+ console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");
+ return;
+ }
+ re = e, ie = n, t.width = Math.floor(e * ae), t.height = Math.floor(n * ae), r === !0 && (t.style.width = e + "px", t.style.height = n + "px"), this.setViewport(0, 0, e, n);
+ }, this.getDrawingBufferSize = function(e) {
+ return e.set(re * ae, ie * ae).floor();
+ }, this.setDrawingBufferSize = function(e, n, r) {
+ re = e, ie = n, ae = r, t.width = Math.floor(e * r), t.height = Math.floor(n * r), this.setViewport(0, 0, e, n);
+ }, this.getCurrentViewport = function(e) {
+ return e.copy(k);
+ }, this.getViewport = function(e) {
+ return e.copy(ce);
+ }, this.setViewport = function(e, t, n, r) {
+ e.isVector4 ? ce.set(e.x, e.y, e.z, e.w) : ce.set(e, t, n, r), M.viewport(k.copy(ce).multiplyScalar(ae).round());
+ }, this.getScissor = function(e) {
+ return e.copy(le);
+ }, this.setScissor = function(e, t, n, r) {
+ e.isVector4 ? le.set(e.x, e.y, e.z, e.w) : le.set(e, t, n, r), M.scissor(ee.copy(le).multiplyScalar(ae).round());
+ }, this.getScissorTest = function() {
+ return ue;
+ }, this.setScissorTest = function(e) {
+ M.setScissorTest(ue = e);
+ }, this.setOpaqueSort = function(e) {
+ oe = e;
+ }, this.setTransparentSort = function(e) {
+ se = e;
+ }, this.getClearColor = function(e) {
+ return e.copy(Fe.getClearColor());
+ }, this.setClearColor = function() {
+ Fe.setClearColor(...arguments);
+ }, this.getClearAlpha = function() {
+ return Fe.getClearAlpha();
+ }, this.setClearAlpha = function() {
+ Fe.setClearAlpha(...arguments);
+ }, this.clear = function(e = !0, t = !0, n = !0) {
+ let r = 0;
+ if (e) {
+ let e = !1;
+ if (E !== null) {
+ let t = E.texture.format;
+ e = t === 1033 || t === 1031 || t === 1029;
+ }
+ if (e) {
+ let e = E.texture.type, t = e === 1009 || e === 1014 || e === 1012 || e === 1020 || e === 1017 || e === 1018, n = Fe.getClearColor(), r = Fe.getClearAlpha(), i = n.r, a = n.g, o = n.b;
+ t ? (h[0] = i, h[1] = a, h[2] = o, h[3] = r, j.clearBufferuiv(j.COLOR, 0, h)) : (g[0] = i, g[1] = a, g[2] = o, g[3] = r, j.clearBufferiv(j.COLOR, 0, g));
+ } else r |= j.COLOR_BUFFER_BIT;
+ }
+ t && (r |= j.DEPTH_BUFFER_BIT), n && (r |= j.STENCIL_BUFFER_BIT, this.state.buffers.stencil.setMask(4294967295)), j.clear(r);
+ }, this.clearColor = function() {
+ this.clear(!0, !1, !1);
+ }, this.clearDepth = function() {
+ this.clear(!1, !0, !1);
+ }, this.clearStencil = function() {
+ this.clear(!1, !1, !0);
+ }, this.dispose = function() {
+ t.removeEventListener("webglcontextlost", We, !1), t.removeEventListener("webglcontextrestored", qe, !1), t.removeEventListener("webglcontextcreationerror", Je, !1), Fe.dispose(), je.dispose(), Me.dispose(), N.dispose(), Te.dispose(), Ee.dispose(), Oe.dispose(), Be.dispose(), Ve.dispose(), ke.dispose(), Ue.dispose(), Ue.removeEventListener("sessionstart", tt), Ue.removeEventListener("sessionend", nt), rt.stop();
+ };
+ function We(e) {
+ e.preventDefault(), console.log("THREE.WebGLRenderer: Context Lost."), C = !0;
+ }
+ function qe() {
+ console.log("THREE.WebGLRenderer: Context Restored."), C = !1;
+ let e = we.autoReset, t = Pe.enabled, n = Pe.autoUpdate, r = Pe.needsUpdate, i = Pe.type;
+ He(), we.autoReset = e, Pe.enabled = t, Pe.autoUpdate = n, Pe.needsUpdate = r, Pe.type = i;
+ }
+ function Je(e) {
+ console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ", e.statusMessage);
+ }
+ function Ye(e) {
+ let t = e.target;
+ t.removeEventListener("dispose", Ye), Xe(t);
+ }
+ function Xe(e) {
+ Ze(e), N.remove(e);
+ }
+ function Ze(e) {
+ let t = N.get(e).programs;
+ t !== void 0 && (t.forEach(function(e) {
+ ke.releaseProgram(e);
+ }), e.isShaderMaterial && ke.releaseShaderCache(e));
+ }
+ this.renderBufferDirect = function(e, t, n, r, i, a) {
+ t === null && (t = ve);
+ let o = i.isMesh && i.matrixWorld.determinant() < 0, s = dt(e, t, n, r, i);
+ M.setMaterial(r, o);
+ let c = n.index, l = 1;
+ if (r.wireframe === !0) {
+ if (c = De.getWireframeAttribute(n), c === void 0) return;
+ l = 2;
+ }
+ let u = n.drawRange, d = n.attributes.position, f = u.start * l, p = (u.start + u.count) * l;
+ a !== null && (f = Math.max(f, a.start * l), p = Math.min(p, (a.start + a.count) * l)), c === null ? d != null && (f = Math.max(f, 0), p = Math.min(p, d.count)) : (f = Math.max(f, 0), p = Math.min(p, c.count));
+ let m = p - f;
+ if (m < 0 || m === Infinity) return;
+ Be.setup(i, r, s, n, c);
+ let h, g = Le;
+ if (c !== null && (h = F.get(c), g = Re, g.setIndex(h)), i.isMesh) r.wireframe === !0 ? (M.setLineWidth(r.wireframeLinewidth * be()), g.setMode(j.LINES)) : g.setMode(j.TRIANGLES);
+ else if (i.isLine) {
+ let e = r.linewidth;
+ e === void 0 && (e = 1), M.setLineWidth(e * be()), i.isLineSegments ? g.setMode(j.LINES) : i.isLineLoop ? g.setMode(j.LINE_LOOP) : g.setMode(j.LINE_STRIP);
+ } else i.isPoints ? g.setMode(j.POINTS) : i.isSprite && g.setMode(j.TRIANGLES);
+ if (i.isBatchedMesh) if (i._multiDrawInstances !== null) jt("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."), g.renderMultiDrawInstances(i._multiDrawStarts, i._multiDrawCounts, i._multiDrawCount, i._multiDrawInstances);
+ else if (Se.get("WEBGL_multi_draw")) g.renderMultiDraw(i._multiDrawStarts, i._multiDrawCounts, i._multiDrawCount);
+ else {
+ let e = i._multiDrawStarts, t = i._multiDrawCounts, n = i._multiDrawCount, a = c ? F.get(c).bytesPerElement : 1, o = N.get(r).currentProgram.getUniforms();
+ for (let r = 0; r < n; r++) o.setValue(j, "_gl_DrawID", r), g.render(e[r] / a, t[r]);
+ }
+ else if (i.isInstancedMesh) g.renderInstances(f, m, i.count);
+ else if (n.isInstancedBufferGeometry) {
+ let e = n._maxInstanceCount === void 0 ? Infinity : n._maxInstanceCount, t = Math.min(n.instanceCount, e);
+ g.renderInstances(f, m, t);
+ } else g.render(f, m);
+ };
+ function Qe(e, t, n) {
+ e.transparent === !0 && e.side === 2 && e.forceSinglePass === !1 ? (e.side = 1, e.needsUpdate = !0, ct(e, t, n), e.side = 0, e.needsUpdate = !0, ct(e, t, n), e.side = 2) : ct(e, t, n);
+ }
+ this.compile = function(e, t, n = null) {
+ n === null && (n = e), v = Me.get(n), v.init(t), b.push(v), n.traverseVisible(function(e) {
+ e.isLight && e.layers.test(t.layers) && (v.pushLight(e), e.castShadow && v.pushShadow(e));
+ }), e !== n && e.traverseVisible(function(e) {
+ e.isLight && e.layers.test(t.layers) && (v.pushLight(e), e.castShadow && v.pushShadow(e));
+ }), v.setupLights();
+ let r = /* @__PURE__ */ new Set();
+ return e.traverse(function(e) {
+ if (!(e.isMesh || e.isPoints || e.isLine || e.isSprite)) return;
+ let t = e.material;
+ if (t) if (Array.isArray(t)) for (let i = 0; i < t.length; i++) {
+ let a = t[i];
+ Qe(a, n, e), r.add(a);
+ }
+ else Qe(t, n, e), r.add(t);
+ }), v = b.pop(), r;
+ }, this.compileAsync = function(e, t, n = null) {
+ let r = this.compile(e, t, n);
+ return new Promise((t) => {
+ function n() {
+ if (r.forEach(function(e) {
+ N.get(e).currentProgram.isReady() && r.delete(e);
+ }), r.size === 0) {
+ t(e);
+ return;
+ }
+ setTimeout(n, 10);
+ }
+ Se.get("KHR_parallel_shader_compile") === null ? setTimeout(n, 10) : n();
+ });
+ };
+ let $e = null;
+ function et(e) {
+ $e && $e(e);
+ }
+ function tt() {
+ rt.stop();
+ }
+ function nt() {
+ rt.start();
+ }
+ let rt = new cs();
+ rt.setAnimationLoop(et), typeof self < "u" && rt.setContext(self), this.setAnimationLoop = function(e) {
+ $e = e, Ue.setAnimationLoop(e), e === null ? rt.stop() : rt.start();
+ }, Ue.addEventListener("sessionstart", tt), Ue.addEventListener("sessionend", nt), this.render = function(e, t) {
+ if (t !== void 0 && t.isCamera !== !0) {
+ console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");
+ return;
+ }
+ if (C === !0) return;
+ if (e.matrixWorldAutoUpdate === !0 && e.updateMatrixWorld(), t.parent === null && t.matrixWorldAutoUpdate === !0 && t.updateMatrixWorld(), Ue.enabled === !0 && Ue.isPresenting === !0 && (Ue.cameraAutoUpdate === !0 && Ue.updateCamera(t), t = Ue.getCamera()), e.isScene === !0 && e.onBeforeRender(S, e, t, E), v = Me.get(e, b.length), v.init(t), b.push(v), he.multiplyMatrices(t.projectionMatrix, t.matrixWorldInverse), de.setFromProjectionMatrix(he), pe = this.localClippingEnabled, fe = Ne.init(this.clippingPlanes, pe), _ = je.get(e, y.length), _.init(), y.push(_), Ue.enabled === !0 && Ue.isPresenting === !0) {
+ let e = S.xr.getDepthSensingMesh();
+ e !== null && I(e, t, -Infinity, S.sortObjects);
+ }
+ I(e, t, 0, S.sortObjects), _.finish(), S.sortObjects === !0 && _.sort(oe, se), ye = Ue.enabled === !1 || Ue.isPresenting === !1 || Ue.hasDepthSensing() === !1, ye && Fe.addToRenderList(_, e), this.info.render.frame++, fe === !0 && Ne.beginShadows();
+ let n = v.state.shadowsArray;
+ Pe.render(n, e, t), fe === !0 && Ne.endShadows(), this.info.autoReset === !0 && this.info.reset();
+ let r = _.opaque, i = _.transmissive;
+ if (v.setupLights(), t.isArrayCamera) {
+ let n = t.cameras;
+ if (i.length > 0) for (let t = 0, a = n.length; t < a; t++) {
+ let a = n[t];
+ at(r, i, e, a);
+ }
+ ye && Fe.render(e);
+ for (let t = 0, r = n.length; t < r; t++) {
+ let r = n[t];
+ it(_, e, r, r.viewport);
+ }
+ } else i.length > 0 && at(r, i, e, t), ye && Fe.render(e), it(_, e, t);
+ E !== null && T === 0 && (P.updateMultisampleRenderTarget(E), P.updateRenderTargetMipmap(E)), e.isScene === !0 && e.onAfterRender(S, e, t), Be.resetDefaultState(), D = -1, O = null, b.pop(), b.length > 0 ? (v = b[b.length - 1], fe === !0 && Ne.setGlobalState(S.clippingPlanes, v.state.camera)) : v = null, y.pop(), _ = y.length > 0 ? y[y.length - 1] : null;
+ };
+ function I(e, t, n, r) {
+ if (e.visible === !1) return;
+ if (e.layers.test(t.layers)) {
+ if (e.isGroup) n = e.renderOrder;
+ else if (e.isLOD) e.autoUpdate === !0 && e.update(t);
+ else if (e.isLight) v.pushLight(e), e.castShadow && v.pushShadow(e);
+ else if (e.isSprite) {
+ if (!e.frustumCulled || de.intersectsSprite(e)) {
+ r && _e.setFromMatrixPosition(e.matrixWorld).applyMatrix4(he);
+ let t = Oe.update(e), i = e.material;
+ i.visible && _.push(e, t, i, n, _e.z, null);
+ }
+ } else if ((e.isMesh || e.isLine || e.isPoints) && (!e.frustumCulled || de.intersectsObject(e))) {
+ let t = Oe.update(e), i = e.material;
+ if (r && (e.boundingSphere === void 0 ? (t.boundingSphere === null && t.computeBoundingSphere(), _e.copy(t.boundingSphere.center)) : (e.boundingSphere === null && e.computeBoundingSphere(), _e.copy(e.boundingSphere.center)), _e.applyMatrix4(e.matrixWorld).applyMatrix4(he)), Array.isArray(i)) {
+ let r = t.groups;
+ for (let a = 0, o = r.length; a < o; a++) {
+ let o = r[a], s = i[o.materialIndex];
+ s && s.visible && _.push(e, t, s, n, _e.z, o);
+ }
+ } else i.visible && _.push(e, t, i, n, _e.z, null);
+ }
+ }
+ let i = e.children;
+ for (let e = 0, a = i.length; e < a; e++) I(i[e], t, n, r);
+ }
+ function it(e, t, n, r) {
+ let i = e.opaque, a = e.transmissive, o = e.transparent;
+ v.setupLightsView(n), fe === !0 && Ne.setGlobalState(S.clippingPlanes, n), r && M.viewport(k.copy(r)), i.length > 0 && ot(i, t, n), a.length > 0 && ot(a, t, n), o.length > 0 && ot(o, t, n), M.buffers.depth.setTest(!0), M.buffers.depth.setMask(!0), M.buffers.color.setMask(!0), M.setPolygonOffset(!1);
+ }
+ function at(e, t, n, r) {
+ if ((n.isScene === !0 ? n.overrideMaterial : null) !== null) return;
+ v.state.transmissionRenderTarget[r.id] === void 0 && (v.state.transmissionRenderTarget[r.id] = new Xt(1, 1, {
+ generateMipmaps: !0,
+ type: Se.has("EXT_color_buffer_half_float") || Se.has("EXT_color_buffer_float") ? x : m,
+ minFilter: p,
+ samples: 4,
+ stencilBuffer: i,
+ resolveDepthBuffer: !1,
+ resolveStencilBuffer: !1,
+ colorSpace: Rt.workingColorSpace
+ }));
+ let a = v.state.transmissionRenderTarget[r.id], o = r.viewport || k;
+ a.setSize(o.z * S.transmissionResolutionScale, o.w * S.transmissionResolutionScale);
+ let s = S.getRenderTarget();
+ S.setRenderTarget(a), S.getClearColor(te), ne = S.getClearAlpha(), ne < 1 && S.setClearColor(16777215, .5), S.clear(), ye && Fe.render(n);
+ let c = S.toneMapping;
+ S.toneMapping = 0;
+ let l = r.viewport;
+ if (r.viewport !== void 0 && (r.viewport = void 0), v.setupLightsView(r), fe === !0 && Ne.setGlobalState(S.clippingPlanes, r), ot(e, n, r), P.updateMultisampleRenderTarget(a), P.updateRenderTargetMipmap(a), Se.has("WEBGL_multisampled_render_to_texture") === !1) {
+ let e = !1;
+ for (let i = 0, a = t.length; i < a; i++) {
+ let a = t[i], o = a.object, s = a.geometry, c = a.material, l = a.group;
+ if (c.side === 2 && o.layers.test(r.layers)) {
+ let t = c.side;
+ c.side = 1, c.needsUpdate = !0, st(o, n, r, s, c, l), c.side = t, c.needsUpdate = !0, e = !0;
+ }
+ }
+ e === !0 && (P.updateMultisampleRenderTarget(a), P.updateRenderTargetMipmap(a));
+ }
+ S.setRenderTarget(s), S.setClearColor(te, ne), l !== void 0 && (r.viewport = l), S.toneMapping = c;
+ }
+ function ot(e, t, n) {
+ let r = t.isScene === !0 ? t.overrideMaterial : null;
+ for (let i = 0, a = e.length; i < a; i++) {
+ let a = e[i], o = a.object, s = a.geometry, c = a.group, l = a.material;
+ l.allowOverride === !0 && r !== null && (l = r), o.layers.test(n.layers) && st(o, t, n, s, l, c);
+ }
+ }
+ function st(e, t, n, r, i, a) {
+ e.onBeforeRender(S, t, n, r, i, a), e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse, e.matrixWorld), e.normalMatrix.getNormalMatrix(e.modelViewMatrix), i.onBeforeRender(S, t, n, r, e, a), i.transparent === !0 && i.side === 2 && i.forceSinglePass === !1 ? (i.side = 1, i.needsUpdate = !0, S.renderBufferDirect(n, t, r, i, e, a), i.side = 0, i.needsUpdate = !0, S.renderBufferDirect(n, t, r, i, e, a), i.side = 2) : S.renderBufferDirect(n, t, r, i, e, a), e.onAfterRender(S, t, n, r, i, a);
+ }
+ function ct(e, t, n) {
+ t.isScene !== !0 && (t = ve);
+ let r = N.get(e), i = v.state.lights, a = v.state.shadowsArray, o = i.state.version, s = ke.getParameters(e, i.state, a, t, n), c = ke.getProgramCacheKey(s), l = r.programs;
+ r.environment = e.isMeshStandardMaterial ? t.environment : null, r.fog = t.fog, r.envMap = (e.isMeshStandardMaterial ? Ee : Te).get(e.envMap || r.environment), r.envMapRotation = r.environment !== null && e.envMap === null ? t.environmentRotation : e.envMapRotation, l === void 0 && (e.addEventListener("dispose", Ye), l = /* @__PURE__ */ new Map(), r.programs = l);
+ let u = l.get(c);
+ if (u !== void 0) {
+ if (r.currentProgram === u && r.lightsStateVersion === o) return ut(e, s), u;
+ } else s.uniforms = ke.getUniforms(e), e.onBeforeCompile(s, S), u = ke.acquireProgram(s, c), l.set(c, u), r.uniforms = s.uniforms;
+ let d = r.uniforms;
+ return (!e.isShaderMaterial && !e.isRawShaderMaterial || e.clipping === !0) && (d.clippingPlanes = Ne.uniform), ut(e, s), r.needsLights = pt(e), r.lightsStateVersion = o, r.needsLights && (d.ambientLightColor.value = i.state.ambient, d.lightProbe.value = i.state.probe, d.directionalLights.value = i.state.directional, d.directionalLightShadows.value = i.state.directionalShadow, d.spotLights.value = i.state.spot, d.spotLightShadows.value = i.state.spotShadow, d.rectAreaLights.value = i.state.rectArea, d.ltc_1.value = i.state.rectAreaLTC1, d.ltc_2.value = i.state.rectAreaLTC2, d.pointLights.value = i.state.point, d.pointLightShadows.value = i.state.pointShadow, d.hemisphereLights.value = i.state.hemi, d.directionalShadowMap.value = i.state.directionalShadowMap, d.directionalShadowMatrix.value = i.state.directionalShadowMatrix, d.spotShadowMap.value = i.state.spotShadowMap, d.spotLightMatrix.value = i.state.spotLightMatrix, d.spotLightMap.value = i.state.spotLightMap, d.pointShadowMap.value = i.state.pointShadowMap, d.pointShadowMatrix.value = i.state.pointShadowMatrix), r.currentProgram = u, r.uniformsList = null, u;
+ }
+ function lt(e) {
+ if (e.uniformsList === null) {
+ let t = e.currentProgram.getUniforms();
+ e.uniformsList = el.seqWithValue(t.seq, e.uniforms);
+ }
+ return e.uniformsList;
+ }
+ function ut(e, t) {
+ let n = N.get(e);
+ n.outputColorSpace = t.outputColorSpace, n.batching = t.batching, n.batchingColor = t.batchingColor, n.instancing = t.instancing, n.instancingColor = t.instancingColor, n.instancingMorph = t.instancingMorph, n.skinning = t.skinning, n.morphTargets = t.morphTargets, n.morphNormals = t.morphNormals, n.morphColors = t.morphColors, n.morphTargetsCount = t.morphTargetsCount, n.numClippingPlanes = t.numClippingPlanes, n.numIntersection = t.numClipIntersection, n.vertexAlphas = t.vertexAlphas, n.vertexTangents = t.vertexTangents, n.toneMapping = t.toneMapping;
+ }
+ function dt(e, t, n, r, i) {
+ t.isScene !== !0 && (t = ve), P.resetTextureUnits();
+ let a = t.fog, o = r.isMeshStandardMaterial ? t.environment : null, s = E === null ? S.outputColorSpace : E.isXRRenderTarget === !0 ? E.texture.colorSpace : Ke, c = (r.isMeshStandardMaterial ? Ee : Te).get(r.envMap || o), l = r.vertexColors === !0 && !!n.attributes.color && n.attributes.color.itemSize === 4, u = !!n.attributes.tangent && (!!r.normalMap || r.anisotropy > 0), d = !!n.morphAttributes.position, f = !!n.morphAttributes.normal, p = !!n.morphAttributes.color, m = 0;
+ r.toneMapped && (E === null || E.isXRRenderTarget === !0) && (m = S.toneMapping);
+ let h = n.morphAttributes.position || n.morphAttributes.normal || n.morphAttributes.color, g = h === void 0 ? 0 : h.length, _ = N.get(r), y = v.state.lights;
+ if (fe === !0 && (pe === !0 || e !== O)) {
+ let t = e === O && r.id === D;
+ Ne.setState(r, e, t);
+ }
+ let b = !1;
+ r.version === _.__version ? _.needsLights && _.lightsStateVersion !== y.state.version ? b = !0 : _.outputColorSpace === s ? i.isBatchedMesh && _.batching === !1 || !i.isBatchedMesh && _.batching === !0 || i.isBatchedMesh && _.batchingColor === !0 && i.colorTexture === null || i.isBatchedMesh && _.batchingColor === !1 && i.colorTexture !== null || i.isInstancedMesh && _.instancing === !1 || !i.isInstancedMesh && _.instancing === !0 || i.isSkinnedMesh && _.skinning === !1 || !i.isSkinnedMesh && _.skinning === !0 || i.isInstancedMesh && _.instancingColor === !0 && i.instanceColor === null || i.isInstancedMesh && _.instancingColor === !1 && i.instanceColor !== null || i.isInstancedMesh && _.instancingMorph === !0 && i.morphTexture === null || i.isInstancedMesh && _.instancingMorph === !1 && i.morphTexture !== null ? b = !0 : _.envMap === c ? r.fog === !0 && _.fog !== a || _.numClippingPlanes !== void 0 && (_.numClippingPlanes !== Ne.numPlanes || _.numIntersection !== Ne.numIntersection) ? b = !0 : _.vertexAlphas === l && _.vertexTangents === u && _.morphTargets === d && _.morphNormals === f && _.morphColors === p && _.toneMapping === m ? _.morphTargetsCount !== g && (b = !0) : b = !0 : b = !0 : b = !0 : (b = !0, _.__version = r.version);
+ let x = _.currentProgram;
+ b === !0 && (x = ct(r, t, i));
+ let C = !1, w = !1, T = !1, k = x.getUniforms(), ee = _.uniforms;
+ if (M.useProgram(x.program) && (C = !0, w = !0, T = !0), r.id !== D && (D = r.id, w = !0), C || O !== e) {
+ M.buffers.depth.getReversed() ? (me.copy(e.projectionMatrix), Nt(me), Pt(me), k.setValue(j, "projectionMatrix", me)) : k.setValue(j, "projectionMatrix", e.projectionMatrix), k.setValue(j, "viewMatrix", e.matrixWorldInverse);
+ let t = k.map.cameraPosition;
+ t !== void 0 && t.setValue(j, ge.setFromMatrixPosition(e.matrixWorld)), Ce.logarithmicDepthBuffer && k.setValue(j, "logDepthBufFC", 2 / (Math.log(e.far + 1) / Math.LN2)), (r.isMeshPhongMaterial || r.isMeshToonMaterial || r.isMeshLambertMaterial || r.isMeshBasicMaterial || r.isMeshStandardMaterial || r.isShaderMaterial) && k.setValue(j, "isOrthographic", e.isOrthographicCamera === !0), O !== e && (O = e, w = !0, T = !0);
+ }
+ if (i.isSkinnedMesh) {
+ k.setOptional(j, i, "bindMatrix"), k.setOptional(j, i, "bindMatrixInverse");
+ let e = i.skeleton;
+ e && (e.boneTexture === null && e.computeBoneTexture(), k.setValue(j, "boneTexture", e.boneTexture, P));
+ }
+ i.isBatchedMesh && (k.setOptional(j, i, "batchingTexture"), k.setValue(j, "batchingTexture", i._matricesTexture, P), k.setOptional(j, i, "batchingIdTexture"), k.setValue(j, "batchingIdTexture", i._indirectTexture, P), k.setOptional(j, i, "batchingColorTexture"), i._colorsTexture !== null && k.setValue(j, "batchingColorTexture", i._colorsTexture, P));
+ let A = n.morphAttributes;
+ if ((A.position !== void 0 || A.normal !== void 0 || A.color !== void 0) && Ie.update(i, n, x), (w || _.receiveShadow !== i.receiveShadow) && (_.receiveShadow = i.receiveShadow, k.setValue(j, "receiveShadow", i.receiveShadow)), r.isMeshGouraudMaterial && r.envMap !== null && (ee.envMap.value = c, ee.flipEnvMap.value = c.isCubeTexture && c.isRenderTargetTexture === !1 ? -1 : 1), r.isMeshStandardMaterial && r.envMap === null && t.environment !== null && (ee.envMapIntensity.value = t.environmentIntensity), w && (k.setValue(j, "toneMappingExposure", S.toneMappingExposure), _.needsLights && ft(ee, T), a && r.fog === !0 && Ae.refreshFogUniforms(ee, a), Ae.refreshMaterialUniforms(ee, r, ae, ie, v.state.transmissionRenderTarget[e.id]), el.upload(j, lt(_), ee, P)), r.isShaderMaterial && r.uniformsNeedUpdate === !0 && (el.upload(j, lt(_), ee, P), r.uniformsNeedUpdate = !1), r.isSpriteMaterial && k.setValue(j, "center", i.center), k.setValue(j, "modelViewMatrix", i.modelViewMatrix), k.setValue(j, "normalMatrix", i.normalMatrix), k.setValue(j, "modelMatrix", i.matrixWorld), r.isShaderMaterial || r.isRawShaderMaterial) {
+ let e = r.uniformsGroups;
+ for (let t = 0, n = e.length; t < n; t++) {
+ let n = e[t];
+ Ve.update(n, x), Ve.bind(n, x);
+ }
+ }
+ return x;
+ }
+ function ft(e, t) {
+ e.ambientLightColor.needsUpdate = t, e.lightProbe.needsUpdate = t, e.directionalLights.needsUpdate = t, e.directionalLightShadows.needsUpdate = t, e.pointLights.needsUpdate = t, e.pointLightShadows.needsUpdate = t, e.spotLights.needsUpdate = t, e.spotLightShadows.needsUpdate = t, e.rectAreaLights.needsUpdate = t, e.hemisphereLights.needsUpdate = t;
+ }
+ function pt(e) {
+ return e.isMeshLambertMaterial || e.isMeshToonMaterial || e.isMeshPhongMaterial || e.isMeshStandardMaterial || e.isShadowMaterial || e.isShaderMaterial && e.lights === !0;
+ }
+ this.getActiveCubeFace = function() {
+ return w;
+ }, this.getActiveMipmapLevel = function() {
+ return T;
+ }, this.getRenderTarget = function() {
+ return E;
+ }, this.setRenderTargetTextures = function(e, t, n) {
+ let r = N.get(e);
+ r.__autoAllocateDepthBuffer = e.resolveDepthBuffer === !1, r.__autoAllocateDepthBuffer === !1 && (r.__useRenderToTexture = !1), N.get(e.texture).__webglTexture = t, N.get(e.depthTexture).__webglTexture = r.__autoAllocateDepthBuffer ? void 0 : n, r.__hasExternalTextures = !0;
+ }, this.setRenderTargetFramebuffer = function(e, t) {
+ let n = N.get(e);
+ n.__webglFramebuffer = t, n.__useDefaultFramebuffer = t === void 0;
+ };
+ let mt = j.createFramebuffer();
+ this.setRenderTarget = function(e, t = 0, n = 0) {
+ E = e, w = t, T = n;
+ let r = !0, i = null, a = !1, o = !1;
+ if (e) {
+ let s = N.get(e);
+ if (s.__useDefaultFramebuffer !== void 0) M.bindFramebuffer(j.FRAMEBUFFER, null), r = !1;
+ else if (s.__webglFramebuffer === void 0) P.setupRenderTarget(e);
+ else if (s.__hasExternalTextures) P.rebindTextures(e, N.get(e.texture).__webglTexture, N.get(e.depthTexture).__webglTexture);
+ else if (e.depthBuffer) {
+ let t = e.depthTexture;
+ if (s.__boundDepthTexture !== t) {
+ if (t !== null && N.has(t) && (e.width !== t.image.width || e.height !== t.image.height)) throw Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");
+ P.setupDepthRenderbuffer(e);
+ }
+ }
+ let c = e.texture;
+ (c.isData3DTexture || c.isDataArrayTexture || c.isCompressedArrayTexture) && (o = !0);
+ let l = N.get(e).__webglFramebuffer;
+ e.isWebGLCubeRenderTarget ? (i = Array.isArray(l[t]) ? l[t][n] : l[t], a = !0) : i = e.samples > 0 && P.useMultisampledRTT(e) === !1 ? N.get(e).__webglMultisampledFramebuffer : Array.isArray(l) ? l[n] : l, k.copy(e.viewport), ee.copy(e.scissor), A = e.scissorTest;
+ } else k.copy(ce).multiplyScalar(ae).floor(), ee.copy(le).multiplyScalar(ae).floor(), A = ue;
+ if (n !== 0 && (i = mt), M.bindFramebuffer(j.FRAMEBUFFER, i) && r && M.drawBuffers(e, i), M.viewport(k), M.scissor(ee), M.setScissorTest(A), a) {
+ let r = N.get(e.texture);
+ j.framebufferTexture2D(j.FRAMEBUFFER, j.COLOR_ATTACHMENT0, j.TEXTURE_CUBE_MAP_POSITIVE_X + t, r.__webglTexture, n);
+ } else if (o) {
+ let r = N.get(e.texture), i = t;
+ j.framebufferTextureLayer(j.FRAMEBUFFER, j.COLOR_ATTACHMENT0, r.__webglTexture, n, i);
+ } else if (e !== null && n !== 0) {
+ let t = N.get(e.texture);
+ j.framebufferTexture2D(j.FRAMEBUFFER, j.COLOR_ATTACHMENT0, j.TEXTURE_2D, t.__webglTexture, n);
+ }
+ D = -1;
+ }, this.readRenderTargetPixels = function(e, t, n, r, i, a, o) {
+ if (!(e && e.isWebGLRenderTarget)) {
+ console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");
+ return;
+ }
+ let s = N.get(e).__webglFramebuffer;
+ if (e.isWebGLCubeRenderTarget && o !== void 0 && (s = s[o]), s) {
+ M.bindFramebuffer(j.FRAMEBUFFER, s);
+ try {
+ let o = e.texture, s = o.format, c = o.type;
+ if (!Ce.textureFormatReadable(s)) {
+ console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");
+ return;
+ }
+ if (!Ce.textureTypeReadable(c)) {
+ console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");
+ return;
+ }
+ t >= 0 && t <= e.width - r && n >= 0 && n <= e.height - i && j.readPixels(t, n, r, i, ze.convert(s), ze.convert(c), a);
+ } finally {
+ let e = E === null ? null : N.get(E).__webglFramebuffer;
+ M.bindFramebuffer(j.FRAMEBUFFER, e);
+ }
+ }
+ }, this.readRenderTargetPixelsAsync = async function(e, t, n, r, i, a, o) {
+ if (!(e && e.isWebGLRenderTarget)) throw Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");
+ let s = N.get(e).__webglFramebuffer;
+ if (e.isWebGLCubeRenderTarget && o !== void 0 && (s = s[o]), s) if (t >= 0 && t <= e.width - r && n >= 0 && n <= e.height - i) {
+ M.bindFramebuffer(j.FRAMEBUFFER, s);
+ let o = e.texture, c = o.format, l = o.type;
+ if (!Ce.textureFormatReadable(c)) throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");
+ if (!Ce.textureTypeReadable(l)) throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");
+ let u = j.createBuffer();
+ j.bindBuffer(j.PIXEL_PACK_BUFFER, u), j.bufferData(j.PIXEL_PACK_BUFFER, a.byteLength, j.STREAM_READ), j.readPixels(t, n, r, i, ze.convert(c), ze.convert(l), 0);
+ let d = E === null ? null : N.get(E).__webglFramebuffer;
+ M.bindFramebuffer(j.FRAMEBUFFER, d);
+ let f = j.fenceSync(j.SYNC_GPU_COMMANDS_COMPLETE, 0);
+ return j.flush(), await Mt(j, f, 4), j.bindBuffer(j.PIXEL_PACK_BUFFER, u), j.getBufferSubData(j.PIXEL_PACK_BUFFER, 0, a), j.deleteBuffer(u), j.deleteSync(f), a;
+ } else throw Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.");
+ }, this.copyFramebufferToTexture = function(e, t = null, n = 0) {
+ let r = 2 ** -n, i = Math.floor(e.image.width * r), a = Math.floor(e.image.height * r), o = t === null ? 0 : t.x, s = t === null ? 0 : t.y;
+ P.setTexture2D(e, 0), j.copyTexSubImage2D(j.TEXTURE_2D, n, 0, 0, o, s, i, a), M.unbindTexture();
+ };
+ let ht = j.createFramebuffer(), gt = j.createFramebuffer();
+ this.copyTextureToTexture = function(e, t, n = null, r = null, i = 0, a = null) {
+ a === null && (i === 0 ? a = 0 : (jt("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."), a = i, i = 0));
+ let o, s, c, l, u, d, f, p, m, h = e.isCompressedTexture ? e.mipmaps[a] : e.image;
+ if (n !== null) o = n.max.x - n.min.x, s = n.max.y - n.min.y, c = n.isBox3 ? n.max.z - n.min.z : 1, l = n.min.x, u = n.min.y, d = n.isBox3 ? n.min.z : 0;
+ else {
+ let t = 2 ** -i;
+ o = Math.floor(h.width * t), s = Math.floor(h.height * t), c = e.isDataArrayTexture ? h.depth : e.isData3DTexture ? Math.floor(h.depth * t) : 1, l = 0, u = 0, d = 0;
+ }
+ r === null ? (f = 0, p = 0, m = 0) : (f = r.x, p = r.y, m = r.z);
+ let g = ze.convert(t.format), _ = ze.convert(t.type), v;
+ t.isData3DTexture ? (P.setTexture3D(t, 0), v = j.TEXTURE_3D) : t.isDataArrayTexture || t.isCompressedArrayTexture ? (P.setTexture2DArray(t, 0), v = j.TEXTURE_2D_ARRAY) : (P.setTexture2D(t, 0), v = j.TEXTURE_2D), j.pixelStorei(j.UNPACK_FLIP_Y_WEBGL, t.flipY), j.pixelStorei(j.UNPACK_PREMULTIPLY_ALPHA_WEBGL, t.premultiplyAlpha), j.pixelStorei(j.UNPACK_ALIGNMENT, t.unpackAlignment);
+ let y = j.getParameter(j.UNPACK_ROW_LENGTH), b = j.getParameter(j.UNPACK_IMAGE_HEIGHT), x = j.getParameter(j.UNPACK_SKIP_PIXELS), S = j.getParameter(j.UNPACK_SKIP_ROWS), C = j.getParameter(j.UNPACK_SKIP_IMAGES);
+ j.pixelStorei(j.UNPACK_ROW_LENGTH, h.width), j.pixelStorei(j.UNPACK_IMAGE_HEIGHT, h.height), j.pixelStorei(j.UNPACK_SKIP_PIXELS, l), j.pixelStorei(j.UNPACK_SKIP_ROWS, u), j.pixelStorei(j.UNPACK_SKIP_IMAGES, d);
+ let w = e.isDataArrayTexture || e.isData3DTexture, T = t.isDataArrayTexture || t.isData3DTexture;
+ if (e.isDepthTexture) {
+ let n = N.get(e), r = N.get(t), h = N.get(n.__renderTarget), g = N.get(r.__renderTarget);
+ M.bindFramebuffer(j.READ_FRAMEBUFFER, h.__webglFramebuffer), M.bindFramebuffer(j.DRAW_FRAMEBUFFER, g.__webglFramebuffer);
+ for (let n = 0; n < c; n++) w && (j.framebufferTextureLayer(j.READ_FRAMEBUFFER, j.COLOR_ATTACHMENT0, N.get(e).__webglTexture, i, d + n), j.framebufferTextureLayer(j.DRAW_FRAMEBUFFER, j.COLOR_ATTACHMENT0, N.get(t).__webglTexture, a, m + n)), j.blitFramebuffer(l, u, o, s, f, p, o, s, j.DEPTH_BUFFER_BIT, j.NEAREST);
+ M.bindFramebuffer(j.READ_FRAMEBUFFER, null), M.bindFramebuffer(j.DRAW_FRAMEBUFFER, null);
+ } else if (i !== 0 || e.isRenderTargetTexture || N.has(e)) {
+ let n = N.get(e), r = N.get(t);
+ M.bindFramebuffer(j.READ_FRAMEBUFFER, ht), M.bindFramebuffer(j.DRAW_FRAMEBUFFER, gt);
+ for (let e = 0; e < c; e++) w ? j.framebufferTextureLayer(j.READ_FRAMEBUFFER, j.COLOR_ATTACHMENT0, n.__webglTexture, i, d + e) : j.framebufferTexture2D(j.READ_FRAMEBUFFER, j.COLOR_ATTACHMENT0, j.TEXTURE_2D, n.__webglTexture, i), T ? j.framebufferTextureLayer(j.DRAW_FRAMEBUFFER, j.COLOR_ATTACHMENT0, r.__webglTexture, a, m + e) : j.framebufferTexture2D(j.DRAW_FRAMEBUFFER, j.COLOR_ATTACHMENT0, j.TEXTURE_2D, r.__webglTexture, a), i === 0 ? T ? j.copyTexSubImage3D(v, a, f, p, m + e, l, u, o, s) : j.copyTexSubImage2D(v, a, f, p, l, u, o, s) : j.blitFramebuffer(l, u, o, s, f, p, o, s, j.COLOR_BUFFER_BIT, j.NEAREST);
+ M.bindFramebuffer(j.READ_FRAMEBUFFER, null), M.bindFramebuffer(j.DRAW_FRAMEBUFFER, null);
+ } else T ? e.isDataTexture || e.isData3DTexture ? j.texSubImage3D(v, a, f, p, m, o, s, c, g, _, h.data) : t.isCompressedArrayTexture ? j.compressedTexSubImage3D(v, a, f, p, m, o, s, c, g, h.data) : j.texSubImage3D(v, a, f, p, m, o, s, c, g, _, h) : e.isDataTexture ? j.texSubImage2D(j.TEXTURE_2D, a, f, p, o, s, g, _, h.data) : e.isCompressedTexture ? j.compressedTexSubImage2D(j.TEXTURE_2D, a, f, p, h.width, h.height, g, h.data) : j.texSubImage2D(j.TEXTURE_2D, a, f, p, o, s, g, _, h);
+ j.pixelStorei(j.UNPACK_ROW_LENGTH, y), j.pixelStorei(j.UNPACK_IMAGE_HEIGHT, b), j.pixelStorei(j.UNPACK_SKIP_PIXELS, x), j.pixelStorei(j.UNPACK_SKIP_ROWS, S), j.pixelStorei(j.UNPACK_SKIP_IMAGES, C), a === 0 && t.generateMipmaps && j.generateMipmap(v), M.unbindTexture();
+ }, this.copyTextureToTexture3D = function(e, t, n = null, r = null, i = 0) {
+ return jt("WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use \"copyTextureToTexture\" instead."), this.copyTextureToTexture(e, t, n, r, i);
+ }, this.initRenderTarget = function(e) {
+ N.get(e).__webglFramebuffer === void 0 && P.setupRenderTarget(e);
+ }, this.initTexture = function(e) {
+ e.isCubeTexture ? P.setTextureCube(e, 0) : e.isData3DTexture ? P.setTexture3D(e, 0) : e.isDataArrayTexture || e.isCompressedArrayTexture ? P.setTexture2DArray(e, 0) : P.setTexture2D(e, 0), M.unbindTexture();
+ }, this.resetState = function() {
+ w = 0, T = 0, E = null, M.reset(), Be.reset();
+ }, typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this }));
+ }
+ get coordinateSystem() {
+ return Ze;
+ }
+ get outputColorSpace() {
+ return this._outputColorSpace;
+ }
+ set outputColorSpace(e) {
+ this._outputColorSpace = e;
+ let t = this.getContext();
+ t.drawingBufferColorSpace = Rt._getDrawingBufferColorSpace(e), t.unpackColorSpace = Rt._getUnpackColorSpace();
+ }
+}, uu = function() {
+ var e = 0, t = document.createElement("div");
+ t.style.cssText = "position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000", t.addEventListener("click", function(n) {
+ n.preventDefault(), r(++e % t.children.length);
+ }, !1);
+ function n(e) {
+ return t.appendChild(e.dom), e;
+ }
+ function r(n) {
+ for (var r = 0; r < t.children.length; r++) t.children[r].style.display = r === n ? "block" : "none";
+ e = n;
+ }
+ var i = (performance || Date).now(), a = i, o = 0, s = n(new uu.Panel("FPS", "#0ff", "#002")), c = n(new uu.Panel("MS", "#0f0", "#020"));
+ if (self.performance && self.performance.memory) var l = n(new uu.Panel("MB", "#f08", "#201"));
+ return r(0), {
+ REVISION: 16,
+ dom: t,
+ addPanel: n,
+ showPanel: r,
+ begin: function() {
+ i = (performance || Date).now();
+ },
+ end: function() {
+ o++;
+ var e = (performance || Date).now();
+ if (c.update(e - i, 200), e >= a + 1e3 && (s.update(o * 1e3 / (e - a), 100), a = e, o = 0, l)) {
+ var t = performance.memory;
+ l.update(t.usedJSHeapSize / 1048576, t.jsHeapSizeLimit / 1048576);
+ }
+ return e;
+ },
+ update: function() {
+ i = this.end();
+ },
+ domElement: t,
+ setMode: r
+ };
+};
+uu.Panel = function(e, t, n) {
+ var r = Infinity, i = 0, a = Math.round, o = a(window.devicePixelRatio || 1), s = 80 * o, c = 48 * o, l = 3 * o, u = 2 * o, d = 3 * o, f = 15 * o, p = 74 * o, m = 30 * o, h = document.createElement("canvas");
+ h.width = s, h.height = c, h.style.cssText = "width:80px;height:48px";
+ var g = h.getContext("2d");
+ return g.font = "bold " + 9 * o + "px Helvetica,Arial,sans-serif", g.textBaseline = "top", g.fillStyle = n, g.fillRect(0, 0, s, c), g.fillStyle = t, g.fillText(e, l, u), g.fillRect(d, f, p, m), g.fillStyle = n, g.globalAlpha = .9, g.fillRect(d, f, p, m), {
+ dom: h,
+ update: function(c, _) {
+ r = Math.min(r, c), i = Math.max(i, c), g.fillStyle = n, g.globalAlpha = 1, g.fillRect(0, 0, s, f), g.fillStyle = t, g.fillText(a(c) + " " + e + " (" + a(r) + "-" + a(i) + ")", l, u), g.drawImage(h, d + o, f, p - o, m, d, f, p - o, m), g.fillRect(d + p - o, f, o, m), g.fillStyle = n, g.globalAlpha = .9, g.fillRect(d + p - o, f, o, a((1 - c / _) * m));
+ }
+ };
+};
+//#endregion
+//#region node_modules/three/examples/jsm/utils/BufferGeometryUtils.js
+function du(e, t) {
+ if (t === 0) return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."), e;
+ if (t === 2 || t === 1) {
+ let n = e.getIndex();
+ if (n === null) {
+ let t = [], r = e.getAttribute("position");
+ if (r !== void 0) {
+ for (let e = 0; e < r.count; e++) t.push(e);
+ e.setIndex(t), n = e.getIndex();
+ } else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."), e;
+ }
+ let r = n.count - 2, i = [];
+ if (t === 2) for (let e = 1; e <= r; e++) i.push(n.getX(0)), i.push(n.getX(e)), i.push(n.getX(e + 1));
+ else for (let e = 0; e < r; e++) e % 2 == 0 ? (i.push(n.getX(e)), i.push(n.getX(e + 1)), i.push(n.getX(e + 2))) : (i.push(n.getX(e + 2)), i.push(n.getX(e + 1)), i.push(n.getX(e)));
+ i.length / 3 !== r && console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");
+ let a = e.clone();
+ return a.setIndex(i), a.clearGroups(), a;
+ } else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:", t), e;
+}
+//#endregion
+//#region node_modules/three/examples/jsm/loaders/GLTFLoader.js
+var fu = class extends so {
+ constructor(e) {
+ super(e), this.dracoLoader = null, this.ktx2Loader = null, this.meshoptDecoder = null, this.pluginCallbacks = [], this.register(function(e) {
+ return new vu(e);
+ }), this.register(function(e) {
+ return new yu(e);
+ }), this.register(function(e) {
+ return new Ou(e);
+ }), this.register(function(e) {
+ return new ku(e);
+ }), this.register(function(e) {
+ return new Au(e);
+ }), this.register(function(e) {
+ return new xu(e);
+ }), this.register(function(e) {
+ return new Su(e);
+ }), this.register(function(e) {
+ return new Cu(e);
+ }), this.register(function(e) {
+ return new wu(e);
+ }), this.register(function(e) {
+ return new _u(e);
+ }), this.register(function(e) {
+ return new Tu(e);
+ }), this.register(function(e) {
+ return new bu(e);
+ }), this.register(function(e) {
+ return new Du(e);
+ }), this.register(function(e) {
+ return new Eu(e);
+ }), this.register(function(e) {
+ return new hu(e);
+ }), this.register(function(e) {
+ return new ju(e);
+ }), this.register(function(e) {
+ return new Mu(e);
+ });
+ }
+ load(e, t, n, r) {
+ let i = this, a;
+ if (this.resourcePath !== "") a = this.resourcePath;
+ else if (this.path !== "") {
+ let t = Mo.extractUrlBase(e);
+ a = Mo.resolveURL(t, this.path);
+ } else a = Mo.extractUrlBase(e);
+ this.manager.itemStart(e);
+ let o = function(t) {
+ r ? r(t) : console.error(t), i.manager.itemError(e), i.manager.itemEnd(e);
+ }, s = new uo(this.manager);
+ s.setPath(this.path), s.setResponseType("arraybuffer"), s.setRequestHeader(this.requestHeader), s.setWithCredentials(this.withCredentials), s.load(e, function(n) {
+ try {
+ i.parse(n, a, function(n) {
+ t(n), i.manager.itemEnd(e);
+ }, o);
+ } catch (e) {
+ o(e);
+ }
+ }, n, o);
+ }
+ setDRACOLoader(e) {
+ return this.dracoLoader = e, this;
+ }
+ setKTX2Loader(e) {
+ return this.ktx2Loader = e, this;
+ }
+ setMeshoptDecoder(e) {
+ return this.meshoptDecoder = e, this;
+ }
+ register(e) {
+ return this.pluginCallbacks.indexOf(e) === -1 && this.pluginCallbacks.push(e), this;
+ }
+ unregister(e) {
+ return this.pluginCallbacks.indexOf(e) !== -1 && this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e), 1), this;
+ }
+ parse(e, t, n, r) {
+ let i, a = {}, o = {}, s = new TextDecoder();
+ if (typeof e == "string") i = JSON.parse(e);
+ else if (e instanceof ArrayBuffer) if (s.decode(new Uint8Array(e, 0, 4)) === Nu) {
+ try {
+ a[mu.KHR_BINARY_GLTF] = new Iu(e);
+ } catch (e) {
+ r && r(e);
+ return;
+ }
+ i = JSON.parse(a[mu.KHR_BINARY_GLTF].content);
+ } else i = JSON.parse(s.decode(e));
+ else i = e;
+ if (i.asset === void 0 || i.asset.version[0] < 2) {
+ r && r(/* @__PURE__ */ Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));
+ return;
+ }
+ let c = new cd(i, {
+ path: t || this.resourcePath || "",
+ crossOrigin: this.crossOrigin,
+ requestHeader: this.requestHeader,
+ manager: this.manager,
+ ktx2Loader: this.ktx2Loader,
+ meshoptDecoder: this.meshoptDecoder
+ });
+ c.fileLoader.setRequestHeader(this.requestHeader);
+ for (let e = 0; e < this.pluginCallbacks.length; e++) {
+ let t = this.pluginCallbacks[e](c);
+ t.name || console.error("THREE.GLTFLoader: Invalid plugin found: missing name"), o[t.name] = t, a[t.name] = !0;
+ }
+ if (i.extensionsUsed) for (let e = 0; e < i.extensionsUsed.length; ++e) {
+ let t = i.extensionsUsed[e], n = i.extensionsRequired || [];
+ switch (t) {
+ case mu.KHR_MATERIALS_UNLIT:
+ a[t] = new gu();
+ break;
+ case mu.KHR_DRACO_MESH_COMPRESSION:
+ a[t] = new Lu(i, this.dracoLoader);
+ break;
+ case mu.KHR_TEXTURE_TRANSFORM:
+ a[t] = new Ru();
+ break;
+ case mu.KHR_MESH_QUANTIZATION:
+ a[t] = new zu();
+ break;
+ default: n.indexOf(t) >= 0 && o[t] === void 0 && console.warn("THREE.GLTFLoader: Unknown extension \"" + t + "\".");
+ }
+ }
+ c.setExtensions(a), c.setPlugins(o), c.parse(n, r);
+ }
+ parseAsync(e, t) {
+ let n = this;
+ return new Promise(function(r, i) {
+ n.parse(e, t, r, i);
+ });
+ }
+};
+function pu() {
+ let e = {};
+ return {
+ get: function(t) {
+ return e[t];
+ },
+ add: function(t, n) {
+ e[t] = n;
+ },
+ remove: function(t) {
+ delete e[t];
+ },
+ removeAll: function() {
+ e = {};
+ }
+ };
+}
+var mu = {
+ KHR_BINARY_GLTF: "KHR_binary_glTF",
+ KHR_DRACO_MESH_COMPRESSION: "KHR_draco_mesh_compression",
+ KHR_LIGHTS_PUNCTUAL: "KHR_lights_punctual",
+ KHR_MATERIALS_CLEARCOAT: "KHR_materials_clearcoat",
+ KHR_MATERIALS_DISPERSION: "KHR_materials_dispersion",
+ KHR_MATERIALS_IOR: "KHR_materials_ior",
+ KHR_MATERIALS_SHEEN: "KHR_materials_sheen",
+ KHR_MATERIALS_SPECULAR: "KHR_materials_specular",
+ KHR_MATERIALS_TRANSMISSION: "KHR_materials_transmission",
+ KHR_MATERIALS_IRIDESCENCE: "KHR_materials_iridescence",
+ KHR_MATERIALS_ANISOTROPY: "KHR_materials_anisotropy",
+ KHR_MATERIALS_UNLIT: "KHR_materials_unlit",
+ KHR_MATERIALS_VOLUME: "KHR_materials_volume",
+ KHR_TEXTURE_BASISU: "KHR_texture_basisu",
+ KHR_TEXTURE_TRANSFORM: "KHR_texture_transform",
+ KHR_MESH_QUANTIZATION: "KHR_mesh_quantization",
+ KHR_MATERIALS_EMISSIVE_STRENGTH: "KHR_materials_emissive_strength",
+ EXT_MATERIALS_BUMP: "EXT_materials_bump",
+ EXT_TEXTURE_WEBP: "EXT_texture_webp",
+ EXT_TEXTURE_AVIF: "EXT_texture_avif",
+ EXT_MESHOPT_COMPRESSION: "EXT_meshopt_compression",
+ EXT_MESH_GPU_INSTANCING: "EXT_mesh_gpu_instancing"
+}, hu = class {
+ constructor(e) {
+ this.parser = e, this.name = mu.KHR_LIGHTS_PUNCTUAL, this.cache = {
+ refs: {},
+ uses: {}
+ };
+ }
+ _markDefs() {
+ let e = this.parser, t = this.parser.json.nodes || [];
+ for (let n = 0, r = t.length; n < r; n++) {
+ let r = t[n];
+ r.extensions && r.extensions[this.name] && r.extensions[this.name].light !== void 0 && e._addNodeRef(this.cache, r.extensions[this.name].light);
+ }
+ }
+ _loadLight(e) {
+ let t = this.parser, n = "light:" + e, r = t.cache.get(n);
+ if (r) return r;
+ let i = t.json, a = ((i.extensions && i.extensions[this.name] || {}).lights || [])[e], o, s = new B(16777215);
+ a.color !== void 0 && s.setRGB(a.color[0], a.color[1], a.color[2], Ke);
+ let c = a.range === void 0 ? 0 : a.range;
+ switch (a.type) {
+ case "directional":
+ o = new Ao(s), o.target.position.set(0, 0, -1), o.add(o.target);
+ break;
+ case "point":
+ o = new Do(s), o.distance = c;
+ break;
+ case "spot":
+ o = new So(s), o.distance = c, a.spot = a.spot || {}, a.spot.innerConeAngle = a.spot.innerConeAngle === void 0 ? 0 : a.spot.innerConeAngle, a.spot.outerConeAngle = a.spot.outerConeAngle === void 0 ? Math.PI / 4 : a.spot.outerConeAngle, o.angle = a.spot.outerConeAngle, o.penumbra = 1 - a.spot.innerConeAngle / a.spot.outerConeAngle, o.target.position.set(0, 0, -1), o.add(o.target);
+ break;
+ default: throw Error("THREE.GLTFLoader: Unexpected light type: " + a.type);
+ }
+ return o.position.set(0, 0, 0), ed(o, a), a.intensity !== void 0 && (o.intensity = a.intensity), o.name = t.createUniqueName(a.name || "light_" + e), r = Promise.resolve(o), t.cache.add(n, r), r;
+ }
+ getDependency(e, t) {
+ if (e === "light") return this._loadLight(t);
+ }
+ createNodeAttachment(e) {
+ let t = this, n = this.parser, r = n.json.nodes[e], i = (r.extensions && r.extensions[this.name] || {}).light;
+ return i === void 0 ? null : this._loadLight(i).then(function(e) {
+ return n._getNodeRef(t.cache, i, e);
+ });
+ }
+}, gu = class {
+ constructor() {
+ this.name = mu.KHR_MATERIALS_UNLIT;
+ }
+ getMaterialType() {
+ return wr;
+ }
+ extendParams(e, t, n) {
+ let r = [];
+ e.color = new B(1, 1, 1), e.opacity = 1;
+ let i = t.pbrMetallicRoughness;
+ if (i) {
+ if (Array.isArray(i.baseColorFactor)) {
+ let t = i.baseColorFactor;
+ e.color.setRGB(t[0], t[1], t[2], Ke), e.opacity = t[3];
+ }
+ i.baseColorTexture !== void 0 && r.push(n.assignTexture(e, "map", i.baseColorTexture, Ge));
+ }
+ return Promise.all(r);
+ }
+}, _u = class {
+ constructor(e) {
+ this.parser = e, this.name = mu.KHR_MATERIALS_EMISSIVE_STRENGTH;
+ }
+ extendMaterialParams(e, t) {
+ let n = this.parser.json.materials[e];
+ if (!n.extensions || !n.extensions[this.name]) return Promise.resolve();
+ let r = n.extensions[this.name].emissiveStrength;
+ return r !== void 0 && (t.emissiveIntensity = r), Promise.resolve();
+ }
+}, vu = class {
+ constructor(e) {
+ this.parser = e, this.name = mu.KHR_MATERIALS_CLEARCOAT;
+ }
+ getMaterialType(e) {
+ let t = this.parser.json.materials[e];
+ return !t.extensions || !t.extensions[this.name] ? null : Fa;
+ }
+ extendMaterialParams(e, t) {
+ let n = this.parser, r = n.json.materials[e];
+ if (!r.extensions || !r.extensions[this.name]) return Promise.resolve();
+ let i = [], a = r.extensions[this.name];
+ if (a.clearcoatFactor !== void 0 && (t.clearcoat = a.clearcoatFactor), a.clearcoatTexture !== void 0 && i.push(n.assignTexture(t, "clearcoatMap", a.clearcoatTexture)), a.clearcoatRoughnessFactor !== void 0 && (t.clearcoatRoughness = a.clearcoatRoughnessFactor), a.clearcoatRoughnessTexture !== void 0 && i.push(n.assignTexture(t, "clearcoatRoughnessMap", a.clearcoatRoughnessTexture)), a.clearcoatNormalTexture !== void 0 && (i.push(n.assignTexture(t, "clearcoatNormalMap", a.clearcoatNormalTexture)), a.clearcoatNormalTexture.scale !== void 0)) {
+ let e = a.clearcoatNormalTexture.scale;
+ t.clearcoatNormalScale = new L(e, e);
+ }
+ return Promise.all(i);
+ }
+}, yu = class {
+ constructor(e) {
+ this.parser = e, this.name = mu.KHR_MATERIALS_DISPERSION;
+ }
+ getMaterialType(e) {
+ let t = this.parser.json.materials[e];
+ return !t.extensions || !t.extensions[this.name] ? null : Fa;
+ }
+ extendMaterialParams(e, t) {
+ let n = this.parser.json.materials[e];
+ if (!n.extensions || !n.extensions[this.name]) return Promise.resolve();
+ let r = n.extensions[this.name];
+ return t.dispersion = r.dispersion === void 0 ? 0 : r.dispersion, Promise.resolve();
+ }
+}, bu = class {
+ constructor(e) {
+ this.parser = e, this.name = mu.KHR_MATERIALS_IRIDESCENCE;
+ }
+ getMaterialType(e) {
+ let t = this.parser.json.materials[e];
+ return !t.extensions || !t.extensions[this.name] ? null : Fa;
+ }
+ extendMaterialParams(e, t) {
+ let n = this.parser, r = n.json.materials[e];
+ if (!r.extensions || !r.extensions[this.name]) return Promise.resolve();
+ let i = [], a = r.extensions[this.name];
+ return a.iridescenceFactor !== void 0 && (t.iridescence = a.iridescenceFactor), a.iridescenceTexture !== void 0 && i.push(n.assignTexture(t, "iridescenceMap", a.iridescenceTexture)), a.iridescenceIor !== void 0 && (t.iridescenceIOR = a.iridescenceIor), t.iridescenceThicknessRange === void 0 && (t.iridescenceThicknessRange = [100, 400]), a.iridescenceThicknessMinimum !== void 0 && (t.iridescenceThicknessRange[0] = a.iridescenceThicknessMinimum), a.iridescenceThicknessMaximum !== void 0 && (t.iridescenceThicknessRange[1] = a.iridescenceThicknessMaximum), a.iridescenceThicknessTexture !== void 0 && i.push(n.assignTexture(t, "iridescenceThicknessMap", a.iridescenceThicknessTexture)), Promise.all(i);
+ }
+}, xu = class {
+ constructor(e) {
+ this.parser = e, this.name = mu.KHR_MATERIALS_SHEEN;
+ }
+ getMaterialType(e) {
+ let t = this.parser.json.materials[e];
+ return !t.extensions || !t.extensions[this.name] ? null : Fa;
+ }
+ extendMaterialParams(e, t) {
+ let n = this.parser, r = n.json.materials[e];
+ if (!r.extensions || !r.extensions[this.name]) return Promise.resolve();
+ let i = [];
+ t.sheenColor = new B(0, 0, 0), t.sheenRoughness = 0, t.sheen = 1;
+ let a = r.extensions[this.name];
+ if (a.sheenColorFactor !== void 0) {
+ let e = a.sheenColorFactor;
+ t.sheenColor.setRGB(e[0], e[1], e[2], Ke);
+ }
+ return a.sheenRoughnessFactor !== void 0 && (t.sheenRoughness = a.sheenRoughnessFactor), a.sheenColorTexture !== void 0 && i.push(n.assignTexture(t, "sheenColorMap", a.sheenColorTexture, Ge)), a.sheenRoughnessTexture !== void 0 && i.push(n.assignTexture(t, "sheenRoughnessMap", a.sheenRoughnessTexture)), Promise.all(i);
+ }
+}, Su = class {
+ constructor(e) {
+ this.parser = e, this.name = mu.KHR_MATERIALS_TRANSMISSION;
+ }
+ getMaterialType(e) {
+ let t = this.parser.json.materials[e];
+ return !t.extensions || !t.extensions[this.name] ? null : Fa;
+ }
+ extendMaterialParams(e, t) {
+ let n = this.parser, r = n.json.materials[e];
+ if (!r.extensions || !r.extensions[this.name]) return Promise.resolve();
+ let i = [], a = r.extensions[this.name];
+ return a.transmissionFactor !== void 0 && (t.transmission = a.transmissionFactor), a.transmissionTexture !== void 0 && i.push(n.assignTexture(t, "transmissionMap", a.transmissionTexture)), Promise.all(i);
+ }
+}, Cu = class {
+ constructor(e) {
+ this.parser = e, this.name = mu.KHR_MATERIALS_VOLUME;
+ }
+ getMaterialType(e) {
+ let t = this.parser.json.materials[e];
+ return !t.extensions || !t.extensions[this.name] ? null : Fa;
+ }
+ extendMaterialParams(e, t) {
+ let n = this.parser, r = n.json.materials[e];
+ if (!r.extensions || !r.extensions[this.name]) return Promise.resolve();
+ let i = [], a = r.extensions[this.name];
+ t.thickness = a.thicknessFactor === void 0 ? 0 : a.thicknessFactor, a.thicknessTexture !== void 0 && i.push(n.assignTexture(t, "thicknessMap", a.thicknessTexture)), t.attenuationDistance = a.attenuationDistance || Infinity;
+ let o = a.attenuationColor || [
+ 1,
+ 1,
+ 1
+ ];
+ return t.attenuationColor = new B().setRGB(o[0], o[1], o[2], Ke), Promise.all(i);
+ }
+}, wu = class {
+ constructor(e) {
+ this.parser = e, this.name = mu.KHR_MATERIALS_IOR;
+ }
+ getMaterialType(e) {
+ let t = this.parser.json.materials[e];
+ return !t.extensions || !t.extensions[this.name] ? null : Fa;
+ }
+ extendMaterialParams(e, t) {
+ let n = this.parser.json.materials[e];
+ if (!n.extensions || !n.extensions[this.name]) return Promise.resolve();
+ let r = n.extensions[this.name];
+ return t.ior = r.ior === void 0 ? 1.5 : r.ior, Promise.resolve();
+ }
+}, Tu = class {
+ constructor(e) {
+ this.parser = e, this.name = mu.KHR_MATERIALS_SPECULAR;
+ }
+ getMaterialType(e) {
+ let t = this.parser.json.materials[e];
+ return !t.extensions || !t.extensions[this.name] ? null : Fa;
+ }
+ extendMaterialParams(e, t) {
+ let n = this.parser, r = n.json.materials[e];
+ if (!r.extensions || !r.extensions[this.name]) return Promise.resolve();
+ let i = [], a = r.extensions[this.name];
+ t.specularIntensity = a.specularFactor === void 0 ? 1 : a.specularFactor, a.specularTexture !== void 0 && i.push(n.assignTexture(t, "specularIntensityMap", a.specularTexture));
+ let o = a.specularColorFactor || [
+ 1,
+ 1,
+ 1
+ ];
+ return t.specularColor = new B().setRGB(o[0], o[1], o[2], Ke), a.specularColorTexture !== void 0 && i.push(n.assignTexture(t, "specularColorMap", a.specularColorTexture, Ge)), Promise.all(i);
+ }
+}, Eu = class {
+ constructor(e) {
+ this.parser = e, this.name = mu.EXT_MATERIALS_BUMP;
+ }
+ getMaterialType(e) {
+ let t = this.parser.json.materials[e];
+ return !t.extensions || !t.extensions[this.name] ? null : Fa;
+ }
+ extendMaterialParams(e, t) {
+ let n = this.parser, r = n.json.materials[e];
+ if (!r.extensions || !r.extensions[this.name]) return Promise.resolve();
+ let i = [], a = r.extensions[this.name];
+ return t.bumpScale = a.bumpFactor === void 0 ? 1 : a.bumpFactor, a.bumpTexture !== void 0 && i.push(n.assignTexture(t, "bumpMap", a.bumpTexture)), Promise.all(i);
+ }
+}, Du = class {
+ constructor(e) {
+ this.parser = e, this.name = mu.KHR_MATERIALS_ANISOTROPY;
+ }
+ getMaterialType(e) {
+ let t = this.parser.json.materials[e];
+ return !t.extensions || !t.extensions[this.name] ? null : Fa;
+ }
+ extendMaterialParams(e, t) {
+ let n = this.parser, r = n.json.materials[e];
+ if (!r.extensions || !r.extensions[this.name]) return Promise.resolve();
+ let i = [], a = r.extensions[this.name];
+ return a.anisotropyStrength !== void 0 && (t.anisotropy = a.anisotropyStrength), a.anisotropyRotation !== void 0 && (t.anisotropyRotation = a.anisotropyRotation), a.anisotropyTexture !== void 0 && i.push(n.assignTexture(t, "anisotropyMap", a.anisotropyTexture)), Promise.all(i);
+ }
+}, Ou = class {
+ constructor(e) {
+ this.parser = e, this.name = mu.KHR_TEXTURE_BASISU;
+ }
+ loadTexture(e) {
+ let t = this.parser, n = t.json, r = n.textures[e];
+ if (!r.extensions || !r.extensions[this.name]) return null;
+ let i = r.extensions[this.name], a = t.options.ktx2Loader;
+ if (!a) {
+ if (n.extensionsRequired && n.extensionsRequired.indexOf(this.name) >= 0) throw Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");
+ return null;
+ }
+ return t.loadTextureImage(e, i.source, a);
+ }
+}, ku = class {
+ constructor(e) {
+ this.parser = e, this.name = mu.EXT_TEXTURE_WEBP;
+ }
+ loadTexture(e) {
+ let t = this.name, n = this.parser, r = n.json, i = r.textures[e];
+ if (!i.extensions || !i.extensions[t]) return null;
+ let a = i.extensions[t], o = r.images[a.source], s = n.textureLoader;
+ if (o.uri) {
+ let e = n.options.manager.getHandler(o.uri);
+ e !== null && (s = e);
+ }
+ return n.loadTextureImage(e, a.source, s);
+ }
+}, Au = class {
+ constructor(e) {
+ this.parser = e, this.name = mu.EXT_TEXTURE_AVIF;
+ }
+ loadTexture(e) {
+ let t = this.name, n = this.parser, r = n.json, i = r.textures[e];
+ if (!i.extensions || !i.extensions[t]) return null;
+ let a = i.extensions[t], o = r.images[a.source], s = n.textureLoader;
+ if (o.uri) {
+ let e = n.options.manager.getHandler(o.uri);
+ e !== null && (s = e);
+ }
+ return n.loadTextureImage(e, a.source, s);
+ }
+}, ju = class {
+ constructor(e) {
+ this.name = mu.EXT_MESHOPT_COMPRESSION, this.parser = e;
+ }
+ loadBufferView(e) {
+ let t = this.parser.json, n = t.bufferViews[e];
+ if (n.extensions && n.extensions[this.name]) {
+ let e = n.extensions[this.name], r = this.parser.getDependency("buffer", e.buffer), i = this.parser.options.meshoptDecoder;
+ if (!i || !i.supported) {
+ if (t.extensionsRequired && t.extensionsRequired.indexOf(this.name) >= 0) throw Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");
+ return null;
+ }
+ return r.then(function(t) {
+ let n = e.byteOffset || 0, r = e.byteLength || 0, a = e.count, o = e.byteStride, s = new Uint8Array(t, n, r);
+ return i.decodeGltfBufferAsync ? i.decodeGltfBufferAsync(a, o, s, e.mode, e.filter).then(function(e) {
+ return e.buffer;
+ }) : i.ready.then(function() {
+ let t = new ArrayBuffer(a * o);
+ return i.decodeGltfBuffer(new Uint8Array(t), a, o, s, e.mode, e.filter), t;
+ });
+ });
+ } else return null;
+ }
+}, Mu = class {
+ constructor(e) {
+ this.name = mu.EXT_MESH_GPU_INSTANCING, this.parser = e;
+ }
+ createNodeMesh(e) {
+ let t = this.parser.json, n = t.nodes[e];
+ if (!n.extensions || !n.extensions[this.name] || n.mesh === void 0) return null;
+ let r = t.meshes[n.mesh];
+ for (let e of r.primitives) if (e.mode !== Uu.TRIANGLES && e.mode !== Uu.TRIANGLE_STRIP && e.mode !== Uu.TRIANGLE_FAN && e.mode !== void 0) return null;
+ let i = n.extensions[this.name].attributes, a = [], o = {};
+ for (let e in i) a.push(this.parser.getDependency("accessor", i[e]).then((t) => (o[e] = t, o[e])));
+ return a.length < 1 ? null : (a.push(this.parser.createNodeMesh(e)), Promise.all(a).then((e) => {
+ let t = e.pop(), n = t.isGroup ? t.children : [t], r = e[0].count, i = [];
+ for (let e of n) {
+ let t = new z(), n = new R(), a = new $t(), s = new R(1, 1, 1), c = new ea(e.geometry, e.material, r);
+ for (let e = 0; e < r; e++) o.TRANSLATION && n.fromBufferAttribute(o.TRANSLATION, e), o.ROTATION && a.fromBufferAttribute(o.ROTATION, e), o.SCALE && s.fromBufferAttribute(o.SCALE, e), c.setMatrixAt(e, t.compose(n, a, s));
+ for (let t in o) if (t === "_COLOR_0") {
+ let e = o[t];
+ c.instanceColor = new Ki(e.array, e.itemSize, e.normalized);
+ } else t !== "TRANSLATION" && t !== "ROTATION" && t !== "SCALE" && e.geometry.setAttribute(t, o[t]);
+ nr.prototype.copy.call(c, e), this.parser.assignFinalMaterial(c), i.push(c);
+ }
+ return t.isGroup ? (t.clear(), t.add(...i), t) : i[0];
+ }));
+ }
+}, Nu = "glTF", Pu = 12, Fu = {
+ JSON: 1313821514,
+ BIN: 5130562
+}, Iu = class {
+ constructor(e) {
+ this.name = mu.KHR_BINARY_GLTF, this.content = null, this.body = null;
+ let t = new DataView(e, 0, Pu), n = new TextDecoder();
+ if (this.header = {
+ magic: n.decode(new Uint8Array(e.slice(0, 4))),
+ version: t.getUint32(4, !0),
+ length: t.getUint32(8, !0)
+ }, this.header.magic !== Nu) throw Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");
+ if (this.header.version < 2) throw Error("THREE.GLTFLoader: Legacy binary file detected.");
+ let r = this.header.length - Pu, i = new DataView(e, Pu), a = 0;
+ for (; a < r;) {
+ let t = i.getUint32(a, !0);
+ a += 4;
+ let r = i.getUint32(a, !0);
+ if (a += 4, r === Fu.JSON) {
+ let r = new Uint8Array(e, Pu + a, t);
+ this.content = n.decode(r);
+ } else if (r === Fu.BIN) {
+ let n = Pu + a;
+ this.body = e.slice(n, n + t);
+ }
+ a += t;
+ }
+ if (this.content === null) throw Error("THREE.GLTFLoader: JSON content not found.");
+ }
+}, Lu = class {
+ constructor(e, t) {
+ if (!t) throw Error("THREE.GLTFLoader: No DRACOLoader instance provided.");
+ this.name = mu.KHR_DRACO_MESH_COMPRESSION, this.json = e, this.dracoLoader = t, this.dracoLoader.preload();
+ }
+ decodePrimitive(e, t) {
+ let n = this.json, r = this.dracoLoader, i = e.extensions[this.name].bufferView, a = e.extensions[this.name].attributes, o = {}, s = {}, c = {};
+ for (let e in a) {
+ let t = Ju[e] || e.toLowerCase();
+ o[t] = a[e];
+ }
+ for (let t in e.attributes) {
+ let r = Ju[t] || t.toLowerCase();
+ if (a[t] !== void 0) {
+ let i = n.accessors[e.attributes[t]];
+ c[r] = Wu[i.componentType].name, s[r] = i.normalized === !0;
+ }
+ }
+ return t.getDependency("bufferView", i).then(function(e) {
+ return new Promise(function(t, n) {
+ r.decodeDracoFile(e, function(e) {
+ for (let t in e.attributes) {
+ let n = e.attributes[t], r = s[t];
+ r !== void 0 && (n.normalized = r);
+ }
+ t(e);
+ }, o, c, Ke, n);
+ });
+ });
+ }
+}, Ru = class {
+ constructor() {
+ this.name = mu.KHR_TEXTURE_TRANSFORM;
+ }
+ extendTexture(e, t) {
+ return (t.texCoord === void 0 || t.texCoord === e.channel) && t.offset === void 0 && t.rotation === void 0 && t.scale === void 0 ? e : (e = e.clone(), t.texCoord !== void 0 && (e.channel = t.texCoord), t.offset !== void 0 && e.offset.fromArray(t.offset), t.rotation !== void 0 && (e.rotation = t.rotation), t.scale !== void 0 && e.repeat.fromArray(t.scale), e.needsUpdate = !0, e);
+ }
+}, zu = class {
+ constructor() {
+ this.name = mu.KHR_MESH_QUANTIZATION;
+ }
+}, Bu = class extends Ua {
+ constructor(e, t, n, r) {
+ super(e, t, n, r);
+ }
+ copySampleValue_(e) {
+ let t = this.resultBuffer, n = this.sampleValues, r = this.valueSize, i = e * r * 3 + r;
+ for (let e = 0; e !== r; e++) t[e] = n[i + e];
+ return t;
+ }
+ interpolate_(e, t, n, r) {
+ let i = this.resultBuffer, a = this.sampleValues, o = this.valueSize, s = o * 2, c = o * 3, l = r - t, u = (n - t) / l, d = u * u, f = d * u, p = e * c, m = p - c, h = -2 * f + 3 * d, g = f - d, _ = 1 - h, v = g - d + u;
+ for (let e = 0; e !== o; e++) {
+ let t = a[m + e + o], n = a[m + e + s] * l, r = a[p + e + o], c = a[p + e] * l;
+ i[e] = _ * t + v * n + h * r + g * c;
+ }
+ return i;
+ }
+}, Vu = new $t(), Hu = class extends Bu {
+ interpolate_(e, t, n, r) {
+ let i = super.interpolate_(e, t, n, r);
+ return Vu.fromArray(i).normalize().toArray(i), i;
+ }
+}, Uu = {
+ FLOAT: 5126,
+ FLOAT_MAT3: 35675,
+ FLOAT_MAT4: 35676,
+ FLOAT_VEC2: 35664,
+ FLOAT_VEC3: 35665,
+ FLOAT_VEC4: 35666,
+ LINEAR: 9729,
+ REPEAT: 10497,
+ SAMPLER_2D: 35678,
+ POINTS: 0,
+ LINES: 1,
+ LINE_LOOP: 2,
+ LINE_STRIP: 3,
+ TRIANGLES: 4,
+ TRIANGLE_STRIP: 5,
+ TRIANGLE_FAN: 6,
+ UNSIGNED_BYTE: 5121,
+ UNSIGNED_SHORT: 5123
+}, Wu = {
+ 5120: Int8Array,
+ 5121: Uint8Array,
+ 5122: Int16Array,
+ 5123: Uint16Array,
+ 5125: Uint32Array,
+ 5126: Float32Array
+}, Gu = {
+ 9728: c,
+ 9729: d,
+ 9984: l,
+ 9985: f,
+ 9986: u,
+ 9987: p
+}, Ku = {
+ 33071: o,
+ 33648: s,
+ 10497: a
+}, qu = {
+ SCALAR: 1,
+ VEC2: 2,
+ VEC3: 3,
+ VEC4: 4,
+ MAT2: 4,
+ MAT3: 9,
+ MAT4: 16
+}, Ju = {
+ POSITION: "position",
+ NORMAL: "normal",
+ TANGENT: "tangent",
+ TEXCOORD_0: "uv",
+ TEXCOORD_1: "uv1",
+ TEXCOORD_2: "uv2",
+ TEXCOORD_3: "uv3",
+ COLOR_0: "color",
+ WEIGHTS_0: "skinWeight",
+ JOINTS_0: "skinIndex"
+}, Yu = {
+ scale: "scale",
+ translation: "position",
+ rotation: "quaternion",
+ weights: "morphTargetInfluences"
+}, Xu = {
+ CUBICSPLINE: void 0,
+ LINEAR: Ie,
+ STEP: Fe
+}, Zu = {
+ OPAQUE: "OPAQUE",
+ MASK: "MASK",
+ BLEND: "BLEND"
+};
+function Qu(e) {
+ return e.DefaultMaterial === void 0 && (e.DefaultMaterial = new Pa({
+ color: 16777215,
+ emissive: 0,
+ metalness: 1,
+ roughness: 1,
+ transparent: !1,
+ depthTest: !0,
+ side: 0
+ })), e.DefaultMaterial;
+}
+function $u(e, t, n) {
+ for (let r in n.extensions) e[r] === void 0 && (t.userData.gltfExtensions = t.userData.gltfExtensions || {}, t.userData.gltfExtensions[r] = n.extensions[r]);
+}
+function ed(e, t) {
+ t.extras !== void 0 && (typeof t.extras == "object" ? Object.assign(e.userData, t.extras) : console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, " + t.extras));
+}
+function td(e, t, n) {
+ let r = !1, i = !1, a = !1;
+ for (let e = 0, n = t.length; e < n; e++) {
+ let n = t[e];
+ if (n.POSITION !== void 0 && (r = !0), n.NORMAL !== void 0 && (i = !0), n.COLOR_0 !== void 0 && (a = !0), r && i && a) break;
+ }
+ if (!r && !i && !a) return Promise.resolve(e);
+ let o = [], s = [], c = [];
+ for (let l = 0, u = t.length; l < u; l++) {
+ let u = t[l];
+ if (r) {
+ let t = u.POSITION === void 0 ? e.attributes.position : n.getDependency("accessor", u.POSITION);
+ o.push(t);
+ }
+ if (i) {
+ let t = u.NORMAL === void 0 ? e.attributes.normal : n.getDependency("accessor", u.NORMAL);
+ s.push(t);
+ }
+ if (a) {
+ let t = u.COLOR_0 === void 0 ? e.attributes.color : n.getDependency("accessor", u.COLOR_0);
+ c.push(t);
+ }
+ }
+ return Promise.all([
+ Promise.all(o),
+ Promise.all(s),
+ Promise.all(c)
+ ]).then(function(t) {
+ let n = t[0], o = t[1], s = t[2];
+ return r && (e.morphAttributes.position = n), i && (e.morphAttributes.normal = o), a && (e.morphAttributes.color = s), e.morphTargetsRelative = !0, e;
+ });
+}
+function nd(e, t) {
+ if (e.updateMorphTargets(), t.weights !== void 0) for (let n = 0, r = t.weights.length; n < r; n++) e.morphTargetInfluences[n] = t.weights[n];
+ if (t.extras && Array.isArray(t.extras.targetNames)) {
+ let n = t.extras.targetNames;
+ if (e.morphTargetInfluences.length === n.length) {
+ e.morphTargetDictionary = {};
+ for (let t = 0, r = n.length; t < r; t++) e.morphTargetDictionary[n[t]] = t;
+ } else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.");
+ }
+}
+function rd(e) {
+ let t, n = e.extensions && e.extensions[mu.KHR_DRACO_MESH_COMPRESSION];
+ if (t = n ? "draco:" + n.bufferView + ":" + n.indices + ":" + id(n.attributes) : e.indices + ":" + id(e.attributes) + ":" + e.mode, e.targets !== void 0) for (let n = 0, r = e.targets.length; n < r; n++) t += ":" + id(e.targets[n]);
+ return t;
+}
+function id(e) {
+ let t = "", n = Object.keys(e).sort();
+ for (let r = 0, i = n.length; r < i; r++) t += n[r] + ":" + e[n[r]] + ";";
+ return t;
+}
+function ad(e) {
+ switch (e) {
+ case Int8Array: return 1 / 127;
+ case Uint8Array: return 1 / 255;
+ case Int16Array: return 1 / 32767;
+ case Uint16Array: return 1 / 65535;
+ default: throw Error("THREE.GLTFLoader: Unsupported normalized accessor component type.");
+ }
+}
+function od(e) {
+ return e.search(/\.jpe?g($|\?)/i) > 0 || e.search(/^data\:image\/jpeg/) === 0 ? "image/jpeg" : e.search(/\.webp($|\?)/i) > 0 || e.search(/^data\:image\/webp/) === 0 ? "image/webp" : e.search(/\.ktx2($|\?)/i) > 0 || e.search(/^data\:image\/ktx2/) === 0 ? "image/ktx2" : "image/png";
+}
+var sd = new z(), cd = class {
+ constructor(e = {}, t = {}) {
+ this.json = e, this.extensions = {}, this.plugins = {}, this.options = t, this.cache = new pu(), this.associations = /* @__PURE__ */ new Map(), this.primitiveCache = {}, this.nodeCache = {}, this.meshCache = {
+ refs: {},
+ uses: {}
+ }, this.cameraCache = {
+ refs: {},
+ uses: {}
+ }, this.lightCache = {
+ refs: {},
+ uses: {}
+ }, this.sourceCache = {}, this.textureCache = {}, this.nodeNamesUsed = {};
+ let n = !1, r = -1, i = !1, a = -1;
+ if (typeof navigator < "u") {
+ let e = navigator.userAgent;
+ n = /^((?!chrome|android).)*safari/i.test(e) === !0;
+ let t = e.match(/Version\/(\d+)/);
+ r = n && t ? parseInt(t[1], 10) : -1, i = e.indexOf("Firefox") > -1, a = i ? e.match(/Firefox\/([0-9]+)\./)[1] : -1;
+ }
+ typeof createImageBitmap > "u" || n && r < 17 || i && a < 98 ? this.textureLoader = new mo(this.options.manager) : this.textureLoader = new No(this.options.manager), this.textureLoader.setCrossOrigin(this.options.crossOrigin), this.textureLoader.setRequestHeader(this.options.requestHeader), this.fileLoader = new uo(this.options.manager), this.fileLoader.setResponseType("arraybuffer"), this.options.crossOrigin === "use-credentials" && this.fileLoader.setWithCredentials(!0);
+ }
+ setExtensions(e) {
+ this.extensions = e;
+ }
+ setPlugins(e) {
+ this.plugins = e;
+ }
+ parse(e, t) {
+ let n = this, r = this.json, i = this.extensions;
+ this.cache.removeAll(), this.nodeCache = {}, this._invokeAll(function(e) {
+ return e._markDefs && e._markDefs();
+ }), Promise.all(this._invokeAll(function(e) {
+ return e.beforeRoot && e.beforeRoot();
+ })).then(function() {
+ return Promise.all([
+ n.getDependencies("scene"),
+ n.getDependencies("animation"),
+ n.getDependencies("camera")
+ ]);
+ }).then(function(t) {
+ let a = {
+ scene: t[0][r.scene || 0],
+ scenes: t[0],
+ animations: t[1],
+ cameras: t[2],
+ asset: r.asset,
+ parser: n,
+ userData: {}
+ };
+ return $u(i, a, r), ed(a, r), Promise.all(n._invokeAll(function(e) {
+ return e.afterRoot && e.afterRoot(a);
+ })).then(function() {
+ for (let e of a.scenes) e.updateMatrixWorld();
+ e(a);
+ });
+ }).catch(t);
+ }
+ _markDefs() {
+ let e = this.json.nodes || [], t = this.json.skins || [], n = this.json.meshes || [];
+ for (let n = 0, r = t.length; n < r; n++) {
+ let r = t[n].joints;
+ for (let t = 0, n = r.length; t < n; t++) e[r[t]].isBone = !0;
+ }
+ for (let t = 0, r = e.length; t < r; t++) {
+ let r = e[t];
+ r.mesh !== void 0 && (this._addNodeRef(this.meshCache, r.mesh), r.skin !== void 0 && (n[r.mesh].isSkinnedMesh = !0)), r.camera !== void 0 && this._addNodeRef(this.cameraCache, r.camera);
+ }
+ }
+ _addNodeRef(e, t) {
+ t !== void 0 && (e.refs[t] === void 0 && (e.refs[t] = e.uses[t] = 0), e.refs[t]++);
+ }
+ _getNodeRef(e, t, n) {
+ if (e.refs[t] <= 1) return n;
+ let r = n.clone(), i = (e, t) => {
+ let n = this.associations.get(e);
+ n != null && this.associations.set(t, n);
+ for (let [n, r] of e.children.entries()) i(r, t.children[n]);
+ };
+ return i(n, r), r.name += "_instance_" + e.uses[t]++, r;
+ }
+ _invokeOne(e) {
+ let t = Object.values(this.plugins);
+ t.push(this);
+ for (let n = 0; n < t.length; n++) {
+ let r = e(t[n]);
+ if (r) return r;
+ }
+ return null;
+ }
+ _invokeAll(e) {
+ let t = Object.values(this.plugins);
+ t.unshift(this);
+ let n = [];
+ for (let r = 0; r < t.length; r++) {
+ let i = e(t[r]);
+ i && n.push(i);
+ }
+ return n;
+ }
+ getDependency(e, t) {
+ let n = e + ":" + t, r = this.cache.get(n);
+ if (!r) {
+ switch (e) {
+ case "scene":
+ r = this.loadScene(t);
+ break;
+ case "node":
+ r = this._invokeOne(function(e) {
+ return e.loadNode && e.loadNode(t);
+ });
+ break;
+ case "mesh":
+ r = this._invokeOne(function(e) {
+ return e.loadMesh && e.loadMesh(t);
+ });
+ break;
+ case "accessor":
+ r = this.loadAccessor(t);
+ break;
+ case "bufferView":
+ r = this._invokeOne(function(e) {
+ return e.loadBufferView && e.loadBufferView(t);
+ });
+ break;
+ case "buffer":
+ r = this.loadBuffer(t);
+ break;
+ case "material":
+ r = this._invokeOne(function(e) {
+ return e.loadMaterial && e.loadMaterial(t);
+ });
+ break;
+ case "texture":
+ r = this._invokeOne(function(e) {
+ return e.loadTexture && e.loadTexture(t);
+ });
+ break;
+ case "skin":
+ r = this.loadSkin(t);
+ break;
+ case "animation":
+ r = this._invokeOne(function(e) {
+ return e.loadAnimation && e.loadAnimation(t);
+ });
+ break;
+ case "camera":
+ r = this.loadCamera(t);
+ break;
+ default:
+ if (r = this._invokeOne(function(n) {
+ return n != this && n.getDependency && n.getDependency(e, t);
+ }), !r) throw Error("Unknown type: " + e);
+ break;
+ }
+ this.cache.add(n, r);
+ }
+ return r;
+ }
+ getDependencies(e) {
+ let t = this.cache.get(e);
+ if (!t) {
+ let n = this, r = this.json[e + (e === "mesh" ? "es" : "s")] || [];
+ t = Promise.all(r.map(function(t, r) {
+ return n.getDependency(e, r);
+ })), this.cache.add(e, t);
+ }
+ return t;
+ }
+ loadBuffer(e) {
+ let t = this.json.buffers[e], n = this.fileLoader;
+ if (t.type && t.type !== "arraybuffer") throw Error("THREE.GLTFLoader: " + t.type + " buffer type is not supported.");
+ if (t.uri === void 0 && e === 0) return Promise.resolve(this.extensions[mu.KHR_BINARY_GLTF].body);
+ let r = this.options;
+ return new Promise(function(e, i) {
+ n.load(Mo.resolveURL(t.uri, r.path), e, void 0, function() {
+ i(/* @__PURE__ */ Error("THREE.GLTFLoader: Failed to load buffer \"" + t.uri + "\"."));
+ });
+ });
+ }
+ loadBufferView(e) {
+ let t = this.json.bufferViews[e];
+ return this.getDependency("buffer", t.buffer).then(function(e) {
+ let n = t.byteLength || 0, r = t.byteOffset || 0;
+ return e.slice(r, r + n);
+ });
+ }
+ loadAccessor(e) {
+ let t = this, n = this.json, r = this.json.accessors[e];
+ if (r.bufferView === void 0 && r.sparse === void 0) {
+ let e = qu[r.type], t = Wu[r.componentType], n = r.normalized === !0, i = new t(r.count * e);
+ return Promise.resolve(new Nr(i, e, n));
+ }
+ let i = [];
+ return r.bufferView === void 0 ? i.push(null) : i.push(this.getDependency("bufferView", r.bufferView)), r.sparse !== void 0 && (i.push(this.getDependency("bufferView", r.sparse.indices.bufferView)), i.push(this.getDependency("bufferView", r.sparse.values.bufferView))), Promise.all(i).then(function(e) {
+ let i = e[0], a = qu[r.type], o = Wu[r.componentType], s = o.BYTES_PER_ELEMENT, c = s * a, l = r.byteOffset || 0, u = r.bufferView === void 0 ? void 0 : n.bufferViews[r.bufferView].byteStride, d = r.normalized === !0, f, p;
+ if (u && u !== c) {
+ let e = Math.floor(l / u), n = "InterleavedBuffer:" + r.bufferView + ":" + r.componentType + ":" + e + ":" + r.count, c = t.cache.get(n);
+ c || (f = new o(i, e * u, r.count * u / s), c = new Oi(f, u / s), t.cache.add(n, c)), p = new Ai(c, a, l % u / s, d);
+ } else f = i === null ? new o(r.count * a) : new o(i, l, r.count * a), p = new Nr(f, a, d);
+ if (r.sparse !== void 0) {
+ let t = qu.SCALAR, n = Wu[r.sparse.indices.componentType], s = r.sparse.indices.byteOffset || 0, c = r.sparse.values.byteOffset || 0, l = new n(e[1], s, r.sparse.count * t), u = new o(e[2], c, r.sparse.count * a);
+ i !== null && (p = new Nr(p.array.slice(), p.itemSize, p.normalized)), p.normalized = !1;
+ for (let e = 0, t = l.length; e < t; e++) {
+ let t = l[e];
+ if (p.setX(t, u[e * a]), a >= 2 && p.setY(t, u[e * a + 1]), a >= 3 && p.setZ(t, u[e * a + 2]), a >= 4 && p.setW(t, u[e * a + 3]), a >= 5) throw Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.");
+ }
+ p.normalized = d;
+ }
+ return p;
+ });
+ }
+ loadTexture(e) {
+ let t = this.json, n = this.options, r = t.textures[e].source, i = t.images[r], a = this.textureLoader;
+ if (i.uri) {
+ let e = n.manager.getHandler(i.uri);
+ e !== null && (a = e);
+ }
+ return this.loadTextureImage(e, r, a);
+ }
+ loadTextureImage(e, t, n) {
+ let r = this, i = this.json, a = i.textures[e], o = i.images[t], s = (o.uri || o.bufferView) + ":" + a.sampler;
+ if (this.textureCache[s]) return this.textureCache[s];
+ let c = this.loadImageSource(t, n).then(function(t) {
+ t.flipY = !1, t.name = a.name || o.name || "", t.name === "" && typeof o.uri == "string" && o.uri.startsWith("data:image/") === !1 && (t.name = o.uri);
+ let n = (i.samplers || {})[a.sampler] || {};
+ return t.magFilter = Gu[n.magFilter] || 1006, t.minFilter = Gu[n.minFilter] || 1008, t.wrapS = Ku[n.wrapS] || 1e3, t.wrapT = Ku[n.wrapT] || 1e3, t.generateMipmaps = !t.isCompressedTexture && t.minFilter !== 1003 && t.minFilter !== 1006, r.associations.set(t, { textures: e }), t;
+ }).catch(function() {
+ return null;
+ });
+ return this.textureCache[s] = c, c;
+ }
+ loadImageSource(e, t) {
+ let n = this, r = this.json, i = this.options;
+ if (this.sourceCache[e] !== void 0) return this.sourceCache[e].then((e) => e.clone());
+ let a = r.images[e], o = self.URL || self.webkitURL, s = a.uri || "", c = !1;
+ if (a.bufferView !== void 0) s = n.getDependency("bufferView", a.bufferView).then(function(e) {
+ c = !0;
+ let t = new Blob([e], { type: a.mimeType });
+ return s = o.createObjectURL(t), s;
+ });
+ else if (a.uri === void 0) throw Error("THREE.GLTFLoader: Image " + e + " is missing URI and bufferView");
+ let l = Promise.resolve(s).then(function(e) {
+ return new Promise(function(n, r) {
+ let a = n;
+ t.isImageBitmapLoader === !0 && (a = function(e) {
+ let t = new qt(e);
+ t.needsUpdate = !0, n(t);
+ }), t.load(Mo.resolveURL(e, i.path), a, void 0, r);
+ });
+ }).then(function(e) {
+ return c === !0 && o.revokeObjectURL(s), ed(e, a), e.userData.mimeType = a.mimeType || od(a.uri), e;
+ }).catch(function(e) {
+ throw console.error("THREE.GLTFLoader: Couldn't load texture", s), e;
+ });
+ return this.sourceCache[e] = l, l;
+ }
+ assignTexture(e, t, n, r) {
+ let i = this;
+ return this.getDependency("texture", n.index).then(function(a) {
+ if (!a) return null;
+ if (n.texCoord !== void 0 && n.texCoord > 0 && (a = a.clone(), a.channel = n.texCoord), i.extensions[mu.KHR_TEXTURE_TRANSFORM]) {
+ let e = n.extensions === void 0 ? void 0 : n.extensions[mu.KHR_TEXTURE_TRANSFORM];
+ if (e) {
+ let t = i.associations.get(a);
+ a = i.extensions[mu.KHR_TEXTURE_TRANSFORM].extendTexture(a, e), i.associations.set(a, t);
+ }
+ }
+ return r !== void 0 && (a.colorSpace = r), e[t] = a, a;
+ });
+ }
+ assignFinalMaterial(e) {
+ let t = e.geometry, n = e.material, r = t.attributes.tangent === void 0, i = t.attributes.color !== void 0, a = t.attributes.normal === void 0;
+ if (e.isPoints) {
+ let e = "PointsMaterial:" + n.uuid, t = this.cache.get(e);
+ t || (t = new Sa(), Cr.prototype.copy.call(t, n), t.color.copy(n.color), t.map = n.map, t.sizeAttenuation = !1, this.cache.add(e, t)), n = t;
+ } else if (e.isLine) {
+ let e = "LineBasicMaterial:" + n.uuid, t = this.cache.get(e);
+ t || (t = new ca(), Cr.prototype.copy.call(t, n), t.color.copy(n.color), t.map = n.map, this.cache.add(e, t)), n = t;
+ }
+ if (r || i || a) {
+ let e = "ClonedMaterial:" + n.uuid + ":";
+ r && (e += "derivative-tangents:"), i && (e += "vertex-colors:"), a && (e += "flat-shading:");
+ let t = this.cache.get(e);
+ t || (t = n.clone(), i && (t.vertexColors = !0), a && (t.flatShading = !0), r && (t.normalScale && (t.normalScale.y *= -1), t.clearcoatNormalScale && (t.clearcoatNormalScale.y *= -1)), this.cache.add(e, t), this.associations.set(t, this.associations.get(n))), n = t;
+ }
+ e.material = n;
+ }
+ getMaterialType() {
+ return Pa;
+ }
+ loadMaterial(e) {
+ let t = this, n = this.json, r = this.extensions, i = n.materials[e], a, o = {}, s = i.extensions || {}, c = [];
+ if (s[mu.KHR_MATERIALS_UNLIT]) {
+ let e = r[mu.KHR_MATERIALS_UNLIT];
+ a = e.getMaterialType(), c.push(e.extendParams(o, i, t));
+ } else {
+ let n = i.pbrMetallicRoughness || {};
+ if (o.color = new B(1, 1, 1), o.opacity = 1, Array.isArray(n.baseColorFactor)) {
+ let e = n.baseColorFactor;
+ o.color.setRGB(e[0], e[1], e[2], Ke), o.opacity = e[3];
+ }
+ n.baseColorTexture !== void 0 && c.push(t.assignTexture(o, "map", n.baseColorTexture, Ge)), o.metalness = n.metallicFactor === void 0 ? 1 : n.metallicFactor, o.roughness = n.roughnessFactor === void 0 ? 1 : n.roughnessFactor, n.metallicRoughnessTexture !== void 0 && (c.push(t.assignTexture(o, "metalnessMap", n.metallicRoughnessTexture)), c.push(t.assignTexture(o, "roughnessMap", n.metallicRoughnessTexture))), a = this._invokeOne(function(t) {
+ return t.getMaterialType && t.getMaterialType(e);
+ }), c.push(Promise.all(this._invokeAll(function(t) {
+ return t.extendMaterialParams && t.extendMaterialParams(e, o);
+ })));
+ }
+ i.doubleSided === !0 && (o.side = 2);
+ let l = i.alphaMode || Zu.OPAQUE;
+ if (l === Zu.BLEND ? (o.transparent = !0, o.depthWrite = !1) : (o.transparent = !1, l === Zu.MASK && (o.alphaTest = i.alphaCutoff === void 0 ? .5 : i.alphaCutoff)), i.normalTexture !== void 0 && a !== wr && (c.push(t.assignTexture(o, "normalMap", i.normalTexture)), o.normalScale = new L(1, 1), i.normalTexture.scale !== void 0)) {
+ let e = i.normalTexture.scale;
+ o.normalScale.set(e, e);
+ }
+ if (i.occlusionTexture !== void 0 && a !== wr && (c.push(t.assignTexture(o, "aoMap", i.occlusionTexture)), i.occlusionTexture.strength !== void 0 && (o.aoMapIntensity = i.occlusionTexture.strength)), i.emissiveFactor !== void 0 && a !== wr) {
+ let e = i.emissiveFactor;
+ o.emissive = new B().setRGB(e[0], e[1], e[2], Ke);
+ }
+ return i.emissiveTexture !== void 0 && a !== wr && c.push(t.assignTexture(o, "emissiveMap", i.emissiveTexture, Ge)), Promise.all(c).then(function() {
+ let n = new a(o);
+ return i.name && (n.name = i.name), ed(n, i), t.associations.set(n, { materials: e }), i.extensions && $u(r, n, i), n;
+ });
+ }
+ createUniqueName(e) {
+ let t = qo.sanitizeNodeName(e || "");
+ return t in this.nodeNamesUsed ? t + "_" + ++this.nodeNamesUsed[t] : (this.nodeNamesUsed[t] = 0, t);
+ }
+ loadGeometries(e) {
+ let t = this, n = this.extensions, r = this.primitiveCache;
+ function i(e) {
+ return n[mu.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e, t).then(function(n) {
+ return ud(n, e, t);
+ });
+ }
+ let a = [];
+ for (let n = 0, o = e.length; n < o; n++) {
+ let o = e[n], s = rd(o), c = r[s];
+ if (c) a.push(c.promise);
+ else {
+ let e;
+ e = o.extensions && o.extensions[mu.KHR_DRACO_MESH_COMPRESSION] ? i(o) : ud(new Wr(), o, t), r[s] = {
+ primitive: o,
+ promise: e
+ }, a.push(e);
+ }
+ }
+ return Promise.all(a);
+ }
+ loadMesh(e) {
+ let t = this, n = this.json, r = this.extensions, i = n.meshes[e], a = i.primitives, o = [];
+ for (let e = 0, t = a.length; e < t; e++) {
+ let t = a[e].material === void 0 ? Qu(this.cache) : this.getDependency("material", a[e].material);
+ o.push(t);
+ }
+ return o.push(t.loadGeometries(a)), Promise.all(o).then(function(n) {
+ let o = n.slice(0, n.length - 1), s = n[n.length - 1], c = [];
+ for (let n = 0, l = s.length; n < l; n++) {
+ let l = s[n], u = a[n], d, f = o[n];
+ if (u.mode === Uu.TRIANGLES || u.mode === Uu.TRIANGLE_STRIP || u.mode === Uu.TRIANGLE_FAN || u.mode === void 0) d = i.isSkinnedMesh === !0 ? new Bi(l, f) : new ni(l, f), d.isSkinnedMesh === !0 && d.normalizeSkinWeights(), u.mode === Uu.TRIANGLE_STRIP ? d.geometry = du(d.geometry, 1) : u.mode === Uu.TRIANGLE_FAN && (d.geometry = du(d.geometry, 2));
+ else if (u.mode === Uu.LINES) d = new ba(l, f);
+ else if (u.mode === Uu.LINE_STRIP) d = new ga(l, f);
+ else if (u.mode === Uu.LINE_LOOP) d = new xa(l, f);
+ else if (u.mode === Uu.POINTS) d = new Da(l, f);
+ else throw Error("THREE.GLTFLoader: Primitive mode unsupported: " + u.mode);
+ Object.keys(d.geometry.morphAttributes).length > 0 && nd(d, i), d.name = t.createUniqueName(i.name || "mesh_" + e), ed(d, i), u.extensions && $u(r, d, u), t.assignFinalMaterial(d), c.push(d);
+ }
+ for (let n = 0, r = c.length; n < r; n++) t.associations.set(c[n], {
+ meshes: e,
+ primitives: n
+ });
+ if (c.length === 1) return i.extensions && $u(r, c[0], i), c[0];
+ let l = new wi();
+ i.extensions && $u(r, l, i), t.associations.set(l, { meshes: e });
+ for (let e = 0, t = c.length; e < t; e++) l.add(c[e]);
+ return l;
+ });
+ }
+ loadCamera(e) {
+ let t, n = this.json.cameras[e], r = n[n.type];
+ if (!r) {
+ console.warn("THREE.GLTFLoader: Missing camera parameters.");
+ return;
+ }
+ return n.type === "perspective" ? t = new vi(wt.radToDeg(r.yfov), r.aspectRatio || 1, r.znear || 1, r.zfar || 2e6) : n.type === "orthographic" && (t = new Oo(-r.xmag, r.xmag, r.ymag, -r.ymag, r.znear, r.zfar)), n.name && (t.name = this.createUniqueName(n.name)), ed(t, n), Promise.resolve(t);
+ }
+ loadSkin(e) {
+ let t = this.json.skins[e], n = [];
+ for (let e = 0, r = t.joints.length; e < r; e++) n.push(this._loadNodeShallow(t.joints[e]));
+ return t.inverseBindMatrices === void 0 ? n.push(null) : n.push(this.getDependency("accessor", t.inverseBindMatrices)), Promise.all(n).then(function(e) {
+ let n = e.pop(), r = e, i = [], a = [];
+ for (let e = 0, o = r.length; e < o; e++) {
+ let o = r[e];
+ if (o) {
+ i.push(o);
+ let t = new z();
+ n !== null && t.fromArray(n.array, e * 16), a.push(t);
+ } else console.warn("THREE.GLTFLoader: Joint \"%s\" could not be found.", t.joints[e]);
+ }
+ return new Gi(i, a);
+ });
+ }
+ loadAnimation(e) {
+ let t = this.json, n = this, r = t.animations[e], i = r.name ? r.name : "animation_" + e, a = [], o = [], s = [], c = [], l = [];
+ for (let e = 0, t = r.channels.length; e < t; e++) {
+ let t = r.channels[e], n = r.samplers[t.sampler], i = t.target, u = i.node, d = r.parameters === void 0 ? n.input : r.parameters[n.input], f = r.parameters === void 0 ? n.output : r.parameters[n.output];
+ i.node !== void 0 && (a.push(this.getDependency("node", u)), o.push(this.getDependency("accessor", d)), s.push(this.getDependency("accessor", f)), c.push(n), l.push(i));
+ }
+ return Promise.all([
+ Promise.all(a),
+ Promise.all(o),
+ Promise.all(s),
+ Promise.all(c),
+ Promise.all(l)
+ ]).then(function(e) {
+ let t = e[0], r = e[1], a = e[2], o = e[3], s = e[4], c = [];
+ for (let e = 0, i = t.length; e < i; e++) {
+ let i = t[e], l = r[e], u = a[e], d = o[e], f = s[e];
+ if (i === void 0) continue;
+ i.updateMatrix && i.updateMatrix();
+ let p = n._createAnimationTracks(i, l, u, d, f);
+ if (p) for (let e = 0; e < p.length; e++) c.push(p[e]);
+ }
+ return new to(i, void 0, c);
+ });
+ }
+ createNodeMesh(e) {
+ let t = this.json, n = this, r = t.nodes[e];
+ return r.mesh === void 0 ? null : n.getDependency("mesh", r.mesh).then(function(e) {
+ let t = n._getNodeRef(n.meshCache, r.mesh, e);
+ return r.weights !== void 0 && t.traverse(function(e) {
+ if (e.isMesh) for (let t = 0, n = r.weights.length; t < n; t++) e.morphTargetInfluences[t] = r.weights[t];
+ }), t;
+ });
+ }
+ loadNode(e) {
+ let t = this.json, n = this, r = t.nodes[e], i = n._loadNodeShallow(e), a = [], o = r.children || [];
+ for (let e = 0, t = o.length; e < t; e++) a.push(n.getDependency("node", o[e]));
+ let s = r.skin === void 0 ? Promise.resolve(null) : n.getDependency("skin", r.skin);
+ return Promise.all([
+ i,
+ Promise.all(a),
+ s
+ ]).then(function(e) {
+ let t = e[0], n = e[1], r = e[2];
+ r !== null && t.traverse(function(e) {
+ e.isSkinnedMesh && e.bind(r, sd);
+ });
+ for (let e = 0, r = n.length; e < r; e++) t.add(n[e]);
+ return t;
+ });
+ }
+ _loadNodeShallow(e) {
+ let t = this.json, n = this.extensions, r = this;
+ if (this.nodeCache[e] !== void 0) return this.nodeCache[e];
+ let i = t.nodes[e], a = i.name ? r.createUniqueName(i.name) : "", o = [], s = r._invokeOne(function(t) {
+ return t.createNodeMesh && t.createNodeMesh(e);
+ });
+ return s && o.push(s), i.camera !== void 0 && o.push(r.getDependency("camera", i.camera).then(function(e) {
+ return r._getNodeRef(r.cameraCache, i.camera, e);
+ })), r._invokeAll(function(t) {
+ return t.createNodeAttachment && t.createNodeAttachment(e);
+ }).forEach(function(e) {
+ o.push(e);
+ }), this.nodeCache[e] = Promise.all(o).then(function(t) {
+ let o;
+ if (o = i.isBone === !0 ? new Vi() : t.length > 1 ? new wi() : t.length === 1 ? t[0] : new nr(), o !== t[0]) for (let e = 0, n = t.length; e < n; e++) o.add(t[e]);
+ if (i.name && (o.userData.name = i.name, o.name = a), ed(o, i), i.extensions && $u(n, o, i), i.matrix !== void 0) {
+ let e = new z();
+ e.fromArray(i.matrix), o.applyMatrix4(e);
+ } else i.translation !== void 0 && o.position.fromArray(i.translation), i.rotation !== void 0 && o.quaternion.fromArray(i.rotation), i.scale !== void 0 && o.scale.fromArray(i.scale);
+ return r.associations.has(o) || r.associations.set(o, {}), r.associations.get(o).nodes = e, o;
+ }), this.nodeCache[e];
+ }
+ loadScene(e) {
+ let t = this.extensions, n = this.json.scenes[e], r = this, i = new wi();
+ n.name && (i.name = r.createUniqueName(n.name)), ed(i, n), n.extensions && $u(t, i, n);
+ let a = n.nodes || [], o = [];
+ for (let e = 0, t = a.length; e < t; e++) o.push(r.getDependency("node", a[e]));
+ return Promise.all(o).then(function(e) {
+ for (let t = 0, n = e.length; t < n; t++) i.add(e[t]);
+ return r.associations = ((e) => {
+ let t = /* @__PURE__ */ new Map();
+ for (let [e, n] of r.associations) (e instanceof Cr || e instanceof qt) && t.set(e, n);
+ return e.traverse((e) => {
+ let n = r.associations.get(e);
+ n != null && t.set(e, n);
+ }), t;
+ })(i), i;
+ });
+ }
+ _createAnimationTracks(e, t, n, r, i) {
+ let a = [], o = e.name ? e.name : e.uuid, s = [];
+ Yu[i.path] === Yu.weights ? e.traverse(function(e) {
+ e.morphTargetInfluences && s.push(e.name ? e.name : e.uuid);
+ }) : s.push(o);
+ let c;
+ switch (Yu[i.path]) {
+ case Yu.weights:
+ c = Xa;
+ break;
+ case Yu.rotation:
+ c = Qa;
+ break;
+ case Yu.translation:
+ case Yu.scale:
+ c = eo;
+ break;
+ default:
+ switch (n.itemSize) {
+ case 1:
+ c = Xa;
+ break;
+ default:
+ c = eo;
+ break;
+ }
+ break;
+ }
+ let l = r.interpolation === void 0 ? Ie : Xu[r.interpolation], u = this._getArrayFromAccessor(n);
+ for (let e = 0, n = s.length; e < n; e++) {
+ let n = new c(s[e] + "." + Yu[i.path], t.array, u, l);
+ r.interpolation === "CUBICSPLINE" && this._createCubicSplineTrackInterpolant(n), a.push(n);
+ }
+ return a;
+ }
+ _getArrayFromAccessor(e) {
+ let t = e.array;
+ if (e.normalized) {
+ let e = ad(t.constructor), n = new Float32Array(t.length);
+ for (let r = 0, i = t.length; r < i; r++) n[r] = t[r] * e;
+ t = n;
+ }
+ return t;
+ }
+ _createCubicSplineTrackInterpolant(e) {
+ e.createInterpolant = function(e) {
+ return new (this instanceof Qa ? Hu : Bu)(this.times, this.values, this.getValueSize() / 3, e);
+ }, e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = !0;
+ }
+};
+function ld(e, t, n) {
+ let r = t.attributes, i = new nn();
+ if (r.POSITION !== void 0) {
+ let e = n.json.accessors[r.POSITION], t = e.min, a = e.max;
+ if (t !== void 0 && a !== void 0) {
+ if (i.set(new R(t[0], t[1], t[2]), new R(a[0], a[1], a[2])), e.normalized) {
+ let t = ad(Wu[e.componentType]);
+ i.min.multiplyScalar(t), i.max.multiplyScalar(t);
+ }
+ } else {
+ console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");
+ return;
+ }
+ } else return;
+ let a = t.targets;
+ if (a !== void 0) {
+ let e = new R(), t = new R();
+ for (let r = 0, i = a.length; r < i; r++) {
+ let i = a[r];
+ if (i.POSITION !== void 0) {
+ let r = n.json.accessors[i.POSITION], a = r.min, o = r.max;
+ if (a !== void 0 && o !== void 0) {
+ if (t.setX(Math.max(Math.abs(a[0]), Math.abs(o[0]))), t.setY(Math.max(Math.abs(a[1]), Math.abs(o[1]))), t.setZ(Math.max(Math.abs(a[2]), Math.abs(o[2]))), r.normalized) {
+ let e = ad(Wu[r.componentType]);
+ t.multiplyScalar(e);
+ }
+ e.max(t);
+ } else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");
+ }
+ }
+ i.expandByVector(e);
+ }
+ e.boundingBox = i;
+ let o = new xn();
+ i.getCenter(o.center), o.radius = i.min.distanceTo(i.max) / 2, e.boundingSphere = o;
+}
+function ud(e, t, n) {
+ let r = t.attributes, i = [];
+ function a(t, r) {
+ return n.getDependency("accessor", t).then(function(t) {
+ e.setAttribute(r, t);
+ });
+ }
+ for (let t in r) {
+ let n = Ju[t] || t.toLowerCase();
+ n in e.attributes || i.push(a(r[t], n));
+ }
+ if (t.indices !== void 0 && !e.index) {
+ let r = n.getDependency("accessor", t.indices).then(function(t) {
+ e.setIndex(t);
+ });
+ i.push(r);
+ }
+ return Rt.workingColorSpace !== "srgb-linear" && "COLOR_0" in r && console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Rt.workingColorSpace}" not supported.`), ed(e, t), ld(e, t, n), Promise.all(i).then(function() {
+ return t.targets === void 0 ? e : td(e, t.targets, n);
+ });
+}
+//#endregion
+//#region node_modules/three/examples/jsm/libs/meshopt_decoder.module.js
+var dd = (function() {
+ var e = "b9H79Tebbbe8Fv9Gbb9Gvuuuuueu9Giuuub9Geueu9Giuuueuikqbeeedddillviebeoweuec:q;iekr;leDo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbeY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVbdE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbiL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtblK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949Wbol79IV9Rbrq:P8Yqdbk;3sezu8Jjjjjbcj;eb9Rgv8Kjjjjbc9:hodnadcefal0mbcuhoaiRbbc:Ge9hmbavaialfgrad9Radz1jjjbhwcj;abad9UhoaicefhldnadTmbaoc;WFbGgocjdaocjd6EhDcbhqinaqae9pmeaDaeaq9RaqaDfae6Egkcsfgocl4cifcd4hxdndndndnaoc9WGgmTmbcbhPcehsawcjdfhzalhHinaraH9Rax6midnaraHaxfgl9RcK6mbczhoinawcj;cbfaogifgoc9WfhOdndndndndnaHaic9WfgAco4fRbbaAci4coG4ciGPlbedibkaO9cb83ibaOcwf9cb83ibxikaOalRblalRbbgAco4gCaCciSgCE86bbaocGfalclfaCfgORbbaAcl4ciGgCaCciSgCE86bbaocVfaOaCfgORbbaAcd4ciGgCaCciSgCE86bbaoc7faOaCfgORbbaAciGgAaAciSgAE86bbaoctfaOaAfgARbbalRbegOco4gCaCciSgCE86bbaoc91faAaCfgARbbaOcl4ciGgCaCciSgCE86bbaoc4faAaCfgARbbaOcd4ciGgCaCciSgCE86bbaoc93faAaCfgARbbaOciGgOaOciSgOE86bbaoc94faAaOfgARbbalRbdgOco4gCaCciSgCE86bbaoc95faAaCfgARbbaOcl4ciGgCaCciSgCE86bbaoc96faAaCfgARbbaOcd4ciGgCaCciSgCE86bbaoc97faAaCfgARbbaOciGgOaOciSgOE86bbaoc98faAaOfgORbbalRbiglco4gAaAciSgAE86bbaoc99faOaAfgORbbalcl4ciGgAaAciSgAE86bbaoc9:faOaAfgORbbalcd4ciGgAaAciSgAE86bbaocufaOaAfgoRbbalciGglalciSglE86bbaoalfhlxdkaOalRbwalRbbgAcl4gCaCcsSgCE86bbaocGfalcwfaCfgORbbaAcsGgAaAcsSgAE86bbaocVfaOaAfgORbbalRbegAcl4gCaCcsSgCE86bbaoc7faOaCfgORbbaAcsGgAaAcsSgAE86bbaoctfaOaAfgORbbalRbdgAcl4gCaCcsSgCE86bbaoc91faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc4faOaAfgORbbalRbigAcl4gCaCcsSgCE86bbaoc93faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc94faOaAfgORbbalRblgAcl4gCaCcsSgCE86bbaoc95faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc96faOaAfgORbbalRbvgAcl4gCaCcsSgCE86bbaoc97faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc98faOaAfgORbbalRbogAcl4gCaCcsSgCE86bbaoc99faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc9:faOaAfgORbbalRbrglcl4gAaAcsSgAE86bbaocufaOaAfgoRbbalcsGglalcsSglE86bbaoalfhlxekaOal8Pbb83bbaOcwfalcwf8Pbb83bbalczfhlkdnaiam9pmbaiczfhoaral9RcL0mekkaiam6mialTmidnakTmbawaPfRbbhOcbhoazhiinaiawcj;cbfaofRbbgAce4cbaAceG9R7aOfgO86bbaiadfhiaocefgoak9hmbkkazcefhzaPcefgPad6hsalhHaPad9hmexvkkcbhlasceGmdxikalaxad2fhCdnakTmbcbhHcehsawcjdfhminaral9Rax6mialTmdalaxfhlawaHfRbbhOcbhoamhiinaiawcj;cbfaofRbbgAce4cbaAceG9R7aOfgO86bbaiadfhiaocefgoak9hmbkamcefhmaHcefgHad6hsaHad9hmbkaChlxikcbhocehsinaral9Rax6mdalTmealaxfhlaocefgoad6hsadao9hmbkaChlxdkcbhlasceGTmekc9:hoxikabaqad2fawcjdfakad2z1jjjb8Aawawcjdfakcufad2fadz1jjjb8Aakaqfhqalmbkc9:hoxekcbc99aral9Radcaadca0ESEhokavcj;ebf8Kjjjjbaok;yzeHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecjez:jjjjb8AavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhodnaeTmbcmcsaDceSEhkcbhxcbhmcbhDcbhicbhlindnaoaq9nmbc9:hoxikdndnawRbbgrc;Ve0mbavc;abfalarcl4cu7fcsGcitfgPydlhsaPydbhzdnarcsGgPak9pmbavaiarcu7fcsGcdtfydbaxaPEhraPThPdndnadcd9hmbabaDcetfgHaz87ebaHcdfas87ebaHclfar87ebxekabaDcdtfgHazBdbaHclfasBdbaHcwfarBdbkaxaPfhxavc;abfalcitfgHarBdbaHasBdlavaicdtfarBdbavc;abfalcefcsGglcitfgHazBdbaHarBdlaiaPfhialcefhlxdkdndnaPcsSmbamaPfaPc987fcefhmxekaocefhrao8SbbgPcFeGhHdndnaPcu9mmbarhoxekaocvfhoaHcFbGhHcrhPdninar8SbbgOcFbGaPtaHVhHaOcu9kmearcefhraPcrfgPc8J9hmbxdkkarcefhokaHce4cbaHceG9R7amfhmkdndnadcd9hmbabaDcetfgraz87ebarcdfas87ebarclfam87ebxekabaDcdtfgrazBdbarclfasBdbarcwfamBdbkavc;abfalcitfgramBdbarasBdlavaicdtfamBdbavc;abfalcefcsGglcitfgrazBdbaramBdlaicefhialcefhlxekdnarcpe0mbaxcefgOavaiaqarcsGfRbbgPcl49RcsGcdtfydbaPcz6gHEhravaiaP9RcsGcdtfydbaOaHfgsaPcsGgOEhPaOThOdndnadcd9hmbabaDcetfgzax87ebazcdfar87ebazclfaP87ebxekabaDcdtfgzaxBdbazclfarBdbazcwfaPBdbkavaicdtfaxBdbavc;abfalcitfgzarBdbazaxBdlavaicefgicsGcdtfarBdbavc;abfalcefcsGcitfgzaPBdbazarBdlavaiaHfcsGgicdtfaPBdbavc;abfalcdfcsGglcitfgraxBdbaraPBdlalcefhlaiaOfhiasaOfhxxekaxcbaoRbbgzEgAarc;:eSgrfhsazcsGhCazcl4hXdndnazcs0mbascefhOxekashOavaiaX9RcsGcdtfydbhskdndnaCmbaOcefhxxekaOhxavaiaz9RcsGcdtfydbhOkdndnarTmbaocefhrxekaocdfhrao8SbegHcFeGhPdnaHcu9kmbaocofhAaPcFbGhPcrhodninar8SbbgHcFbGaotaPVhPaHcu9kmearcefhraocrfgoc8J9hmbkaAhrxekarcefhrkaPce4cbaPceG9R7amfgmhAkdndnaXcsSmbarhPxekarcefhPar8SbbgocFeGhHdnaocu9kmbarcvfhsaHcFbGhHcrhodninaP8SbbgrcFbGaotaHVhHarcu9kmeaPcefhPaocrfgoc8J9hmbkashPxekaPcefhPkaHce4cbaHceG9R7amfgmhskdndnaCcsSmbaPhoxekaPcefhoaP8SbbgrcFeGhHdnarcu9kmbaPcvfhOaHcFbGhHcrhrdninao8SbbgPcFbGartaHVhHaPcu9kmeaocefhoarcrfgrc8J9hmbkaOhoxekaocefhokaHce4cbaHceG9R7amfgmhOkdndnadcd9hmbabaDcetfgraA87ebarcdfas87ebarclfaO87ebxekabaDcdtfgraABdbarclfasBdbarcwfaOBdbkavc;abfalcitfgrasBdbaraABdlavaicdtfaABdbavc;abfalcefcsGcitfgraOBdbarasBdlavaicefgicsGcdtfasBdbavc;abfalcdfcsGcitfgraABdbaraOBdlavaiazcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhialcifhlkawcefhwalcsGhlaicsGhiaDcifgDae6mbkkcbc99aoaqSEhokavc;aef8Kjjjjbaok:llevu8Jjjjjbcz9Rhvc9:hodnaecvfal0mbcuhoaiRbbc;:eGc;qe9hmbav9cb83iwaicefhraialfc98fhwdnaeTmbdnadcdSmbcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcdtfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfglBdbaoalBdbaDcefgDae9hmbxdkkcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcetfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfgl87ebaoalBdbaDcefgDae9hmbkkcbc99arawSEhokaok:Lvoeue99dud99eud99dndnadcl9hmbaeTmeindndnabcdfgd8Sbb:Yab8Sbbgi:Ygl:l:tabcefgv8Sbbgo:Ygr:l:tgwJbb;:9cawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai86bbdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad86bbdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad86bbabclfhbaecufgembxdkkaeTmbindndnabclfgd8Ueb:Yab8Uebgi:Ygl:l:tabcdfgv8Uebgo:Ygr:l:tgwJb;:FSawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai87ebdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad87ebdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad87ebabcwfhbaecufgembkkk;siliui99iue99dnaeTmbcbhiabhlindndnJ;Zl81Zalcof8UebgvciV:Y:vgoal8Ueb:YNgrJb;:FSNJbbbZJbbb:;arJbbbb9GEMgw:lJbbb9p9DTmbaw:OhDxekcjjjj94hDkalclf8Uebhqalcdf8UebhkabavcefciGaiVcetfaD87ebdndnaoak:YNgwJb;:FSNJbbbZJbbb:;awJbbbb9GEMgx:lJbbb9p9DTmbax:Ohkxekcjjjj94hkkabavcdfciGaiVcetfak87ebdndnaoaq:YNgoJb;:FSNJbbbZJbbb:;aoJbbbb9GEMgx:lJbbb9p9DTmbax:Ohqxekcjjjj94hqkabavcufciGaiVcetfaq87ebdndnJbbjZararN:tawawN:taoaoN:tgrJbbbbarJbbbb9GE:rJb;:FSNJbbbZMgr:lJbbb9p9DTmbar:Ohqxekcjjjj94hqkabavciGaiVcetfaq87ebalcwfhlaiclfhiaecufgembkkk9mbdnadcd4ae2geTmbinababydbgdcwtcw91:Yadce91cjjj;8ifcjjj98G::NUdbabclfhbaecufgembkkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaiczfhiaeczfheadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabkkkebcjwklz9Kbb", t = "b9H79TebbbeKl9Gbb9Gvuuuuueu9Giuuub9Geueuikqbbebeedddilve9Weeeviebeoweuec:q;Aekr;leDo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbdY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVblE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtboK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbrL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949Wbwl79IV9RbDq;t9tqlbzik9:evu8Jjjjjbcz9Rhbcbheincbhdcbhiinabcwfadfaicjuaead4ceGglE86bbaialfhiadcefgdcw9hmbkaec:q:yjjbfai86bbaecitc:q1jjbfab8Piw83ibaecefgecjd9hmbkk;h8JlHud97euo978Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnadcefal0mbcuhoaiRbbc:Ge9hmbavaialfgrad9Rad;8qbbcj;abad9UhoaicefhldnadTmbaoc;WFbGgocjdaocjd6EhwcbhDinaDae9pmeawaeaD9RaDawfae6Egqcsfgoc9WGgkci2hxakcethmaocl4cifcd4hPabaDad2fhscbhzdnincehHalhOcbhAdninaraO9RaP6miavcj;cbfaAak2fhCaOaPfhlcbhidnakc;ab6mbaral9Rc;Gb6mbcbhoinaCaofhidndndndndnaOaoco4fRbbgXciGPlbedibkaipxbbbbbbbbbbbbbbbbpklbxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklbalczfhlkdndndndndnaXcd4ciGPlbedibkaipxbbbbbbbbbbbbbbbbpklzxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklzalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklzalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklzalczfhlkdndndndndnaXcl4ciGPlbedibkaipxbbbbbbbbbbbbbbbbpklaxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklaalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklaalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklaalczfhlkdndndndndnaXco4Plbedibkaipxbbbbbbbbbbbbbbbbpkl8WxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibaXc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spkl8WalclfaYpQbfaXc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibaXc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spkl8WalcwfaYpQbfaXc:q:yjjbfRbbfhlxekaialpbbbpkl8Walczfhlkaoc;abfhiaocjefak0meaihoaral9Rc;Fb0mbkkdndnaiak9pmbaici4hoinaral9RcK6mdaCaifhXdndndndndnaOaico4fRbbaocoG4ciGPlbedibkaXpxbbbbbbbbbbbbbbbbpklbxikaXalpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaXalpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaXalpbbbpklbalczfhlkaocdfhoaiczfgiak6mbkkalTmbaAci6hHalhOaAcefgohAaoclSmdxekkcbhlaHceGmdkdnakTmbavcjdfazfhiavazfpbdbhYcbhXinaiavcj;cbfaXfgopblbgLcep9TaLpxeeeeeeeeeeeeeeeegQp9op9Hp9rgLaoakfpblbg8Acep9Ta8AaQp9op9Hp9rg8ApmbzeHdOiAlCvXoQrLgEaoamfpblbg3cep9Ta3aQp9op9Hp9rg3aoaxfpblbg5cep9Ta5aQp9op9Hp9rg5pmbzeHdOiAlCvXoQrLg8EpmbezHdiOAlvCXorQLgQaQpmbedibedibedibediaYp9UgYp9AdbbaiadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfgoaYaEa8EpmwDKYqk8AExm35Ps8E8FgQaQpmbedibedibedibedip9UgYp9AdbbaoadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfgoaYaLa8ApmwKDYq8AkEx3m5P8Es8FgLa3a5pmwKDYq8AkEx3m5P8Es8Fg8ApmbezHdiOAlvCXorQLgQaQpmbedibedibedibedip9UgYp9AdbbaoadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfgoaYaLa8ApmwDKYqk8AExm35Ps8E8FgQaQpmbedibedibedibedip9UgYp9AdbbaoadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfhiaXczfgXak6mbkkazclfgzad6mbkasavcjdfaqad2;8qbbavavcjdfaqcufad2fad;8qbbaqaDfhDc9:hoalmexikkc9:hoxekcbc99aral9Radcaadca0ESEhokavcj;kbf8Kjjjjbaokwbz:bjjjbk;uzeHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecje;8kbavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhodnaeTmbcmcsaDceSEhkcbhxcbhmcbhDcbhicbhlindnaoaq9nmbc9:hoxikdndnawRbbgrc;Ve0mbavc;abfalarcl4cu7fcsGcitfgPydlhsaPydbhzdnarcsGgPak9pmbavaiarcu7fcsGcdtfydbaxaPEhraPThPdndnadcd9hmbabaDcetfgHaz87ebaHcdfas87ebaHclfar87ebxekabaDcdtfgHazBdbaHclfasBdbaHcwfarBdbkaxaPfhxavc;abfalcitfgHarBdbaHasBdlavaicdtfarBdbavc;abfalcefcsGglcitfgHazBdbaHarBdlaiaPfhialcefhlxdkdndnaPcsSmbamaPfaPc987fcefhmxekaocefhrao8SbbgPcFeGhHdndnaPcu9mmbarhoxekaocvfhoaHcFbGhHcrhPdninar8SbbgOcFbGaPtaHVhHaOcu9kmearcefhraPcrfgPc8J9hmbxdkkarcefhokaHce4cbaHceG9R7amfhmkdndnadcd9hmbabaDcetfgraz87ebarcdfas87ebarclfam87ebxekabaDcdtfgrazBdbarclfasBdbarcwfamBdbkavc;abfalcitfgramBdbarasBdlavaicdtfamBdbavc;abfalcefcsGglcitfgrazBdbaramBdlaicefhialcefhlxekdnarcpe0mbaxcefgOavaiaqarcsGfRbbgPcl49RcsGcdtfydbaPcz6gHEhravaiaP9RcsGcdtfydbaOaHfgsaPcsGgOEhPaOThOdndnadcd9hmbabaDcetfgzax87ebazcdfar87ebazclfaP87ebxekabaDcdtfgzaxBdbazclfarBdbazcwfaPBdbkavaicdtfaxBdbavc;abfalcitfgzarBdbazaxBdlavaicefgicsGcdtfarBdbavc;abfalcefcsGcitfgzaPBdbazarBdlavaiaHfcsGgicdtfaPBdbavc;abfalcdfcsGglcitfgraxBdbaraPBdlalcefhlaiaOfhiasaOfhxxekaxcbaoRbbgzEgAarc;:eSgrfhsazcsGhCazcl4hXdndnazcs0mbascefhOxekashOavaiaX9RcsGcdtfydbhskdndnaCmbaOcefhxxekaOhxavaiaz9RcsGcdtfydbhOkdndnarTmbaocefhrxekaocdfhrao8SbegHcFeGhPdnaHcu9kmbaocofhAaPcFbGhPcrhodninar8SbbgHcFbGaotaPVhPaHcu9kmearcefhraocrfgoc8J9hmbkaAhrxekarcefhrkaPce4cbaPceG9R7amfgmhAkdndnaXcsSmbarhPxekarcefhPar8SbbgocFeGhHdnaocu9kmbarcvfhsaHcFbGhHcrhodninaP8SbbgrcFbGaotaHVhHarcu9kmeaPcefhPaocrfgoc8J9hmbkashPxekaPcefhPkaHce4cbaHceG9R7amfgmhskdndnaCcsSmbaPhoxekaPcefhoaP8SbbgrcFeGhHdnarcu9kmbaPcvfhOaHcFbGhHcrhrdninao8SbbgPcFbGartaHVhHaPcu9kmeaocefhoarcrfgrc8J9hmbkaOhoxekaocefhokaHce4cbaHceG9R7amfgmhOkdndnadcd9hmbabaDcetfgraA87ebarcdfas87ebarclfaO87ebxekabaDcdtfgraABdbarclfasBdbarcwfaOBdbkavc;abfalcitfgrasBdbaraABdlavaicdtfaABdbavc;abfalcefcsGcitfgraOBdbarasBdlavaicefgicsGcdtfasBdbavc;abfalcdfcsGcitfgraABdbaraOBdlavaiazcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhialcifhlkawcefhwalcsGhlaicsGhiaDcifgDae6mbkkcbc99aoaqSEhokavc;aef8Kjjjjbaok:llevu8Jjjjjbcz9Rhvc9:hodnaecvfal0mbcuhoaiRbbc;:eGc;qe9hmbav9cb83iwaicefhraialfc98fhwdnaeTmbdnadcdSmbcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcdtfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfglBdbaoalBdbaDcefgDae9hmbxdkkcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcetfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfgl87ebaoalBdbaDcefgDae9hmbkkcbc99arawSEhokaok:EPliuo97eue978Jjjjjbca9Rhidndnadcl9hmbdnaec98GglTmbcbhvabhdinadadpbbbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpkbbadczfhdavclfgval6mbkkalae9pmeaiaeciGgvcdtgdVcbczad9R;8kbaiabalcdtfglad;8qbbdnavTmbaiaipblbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpklbkalaiad;8qbbskdnaec98GgxTmbcbhvabhdinadczfglalpbbbgopxbbbbbbFFbbbbbbFFgkp9oadpbbbgDaopmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eaDaopmbediwDqkzHOAKY8AEgoczp:Sep;6egrp;Geaoczp:Reczp:Sep;6egwp;Gep;Kep;Legopxb;:FSb;:FSb;:FSb;:FSawaopxbbbbbbbbbbbbbbbbp:2egqawpxbbbjbbbjbbbjbbbjgmp9op9rp;Kegwawp;Meaoaop;Mearaqaramp9op9rp;Kegoaop;Mep;Kep;Kep;Jep;Negrp;Mepxbbn0bbn0bbn0bbn0gqp;Keczp:Reawarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9op9qgwaoarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogopmwDKYqk8AExm35Ps8E8Fp9qpkbbadaDakp9oawaopmbezHdiOAlvCXorQLp9qpkbbadcafhdavclfgvax6mbkkaxae9pmbaiaeciGgvcitgdfcbcaad9R;8kbaiabaxcitfglad;8qbbdnavTmbaiaipblzgopxbbbbbbFFbbbbbbFFgkp9oaipblbgDaopmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eaDaopmbediwDqkzHOAKY8AEgoczp:Sep;6egrp;Geaoczp:Reczp:Sep;6egwp;Gep;Kep;Legopxb;:FSb;:FSb;:FSb;:FSawaopxbbbbbbbbbbbbbbbbp:2egqawpxbbbjbbbjbbbjbbbjgmp9op9rp;Kegwawp;Meaoaop;Mearaqaramp9op9rp;Kegoaop;Mep;Kep;Kep;Jep;Negrp;Mepxbbn0bbn0bbn0bbn0gqp;Keczp:Reawarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9op9qgwaoarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogopmwDKYqk8AExm35Ps8E8Fp9qpklzaiaDakp9oawaopmbezHdiOAlvCXorQLp9qpklbkalaiad;8qbbkk;4wllue97euv978Jjjjjbc8W9Rhidnaec98GglTmbcbhvabhoinaiaopbbbgraoczfgwpbbbgDpmlvorxmPsCXQL358E8Fgqczp:Segkclp:RepklbaopxbbjZbbjZbbjZbbjZpx;Zl81Z;Zl81Z;Zl81Z;Zl81Zakpxibbbibbbibbbibbbp9qp;6ep;NegkaraDpmbediwDqkzHOAKY8AEgrczp:Reczp:Sep;6ep;MegDaDp;Meakarczp:Sep;6ep;Megxaxp;Meakaqczp:Reczp:Sep;6ep;Megqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jepxb;:FSb;:FSb;:FSb;:FSgkp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbgmp9oaxakp;Mearp;Keczp:Rep9qgxaqakp;Mearp;Keczp:ReaDakp;Mearp;Keamp9op9qgkpmbezHdiOAlvCXorQLgrp5baipblbpEb:T:j83ibaocwfarp5eaipblbpEe:T:j83ibawaxakpmwDKYqk8AExm35Ps8E8Fgkp5baipblbpEd:T:j83ibaocKfakp5eaipblbpEi:T:j83ibaocafhoavclfgval6mbkkdnalae9pmbaiaeciGgvcitgofcbcaao9R;8kbaiabalcitfgwao;8qbbdnavTmbaiaipblbgraipblzgDpmlvorxmPsCXQL358E8Fgqczp:Segkclp:RepklaaipxbbjZbbjZbbjZbbjZpx;Zl81Z;Zl81Z;Zl81Z;Zl81Zakpxibbbibbbibbbibbbp9qp;6ep;NegkaraDpmbediwDqkzHOAKY8AEgrczp:Reczp:Sep;6ep;MegDaDp;Meakarczp:Sep;6ep;Megxaxp;Meakaqczp:Reczp:Sep;6ep;Megqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jepxb;:FSb;:FSb;:FSb;:FSgkp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbgmp9oaxakp;Mearp;Keczp:Rep9qgxaqakp;Mearp;Keczp:ReaDakp;Mearp;Keamp9op9qgkpmbezHdiOAlvCXorQLgrp5baipblapEb:T:j83ibaiarp5eaipblapEe:T:j83iwaiaxakpmwDKYqk8AExm35Ps8E8Fgkp5baipblapEd:T:j83izaiakp5eaipblapEi:T:j83iKkawaiao;8qbbkk:Pddiue978Jjjjjbc;ab9Rhidnadcd4ae2glc98GgvTmbcbhdabheinaeaepbbbgocwp:Recwp:Sep;6eaocep:SepxbbjZbbjZbbjZbbjZp:UepxbbjFbbjFbbjFbbjFp9op;Mepkbbaeczfheadclfgdav6mbkkdnaval9pmbaialciGgdcdtgeVcbc;abae9R;8kbaiabavcdtfgvae;8qbbdnadTmbaiaipblbgocwp:Recwp:Sep;6eaocep:SepxbbjZbbjZbbjZbbjZp:UepxbbjFbbjFbbjFbbjFp9op;Mepklbkavaiae;8qbbkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikkkebcjwklz9Tbb", n = new Uint8Array([
+ 0,
+ 97,
+ 115,
+ 109,
+ 1,
+ 0,
+ 0,
+ 0,
+ 1,
+ 4,
+ 1,
+ 96,
+ 0,
+ 0,
+ 3,
+ 3,
+ 2,
+ 0,
+ 0,
+ 5,
+ 3,
+ 1,
+ 0,
+ 1,
+ 12,
+ 1,
+ 0,
+ 10,
+ 22,
+ 2,
+ 12,
+ 0,
+ 65,
+ 0,
+ 65,
+ 0,
+ 65,
+ 0,
+ 252,
+ 10,
+ 0,
+ 0,
+ 11,
+ 7,
+ 0,
+ 65,
+ 0,
+ 253,
+ 15,
+ 26,
+ 11
+ ]), r = new Uint8Array([
+ 32,
+ 0,
+ 65,
+ 2,
+ 1,
+ 106,
+ 34,
+ 33,
+ 3,
+ 128,
+ 11,
+ 4,
+ 13,
+ 64,
+ 6,
+ 253,
+ 10,
+ 7,
+ 15,
+ 116,
+ 127,
+ 5,
+ 8,
+ 12,
+ 40,
+ 16,
+ 19,
+ 54,
+ 20,
+ 9,
+ 27,
+ 255,
+ 113,
+ 17,
+ 42,
+ 67,
+ 24,
+ 23,
+ 146,
+ 148,
+ 18,
+ 14,
+ 22,
+ 45,
+ 70,
+ 69,
+ 56,
+ 114,
+ 101,
+ 21,
+ 25,
+ 63,
+ 75,
+ 136,
+ 108,
+ 28,
+ 118,
+ 29,
+ 73,
+ 115
+ ]);
+ if (typeof WebAssembly != "object") return { supported: !1 };
+ var i = WebAssembly.validate(n) ? t : e, a, o = WebAssembly.instantiate(s(i), {}).then(function(e) {
+ a = e.instance, a.exports.__wasm_call_ctors();
+ });
+ function s(e) {
+ for (var t = new Uint8Array(e.length), n = 0; n < e.length; ++n) {
+ var i = e.charCodeAt(n);
+ t[n] = i > 96 ? i - 97 : i > 64 ? i - 39 : i + 4;
+ }
+ for (var a = 0, n = 0; n < e.length; ++n) t[a++] = t[n] < 60 ? r[t[n]] : (t[n] - 60) * 64 + t[++n];
+ return t.buffer.slice(0, a);
+ }
+ function c(e, t, n, r, i, o) {
+ var s = a.exports.sbrk, c = n + 3 & -4, l = s(c * r), u = s(i.length), d = new Uint8Array(a.exports.memory.buffer);
+ d.set(i, u);
+ var f = e(l, n, r, u, i.length);
+ if (f == 0 && o && o(l, c, r), t.set(d.subarray(l, l + n * r)), s(l - s(0)), f != 0) throw Error("Malformed buffer data: " + f);
+ }
+ var l = {
+ NONE: "",
+ OCTAHEDRAL: "meshopt_decodeFilterOct",
+ QUATERNION: "meshopt_decodeFilterQuat",
+ EXPONENTIAL: "meshopt_decodeFilterExp"
+ }, u = {
+ ATTRIBUTES: "meshopt_decodeVertexBuffer",
+ TRIANGLES: "meshopt_decodeIndexBuffer",
+ INDICES: "meshopt_decodeIndexSequence"
+ }, d = [], f = 0;
+ function p(e) {
+ var t = {
+ object: new Worker(e),
+ pending: 0,
+ requests: {}
+ };
+ return t.object.onmessage = function(e) {
+ var n = e.data;
+ t.pending -= n.count, t.requests[n.id][n.action](n.value), delete t.requests[n.id];
+ }, t;
+ }
+ function m(e) {
+ for (var t = "var instance; var ready = WebAssembly.instantiate(new Uint8Array([" + new Uint8Array(s(i)) + "]), {}).then(function(result) { instance = result.instance; instance.exports.__wasm_call_ctors(); });self.onmessage = workerProcess;" + c.toString() + g.toString(), n = new Blob([t], { type: "text/javascript" }), r = URL.createObjectURL(n), a = 0; a < e; ++a) d[a] = p(r);
+ URL.revokeObjectURL(r);
+ }
+ function h(e, t, n, r, i) {
+ for (var a = d[0], o = 1; o < d.length; ++o) d[o].pending < a.pending && (a = d[o]);
+ return new Promise(function(o, s) {
+ var c = new Uint8Array(n), l = f++;
+ a.pending += e, a.requests[l] = {
+ resolve: o,
+ reject: s
+ }, a.object.postMessage({
+ id: l,
+ count: e,
+ size: t,
+ source: c,
+ mode: r,
+ filter: i
+ }, [c.buffer]);
+ });
+ }
+ function g(e) {
+ o.then(function() {
+ var t = e.data;
+ try {
+ var n = new Uint8Array(t.count * t.size);
+ c(a.exports[t.mode], n, t.count, t.size, t.source, a.exports[t.filter]), self.postMessage({
+ id: t.id,
+ count: t.count,
+ action: "resolve",
+ value: n
+ }, [n.buffer]);
+ } catch (e) {
+ self.postMessage({
+ id: t.id,
+ count: t.count,
+ action: "reject",
+ value: e
+ });
+ }
+ });
+ }
+ return {
+ ready: o,
+ supported: !0,
+ useWorkers: function(e) {
+ m(e);
+ },
+ decodeVertexBuffer: function(e, t, n, r, i) {
+ c(a.exports.meshopt_decodeVertexBuffer, e, t, n, r, a.exports[l[i]]);
+ },
+ decodeIndexBuffer: function(e, t, n, r) {
+ c(a.exports.meshopt_decodeIndexBuffer, e, t, n, r);
+ },
+ decodeIndexSequence: function(e, t, n, r) {
+ c(a.exports.meshopt_decodeIndexSequence, e, t, n, r);
+ },
+ decodeGltfBuffer: function(e, t, n, r, i, o) {
+ c(a.exports[u[i]], e, t, n, r, a.exports[l[o]]);
+ },
+ decodeGltfBufferAsync: function(e, t, n, r, i) {
+ return d.length > 0 ? h(e, t, n, u[r], l[i]) : o.then(function() {
+ var o = new Uint8Array(e * t);
+ return c(a.exports[u[r]], o, e, t, n, a.exports[l[i]]), o;
+ });
+ }
+ };
+})(), fd = { type: "change" }, pd = { type: "start" }, md = { type: "end" }, hd = new kn(), gd = new ia(), _d = Math.cos(70 * wt.DEG2RAD), vd = new R(), yd = 2 * Math.PI, bd = {
+ NONE: -1,
+ ROTATE: 0,
+ DOLLY: 1,
+ PAN: 2,
+ TOUCH_ROTATE: 3,
+ TOUCH_PAN: 4,
+ TOUCH_DOLLY_PAN: 5,
+ TOUCH_DOLLY_ROTATE: 6
+}, xd = 1e-6, Sd = class extends as {
+ constructor(e, t = null) {
+ super(e, t), this.state = bd.NONE, this.target = new R(), this.cursor = new R(), this.minDistance = 0, this.maxDistance = Infinity, this.minZoom = 0, this.maxZoom = Infinity, this.minTargetRadius = 0, this.maxTargetRadius = Infinity, this.minPolarAngle = 0, this.maxPolarAngle = Math.PI, this.minAzimuthAngle = -Infinity, this.maxAzimuthAngle = Infinity, this.enableDamping = !1, this.dampingFactor = .05, this.enableZoom = !0, this.zoomSpeed = 1, this.enableRotate = !0, this.rotateSpeed = 1, this.keyRotateSpeed = 1, this.enablePan = !0, this.panSpeed = 1, this.screenSpacePanning = !0, this.keyPanSpeed = 7, this.zoomToCursor = !1, this.autoRotate = !1, this.autoRotateSpeed = 2, this.keys = {
+ LEFT: "ArrowLeft",
+ UP: "ArrowUp",
+ RIGHT: "ArrowRight",
+ BOTTOM: "ArrowDown"
+ }, this.mouseButtons = {
+ LEFT: n.ROTATE,
+ MIDDLE: n.DOLLY,
+ RIGHT: n.PAN
+ }, this.touches = {
+ ONE: r.ROTATE,
+ TWO: r.DOLLY_PAN
+ }, this.target0 = this.target.clone(), this.position0 = this.object.position.clone(), this.zoom0 = this.object.zoom, this._domElementKeyEvents = null, this._lastPosition = new R(), this._lastQuaternion = new $t(), this._lastTargetPosition = new R(), this._quat = new $t().setFromUnitVectors(e.up, new R(0, 1, 0)), this._quatInverse = this._quat.clone().invert(), this._spherical = new Zo(), this._sphericalDelta = new Zo(), this._scale = 1, this._panOffset = new R(), this._rotateStart = new L(), this._rotateEnd = new L(), this._rotateDelta = new L(), this._panStart = new L(), this._panEnd = new L(), this._panDelta = new L(), this._dollyStart = new L(), this._dollyEnd = new L(), this._dollyDelta = new L(), this._dollyDirection = new R(), this._mouse = new L(), this._performCursorZoom = !1, this._pointers = [], this._pointerPositions = {}, this._controlActive = !1, this._onPointerMove = wd.bind(this), this._onPointerDown = Cd.bind(this), this._onPointerUp = Td.bind(this), this._onContextMenu = Md.bind(this), this._onMouseWheel = Od.bind(this), this._onKeyDown = kd.bind(this), this._onTouchStart = Ad.bind(this), this._onTouchMove = jd.bind(this), this._onMouseDown = Ed.bind(this), this._onMouseMove = Dd.bind(this), this._interceptControlDown = Nd.bind(this), this._interceptControlUp = Pd.bind(this), this.domElement !== null && this.connect(this.domElement), this.update();
+ }
+ connect(e) {
+ super.connect(e), this.domElement.addEventListener("pointerdown", this._onPointerDown), this.domElement.addEventListener("pointercancel", this._onPointerUp), this.domElement.addEventListener("contextmenu", this._onContextMenu), this.domElement.addEventListener("wheel", this._onMouseWheel, { passive: !1 }), this.domElement.getRootNode().addEventListener("keydown", this._interceptControlDown, {
+ passive: !0,
+ capture: !0
+ }), this.domElement.style.touchAction = "none";
+ }
+ disconnect() {
+ this.domElement.removeEventListener("pointerdown", this._onPointerDown), this.domElement.removeEventListener("pointermove", this._onPointerMove), this.domElement.removeEventListener("pointerup", this._onPointerUp), this.domElement.removeEventListener("pointercancel", this._onPointerUp), this.domElement.removeEventListener("wheel", this._onMouseWheel), this.domElement.removeEventListener("contextmenu", this._onContextMenu), this.stopListenToKeyEvents(), this.domElement.getRootNode().removeEventListener("keydown", this._interceptControlDown, { capture: !0 }), this.domElement.style.touchAction = "auto";
+ }
+ dispose() {
+ this.disconnect();
+ }
+ getPolarAngle() {
+ return this._spherical.phi;
+ }
+ getAzimuthalAngle() {
+ return this._spherical.theta;
+ }
+ getDistance() {
+ return this.object.position.distanceTo(this.target);
+ }
+ listenToKeyEvents(e) {
+ e.addEventListener("keydown", this._onKeyDown), this._domElementKeyEvents = e;
+ }
+ stopListenToKeyEvents() {
+ this._domElementKeyEvents !== null && (this._domElementKeyEvents.removeEventListener("keydown", this._onKeyDown), this._domElementKeyEvents = null);
+ }
+ saveState() {
+ this.target0.copy(this.target), this.position0.copy(this.object.position), this.zoom0 = this.object.zoom;
+ }
+ reset() {
+ this.target.copy(this.target0), this.object.position.copy(this.position0), this.object.zoom = this.zoom0, this.object.updateProjectionMatrix(), this.dispatchEvent(fd), this.update(), this.state = bd.NONE;
+ }
+ update(e = null) {
+ let t = this.object.position;
+ vd.copy(t).sub(this.target), vd.applyQuaternion(this._quat), this._spherical.setFromVector3(vd), this.autoRotate && this.state === bd.NONE && this._rotateLeft(this._getAutoRotationAngle(e)), this.enableDamping ? (this._spherical.theta += this._sphericalDelta.theta * this.dampingFactor, this._spherical.phi += this._sphericalDelta.phi * this.dampingFactor) : (this._spherical.theta += this._sphericalDelta.theta, this._spherical.phi += this._sphericalDelta.phi);
+ let n = this.minAzimuthAngle, r = this.maxAzimuthAngle;
+ isFinite(n) && isFinite(r) && (n < -Math.PI ? n += yd : n > Math.PI && (n -= yd), r < -Math.PI ? r += yd : r > Math.PI && (r -= yd), n <= r ? this._spherical.theta = Math.max(n, Math.min(r, this._spherical.theta)) : this._spherical.theta = this._spherical.theta > (n + r) / 2 ? Math.max(n, this._spherical.theta) : Math.min(r, this._spherical.theta)), this._spherical.phi = Math.max(this.minPolarAngle, Math.min(this.maxPolarAngle, this._spherical.phi)), this._spherical.makeSafe(), this.enableDamping === !0 ? this.target.addScaledVector(this._panOffset, this.dampingFactor) : this.target.add(this._panOffset), this.target.sub(this.cursor), this.target.clampLength(this.minTargetRadius, this.maxTargetRadius), this.target.add(this.cursor);
+ let i = !1;
+ if (this.zoomToCursor && this._performCursorZoom || this.object.isOrthographicCamera) this._spherical.radius = this._clampDistance(this._spherical.radius);
+ else {
+ let e = this._spherical.radius;
+ this._spherical.radius = this._clampDistance(this._spherical.radius * this._scale), i = e != this._spherical.radius;
+ }
+ if (vd.setFromSpherical(this._spherical), vd.applyQuaternion(this._quatInverse), t.copy(this.target).add(vd), this.object.lookAt(this.target), this.enableDamping === !0 ? (this._sphericalDelta.theta *= 1 - this.dampingFactor, this._sphericalDelta.phi *= 1 - this.dampingFactor, this._panOffset.multiplyScalar(1 - this.dampingFactor)) : (this._sphericalDelta.set(0, 0, 0), this._panOffset.set(0, 0, 0)), this.zoomToCursor && this._performCursorZoom) {
+ let e = null;
+ if (this.object.isPerspectiveCamera) {
+ let t = vd.length();
+ e = this._clampDistance(t * this._scale);
+ let n = t - e;
+ this.object.position.addScaledVector(this._dollyDirection, n), this.object.updateMatrixWorld(), i = !!n;
+ } else if (this.object.isOrthographicCamera) {
+ let t = new R(this._mouse.x, this._mouse.y, 0);
+ t.unproject(this.object);
+ let n = this.object.zoom;
+ this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom / this._scale)), this.object.updateProjectionMatrix(), i = n !== this.object.zoom;
+ let r = new R(this._mouse.x, this._mouse.y, 0);
+ r.unproject(this.object), this.object.position.sub(r).add(t), this.object.updateMatrixWorld(), e = vd.length();
+ } else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."), this.zoomToCursor = !1;
+ e !== null && (this.screenSpacePanning ? this.target.set(0, 0, -1).transformDirection(this.object.matrix).multiplyScalar(e).add(this.object.position) : (hd.origin.copy(this.object.position), hd.direction.set(0, 0, -1).transformDirection(this.object.matrix), Math.abs(this.object.up.dot(hd.direction)) < _d ? this.object.lookAt(this.target) : (gd.setFromNormalAndCoplanarPoint(this.object.up, this.target), hd.intersectPlane(gd, this.target))));
+ } else if (this.object.isOrthographicCamera) {
+ let e = this.object.zoom;
+ this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom / this._scale)), e !== this.object.zoom && (this.object.updateProjectionMatrix(), i = !0);
+ }
+ return this._scale = 1, this._performCursorZoom = !1, i || this._lastPosition.distanceToSquared(this.object.position) > xd || 8 * (1 - this._lastQuaternion.dot(this.object.quaternion)) > xd || this._lastTargetPosition.distanceToSquared(this.target) > xd ? (this.dispatchEvent(fd), this._lastPosition.copy(this.object.position), this._lastQuaternion.copy(this.object.quaternion), this._lastTargetPosition.copy(this.target), !0) : !1;
+ }
+ _getAutoRotationAngle(e) {
+ return e === null ? yd / 60 / 60 * this.autoRotateSpeed : yd / 60 * this.autoRotateSpeed * e;
+ }
+ _getZoomScale(e) {
+ let t = Math.abs(e * .01);
+ return .95 ** (this.zoomSpeed * t);
+ }
+ _rotateLeft(e) {
+ this._sphericalDelta.theta -= e;
+ }
+ _rotateUp(e) {
+ this._sphericalDelta.phi -= e;
+ }
+ _panLeft(e, t) {
+ vd.setFromMatrixColumn(t, 0), vd.multiplyScalar(-e), this._panOffset.add(vd);
+ }
+ _panUp(e, t) {
+ this.screenSpacePanning === !0 ? vd.setFromMatrixColumn(t, 1) : (vd.setFromMatrixColumn(t, 0), vd.crossVectors(this.object.up, vd)), vd.multiplyScalar(e), this._panOffset.add(vd);
+ }
+ _pan(e, t) {
+ let n = this.domElement;
+ if (this.object.isPerspectiveCamera) {
+ let r = this.object.position;
+ vd.copy(r).sub(this.target);
+ let i = vd.length();
+ i *= Math.tan(this.object.fov / 2 * Math.PI / 180), this._panLeft(2 * e * i / n.clientHeight, this.object.matrix), this._panUp(2 * t * i / n.clientHeight, this.object.matrix);
+ } else this.object.isOrthographicCamera ? (this._panLeft(e * (this.object.right - this.object.left) / this.object.zoom / n.clientWidth, this.object.matrix), this._panUp(t * (this.object.top - this.object.bottom) / this.object.zoom / n.clientHeight, this.object.matrix)) : (console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."), this.enablePan = !1);
+ }
+ _dollyOut(e) {
+ this.object.isPerspectiveCamera || this.object.isOrthographicCamera ? this._scale /= e : (console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."), this.enableZoom = !1);
+ }
+ _dollyIn(e) {
+ this.object.isPerspectiveCamera || this.object.isOrthographicCamera ? this._scale *= e : (console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."), this.enableZoom = !1);
+ }
+ _updateZoomParameters(e, t) {
+ if (!this.zoomToCursor) return;
+ this._performCursorZoom = !0;
+ let n = this.domElement.getBoundingClientRect(), r = e - n.left, i = t - n.top, a = n.width, o = n.height;
+ this._mouse.x = r / a * 2 - 1, this._mouse.y = -(i / o) * 2 + 1, this._dollyDirection.set(this._mouse.x, this._mouse.y, 1).unproject(this.object).sub(this.object.position).normalize();
+ }
+ _clampDistance(e) {
+ return Math.max(this.minDistance, Math.min(this.maxDistance, e));
+ }
+ _handleMouseDownRotate(e) {
+ this._rotateStart.set(e.clientX, e.clientY);
+ }
+ _handleMouseDownDolly(e) {
+ this._updateZoomParameters(e.clientX, e.clientX), this._dollyStart.set(e.clientX, e.clientY);
+ }
+ _handleMouseDownPan(e) {
+ this._panStart.set(e.clientX, e.clientY);
+ }
+ _handleMouseMoveRotate(e) {
+ this._rotateEnd.set(e.clientX, e.clientY), this._rotateDelta.subVectors(this._rotateEnd, this._rotateStart).multiplyScalar(this.rotateSpeed);
+ let t = this.domElement;
+ this._rotateLeft(yd * this._rotateDelta.x / t.clientHeight), this._rotateUp(yd * this._rotateDelta.y / t.clientHeight), this._rotateStart.copy(this._rotateEnd), this.update();
+ }
+ _handleMouseMoveDolly(e) {
+ this._dollyEnd.set(e.clientX, e.clientY), this._dollyDelta.subVectors(this._dollyEnd, this._dollyStart), this._dollyDelta.y > 0 ? this._dollyOut(this._getZoomScale(this._dollyDelta.y)) : this._dollyDelta.y < 0 && this._dollyIn(this._getZoomScale(this._dollyDelta.y)), this._dollyStart.copy(this._dollyEnd), this.update();
+ }
+ _handleMouseMovePan(e) {
+ this._panEnd.set(e.clientX, e.clientY), this._panDelta.subVectors(this._panEnd, this._panStart).multiplyScalar(this.panSpeed), this._pan(this._panDelta.x, this._panDelta.y), this._panStart.copy(this._panEnd), this.update();
+ }
+ _handleMouseWheel(e) {
+ this._updateZoomParameters(e.clientX, e.clientY), e.deltaY < 0 ? this._dollyIn(this._getZoomScale(e.deltaY)) : e.deltaY > 0 && this._dollyOut(this._getZoomScale(e.deltaY)), this.update();
+ }
+ _handleKeyDown(e) {
+ let t = !1;
+ switch (e.code) {
+ case this.keys.UP:
+ e.ctrlKey || e.metaKey || e.shiftKey ? this.enableRotate && this._rotateUp(yd * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(0, this.keyPanSpeed), t = !0;
+ break;
+ case this.keys.BOTTOM:
+ e.ctrlKey || e.metaKey || e.shiftKey ? this.enableRotate && this._rotateUp(-yd * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(0, -this.keyPanSpeed), t = !0;
+ break;
+ case this.keys.LEFT:
+ e.ctrlKey || e.metaKey || e.shiftKey ? this.enableRotate && this._rotateLeft(yd * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(this.keyPanSpeed, 0), t = !0;
+ break;
+ case this.keys.RIGHT:
+ e.ctrlKey || e.metaKey || e.shiftKey ? this.enableRotate && this._rotateLeft(-yd * this.keyRotateSpeed / this.domElement.clientHeight) : this.enablePan && this._pan(-this.keyPanSpeed, 0), t = !0;
+ break;
+ }
+ t && (e.preventDefault(), this.update());
+ }
+ _handleTouchStartRotate(e) {
+ if (this._pointers.length === 1) this._rotateStart.set(e.pageX, e.pageY);
+ else {
+ let t = this._getSecondPointerPosition(e), n = .5 * (e.pageX + t.x), r = .5 * (e.pageY + t.y);
+ this._rotateStart.set(n, r);
+ }
+ }
+ _handleTouchStartPan(e) {
+ if (this._pointers.length === 1) this._panStart.set(e.pageX, e.pageY);
+ else {
+ let t = this._getSecondPointerPosition(e), n = .5 * (e.pageX + t.x), r = .5 * (e.pageY + t.y);
+ this._panStart.set(n, r);
+ }
+ }
+ _handleTouchStartDolly(e) {
+ let t = this._getSecondPointerPosition(e), n = e.pageX - t.x, r = e.pageY - t.y, i = Math.sqrt(n * n + r * r);
+ this._dollyStart.set(0, i);
+ }
+ _handleTouchStartDollyPan(e) {
+ this.enableZoom && this._handleTouchStartDolly(e), this.enablePan && this._handleTouchStartPan(e);
+ }
+ _handleTouchStartDollyRotate(e) {
+ this.enableZoom && this._handleTouchStartDolly(e), this.enableRotate && this._handleTouchStartRotate(e);
+ }
+ _handleTouchMoveRotate(e) {
+ if (this._pointers.length == 1) this._rotateEnd.set(e.pageX, e.pageY);
+ else {
+ let t = this._getSecondPointerPosition(e), n = .5 * (e.pageX + t.x), r = .5 * (e.pageY + t.y);
+ this._rotateEnd.set(n, r);
+ }
+ this._rotateDelta.subVectors(this._rotateEnd, this._rotateStart).multiplyScalar(this.rotateSpeed);
+ let t = this.domElement;
+ this._rotateLeft(yd * this._rotateDelta.x / t.clientHeight), this._rotateUp(yd * this._rotateDelta.y / t.clientHeight), this._rotateStart.copy(this._rotateEnd);
+ }
+ _handleTouchMovePan(e) {
+ if (this._pointers.length === 1) this._panEnd.set(e.pageX, e.pageY);
+ else {
+ let t = this._getSecondPointerPosition(e), n = .5 * (e.pageX + t.x), r = .5 * (e.pageY + t.y);
+ this._panEnd.set(n, r);
+ }
+ this._panDelta.subVectors(this._panEnd, this._panStart).multiplyScalar(this.panSpeed), this._pan(this._panDelta.x, this._panDelta.y), this._panStart.copy(this._panEnd);
+ }
+ _handleTouchMoveDolly(e) {
+ let t = this._getSecondPointerPosition(e), n = e.pageX - t.x, r = e.pageY - t.y, i = Math.sqrt(n * n + r * r);
+ this._dollyEnd.set(0, i), this._dollyDelta.set(0, (this._dollyEnd.y / this._dollyStart.y) ** +this.zoomSpeed), this._dollyOut(this._dollyDelta.y), this._dollyStart.copy(this._dollyEnd);
+ let a = (e.pageX + t.x) * .5, o = (e.pageY + t.y) * .5;
+ this._updateZoomParameters(a, o);
+ }
+ _handleTouchMoveDollyPan(e) {
+ this.enableZoom && this._handleTouchMoveDolly(e), this.enablePan && this._handleTouchMovePan(e);
+ }
+ _handleTouchMoveDollyRotate(e) {
+ this.enableZoom && this._handleTouchMoveDolly(e), this.enableRotate && this._handleTouchMoveRotate(e);
+ }
+ _addPointer(e) {
+ this._pointers.push(e.pointerId);
+ }
+ _removePointer(e) {
+ delete this._pointerPositions[e.pointerId];
+ for (let t = 0; t < this._pointers.length; t++) if (this._pointers[t] == e.pointerId) {
+ this._pointers.splice(t, 1);
+ return;
+ }
+ }
+ _isTrackingPointer(e) {
+ for (let t = 0; t < this._pointers.length; t++) if (this._pointers[t] == e.pointerId) return !0;
+ return !1;
+ }
+ _trackPointer(e) {
+ let t = this._pointerPositions[e.pointerId];
+ t === void 0 && (t = new L(), this._pointerPositions[e.pointerId] = t), t.set(e.pageX, e.pageY);
+ }
+ _getSecondPointerPosition(e) {
+ let t = e.pointerId === this._pointers[0] ? this._pointers[1] : this._pointers[0];
+ return this._pointerPositions[t];
+ }
+ _customWheelEvent(e) {
+ let t = e.deltaMode, n = {
+ clientX: e.clientX,
+ clientY: e.clientY,
+ deltaY: e.deltaY
+ };
+ switch (t) {
+ case 1:
+ n.deltaY *= 16;
+ break;
+ case 2:
+ n.deltaY *= 100;
+ break;
+ }
+ return e.ctrlKey && !this._controlActive && (n.deltaY *= 10), n;
+ }
+};
+function Cd(e) {
+ this.enabled !== !1 && (this._pointers.length === 0 && (this.domElement.setPointerCapture(e.pointerId), this.domElement.addEventListener("pointermove", this._onPointerMove), this.domElement.addEventListener("pointerup", this._onPointerUp)), !this._isTrackingPointer(e) && (this._addPointer(e), e.pointerType === "touch" ? this._onTouchStart(e) : this._onMouseDown(e)));
+}
+function wd(e) {
+ this.enabled !== !1 && (e.pointerType === "touch" ? this._onTouchMove(e) : this._onMouseMove(e));
+}
+function Td(e) {
+ switch (this._removePointer(e), this._pointers.length) {
+ case 0:
+ this.domElement.releasePointerCapture(e.pointerId), this.domElement.removeEventListener("pointermove", this._onPointerMove), this.domElement.removeEventListener("pointerup", this._onPointerUp), this.dispatchEvent(md), this.state = bd.NONE;
+ break;
+ case 1:
+ let t = this._pointers[0], n = this._pointerPositions[t];
+ this._onTouchStart({
+ pointerId: t,
+ pageX: n.x,
+ pageY: n.y
+ });
+ break;
+ }
+}
+function Ed(e) {
+ let t;
+ switch (e.button) {
+ case 0:
+ t = this.mouseButtons.LEFT;
+ break;
+ case 1:
+ t = this.mouseButtons.MIDDLE;
+ break;
+ case 2:
+ t = this.mouseButtons.RIGHT;
+ break;
+ default: t = -1;
+ }
+ switch (t) {
+ case n.DOLLY:
+ if (this.enableZoom === !1) return;
+ this._handleMouseDownDolly(e), this.state = bd.DOLLY;
+ break;
+ case n.ROTATE:
+ if (e.ctrlKey || e.metaKey || e.shiftKey) {
+ if (this.enablePan === !1) return;
+ this._handleMouseDownPan(e), this.state = bd.PAN;
+ } else {
+ if (this.enableRotate === !1) return;
+ this._handleMouseDownRotate(e), this.state = bd.ROTATE;
+ }
+ break;
+ case n.PAN:
+ if (e.ctrlKey || e.metaKey || e.shiftKey) {
+ if (this.enableRotate === !1) return;
+ this._handleMouseDownRotate(e), this.state = bd.ROTATE;
+ } else {
+ if (this.enablePan === !1) return;
+ this._handleMouseDownPan(e), this.state = bd.PAN;
+ }
+ break;
+ default: this.state = bd.NONE;
+ }
+ this.state !== bd.NONE && this.dispatchEvent(pd);
+}
+function Dd(e) {
+ switch (this.state) {
+ case bd.ROTATE:
+ if (this.enableRotate === !1) return;
+ this._handleMouseMoveRotate(e);
+ break;
+ case bd.DOLLY:
+ if (this.enableZoom === !1) return;
+ this._handleMouseMoveDolly(e);
+ break;
+ case bd.PAN:
+ if (this.enablePan === !1) return;
+ this._handleMouseMovePan(e);
+ break;
+ }
+}
+function Od(e) {
+ this.enabled === !1 || this.enableZoom === !1 || this.state !== bd.NONE || (e.preventDefault(), this.dispatchEvent(pd), this._handleMouseWheel(this._customWheelEvent(e)), this.dispatchEvent(md));
+}
+function kd(e) {
+ this.enabled !== !1 && this._handleKeyDown(e);
+}
+function Ad(e) {
+ switch (this._trackPointer(e), this._pointers.length) {
+ case 1:
+ switch (this.touches.ONE) {
+ case r.ROTATE:
+ if (this.enableRotate === !1) return;
+ this._handleTouchStartRotate(e), this.state = bd.TOUCH_ROTATE;
+ break;
+ case r.PAN:
+ if (this.enablePan === !1) return;
+ this._handleTouchStartPan(e), this.state = bd.TOUCH_PAN;
+ break;
+ default: this.state = bd.NONE;
+ }
+ break;
+ case 2:
+ switch (this.touches.TWO) {
+ case r.DOLLY_PAN:
+ if (this.enableZoom === !1 && this.enablePan === !1) return;
+ this._handleTouchStartDollyPan(e), this.state = bd.TOUCH_DOLLY_PAN;
+ break;
+ case r.DOLLY_ROTATE:
+ if (this.enableZoom === !1 && this.enableRotate === !1) return;
+ this._handleTouchStartDollyRotate(e), this.state = bd.TOUCH_DOLLY_ROTATE;
+ break;
+ default: this.state = bd.NONE;
+ }
+ break;
+ default: this.state = bd.NONE;
+ }
+ this.state !== bd.NONE && this.dispatchEvent(pd);
+}
+function jd(e) {
+ switch (this._trackPointer(e), this.state) {
+ case bd.TOUCH_ROTATE:
+ if (this.enableRotate === !1) return;
+ this._handleTouchMoveRotate(e), this.update();
+ break;
+ case bd.TOUCH_PAN:
+ if (this.enablePan === !1) return;
+ this._handleTouchMovePan(e), this.update();
+ break;
+ case bd.TOUCH_DOLLY_PAN:
+ if (this.enableZoom === !1 && this.enablePan === !1) return;
+ this._handleTouchMoveDollyPan(e), this.update();
+ break;
+ case bd.TOUCH_DOLLY_ROTATE:
+ if (this.enableZoom === !1 && this.enableRotate === !1) return;
+ this._handleTouchMoveDollyRotate(e), this.update();
+ break;
+ default: this.state = bd.NONE;
+ }
+}
+function Md(e) {
+ this.enabled !== !1 && e.preventDefault();
+}
+function Nd(e) {
+ e.key === "Control" && (this._controlActive = !0, this.domElement.getRootNode().addEventListener("keyup", this._interceptControlUp, {
+ passive: !0,
+ capture: !0
+ }));
+}
+function Pd(e) {
+ e.key === "Control" && (this._controlActive = !1, this.domElement.getRootNode().removeEventListener("keyup", this._interceptControlUp, {
+ passive: !0,
+ capture: !0
+ }));
+}
+//#endregion
+//#region node_modules/three/examples/jsm/environments/RoomEnvironment.js
+var Fd = class extends Di {
+ constructor() {
+ super();
+ let e = new ai();
+ e.deleteAttribute("uv");
+ let t = new Pa({ side: 1 }), n = new Pa(), r = new Do(16777215, 900, 28, 2);
+ r.position.set(.418, 16.199, .3), this.add(r);
+ let i = new ni(e, t);
+ i.position.set(-.757, 13.219, .717), i.scale.set(31.713, 28.305, 28.591), this.add(i);
+ let a = new ea(e, n, 6), o = new nr();
+ o.position.set(-10.906, 2.009, 1.846), o.rotation.set(0, -.195, 0), o.scale.set(2.328, 7.905, 4.651), o.updateMatrix(), a.setMatrixAt(0, o.matrix), o.position.set(-5.607, -.754, -.758), o.rotation.set(0, .994, 0), o.scale.set(1.97, 1.534, 3.955), o.updateMatrix(), a.setMatrixAt(1, o.matrix), o.position.set(6.167, .857, 7.803), o.rotation.set(0, .561, 0), o.scale.set(3.927, 6.285, 3.687), o.updateMatrix(), a.setMatrixAt(2, o.matrix), o.position.set(-2.017, .018, 6.124), o.rotation.set(0, .333, 0), o.scale.set(2.002, 4.566, 2.064), o.updateMatrix(), a.setMatrixAt(3, o.matrix), o.position.set(2.291, -.756, -2.621), o.rotation.set(0, -.286, 0), o.scale.set(1.546, 1.552, 1.496), o.updateMatrix(), a.setMatrixAt(4, o.matrix), o.position.set(-2.193, -.369, -5.547), o.rotation.set(0, .516, 0), o.scale.set(3.875, 3.487, 2.986), o.updateMatrix(), a.setMatrixAt(5, o.matrix), this.add(a);
+ let s = new ni(e, Id(50));
+ s.position.set(-16.116, 14.37, 8.208), s.scale.set(.1, 2.428, 2.739), this.add(s);
+ let c = new ni(e, Id(50));
+ c.position.set(-16.109, 18.021, -8.207), c.scale.set(.1, 2.425, 2.751), this.add(c);
+ let l = new ni(e, Id(17));
+ l.position.set(14.904, 12.198, -1.832), l.scale.set(.15, 4.265, 6.331), this.add(l);
+ let u = new ni(e, Id(43));
+ u.position.set(-.462, 8.89, 14.52), u.scale.set(4.38, 5.441, .088), this.add(u);
+ let d = new ni(e, Id(20));
+ d.position.set(3.235, 11.486, -12.541), d.scale.set(2.5, 2, .1), this.add(d);
+ let f = new ni(e, Id(100));
+ f.position.set(0, 20, 0), f.scale.set(1, .1, 1), this.add(f);
+ }
+ dispose() {
+ let e = /* @__PURE__ */ new Set();
+ this.traverse((t) => {
+ t.isMesh && (e.add(t.geometry), e.add(t.material));
+ });
+ for (let t of e) t.dispose();
+ }
+};
+function Id(e) {
+ let t = new wr();
+ return t.color.setScalar(e), t;
+}
+//#endregion
+//#region node_modules/dat.gui/build/dat.gui.module.js
+function Ld(e) {
+ if (e && !(typeof window > "u")) {
+ var t = document.createElement("style");
+ return t.setAttribute("type", "text/css"), t.innerHTML = e, document.head.appendChild(t), e;
+ }
+}
+function Rd(e, t) {
+ var n = e.__state.conversionName.toString(), r = Math.round(e.r), i = Math.round(e.g), a = Math.round(e.b), o = e.a, s = Math.round(e.h), c = e.s.toFixed(1), l = e.v.toFixed(1);
+ if (t || n === "THREE_CHAR_HEX" || n === "SIX_CHAR_HEX") {
+ for (var u = e.hex.toString(16); u.length < 6;) u = "0" + u;
+ return "#" + u;
+ } else if (n === "CSS_RGB") return "rgb(" + r + "," + i + "," + a + ")";
+ else if (n === "CSS_RGBA") return "rgba(" + r + "," + i + "," + a + "," + o + ")";
+ else if (n === "HEX") return "0x" + e.hex.toString(16);
+ else if (n === "RGB_ARRAY") return "[" + r + "," + i + "," + a + "]";
+ else if (n === "RGBA_ARRAY") return "[" + r + "," + i + "," + a + "," + o + "]";
+ else if (n === "RGB_OBJ") return "{r:" + r + ",g:" + i + ",b:" + a + "}";
+ else if (n === "RGBA_OBJ") return "{r:" + r + ",g:" + i + ",b:" + a + ",a:" + o + "}";
+ else if (n === "HSV_OBJ") return "{h:" + s + ",s:" + c + ",v:" + l + "}";
+ else if (n === "HSVA_OBJ") return "{h:" + s + ",s:" + c + ",v:" + l + ",a:" + o + "}";
+ return "unknown format";
+}
+var zd = Array.prototype.forEach, Bd = Array.prototype.slice, U = {
+ BREAK: {},
+ extend: function(e) {
+ return this.each(Bd.call(arguments, 1), function(t) {
+ (this.isObject(t) ? Object.keys(t) : []).forEach(function(n) {
+ this.isUndefined(t[n]) || (e[n] = t[n]);
+ }.bind(this));
+ }, this), e;
+ },
+ defaults: function(e) {
+ return this.each(Bd.call(arguments, 1), function(t) {
+ (this.isObject(t) ? Object.keys(t) : []).forEach(function(n) {
+ this.isUndefined(e[n]) && (e[n] = t[n]);
+ }.bind(this));
+ }, this), e;
+ },
+ compose: function() {
+ var e = Bd.call(arguments);
+ return function() {
+ for (var t = Bd.call(arguments), n = e.length - 1; n >= 0; n--) t = [e[n].apply(this, t)];
+ return t[0];
+ };
+ },
+ each: function(e, t, n) {
+ if (e) {
+ if (zd && e.forEach && e.forEach === zd) e.forEach(t, n);
+ else if (e.length === e.length + 0) {
+ var r = void 0, i = void 0;
+ for (r = 0, i = e.length; r < i; r++) if (r in e && t.call(n, e[r], r) === this.BREAK) return;
+ } else for (var a in e) if (t.call(n, e[a], a) === this.BREAK) return;
+ }
+ },
+ defer: function(e) {
+ setTimeout(e, 0);
+ },
+ debounce: function(e, t, n) {
+ var r = void 0;
+ return function() {
+ var i = this, a = arguments;
+ function o() {
+ r = null, n || e.apply(i, a);
+ }
+ var s = n || !r;
+ clearTimeout(r), r = setTimeout(o, t), s && e.apply(i, a);
+ };
+ },
+ toArray: function(e) {
+ return e.toArray ? e.toArray() : Bd.call(e);
+ },
+ isUndefined: function(e) {
+ return e === void 0;
+ },
+ isNull: function(e) {
+ return e === null;
+ },
+ isNaN: function(e) {
+ function t(t) {
+ return e.apply(this, arguments);
+ }
+ return t.toString = function() {
+ return e.toString();
+ }, t;
+ }(function(e) {
+ return isNaN(e);
+ }),
+ isArray: Array.isArray || function(e) {
+ return e.constructor === Array;
+ },
+ isObject: function(e) {
+ return e === Object(e);
+ },
+ isNumber: function(e) {
+ return e === e + 0;
+ },
+ isString: function(e) {
+ return e === e + "";
+ },
+ isBoolean: function(e) {
+ return e === !1 || e === !0;
+ },
+ isFunction: function(e) {
+ return e instanceof Function;
+ }
+}, Vd = [
+ {
+ litmus: U.isString,
+ conversions: {
+ THREE_CHAR_HEX: {
+ read: function(e) {
+ var t = e.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
+ return t === null ? !1 : {
+ space: "HEX",
+ hex: parseInt("0x" + t[1].toString() + t[1].toString() + t[2].toString() + t[2].toString() + t[3].toString() + t[3].toString(), 0)
+ };
+ },
+ write: Rd
+ },
+ SIX_CHAR_HEX: {
+ read: function(e) {
+ var t = e.match(/^#([A-F0-9]{6})$/i);
+ return t === null ? !1 : {
+ space: "HEX",
+ hex: parseInt("0x" + t[1].toString(), 0)
+ };
+ },
+ write: Rd
+ },
+ CSS_RGB: {
+ read: function(e) {
+ var t = e.match(/^rgb\(\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*\)/);
+ return t === null ? !1 : {
+ space: "RGB",
+ r: parseFloat(t[1]),
+ g: parseFloat(t[2]),
+ b: parseFloat(t[3])
+ };
+ },
+ write: Rd
+ },
+ CSS_RGBA: {
+ read: function(e) {
+ var t = e.match(/^rgba\(\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*\)/);
+ return t === null ? !1 : {
+ space: "RGB",
+ r: parseFloat(t[1]),
+ g: parseFloat(t[2]),
+ b: parseFloat(t[3]),
+ a: parseFloat(t[4])
+ };
+ },
+ write: Rd
+ }
+ }
+ },
+ {
+ litmus: U.isNumber,
+ conversions: { HEX: {
+ read: function(e) {
+ return {
+ space: "HEX",
+ hex: e,
+ conversionName: "HEX"
+ };
+ },
+ write: function(e) {
+ return e.hex;
+ }
+ } }
+ },
+ {
+ litmus: U.isArray,
+ conversions: {
+ RGB_ARRAY: {
+ read: function(e) {
+ return e.length === 3 ? {
+ space: "RGB",
+ r: e[0],
+ g: e[1],
+ b: e[2]
+ } : !1;
+ },
+ write: function(e) {
+ return [
+ e.r,
+ e.g,
+ e.b
+ ];
+ }
+ },
+ RGBA_ARRAY: {
+ read: function(e) {
+ return e.length === 4 ? {
+ space: "RGB",
+ r: e[0],
+ g: e[1],
+ b: e[2],
+ a: e[3]
+ } : !1;
+ },
+ write: function(e) {
+ return [
+ e.r,
+ e.g,
+ e.b,
+ e.a
+ ];
+ }
+ }
+ }
+ },
+ {
+ litmus: U.isObject,
+ conversions: {
+ RGBA_OBJ: {
+ read: function(e) {
+ return U.isNumber(e.r) && U.isNumber(e.g) && U.isNumber(e.b) && U.isNumber(e.a) ? {
+ space: "RGB",
+ r: e.r,
+ g: e.g,
+ b: e.b,
+ a: e.a
+ } : !1;
+ },
+ write: function(e) {
+ return {
+ r: e.r,
+ g: e.g,
+ b: e.b,
+ a: e.a
+ };
+ }
+ },
+ RGB_OBJ: {
+ read: function(e) {
+ return U.isNumber(e.r) && U.isNumber(e.g) && U.isNumber(e.b) ? {
+ space: "RGB",
+ r: e.r,
+ g: e.g,
+ b: e.b
+ } : !1;
+ },
+ write: function(e) {
+ return {
+ r: e.r,
+ g: e.g,
+ b: e.b
+ };
+ }
+ },
+ HSVA_OBJ: {
+ read: function(e) {
+ return U.isNumber(e.h) && U.isNumber(e.s) && U.isNumber(e.v) && U.isNumber(e.a) ? {
+ space: "HSV",
+ h: e.h,
+ s: e.s,
+ v: e.v,
+ a: e.a
+ } : !1;
+ },
+ write: function(e) {
+ return {
+ h: e.h,
+ s: e.s,
+ v: e.v,
+ a: e.a
+ };
+ }
+ },
+ HSV_OBJ: {
+ read: function(e) {
+ return U.isNumber(e.h) && U.isNumber(e.s) && U.isNumber(e.v) ? {
+ space: "HSV",
+ h: e.h,
+ s: e.s,
+ v: e.v
+ } : !1;
+ },
+ write: function(e) {
+ return {
+ h: e.h,
+ s: e.s,
+ v: e.v
+ };
+ }
+ }
+ }
+ }
+], Hd = void 0, Ud = void 0, Wd = function() {
+ Ud = !1;
+ var e = arguments.length > 1 ? U.toArray(arguments) : arguments[0];
+ return U.each(Vd, function(t) {
+ if (t.litmus(e)) return U.each(t.conversions, function(t, n) {
+ if (Hd = t.read(e), Ud === !1 && Hd !== !1) return Ud = Hd, Hd.conversionName = n, Hd.conversion = t, U.BREAK;
+ }), U.BREAK;
+ }), Ud;
+}, Gd = void 0, Kd = {
+ hsv_to_rgb: function(e, t, n) {
+ var r = Math.floor(e / 60) % 6, i = e / 60 - Math.floor(e / 60), a = n * (1 - t), o = n * (1 - i * t), s = n * (1 - (1 - i) * t), c = [
+ [
+ n,
+ s,
+ a
+ ],
+ [
+ o,
+ n,
+ a
+ ],
+ [
+ a,
+ n,
+ s
+ ],
+ [
+ a,
+ o,
+ n
+ ],
+ [
+ s,
+ a,
+ n
+ ],
+ [
+ n,
+ a,
+ o
+ ]
+ ][r];
+ return {
+ r: c[0] * 255,
+ g: c[1] * 255,
+ b: c[2] * 255
+ };
+ },
+ rgb_to_hsv: function(e, t, n) {
+ var r = Math.min(e, t, n), i = Math.max(e, t, n), a = i - r, o = void 0, s = void 0;
+ if (i !== 0) s = a / i;
+ else return {
+ h: NaN,
+ s: 0,
+ v: 0
+ };
+ return o = e === i ? (t - n) / a : t === i ? 2 + (n - e) / a : 4 + (e - t) / a, o /= 6, o < 0 && (o += 1), {
+ h: o * 360,
+ s,
+ v: i / 255
+ };
+ },
+ rgb_to_hex: function(e, t, n) {
+ var r = this.hex_with_component(0, 2, e);
+ return r = this.hex_with_component(r, 1, t), r = this.hex_with_component(r, 0, n), r;
+ },
+ component_from_hex: function(e, t) {
+ return e >> t * 8 & 255;
+ },
+ hex_with_component: function(e, t, n) {
+ return n << (Gd = t * 8) | e & ~(255 << Gd);
+ }
+}, qd = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(e) {
+ return typeof e;
+} : function(e) {
+ return e && typeof Symbol == "function" && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e;
+}, Jd = function(e, t) {
+ if (!(e instanceof t)) throw TypeError("Cannot call a class as a function");
+}, Yd = function() {
+ function e(e, t) {
+ for (var n = 0; n < t.length; n++) {
+ var r = t[n];
+ r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r);
+ }
+ }
+ return function(t, n, r) {
+ return n && e(t.prototype, n), r && e(t, r), t;
+ };
+}(), Xd = function e(t, n, r) {
+ t === null && (t = Function.prototype);
+ var i = Object.getOwnPropertyDescriptor(t, n);
+ if (i === void 0) {
+ var a = Object.getPrototypeOf(t);
+ return a === null ? void 0 : e(a, n, r);
+ } else if ("value" in i) return i.value;
+ else {
+ var o = i.get;
+ return o === void 0 ? void 0 : o.call(r);
+ }
+}, Zd = function(e, t) {
+ if (typeof t != "function" && t !== null) throw TypeError("Super expression must either be null or a function, not " + typeof t);
+ e.prototype = Object.create(t && t.prototype, { constructor: {
+ value: e,
+ enumerable: !1,
+ writable: !0,
+ configurable: !0
+ } }), t && (Object.setPrototypeOf ? Object.setPrototypeOf(e, t) : e.__proto__ = t);
+}, Qd = function(e, t) {
+ if (!e) throw ReferenceError("this hasn't been initialised - super() hasn't been called");
+ return t && (typeof t == "object" || typeof t == "function") ? t : e;
+}, $d = function() {
+ function e() {
+ if (Jd(this, e), this.__state = Wd.apply(this, arguments), this.__state === !1) throw Error("Failed to interpret color arguments");
+ this.__state.a = this.__state.a || 1;
+ }
+ return Yd(e, [
+ {
+ key: "toString",
+ value: function() {
+ return Rd(this);
+ }
+ },
+ {
+ key: "toHexString",
+ value: function() {
+ return Rd(this, !0);
+ }
+ },
+ {
+ key: "toOriginal",
+ value: function() {
+ return this.__state.conversion.write(this);
+ }
+ }
+ ]), e;
+}();
+function ef(e, t, n) {
+ Object.defineProperty(e, t, {
+ get: function() {
+ return this.__state.space === "RGB" || $d.recalculateRGB(this, t, n), this.__state[t];
+ },
+ set: function(e) {
+ this.__state.space !== "RGB" && ($d.recalculateRGB(this, t, n), this.__state.space = "RGB"), this.__state[t] = e;
+ }
+ });
+}
+function tf(e, t) {
+ Object.defineProperty(e, t, {
+ get: function() {
+ return this.__state.space === "HSV" || $d.recalculateHSV(this), this.__state[t];
+ },
+ set: function(e) {
+ this.__state.space !== "HSV" && ($d.recalculateHSV(this), this.__state.space = "HSV"), this.__state[t] = e;
+ }
+ });
+}
+$d.recalculateRGB = function(e, t, n) {
+ if (e.__state.space === "HEX") e.__state[t] = Kd.component_from_hex(e.__state.hex, n);
+ else if (e.__state.space === "HSV") U.extend(e.__state, Kd.hsv_to_rgb(e.__state.h, e.__state.s, e.__state.v));
+ else throw Error("Corrupted color state");
+}, $d.recalculateHSV = function(e) {
+ var t = Kd.rgb_to_hsv(e.r, e.g, e.b);
+ U.extend(e.__state, {
+ s: t.s,
+ v: t.v
+ }), U.isNaN(t.h) ? U.isUndefined(e.__state.h) && (e.__state.h = 0) : e.__state.h = t.h;
+}, $d.COMPONENTS = [
+ "r",
+ "g",
+ "b",
+ "h",
+ "s",
+ "v",
+ "hex",
+ "a"
+], ef($d.prototype, "r", 2), ef($d.prototype, "g", 1), ef($d.prototype, "b", 0), tf($d.prototype, "h"), tf($d.prototype, "s"), tf($d.prototype, "v"), Object.defineProperty($d.prototype, "a", {
+ get: function() {
+ return this.__state.a;
+ },
+ set: function(e) {
+ this.__state.a = e;
+ }
+}), Object.defineProperty($d.prototype, "hex", {
+ get: function() {
+ return this.__state.space !== "HEX" && (this.__state.hex = Kd.rgb_to_hex(this.r, this.g, this.b), this.__state.space = "HEX"), this.__state.hex;
+ },
+ set: function(e) {
+ this.__state.space = "HEX", this.__state.hex = e;
+ }
+});
+var nf = function() {
+ function e(t, n) {
+ Jd(this, e), this.initialValue = t[n], this.domElement = document.createElement("div"), this.object = t, this.property = n, this.__onChange = void 0, this.__onFinishChange = void 0;
+ }
+ return Yd(e, [
+ {
+ key: "onChange",
+ value: function(e) {
+ return this.__onChange = e, this;
+ }
+ },
+ {
+ key: "onFinishChange",
+ value: function(e) {
+ return this.__onFinishChange = e, this;
+ }
+ },
+ {
+ key: "setValue",
+ value: function(e) {
+ return this.object[this.property] = e, this.__onChange && this.__onChange.call(this, e), this.updateDisplay(), this;
+ }
+ },
+ {
+ key: "getValue",
+ value: function() {
+ return this.object[this.property];
+ }
+ },
+ {
+ key: "updateDisplay",
+ value: function() {
+ return this;
+ }
+ },
+ {
+ key: "isModified",
+ value: function() {
+ return this.initialValue !== this.getValue();
+ }
+ }
+ ]), e;
+}(), rf = {
+ HTMLEvents: ["change"],
+ MouseEvents: [
+ "click",
+ "mousemove",
+ "mousedown",
+ "mouseup",
+ "mouseover"
+ ],
+ KeyboardEvents: ["keydown"]
+}, af = {};
+U.each(rf, function(e, t) {
+ U.each(e, function(e) {
+ af[e] = t;
+ });
+});
+var of = /(\d+(\.\d+)?)px/;
+function sf(e) {
+ if (e === "0" || U.isUndefined(e)) return 0;
+ var t = e.match(of);
+ return U.isNull(t) ? 0 : parseFloat(t[1]);
+}
+var W = {
+ makeSelectable: function(e, t) {
+ e === void 0 || e.style === void 0 || (e.onselectstart = t ? function() {
+ return !1;
+ } : function() {}, e.style.MozUserSelect = t ? "auto" : "none", e.style.KhtmlUserSelect = t ? "auto" : "none", e.unselectable = t ? "on" : "off");
+ },
+ makeFullscreen: function(e, t, n) {
+ var r = n, i = t;
+ U.isUndefined(i) && (i = !0), U.isUndefined(r) && (r = !0), e.style.position = "absolute", i && (e.style.left = 0, e.style.right = 0), r && (e.style.top = 0, e.style.bottom = 0);
+ },
+ fakeEvent: function(e, t, n, r) {
+ var i = n || {}, a = af[t];
+ if (!a) throw Error("Event type " + t + " not supported.");
+ var o = document.createEvent(a);
+ switch (a) {
+ case "MouseEvents":
+ var s = i.x || i.clientX || 0, c = i.y || i.clientY || 0;
+ o.initMouseEvent(t, i.bubbles || !1, i.cancelable || !0, window, i.clickCount || 1, 0, 0, s, c, !1, !1, !1, !1, 0, null);
+ break;
+ case "KeyboardEvents":
+ var l = o.initKeyboardEvent || o.initKeyEvent;
+ U.defaults(i, {
+ cancelable: !0,
+ ctrlKey: !1,
+ altKey: !1,
+ shiftKey: !1,
+ metaKey: !1,
+ keyCode: void 0,
+ charCode: void 0
+ }), l(t, i.bubbles || !1, i.cancelable, window, i.ctrlKey, i.altKey, i.shiftKey, i.metaKey, i.keyCode, i.charCode);
+ break;
+ default:
+ o.initEvent(t, i.bubbles || !1, i.cancelable || !0);
+ break;
+ }
+ U.defaults(o, r), e.dispatchEvent(o);
+ },
+ bind: function(e, t, n, r) {
+ var i = r || !1;
+ return e.addEventListener ? e.addEventListener(t, n, i) : e.attachEvent && e.attachEvent("on" + t, n), W;
+ },
+ unbind: function(e, t, n, r) {
+ var i = r || !1;
+ return e.removeEventListener ? e.removeEventListener(t, n, i) : e.detachEvent && e.detachEvent("on" + t, n), W;
+ },
+ addClass: function(e, t) {
+ if (e.className === void 0) e.className = t;
+ else if (e.className !== t) {
+ var n = e.className.split(/ +/);
+ n.indexOf(t) === -1 && (n.push(t), e.className = n.join(" ").replace(/^\s+/, "").replace(/\s+$/, ""));
+ }
+ return W;
+ },
+ removeClass: function(e, t) {
+ if (t) if (e.className === t) e.removeAttribute("class");
+ else {
+ var n = e.className.split(/ +/), r = n.indexOf(t);
+ r !== -1 && (n.splice(r, 1), e.className = n.join(" "));
+ }
+ else e.className = void 0;
+ return W;
+ },
+ hasClass: function(e, t) {
+ return RegExp("(?:^|\\s+)" + t + "(?:\\s+|$)").test(e.className) || !1;
+ },
+ getWidth: function(e) {
+ var t = getComputedStyle(e);
+ return sf(t["border-left-width"]) + sf(t["border-right-width"]) + sf(t["padding-left"]) + sf(t["padding-right"]) + sf(t.width);
+ },
+ getHeight: function(e) {
+ var t = getComputedStyle(e);
+ return sf(t["border-top-width"]) + sf(t["border-bottom-width"]) + sf(t["padding-top"]) + sf(t["padding-bottom"]) + sf(t.height);
+ },
+ getOffset: function(e) {
+ var t = e, n = {
+ left: 0,
+ top: 0
+ };
+ if (t.offsetParent) do
+ n.left += t.offsetLeft, n.top += t.offsetTop, t = t.offsetParent;
+ while (t);
+ return n;
+ },
+ isActive: function(e) {
+ return e === document.activeElement && (e.type || e.href);
+ }
+}, cf = function(e) {
+ Zd(t, e);
+ function t(e, n) {
+ Jd(this, t);
+ var r = Qd(this, (t.__proto__ || Object.getPrototypeOf(t)).call(this, e, n)), i = r;
+ r.__prev = r.getValue(), r.__checkbox = document.createElement("input"), r.__checkbox.setAttribute("type", "checkbox");
+ function a() {
+ i.setValue(!i.__prev);
+ }
+ return W.bind(r.__checkbox, "change", a, !1), r.domElement.appendChild(r.__checkbox), r.updateDisplay(), r;
+ }
+ return Yd(t, [{
+ key: "setValue",
+ value: function(e) {
+ var n = Xd(t.prototype.__proto__ || Object.getPrototypeOf(t.prototype), "setValue", this).call(this, e);
+ return this.__onFinishChange && this.__onFinishChange.call(this, this.getValue()), this.__prev = this.getValue(), n;
+ }
+ }, {
+ key: "updateDisplay",
+ value: function() {
+ return this.getValue() === !0 ? (this.__checkbox.setAttribute("checked", "checked"), this.__checkbox.checked = !0, this.__prev = !0) : (this.__checkbox.checked = !1, this.__prev = !1), Xd(t.prototype.__proto__ || Object.getPrototypeOf(t.prototype), "updateDisplay", this).call(this);
+ }
+ }]), t;
+}(nf), lf = function(e) {
+ Zd(t, e);
+ function t(e, n, r) {
+ Jd(this, t);
+ var i = Qd(this, (t.__proto__ || Object.getPrototypeOf(t)).call(this, e, n)), a = r, o = i;
+ if (i.__select = document.createElement("select"), U.isArray(a)) {
+ var s = {};
+ U.each(a, function(e) {
+ s[e] = e;
+ }), a = s;
+ }
+ return U.each(a, function(e, t) {
+ var n = document.createElement("option");
+ n.innerHTML = t, n.setAttribute("value", e), o.__select.appendChild(n);
+ }), i.updateDisplay(), W.bind(i.__select, "change", function() {
+ var e = this.options[this.selectedIndex].value;
+ o.setValue(e);
+ }), i.domElement.appendChild(i.__select), i;
+ }
+ return Yd(t, [{
+ key: "setValue",
+ value: function(e) {
+ var n = Xd(t.prototype.__proto__ || Object.getPrototypeOf(t.prototype), "setValue", this).call(this, e);
+ return this.__onFinishChange && this.__onFinishChange.call(this, this.getValue()), n;
+ }
+ }, {
+ key: "updateDisplay",
+ value: function() {
+ return W.isActive(this.__select) ? this : (this.__select.value = this.getValue(), Xd(t.prototype.__proto__ || Object.getPrototypeOf(t.prototype), "updateDisplay", this).call(this));
+ }
+ }]), t;
+}(nf), uf = function(e) {
+ Zd(t, e);
+ function t(e, n) {
+ Jd(this, t);
+ var r = Qd(this, (t.__proto__ || Object.getPrototypeOf(t)).call(this, e, n)), i = r;
+ function a() {
+ i.setValue(i.__input.value);
+ }
+ function o() {
+ i.__onFinishChange && i.__onFinishChange.call(i, i.getValue());
+ }
+ return r.__input = document.createElement("input"), r.__input.setAttribute("type", "text"), W.bind(r.__input, "keyup", a), W.bind(r.__input, "change", a), W.bind(r.__input, "blur", o), W.bind(r.__input, "keydown", function(e) {
+ e.keyCode === 13 && this.blur();
+ }), r.updateDisplay(), r.domElement.appendChild(r.__input), r;
+ }
+ return Yd(t, [{
+ key: "updateDisplay",
+ value: function() {
+ return W.isActive(this.__input) || (this.__input.value = this.getValue()), Xd(t.prototype.__proto__ || Object.getPrototypeOf(t.prototype), "updateDisplay", this).call(this);
+ }
+ }]), t;
+}(nf);
+function df(e) {
+ var t = e.toString();
+ return t.indexOf(".") > -1 ? t.length - t.indexOf(".") - 1 : 0;
+}
+var ff = function(e) {
+ Zd(t, e);
+ function t(e, n, r) {
+ Jd(this, t);
+ var i = Qd(this, (t.__proto__ || Object.getPrototypeOf(t)).call(this, e, n)), a = r || {};
+ return i.__min = a.min, i.__max = a.max, i.__step = a.step, U.isUndefined(i.__step) ? i.initialValue === 0 ? i.__impliedStep = 1 : i.__impliedStep = 10 ** Math.floor(Math.log(Math.abs(i.initialValue)) / Math.LN10) / 10 : i.__impliedStep = i.__step, i.__precision = df(i.__impliedStep), i;
+ }
+ return Yd(t, [
+ {
+ key: "setValue",
+ value: function(e) {
+ var n = e;
+ return this.__min !== void 0 && n < this.__min ? n = this.__min : this.__max !== void 0 && n > this.__max && (n = this.__max), this.__step !== void 0 && n % this.__step !== 0 && (n = Math.round(n / this.__step) * this.__step), Xd(t.prototype.__proto__ || Object.getPrototypeOf(t.prototype), "setValue", this).call(this, n);
+ }
+ },
+ {
+ key: "min",
+ value: function(e) {
+ return this.__min = e, this;
+ }
+ },
+ {
+ key: "max",
+ value: function(e) {
+ return this.__max = e, this;
+ }
+ },
+ {
+ key: "step",
+ value: function(e) {
+ return this.__step = e, this.__impliedStep = e, this.__precision = df(e), this;
+ }
+ }
+ ]), t;
+}(nf);
+function pf(e, t) {
+ var n = 10 ** t;
+ return Math.round(e * n) / n;
+}
+var mf = function(e) {
+ Zd(t, e);
+ function t(e, n, r) {
+ Jd(this, t);
+ var i = Qd(this, (t.__proto__ || Object.getPrototypeOf(t)).call(this, e, n, r));
+ i.__truncationSuspended = !1;
+ var a = i, o = void 0;
+ function s() {
+ var e = parseFloat(a.__input.value);
+ U.isNaN(e) || a.setValue(e);
+ }
+ function c() {
+ a.__onFinishChange && a.__onFinishChange.call(a, a.getValue());
+ }
+ function l() {
+ c();
+ }
+ function u(e) {
+ var t = o - e.clientY;
+ a.setValue(a.getValue() + t * a.__impliedStep), o = e.clientY;
+ }
+ function d() {
+ W.unbind(window, "mousemove", u), W.unbind(window, "mouseup", d), c();
+ }
+ function f(e) {
+ W.bind(window, "mousemove", u), W.bind(window, "mouseup", d), o = e.clientY;
+ }
+ return i.__input = document.createElement("input"), i.__input.setAttribute("type", "text"), W.bind(i.__input, "change", s), W.bind(i.__input, "blur", l), W.bind(i.__input, "mousedown", f), W.bind(i.__input, "keydown", function(e) {
+ e.keyCode === 13 && (a.__truncationSuspended = !0, this.blur(), a.__truncationSuspended = !1, c());
+ }), i.updateDisplay(), i.domElement.appendChild(i.__input), i;
+ }
+ return Yd(t, [{
+ key: "updateDisplay",
+ value: function() {
+ return this.__input.value = this.__truncationSuspended ? this.getValue() : pf(this.getValue(), this.__precision), Xd(t.prototype.__proto__ || Object.getPrototypeOf(t.prototype), "updateDisplay", this).call(this);
+ }
+ }]), t;
+}(ff);
+function hf(e, t, n, r, i) {
+ return r + (i - r) * ((e - t) / (n - t));
+}
+var gf = function(e) {
+ Zd(t, e);
+ function t(e, n, r, i, a) {
+ Jd(this, t);
+ var o = Qd(this, (t.__proto__ || Object.getPrototypeOf(t)).call(this, e, n, {
+ min: r,
+ max: i,
+ step: a
+ })), s = o;
+ o.__background = document.createElement("div"), o.__foreground = document.createElement("div"), W.bind(o.__background, "mousedown", c), W.bind(o.__background, "touchstart", d), W.addClass(o.__background, "slider"), W.addClass(o.__foreground, "slider-fg");
+ function c(e) {
+ document.activeElement.blur(), W.bind(window, "mousemove", l), W.bind(window, "mouseup", u), l(e);
+ }
+ function l(e) {
+ e.preventDefault();
+ var t = s.__background.getBoundingClientRect();
+ return s.setValue(hf(e.clientX, t.left, t.right, s.__min, s.__max)), !1;
+ }
+ function u() {
+ W.unbind(window, "mousemove", l), W.unbind(window, "mouseup", u), s.__onFinishChange && s.__onFinishChange.call(s, s.getValue());
+ }
+ function d(e) {
+ e.touches.length === 1 && (W.bind(window, "touchmove", f), W.bind(window, "touchend", p), f(e));
+ }
+ function f(e) {
+ var t = e.touches[0].clientX, n = s.__background.getBoundingClientRect();
+ s.setValue(hf(t, n.left, n.right, s.__min, s.__max));
+ }
+ function p() {
+ W.unbind(window, "touchmove", f), W.unbind(window, "touchend", p), s.__onFinishChange && s.__onFinishChange.call(s, s.getValue());
+ }
+ return o.updateDisplay(), o.__background.appendChild(o.__foreground), o.domElement.appendChild(o.__background), o;
+ }
+ return Yd(t, [{
+ key: "updateDisplay",
+ value: function() {
+ var e = (this.getValue() - this.__min) / (this.__max - this.__min);
+ return this.__foreground.style.width = e * 100 + "%", Xd(t.prototype.__proto__ || Object.getPrototypeOf(t.prototype), "updateDisplay", this).call(this);
+ }
+ }]), t;
+}(ff), _f = function(e) {
+ Zd(t, e);
+ function t(e, n, r) {
+ Jd(this, t);
+ var i = Qd(this, (t.__proto__ || Object.getPrototypeOf(t)).call(this, e, n)), a = i;
+ return i.__button = document.createElement("div"), i.__button.innerHTML = r === void 0 ? "Fire" : r, W.bind(i.__button, "click", function(e) {
+ return e.preventDefault(), a.fire(), !1;
+ }), W.addClass(i.__button, "button"), i.domElement.appendChild(i.__button), i;
+ }
+ return Yd(t, [{
+ key: "fire",
+ value: function() {
+ this.__onChange && this.__onChange.call(this), this.getValue().call(this.object), this.__onFinishChange && this.__onFinishChange.call(this, this.getValue());
+ }
+ }]), t;
+}(nf), vf = function(e) {
+ Zd(t, e);
+ function t(e, n) {
+ Jd(this, t);
+ var r = Qd(this, (t.__proto__ || Object.getPrototypeOf(t)).call(this, e, n));
+ r.__color = new $d(r.getValue()), r.__temp = new $d(0);
+ var i = r;
+ r.domElement = document.createElement("div"), W.makeSelectable(r.domElement, !1), r.__selector = document.createElement("div"), r.__selector.className = "selector", r.__saturation_field = document.createElement("div"), r.__saturation_field.className = "saturation-field", r.__field_knob = document.createElement("div"), r.__field_knob.className = "field-knob", r.__field_knob_border = "2px solid ", r.__hue_knob = document.createElement("div"), r.__hue_knob.className = "hue-knob", r.__hue_field = document.createElement("div"), r.__hue_field.className = "hue-field", r.__input = document.createElement("input"), r.__input.type = "text", r.__input_textShadow = "0 1px 1px ", W.bind(r.__input, "keydown", function(e) {
+ e.keyCode === 13 && u.call(this);
+ }), W.bind(r.__input, "blur", u), W.bind(r.__selector, "mousedown", function() {
+ W.addClass(this, "drag").bind(window, "mouseup", function() {
+ W.removeClass(i.__selector, "drag");
+ });
+ }), W.bind(r.__selector, "touchstart", function() {
+ W.addClass(this, "drag").bind(window, "touchend", function() {
+ W.removeClass(i.__selector, "drag");
+ });
+ });
+ var a = document.createElement("div");
+ U.extend(r.__selector.style, {
+ width: "122px",
+ height: "102px",
+ padding: "3px",
+ backgroundColor: "#222",
+ boxShadow: "0px 1px 3px rgba(0,0,0,0.3)"
+ }), U.extend(r.__field_knob.style, {
+ position: "absolute",
+ width: "12px",
+ height: "12px",
+ border: r.__field_knob_border + (r.__color.v < .5 ? "#fff" : "#000"),
+ boxShadow: "0px 1px 3px rgba(0,0,0,0.5)",
+ borderRadius: "12px",
+ zIndex: 1
+ }), U.extend(r.__hue_knob.style, {
+ position: "absolute",
+ width: "15px",
+ height: "2px",
+ borderRight: "4px solid #fff",
+ zIndex: 1
+ }), U.extend(r.__saturation_field.style, {
+ width: "100px",
+ height: "100px",
+ border: "1px solid #555",
+ marginRight: "3px",
+ display: "inline-block",
+ cursor: "pointer"
+ }), U.extend(a.style, {
+ width: "100%",
+ height: "100%",
+ background: "none"
+ }), bf(a, "top", "rgba(0,0,0,0)", "#000"), U.extend(r.__hue_field.style, {
+ width: "15px",
+ height: "100px",
+ border: "1px solid #555",
+ cursor: "ns-resize",
+ position: "absolute",
+ top: "3px",
+ right: "3px"
+ }), xf(r.__hue_field), U.extend(r.__input.style, {
+ outline: "none",
+ textAlign: "center",
+ color: "#fff",
+ border: 0,
+ fontWeight: "bold",
+ textShadow: r.__input_textShadow + "rgba(0,0,0,0.7)"
+ }), W.bind(r.__saturation_field, "mousedown", o), W.bind(r.__saturation_field, "touchstart", o), W.bind(r.__field_knob, "mousedown", o), W.bind(r.__field_knob, "touchstart", o), W.bind(r.__hue_field, "mousedown", s), W.bind(r.__hue_field, "touchstart", s);
+ function o(e) {
+ f(e), W.bind(window, "mousemove", f), W.bind(window, "touchmove", f), W.bind(window, "mouseup", c), W.bind(window, "touchend", c);
+ }
+ function s(e) {
+ p(e), W.bind(window, "mousemove", p), W.bind(window, "touchmove", p), W.bind(window, "mouseup", l), W.bind(window, "touchend", l);
+ }
+ function c() {
+ W.unbind(window, "mousemove", f), W.unbind(window, "touchmove", f), W.unbind(window, "mouseup", c), W.unbind(window, "touchend", c), d();
+ }
+ function l() {
+ W.unbind(window, "mousemove", p), W.unbind(window, "touchmove", p), W.unbind(window, "mouseup", l), W.unbind(window, "touchend", l), d();
+ }
+ function u() {
+ var e = Wd(this.value);
+ e === !1 ? this.value = i.__color.toString() : (i.__color.__state = e, i.setValue(i.__color.toOriginal()));
+ }
+ function d() {
+ i.__onFinishChange && i.__onFinishChange.call(i, i.__color.toOriginal());
+ }
+ r.__saturation_field.appendChild(a), r.__selector.appendChild(r.__field_knob), r.__selector.appendChild(r.__saturation_field), r.__selector.appendChild(r.__hue_field), r.__hue_field.appendChild(r.__hue_knob), r.domElement.appendChild(r.__input), r.domElement.appendChild(r.__selector), r.updateDisplay();
+ function f(e) {
+ e.type.indexOf("touch") === -1 && e.preventDefault();
+ var t = i.__saturation_field.getBoundingClientRect(), n = e.touches && e.touches[0] || e, r = n.clientX, a = n.clientY, o = (r - t.left) / (t.right - t.left), s = 1 - (a - t.top) / (t.bottom - t.top);
+ return s > 1 ? s = 1 : s < 0 && (s = 0), o > 1 ? o = 1 : o < 0 && (o = 0), i.__color.v = s, i.__color.s = o, i.setValue(i.__color.toOriginal()), !1;
+ }
+ function p(e) {
+ e.type.indexOf("touch") === -1 && e.preventDefault();
+ var t = i.__hue_field.getBoundingClientRect(), n = 1 - ((e.touches && e.touches[0] || e).clientY - t.top) / (t.bottom - t.top);
+ return n > 1 ? n = 1 : n < 0 && (n = 0), i.__color.h = n * 360, i.setValue(i.__color.toOriginal()), !1;
+ }
+ return r;
+ }
+ return Yd(t, [{
+ key: "updateDisplay",
+ value: function() {
+ var e = Wd(this.getValue());
+ if (e !== !1) {
+ var t = !1;
+ U.each($d.COMPONENTS, function(n) {
+ if (!U.isUndefined(e[n]) && !U.isUndefined(this.__color.__state[n]) && e[n] !== this.__color.__state[n]) return t = !0, {};
+ }, this), t && U.extend(this.__color.__state, e);
+ }
+ U.extend(this.__temp.__state, this.__color.__state), this.__temp.a = 1;
+ var n = this.__color.v < .5 || this.__color.s > .5 ? 255 : 0, r = 255 - n;
+ U.extend(this.__field_knob.style, {
+ marginLeft: 100 * this.__color.s - 7 + "px",
+ marginTop: 100 * (1 - this.__color.v) - 7 + "px",
+ backgroundColor: this.__temp.toHexString(),
+ border: this.__field_knob_border + "rgb(" + n + "," + n + "," + n + ")"
+ }), this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + "px", this.__temp.s = 1, this.__temp.v = 1, bf(this.__saturation_field, "left", "#fff", this.__temp.toHexString()), this.__input.value = this.__color.toString(), U.extend(this.__input.style, {
+ backgroundColor: this.__color.toHexString(),
+ color: "rgb(" + n + "," + n + "," + n + ")",
+ textShadow: this.__input_textShadow + "rgba(" + r + "," + r + "," + r + ",.7)"
+ });
+ }
+ }]), t;
+}(nf), yf = [
+ "-moz-",
+ "-o-",
+ "-webkit-",
+ "-ms-",
+ ""
+];
+function bf(e, t, n, r) {
+ e.style.background = "", U.each(yf, function(i) {
+ e.style.cssText += "background: " + i + "linear-gradient(" + t + ", " + n + " 0%, " + r + " 100%); ";
+ });
+}
+function xf(e) {
+ e.style.background = "", e.style.cssText += "background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);", e.style.cssText += "background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);", e.style.cssText += "background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);", e.style.cssText += "background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);", e.style.cssText += "background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);";
+}
+var Sf = {
+ load: function(e, t) {
+ var n = t || document, r = n.createElement("link");
+ r.type = "text/css", r.rel = "stylesheet", r.href = e, n.getElementsByTagName("head")[0].appendChild(r);
+ },
+ inject: function(e, t) {
+ var n = t || document, r = document.createElement("style");
+ r.type = "text/css", r.innerHTML = e;
+ var i = n.getElementsByTagName("head")[0];
+ try {
+ i.appendChild(r);
+ } catch {}
+ }
+}, Cf = "<div id=\"dg-save\" class=\"dg dialogue\">\n\n Here's the new load parameter for your <code>GUI</code>'s constructor:\n\n <textarea id=\"dg-new-constructor\"></textarea>\n\n <div id=\"dg-save-locally\">\n\n <input id=\"dg-local-storage\" type=\"checkbox\"/> Automatically save\n values to <code>localStorage</code> on exit.\n\n <div id=\"dg-local-explain\">The values saved to <code>localStorage</code> will\n override those passed to <code>dat.GUI</code>'s constructor. This makes it\n easier to work incrementally, but <code>localStorage</code> is fragile,\n and your friends may not see the same values you do.\n\n </div>\n\n </div>\n\n</div>", wf = function(e, t) {
+ var n = e[t];
+ return U.isArray(arguments[2]) || U.isObject(arguments[2]) ? new lf(e, t, arguments[2]) : U.isNumber(n) ? U.isNumber(arguments[2]) && U.isNumber(arguments[3]) ? U.isNumber(arguments[4]) ? new gf(e, t, arguments[2], arguments[3], arguments[4]) : new gf(e, t, arguments[2], arguments[3]) : U.isNumber(arguments[4]) ? new mf(e, t, {
+ min: arguments[2],
+ max: arguments[3],
+ step: arguments[4]
+ }) : new mf(e, t, {
+ min: arguments[2],
+ max: arguments[3]
+ }) : U.isString(n) ? new uf(e, t) : U.isFunction(n) ? new _f(e, t, "") : U.isBoolean(n) ? new cf(e, t) : null;
+};
+function Tf(e) {
+ setTimeout(e, 1e3 / 60);
+}
+var Ef = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || Tf, Df = function() {
+ function e() {
+ Jd(this, e), this.backgroundElement = document.createElement("div"), U.extend(this.backgroundElement.style, {
+ backgroundColor: "rgba(0,0,0,0.8)",
+ top: 0,
+ left: 0,
+ display: "none",
+ zIndex: "1000",
+ opacity: 0,
+ WebkitTransition: "opacity 0.2s linear",
+ transition: "opacity 0.2s linear"
+ }), W.makeFullscreen(this.backgroundElement), this.backgroundElement.style.position = "fixed", this.domElement = document.createElement("div"), U.extend(this.domElement.style, {
+ position: "fixed",
+ display: "none",
+ zIndex: "1001",
+ opacity: 0,
+ WebkitTransition: "-webkit-transform 0.2s ease-out, opacity 0.2s linear",
+ transition: "transform 0.2s ease-out, opacity 0.2s linear"
+ }), document.body.appendChild(this.backgroundElement), document.body.appendChild(this.domElement);
+ var t = this;
+ W.bind(this.backgroundElement, "click", function() {
+ t.hide();
+ });
+ }
+ return Yd(e, [
+ {
+ key: "show",
+ value: function() {
+ var e = this;
+ this.backgroundElement.style.display = "block", this.domElement.style.display = "block", this.domElement.style.opacity = 0, this.domElement.style.webkitTransform = "scale(1.1)", this.layout(), U.defer(function() {
+ e.backgroundElement.style.opacity = 1, e.domElement.style.opacity = 1, e.domElement.style.webkitTransform = "scale(1)";
+ });
+ }
+ },
+ {
+ key: "hide",
+ value: function() {
+ var e = this, t = function t() {
+ e.domElement.style.display = "none", e.backgroundElement.style.display = "none", W.unbind(e.domElement, "webkitTransitionEnd", t), W.unbind(e.domElement, "transitionend", t), W.unbind(e.domElement, "oTransitionEnd", t);
+ };
+ W.bind(this.domElement, "webkitTransitionEnd", t), W.bind(this.domElement, "transitionend", t), W.bind(this.domElement, "oTransitionEnd", t), this.backgroundElement.style.opacity = 0, this.domElement.style.opacity = 0, this.domElement.style.webkitTransform = "scale(1.1)";
+ }
+ },
+ {
+ key: "layout",
+ value: function() {
+ this.domElement.style.left = window.innerWidth / 2 - W.getWidth(this.domElement) / 2 + "px", this.domElement.style.top = window.innerHeight / 2 - W.getHeight(this.domElement) / 2 + "px";
+ }
+ }
+ ]), e;
+}(), Of = Ld(".dg ul{list-style:none;margin:0;padding:0;width:100%;clear:both}.dg.ac{position:fixed;top:0;left:0;right:0;height:0;z-index:0}.dg:not(.ac) .main{overflow:hidden}.dg.main{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear}.dg.main.taller-than-window{overflow-y:auto}.dg.main.taller-than-window .close-button{opacity:1;margin-top:-1px;border-top:1px solid #2c2c2c}.dg.main ul.closed .close-button{opacity:1 !important}.dg.main:hover .close-button,.dg.main .close-button.drag{opacity:1}.dg.main .close-button{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear;border:0;line-height:19px;height:20px;cursor:pointer;text-align:center;background-color:#000}.dg.main .close-button.close-top{position:relative}.dg.main .close-button.close-bottom{position:absolute}.dg.main .close-button:hover{background-color:#111}.dg.a{float:right;margin-right:15px;overflow-y:visible}.dg.a.has-save>ul.close-top{margin-top:0}.dg.a.has-save>ul.close-bottom{margin-top:27px}.dg.a.has-save>ul.closed{margin-top:0}.dg.a .save-row{top:0;z-index:1002}.dg.a .save-row.close-top{position:relative}.dg.a .save-row.close-bottom{position:fixed}.dg li{-webkit-transition:height .1s ease-out;-o-transition:height .1s ease-out;-moz-transition:height .1s ease-out;transition:height .1s ease-out;-webkit-transition:overflow .1s linear;-o-transition:overflow .1s linear;-moz-transition:overflow .1s linear;transition:overflow .1s linear}.dg li:not(.folder){cursor:auto;height:27px;line-height:27px;padding:0 4px 0 5px}.dg li.folder{padding:0;border-left:4px solid rgba(0,0,0,0)}.dg li.title{cursor:pointer;margin-left:-4px}.dg .closed li:not(.title),.dg .closed ul li,.dg .closed ul li>*{height:0;overflow:hidden;border:0}.dg .cr{clear:both;padding-left:3px;height:27px;overflow:hidden}.dg .property-name{cursor:default;float:left;clear:left;width:40%;overflow:hidden;text-overflow:ellipsis}.dg .cr.function .property-name{width:100%}.dg .c{float:left;width:60%;position:relative}.dg .c input[type=text]{border:0;margin-top:4px;padding:3px;width:100%;float:right}.dg .has-slider input[type=text]{width:30%;margin-left:0}.dg .slider{float:left;width:66%;margin-left:-5px;margin-right:0;height:19px;margin-top:4px}.dg .slider-fg{height:100%}.dg .c input[type=checkbox]{margin-top:7px}.dg .c select{margin-top:5px}.dg .cr.function,.dg .cr.function .property-name,.dg .cr.function *,.dg .cr.boolean,.dg .cr.boolean *{cursor:pointer}.dg .cr.color{overflow:visible}.dg .selector{display:none;position:absolute;margin-left:-9px;margin-top:23px;z-index:10}.dg .c:hover .selector,.dg .selector.drag{display:block}.dg li.save-row{padding:0}.dg li.save-row .button{display:inline-block;padding:0px 6px}.dg.dialogue{background-color:#222;width:460px;padding:15px;font-size:13px;line-height:15px}#dg-new-constructor{padding:10px;color:#222;font-family:Monaco, monospace;font-size:10px;border:0;resize:none;box-shadow:inset 1px 1px 1px #888;word-wrap:break-word;margin:12px 0;display:block;width:440px;overflow-y:scroll;height:100px;position:relative}#dg-local-explain{display:none;font-size:11px;line-height:17px;border-radius:3px;background-color:#333;padding:8px;margin-top:10px}#dg-local-explain code{font-size:10px}#dat-gui-save-locally{display:none}.dg{color:#eee;font:11px 'Lucida Grande', sans-serif;text-shadow:0 -1px 0 #111}.dg.main::-webkit-scrollbar{width:5px;background:#1a1a1a}.dg.main::-webkit-scrollbar-corner{height:0;display:none}.dg.main::-webkit-scrollbar-thumb{border-radius:5px;background:#676767}.dg li:not(.folder){background:#1a1a1a;border-bottom:1px solid #2c2c2c}.dg li.save-row{line-height:25px;background:#dad5cb;border:0}.dg li.save-row select{margin-left:5px;width:108px}.dg li.save-row .button{margin-left:5px;margin-top:1px;border-radius:2px;font-size:9px;line-height:7px;padding:4px 4px 5px 4px;background:#c5bdad;color:#fff;text-shadow:0 1px 0 #b0a58f;box-shadow:0 -1px 0 #b0a58f;cursor:pointer}.dg li.save-row .button.gears{background:#c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;height:7px;width:8px}.dg li.save-row .button:hover{background-color:#bab19e;box-shadow:0 -1px 0 #b0a58f}.dg li.folder{border-bottom:0}.dg li.title{padding-left:16px;background:#000 url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.2)}.dg .closed li.title{background-image:url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==)}.dg .cr.boolean{border-left:3px solid #806787}.dg .cr.color{border-left:3px solid}.dg .cr.function{border-left:3px solid #e61d5f}.dg .cr.number{border-left:3px solid #2FA1D6}.dg .cr.number input[type=text]{color:#2FA1D6}.dg .cr.string{border-left:3px solid #1ed36f}.dg .cr.string input[type=text]{color:#1ed36f}.dg .cr.function:hover,.dg .cr.boolean:hover{background:#111}.dg .c input[type=text]{background:#303030;outline:none}.dg .c input[type=text]:hover{background:#3c3c3c}.dg .c input[type=text]:focus{background:#494949;color:#fff}.dg .c .slider{background:#303030;cursor:ew-resize}.dg .c .slider-fg{background:#2FA1D6;max-width:100%}.dg .c .slider:hover{background:#3c3c3c}.dg .c .slider:hover .slider-fg{background:#44abda}\n");
+Sf.inject(Of);
+var kf = "dg", Af = 72, jf = 20, Mf = "Default", Nf = function() {
+ try {
+ return !!window.localStorage;
+ } catch {
+ return !1;
+ }
+}(), Pf = void 0, Ff = !0, If = void 0, Lf = !1, Rf = [], zf = function e(t) {
+ var n = this, r = t || {};
+ this.domElement = document.createElement("div"), this.__ul = document.createElement("ul"), this.domElement.appendChild(this.__ul), W.addClass(this.domElement, kf), this.__folders = {}, this.__controllers = [], this.__rememberedObjects = [], this.__rememberedObjectIndecesToControllers = [], this.__listening = [], r = U.defaults(r, {
+ closeOnTop: !1,
+ autoPlace: !0,
+ width: e.DEFAULT_WIDTH
+ }), r = U.defaults(r, {
+ resizable: r.autoPlace,
+ hideable: r.autoPlace
+ }), U.isUndefined(r.load) ? r.load = { preset: Mf } : r.preset && (r.load.preset = r.preset), U.isUndefined(r.parent) && r.hideable && Rf.push(this), r.resizable = U.isUndefined(r.parent) && r.resizable, r.autoPlace && U.isUndefined(r.scrollable) && (r.scrollable = !0);
+ var i = Nf && localStorage.getItem(Kf(this, "isLocal")) === "true", a = void 0, o = void 0;
+ if (Object.defineProperties(this, {
+ parent: { get: function() {
+ return r.parent;
+ } },
+ scrollable: { get: function() {
+ return r.scrollable;
+ } },
+ autoPlace: { get: function() {
+ return r.autoPlace;
+ } },
+ closeOnTop: { get: function() {
+ return r.closeOnTop;
+ } },
+ preset: {
+ get: function() {
+ return n.parent ? n.getRoot().preset : r.load.preset;
+ },
+ set: function(e) {
+ n.parent ? n.getRoot().preset = e : r.load.preset = e, $f(this), n.revert();
+ }
+ },
+ width: {
+ get: function() {
+ return r.width;
+ },
+ set: function(e) {
+ r.width = e, Zf(n, e);
+ }
+ },
+ name: {
+ get: function() {
+ return r.name;
+ },
+ set: function(e) {
+ r.name = e, o && (o.innerHTML = r.name);
+ }
+ },
+ closed: {
+ get: function() {
+ return r.closed;
+ },
+ set: function(t) {
+ r.closed = t, r.closed ? W.addClass(n.__ul, e.CLASS_CLOSED) : W.removeClass(n.__ul, e.CLASS_CLOSED), this.onResize(), n.__closeButton && (n.__closeButton.innerHTML = t ? e.TEXT_OPEN : e.TEXT_CLOSED);
+ }
+ },
+ load: { get: function() {
+ return r.load;
+ } },
+ useLocalStorage: {
+ get: function() {
+ return i;
+ },
+ set: function(e) {
+ Nf && (i = e, e ? W.bind(window, "unload", a) : W.unbind(window, "unload", a), localStorage.setItem(Kf(n, "isLocal"), e));
+ }
+ }
+ }), U.isUndefined(r.parent)) {
+ if (this.closed = r.closed || !1, W.addClass(this.domElement, e.CLASS_MAIN), W.makeSelectable(this.domElement, !1), Nf && i) {
+ n.useLocalStorage = !0;
+ var s = localStorage.getItem(Kf(this, "gui"));
+ s && (r.load = JSON.parse(s));
+ }
+ this.__closeButton = document.createElement("div"), this.__closeButton.innerHTML = e.TEXT_CLOSED, W.addClass(this.__closeButton, e.CLASS_CLOSE_BUTTON), r.closeOnTop ? (W.addClass(this.__closeButton, e.CLASS_CLOSE_TOP), this.domElement.insertBefore(this.__closeButton, this.domElement.childNodes[0])) : (W.addClass(this.__closeButton, e.CLASS_CLOSE_BOTTOM), this.domElement.appendChild(this.__closeButton)), W.bind(this.__closeButton, "click", function() {
+ n.closed = !n.closed;
+ });
+ } else {
+ r.closed === void 0 && (r.closed = !0);
+ var c = document.createTextNode(r.name);
+ W.addClass(c, "controller-name"), o = Bf(n, c), W.addClass(this.__ul, e.CLASS_CLOSED), W.addClass(o, "title"), W.bind(o, "click", function(e) {
+ return e.preventDefault(), n.closed = !n.closed, !1;
+ }), r.closed || (this.closed = !1);
+ }
+ r.autoPlace && (U.isUndefined(r.parent) && (Ff &&= (If = document.createElement("div"), W.addClass(If, kf), W.addClass(If, e.CLASS_AUTO_PLACE_CONTAINER), document.body.appendChild(If), !1), If.appendChild(this.domElement), W.addClass(this.domElement, e.CLASS_AUTO_PLACE)), this.parent || Zf(n, r.width)), this.__resizeHandler = function() {
+ n.onResizeDebounced();
+ }, W.bind(window, "resize", this.__resizeHandler), W.bind(this.__ul, "webkitTransitionEnd", this.__resizeHandler), W.bind(this.__ul, "transitionend", this.__resizeHandler), W.bind(this.__ul, "oTransitionEnd", this.__resizeHandler), this.onResize(), r.resizable && Xf(this), a = function() {
+ Nf && localStorage.getItem(Kf(n, "isLocal")) === "true" && localStorage.setItem(Kf(n, "gui"), JSON.stringify(n.getSaveObject()));
+ }, this.saveToLocalStorageIfPossible = a;
+ function l() {
+ var e = n.getRoot();
+ e.width += 1, U.defer(function() {
+ --e.width;
+ });
+ }
+ r.parent || l();
+};
+zf.toggleHide = function() {
+ Lf = !Lf, U.each(Rf, function(e) {
+ e.domElement.style.display = Lf ? "none" : "";
+ });
+}, zf.CLASS_AUTO_PLACE = "a", zf.CLASS_AUTO_PLACE_CONTAINER = "ac", zf.CLASS_MAIN = "main", zf.CLASS_CONTROLLER_ROW = "cr", zf.CLASS_TOO_TALL = "taller-than-window", zf.CLASS_CLOSED = "closed", zf.CLASS_CLOSE_BUTTON = "close-button", zf.CLASS_CLOSE_TOP = "close-top", zf.CLASS_CLOSE_BOTTOM = "close-bottom", zf.CLASS_DRAG = "drag", zf.DEFAULT_WIDTH = 245, zf.TEXT_CLOSED = "Close Controls", zf.TEXT_OPEN = "Open Controls", zf._keydownHandler = function(e) {
+ document.activeElement.type !== "text" && (e.which === Af || e.keyCode === Af) && zf.toggleHide();
+}, W.bind(window, "keydown", zf._keydownHandler, !1), U.extend(zf.prototype, {
+ add: function(e, t) {
+ return Gf(this, e, t, { factoryArgs: Array.prototype.slice.call(arguments, 2) });
+ },
+ addColor: function(e, t) {
+ return Gf(this, e, t, { color: !0 });
+ },
+ remove: function(e) {
+ this.__ul.removeChild(e.__li), this.__controllers.splice(this.__controllers.indexOf(e), 1);
+ var t = this;
+ U.defer(function() {
+ t.onResize();
+ });
+ },
+ destroy: function() {
+ if (this.parent) throw Error("Only the root GUI should be removed with .destroy(). For subfolders, use gui.removeFolder(folder) instead.");
+ this.autoPlace && If.removeChild(this.domElement);
+ var e = this;
+ U.each(this.__folders, function(t) {
+ e.removeFolder(t);
+ }), W.unbind(window, "keydown", zf._keydownHandler, !1), Vf(this);
+ },
+ addFolder: function(e) {
+ if (this.__folders[e] !== void 0) throw Error("You already have a folder in this GUI by the name \"" + e + "\"");
+ var t = {
+ name: e,
+ parent: this
+ };
+ t.autoPlace = this.autoPlace, this.load && this.load.folders && this.load.folders[e] && (t.closed = this.load.folders[e].closed, t.load = this.load.folders[e]);
+ var n = new zf(t);
+ this.__folders[e] = n;
+ var r = Bf(this, n.domElement);
+ return W.addClass(r, "folder"), n;
+ },
+ removeFolder: function(e) {
+ this.__ul.removeChild(e.domElement.parentElement), delete this.__folders[e.name], this.load && this.load.folders && this.load.folders[e.name] && delete this.load.folders[e.name], Vf(e);
+ var t = this;
+ U.each(e.__folders, function(t) {
+ e.removeFolder(t);
+ }), U.defer(function() {
+ t.onResize();
+ });
+ },
+ open: function() {
+ this.closed = !1;
+ },
+ close: function() {
+ this.closed = !0;
+ },
+ hide: function() {
+ this.domElement.style.display = "none";
+ },
+ show: function() {
+ this.domElement.style.display = "";
+ },
+ onResize: function() {
+ var e = this.getRoot();
+ if (e.scrollable) {
+ var t = W.getOffset(e.__ul).top, n = 0;
+ U.each(e.__ul.childNodes, function(t) {
+ e.autoPlace && t === e.__save_row || (n += W.getHeight(t));
+ }), window.innerHeight - t - jf < n ? (W.addClass(e.domElement, zf.CLASS_TOO_TALL), e.__ul.style.height = window.innerHeight - t - jf + "px") : (W.removeClass(e.domElement, zf.CLASS_TOO_TALL), e.__ul.style.height = "auto");
+ }
+ e.__resize_handle && U.defer(function() {
+ e.__resize_handle.style.height = e.__ul.offsetHeight + "px";
+ }), e.__closeButton && (e.__closeButton.style.width = e.width + "px");
+ },
+ onResizeDebounced: U.debounce(function() {
+ this.onResize();
+ }, 50),
+ remember: function() {
+ if (U.isUndefined(Pf) && (Pf = new Df(), Pf.domElement.innerHTML = Cf), this.parent) throw Error("You can only call remember on a top level GUI.");
+ var e = this;
+ U.each(Array.prototype.slice.call(arguments), function(t) {
+ e.__rememberedObjects.length === 0 && Yf(e), e.__rememberedObjects.indexOf(t) === -1 && e.__rememberedObjects.push(t);
+ }), this.autoPlace && Zf(this, this.width);
+ },
+ getRoot: function() {
+ for (var e = this; e.parent;) e = e.parent;
+ return e;
+ },
+ getSaveObject: function() {
+ var e = this.load;
+ return e.closed = this.closed, this.__rememberedObjects.length > 0 && (e.preset = this.preset, e.remembered ||= {}, e.remembered[this.preset] = Qf(this)), e.folders = {}, U.each(this.__folders, function(t, n) {
+ e.folders[n] = t.getSaveObject();
+ }), e;
+ },
+ save: function() {
+ this.load.remembered || (this.load.remembered = {}), this.load.remembered[this.preset] = Qf(this), Hf(this, !1), this.saveToLocalStorageIfPossible();
+ },
+ saveAs: function(e) {
+ this.load.remembered || (this.load.remembered = {}, this.load.remembered[Mf] = Qf(this, !0)), this.load.remembered[e] = Qf(this), this.preset = e, qf(this, e, !0), this.saveToLocalStorageIfPossible();
+ },
+ revert: function(e) {
+ U.each(this.__controllers, function(t) {
+ this.getRoot().load.remembered ? Wf(e || this.getRoot(), t) : t.setValue(t.initialValue), t.__onFinishChange && t.__onFinishChange.call(t, t.getValue());
+ }, this), U.each(this.__folders, function(e) {
+ e.revert(e);
+ }), e || Hf(this.getRoot(), !1);
+ },
+ listen: function(e) {
+ var t = this.__listening.length === 0;
+ this.__listening.push(e), t && ep(this.__listening);
+ },
+ updateDisplay: function() {
+ U.each(this.__controllers, function(e) {
+ e.updateDisplay();
+ }), U.each(this.__folders, function(e) {
+ e.updateDisplay();
+ });
+ }
+});
+function Bf(e, t, n) {
+ var r = document.createElement("li");
+ return t && r.appendChild(t), n ? e.__ul.insertBefore(r, n) : e.__ul.appendChild(r), e.onResize(), r;
+}
+function Vf(e) {
+ W.unbind(window, "resize", e.__resizeHandler), e.saveToLocalStorageIfPossible && W.unbind(window, "unload", e.saveToLocalStorageIfPossible);
+}
+function Hf(e, t) {
+ var n = e.__preset_select[e.__preset_select.selectedIndex];
+ t ? n.innerHTML = n.value + "*" : n.innerHTML = n.value;
+}
+function Uf(e, t, n) {
+ if (n.__li = t, n.__gui = e, U.extend(n, {
+ options: function(t) {
+ if (arguments.length > 1) {
+ var r = n.__li.nextElementSibling;
+ return n.remove(), Gf(e, n.object, n.property, {
+ before: r,
+ factoryArgs: [U.toArray(arguments)]
+ });
+ }
+ if (U.isArray(t) || U.isObject(t)) {
+ var i = n.__li.nextElementSibling;
+ return n.remove(), Gf(e, n.object, n.property, {
+ before: i,
+ factoryArgs: [t]
+ });
+ }
+ },
+ name: function(e) {
+ return n.__li.firstElementChild.firstElementChild.innerHTML = e, n;
+ },
+ listen: function() {
+ return n.__gui.listen(n), n;
+ },
+ remove: function() {
+ return n.__gui.remove(n), n;
+ }
+ }), n instanceof gf) {
+ var r = new mf(n.object, n.property, {
+ min: n.__min,
+ max: n.__max,
+ step: n.__step
+ });
+ U.each([
+ "updateDisplay",
+ "onChange",
+ "onFinishChange",
+ "step",
+ "min",
+ "max"
+ ], function(e) {
+ var t = n[e], i = r[e];
+ n[e] = r[e] = function() {
+ var e = Array.prototype.slice.call(arguments);
+ return i.apply(r, e), t.apply(n, e);
+ };
+ }), W.addClass(t, "has-slider"), n.domElement.insertBefore(r.domElement, n.domElement.firstElementChild);
+ } else if (n instanceof mf) {
+ var i = function(t) {
+ if (U.isNumber(n.__min) && U.isNumber(n.__max)) {
+ var r = n.__li.firstElementChild.firstElementChild.innerHTML, i = n.__gui.__listening.indexOf(n) > -1;
+ n.remove();
+ var a = Gf(e, n.object, n.property, {
+ before: n.__li.nextElementSibling,
+ factoryArgs: [
+ n.__min,
+ n.__max,
+ n.__step
+ ]
+ });
+ return a.name(r), i && a.listen(), a;
+ }
+ return t;
+ };
+ n.min = U.compose(i, n.min), n.max = U.compose(i, n.max);
+ } else n instanceof cf ? (W.bind(t, "click", function() {
+ W.fakeEvent(n.__checkbox, "click");
+ }), W.bind(n.__checkbox, "click", function(e) {
+ e.stopPropagation();
+ })) : n instanceof _f ? (W.bind(t, "click", function() {
+ W.fakeEvent(n.__button, "click");
+ }), W.bind(t, "mouseover", function() {
+ W.addClass(n.__button, "hover");
+ }), W.bind(t, "mouseout", function() {
+ W.removeClass(n.__button, "hover");
+ })) : n instanceof vf && (W.addClass(t, "color"), n.updateDisplay = U.compose(function(e) {
+ return t.style.borderLeftColor = n.__color.toString(), e;
+ }, n.updateDisplay), n.updateDisplay());
+ n.setValue = U.compose(function(t) {
+ return e.getRoot().__preset_select && n.isModified() && Hf(e.getRoot(), !0), t;
+ }, n.setValue);
+}
+function Wf(e, t) {
+ var n = e.getRoot(), r = n.__rememberedObjects.indexOf(t.object);
+ if (r !== -1) {
+ var i = n.__rememberedObjectIndecesToControllers[r];
+ if (i === void 0 && (i = {}, n.__rememberedObjectIndecesToControllers[r] = i), i[t.property] = t, n.load && n.load.remembered) {
+ var a = n.load.remembered, o = void 0;
+ if (a[e.preset]) o = a[e.preset];
+ else if (a[Mf]) o = a[Mf];
+ else return;
+ if (o[r] && o[r][t.property] !== void 0) {
+ var s = o[r][t.property];
+ t.initialValue = s, t.setValue(s);
+ }
+ }
+ }
+}
+function Gf(e, t, n, r) {
+ if (t[n] === void 0) throw Error("Object \"" + t + "\" has no property \"" + n + "\"");
+ var i = void 0;
+ if (r.color) i = new vf(t, n);
+ else {
+ var a = [t, n].concat(r.factoryArgs);
+ i = wf.apply(e, a);
+ }
+ r.before instanceof nf && (r.before = r.before.__li), Wf(e, i), W.addClass(i.domElement, "c");
+ var o = document.createElement("span");
+ W.addClass(o, "property-name"), o.innerHTML = i.property;
+ var s = document.createElement("div");
+ s.appendChild(o), s.appendChild(i.domElement);
+ var c = Bf(e, s, r.before);
+ return W.addClass(c, zf.CLASS_CONTROLLER_ROW), i instanceof vf ? W.addClass(c, "color") : W.addClass(c, qd(i.getValue())), Uf(e, c, i), e.__controllers.push(i), i;
+}
+function Kf(e, t) {
+ return document.location.href + "." + t;
+}
+function qf(e, t, n) {
+ var r = document.createElement("option");
+ r.innerHTML = t, r.value = t, e.__preset_select.appendChild(r), n && (e.__preset_select.selectedIndex = e.__preset_select.length - 1);
+}
+function Jf(e, t) {
+ t.style.display = e.useLocalStorage ? "block" : "none";
+}
+function Yf(e) {
+ var t = e.__save_row = document.createElement("li");
+ W.addClass(e.domElement, "has-save"), e.__ul.insertBefore(t, e.__ul.firstChild), W.addClass(t, "save-row");
+ var n = document.createElement("span");
+ n.innerHTML = "&nbsp;", W.addClass(n, "button gears");
+ var r = document.createElement("span");
+ r.innerHTML = "Save", W.addClass(r, "button"), W.addClass(r, "save");
+ var i = document.createElement("span");
+ i.innerHTML = "New", W.addClass(i, "button"), W.addClass(i, "save-as");
+ var a = document.createElement("span");
+ a.innerHTML = "Revert", W.addClass(a, "button"), W.addClass(a, "revert");
+ var o = e.__preset_select = document.createElement("select");
+ if (e.load && e.load.remembered ? U.each(e.load.remembered, function(t, n) {
+ qf(e, n, n === e.preset);
+ }) : qf(e, Mf, !1), W.bind(o, "change", function() {
+ for (var t = 0; t < e.__preset_select.length; t++) e.__preset_select[t].innerHTML = e.__preset_select[t].value;
+ e.preset = this.value;
+ }), t.appendChild(o), t.appendChild(n), t.appendChild(r), t.appendChild(i), t.appendChild(a), Nf) {
+ var s = document.getElementById("dg-local-explain"), c = document.getElementById("dg-local-storage"), l = document.getElementById("dg-save-locally");
+ l.style.display = "block", localStorage.getItem(Kf(e, "isLocal")) === "true" && c.setAttribute("checked", "checked"), Jf(e, s), W.bind(c, "change", function() {
+ e.useLocalStorage = !e.useLocalStorage, Jf(e, s);
+ });
+ }
+ var u = document.getElementById("dg-new-constructor");
+ W.bind(u, "keydown", function(e) {
+ e.metaKey && (e.which === 67 || e.keyCode === 67) && Pf.hide();
+ }), W.bind(n, "click", function() {
+ u.innerHTML = JSON.stringify(e.getSaveObject(), void 0, 2), Pf.show(), u.focus(), u.select();
+ }), W.bind(r, "click", function() {
+ e.save();
+ }), W.bind(i, "click", function() {
+ var t = prompt("Enter a new preset name.");
+ t && e.saveAs(t);
+ }), W.bind(a, "click", function() {
+ e.revert();
+ });
+}
+function Xf(e) {
+ var t = void 0;
+ e.__resize_handle = document.createElement("div"), U.extend(e.__resize_handle.style, {
+ width: "6px",
+ marginLeft: "-3px",
+ height: "200px",
+ cursor: "ew-resize",
+ position: "absolute"
+ });
+ function n(n) {
+ return n.preventDefault(), e.width += t - n.clientX, e.onResize(), t = n.clientX, !1;
+ }
+ function r() {
+ W.removeClass(e.__closeButton, zf.CLASS_DRAG), W.unbind(window, "mousemove", n), W.unbind(window, "mouseup", r);
+ }
+ function i(i) {
+ return i.preventDefault(), t = i.clientX, W.addClass(e.__closeButton, zf.CLASS_DRAG), W.bind(window, "mousemove", n), W.bind(window, "mouseup", r), !1;
+ }
+ W.bind(e.__resize_handle, "mousedown", i), W.bind(e.__closeButton, "mousedown", i), e.domElement.insertBefore(e.__resize_handle, e.domElement.firstElementChild);
+}
+function Zf(e, t) {
+ e.domElement.style.width = t + "px", e.__save_row && e.autoPlace && (e.__save_row.style.width = t + "px"), e.__closeButton && (e.__closeButton.style.width = t + "px");
+}
+function Qf(e, t) {
+ var n = {};
+ return U.each(e.__rememberedObjects, function(r, i) {
+ var a = {}, o = e.__rememberedObjectIndecesToControllers[i];
+ U.each(o, function(e, n) {
+ a[n] = t ? e.initialValue : e.getValue();
+ }), n[i] = a;
+ }), n;
+}
+function $f(e) {
+ for (var t = 0; t < e.__preset_select.length; t++) e.__preset_select[t].value === e.preset && (e.__preset_select.selectedIndex = t);
+}
+function ep(e) {
+ e.length !== 0 && Ef.call(window, function() {
+ ep(e);
+ }), U.each(e, function(e) {
+ e.updateDisplay();
+ });
+}
+var tp = zf, np = [
+ {
+ id: "",
+ name: "None",
+ path: null
+ },
+ {
+ id: "neutral",
+ name: "Neutral",
+ path: null
+ },
+ {
+ id: "venice-sunset",
+ name: "Venice Sunset",
+ path: "https://storage.googleapis.com/donmccurdy-static/venice_sunset_1k.exr",
+ format: ".exr"
+ },
+ {
+ id: "footprint-court",
+ name: "Footprint Court (HDR Labs)",
+ path: "https://storage.googleapis.com/donmccurdy-static/footprint_court_2k.exr",
+ format: ".exr"
+ }
+], rp = /* @__PURE__ */ "BN.BN.BN.BN.BN.BN.BN.BN.BN.S.B.S.WS.B.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.B.B.B.S.WS.ON.ON.ET.ET.ET.ON.ON.ON.ON.ON.ES.CS.ES.CS.CS.EN.EN.EN.EN.EN.EN.EN.EN.EN.EN.CS.ON.ON.ON.ON.ON.ON.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.ON.ON.ON.ON.ON.ON.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.ON.ON.ON.ON.BN.BN.BN.BN.BN.BN.B.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.CS.ON.ET.ET.ET.ET.ON.ON.ON.ON.L.ON.ON.BN.ON.ON.ET.ET.EN.EN.ON.L.ON.ON.ON.EN.L.ON.ON.ON.ON.ON.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.ON.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.ON.L.L.L.L.L.L.L.L".split("."), ip = [
+ [
+ 697,
+ 698,
+ "ON"
+ ],
+ [
+ 706,
+ 719,
+ "ON"
+ ],
+ [
+ 722,
+ 735,
+ "ON"
+ ],
+ [
+ 741,
+ 749,
+ "ON"
+ ],
+ [
+ 751,
+ 767,
+ "ON"
+ ],
+ [
+ 768,
+ 879,
+ "NSM"
+ ],
+ [
+ 884,
+ 885,
+ "ON"
+ ],
+ [
+ 894,
+ 894,
+ "ON"
+ ],
+ [
+ 900,
+ 901,
+ "ON"
+ ],
+ [
+ 903,
+ 903,
+ "ON"
+ ],
+ [
+ 1014,
+ 1014,
+ "ON"
+ ],
+ [
+ 1155,
+ 1161,
+ "NSM"
+ ],
+ [
+ 1418,
+ 1418,
+ "ON"
+ ],
+ [
+ 1421,
+ 1422,
+ "ON"
+ ],
+ [
+ 1423,
+ 1423,
+ "ET"
+ ],
+ [
+ 1424,
+ 1424,
+ "R"
+ ],
+ [
+ 1425,
+ 1469,
+ "NSM"
+ ],
+ [
+ 1470,
+ 1470,
+ "R"
+ ],
+ [
+ 1471,
+ 1471,
+ "NSM"
+ ],
+ [
+ 1472,
+ 1472,
+ "R"
+ ],
+ [
+ 1473,
+ 1474,
+ "NSM"
+ ],
+ [
+ 1475,
+ 1475,
+ "R"
+ ],
+ [
+ 1476,
+ 1477,
+ "NSM"
+ ],
+ [
+ 1478,
+ 1478,
+ "R"
+ ],
+ [
+ 1479,
+ 1479,
+ "NSM"
+ ],
+ [
+ 1480,
+ 1535,
+ "R"
+ ],
+ [
+ 1536,
+ 1541,
+ "AN"
+ ],
+ [
+ 1542,
+ 1543,
+ "ON"
+ ],
+ [
+ 1544,
+ 1544,
+ "AL"
+ ],
+ [
+ 1545,
+ 1546,
+ "ET"
+ ],
+ [
+ 1547,
+ 1547,
+ "AL"
+ ],
+ [
+ 1548,
+ 1548,
+ "CS"
+ ],
+ [
+ 1549,
+ 1549,
+ "AL"
+ ],
+ [
+ 1550,
+ 1551,
+ "ON"
+ ],
+ [
+ 1552,
+ 1562,
+ "NSM"
+ ],
+ [
+ 1563,
+ 1610,
+ "AL"
+ ],
+ [
+ 1611,
+ 1631,
+ "NSM"
+ ],
+ [
+ 1632,
+ 1641,
+ "AN"
+ ],
+ [
+ 1642,
+ 1642,
+ "ET"
+ ],
+ [
+ 1643,
+ 1644,
+ "AN"
+ ],
+ [
+ 1645,
+ 1647,
+ "AL"
+ ],
+ [
+ 1648,
+ 1648,
+ "NSM"
+ ],
+ [
+ 1649,
+ 1749,
+ "AL"
+ ],
+ [
+ 1750,
+ 1756,
+ "NSM"
+ ],
+ [
+ 1757,
+ 1757,
+ "AN"
+ ],
+ [
+ 1758,
+ 1758,
+ "ON"
+ ],
+ [
+ 1759,
+ 1764,
+ "NSM"
+ ],
+ [
+ 1765,
+ 1766,
+ "AL"
+ ],
+ [
+ 1767,
+ 1768,
+ "NSM"
+ ],
+ [
+ 1769,
+ 1769,
+ "ON"
+ ],
+ [
+ 1770,
+ 1773,
+ "NSM"
+ ],
+ [
+ 1774,
+ 1775,
+ "AL"
+ ],
+ [
+ 1776,
+ 1785,
+ "EN"
+ ],
+ [
+ 1786,
+ 1808,
+ "AL"
+ ],
+ [
+ 1809,
+ 1809,
+ "NSM"
+ ],
+ [
+ 1810,
+ 1839,
+ "AL"
+ ],
+ [
+ 1840,
+ 1866,
+ "NSM"
+ ],
+ [
+ 1867,
+ 1957,
+ "AL"
+ ],
+ [
+ 1958,
+ 1968,
+ "NSM"
+ ],
+ [
+ 1969,
+ 1983,
+ "AL"
+ ],
+ [
+ 1984,
+ 2026,
+ "R"
+ ],
+ [
+ 2027,
+ 2035,
+ "NSM"
+ ],
+ [
+ 2036,
+ 2037,
+ "R"
+ ],
+ [
+ 2038,
+ 2041,
+ "ON"
+ ],
+ [
+ 2042,
+ 2044,
+ "R"
+ ],
+ [
+ 2045,
+ 2045,
+ "NSM"
+ ],
+ [
+ 2046,
+ 2069,
+ "R"
+ ],
+ [
+ 2070,
+ 2073,
+ "NSM"
+ ],
+ [
+ 2074,
+ 2074,
+ "R"
+ ],
+ [
+ 2075,
+ 2083,
+ "NSM"
+ ],
+ [
+ 2084,
+ 2084,
+ "R"
+ ],
+ [
+ 2085,
+ 2087,
+ "NSM"
+ ],
+ [
+ 2088,
+ 2088,
+ "R"
+ ],
+ [
+ 2089,
+ 2093,
+ "NSM"
+ ],
+ [
+ 2094,
+ 2136,
+ "R"
+ ],
+ [
+ 2137,
+ 2139,
+ "NSM"
+ ],
+ [
+ 2140,
+ 2143,
+ "R"
+ ],
+ [
+ 2144,
+ 2191,
+ "AL"
+ ],
+ [
+ 2192,
+ 2193,
+ "AN"
+ ],
+ [
+ 2194,
+ 2198,
+ "AL"
+ ],
+ [
+ 2199,
+ 2207,
+ "NSM"
+ ],
+ [
+ 2208,
+ 2249,
+ "AL"
+ ],
+ [
+ 2250,
+ 2273,
+ "NSM"
+ ],
+ [
+ 2274,
+ 2274,
+ "AN"
+ ],
+ [
+ 2275,
+ 2306,
+ "NSM"
+ ],
+ [
+ 2362,
+ 2362,
+ "NSM"
+ ],
+ [
+ 2364,
+ 2364,
+ "NSM"
+ ],
+ [
+ 2369,
+ 2376,
+ "NSM"
+ ],
+ [
+ 2381,
+ 2381,
+ "NSM"
+ ],
+ [
+ 2385,
+ 2391,
+ "NSM"
+ ],
+ [
+ 2402,
+ 2403,
+ "NSM"
+ ],
+ [
+ 2433,
+ 2433,
+ "NSM"
+ ],
+ [
+ 2492,
+ 2492,
+ "NSM"
+ ],
+ [
+ 2497,
+ 2500,
+ "NSM"
+ ],
+ [
+ 2509,
+ 2509,
+ "NSM"
+ ],
+ [
+ 2530,
+ 2531,
+ "NSM"
+ ],
+ [
+ 2546,
+ 2547,
+ "ET"
+ ],
+ [
+ 2555,
+ 2555,
+ "ET"
+ ],
+ [
+ 2558,
+ 2558,
+ "NSM"
+ ],
+ [
+ 2561,
+ 2562,
+ "NSM"
+ ],
+ [
+ 2620,
+ 2620,
+ "NSM"
+ ],
+ [
+ 2625,
+ 2626,
+ "NSM"
+ ],
+ [
+ 2631,
+ 2632,
+ "NSM"
+ ],
+ [
+ 2635,
+ 2637,
+ "NSM"
+ ],
+ [
+ 2641,
+ 2641,
+ "NSM"
+ ],
+ [
+ 2672,
+ 2673,
+ "NSM"
+ ],
+ [
+ 2677,
+ 2677,
+ "NSM"
+ ],
+ [
+ 2689,
+ 2690,
+ "NSM"
+ ],
+ [
+ 2748,
+ 2748,
+ "NSM"
+ ],
+ [
+ 2753,
+ 2757,
+ "NSM"
+ ],
+ [
+ 2759,
+ 2760,
+ "NSM"
+ ],
+ [
+ 2765,
+ 2765,
+ "NSM"
+ ],
+ [
+ 2786,
+ 2787,
+ "NSM"
+ ],
+ [
+ 2801,
+ 2801,
+ "ET"
+ ],
+ [
+ 2810,
+ 2815,
+ "NSM"
+ ],
+ [
+ 2817,
+ 2817,
+ "NSM"
+ ],
+ [
+ 2876,
+ 2876,
+ "NSM"
+ ],
+ [
+ 2879,
+ 2879,
+ "NSM"
+ ],
+ [
+ 2881,
+ 2884,
+ "NSM"
+ ],
+ [
+ 2893,
+ 2893,
+ "NSM"
+ ],
+ [
+ 2901,
+ 2902,
+ "NSM"
+ ],
+ [
+ 2914,
+ 2915,
+ "NSM"
+ ],
+ [
+ 2946,
+ 2946,
+ "NSM"
+ ],
+ [
+ 3008,
+ 3008,
+ "NSM"
+ ],
+ [
+ 3021,
+ 3021,
+ "NSM"
+ ],
+ [
+ 3059,
+ 3064,
+ "ON"
+ ],
+ [
+ 3065,
+ 3065,
+ "ET"
+ ],
+ [
+ 3066,
+ 3066,
+ "ON"
+ ],
+ [
+ 3072,
+ 3072,
+ "NSM"
+ ],
+ [
+ 3076,
+ 3076,
+ "NSM"
+ ],
+ [
+ 3132,
+ 3132,
+ "NSM"
+ ],
+ [
+ 3134,
+ 3136,
+ "NSM"
+ ],
+ [
+ 3142,
+ 3144,
+ "NSM"
+ ],
+ [
+ 3146,
+ 3149,
+ "NSM"
+ ],
+ [
+ 3157,
+ 3158,
+ "NSM"
+ ],
+ [
+ 3170,
+ 3171,
+ "NSM"
+ ],
+ [
+ 3192,
+ 3198,
+ "ON"
+ ],
+ [
+ 3201,
+ 3201,
+ "NSM"
+ ],
+ [
+ 3260,
+ 3260,
+ "NSM"
+ ],
+ [
+ 3276,
+ 3277,
+ "NSM"
+ ],
+ [
+ 3298,
+ 3299,
+ "NSM"
+ ],
+ [
+ 3328,
+ 3329,
+ "NSM"
+ ],
+ [
+ 3387,
+ 3388,
+ "NSM"
+ ],
+ [
+ 3393,
+ 3396,
+ "NSM"
+ ],
+ [
+ 3405,
+ 3405,
+ "NSM"
+ ],
+ [
+ 3426,
+ 3427,
+ "NSM"
+ ],
+ [
+ 3457,
+ 3457,
+ "NSM"
+ ],
+ [
+ 3530,
+ 3530,
+ "NSM"
+ ],
+ [
+ 3538,
+ 3540,
+ "NSM"
+ ],
+ [
+ 3542,
+ 3542,
+ "NSM"
+ ],
+ [
+ 3633,
+ 3633,
+ "NSM"
+ ],
+ [
+ 3636,
+ 3642,
+ "NSM"
+ ],
+ [
+ 3647,
+ 3647,
+ "ET"
+ ],
+ [
+ 3655,
+ 3662,
+ "NSM"
+ ],
+ [
+ 3761,
+ 3761,
+ "NSM"
+ ],
+ [
+ 3764,
+ 3772,
+ "NSM"
+ ],
+ [
+ 3784,
+ 3790,
+ "NSM"
+ ],
+ [
+ 3864,
+ 3865,
+ "NSM"
+ ],
+ [
+ 3893,
+ 3893,
+ "NSM"
+ ],
+ [
+ 3895,
+ 3895,
+ "NSM"
+ ],
+ [
+ 3897,
+ 3897,
+ "NSM"
+ ],
+ [
+ 3898,
+ 3901,
+ "ON"
+ ],
+ [
+ 3953,
+ 3966,
+ "NSM"
+ ],
+ [
+ 3968,
+ 3972,
+ "NSM"
+ ],
+ [
+ 3974,
+ 3975,
+ "NSM"
+ ],
+ [
+ 3981,
+ 3991,
+ "NSM"
+ ],
+ [
+ 3993,
+ 4028,
+ "NSM"
+ ],
+ [
+ 4038,
+ 4038,
+ "NSM"
+ ],
+ [
+ 4141,
+ 4144,
+ "NSM"
+ ],
+ [
+ 4146,
+ 4151,
+ "NSM"
+ ],
+ [
+ 4153,
+ 4154,
+ "NSM"
+ ],
+ [
+ 4157,
+ 4158,
+ "NSM"
+ ],
+ [
+ 4184,
+ 4185,
+ "NSM"
+ ],
+ [
+ 4190,
+ 4192,
+ "NSM"
+ ],
+ [
+ 4209,
+ 4212,
+ "NSM"
+ ],
+ [
+ 4226,
+ 4226,
+ "NSM"
+ ],
+ [
+ 4229,
+ 4230,
+ "NSM"
+ ],
+ [
+ 4237,
+ 4237,
+ "NSM"
+ ],
+ [
+ 4253,
+ 4253,
+ "NSM"
+ ],
+ [
+ 4957,
+ 4959,
+ "NSM"
+ ],
+ [
+ 5008,
+ 5017,
+ "ON"
+ ],
+ [
+ 5120,
+ 5120,
+ "ON"
+ ],
+ [
+ 5760,
+ 5760,
+ "WS"
+ ],
+ [
+ 5787,
+ 5788,
+ "ON"
+ ],
+ [
+ 5906,
+ 5908,
+ "NSM"
+ ],
+ [
+ 5938,
+ 5939,
+ "NSM"
+ ],
+ [
+ 5970,
+ 5971,
+ "NSM"
+ ],
+ [
+ 6002,
+ 6003,
+ "NSM"
+ ],
+ [
+ 6068,
+ 6069,
+ "NSM"
+ ],
+ [
+ 6071,
+ 6077,
+ "NSM"
+ ],
+ [
+ 6086,
+ 6086,
+ "NSM"
+ ],
+ [
+ 6089,
+ 6099,
+ "NSM"
+ ],
+ [
+ 6107,
+ 6107,
+ "ET"
+ ],
+ [
+ 6109,
+ 6109,
+ "NSM"
+ ],
+ [
+ 6128,
+ 6137,
+ "ON"
+ ],
+ [
+ 6144,
+ 6154,
+ "ON"
+ ],
+ [
+ 6155,
+ 6157,
+ "NSM"
+ ],
+ [
+ 6158,
+ 6158,
+ "BN"
+ ],
+ [
+ 6159,
+ 6159,
+ "NSM"
+ ],
+ [
+ 6277,
+ 6278,
+ "NSM"
+ ],
+ [
+ 6313,
+ 6313,
+ "NSM"
+ ],
+ [
+ 6432,
+ 6434,
+ "NSM"
+ ],
+ [
+ 6439,
+ 6440,
+ "NSM"
+ ],
+ [
+ 6450,
+ 6450,
+ "NSM"
+ ],
+ [
+ 6457,
+ 6459,
+ "NSM"
+ ],
+ [
+ 6464,
+ 6464,
+ "ON"
+ ],
+ [
+ 6468,
+ 6469,
+ "ON"
+ ],
+ [
+ 6622,
+ 6655,
+ "ON"
+ ],
+ [
+ 6679,
+ 6680,
+ "NSM"
+ ],
+ [
+ 6683,
+ 6683,
+ "NSM"
+ ],
+ [
+ 6742,
+ 6742,
+ "NSM"
+ ],
+ [
+ 6744,
+ 6750,
+ "NSM"
+ ],
+ [
+ 6752,
+ 6752,
+ "NSM"
+ ],
+ [
+ 6754,
+ 6754,
+ "NSM"
+ ],
+ [
+ 6757,
+ 6764,
+ "NSM"
+ ],
+ [
+ 6771,
+ 6780,
+ "NSM"
+ ],
+ [
+ 6783,
+ 6783,
+ "NSM"
+ ],
+ [
+ 6832,
+ 6877,
+ "NSM"
+ ],
+ [
+ 6880,
+ 6891,
+ "NSM"
+ ],
+ [
+ 6912,
+ 6915,
+ "NSM"
+ ],
+ [
+ 6964,
+ 6964,
+ "NSM"
+ ],
+ [
+ 6966,
+ 6970,
+ "NSM"
+ ],
+ [
+ 6972,
+ 6972,
+ "NSM"
+ ],
+ [
+ 6978,
+ 6978,
+ "NSM"
+ ],
+ [
+ 7019,
+ 7027,
+ "NSM"
+ ],
+ [
+ 7040,
+ 7041,
+ "NSM"
+ ],
+ [
+ 7074,
+ 7077,
+ "NSM"
+ ],
+ [
+ 7080,
+ 7081,
+ "NSM"
+ ],
+ [
+ 7083,
+ 7085,
+ "NSM"
+ ],
+ [
+ 7142,
+ 7142,
+ "NSM"
+ ],
+ [
+ 7144,
+ 7145,
+ "NSM"
+ ],
+ [
+ 7149,
+ 7149,
+ "NSM"
+ ],
+ [
+ 7151,
+ 7153,
+ "NSM"
+ ],
+ [
+ 7212,
+ 7219,
+ "NSM"
+ ],
+ [
+ 7222,
+ 7223,
+ "NSM"
+ ],
+ [
+ 7376,
+ 7378,
+ "NSM"
+ ],
+ [
+ 7380,
+ 7392,
+ "NSM"
+ ],
+ [
+ 7394,
+ 7400,
+ "NSM"
+ ],
+ [
+ 7405,
+ 7405,
+ "NSM"
+ ],
+ [
+ 7412,
+ 7412,
+ "NSM"
+ ],
+ [
+ 7416,
+ 7417,
+ "NSM"
+ ],
+ [
+ 7616,
+ 7679,
+ "NSM"
+ ],
+ [
+ 8125,
+ 8125,
+ "ON"
+ ],
+ [
+ 8127,
+ 8129,
+ "ON"
+ ],
+ [
+ 8141,
+ 8143,
+ "ON"
+ ],
+ [
+ 8157,
+ 8159,
+ "ON"
+ ],
+ [
+ 8173,
+ 8175,
+ "ON"
+ ],
+ [
+ 8189,
+ 8190,
+ "ON"
+ ],
+ [
+ 8192,
+ 8202,
+ "WS"
+ ],
+ [
+ 8203,
+ 8205,
+ "BN"
+ ],
+ [
+ 8207,
+ 8207,
+ "R"
+ ],
+ [
+ 8208,
+ 8231,
+ "ON"
+ ],
+ [
+ 8232,
+ 8232,
+ "WS"
+ ],
+ [
+ 8233,
+ 8233,
+ "B"
+ ],
+ [
+ 8234,
+ 8238,
+ "BN"
+ ],
+ [
+ 8239,
+ 8239,
+ "CS"
+ ],
+ [
+ 8240,
+ 8244,
+ "ET"
+ ],
+ [
+ 8245,
+ 8259,
+ "ON"
+ ],
+ [
+ 8260,
+ 8260,
+ "CS"
+ ],
+ [
+ 8261,
+ 8286,
+ "ON"
+ ],
+ [
+ 8287,
+ 8287,
+ "WS"
+ ],
+ [
+ 8288,
+ 8303,
+ "BN"
+ ],
+ [
+ 8304,
+ 8304,
+ "EN"
+ ],
+ [
+ 8308,
+ 8313,
+ "EN"
+ ],
+ [
+ 8314,
+ 8315,
+ "ES"
+ ],
+ [
+ 8316,
+ 8318,
+ "ON"
+ ],
+ [
+ 8320,
+ 8329,
+ "EN"
+ ],
+ [
+ 8330,
+ 8331,
+ "ES"
+ ],
+ [
+ 8332,
+ 8334,
+ "ON"
+ ],
+ [
+ 8352,
+ 8399,
+ "ET"
+ ],
+ [
+ 8400,
+ 8432,
+ "NSM"
+ ],
+ [
+ 8448,
+ 8449,
+ "ON"
+ ],
+ [
+ 8451,
+ 8454,
+ "ON"
+ ],
+ [
+ 8456,
+ 8457,
+ "ON"
+ ],
+ [
+ 8468,
+ 8468,
+ "ON"
+ ],
+ [
+ 8470,
+ 8472,
+ "ON"
+ ],
+ [
+ 8478,
+ 8483,
+ "ON"
+ ],
+ [
+ 8485,
+ 8485,
+ "ON"
+ ],
+ [
+ 8487,
+ 8487,
+ "ON"
+ ],
+ [
+ 8489,
+ 8489,
+ "ON"
+ ],
+ [
+ 8494,
+ 8494,
+ "ET"
+ ],
+ [
+ 8506,
+ 8507,
+ "ON"
+ ],
+ [
+ 8512,
+ 8516,
+ "ON"
+ ],
+ [
+ 8522,
+ 8525,
+ "ON"
+ ],
+ [
+ 8528,
+ 8543,
+ "ON"
+ ],
+ [
+ 8585,
+ 8587,
+ "ON"
+ ],
+ [
+ 8592,
+ 8721,
+ "ON"
+ ],
+ [
+ 8722,
+ 8722,
+ "ES"
+ ],
+ [
+ 8723,
+ 8723,
+ "ET"
+ ],
+ [
+ 8724,
+ 9013,
+ "ON"
+ ],
+ [
+ 9083,
+ 9108,
+ "ON"
+ ],
+ [
+ 9110,
+ 9257,
+ "ON"
+ ],
+ [
+ 9280,
+ 9290,
+ "ON"
+ ],
+ [
+ 9312,
+ 9351,
+ "ON"
+ ],
+ [
+ 9352,
+ 9371,
+ "EN"
+ ],
+ [
+ 9450,
+ 9899,
+ "ON"
+ ],
+ [
+ 9901,
+ 10239,
+ "ON"
+ ],
+ [
+ 10496,
+ 11123,
+ "ON"
+ ],
+ [
+ 11126,
+ 11263,
+ "ON"
+ ],
+ [
+ 11493,
+ 11498,
+ "ON"
+ ],
+ [
+ 11503,
+ 11505,
+ "NSM"
+ ],
+ [
+ 11513,
+ 11519,
+ "ON"
+ ],
+ [
+ 11647,
+ 11647,
+ "NSM"
+ ],
+ [
+ 11744,
+ 11775,
+ "NSM"
+ ],
+ [
+ 11776,
+ 11869,
+ "ON"
+ ],
+ [
+ 11904,
+ 11929,
+ "ON"
+ ],
+ [
+ 11931,
+ 12019,
+ "ON"
+ ],
+ [
+ 12032,
+ 12245,
+ "ON"
+ ],
+ [
+ 12272,
+ 12287,
+ "ON"
+ ],
+ [
+ 12288,
+ 12288,
+ "WS"
+ ],
+ [
+ 12289,
+ 12292,
+ "ON"
+ ],
+ [
+ 12296,
+ 12320,
+ "ON"
+ ],
+ [
+ 12330,
+ 12333,
+ "NSM"
+ ],
+ [
+ 12336,
+ 12336,
+ "ON"
+ ],
+ [
+ 12342,
+ 12343,
+ "ON"
+ ],
+ [
+ 12349,
+ 12351,
+ "ON"
+ ],
+ [
+ 12441,
+ 12442,
+ "NSM"
+ ],
+ [
+ 12443,
+ 12444,
+ "ON"
+ ],
+ [
+ 12448,
+ 12448,
+ "ON"
+ ],
+ [
+ 12539,
+ 12539,
+ "ON"
+ ],
+ [
+ 12736,
+ 12773,
+ "ON"
+ ],
+ [
+ 12783,
+ 12783,
+ "ON"
+ ],
+ [
+ 12829,
+ 12830,
+ "ON"
+ ],
+ [
+ 12880,
+ 12895,
+ "ON"
+ ],
+ [
+ 12924,
+ 12926,
+ "ON"
+ ],
+ [
+ 12977,
+ 12991,
+ "ON"
+ ],
+ [
+ 13004,
+ 13007,
+ "ON"
+ ],
+ [
+ 13175,
+ 13178,
+ "ON"
+ ],
+ [
+ 13278,
+ 13279,
+ "ON"
+ ],
+ [
+ 13311,
+ 13311,
+ "ON"
+ ],
+ [
+ 19904,
+ 19967,
+ "ON"
+ ],
+ [
+ 42128,
+ 42182,
+ "ON"
+ ],
+ [
+ 42509,
+ 42511,
+ "ON"
+ ],
+ [
+ 42607,
+ 42610,
+ "NSM"
+ ],
+ [
+ 42611,
+ 42611,
+ "ON"
+ ],
+ [
+ 42612,
+ 42621,
+ "NSM"
+ ],
+ [
+ 42622,
+ 42623,
+ "ON"
+ ],
+ [
+ 42654,
+ 42655,
+ "NSM"
+ ],
+ [
+ 42736,
+ 42737,
+ "NSM"
+ ],
+ [
+ 42752,
+ 42785,
+ "ON"
+ ],
+ [
+ 42888,
+ 42888,
+ "ON"
+ ],
+ [
+ 43010,
+ 43010,
+ "NSM"
+ ],
+ [
+ 43014,
+ 43014,
+ "NSM"
+ ],
+ [
+ 43019,
+ 43019,
+ "NSM"
+ ],
+ [
+ 43045,
+ 43046,
+ "NSM"
+ ],
+ [
+ 43048,
+ 43051,
+ "ON"
+ ],
+ [
+ 43052,
+ 43052,
+ "NSM"
+ ],
+ [
+ 43064,
+ 43065,
+ "ET"
+ ],
+ [
+ 43124,
+ 43127,
+ "ON"
+ ],
+ [
+ 43204,
+ 43205,
+ "NSM"
+ ],
+ [
+ 43232,
+ 43249,
+ "NSM"
+ ],
+ [
+ 43263,
+ 43263,
+ "NSM"
+ ],
+ [
+ 43302,
+ 43309,
+ "NSM"
+ ],
+ [
+ 43335,
+ 43345,
+ "NSM"
+ ],
+ [
+ 43392,
+ 43394,
+ "NSM"
+ ],
+ [
+ 43443,
+ 43443,
+ "NSM"
+ ],
+ [
+ 43446,
+ 43449,
+ "NSM"
+ ],
+ [
+ 43452,
+ 43453,
+ "NSM"
+ ],
+ [
+ 43493,
+ 43493,
+ "NSM"
+ ],
+ [
+ 43561,
+ 43566,
+ "NSM"
+ ],
+ [
+ 43569,
+ 43570,
+ "NSM"
+ ],
+ [
+ 43573,
+ 43574,
+ "NSM"
+ ],
+ [
+ 43587,
+ 43587,
+ "NSM"
+ ],
+ [
+ 43596,
+ 43596,
+ "NSM"
+ ],
+ [
+ 43644,
+ 43644,
+ "NSM"
+ ],
+ [
+ 43696,
+ 43696,
+ "NSM"
+ ],
+ [
+ 43698,
+ 43700,
+ "NSM"
+ ],
+ [
+ 43703,
+ 43704,
+ "NSM"
+ ],
+ [
+ 43710,
+ 43711,
+ "NSM"
+ ],
+ [
+ 43713,
+ 43713,
+ "NSM"
+ ],
+ [
+ 43756,
+ 43757,
+ "NSM"
+ ],
+ [
+ 43766,
+ 43766,
+ "NSM"
+ ],
+ [
+ 43882,
+ 43883,
+ "ON"
+ ],
+ [
+ 44005,
+ 44005,
+ "NSM"
+ ],
+ [
+ 44008,
+ 44008,
+ "NSM"
+ ],
+ [
+ 44013,
+ 44013,
+ "NSM"
+ ],
+ [
+ 64285,
+ 64285,
+ "R"
+ ],
+ [
+ 64286,
+ 64286,
+ "NSM"
+ ],
+ [
+ 64287,
+ 64296,
+ "R"
+ ],
+ [
+ 64297,
+ 64297,
+ "ES"
+ ],
+ [
+ 64298,
+ 64335,
+ "R"
+ ],
+ [
+ 64336,
+ 64450,
+ "AL"
+ ],
+ [
+ 64451,
+ 64466,
+ "ON"
+ ],
+ [
+ 64467,
+ 64829,
+ "AL"
+ ],
+ [
+ 64830,
+ 64847,
+ "ON"
+ ],
+ [
+ 64848,
+ 64911,
+ "AL"
+ ],
+ [
+ 64912,
+ 64913,
+ "ON"
+ ],
+ [
+ 64914,
+ 64967,
+ "AL"
+ ],
+ [
+ 64968,
+ 64975,
+ "ON"
+ ],
+ [
+ 64976,
+ 65007,
+ "BN"
+ ],
+ [
+ 65008,
+ 65020,
+ "AL"
+ ],
+ [
+ 65021,
+ 65023,
+ "ON"
+ ],
+ [
+ 65024,
+ 65039,
+ "NSM"
+ ],
+ [
+ 65040,
+ 65049,
+ "ON"
+ ],
+ [
+ 65056,
+ 65071,
+ "NSM"
+ ],
+ [
+ 65072,
+ 65103,
+ "ON"
+ ],
+ [
+ 65104,
+ 65104,
+ "CS"
+ ],
+ [
+ 65105,
+ 65105,
+ "ON"
+ ],
+ [
+ 65106,
+ 65106,
+ "CS"
+ ],
+ [
+ 65108,
+ 65108,
+ "ON"
+ ],
+ [
+ 65109,
+ 65109,
+ "CS"
+ ],
+ [
+ 65110,
+ 65118,
+ "ON"
+ ],
+ [
+ 65119,
+ 65119,
+ "ET"
+ ],
+ [
+ 65120,
+ 65121,
+ "ON"
+ ],
+ [
+ 65122,
+ 65123,
+ "ES"
+ ],
+ [
+ 65124,
+ 65126,
+ "ON"
+ ],
+ [
+ 65128,
+ 65128,
+ "ON"
+ ],
+ [
+ 65129,
+ 65130,
+ "ET"
+ ],
+ [
+ 65131,
+ 65131,
+ "ON"
+ ],
+ [
+ 65136,
+ 65278,
+ "AL"
+ ],
+ [
+ 65279,
+ 65279,
+ "BN"
+ ],
+ [
+ 65281,
+ 65282,
+ "ON"
+ ],
+ [
+ 65283,
+ 65285,
+ "ET"
+ ],
+ [
+ 65286,
+ 65290,
+ "ON"
+ ],
+ [
+ 65291,
+ 65291,
+ "ES"
+ ],
+ [
+ 65292,
+ 65292,
+ "CS"
+ ],
+ [
+ 65293,
+ 65293,
+ "ES"
+ ],
+ [
+ 65294,
+ 65295,
+ "CS"
+ ],
+ [
+ 65296,
+ 65305,
+ "EN"
+ ],
+ [
+ 65306,
+ 65306,
+ "CS"
+ ],
+ [
+ 65307,
+ 65312,
+ "ON"
+ ],
+ [
+ 65339,
+ 65344,
+ "ON"
+ ],
+ [
+ 65371,
+ 65381,
+ "ON"
+ ],
+ [
+ 65504,
+ 65505,
+ "ET"
+ ],
+ [
+ 65506,
+ 65508,
+ "ON"
+ ],
+ [
+ 65509,
+ 65510,
+ "ET"
+ ],
+ [
+ 65512,
+ 65518,
+ "ON"
+ ],
+ [
+ 65520,
+ 65528,
+ "BN"
+ ],
+ [
+ 65529,
+ 65533,
+ "ON"
+ ],
+ [
+ 65534,
+ 65535,
+ "BN"
+ ],
+ [
+ 65793,
+ 65793,
+ "ON"
+ ],
+ [
+ 65856,
+ 65932,
+ "ON"
+ ],
+ [
+ 65936,
+ 65948,
+ "ON"
+ ],
+ [
+ 65952,
+ 65952,
+ "ON"
+ ],
+ [
+ 66045,
+ 66045,
+ "NSM"
+ ],
+ [
+ 66272,
+ 66272,
+ "NSM"
+ ],
+ [
+ 66273,
+ 66299,
+ "EN"
+ ],
+ [
+ 66422,
+ 66426,
+ "NSM"
+ ],
+ [
+ 67584,
+ 67870,
+ "R"
+ ],
+ [
+ 67871,
+ 67871,
+ "ON"
+ ],
+ [
+ 67872,
+ 68096,
+ "R"
+ ],
+ [
+ 68097,
+ 68099,
+ "NSM"
+ ],
+ [
+ 68100,
+ 68100,
+ "R"
+ ],
+ [
+ 68101,
+ 68102,
+ "NSM"
+ ],
+ [
+ 68103,
+ 68107,
+ "R"
+ ],
+ [
+ 68108,
+ 68111,
+ "NSM"
+ ],
+ [
+ 68112,
+ 68151,
+ "R"
+ ],
+ [
+ 68152,
+ 68154,
+ "NSM"
+ ],
+ [
+ 68155,
+ 68158,
+ "R"
+ ],
+ [
+ 68159,
+ 68159,
+ "NSM"
+ ],
+ [
+ 68160,
+ 68324,
+ "R"
+ ],
+ [
+ 68325,
+ 68326,
+ "NSM"
+ ],
+ [
+ 68327,
+ 68408,
+ "R"
+ ],
+ [
+ 68409,
+ 68415,
+ "ON"
+ ],
+ [
+ 68416,
+ 68863,
+ "R"
+ ],
+ [
+ 68864,
+ 68899,
+ "AL"
+ ],
+ [
+ 68900,
+ 68903,
+ "NSM"
+ ],
+ [
+ 68904,
+ 68911,
+ "AL"
+ ],
+ [
+ 68912,
+ 68921,
+ "AN"
+ ],
+ [
+ 68922,
+ 68927,
+ "AL"
+ ],
+ [
+ 68928,
+ 68937,
+ "AN"
+ ],
+ [
+ 68938,
+ 68968,
+ "R"
+ ],
+ [
+ 68969,
+ 68973,
+ "NSM"
+ ],
+ [
+ 68974,
+ 68974,
+ "ON"
+ ],
+ [
+ 68975,
+ 69215,
+ "R"
+ ],
+ [
+ 69216,
+ 69246,
+ "AN"
+ ],
+ [
+ 69247,
+ 69290,
+ "R"
+ ],
+ [
+ 69291,
+ 69292,
+ "NSM"
+ ],
+ [
+ 69293,
+ 69311,
+ "R"
+ ],
+ [
+ 69312,
+ 69327,
+ "AL"
+ ],
+ [
+ 69328,
+ 69336,
+ "ON"
+ ],
+ [
+ 69337,
+ 69369,
+ "AL"
+ ],
+ [
+ 69370,
+ 69375,
+ "NSM"
+ ],
+ [
+ 69376,
+ 69423,
+ "R"
+ ],
+ [
+ 69424,
+ 69445,
+ "AL"
+ ],
+ [
+ 69446,
+ 69456,
+ "NSM"
+ ],
+ [
+ 69457,
+ 69487,
+ "AL"
+ ],
+ [
+ 69488,
+ 69505,
+ "R"
+ ],
+ [
+ 69506,
+ 69509,
+ "NSM"
+ ],
+ [
+ 69510,
+ 69631,
+ "R"
+ ],
+ [
+ 69633,
+ 69633,
+ "NSM"
+ ],
+ [
+ 69688,
+ 69702,
+ "NSM"
+ ],
+ [
+ 69714,
+ 69733,
+ "ON"
+ ],
+ [
+ 69744,
+ 69744,
+ "NSM"
+ ],
+ [
+ 69747,
+ 69748,
+ "NSM"
+ ],
+ [
+ 69759,
+ 69761,
+ "NSM"
+ ],
+ [
+ 69811,
+ 69814,
+ "NSM"
+ ],
+ [
+ 69817,
+ 69818,
+ "NSM"
+ ],
+ [
+ 69826,
+ 69826,
+ "NSM"
+ ],
+ [
+ 69888,
+ 69890,
+ "NSM"
+ ],
+ [
+ 69927,
+ 69931,
+ "NSM"
+ ],
+ [
+ 69933,
+ 69940,
+ "NSM"
+ ],
+ [
+ 70003,
+ 70003,
+ "NSM"
+ ],
+ [
+ 70016,
+ 70017,
+ "NSM"
+ ],
+ [
+ 70070,
+ 70078,
+ "NSM"
+ ],
+ [
+ 70089,
+ 70092,
+ "NSM"
+ ],
+ [
+ 70095,
+ 70095,
+ "NSM"
+ ],
+ [
+ 70191,
+ 70193,
+ "NSM"
+ ],
+ [
+ 70196,
+ 70196,
+ "NSM"
+ ],
+ [
+ 70198,
+ 70199,
+ "NSM"
+ ],
+ [
+ 70206,
+ 70206,
+ "NSM"
+ ],
+ [
+ 70209,
+ 70209,
+ "NSM"
+ ],
+ [
+ 70367,
+ 70367,
+ "NSM"
+ ],
+ [
+ 70371,
+ 70378,
+ "NSM"
+ ],
+ [
+ 70400,
+ 70401,
+ "NSM"
+ ],
+ [
+ 70459,
+ 70460,
+ "NSM"
+ ],
+ [
+ 70464,
+ 70464,
+ "NSM"
+ ],
+ [
+ 70502,
+ 70508,
+ "NSM"
+ ],
+ [
+ 70512,
+ 70516,
+ "NSM"
+ ],
+ [
+ 70587,
+ 70592,
+ "NSM"
+ ],
+ [
+ 70606,
+ 70606,
+ "NSM"
+ ],
+ [
+ 70608,
+ 70608,
+ "NSM"
+ ],
+ [
+ 70610,
+ 70610,
+ "NSM"
+ ],
+ [
+ 70625,
+ 70626,
+ "NSM"
+ ],
+ [
+ 70712,
+ 70719,
+ "NSM"
+ ],
+ [
+ 70722,
+ 70724,
+ "NSM"
+ ],
+ [
+ 70726,
+ 70726,
+ "NSM"
+ ],
+ [
+ 70750,
+ 70750,
+ "NSM"
+ ],
+ [
+ 70835,
+ 70840,
+ "NSM"
+ ],
+ [
+ 70842,
+ 70842,
+ "NSM"
+ ],
+ [
+ 70847,
+ 70848,
+ "NSM"
+ ],
+ [
+ 70850,
+ 70851,
+ "NSM"
+ ],
+ [
+ 71090,
+ 71093,
+ "NSM"
+ ],
+ [
+ 71100,
+ 71101,
+ "NSM"
+ ],
+ [
+ 71103,
+ 71104,
+ "NSM"
+ ],
+ [
+ 71132,
+ 71133,
+ "NSM"
+ ],
+ [
+ 71219,
+ 71226,
+ "NSM"
+ ],
+ [
+ 71229,
+ 71229,
+ "NSM"
+ ],
+ [
+ 71231,
+ 71232,
+ "NSM"
+ ],
+ [
+ 71264,
+ 71276,
+ "ON"
+ ],
+ [
+ 71339,
+ 71339,
+ "NSM"
+ ],
+ [
+ 71341,
+ 71341,
+ "NSM"
+ ],
+ [
+ 71344,
+ 71349,
+ "NSM"
+ ],
+ [
+ 71351,
+ 71351,
+ "NSM"
+ ],
+ [
+ 71453,
+ 71453,
+ "NSM"
+ ],
+ [
+ 71455,
+ 71455,
+ "NSM"
+ ],
+ [
+ 71458,
+ 71461,
+ "NSM"
+ ],
+ [
+ 71463,
+ 71467,
+ "NSM"
+ ],
+ [
+ 71727,
+ 71735,
+ "NSM"
+ ],
+ [
+ 71737,
+ 71738,
+ "NSM"
+ ],
+ [
+ 71995,
+ 71996,
+ "NSM"
+ ],
+ [
+ 71998,
+ 71998,
+ "NSM"
+ ],
+ [
+ 72003,
+ 72003,
+ "NSM"
+ ],
+ [
+ 72148,
+ 72151,
+ "NSM"
+ ],
+ [
+ 72154,
+ 72155,
+ "NSM"
+ ],
+ [
+ 72160,
+ 72160,
+ "NSM"
+ ],
+ [
+ 72193,
+ 72198,
+ "NSM"
+ ],
+ [
+ 72201,
+ 72202,
+ "NSM"
+ ],
+ [
+ 72243,
+ 72248,
+ "NSM"
+ ],
+ [
+ 72251,
+ 72254,
+ "NSM"
+ ],
+ [
+ 72263,
+ 72263,
+ "NSM"
+ ],
+ [
+ 72273,
+ 72278,
+ "NSM"
+ ],
+ [
+ 72281,
+ 72283,
+ "NSM"
+ ],
+ [
+ 72330,
+ 72342,
+ "NSM"
+ ],
+ [
+ 72344,
+ 72345,
+ "NSM"
+ ],
+ [
+ 72544,
+ 72544,
+ "NSM"
+ ],
+ [
+ 72546,
+ 72548,
+ "NSM"
+ ],
+ [
+ 72550,
+ 72550,
+ "NSM"
+ ],
+ [
+ 72752,
+ 72758,
+ "NSM"
+ ],
+ [
+ 72760,
+ 72765,
+ "NSM"
+ ],
+ [
+ 72850,
+ 72871,
+ "NSM"
+ ],
+ [
+ 72874,
+ 72880,
+ "NSM"
+ ],
+ [
+ 72882,
+ 72883,
+ "NSM"
+ ],
+ [
+ 72885,
+ 72886,
+ "NSM"
+ ],
+ [
+ 73009,
+ 73014,
+ "NSM"
+ ],
+ [
+ 73018,
+ 73018,
+ "NSM"
+ ],
+ [
+ 73020,
+ 73021,
+ "NSM"
+ ],
+ [
+ 73023,
+ 73029,
+ "NSM"
+ ],
+ [
+ 73031,
+ 73031,
+ "NSM"
+ ],
+ [
+ 73104,
+ 73105,
+ "NSM"
+ ],
+ [
+ 73109,
+ 73109,
+ "NSM"
+ ],
+ [
+ 73111,
+ 73111,
+ "NSM"
+ ],
+ [
+ 73459,
+ 73460,
+ "NSM"
+ ],
+ [
+ 73472,
+ 73473,
+ "NSM"
+ ],
+ [
+ 73526,
+ 73530,
+ "NSM"
+ ],
+ [
+ 73536,
+ 73536,
+ "NSM"
+ ],
+ [
+ 73538,
+ 73538,
+ "NSM"
+ ],
+ [
+ 73562,
+ 73562,
+ "NSM"
+ ],
+ [
+ 73685,
+ 73692,
+ "ON"
+ ],
+ [
+ 73693,
+ 73696,
+ "ET"
+ ],
+ [
+ 73697,
+ 73713,
+ "ON"
+ ],
+ [
+ 78912,
+ 78912,
+ "NSM"
+ ],
+ [
+ 78919,
+ 78933,
+ "NSM"
+ ],
+ [
+ 90398,
+ 90409,
+ "NSM"
+ ],
+ [
+ 90413,
+ 90415,
+ "NSM"
+ ],
+ [
+ 92912,
+ 92916,
+ "NSM"
+ ],
+ [
+ 92976,
+ 92982,
+ "NSM"
+ ],
+ [
+ 94031,
+ 94031,
+ "NSM"
+ ],
+ [
+ 94095,
+ 94098,
+ "NSM"
+ ],
+ [
+ 94178,
+ 94178,
+ "ON"
+ ],
+ [
+ 94180,
+ 94180,
+ "NSM"
+ ],
+ [
+ 113821,
+ 113822,
+ "NSM"
+ ],
+ [
+ 113824,
+ 113827,
+ "BN"
+ ],
+ [
+ 117760,
+ 117973,
+ "ON"
+ ],
+ [
+ 118e3,
+ 118009,
+ "EN"
+ ],
+ [
+ 118010,
+ 118012,
+ "ON"
+ ],
+ [
+ 118016,
+ 118451,
+ "ON"
+ ],
+ [
+ 118458,
+ 118480,
+ "ON"
+ ],
+ [
+ 118496,
+ 118512,
+ "ON"
+ ],
+ [
+ 118528,
+ 118573,
+ "NSM"
+ ],
+ [
+ 118576,
+ 118598,
+ "NSM"
+ ],
+ [
+ 119143,
+ 119145,
+ "NSM"
+ ],
+ [
+ 119155,
+ 119162,
+ "BN"
+ ],
+ [
+ 119163,
+ 119170,
+ "NSM"
+ ],
+ [
+ 119173,
+ 119179,
+ "NSM"
+ ],
+ [
+ 119210,
+ 119213,
+ "NSM"
+ ],
+ [
+ 119273,
+ 119274,
+ "ON"
+ ],
+ [
+ 119296,
+ 119361,
+ "ON"
+ ],
+ [
+ 119362,
+ 119364,
+ "NSM"
+ ],
+ [
+ 119365,
+ 119365,
+ "ON"
+ ],
+ [
+ 119552,
+ 119638,
+ "ON"
+ ],
+ [
+ 120513,
+ 120513,
+ "ON"
+ ],
+ [
+ 120539,
+ 120539,
+ "ON"
+ ],
+ [
+ 120571,
+ 120571,
+ "ON"
+ ],
+ [
+ 120597,
+ 120597,
+ "ON"
+ ],
+ [
+ 120629,
+ 120629,
+ "ON"
+ ],
+ [
+ 120655,
+ 120655,
+ "ON"
+ ],
+ [
+ 120687,
+ 120687,
+ "ON"
+ ],
+ [
+ 120713,
+ 120713,
+ "ON"
+ ],
+ [
+ 120745,
+ 120745,
+ "ON"
+ ],
+ [
+ 120771,
+ 120771,
+ "ON"
+ ],
+ [
+ 120782,
+ 120831,
+ "EN"
+ ],
+ [
+ 121344,
+ 121398,
+ "NSM"
+ ],
+ [
+ 121403,
+ 121452,
+ "NSM"
+ ],
+ [
+ 121461,
+ 121461,
+ "NSM"
+ ],
+ [
+ 121476,
+ 121476,
+ "NSM"
+ ],
+ [
+ 121499,
+ 121503,
+ "NSM"
+ ],
+ [
+ 121505,
+ 121519,
+ "NSM"
+ ],
+ [
+ 122880,
+ 122886,
+ "NSM"
+ ],
+ [
+ 122888,
+ 122904,
+ "NSM"
+ ],
+ [
+ 122907,
+ 122913,
+ "NSM"
+ ],
+ [
+ 122915,
+ 122916,
+ "NSM"
+ ],
+ [
+ 122918,
+ 122922,
+ "NSM"
+ ],
+ [
+ 123023,
+ 123023,
+ "NSM"
+ ],
+ [
+ 123184,
+ 123190,
+ "NSM"
+ ],
+ [
+ 123566,
+ 123566,
+ "NSM"
+ ],
+ [
+ 123628,
+ 123631,
+ "NSM"
+ ],
+ [
+ 123647,
+ 123647,
+ "ET"
+ ],
+ [
+ 124140,
+ 124143,
+ "NSM"
+ ],
+ [
+ 124398,
+ 124399,
+ "NSM"
+ ],
+ [
+ 124643,
+ 124643,
+ "NSM"
+ ],
+ [
+ 124646,
+ 124646,
+ "NSM"
+ ],
+ [
+ 124654,
+ 124655,
+ "NSM"
+ ],
+ [
+ 124661,
+ 124661,
+ "NSM"
+ ],
+ [
+ 124928,
+ 125135,
+ "R"
+ ],
+ [
+ 125136,
+ 125142,
+ "NSM"
+ ],
+ [
+ 125143,
+ 125251,
+ "R"
+ ],
+ [
+ 125252,
+ 125258,
+ "NSM"
+ ],
+ [
+ 125259,
+ 126063,
+ "R"
+ ],
+ [
+ 126064,
+ 126143,
+ "AL"
+ ],
+ [
+ 126144,
+ 126207,
+ "R"
+ ],
+ [
+ 126208,
+ 126287,
+ "AL"
+ ],
+ [
+ 126288,
+ 126463,
+ "R"
+ ],
+ [
+ 126464,
+ 126703,
+ "AL"
+ ],
+ [
+ 126704,
+ 126705,
+ "ON"
+ ],
+ [
+ 126706,
+ 126719,
+ "AL"
+ ],
+ [
+ 126720,
+ 126975,
+ "R"
+ ],
+ [
+ 126976,
+ 127019,
+ "ON"
+ ],
+ [
+ 127024,
+ 127123,
+ "ON"
+ ],
+ [
+ 127136,
+ 127150,
+ "ON"
+ ],
+ [
+ 127153,
+ 127167,
+ "ON"
+ ],
+ [
+ 127169,
+ 127183,
+ "ON"
+ ],
+ [
+ 127185,
+ 127221,
+ "ON"
+ ],
+ [
+ 127232,
+ 127242,
+ "EN"
+ ],
+ [
+ 127243,
+ 127247,
+ "ON"
+ ],
+ [
+ 127279,
+ 127279,
+ "ON"
+ ],
+ [
+ 127338,
+ 127343,
+ "ON"
+ ],
+ [
+ 127405,
+ 127405,
+ "ON"
+ ],
+ [
+ 127584,
+ 127589,
+ "ON"
+ ],
+ [
+ 127744,
+ 128728,
+ "ON"
+ ],
+ [
+ 128732,
+ 128748,
+ "ON"
+ ],
+ [
+ 128752,
+ 128764,
+ "ON"
+ ],
+ [
+ 128768,
+ 128985,
+ "ON"
+ ],
+ [
+ 128992,
+ 129003,
+ "ON"
+ ],
+ [
+ 129008,
+ 129008,
+ "ON"
+ ],
+ [
+ 129024,
+ 129035,
+ "ON"
+ ],
+ [
+ 129040,
+ 129095,
+ "ON"
+ ],
+ [
+ 129104,
+ 129113,
+ "ON"
+ ],
+ [
+ 129120,
+ 129159,
+ "ON"
+ ],
+ [
+ 129168,
+ 129197,
+ "ON"
+ ],
+ [
+ 129200,
+ 129211,
+ "ON"
+ ],
+ [
+ 129216,
+ 129217,
+ "ON"
+ ],
+ [
+ 129232,
+ 129240,
+ "ON"
+ ],
+ [
+ 129280,
+ 129623,
+ "ON"
+ ],
+ [
+ 129632,
+ 129645,
+ "ON"
+ ],
+ [
+ 129648,
+ 129660,
+ "ON"
+ ],
+ [
+ 129664,
+ 129674,
+ "ON"
+ ],
+ [
+ 129678,
+ 129734,
+ "ON"
+ ],
+ [
+ 129736,
+ 129736,
+ "ON"
+ ],
+ [
+ 129741,
+ 129756,
+ "ON"
+ ],
+ [
+ 129759,
+ 129770,
+ "ON"
+ ],
+ [
+ 129775,
+ 129784,
+ "ON"
+ ],
+ [
+ 129792,
+ 129938,
+ "ON"
+ ],
+ [
+ 129940,
+ 130031,
+ "ON"
+ ],
+ [
+ 130032,
+ 130041,
+ "EN"
+ ],
+ [
+ 130042,
+ 130042,
+ "ON"
+ ],
+ [
+ 131070,
+ 131071,
+ "BN"
+ ],
+ [
+ 196606,
+ 196607,
+ "BN"
+ ],
+ [
+ 262142,
+ 262143,
+ "BN"
+ ],
+ [
+ 327678,
+ 327679,
+ "BN"
+ ],
+ [
+ 393214,
+ 393215,
+ "BN"
+ ],
+ [
+ 458750,
+ 458751,
+ "BN"
+ ],
+ [
+ 524286,
+ 524287,
+ "BN"
+ ],
+ [
+ 589822,
+ 589823,
+ "BN"
+ ],
+ [
+ 655358,
+ 655359,
+ "BN"
+ ],
+ [
+ 720894,
+ 720895,
+ "BN"
+ ],
+ [
+ 786430,
+ 786431,
+ "BN"
+ ],
+ [
+ 851966,
+ 851967,
+ "BN"
+ ],
+ [
+ 917502,
+ 917759,
+ "BN"
+ ],
+ [
+ 917760,
+ 917999,
+ "NSM"
+ ],
+ [
+ 918e3,
+ 921599,
+ "BN"
+ ],
+ [
+ 983038,
+ 983039,
+ "BN"
+ ],
+ [
+ 1048574,
+ 1048575,
+ "BN"
+ ],
+ [
+ 1114110,
+ 1114111,
+ "BN"
+ ]
+];
+//#endregion
+//#region node_modules/@chenglou/pretext/dist/bidi.js
+function ap(e) {
+ if (e <= 255) return rp[e];
+ let t = 0, n = ip.length - 1;
+ for (; t <= n;) {
+ let r = t + n >> 1, i = ip[r];
+ if (e < i[0]) {
+ n = r - 1;
+ continue;
+ }
+ if (e > i[1]) {
+ t = r + 1;
+ continue;
+ }
+ return i[2];
+ }
+ return "L";
+}
+function op(e) {
+ let t = e.length;
+ if (t === 0) return null;
+ let n = Array(t), r = !1;
+ for (let i = 0; i < t;) {
+ let a = e.charCodeAt(i), o = a, s = 1;
+ if (a >= 55296 && a <= 56319 && i + 1 < t) {
+ let t = e.charCodeAt(i + 1);
+ t >= 56320 && t <= 57343 && (o = (a - 55296 << 10) + (t - 56320) + 65536, s = 2);
+ }
+ let c = ap(o);
+ (c === "R" || c === "AL" || c === "AN") && (r = !0);
+ for (let e = 0; e < s; e++) n[i + e] = c;
+ i += s;
+ }
+ if (!r) return null;
+ let i = 0;
+ for (let e = 0; e < t; e++) {
+ let t = n[e];
+ if (t === "L") {
+ i = 0;
+ break;
+ }
+ if (t === "R" || t === "AL") {
+ i = 1;
+ break;
+ }
+ }
+ let a = new Int8Array(t);
+ for (let e = 0; e < t; e++) a[e] = i;
+ let o = i & 1 ? "R" : "L", s = o, c = s;
+ for (let e = 0; e < t; e++) n[e] === "NSM" ? n[e] = c : c = n[e];
+ c = s;
+ for (let e = 0; e < t; e++) {
+ let t = n[e];
+ t === "EN" ? n[e] = c === "AL" ? "AN" : "EN" : (t === "R" || t === "L" || t === "AL") && (c = t);
+ }
+ for (let e = 0; e < t; e++) n[e] === "AL" && (n[e] = "R");
+ for (let e = 1; e < t - 1; e++) n[e] === "ES" && n[e - 1] === "EN" && n[e + 1] === "EN" && (n[e] = "EN"), n[e] === "CS" && (n[e - 1] === "EN" || n[e - 1] === "AN") && n[e + 1] === n[e - 1] && (n[e] = n[e - 1]);
+ for (let e = 0; e < t; e++) {
+ if (n[e] !== "EN") continue;
+ let r;
+ for (r = e - 1; r >= 0 && n[r] === "ET"; r--) n[r] = "EN";
+ for (r = e + 1; r < t && n[r] === "ET"; r++) n[r] = "EN";
+ }
+ for (let e = 0; e < t; e++) {
+ let t = n[e];
+ (t === "WS" || t === "ES" || t === "ET" || t === "CS") && (n[e] = "ON");
+ }
+ c = s;
+ for (let e = 0; e < t; e++) {
+ let t = n[e];
+ t === "EN" ? n[e] = c === "L" ? "L" : "EN" : (t === "R" || t === "L") && (c = t);
+ }
+ for (let e = 0; e < t; e++) {
+ if (n[e] !== "ON") continue;
+ let r = e + 1;
+ for (; r < t && n[r] === "ON";) r++;
+ let i = e > 0 ? n[e - 1] : s, a = r < t ? n[r] : s, o = i === "L" ? "L" : "R";
+ if (o === (a === "L" ? "L" : "R")) for (let t = e; t < r; t++) n[t] = o;
+ e = r - 1;
+ }
+ for (let e = 0; e < t; e++) n[e] === "ON" && (n[e] = o);
+ for (let e = 0; e < t; e++) {
+ let t = n[e];
+ a[e] & 1 ? (t === "L" || t === "AN" || t === "EN") && a[e]++ : t === "R" ? a[e]++ : (t === "AN" || t === "EN") && (a[e] += 2);
+ }
+ return a;
+}
+function sp(e, t) {
+ let n = op(e);
+ if (n === null) return null;
+ let r = new Int8Array(t.length);
+ for (let e = 0; e < t.length; e++) r[e] = n[t[e]];
+ return r;
+}
+//#endregion
+//#region node_modules/@chenglou/pretext/dist/analysis.js
+var cp = /[ \t\n\r\f]+/g, lp = /[\t\n\r\f]| {2,}|^ | $/;
+function up(e) {
+ let t = e ?? "normal";
+ return t === "pre-wrap" ? {
+ mode: t,
+ preserveOrdinarySpaces: !0,
+ preserveHardBreaks: !0
+ } : {
+ mode: t,
+ preserveOrdinarySpaces: !1,
+ preserveHardBreaks: !1
+ };
+}
+function dp(e) {
+ if (!lp.test(e)) return e;
+ let t = e.replace(cp, " ");
+ return t.charCodeAt(0) === 32 && (t = t.slice(1)), t.length > 0 && t.charCodeAt(t.length - 1) === 32 && (t = t.slice(0, -1)), t;
+}
+function fp(e) {
+ return /[\r\f]/.test(e) ? e.replace(/\r\n/g, "\n").replace(/[\r\f]/g, "\n") : e.replace(/\r\n/g, "\n");
+}
+var pp = null, mp;
+function hp() {
+ return pp === null && (pp = new Intl.Segmenter(mp, { granularity: "word" })), pp;
+}
+var gp = /\p{Script=Arabic}/u, _p = /\p{M}/u, vp = /\p{Nd}/u;
+function yp(e) {
+ return gp.test(e);
+}
+function bp(e) {
+ return e >= 19968 && e <= 40959 || e >= 13312 && e <= 19903 || e >= 131072 && e <= 173791 || e >= 173824 && e <= 177983 || e >= 177984 && e <= 178207 || e >= 178208 && e <= 183983 || e >= 183984 && e <= 191471 || e >= 191472 && e <= 192093 || e >= 194560 && e <= 195103 || e >= 196608 && e <= 201551 || e >= 201552 && e <= 205743 || e >= 205744 && e <= 210041 || e >= 63744 && e <= 64255 || e >= 12288 && e <= 12351 || e >= 12352 && e <= 12447 || e >= 12448 && e <= 12543 || e >= 44032 && e <= 55215 || e >= 65280 && e <= 65519;
+}
+function xp(e) {
+ for (let t = 0; t < e.length; t++) {
+ let n = e.charCodeAt(t);
+ if (!(n < 12288)) {
+ if (n >= 55296 && n <= 56319 && t + 1 < e.length) {
+ let r = e.charCodeAt(t + 1);
+ if (r >= 56320 && r <= 57343) {
+ if (bp((n - 55296 << 10) + (r - 56320) + 65536)) return !0;
+ t++;
+ continue;
+ }
+ }
+ if (bp(n)) return !0;
+ }
+ }
+ return !1;
+}
+function Sp(e) {
+ let t = zp(e);
+ return t !== null && (Dp.has(t) || Ap.has(t));
+}
+var Cp = new Set([
+ "\xA0",
+ " ",
+ "⁠",
+ ""
+]);
+function wp(e) {
+ return xp(e);
+}
+function Tp(e) {
+ let t = zp(e);
+ return t !== null && Cp.has(t);
+}
+function Ep(e) {
+ return !Sp(e) && !Tp(e);
+}
+var Dp = new Set(/* @__PURE__ */ ",...!.:.;.?.、.。.・.).〕.〉.》.」.』.】.〗.〙.〛.ー.々.〻.ゝ.ゞ.ヽ.ヾ".split(".")), Op = new Set([
+ "\"",
+ "(",
+ "[",
+ "{",
+ "“",
+ "‘",
+ "«",
+ "‹",
+ "(",
+ "〔",
+ "〈",
+ "《",
+ "「",
+ "『",
+ "【",
+ "〖",
+ "〘",
+ "〚"
+]), kp = new Set(["'", "’"]), Ap = new Set(/* @__PURE__ */ ".(,(!(?(:(;(،(؛(؟(।(॥(၊(။(၌(၍(၏()(](}(%(\"(”(’(»(›(…".split("(")), jp = new Set([
+ ":",
+ ".",
+ "،",
+ "؛"
+]), Mp = new Set(["၏"]), Np = new Set([
+ "”",
+ "’",
+ "»",
+ "›",
+ "」",
+ "』",
+ "】",
+ "》",
+ "〉",
+ "〕",
+ ")"
+]);
+function Pp(e) {
+ if (Lp(e)) return !0;
+ let t = !1;
+ for (let n of e) {
+ if (Ap.has(n)) {
+ t = !0;
+ continue;
+ }
+ if (!(t && _p.test(n))) return !1;
+ }
+ return t;
+}
+function Fp(e) {
+ for (let t of e) if (!Dp.has(t) && !Ap.has(t)) return !1;
+ return e.length > 0;
+}
+function Ip(e) {
+ if (Lp(e)) return !0;
+ for (let t of e) if (!Op.has(t) && !kp.has(t) && !_p.test(t)) return !1;
+ return e.length > 0;
+}
+function Lp(e) {
+ let t = !1;
+ for (let n of e) if (!(n === "\\" || _p.test(n))) {
+ if (Op.has(n) || Ap.has(n) || kp.has(n)) {
+ t = !0;
+ continue;
+ }
+ return !1;
+ }
+ return t;
+}
+function Rp(e, t) {
+ let n = t - 1;
+ if (n <= 0) return Math.max(n, 0);
+ let r = e.charCodeAt(n);
+ if (r < 56320 || r > 57343) return n;
+ let i = n - 1;
+ if (i < 0) return n;
+ let a = e.charCodeAt(i);
+ return a >= 55296 && a <= 56319 ? i : n;
+}
+function zp(e) {
+ if (e.length === 0) return null;
+ let t = Rp(e, e.length);
+ return e.slice(t);
+}
+function Bp(e) {
+ let t = Array.from(e), n = t.length;
+ for (; n > 0;) {
+ let e = t[n - 1];
+ if (_p.test(e)) {
+ n--;
+ continue;
+ }
+ if (Op.has(e) || kp.has(e)) {
+ n--;
+ continue;
+ }
+ break;
+ }
+ return n <= 0 || n === t.length ? null : {
+ head: t.slice(0, n).join(""),
+ tail: t.slice(n).join("")
+ };
+}
+function Vp(e, t, n) {
+ return n === "text" && !t && e.length === 1 && e !== "-" && e !== "—" ? e : null;
+}
+function Hp(e, t, n, r) {
+ let i = t[r], a = e[r];
+ if (i == null) return a;
+ let o = n[r];
+ if (a.length === o) return a;
+ let s = i.repeat(o);
+ return e[r] = s, s;
+}
+function Up(e, t) {
+ return e && t !== null && jp.has(t);
+}
+function Wp(e) {
+ let t = zp(e);
+ return t !== null && Mp.has(t);
+}
+function Gp(e) {
+ if (e.length < 2 || e[0] !== " ") return null;
+ let t = e.slice(1);
+ return /^\p{M}+$/u.test(t) ? {
+ space: " ",
+ marks: t
+ } : null;
+}
+function Kp(e) {
+ let t = e.length;
+ for (; t > 0;) {
+ let n = Rp(e, t), r = e.slice(n, t);
+ if (Np.has(r)) return !0;
+ if (!Ap.has(r)) return !1;
+ t = n;
+ }
+ return !1;
+}
+function qp(e, t) {
+ if (t.preserveOrdinarySpaces || t.preserveHardBreaks) {
+ if (e === " ") return "preserved-space";
+ if (e === " ") return "tab";
+ if (t.preserveHardBreaks && e === "\n") return "hard-break";
+ }
+ return e === " " ? "space" : e === "\xA0" || e === " " || e === "⁠" || e === "" ? "glue" : e === "​" ? "zero-width-break" : e === "­" ? "soft-hyphen" : "text";
+}
+var Jp = /[\x20\t\n\xA0\xAD\u200B\u202F\u2060\uFEFF]/;
+function Yp(e) {
+ return e.length === 1 ? e[0] : e.join("");
+}
+function Xp(e, t) {
+ let n = [];
+ for (let t = e.length - 1; t >= 0; t--) n.push(e[t]);
+ return n.push(t), Yp(n);
+}
+function Zp(e, t, n, r) {
+ if (!Jp.test(e)) return [{
+ text: e,
+ isWordLike: t,
+ kind: "text",
+ start: n
+ }];
+ let i = [], a = null, o = [], s = n, c = !1, l = 0;
+ for (let u of e) {
+ let e = qp(u, r), d = e === "text" && t;
+ if (a !== null && e === a && d === c) {
+ o.push(u), l += u.length;
+ continue;
+ }
+ a !== null && i.push({
+ text: Yp(o),
+ isWordLike: c,
+ kind: a,
+ start: s
+ }), a = e, o = [u], s = n + l, c = d, l += u.length;
+ }
+ return a !== null && i.push({
+ text: Yp(o),
+ isWordLike: c,
+ kind: a,
+ start: s
+ }), i;
+}
+function Qp(e) {
+ return e === "space" || e === "preserved-space" || e === "zero-width-break" || e === "hard-break";
+}
+var $p = /^[A-Za-z][A-Za-z0-9+.-]*:$/;
+function em(e, t) {
+ let n = e.texts[t];
+ return n.startsWith("www.") ? !0 : $p.test(n) && t + 1 < e.len && e.kinds[t + 1] === "text" && e.texts[t + 1] === "//";
+}
+function tm(e) {
+ return e.includes("?") && (e.includes("://") || e.startsWith("www."));
+}
+function nm(e) {
+ let t = e.texts.slice(), n = e.isWordLike.slice(), r = e.kinds.slice(), i = e.starts.slice();
+ for (let i = 0; i < e.len; i++) {
+ if (r[i] !== "text" || !em(e, i)) continue;
+ let a = [t[i]], o = i + 1;
+ for (; o < e.len && !Qp(r[o]);) {
+ a.push(t[o]), n[i] = !0;
+ let e = t[o].includes("?");
+ if (r[o] = "text", t[o] = "", o++, e) break;
+ }
+ t[i] = Yp(a);
+ }
+ let a = 0;
+ for (let e = 0; e < t.length; e++) {
+ let o = t[e];
+ o.length !== 0 && (a !== e && (t[a] = o, n[a] = n[e], r[a] = r[e], i[a] = i[e]), a++);
+ }
+ return t.length = a, n.length = a, r.length = a, i.length = a, {
+ len: a,
+ texts: t,
+ isWordLike: n,
+ kinds: r,
+ starts: i
+ };
+}
+function rm(e) {
+ let t = [], n = [], r = [], i = [];
+ for (let a = 0; a < e.len; a++) {
+ let o = e.texts[a];
+ if (t.push(o), n.push(e.isWordLike[a]), r.push(e.kinds[a]), i.push(e.starts[a]), !tm(o)) continue;
+ let s = a + 1;
+ if (s >= e.len || Qp(e.kinds[s])) continue;
+ let c = [], l = e.starts[s], u = s;
+ for (; u < e.len && !Qp(e.kinds[u]);) c.push(e.texts[u]), u++;
+ c.length > 0 && (t.push(Yp(c)), n.push(!0), r.push("text"), i.push(l), a = u - 1);
+ }
+ return {
+ len: t.length,
+ texts: t,
+ isWordLike: n,
+ kinds: r,
+ starts: i
+ };
+}
+var im = new Set([
+ ":",
+ "-",
+ "/",
+ "×",
+ ",",
+ ".",
+ "+",
+ "–",
+ "—"
+]), am = /^[A-Za-z0-9_]+[,:;]*$/, om = /[,:;]+$/;
+function sm(e) {
+ for (let t of e) if (vp.test(t)) return !0;
+ return !1;
+}
+function cm(e) {
+ if (e.length === 0) return !1;
+ for (let t of e) if (!(vp.test(t) || im.has(t))) return !1;
+ return !0;
+}
+function lm(e) {
+ let t = [], n = [], r = [], i = [];
+ for (let a = 0; a < e.len; a++) {
+ let o = e.texts[a], s = e.kinds[a];
+ if (s === "text" && cm(o) && sm(o)) {
+ let s = [o], c = a + 1;
+ for (; c < e.len && e.kinds[c] === "text" && cm(e.texts[c]);) s.push(e.texts[c]), c++;
+ t.push(Yp(s)), n.push(!0), r.push("text"), i.push(e.starts[a]), a = c - 1;
+ continue;
+ }
+ t.push(o), n.push(e.isWordLike[a]), r.push(s), i.push(e.starts[a]);
+ }
+ return {
+ len: t.length,
+ texts: t,
+ isWordLike: n,
+ kinds: r,
+ starts: i
+ };
+}
+function um(e) {
+ let t = [], n = [], r = [], i = [];
+ for (let a = 0; a < e.len; a++) {
+ let o = e.texts[a], s = e.kinds[a], c = e.isWordLike[a];
+ if (s === "text" && c && am.test(o)) {
+ let s = [o], c = om.test(o), l = a + 1;
+ for (; c && l < e.len && e.kinds[l] === "text" && e.isWordLike[l] && am.test(e.texts[l]);) {
+ let t = e.texts[l];
+ s.push(t), c = om.test(t), l++;
+ }
+ t.push(Yp(s)), n.push(!0), r.push("text"), i.push(e.starts[a]), a = l - 1;
+ continue;
+ }
+ t.push(o), n.push(c), r.push(s), i.push(e.starts[a]);
+ }
+ return {
+ len: t.length,
+ texts: t,
+ isWordLike: n,
+ kinds: r,
+ starts: i
+ };
+}
+function dm(e) {
+ let t = [], n = [], r = [], i = [];
+ for (let a = 0; a < e.len; a++) {
+ let o = e.texts[a];
+ if (e.kinds[a] === "text" && o.includes("-")) {
+ let s = o.split("-"), c = s.length > 1;
+ for (let e = 0; e < s.length; e++) {
+ let t = s[e];
+ if (!c) break;
+ (t.length === 0 || !sm(t) || !cm(t)) && (c = !1);
+ }
+ if (c) {
+ let o = 0;
+ for (let c = 0; c < s.length; c++) {
+ let l = s[c], u = c < s.length - 1 ? `${l}-` : l;
+ t.push(u), n.push(!0), r.push("text"), i.push(e.starts[a] + o), o += u.length;
+ }
+ continue;
+ }
+ }
+ t.push(o), n.push(e.isWordLike[a]), r.push(e.kinds[a]), i.push(e.starts[a]);
+ }
+ return {
+ len: t.length,
+ texts: t,
+ isWordLike: n,
+ kinds: r,
+ starts: i
+ };
+}
+function fm(e) {
+ let t = [], n = [], r = [], i = [], a = 0;
+ for (; a < e.len;) {
+ let o = [e.texts[a]], s = e.isWordLike[a], c = e.kinds[a], l = e.starts[a];
+ if (c === "glue") {
+ let u = [o[0]], d = l;
+ for (a++; a < e.len && e.kinds[a] === "glue";) u.push(e.texts[a]), a++;
+ let f = Yp(u);
+ if (a < e.len && e.kinds[a] === "text") o[0] = f, o.push(e.texts[a]), s = e.isWordLike[a], c = "text", l = d, a++;
+ else {
+ t.push(f), n.push(!1), r.push("glue"), i.push(d);
+ continue;
+ }
+ } else a++;
+ if (c === "text") for (; a < e.len && e.kinds[a] === "glue";) {
+ let t = [];
+ for (; a < e.len && e.kinds[a] === "glue";) t.push(e.texts[a]), a++;
+ let n = Yp(t);
+ if (a < e.len && e.kinds[a] === "text") {
+ o.push(n, e.texts[a]), s ||= e.isWordLike[a], a++;
+ continue;
+ }
+ o.push(n);
+ }
+ t.push(Yp(o)), n.push(s), r.push(c), i.push(l);
+ }
+ return {
+ len: t.length,
+ texts: t,
+ isWordLike: n,
+ kinds: r,
+ starts: i
+ };
+}
+function pm(e) {
+ let t = e.texts.slice(), n = e.isWordLike.slice(), r = e.kinds.slice(), i = e.starts.slice();
+ for (let e = 0; e < t.length - 1; e++) {
+ if (r[e] !== "text" || r[e + 1] !== "text" || !xp(t[e]) || !xp(t[e + 1])) continue;
+ let n = Bp(t[e]);
+ n !== null && (t[e] = n.head, t[e + 1] = n.tail + t[e + 1], i[e + 1] = i[e] + n.head.length);
+ }
+ return {
+ len: t.length,
+ texts: t,
+ isWordLike: n,
+ kinds: r,
+ starts: i
+ };
+}
+function mm(e, t, n) {
+ let r = hp(), i = 0, a = [], o = [], s = [], c = [], l = [], u = [], d = [], f = [], p = [], m = [], h = [], g = [];
+ for (let _ of r.segment(e)) for (let e of Zp(_.segment, _.isWordLike ?? !1, _.index, n)) {
+ let n = e.kind === "text", r = Vp(e.text, e.isWordLike, e.kind), _ = xp(e.text), v = yp(e.text), y = zp(e.text), b = Kp(e.text), x = Wp(e.text), S = i - 1;
+ function C() {
+ u[S] !== null && (o[S] = [Hp(a, u, d, S)], u[S] = null), o[S].push(e.text), s[S] = s[S] || e.isWordLike, f[S] = f[S] || _, p[S] = p[S] || v, m[S] = b, h[S] = x, g[S] = Up(p[S], y);
+ }
+ t.carryCJKAfterClosingQuote && n && i > 0 && c[S] === "text" && _ && f[S] && m[S] || n && i > 0 && c[S] === "text" && Fp(e.text) && f[S] || n && i > 0 && c[S] === "text" && h[S] ? C() : n && i > 0 && c[S] === "text" && e.isWordLike && v && g[S] ? (C(), s[S] = !0) : r !== null && i > 0 && c[S] === "text" && u[S] === r ? d[S] = (d[S] ?? 1) + 1 : n && !e.isWordLike && i > 0 && c[S] === "text" && (Pp(e.text) || e.text === "-" && s[S]) ? C() : (a[i] = e.text, o[i] = [e.text], s[i] = e.isWordLike, c[i] = e.kind, l[i] = e.start, u[i] = r, d[i] = r === null ? 0 : 1, f[i] = _, p[i] = v, m[i] = b, h[i] = x, g[i] = Up(v, y), i++);
+ }
+ for (let e = 0; e < i; e++) {
+ if (u[e] !== null) {
+ a[e] = Hp(a, u, d, e);
+ continue;
+ }
+ a[e] = Yp(o[e]);
+ }
+ for (let e = 1; e < i; e++) c[e] === "text" && !s[e] && Lp(a[e]) && c[e - 1] === "text" && (a[e - 1] += a[e], s[e - 1] = s[e - 1] || s[e], a[e] = "");
+ let _ = Array.from({ length: i }, () => null), v = -1;
+ for (let e = i - 1; e >= 0; e--) {
+ let t = a[e];
+ if (t.length !== 0) {
+ if (c[e] === "text" && !s[e] && Ip(t) && v >= 0 && c[v] === "text") {
+ let n = _[v] ?? [];
+ n.push(t), _[v] = n, l[v] = l[e], a[e] = "";
+ continue;
+ }
+ v = e;
+ }
+ }
+ for (let e = 0; e < i; e++) {
+ let t = _[e];
+ t != null && (a[e] = Xp(t, a[e]));
+ }
+ let y = 0;
+ for (let e = 0; e < i; e++) {
+ let t = a[e];
+ t.length !== 0 && (y !== e && (a[y] = t, s[y] = s[e], c[y] = c[e], l[y] = l[e]), y++);
+ }
+ a.length = y, s.length = y, c.length = y, l.length = y;
+ let b = pm(um(dm(lm(rm(nm(fm({
+ len: y,
+ texts: a,
+ isWordLike: s,
+ kinds: c,
+ starts: l
+ })))))));
+ for (let e = 0; e < b.len - 1; e++) {
+ let t = Gp(b.texts[e]);
+ t !== null && (b.kinds[e] !== "space" && b.kinds[e] !== "preserved-space" || b.kinds[e + 1] !== "text" || !yp(b.texts[e + 1]) || (b.texts[e] = t.space, b.isWordLike[e] = !1, b.kinds[e] = b.kinds[e] === "preserved-space" ? "preserved-space" : "space", b.texts[e + 1] = t.marks + b.texts[e + 1], b.starts[e + 1] = b.starts[e] + t.space.length));
+ }
+ return b;
+}
+function hm(e, t) {
+ if (e.len === 0) return [];
+ if (!t.preserveHardBreaks) return [{
+ startSegmentIndex: 0,
+ endSegmentIndex: e.len,
+ consumedEndSegmentIndex: e.len
+ }];
+ let n = [], r = 0;
+ for (let t = 0; t < e.len; t++) e.kinds[t] === "hard-break" && (n.push({
+ startSegmentIndex: r,
+ endSegmentIndex: t,
+ consumedEndSegmentIndex: t + 1
+ }), r = t + 1);
+ return r < e.len && n.push({
+ startSegmentIndex: r,
+ endSegmentIndex: e.len,
+ consumedEndSegmentIndex: e.len
+ }), n;
+}
+function gm(e) {
+ if (e.len <= 1) return e;
+ let t = [], n = [], r = [], i = [], a = null, o = !1, s = 0, c = !1, l = !1;
+ function u() {
+ a !== null && (t.push(Yp(a)), n.push(o), r.push("text"), i.push(s), a = null);
+ }
+ for (let d = 0; d < e.len; d++) {
+ let f = e.texts[d], p = e.kinds[d], m = e.isWordLike[d], h = e.starts[d];
+ if (p === "text") {
+ let e = wp(f), t = Ep(f);
+ if (a !== null && c && l) {
+ a.push(f), o ||= m, c ||= e, l = t;
+ continue;
+ }
+ u(), a = [f], o = m, s = h, c = e, l = t;
+ continue;
+ }
+ u(), t.push(f), n.push(m), r.push(p), i.push(h);
+ }
+ return u(), {
+ len: t.length,
+ texts: t,
+ isWordLike: n,
+ kinds: r,
+ starts: i
+ };
+}
+function _m(e, t, n = "normal", r = "normal") {
+ let i = up(n), a = i.mode === "pre-wrap" ? fp(e) : dp(e);
+ if (a.length === 0) return {
+ normalized: a,
+ chunks: [],
+ len: 0,
+ texts: [],
+ isWordLike: [],
+ kinds: [],
+ starts: []
+ };
+ let o = r === "keep-all" ? gm(mm(a, t, i)) : mm(a, t, i);
+ return {
+ normalized: a,
+ chunks: hm(o, i),
+ ...o
+ };
+}
+//#endregion
+//#region node_modules/@chenglou/pretext/dist/measurement.js
+var vm = null, ym = /* @__PURE__ */ new Map(), bm = null, xm = 96, Sm = /\p{Emoji_Presentation}/u, Cm = /[\p{Emoji_Presentation}\p{Extended_Pictographic}\p{Regional_Indicator}\uFE0F\u20E3]/u, wm = null, Tm = /* @__PURE__ */ new Map();
+function Em() {
+ if (vm !== null) return vm;
+ if (typeof OffscreenCanvas < "u") return vm = new OffscreenCanvas(1, 1).getContext("2d"), vm;
+ if (typeof document < "u") return vm = document.createElement("canvas").getContext("2d"), vm;
+ throw Error("Text measurement requires OffscreenCanvas or a DOM canvas context.");
+}
+function Dm(e) {
+ let t = ym.get(e);
+ return t || (t = /* @__PURE__ */ new Map(), ym.set(e, t)), t;
+}
+function Om(e, t) {
+ let n = t.get(e);
+ return n === void 0 && (n = {
+ width: Em().measureText(e).width,
+ containsCJK: xp(e)
+ }, t.set(e, n)), n;
+}
+function km() {
+ if (bm !== null) return bm;
+ if (typeof navigator > "u") return bm = {
+ lineFitEpsilon: .005,
+ carryCJKAfterClosingQuote: !1,
+ preferPrefixWidthsForBreakableRuns: !1,
+ preferEarlySoftHyphenBreak: !1
+ }, bm;
+ let e = navigator.userAgent, t = navigator.vendor === "Apple Computer, Inc." && e.includes("Safari/") && !e.includes("Chrome/") && !e.includes("Chromium/") && !e.includes("CriOS/") && !e.includes("FxiOS/") && !e.includes("EdgiOS/"), n = e.includes("Chrome/") || e.includes("Chromium/") || e.includes("CriOS/") || e.includes("Edg/");
+ return bm = {
+ lineFitEpsilon: t ? 1 / 64 : .005,
+ carryCJKAfterClosingQuote: n,
+ preferPrefixWidthsForBreakableRuns: t,
+ preferEarlySoftHyphenBreak: t
+ }, bm;
+}
+function Am(e) {
+ let t = e.match(/(\d+(?:\.\d+)?)\s*px/);
+ return t ? parseFloat(t[1]) : 16;
+}
+function jm() {
+ return wm === null && (wm = new Intl.Segmenter(void 0, { granularity: "grapheme" })), wm;
+}
+function Mm(e) {
+ return Sm.test(e) || e.includes("️");
+}
+function Nm(e) {
+ return Cm.test(e);
+}
+function Pm(e, t) {
+ let n = Tm.get(e);
+ if (n !== void 0) return n;
+ let r = Em();
+ r.font = e;
+ let i = r.measureText("😀").width;
+ if (n = 0, i > t + .5 && typeof document < "u" && document.body !== null) {
+ let t = document.createElement("span");
+ t.style.font = e, t.style.display = "inline-block", t.style.visibility = "hidden", t.style.position = "absolute", t.textContent = "😀", document.body.appendChild(t);
+ let r = t.getBoundingClientRect().width;
+ document.body.removeChild(t), i - r > .5 && (n = i - r);
+ }
+ return Tm.set(e, n), n;
+}
+function Fm(e) {
+ let t = 0, n = jm();
+ for (let r of n.segment(e)) Mm(r.segment) && t++;
+ return t;
+}
+function Im(e, t) {
+ return t.emojiCount === void 0 && (t.emojiCount = Fm(e)), t.emojiCount;
+}
+function Lm(e, t, n) {
+ return n === 0 ? t.width : t.width - Im(e, t) * n;
+}
+function Rm(e, t, n, r, i) {
+ if (t.breakableFitAdvances !== void 0) return t.breakableFitAdvances;
+ let a = jm(), o = [];
+ for (let t of a.segment(e)) o.push(t.segment);
+ if (o.length <= 1) return t.breakableFitAdvances = null, t.breakableFitAdvances;
+ if (i === "sum-graphemes") {
+ let e = [];
+ for (let t of o) {
+ let i = Om(t, n);
+ e.push(Lm(t, i, r));
+ }
+ return t.breakableFitAdvances = e, t.breakableFitAdvances;
+ }
+ if (i === "pair-context" || o.length > xm) {
+ let e = [], i = null, a = 0;
+ for (let t of o) {
+ let o = Lm(t, Om(t, n), r);
+ if (i === null) e.push(o);
+ else {
+ let o = i + t, s = Om(o, n);
+ e.push(Lm(o, s, r) - a);
+ }
+ i = t, a = o;
+ }
+ return t.breakableFitAdvances = e, t.breakableFitAdvances;
+ }
+ let s = [], c = "", l = 0;
+ for (let e of o) {
+ c += e;
+ let t = Om(c, n), i = Lm(c, t, r);
+ s.push(i - l), l = i;
+ }
+ return t.breakableFitAdvances = s, t.breakableFitAdvances;
+}
+function zm(e, t) {
+ let n = Em();
+ n.font = e;
+ let r = Dm(e), i = Am(e);
+ return {
+ cache: r,
+ fontSize: i,
+ emojiCorrection: t ? Pm(e, i) : 0
+ };
+}
+//#endregion
+//#region node_modules/@chenglou/pretext/dist/line-break.js
+function Bm(e, t) {
+ for (; t < e.widths.length;) {
+ let n = e.kinds[t];
+ if (n !== "space" && n !== "zero-width-break" && n !== "soft-hyphen") break;
+ t++;
+ }
+ return t;
+}
+function Vm(e, t) {
+ if (t <= 0) return 0;
+ let n = e % t;
+ return Math.abs(n) <= 1e-6 ? t : t - n;
+}
+function Hm(e, t, n, r, i) {
+ let a = 0, o = t;
+ for (; a < e.length;) {
+ let t = o + e[a];
+ if ((a + 1 < e.length ? t + i : t) > n + r) break;
+ o = t, a++;
+ }
+ return {
+ fitCount: a,
+ fittedWidth: o
+ };
+}
+function Um(e, t) {
+ let n = 0, r = e.chunks.length;
+ for (; n < r;) {
+ let i = Math.floor((n + r) / 2);
+ t < e.chunks[i].consumedEndSegmentIndex ? r = i : n = i + 1;
+ }
+ return n < e.chunks.length ? n : -1;
+}
+function Wm(e, t, n) {
+ let r = n.segmentIndex;
+ if (n.graphemeIndex > 0) return t;
+ let i = e.chunks[t];
+ if (i.startSegmentIndex === i.endSegmentIndex && r === i.startSegmentIndex) return n.segmentIndex = r, n.graphemeIndex = 0, t;
+ for (r < i.startSegmentIndex && (r = i.startSegmentIndex); r < i.endSegmentIndex;) {
+ let i = e.kinds[r];
+ if (i !== "space" && i !== "zero-width-break" && i !== "soft-hyphen") return n.segmentIndex = r, n.graphemeIndex = 0, t;
+ r++;
+ }
+ return i.consumedEndSegmentIndex >= e.widths.length ? -1 : (n.segmentIndex = i.consumedEndSegmentIndex, n.graphemeIndex = 0, t + 1);
+}
+function Gm(e, t) {
+ if (t.segmentIndex >= e.widths.length) return -1;
+ let n = Um(e, t.segmentIndex);
+ return n < 0 ? -1 : Wm(e, n, t);
+}
+function Km(e, t, n) {
+ if (n.segmentIndex >= e.widths.length) return -1;
+ let r = t;
+ for (; r < e.chunks.length && n.segmentIndex >= e.chunks[r].consumedEndSegmentIndex;) r++;
+ return r >= e.chunks.length ? -1 : Wm(e, r, n);
+}
+function qm(e, t) {
+ return e.simpleLineWalkFastPath ? Jm(e, t) : Ym(e, t);
+}
+function Jm(e, t, n) {
+ let { widths: r, kinds: i, breakableFitAdvances: a } = e;
+ if (r.length === 0) return 0;
+ let o = t + km().lineFitEpsilon, s = 0, c = 0, l = !1, u = 0, d = 0, f = 0, p = 0, m = -1, h = 0;
+ function g() {
+ m = -1, h = 0;
+ }
+ function _(e = f, t = p, r = c) {
+ s++, n?.({
+ startSegmentIndex: u,
+ startGraphemeIndex: d,
+ endSegmentIndex: e,
+ endGraphemeIndex: t,
+ width: r
+ }), c = 0, l = !1, g();
+ }
+ function v(e, t) {
+ l = !0, u = e, d = 0, f = e + 1, p = 0, c = t;
+ }
+ function y(e, t, n) {
+ l = !0, u = e, d = t, f = e, p = t + 1, c = n;
+ }
+ function b(e, t) {
+ if (!l) {
+ v(e, t);
+ return;
+ }
+ c += t, f = e + 1, p = 0;
+ }
+ function x(e, t) {
+ let n = a[e];
+ for (let r = t; r < n.length; r++) {
+ let t = n[r];
+ l ? c + t > o ? (_(), y(e, r, t)) : (c += t, f = e, p = r + 1) : y(e, r, t);
+ }
+ l && f === e && p === n.length && (f = e + 1, p = 0);
+ }
+ let S = 0;
+ for (; S < r.length && !(!l && (S = Bm(e, S), S >= r.length));) {
+ let e = r[S], n = i[S], s = n === "space" || n === "preserved-space" || n === "tab" || n === "zero-width-break" || n === "soft-hyphen";
+ if (!l) {
+ e > t && a[S] !== null ? x(S, 0) : v(S, e), s && (m = S + 1, h = c - e), S++;
+ continue;
+ }
+ if (c + e > o) {
+ if (s) {
+ b(S, e), _(S + 1, 0, c - e), S++;
+ continue;
+ }
+ if (m >= 0) {
+ if (f > m || f === m && p > 0) {
+ _();
+ continue;
+ }
+ _(m, 0, h);
+ continue;
+ }
+ if (e > t && a[S] !== null) {
+ _(), x(S, 0), S++;
+ continue;
+ }
+ _();
+ continue;
+ }
+ b(S, e), s && (m = S + 1, h = c - e), S++;
+ }
+ return l && _(), s;
+}
+function Ym(e, t, n) {
+ if (e.simpleLineWalkFastPath) return Jm(e, t, n);
+ let { widths: r, lineEndFitAdvances: i, lineEndPaintAdvances: a, kinds: o, breakableFitAdvances: s, discretionaryHyphenWidth: c, tabStopAdvance: l, chunks: u } = e;
+ if (r.length === 0 || u.length === 0) return 0;
+ let d = km(), f = d.lineFitEpsilon, p = t + f, m = 0, h = 0, g = !1, _ = 0, v = 0, y = 0, b = 0, x = -1, S = 0, C = 0, w = null;
+ function T() {
+ x = -1, S = 0, C = 0, w = null;
+ }
+ function E(e = y, t = b, r = h) {
+ m++, n?.({
+ startSegmentIndex: _,
+ startGraphemeIndex: v,
+ endSegmentIndex: e,
+ endGraphemeIndex: t,
+ width: r
+ }), h = 0, g = !1, T();
+ }
+ function D(e, t) {
+ g = !0, _ = e, v = 0, y = e + 1, b = 0, h = t;
+ }
+ function O(e, t, n) {
+ g = !0, _ = e, v = t, y = e, b = t + 1, h = n;
+ }
+ function k(e, t) {
+ if (!g) {
+ D(e, t);
+ return;
+ }
+ h += t, y = e + 1, b = 0;
+ }
+ function ee(e, t, n, r) {
+ if (!t) return;
+ let o = e === "tab" ? 0 : i[n], s = e === "tab" ? r : a[n];
+ x = n + 1, S = h - r + o, C = h - r + s, w = e;
+ }
+ function A(e, t) {
+ let n = s[e];
+ for (let r = t; r < n.length; r++) {
+ let t = n[r];
+ g ? h + t > p ? (E(), O(e, r, t)) : (h += t, y = e, b = r + 1) : O(e, r, t);
+ }
+ g && y === e && b === n.length && (y = e + 1, b = 0);
+ }
+ function te(e) {
+ if (w !== "soft-hyphen") return !1;
+ let n = s[e];
+ if (n == null) return !1;
+ let { fitCount: r, fittedWidth: i } = Hm(n, h, t, f, c);
+ return r === 0 ? !1 : (h = i, y = e, b = r, T(), r === n.length ? (y = e + 1, b = 0, !0) : (E(e, r, i + c), A(e, r), !0));
+ }
+ function ne(e) {
+ m++, n?.({
+ startSegmentIndex: e.startSegmentIndex,
+ startGraphemeIndex: 0,
+ endSegmentIndex: e.consumedEndSegmentIndex,
+ endGraphemeIndex: 0,
+ width: 0
+ }), T();
+ }
+ for (let e = 0; e < u.length; e++) {
+ let n = u[e];
+ if (n.startSegmentIndex === n.endSegmentIndex) {
+ ne(n);
+ continue;
+ }
+ g = !1, h = 0, _ = n.startSegmentIndex, v = 0, y = n.startSegmentIndex, b = 0, T();
+ let f = n.startSegmentIndex;
+ for (; f < n.endSegmentIndex;) {
+ let e = o[f], n = e === "space" || e === "preserved-space" || e === "tab" || e === "zero-width-break" || e === "soft-hyphen", u = e === "tab" ? Vm(h, l) : r[f];
+ if (e === "soft-hyphen") {
+ g && (y = f + 1, b = 0, x = f + 1, S = h + c, C = h + c, w = e), f++;
+ continue;
+ }
+ if (!g) {
+ u > t && s[f] !== null ? A(f, 0) : D(f, u), ee(e, n, f, u), f++;
+ continue;
+ }
+ if (h + u > p) {
+ let r = h + (e === "tab" ? 0 : i[f]), o = h + (e === "tab" ? u : a[f]);
+ if (w === "soft-hyphen" && d.preferEarlySoftHyphenBreak && S <= p) {
+ E(x, 0, C);
+ continue;
+ }
+ if (w === "soft-hyphen" && te(f)) {
+ f++;
+ continue;
+ }
+ if (n && r <= p) {
+ k(f, u), E(f + 1, 0, o), f++;
+ continue;
+ }
+ if (x >= 0 && S <= p) {
+ if (y > x || y === x && b > 0) {
+ E();
+ continue;
+ }
+ let e = x;
+ E(e, 0, C), f = e;
+ continue;
+ }
+ if (u > t && s[f] !== null) {
+ E(), A(f, 0), f++;
+ continue;
+ }
+ E();
+ continue;
+ }
+ k(f, u), ee(e, n, f, u), f++;
+ }
+ if (g) {
+ let e = x === n.consumedEndSegmentIndex ? C : h;
+ E(n.consumedEndSegmentIndex, 0, e);
+ }
+ }
+ return m;
+}
+function Xm(e, t, n, r) {
+ let i = e.chunks[n];
+ if (i.startSegmentIndex === i.endSegmentIndex) return t.segmentIndex = i.consumedEndSegmentIndex, t.graphemeIndex = 0, 0;
+ let { widths: a, lineEndFitAdvances: o, lineEndPaintAdvances: s, kinds: c, breakableFitAdvances: l, discretionaryHyphenWidth: u, tabStopAdvance: d } = e, f = km(), p = f.lineFitEpsilon, m = r + p, h = 0, g = !1, _ = t.segmentIndex, v = t.graphemeIndex, y = -1, b = 0, x = 0, S = null;
+ function C() {
+ y = -1, b = 0, x = 0, S = null;
+ }
+ function w(e = _, n = v, r = h) {
+ return g ? (t.segmentIndex = e, t.graphemeIndex = n, r) : null;
+ }
+ function T(e, t) {
+ g = !0, _ = e + 1, v = 0, h = t;
+ }
+ function E(e, t, n) {
+ g = !0, _ = e, v = t + 1, h = n;
+ }
+ function D(e, t) {
+ if (!g) {
+ T(e, t);
+ return;
+ }
+ h += t, _ = e + 1, v = 0;
+ }
+ function O(e, t, n, r) {
+ if (!t) return;
+ let i = e === "tab" ? 0 : o[n], a = e === "tab" ? r : s[n];
+ y = n + 1, b = h - r + i, x = h - r + a, S = e;
+ }
+ function k(e, t) {
+ let n = l[e];
+ for (let r = t; r < n.length; r++) {
+ let t = n[r];
+ if (!g) E(e, r, t);
+ else {
+ if (h + t > m) return w();
+ h += t, _ = e, v = r + 1;
+ }
+ }
+ return g && _ === e && v === n.length && (_ = e + 1, v = 0), null;
+ }
+ function ee(e) {
+ if (S !== "soft-hyphen" || y < 0) return null;
+ let t = l[e] ?? null;
+ if (t !== null) {
+ let { fitCount: n, fittedWidth: i } = Hm(t, h, r, p, u);
+ if (n === t.length) return h = i, _ = e + 1, v = 0, C(), null;
+ if (n > 0) return w(e, n, i + u);
+ }
+ return b <= m ? w(y, 0, x) : null;
+ }
+ for (let e = t.segmentIndex; e < i.endSegmentIndex; e++) {
+ let n = c[e], i = n === "space" || n === "preserved-space" || n === "tab" || n === "zero-width-break" || n === "soft-hyphen", p = e === t.segmentIndex ? t.graphemeIndex : 0, C = n === "tab" ? Vm(h, d) : a[e];
+ if (n === "soft-hyphen" && p === 0) {
+ g && (_ = e + 1, v = 0, y = e + 1, b = h + u, x = h + u, S = n);
+ continue;
+ }
+ if (!g) {
+ if (p > 0) {
+ let t = k(e, p);
+ if (t !== null) return t;
+ } else if (C > r && l[e] !== null) {
+ let t = k(e, 0);
+ if (t !== null) return t;
+ } else T(e, C);
+ O(n, i, e, C);
+ continue;
+ }
+ if (h + C > m) {
+ let t = h + (n === "tab" ? 0 : o[e]), a = h + (n === "tab" ? C : s[e]);
+ if (S === "soft-hyphen" && f.preferEarlySoftHyphenBreak && b <= m) return w(y, 0, x);
+ let c = ee(e);
+ if (c !== null) return c;
+ if (i && t <= m) return D(e, C), w(e + 1, 0, a);
+ if (y >= 0 && b <= m) return _ > y || _ === y && v > 0 ? w() : w(y, 0, x);
+ if (C > r && l[e] !== null) {
+ let t = w();
+ if (t !== null) return t;
+ let n = k(e, 0);
+ if (n !== null) return n;
+ }
+ return w();
+ }
+ D(e, C), O(n, i, e, C);
+ }
+ return y === i.consumedEndSegmentIndex && v === 0 ? w(i.consumedEndSegmentIndex, 0, x) : w(i.consumedEndSegmentIndex, 0, h);
+}
+function Zm(e, t, n) {
+ let { widths: r, kinds: i, breakableFitAdvances: a } = e, o = n + km().lineFitEpsilon, s = 0, c = !1, l = t.segmentIndex, u = t.graphemeIndex, d = -1, f = 0;
+ for (let e = t.segmentIndex; e < r.length; e++) {
+ let p = r[e], m = i[e], h = m === "space" || m === "preserved-space" || m === "tab" || m === "zero-width-break" || m === "soft-hyphen", g = e === t.segmentIndex ? t.graphemeIndex : 0, _ = a[e];
+ if (!c) {
+ if (g > 0 || p > n && _ !== null) {
+ let n = _, r = n[g];
+ c = !0, s = r, l = e, u = g + 1;
+ for (let r = g + 1; r < n.length; r++) {
+ let i = n[r];
+ if (s + i > o) return t.segmentIndex = l, t.graphemeIndex = u, s;
+ s += i, l = e, u = r + 1;
+ }
+ l === e && u === n.length && (l = e + 1, u = 0);
+ } else c = !0, s = p, l = e + 1, u = 0;
+ h && (d = e + 1, f = s - p);
+ continue;
+ }
+ if (s + p > o) return h ? (t.segmentIndex = e + 1, t.graphemeIndex = 0, s) : d >= 0 ? l > d || l === d && u > 0 ? (t.segmentIndex = l, t.graphemeIndex = u, s) : (t.segmentIndex = d, t.graphemeIndex = 0, f) : (t.segmentIndex = l, t.graphemeIndex = u, s);
+ s += p, l = e + 1, u = 0, h && (d = e + 1, f = s - p);
+ }
+ return c ? (t.segmentIndex = l, t.graphemeIndex = u, s) : null;
+}
+function Qm(e, t, n) {
+ let r = {
+ segmentIndex: t.segmentIndex,
+ graphemeIndex: t.graphemeIndex
+ }, i = Gm(e, r);
+ if (i < 0) return null;
+ let a = r.segmentIndex, o = r.graphemeIndex, s = e.simpleLineWalkFastPath ? Zm(e, r, n) : Xm(e, r, i, n);
+ return s === null ? null : {
+ startSegmentIndex: a,
+ startGraphemeIndex: o,
+ endSegmentIndex: r.segmentIndex,
+ endGraphemeIndex: r.graphemeIndex,
+ width: s
+ };
+}
+function $m(e, t, n) {
+ let r = Gm(e, t);
+ return r < 0 ? null : e.simpleLineWalkFastPath ? Zm(e, t, n) : Xm(e, t, r, n);
+}
+function eh(e, t) {
+ if (e.widths.length === 0) return {
+ lineCount: 0,
+ maxLineWidth: 0
+ };
+ let n = {
+ segmentIndex: 0,
+ graphemeIndex: 0
+ }, r = 0, i = 0;
+ if (!e.simpleLineWalkFastPath) {
+ let a = Gm(e, n);
+ for (; a >= 0;) {
+ let o = Xm(e, n, a, t);
+ if (o === null) return {
+ lineCount: r,
+ maxLineWidth: i
+ };
+ r++, o > i && (i = o), a = Km(e, a, n);
+ }
+ return {
+ lineCount: r,
+ maxLineWidth: i
+ };
+ }
+ for (;;) {
+ let a = $m(e, n, t);
+ if (a === null) return {
+ lineCount: r,
+ maxLineWidth: i
+ };
+ r++, a > i && (i = a);
+ }
+}
+//#endregion
+//#region node_modules/@chenglou/pretext/dist/layout.js
+var th = null, nh = /* @__PURE__ */ new WeakMap();
+function rh() {
+ return th === null && (th = new Intl.Segmenter(void 0, { granularity: "grapheme" })), th;
+}
+function ih(e) {
+ return e ? {
+ widths: [],
+ lineEndFitAdvances: [],
+ lineEndPaintAdvances: [],
+ kinds: [],
+ simpleLineWalkFastPath: !0,
+ segLevels: null,
+ breakableFitAdvances: [],
+ discretionaryHyphenWidth: 0,
+ tabStopAdvance: 0,
+ chunks: [],
+ segments: []
+ } : {
+ widths: [],
+ lineEndFitAdvances: [],
+ lineEndPaintAdvances: [],
+ kinds: [],
+ simpleLineWalkFastPath: !0,
+ segLevels: null,
+ breakableFitAdvances: [],
+ discretionaryHyphenWidth: 0,
+ tabStopAdvance: 0,
+ chunks: []
+ };
+}
+function ah(e, t) {
+ let n = [], r = [], i = 0, a = !1, o = !1, s = !1;
+ function c() {
+ r.length !== 0 && (n.push({
+ text: r.length === 1 ? r[0] : r.join(""),
+ start: i
+ }), r = [], a = !1, o = !1, s = !1);
+ }
+ function l(e, t, n) {
+ r = [e], i = t, a = n, o = Kp(e), s = Op.has(e);
+ }
+ function u(e, t) {
+ r.push(e), a ||= t;
+ let n = Kp(e);
+ e.length === 1 && Ap.has(e) ? o ||= n : o = n, s = !1;
+ }
+ for (let n of rh().segment(e)) {
+ let e = n.segment, i = xp(e);
+ if (r.length === 0) {
+ l(e, n.index, i);
+ continue;
+ }
+ if (s || Dp.has(e) || Ap.has(e) || t.carryCJKAfterClosingQuote && i && o) {
+ u(e, i);
+ continue;
+ }
+ if (!a && !i) {
+ u(e, i);
+ continue;
+ }
+ c(), l(e, n.index, i);
+ }
+ return c(), n;
+}
+function oh(e) {
+ if (e.length <= 1) return e;
+ let t = [], n = [e[0].text], r = e[0].start, i = xp(e[0].text), a = Ep(e[0].text);
+ function o() {
+ t.push({
+ text: n.length === 1 ? n[0] : n.join(""),
+ start: r
+ });
+ }
+ for (let t = 1; t < e.length; t++) {
+ let s = e[t], c = xp(s.text), l = Ep(s.text);
+ if (i && a) {
+ n.push(s.text), i ||= c, a = l;
+ continue;
+ }
+ o(), n = [s.text], r = s.start, i = c, a = l;
+ }
+ return o(), t;
+}
+function sh(e, t, n, r) {
+ let i = km(), { cache: a, emojiCorrection: o } = zm(t, Nm(e.normalized)), s = Lm("-", Om("-", a), o), c = Lm(" ", Om(" ", a), o) * 8;
+ if (e.len === 0) return ih(n);
+ let l = [], u = [], d = [], f = [], p = e.chunks.length <= 1, m = n ? [] : null, h = [], g = n ? [] : null, _ = Array.from({ length: e.len });
+ function v(e, t, n, r, i, a, o) {
+ i !== "text" && i !== "space" && i !== "zero-width-break" && (p = !1), l.push(t), u.push(n), d.push(r), f.push(i), m?.push(a), h.push(o), g !== null && g.push(e);
+ }
+ function y(e, t, n, r, s) {
+ let c = Om(e, a), l = Lm(e, c, o), u = t === "space" || t === "preserved-space" || t === "zero-width-break" ? 0 : l, d = t === "space" || t === "zero-width-break" ? 0 : l;
+ if (s && r && e.length > 1) {
+ let r = "sum-graphemes";
+ cm(e) ? r = "pair-context" : i.preferPrefixWidthsForBreakableRuns && (r = "segment-prefixes"), v(e, l, u, d, t, n, Rm(e, c, a, o, r));
+ return;
+ }
+ v(e, l, u, d, t, n, null);
+ }
+ for (let t = 0; t < e.len; t++) {
+ _[t] = l.length;
+ let n = e.texts[t], o = e.isWordLike[t], c = e.kinds[t], u = e.starts[t];
+ if (c === "soft-hyphen") {
+ v(n, 0, s, s, c, u, null);
+ continue;
+ }
+ if (c === "hard-break") {
+ v(n, 0, 0, 0, c, u, null);
+ continue;
+ }
+ if (c === "tab") {
+ v(n, 0, 0, 0, c, u, null);
+ continue;
+ }
+ let d = Om(n, a);
+ if (c === "text" && d.containsCJK) {
+ let e = ah(n, i), t = r === "keep-all" ? oh(e) : e;
+ for (let e = 0; e < t.length; e++) {
+ let n = t[e];
+ y(n.text, "text", u + n.start, o, r === "keep-all" || !xp(n.text));
+ }
+ continue;
+ }
+ y(n, c, u, o, !0);
+ }
+ let b = ch(e.chunks, _, l.length), x = m === null ? null : sp(e.normalized, m);
+ return g === null ? {
+ widths: l,
+ lineEndFitAdvances: u,
+ lineEndPaintAdvances: d,
+ kinds: f,
+ simpleLineWalkFastPath: p,
+ segLevels: x,
+ breakableFitAdvances: h,
+ discretionaryHyphenWidth: s,
+ tabStopAdvance: c,
+ chunks: b
+ } : {
+ widths: l,
+ lineEndFitAdvances: u,
+ lineEndPaintAdvances: d,
+ kinds: f,
+ simpleLineWalkFastPath: p,
+ segLevels: x,
+ breakableFitAdvances: h,
+ discretionaryHyphenWidth: s,
+ tabStopAdvance: c,
+ chunks: b,
+ segments: g
+ };
+}
+function ch(e, t, n) {
+ let r = [];
+ for (let i = 0; i < e.length; i++) {
+ let a = e[i], o = a.startSegmentIndex < t.length ? t[a.startSegmentIndex] : n, s = a.endSegmentIndex < t.length ? t[a.endSegmentIndex] : n, c = a.consumedEndSegmentIndex < t.length ? t[a.consumedEndSegmentIndex] : n;
+ r.push({
+ startSegmentIndex: o,
+ endSegmentIndex: s,
+ consumedEndSegmentIndex: c
+ });
+ }
+ return r;
+}
+function lh(e, t, n, r) {
+ let i = r?.wordBreak ?? "normal";
+ return sh(_m(e, km(), r?.whiteSpace, i), t, n, i);
+}
+function uh(e, t, n) {
+ return lh(e, t, !1, n);
+}
+function dh(e, t, n) {
+ return lh(e, t, !0, n);
+}
+function fh(e) {
+ return e;
+}
+function ph(e, t, n) {
+ let r = qm(fh(e), t);
+ return {
+ lineCount: r,
+ height: r * n
+ };
+}
+function mh(e, t, n) {
+ let r = n.get(e);
+ if (r !== void 0) return r;
+ r = [];
+ let i = rh();
+ for (let n of i.segment(t[e])) r.push(n.segment);
+ return n.set(e, r), r;
+}
+function hh(e) {
+ let t = nh.get(e);
+ return t === void 0 ? (t = /* @__PURE__ */ new Map(), nh.set(e, t), t) : t;
+}
+function gh(e, t, n, r) {
+ return r > 0 && e[r - 1] === "soft-hyphen" && !(t === r && n > 0);
+}
+function _h(e, t, n, r, i, a, o) {
+ let s = "", c = gh(t, r, i, a);
+ for (let o = r; o < a; o++) t[o] === "soft-hyphen" || t[o] === "hard-break" || (o === r && i > 0 ? s += mh(o, e, n).slice(i).join("") : s += e[o]);
+ return o > 0 ? (c && (s += "-"), s += mh(a, e, n).slice(r === a ? i : 0, o).join("")) : c && (s += "-"), s;
+}
+function vh(e, t, n, r, i, a, o) {
+ return {
+ text: _h(e.segments, e.kinds, t, r, i, a, o),
+ width: n,
+ start: {
+ segmentIndex: r,
+ graphemeIndex: i
+ },
+ end: {
+ segmentIndex: a,
+ graphemeIndex: o
+ }
+ };
+}
+function yh(e, t, n) {
+ return vh(e, t, n.width, n.startSegmentIndex, n.startGraphemeIndex, n.endSegmentIndex, n.endGraphemeIndex);
+}
+function bh(e) {
+ return {
+ width: e.width,
+ start: {
+ segmentIndex: e.startSegmentIndex,
+ graphemeIndex: e.startGraphemeIndex
+ },
+ end: {
+ segmentIndex: e.endSegmentIndex,
+ graphemeIndex: e.endGraphemeIndex
+ }
+ };
+}
+function xh(e, t) {
+ return vh(e, hh(e), t.width, t.start.segmentIndex, t.start.graphemeIndex, t.end.segmentIndex, t.end.graphemeIndex);
+}
+function Sh(e, t, n) {
+ return e.widths.length === 0 ? 0 : Ym(fh(e), t, (e) => {
+ n(bh(e));
+ });
+}
+function Ch(e, t) {
+ return eh(fh(e), t);
+}
+function wh(e) {
+ let t = 0;
+ return Sh(e, Infinity, (e) => {
+ e.width > t && (t = e.width);
+ }), t;
+}
+function Th(e, t, n) {
+ let r = [];
+ if (e.widths.length === 0) return {
+ lineCount: 0,
+ height: 0,
+ lines: r
+ };
+ let i = hh(e), a = Ym(fh(e), t, (t) => {
+ r.push(yh(e, i, t));
+ });
+ return {
+ lineCount: a,
+ height: a * n,
+ lines: r
+ };
+}
+//#endregion
+//#region node_modules/@chenglou/pretext/dist/rich-inline.js
+var Eh = /[ \t\n\f\r]+/, Dh = /^[ \t\n\f\r]+/, Oh = /[ \t\n\f\r]+$/, kh = {
+ segmentIndex: 0,
+ graphemeIndex: 0
+}, Ah = {
+ itemIndex: 0,
+ segmentIndex: 0,
+ graphemeIndex: 0
+};
+function jh(e) {
+ return e;
+}
+function Mh(e) {
+ return {
+ segmentIndex: e.segmentIndex,
+ graphemeIndex: e.graphemeIndex
+ };
+}
+function Nh(e) {
+ return e.segmentIndex === 0 && e.graphemeIndex === 0;
+}
+function Ph(e, t) {
+ let n = t.get(e);
+ if (n !== void 0) return n;
+ let r = wh(dh("A A", e)), i = wh(dh("AA", e)), a = Math.max(0, r - i);
+ return t.set(e, a), a;
+}
+function Fh(e) {
+ let t = Qm(e, kh, Infinity);
+ return t === null ? null : {
+ endGraphemeIndex: t.endGraphemeIndex,
+ endSegmentIndex: t.endSegmentIndex,
+ width: t.width
+ };
+}
+function Ih(e, t) {
+ return e === 0 && t > 0;
+}
+function Lh(e) {
+ let t = [], n = Array.from({ length: e.length }), r = /* @__PURE__ */ new Map(), i = 0;
+ for (let a = 0; a < e.length; a++) {
+ let o = e[a], s = Dh.test(o.text), c = Oh.test(o.text), l = o.text.replace(Dh, "").replace(Oh, "");
+ if (l.length === 0) {
+ Eh.test(o.text) && i === 0 && (i = Ph(o.font, r));
+ continue;
+ }
+ let u = i > 0 ? i : s ? Ph(o.font, r) : 0, d = dh(l, o.font), f = Fh(d);
+ if (f === null) {
+ i = c ? Ph(o.font, r) : 0;
+ continue;
+ }
+ let p = {
+ break: o.break ?? "normal",
+ endGraphemeIndex: f.endGraphemeIndex,
+ endSegmentIndex: f.endSegmentIndex,
+ extraWidth: o.extraWidth ?? 0,
+ gapBefore: u,
+ naturalWidth: f.width,
+ prepared: d,
+ sourceItemIndex: a
+ };
+ t.push(p), n[a] = p, i = c ? Ph(o.font, r) : 0;
+ }
+ return {
+ items: t,
+ itemsBySourceItemIndex: n
+ };
+}
+function Rh(e, t, n, r) {
+ if (e.items.length === 0 || n.itemIndex >= e.items.length) return null;
+ let i = Math.max(1, t), a = 0, o = i, s = n.itemIndex, c = {
+ segmentIndex: n.segmentIndex,
+ graphemeIndex: n.graphemeIndex
+ };
+ lineLoop: for (; s < e.items.length;) {
+ let t = e.items[s];
+ if (!Nh(c) && c.segmentIndex === t.endSegmentIndex && c.graphemeIndex === t.endGraphemeIndex) {
+ s++, c.segmentIndex = 0, c.graphemeIndex = 0;
+ continue;
+ }
+ let n = a === 0 ? 0 : t.gapBefore, l = Nh(c);
+ if (t.break === "never") {
+ if (!l) {
+ s++, c.segmentIndex = 0, c.graphemeIndex = 0;
+ continue;
+ }
+ let e = t.naturalWidth + t.extraWidth, u = n + e;
+ if (a > 0 && u > o) break lineLoop;
+ r?.(t, n, e, Mh(kh), {
+ segmentIndex: t.endSegmentIndex,
+ graphemeIndex: t.endGraphemeIndex
+ }), a += u, o = Math.max(0, i - a), s++, c.segmentIndex = 0, c.graphemeIndex = 0;
+ continue;
+ }
+ let u = n + t.extraWidth;
+ if (a > 0 && u >= o) break lineLoop;
+ if (l) {
+ let e = u + t.naturalWidth;
+ if (e <= o) {
+ r?.(t, n, t.naturalWidth + t.extraWidth, Mh(kh), {
+ segmentIndex: t.endSegmentIndex,
+ graphemeIndex: t.endGraphemeIndex
+ }), a += e, o = Math.max(0, i - a), s++, c.segmentIndex = 0, c.graphemeIndex = 0;
+ continue;
+ }
+ }
+ let d = Math.max(1, o - u), f = Qm(t.prepared, c, d);
+ if (f === null) {
+ s++, c.segmentIndex = 0, c.graphemeIndex = 0;
+ continue;
+ }
+ if (c.segmentIndex === f.endSegmentIndex && c.graphemeIndex === f.endGraphemeIndex) {
+ s++, c.segmentIndex = 0, c.graphemeIndex = 0;
+ continue;
+ }
+ if (a > 0 && l && n > 0 && Ih(f.endSegmentIndex, f.endGraphemeIndex)) {
+ let e = Qm(t.prepared, kh, Math.max(1, i - t.extraWidth));
+ if (e !== null && (e.endSegmentIndex > f.endSegmentIndex || e.endSegmentIndex === f.endSegmentIndex && e.endGraphemeIndex > f.endGraphemeIndex)) break lineLoop;
+ }
+ if (r?.(t, n, f.width + t.extraWidth, Mh(c), {
+ segmentIndex: f.endSegmentIndex,
+ graphemeIndex: f.endGraphemeIndex
+ }), a += n + f.width + t.extraWidth, o = Math.max(0, i - a), f.endSegmentIndex === t.endSegmentIndex && f.endGraphemeIndex === t.endGraphemeIndex) {
+ s++, c.segmentIndex = 0, c.graphemeIndex = 0;
+ continue;
+ }
+ c.segmentIndex = f.endSegmentIndex, c.graphemeIndex = f.endGraphemeIndex;
+ break;
+ }
+ return a === 0 ? null : (n.itemIndex = s, n.segmentIndex = c.segmentIndex, n.graphemeIndex = c.graphemeIndex, a);
+}
+function zh(e, t, n = Ah) {
+ let r = jh(e), i = {
+ itemIndex: n.itemIndex,
+ segmentIndex: n.segmentIndex,
+ graphemeIndex: n.graphemeIndex
+ }, a = [], o = Rh(r, t, i, (e, t, n, r, i) => {
+ a.push({
+ itemIndex: e.sourceItemIndex,
+ gapBefore: t,
+ occupiedWidth: n,
+ start: r,
+ end: i
+ });
+ });
+ return o === null ? null : {
+ fragments: a,
+ width: o,
+ end: i
+ };
+}
+function Bh(e, t) {
+ return xh(e.prepared, {
+ width: t.occupiedWidth - e.extraWidth,
+ start: t.start,
+ end: t.end
+ }).text;
+}
+function Vh(e, t) {
+ let n = jh(e);
+ return {
+ fragments: t.fragments.map((e) => {
+ let t = n.itemsBySourceItemIndex[e.itemIndex];
+ if (t === void 0) throw Error("Missing rich-text inline item for fragment");
+ return {
+ ...e,
+ text: Bh(t, e)
+ };
+ }),
+ width: t.width,
+ end: t.end
+ };
+}
+function Hh(e, t, n) {
+ let r = 0, i = Ah;
+ for (;;) {
+ let a = zh(e, t, i);
+ if (a === null) return r;
+ n(a), r++, i = a.end;
+ }
+}
+//#endregion
+//#region src/model-info.js
+var Uh = "500 14px Inter, sans-serif", Wh = "600 10px Inter, sans-serif", Gh = "300 13px Inter, sans-serif", Kh = "600 10px Inter, sans-serif", qh = "300 12px Inter, sans-serif", Jh = 18, Yh = 16, Xh = 16, Zh = 6, Qh = 12, $h = Math.min(window.devicePixelRatio || 1, 2), eg = "rgba(0, 0, 0, 0.75)", tg = "rgba(255, 255, 255, 0.08)", ng = "rgba(255, 255, 255, 0.9)", rg = "rgba(255, 255, 255, 0.30)", ig = "rgba(255, 255, 255, 0.85)", ag = "rgba(255, 255, 255, 0.08)", og = "rgba(255, 255, 255, 0.45)", sg = "rgba(255, 255, 255, 0.08)", cg = "rgba(255, 255, 255, 0.7)";
+function lg(e) {
+ let t = 0, n = 0, r = 0, i = /* @__PURE__ */ new Set(), a = /* @__PURE__ */ new Set(), o = /* @__PURE__ */ new Set(), s = !1, c = !1;
+ return e.traverse((e) => {
+ if (e.isMesh || e.isPoints || e.isLine) {
+ r++;
+ let l = e.geometry;
+ l && (l.index ? n += l.index.count / 3 : l.attributes.position && (n += l.attributes.position.count / 3), l.attributes.position && (t += l.attributes.position.count)), e.skeleton && (s = !0), e.morphTargetInfluences && e.morphTargetInfluences.length > 0 && (c = !0), (Array.isArray(e.material) ? e.material : [e.material]).forEach((e) => {
+ if (e) {
+ i.add(e.uuid), o.add(e.type.replace("Material", ""));
+ for (let t in e) e[t] && e[t].isTexture && a.add(e[t].uuid);
+ }
+ });
+ }
+ }), {
+ vertices: t,
+ triangles: Math.floor(n),
+ meshes: r,
+ materials: i.size,
+ textures: a.size,
+ materialTypes: Array.from(o),
+ hasSkinning: s,
+ hasMorphs: c
+ };
+}
+function ug(e) {
+ return e >= 1e6 ? (e / 1e6).toFixed(1) + "M" : e >= 1e3 ? (e / 1e3).toFixed(1) + "K" : e.toString();
+}
+function dg(e, t) {
+ let n = [];
+ return e.hasSkinning && n.push("skinned"), e.hasMorphs && n.push("morph targets"), t && t.length > 0 && n.push(`${t.length} animation${t.length > 1 ? "s" : ""}`), e.materialTypes.length > 0 && n.push(e.materialTypes.join(", ")), n.length > 0 ? n.join(" · ") : "";
+}
+function fg(e, t, n) {
+ let r = lg(t), i = dg(r, n), a = [
+ {
+ label: "MESHES",
+ value: ug(r.meshes)
+ },
+ {
+ label: "VERTICES",
+ value: ug(r.vertices)
+ },
+ {
+ label: "TRIANGLES",
+ value: ug(r.triangles)
+ },
+ {
+ label: "MATERIALS",
+ value: ug(r.materials)
+ },
+ {
+ label: "TEXTURES",
+ value: ug(r.textures)
+ }
+ ];
+ n && n.length > 0 && a.push({
+ label: "ANIMATIONS",
+ value: n.length.toString()
+ });
+ let o = [];
+ r.materialTypes.forEach((e) => o.push(e)), r.hasSkinning && o.push("Skinned"), r.hasMorphs && o.push("Morph"), n && n.length > 0 && o.push("Animated");
+ let s = ph(uh("Model Info", Uh), 200, Jh + 2), c = a.map((e) => {
+ let t = Lh([{
+ text: e.label + " ",
+ font: Wh
+ }, {
+ text: e.value,
+ font: Gh
+ }]), n = Ch(uh(e.label, Wh), 200), r = Ch(uh(e.value, Gh), 200);
+ return {
+ ...e,
+ labelWidth: n.maxLineWidth,
+ valueWidth: r.maxLineWidth,
+ richPrepared: t
+ };
+ }), l = o.map((e) => ({
+ text: e,
+ width: Ch(uh(e, Kh), 300).maxLineWidth + Qh
+ })), u = [], d = 0;
+ if (i) {
+ let e = Th(dh(i, qh), 200 - Xh, Jh);
+ u = e.lines, d = e.height;
+ }
+ let f = Math.max(s.width + Xh * 2, ...c.map((e) => e.labelWidth + e.valueWidth + Xh * 3)), p = Math.max(f, 180), m = 0;
+ if (l.length > 0) {
+ let e = 0, t = 1;
+ l.forEach((n) => {
+ e > 0 && e + n.width > p - Xh * 2 && (t++, e = 0), e += n.width + 6;
+ }), m = t * (Yh + 6) + Zh;
+ }
+ let h = Xh + s.height + Zh + Zh + c.length * (Jh + Zh) + m + (d > 0 ? Zh + d : 0) + Xh, g = document.createElement("canvas");
+ g.width = p * $h, g.height = h * $h, g.style.width = p + "px", g.style.height = h + "px";
+ let _ = g.getContext("2d");
+ _.scale($h, $h), _.fillStyle = eg, pg(_, 0, 0, p, h, 10), _.fill(), _.strokeStyle = tg, _.lineWidth = 1, pg(_, .5, .5, p - 1, h - 1, 10), _.stroke();
+ let v = Xh;
+ if (_.font = Uh, _.fillStyle = ng, _.textBaseline = "top", _.fillText("Model Info", Xh, v), v += s.height + Zh, _.strokeStyle = ag, _.beginPath(), _.moveTo(Xh, v), _.lineTo(p - Xh, v), _.stroke(), v += Zh, c.forEach((e) => {
+ _.font = Wh, _.fillStyle = rg, _.textAlign = "left", _.fillText(e.label, Xh, v), _.font = Gh, _.fillStyle = ig, _.textAlign = "right", _.fillText(e.value, p - Xh, v), _.textAlign = "left", v += Jh + Zh;
+ }), l.length > 0) {
+ let e = Xh;
+ l.forEach((t) => {
+ e > Xh && e + t.width > p - Xh && (e = Xh, v += Yh + 6), _.fillStyle = sg, pg(_, e, v, t.width, Yh, 4), _.fill(), _.font = Kh, _.fillStyle = cg, _.textBaseline = "top", _.fillText(t.text, e + Qh / 2, v + 3), e += t.width + 6;
+ }), v += Yh + Zh + 4;
+ }
+ u.length > 0 && (_.strokeStyle = ag, _.beginPath(), _.moveTo(Xh, v), _.lineTo(p - Xh, v), _.stroke(), v += Zh, _.font = qh, _.fillStyle = og, _.textBaseline = "top", u.forEach((e) => {
+ _.fillText(e.text, Xh, v), v += Jh;
+ }));
+ let y = document.createElement("div");
+ return y.classList.add("model-info"), y.appendChild(g), e.appendChild(y), {
+ el: y,
+ canvas: g,
+ remove() {
+ y.remove();
+ }
+ };
+}
+function pg(e, t, n, r, i, a) {
+ e.beginPath(), e.moveTo(t + a, n), e.lineTo(t + r - a, n), e.quadraticCurveTo(t + r, n, t + r, n + a), e.lineTo(t + r, n + i - a), e.quadraticCurveTo(t + r, n + i, t + r - a, n + i), e.lineTo(t + a, n + i), e.quadraticCurveTo(t, n + i, t, n + i - a), e.lineTo(t, n + a), e.quadraticCurveTo(t, n, t + a, n), e.closePath();
+}
+//#endregion
+//#region src/annotations.js
+var mg = "500 11px Inter, sans-serif", hg = "300 10px Inter, sans-serif", gg = 10, _g = 6, vg = 14, yg = Math.min(window.devicePixelRatio || 1, 2), bg = 8;
+function xg(e) {
+ let t = [];
+ return e.traverse((e) => {
+ if (t.length >= bg || !e.isMesh || !e.name || e.name.startsWith("_")) return;
+ let n = e.geometry, r = Array.isArray(e.material) ? e.material[0] : e.material, i = n && n.attributes.position ? n.attributes.position.count : 0, a = r ? r.type.replace("Material", "") : "", o = [{
+ text: e.name,
+ font: mg
+ }];
+ i > 0 && o.push({
+ text: " " + Cg(i) + " verts",
+ font: hg
+ }), a && o.push({
+ text: " " + a,
+ font: hg
+ });
+ let s = Lh(o), c = 0, l = 0;
+ Hh(s, 300, (e) => {
+ let t = Vh(s, e);
+ c = Math.max(c, t.width), l++;
+ });
+ let u = c + gg * 2, d = l * vg + _g * 2;
+ n && n.computeBoundingBox();
+ let f = n ? n.boundingBox : null, p = new R();
+ f ? (f.getCenter(p), p.applyMatrix4(e.matrixWorld)) : e.getWorldPosition(p), t.push({
+ name: e.name,
+ items: o,
+ prepared: s,
+ labelWidth: u,
+ labelHeight: d,
+ position: p,
+ vertCount: i,
+ matType: a
+ });
+ }), t;
+}
+function Sg(e) {
+ let { labelWidth: t, labelHeight: n, items: r, prepared: i } = e, a = document.createElement("canvas");
+ a.width = t * yg, a.height = n * yg, a.style.width = t + "px", a.style.height = n + "px";
+ let o = a.getContext("2d");
+ o.scale(yg, yg), o.fillStyle = "rgba(0, 0, 0, 0.8)", wg(o, 0, 0, t, n, 6), o.fill(), o.strokeStyle = "rgba(255, 255, 255, 0.1)", o.lineWidth = 1, wg(o, .5, .5, t - 1, n - 1, 6), o.stroke(), o.textBaseline = "top";
+ let s = _g;
+ return Hh(i, t - gg * 2, (e) => {
+ let t = Vh(i, e), n = gg;
+ t.fragments.forEach((e) => {
+ n += e.gapBefore, o.font = r[e.itemIndex].font, o.fillStyle = e.itemIndex === 0 ? "rgba(255, 255, 255, 0.9)" : "rgba(255, 255, 255, 0.45)", o.fillText(e.text, n, s), n += e.occupiedWidth;
+ }), s += vg;
+ }), a;
+}
+function Cg(e) {
+ return e >= 1e6 ? (e / 1e6).toFixed(1) + "M" : e >= 1e3 ? (e / 1e3).toFixed(1) + "K" : e.toString();
+}
+function wg(e, t, n, r, i, a) {
+ e.beginPath(), e.moveTo(t + a, n), e.lineTo(t + r - a, n), e.quadraticCurveTo(t + r, n, t + r, n + a), e.lineTo(t + r, n + i - a), e.quadraticCurveTo(t + r, n + i, t + r - a, n + i), e.lineTo(t + a, n + i), e.quadraticCurveTo(t, n + i, t, n + i - a), e.lineTo(t, n + a), e.quadraticCurveTo(t, n, t + a, n), e.closePath();
+}
+//#endregion
+//#region node_modules/three/examples/jsm/loaders/DRACOLoader.js
+var Tg = /* @__PURE__ */ new WeakMap(), Eg = class extends so {
+ constructor(e) {
+ super(e), this.decoderPath = "", this.decoderConfig = {}, this.decoderBinary = null, this.decoderPending = null, this.workerLimit = 4, this.workerPool = [], this.workerNextTaskID = 1, this.workerSourceURL = "", this.defaultAttributeIDs = {
+ position: "POSITION",
+ normal: "NORMAL",
+ color: "COLOR",
+ uv: "TEX_COORD"
+ }, this.defaultAttributeTypes = {
+ position: "Float32Array",
+ normal: "Float32Array",
+ color: "Float32Array",
+ uv: "Float32Array"
+ };
+ }
+ setDecoderPath(e) {
+ return this.decoderPath = e, this;
+ }
+ setDecoderConfig(e) {
+ return this.decoderConfig = e, this;
+ }
+ setWorkerLimit(e) {
+ return this.workerLimit = e, this;
+ }
+ load(e, t, n, r) {
+ let i = new uo(this.manager);
+ i.setPath(this.path), i.setResponseType("arraybuffer"), i.setRequestHeader(this.requestHeader), i.setWithCredentials(this.withCredentials), i.load(e, (e) => {
+ this.parse(e, t, r);
+ }, n, r);
+ }
+ parse(e, t, n = () => {}) {
+ this.decodeDracoFile(e, t, null, null, Ge, n).catch(n);
+ }
+ decodeDracoFile(e, t, n, r, i = Ke, a = () => {}) {
+ let o = {
+ attributeIDs: n || this.defaultAttributeIDs,
+ attributeTypes: r || this.defaultAttributeTypes,
+ useUniqueIDs: !!n,
+ vertexColorSpace: i
+ };
+ return this.decodeGeometry(e, o).then(t).catch(a);
+ }
+ decodeGeometry(e, t) {
+ let n = JSON.stringify(t);
+ if (Tg.has(e)) {
+ let t = Tg.get(e);
+ if (t.key === n) return t.promise;
+ if (e.byteLength === 0) throw Error("THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.");
+ }
+ let r, i = this.workerNextTaskID++, a = e.byteLength, o = this._getWorker(i, a).then((n) => (r = n, new Promise((n, a) => {
+ r._callbacks[i] = {
+ resolve: n,
+ reject: a
+ }, r.postMessage({
+ type: "decode",
+ id: i,
+ taskConfig: t,
+ buffer: e
+ }, [e]);
+ }))).then((e) => this._createGeometry(e.geometry));
+ return o.catch(() => !0).then(() => {
+ r && i && this._releaseTask(r, i);
+ }), Tg.set(e, {
+ key: n,
+ promise: o
+ }), o;
+ }
+ _createGeometry(e) {
+ let t = new Wr();
+ e.index && t.setIndex(new Nr(e.index.array, 1));
+ for (let n = 0; n < e.attributes.length; n++) {
+ let r = e.attributes[n], i = r.name, a = r.array, o = r.itemSize, s = new Nr(a, o);
+ i === "color" && (this._assignVertexColorSpace(s, r.vertexColorSpace), s.normalized = !(a instanceof Float32Array)), t.setAttribute(i, s);
+ }
+ return t;
+ }
+ _assignVertexColorSpace(e, t) {
+ if (t !== "srgb") return;
+ let n = new B();
+ for (let t = 0, r = e.count; t < r; t++) n.fromBufferAttribute(e, t), Rt.toWorkingColorSpace(n, Ge), e.setXYZ(t, n.r, n.g, n.b);
+ }
+ _loadLibrary(e, t) {
+ let n = new uo(this.manager);
+ return n.setPath(this.decoderPath), n.setResponseType(t), n.setWithCredentials(this.withCredentials), new Promise((t, r) => {
+ n.load(e, t, void 0, r);
+ });
+ }
+ preload() {
+ return this._initDecoder(), this;
+ }
+ _initDecoder() {
+ if (this.decoderPending) return this.decoderPending;
+ let e = typeof WebAssembly != "object" || this.decoderConfig.type === "js", t = [];
+ return e ? t.push(this._loadLibrary("draco_decoder.js", "text")) : (t.push(this._loadLibrary("draco_wasm_wrapper.js", "text")), t.push(this._loadLibrary("draco_decoder.wasm", "arraybuffer"))), this.decoderPending = Promise.all(t).then((t) => {
+ let n = t[0];
+ e || (this.decoderConfig.wasmBinary = t[1]);
+ let r = Dg.toString(), i = [
+ "/* draco decoder */",
+ n,
+ "",
+ "/* worker */",
+ r.substring(r.indexOf("{") + 1, r.lastIndexOf("}"))
+ ].join("\n");
+ this.workerSourceURL = URL.createObjectURL(new Blob([i]));
+ }), this.decoderPending;
+ }
+ _getWorker(e, t) {
+ return this._initDecoder().then(() => {
+ if (this.workerPool.length < this.workerLimit) {
+ let e = new Worker(this.workerSourceURL);
+ e._callbacks = {}, e._taskCosts = {}, e._taskLoad = 0, e.postMessage({
+ type: "init",
+ decoderConfig: this.decoderConfig
+ }), e.onmessage = function(t) {
+ let n = t.data;
+ switch (n.type) {
+ case "decode":
+ e._callbacks[n.id].resolve(n);
+ break;
+ case "error":
+ e._callbacks[n.id].reject(n);
+ break;
+ default: console.error("THREE.DRACOLoader: Unexpected message, \"" + n.type + "\"");
+ }
+ }, this.workerPool.push(e);
+ } else this.workerPool.sort(function(e, t) {
+ return e._taskLoad > t._taskLoad ? -1 : 1;
+ });
+ let n = this.workerPool[this.workerPool.length - 1];
+ return n._taskCosts[e] = t, n._taskLoad += t, n;
+ });
+ }
+ _releaseTask(e, t) {
+ e._taskLoad -= e._taskCosts[t], delete e._callbacks[t], delete e._taskCosts[t];
+ }
+ debug() {
+ console.log("Task load: ", this.workerPool.map((e) => e._taskLoad));
+ }
+ dispose() {
+ for (let e = 0; e < this.workerPool.length; ++e) this.workerPool[e].terminate();
+ return this.workerPool.length = 0, this.workerSourceURL !== "" && URL.revokeObjectURL(this.workerSourceURL), this;
+ }
+};
+function Dg() {
+ let e, t;
+ onmessage = function(r) {
+ let i = r.data;
+ switch (i.type) {
+ case "init":
+ e = i.decoderConfig, t = new Promise(function(t) {
+ e.onModuleLoaded = function(e) {
+ t({ draco: e });
+ }, DracoDecoderModule(e);
+ });
+ break;
+ case "decode":
+ let r = i.buffer, a = i.taskConfig;
+ t.then((e) => {
+ let t = e.draco, o = new t.Decoder();
+ try {
+ let e = n(t, o, new Int8Array(r), a), s = e.attributes.map((e) => e.array.buffer);
+ e.index && s.push(e.index.array.buffer), self.postMessage({
+ type: "decode",
+ id: i.id,
+ geometry: e
+ }, s);
+ } catch (e) {
+ console.error(e), self.postMessage({
+ type: "error",
+ id: i.id,
+ error: e.message
+ });
+ } finally {
+ t.destroy(o);
+ }
+ });
+ break;
+ }
+ };
+ function n(e, t, n, a) {
+ let o = a.attributeIDs, s = a.attributeTypes, c, l, u = t.GetEncodedGeometryType(n);
+ if (u === e.TRIANGULAR_MESH) c = new e.Mesh(), l = t.DecodeArrayToMesh(n, n.byteLength, c);
+ else if (u === e.POINT_CLOUD) c = new e.PointCloud(), l = t.DecodeArrayToPointCloud(n, n.byteLength, c);
+ else throw Error("THREE.DRACOLoader: Unexpected geometry type.");
+ if (!l.ok() || c.ptr === 0) throw Error("THREE.DRACOLoader: Decoding failed: " + l.error_msg());
+ let d = {
+ index: null,
+ attributes: []
+ };
+ for (let n in o) {
+ let r = self[s[n]], l, u;
+ if (a.useUniqueIDs) u = o[n], l = t.GetAttributeByUniqueId(c, u);
+ else {
+ if (u = t.GetAttributeId(c, e[o[n]]), u === -1) continue;
+ l = t.GetAttribute(c, u);
+ }
+ let f = i(e, t, c, n, r, l);
+ n === "color" && (f.vertexColorSpace = a.vertexColorSpace), d.attributes.push(f);
+ }
+ return u === e.TRIANGULAR_MESH && (d.index = r(e, t, c)), e.destroy(c), d;
+ }
+ function r(e, t, n) {
+ let r = n.num_faces() * 3, i = r * 4, a = e._malloc(i);
+ t.GetTrianglesUInt32Array(n, i, a);
+ let o = new Uint32Array(e.HEAPF32.buffer, a, r).slice();
+ return e._free(a), {
+ array: o,
+ itemSize: 1
+ };
+ }
+ function i(e, t, n, r, i, o) {
+ let s = o.num_components(), c = n.num_points() * s, l = c * i.BYTES_PER_ELEMENT, u = a(e, i), d = e._malloc(l);
+ t.GetAttributeDataArrayForAllPoints(n, o, u, l, d);
+ let f = new i(e.HEAPF32.buffer, d, c).slice();
+ return e._free(d), {
+ name: r,
+ array: f,
+ itemSize: s
+ };
+ }
+ function a(e, t) {
+ switch (t) {
+ case Float32Array: return e.DT_FLOAT32;
+ case Int8Array: return e.DT_INT8;
+ case Int16Array: return e.DT_INT16;
+ case Int32Array: return e.DT_INT32;
+ case Uint8Array: return e.DT_UINT8;
+ case Uint16Array: return e.DT_UINT16;
+ case Uint32Array: return e.DT_UINT32;
+ }
+ }
+}
+//#endregion
+//#region node_modules/three/examples/jsm/utils/WorkerPool.js
+var Og = class {
+ constructor(e = 4) {
+ this.pool = e, this.queue = [], this.workers = [], this.workersResolve = [], this.workerStatus = 0, this.workerCreator = null;
+ }
+ _initWorker(e) {
+ if (!this.workers[e]) {
+ let t = this.workerCreator();
+ t.addEventListener("message", this._onMessage.bind(this, e)), this.workers[e] = t;
+ }
+ }
+ _getIdleWorker() {
+ for (let e = 0; e < this.pool; e++) if (!(this.workerStatus & 1 << e)) return e;
+ return -1;
+ }
+ _onMessage(e, t) {
+ let n = this.workersResolve[e];
+ if (n && n(t), this.queue.length) {
+ let { resolve: t, msg: n, transfer: r } = this.queue.shift();
+ this.workersResolve[e] = t, this.workers[e].postMessage(n, r);
+ } else this.workerStatus ^= 1 << e;
+ }
+ setWorkerCreator(e) {
+ this.workerCreator = e;
+ }
+ setWorkerLimit(e) {
+ this.pool = e;
+ }
+ postMessage(e, t) {
+ return new Promise((n) => {
+ let r = this._getIdleWorker();
+ r === -1 ? this.queue.push({
+ resolve: n,
+ msg: e,
+ transfer: t
+ }) : (this._initWorker(r), this.workerStatus |= 1 << r, this.workersResolve[r] = n, this.workers[r].postMessage(e, t));
+ });
+ }
+ dispose() {
+ this.workers.forEach((e) => e.terminate()), this.workersResolve.length = 0, this.workers.length = 0, this.queue.length = 0, this.workerStatus = 0;
+ }
+}, kg = 1000066e3, Ag = class {
+ constructor() {
+ this.vkFormat = 0, this.typeSize = 1, this.pixelWidth = 0, this.pixelHeight = 0, this.pixelDepth = 0, this.layerCount = 0, this.faceCount = 1, this.supercompressionScheme = 0, this.levels = [], this.dataFormatDescriptor = [{
+ vendorId: 0,
+ descriptorType: 0,
+ descriptorBlockSize: 0,
+ versionNumber: 2,
+ colorModel: 0,
+ colorPrimaries: 1,
+ transferFunction: 2,
+ flags: 0,
+ texelBlockDimension: [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ bytesPlane: [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ samples: []
+ }], this.keyValue = {}, this.globalData = null;
+ }
+}, jg = class {
+ constructor(e, t, n, r) {
+ this._dataView = void 0, this._littleEndian = void 0, this._offset = void 0, this._dataView = new DataView(e.buffer, e.byteOffset + t, n), this._littleEndian = r, this._offset = 0;
+ }
+ _nextUint8() {
+ let e = this._dataView.getUint8(this._offset);
+ return this._offset += 1, e;
+ }
+ _nextUint16() {
+ let e = this._dataView.getUint16(this._offset, this._littleEndian);
+ return this._offset += 2, e;
+ }
+ _nextUint32() {
+ let e = this._dataView.getUint32(this._offset, this._littleEndian);
+ return this._offset += 4, e;
+ }
+ _nextUint64() {
+ let e = this._dataView.getUint32(this._offset, this._littleEndian) + 2 ** 32 * this._dataView.getUint32(this._offset + 4, this._littleEndian);
+ return this._offset += 8, e;
+ }
+ _nextInt32() {
+ let e = this._dataView.getInt32(this._offset, this._littleEndian);
+ return this._offset += 4, e;
+ }
+ _nextUint8Array(e) {
+ let t = new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + this._offset, e);
+ return this._offset += e, t;
+ }
+ _skip(e) {
+ return this._offset += e, this;
+ }
+ _scan(e, t) {
+ t === void 0 && (t = 0);
+ let n = this._offset, r = 0;
+ for (; this._dataView.getUint8(this._offset) !== t && r < e;) r++, this._offset++;
+ return r < e && this._offset++, new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + n, r);
+ }
+};
+new Uint8Array([0]);
+var Mg = [
+ 171,
+ 75,
+ 84,
+ 88,
+ 32,
+ 50,
+ 48,
+ 187,
+ 13,
+ 10,
+ 26,
+ 10
+];
+function Ng(e) {
+ return new TextDecoder().decode(e);
+}
+function Pg(e) {
+ let t = new Uint8Array(e.buffer, e.byteOffset, Mg.length);
+ if (t[0] !== Mg[0] || t[1] !== Mg[1] || t[2] !== Mg[2] || t[3] !== Mg[3] || t[4] !== Mg[4] || t[5] !== Mg[5] || t[6] !== Mg[6] || t[7] !== Mg[7] || t[8] !== Mg[8] || t[9] !== Mg[9] || t[10] !== Mg[10] || t[11] !== Mg[11]) throw Error("Missing KTX 2.0 identifier.");
+ let n = new Ag(), r = 17 * Uint32Array.BYTES_PER_ELEMENT, i = new jg(e, Mg.length, r, !0);
+ n.vkFormat = i._nextUint32(), n.typeSize = i._nextUint32(), n.pixelWidth = i._nextUint32(), n.pixelHeight = i._nextUint32(), n.pixelDepth = i._nextUint32(), n.layerCount = i._nextUint32(), n.faceCount = i._nextUint32();
+ let a = i._nextUint32();
+ n.supercompressionScheme = i._nextUint32();
+ let o = i._nextUint32(), s = i._nextUint32(), c = i._nextUint32(), l = i._nextUint32(), u = i._nextUint64(), d = i._nextUint64(), f = new jg(e, Mg.length + r, 3 * a * 8, !0);
+ for (let t = 0; t < a; t++) n.levels.push({
+ levelData: new Uint8Array(e.buffer, e.byteOffset + f._nextUint64(), f._nextUint64()),
+ uncompressedByteLength: f._nextUint64()
+ });
+ let p = new jg(e, o, s, !0), m = {
+ vendorId: p._skip(4)._nextUint16(),
+ descriptorType: p._nextUint16(),
+ versionNumber: p._nextUint16(),
+ descriptorBlockSize: p._nextUint16(),
+ colorModel: p._nextUint8(),
+ colorPrimaries: p._nextUint8(),
+ transferFunction: p._nextUint8(),
+ flags: p._nextUint8(),
+ texelBlockDimension: [
+ p._nextUint8(),
+ p._nextUint8(),
+ p._nextUint8(),
+ p._nextUint8()
+ ],
+ bytesPlane: [
+ p._nextUint8(),
+ p._nextUint8(),
+ p._nextUint8(),
+ p._nextUint8(),
+ p._nextUint8(),
+ p._nextUint8(),
+ p._nextUint8(),
+ p._nextUint8()
+ ],
+ samples: []
+ }, h = (m.descriptorBlockSize / 4 - 6) / 4;
+ for (let e = 0; e < h; e++) {
+ let t = {
+ bitOffset: p._nextUint16(),
+ bitLength: p._nextUint8(),
+ channelType: p._nextUint8(),
+ samplePosition: [
+ p._nextUint8(),
+ p._nextUint8(),
+ p._nextUint8(),
+ p._nextUint8()
+ ],
+ sampleLower: -Infinity,
+ sampleUpper: Infinity
+ };
+ 64 & t.channelType ? (t.sampleLower = p._nextInt32(), t.sampleUpper = p._nextInt32()) : (t.sampleLower = p._nextUint32(), t.sampleUpper = p._nextUint32()), m.samples[e] = t;
+ }
+ n.dataFormatDescriptor.length = 0, n.dataFormatDescriptor.push(m);
+ let g = new jg(e, c, l, !0);
+ for (; g._offset < l;) {
+ let e = g._nextUint32(), t = g._scan(e), r = Ng(t);
+ if (n.keyValue[r] = g._nextUint8Array(e - t.byteLength - 1), r.match(/^ktx/i)) {
+ let e = Ng(n.keyValue[r]);
+ n.keyValue[r] = e.substring(0, e.lastIndexOf("\0"));
+ }
+ g._skip(e % 4 ? 4 - e % 4 : 0);
+ }
+ if (d <= 0) return n;
+ let _ = new jg(e, u, d, !0), v = _._nextUint16(), y = _._nextUint16(), b = _._nextUint32(), x = _._nextUint32(), S = _._nextUint32(), C = _._nextUint32(), w = [];
+ for (let e = 0; e < a; e++) w.push({
+ imageFlags: _._nextUint32(),
+ rgbSliceByteOffset: _._nextUint32(),
+ rgbSliceByteLength: _._nextUint32(),
+ alphaSliceByteOffset: _._nextUint32(),
+ alphaSliceByteLength: _._nextUint32()
+ });
+ let T = u + _._offset, E = T + b, D = E + x, O = D + S;
+ return n.globalData = {
+ endpointCount: v,
+ selectorCount: y,
+ imageDescs: w,
+ endpointsData: new Uint8Array(e.buffer, e.byteOffset + T, b),
+ selectorsData: new Uint8Array(e.buffer, e.byteOffset + E, x),
+ tablesData: new Uint8Array(e.buffer, e.byteOffset + D, S),
+ extendedData: new Uint8Array(e.buffer, e.byteOffset + O, C)
+ }, n;
+}
+//#endregion
+//#region node_modules/three/examples/jsm/libs/zstddec.module.js
+var Fg, Ig, Lg, Rg = { env: { emscripten_notify_memory_growth: function(e) {
+ Lg = new Uint8Array(Ig.exports.memory.buffer);
+} } }, zg = class {
+ init() {
+ return Fg || (Fg = typeof fetch < "u" ? fetch("data:application/wasm;base64," + Bg).then((e) => e.arrayBuffer()).then((e) => WebAssembly.instantiate(e, Rg)).then(this._init) : WebAssembly.instantiate(Buffer.from(Bg, "base64"), Rg).then(this._init), Fg);
+ }
+ _init(e) {
+ Ig = e.instance, Rg.env.emscripten_notify_memory_growth(0);
+ }
+ decode(e, t = 0) {
+ if (!Ig) throw Error("ZSTDDecoder: Await .init() before decoding.");
+ let n = e.byteLength, r = Ig.exports.malloc(n);
+ Lg.set(e, r), t ||= Number(Ig.exports.ZSTD_findDecompressedSize(r, n));
+ let i = Ig.exports.malloc(t), a = Ig.exports.ZSTD_decompress(i, t, r, n), o = Lg.slice(i, i + a);
+ return Ig.exports.free(r), Ig.exports.free(i), o;
+ }
+}, Bg = "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IAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQh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ASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigC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C0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdB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IAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/IwBBMGsiBCQAIABB/wFqIgVBfWohBgJAIAMvAQIEQCAEQRhqIAEgAhAGIgIQAw0BIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahASOgAAIAMgBEEIaiAEQRhqEBI6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0FIAEgBEEQaiAEQRhqEBI6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBSABIARBCGogBEEYahASOgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEjoAACABIAJqIABrIQIMAwsgAyAEQRBqIARBGGoQEjoAAiADIARBCGogBEEYahASOgADIANBBGohAwwAAAsACyAEQRhqIAEgAhAGIgIQAw0AIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahAROgAAIAMgBEEIaiAEQRhqEBE6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0EIAEgBEEQaiAEQRhqEBE6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBCABIARBCGogBEEYahAROgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEToAACABIAJqIABrIQIMAgsgAyAEQRBqIARBGGoQEToAAiADIARBCGogBEEYahAROgADIANBBGohAwwAAAsACyAEQTBqJAAgAgtpAQF/An8CQAJAIAJBB00NACABKAAAQbfIwuF+Rw0AIAAgASgABDYCmOIBQWIgAEEQaiABIAIQPiIDEAMNAhogAEKBgICAEDcDiOEBIAAgASADaiACIANrECoMAQsgACABIAIQKgtBAAsLrQMBBn8jAEGAAWsiAyQAQWIhCAJAIAJBCUkNACAAQZjQAGogAUEIaiIEIAJBeGogAEGY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wOABCwutAgIEfwF+IwBBQGoiBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEEdCAAbiECCyAAQQh2IgEgAkEYbCIAQYwIaigCAGwgAEGICGooAgBqIgJBA3YgAmogAEGACGooAgAgAEGECGooAgAgAWxqSQs3ACAAIAMgBCAFQYAQEDMiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQMgVBuH8LC78DAQN/IwBBIGsiBSQAIAVBCGogAiADEAYiAhADRQRAIAAgAWoiB0F9aiEGIAUgBBAOIARBBGohAiAFLQACIQMDQEEAIAAgBkkgBUEIahAEGwRAIAAgAiAFQQhqIAMQAkECdGoiBC8BADsAACAFQQhqIAQtAAIQASAAIAQtAANqIgQgAiAFQQhqIAMQAkECdGoiAC8BADsAACAFQQhqIAAtAAIQASAEIAAtAANqIQAMAQUgB0F+aiEEA0AgBUEIahAEIAAgBEtyRQRAIAAgAiAFQQhqIAMQAkECdGoiBi8BADsAACAFQQhqIAYtAAIQASAAIAYtAANqIQAMAQsLA0AgACAES0UEQCAAIAIgBUEIaiADEAJBAnRqIgYvAQA7AAAgBUEIaiAGLQACEAEgACAGLQADaiEADAELCwJAIAAgB08NACAAIAIgBUEIaiADEAIiA0ECdGoiAC0AADoAACAALQADQQFGBEAgBUEIaiAALQACEAEMAQsgBSgCDEEfSw0AIAVBCGogAiADQQJ0ai0AAhABIAUoAgxBIUkNACAFQSA2AgwLIAFBbCAFQQhqEAobIQILCwsgBUEgaiQAIAILkgIBBH8jAEFAaiIJJAAgCSADQTQQCyEDAkAgBEECSA0AIAMgBEECdGooAgAhCSADQTxqIAgQIyADQQE6AD8gAyACOgA+QQAhBCADKAI8IQoDQCAEIAlGDQEgACAEQQJ0aiAKNgEAIARBAWohBAwAAAsAC0EAIQkDQCAGIAlGRQRAIAMgBSAJQQF0aiIKLQABIgtBAnRqIgwoAgAhBCADQTxqIAotAABBCHQgCGpB//8DcRAjIANBAjoAPyADIAcgC2siCiACajoAPiAEQQEgASAKa3RqIQogAygCPCELA0AgACAEQQJ0aiALNgEAIARBAWoiBCAKSQ0ACyAMIAo2AgAgCUEBaiEJDAELCyADQUBrJAALowIBCX8jAEHQAGsiCSQAIAlBEGogBUE0EAsaIAcgBmshDyAHIAFrIRADQAJAIAMgCkcEQEEBIAEgByACIApBAXRqIgYtAAEiDGsiCGsiC3QhDSAGLQAAIQ4gCUEQaiAMQQJ0aiIMKAIAIQYgCyAPTwRAIAAgBkECdGogCyAIIAUgCEE0bGogCCAQaiIIQQEgCEEBShsiCCACIAQgCEECdGooAgAiCEEBdGogAyAIayAHIA4QYyAGIA1qIQgMAgsgCUEMaiAOECMgCUEBOgAPIAkgCDoADiAGIA1qIQggCSgCDCELA0AgBiAITw0CIAAgBkECdGogCzYBACAGQQFqIQYMAAALAAsgCUHQAGokAA8LIAwgCDYCACAKQQFqIQoMAAALAAs0ACAAIAMgBCAFEDYiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQNAVBuH8LCyMAIAA/AEEQdGtB//8DakEQdkAAQX9GBEBBAA8LQQAQAEEBCzsBAX8gAgRAA0AgACABIAJBgCAgAkGAIEkbIgMQCyEAIAFBgCBqIQEgAEGAIGohACACIANrIgINAAsLCwYAIAAQAwsLqBUJAEGICAsNAQAAAAEAAAACAAAAAgBBoAgLswYBAAAAAQAAAAIAAAACAAAAJgAAAIIAAAAhBQAASgAAAGcIAAAmAAAAwAEAAIAAAABJBQAASgAAAL4IAAApAAAALAIAAIAAAABJBQAASgAAAL4IAAAvAAAAygIAAIAAAACKBQAASgAAAIQJAAA1AAAAcwMAAIAAAACdBQAASgAAAKAJAAA9AAAAgQMAAIAAAADrBQAASwAAAD4KAABEAAAAngMAAIAAAABNBgAASwAAAKoKAABLAAAAswMAAIAAAADBBgAATQAAAB8NAABNAAAAUwQAAIAAAAAjCAAAUQAAAKYPAABUAAAAmQQAAIAAAABLCQAAVwAAALESAABYAAAA2gQAAIAAAABvCQAAXQAAACMUAABUAAAARQUAAIAAAABUCgAAagAAAIwUAABqAAAArwUAAIAAAAB2CQAAfAAAAE4QAAB8AAAA0gIAAIAAAABjBwAAkQAAAJAHAACSAAAAAAAAAAEAAAABAAAABQAAAA0AAAAdAAAAPQAAAH0AAAD9AAAA/QEAAP0DAAD9BwAA/Q8AAP0fAAD9PwAA/X8AAP3/AAD9/wEA/f8DAP3/BwD9/w8A/f8fAP3/PwD9/38A/f//AP3//wH9//8D/f//B/3//w/9//8f/f//P/3//38AAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAAAMAAAAEAAAABQAAAAYAAAAHAAAACAAAAAkAAAAKAAAACwAAAAwAAAANAAAADgAAAA8AAAAQAAAAEQAAABIAAAATAAAAFAAAABUAAAAWAAAAFwAAABgAAAAZAAAAGgAAABsAAAAcAAAAHQAAAB4AAAAfAAAAIAAAACEAAAAiAAAAIwAAACUAAAAnAAAAKQAAACsAAAAvAAAAMwAAADsAAABDAAAAUwAAAGMAAACDAAAAAwEAAAMCAAADBAAAAwgAAAMQAAADIAAAA0AAAAOAAAADAAEAQeAPC1EBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAEAAAABQAAAAcAAAAIAAAACQAAAAoAAAALAAAADAAAAA0AAAAOAAAADwAAABAAQcQQC4sBAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABIAAAAUAAAAFgAAABgAAAAcAAAAIAAAACgAAAAwAAAAQAAAAIAAAAAAAQAAAAIAAAAEAAAACAAAABAAAAAgAAAAQAAAAIAAAAAAAQBBkBIL5gQBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAAAEAAAAEAAAACAAAAAAAAAABAAEBBgAAAAAAAAQAAAAAEAAABAAAAAAgAAAFAQAAAAAAAAUDAAAAAAAABQQAAAAAAAAFBgAAAAAAAAUHAAAAAAAABQkAAAAAAAAFCgAAAAAAAAUMAAAAAAAABg4AAAAAAAEFEAAAAAAAAQUUAAAAAAABBRYAAAAAAAIFHAAAAAAAAwUgAAAAAAAEBTAAAAAgAAYFQAAAAAAABwWAAAAAAAAIBgABAAAAAAoGAAQAAAAADAYAEAAAIAAABAAAAAAAAAAEAQAAAAAAAAUCAAAAIAAABQQAAAAAAAAFBQAAACAAAAUHAAAAAAAABQgAAAAgAAAFCgAAAAAAAAULAAAAAAAABg0AAAAgAAEFEAAAAAAAAQUSAAAAIAABBRYAAAAAAAIFGAAAACAAAwUgAAAAAAADBSgAAAAAAAYEQAAAABAABgRAAAAAIAAHBYAAAAAAAAkGAAIAAAAACwYACAAAMAAABAAAAAAQAAAEAQAAACAAAAUCAAAAIAAABQMAAAAgAAAFBQAAACAAAAUGAAAAIAAABQgAAAAgAAAFCQAAACAAAAULAAAAIAAABQwAAAAAAAAGDwAAACAAAQUSAAAAIAABBRQAAAAgAAIFGAAAACAAAgUcAAAAIAADBSgAAAAgAAQFMAAAAAAAEAYAAAEAAAAPBgCAAAAAAA4GAEAAAAAADQYAIABBgBcLhwIBAAEBBQAAAAAAAAUAAAAAAAAGBD0AAAAAAAkF/QEAAAAADwX9fwAAAAAVBf3/HwAAAAMFBQAAAAAABwR9AAAAAAAMBf0PAAAAABIF/f8DAAAAFwX9/38AAAAFBR0AAAAAAAgE/QAAAAAADgX9PwAAAAAUBf3/DwAAAAIFAQAAABAABwR9AAAAAAALBf0HAAAAABEF/f8BAAAAFgX9/z8AAAAEBQ0AAAAQAAgE/QAAAAAADQX9HwAAAAATBf3/BwAAAAEFAQAAABAABgQ9AAAAAAAKBf0DAAAAABAF/f8AAAAAHAX9//8PAAAbBf3//wcAABoF/f//AwAAGQX9//8BAAAYBf3//wBBkBkLhgQBAAEBBgAAAAAAAAYDAAAAAAAABAQAAAAgAAAFBQAAAAAAAAUGAAAAAAAABQgAAAAAAAAFCQAAAAAAAAULAAAAAAAABg0AAAAAAAAGEAAAAAAAAAYTAAAAAAAABhYAAAAAAAAGGQAAAAAAAAYcAAAAAAAABh8AAAAAAAAGIgAAAAAAAQYlAAAAAAABBikAAAAAAAIGLwAAAAAAAwY7AAAAAAAEBlMAAAAAAAcGgwAAAAAACQYDAgAAEAAABAQAAAAAAAAEBQAAACAAAAUGAAAAAAAABQcAAAAgAAAFCQAAAAAAAAUKAAAAAAAABgwAAAAAAAAGDwAAAAAAAAYSAAAAAAAABhUAAAAAAAAGGAAAAAAAAAYbAAAAAAAABh4AAAAAAAAGIQAAAAAAAQYjAAAAAAABBicAAAAAAAIGKwAAAAAAAwYzAAAAAAAEBkMAAAAAAAUGYwAAAAAACAYDAQAAIAAABAQAAAAwAAAEBAAAABAAAAQFAAAAIAAABQcAAAAgAAAFCAAAACAAAAUKAAAAIAAABQsAAAAAAAAGDgAAAAAAAAYRAAAAAAAABhQAAAAAAAAGFwAAAAAAAAYaAAAAAAAABh0AAAAAAAAGIAAAAAAAEAYDAAEAAAAPBgOAAAAAAA4GA0AAAAAADQYDIAAAAAAMBgMQAAAAAAsGAwgAAAAACgYDBABBpB0L2QEBAAAAAwAAAAcAAAAPAAAAHwAAAD8AAAB/AAAA/wAAAP8BAAD/AwAA/wcAAP8PAAD/HwAA/z8AAP9/AAD//wAA//8BAP//AwD//wcA//8PAP//HwD//z8A//9/AP///wD///8B////A////wf///8P////H////z////9/AAAAAAEAAAACAAAABAAAAAAAAAACAAAABAAAAAgAAAAAAAAAAQAAAAIAAAABAAAABAAAAAQAAAAEAAAABAAAAAgAAAAIAAAACAAAAAcAAAAIAAAACQAAAAoAAAALAEGgIAsDwBBQ", Vg = "display-p3", Hg = "display-p3-linear", Ug = /* @__PURE__ */ new WeakMap(), Wg = 0, Gg, Kg = class e extends so {
+ constructor(e) {
+ super(e), this.transcoderPath = "", this.transcoderBinary = null, this.transcoderPending = null, this.workerPool = new Og(), this.workerSourceURL = "", this.workerConfig = null, typeof MSC_TRANSCODER < "u" && console.warn("THREE.KTX2Loader: Please update to latest \"basis_transcoder\". \"msc_basis_transcoder\" is no longer supported in three.js r125+.");
+ }
+ setTranscoderPath(e) {
+ return this.transcoderPath = e, this;
+ }
+ setWorkerLimit(e) {
+ return this.workerPool.setWorkerLimit(e), this;
+ }
+ async detectSupportAsync(e) {
+ return this.workerConfig = {
+ astcSupported: await e.hasFeatureAsync("texture-compression-astc"),
+ astcHDRSupported: !1,
+ etc1Supported: await e.hasFeatureAsync("texture-compression-etc1"),
+ etc2Supported: await e.hasFeatureAsync("texture-compression-etc2"),
+ dxtSupported: await e.hasFeatureAsync("texture-compression-bc"),
+ bptcSupported: await e.hasFeatureAsync("texture-compression-bptc"),
+ pvrtcSupported: await e.hasFeatureAsync("texture-compression-pvrtc")
+ }, this;
+ }
+ detectSupport(e) {
+ return e.isWebGPURenderer === !0 ? this.workerConfig = {
+ astcSupported: e.hasFeature("texture-compression-astc"),
+ astcHDRSupported: !1,
+ etc1Supported: e.hasFeature("texture-compression-etc1"),
+ etc2Supported: e.hasFeature("texture-compression-etc2"),
+ dxtSupported: e.hasFeature("texture-compression-bc"),
+ bptcSupported: e.hasFeature("texture-compression-bptc"),
+ pvrtcSupported: e.hasFeature("texture-compression-pvrtc")
+ } : this.workerConfig = {
+ astcSupported: e.extensions.has("WEBGL_compressed_texture_astc"),
+ astcHDRSupported: e.extensions.has("WEBGL_compressed_texture_astc") && e.extensions.get("WEBGL_compressed_texture_astc").getSupportedProfiles().includes("hdr"),
+ etc1Supported: e.extensions.has("WEBGL_compressed_texture_etc1"),
+ etc2Supported: e.extensions.has("WEBGL_compressed_texture_etc"),
+ dxtSupported: e.extensions.has("WEBGL_compressed_texture_s3tc"),
+ bptcSupported: e.extensions.has("EXT_texture_compression_bptc"),
+ pvrtcSupported: e.extensions.has("WEBGL_compressed_texture_pvrtc") || e.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")
+ }, this;
+ }
+ init() {
+ if (!this.transcoderPending) {
+ let t = new uo(this.manager);
+ t.setPath(this.transcoderPath), t.setWithCredentials(this.withCredentials);
+ let n = t.loadAsync("basis_transcoder.js"), r = new uo(this.manager);
+ r.setPath(this.transcoderPath), r.setResponseType("arraybuffer"), r.setWithCredentials(this.withCredentials);
+ let i = r.loadAsync("basis_transcoder.wasm");
+ this.transcoderPending = Promise.all([n, i]).then(([t, n]) => {
+ let r = e.BasisWorker.toString(), i = [
+ "/* constants */",
+ "let _EngineFormat = " + JSON.stringify(e.EngineFormat),
+ "let _EngineType = " + JSON.stringify(e.EngineType),
+ "let _TranscoderFormat = " + JSON.stringify(e.TranscoderFormat),
+ "let _BasisFormat = " + JSON.stringify(e.BasisFormat),
+ "/* basis_transcoder.js */",
+ t,
+ "/* worker */",
+ r.substring(r.indexOf("{") + 1, r.lastIndexOf("}"))
+ ].join("\n");
+ this.workerSourceURL = URL.createObjectURL(new Blob([i])), this.transcoderBinary = n, this.workerPool.setWorkerCreator(() => {
+ let e = new Worker(this.workerSourceURL), t = this.transcoderBinary.slice(0);
+ return e.postMessage({
+ type: "init",
+ config: this.workerConfig,
+ transcoderBinary: t
+ }, [t]), e;
+ });
+ }), Wg > 0 && console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances."), Wg++;
+ }
+ return this.transcoderPending;
+ }
+ load(e, t, n, r) {
+ if (this.workerConfig === null) throw Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");
+ let i = new uo(this.manager);
+ i.setResponseType("arraybuffer"), i.setWithCredentials(this.withCredentials), i.load(e, (e) => {
+ this.parse(e, t, r);
+ }, n, r);
+ }
+ parse(e, t, n) {
+ if (this.workerConfig === null) throw Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");
+ if (Ug.has(e)) return Ug.get(e).promise.then(t).catch(n);
+ this._createTexture(e).then((e) => t ? t(e) : null).catch(n);
+ }
+ _createTextureFrom(e, t) {
+ let { type: n, error: r, data: { faces: i, width: a, height: o, format: s, type: c, dfdFlags: l } } = e;
+ if (n === "error") return Promise.reject(r);
+ let u;
+ if (t.faceCount === 6) u = new ja(i, s, c);
+ else {
+ let e = i[0].mipmaps;
+ u = t.layerCount > 1 ? new Aa(e, a, o, t.layerCount, s, c) : new ka(e, a, o, s, c);
+ }
+ return u.minFilter = i[0].mipmaps.length === 1 ? d : p, u.magFilter = d, u.generateMipmaps = !1, u.needsUpdate = !0, u.colorSpace = Zg(t), u.premultiplyAlpha = !!(l & 1), u;
+ }
+ async _createTexture(e, t = {}) {
+ let n = Pg(new Uint8Array(e)), r = n.vkFormat === 1000066e3 && n.dataFormatDescriptor[0].colorModel === 167;
+ if (!(n.vkFormat === 0 || r && !this.workerConfig.astcHDRSupported)) return Xg(n);
+ let i = t, a = this.init().then(() => this.workerPool.postMessage({
+ type: "transcode",
+ buffer: e,
+ taskConfig: i
+ }, [e])).then((e) => this._createTextureFrom(e.data, n));
+ return Ug.set(e, { promise: a }), a;
+ }
+ dispose() {
+ this.workerPool.dispose(), this.workerSourceURL && URL.revokeObjectURL(this.workerSourceURL), Wg--;
+ }
+};
+Kg.BasisFormat = {
+ ETC1S: 0,
+ UASTC: 1,
+ UASTC_HDR: 2
+}, Kg.TranscoderFormat = {
+ ETC1: 0,
+ ETC2: 1,
+ BC1: 2,
+ BC3: 3,
+ BC4: 4,
+ BC5: 5,
+ BC7_M6_OPAQUE_ONLY: 6,
+ BC7_M5: 7,
+ PVRTC1_4_RGB: 8,
+ PVRTC1_4_RGBA: 9,
+ ASTC_4x4: 10,
+ ATC_RGB: 11,
+ ATC_RGBA_INTERPOLATED_ALPHA: 12,
+ RGBA32: 13,
+ RGB565: 14,
+ BGR565: 15,
+ RGBA4444: 16,
+ BC6H: 22,
+ RGB_HALF: 24,
+ RGBA_HALF: 25
+}, Kg.EngineFormat = {
+ RGBAFormat: O,
+ RGBA_ASTC_4x4_Format: ge,
+ RGB_BPTC_UNSIGNED_Format: De,
+ RGBA_BPTC_Format: Ee,
+ RGBA_ETC2_EAC_Format: he,
+ RGBA_PVRTC_4BPPV1_Format: de,
+ RGBA_S3TC_DXT5_Format: ce,
+ RGB_ETC1_Format: pe,
+ RGB_ETC2_Format: me,
+ RGB_PVRTC_4BPPV1_Format: le,
+ RGBA_S3TC_DXT1_Format: oe
+}, Kg.EngineType = {
+ UnsignedByteType: m,
+ HalfFloatType: x,
+ FloatType: b
+}, Kg.BasisWorker = function() {
+ let e, t, n, r = _EngineFormat, i = _EngineType, a = _TranscoderFormat, o = _BasisFormat;
+ self.addEventListener("message", function(n) {
+ let r = n.data;
+ switch (r.type) {
+ case "init":
+ e = r.config, s(r.transcoderBinary);
+ break;
+ case "transcode":
+ t.then(() => {
+ try {
+ let { faces: e, buffers: t, width: n, height: i, hasAlpha: a, format: o, type: s, dfdFlags: l } = c(r.buffer);
+ self.postMessage({
+ type: "transcode",
+ id: r.id,
+ data: {
+ faces: e,
+ width: n,
+ height: i,
+ hasAlpha: a,
+ format: o,
+ type: s,
+ dfdFlags: l
+ }
+ }, t);
+ } catch (e) {
+ console.error(e), self.postMessage({
+ type: "error",
+ id: r.id,
+ error: e.message
+ });
+ }
+ });
+ break;
+ }
+ });
+ function s(e) {
+ t = new Promise((t) => {
+ n = {
+ wasmBinary: e,
+ onRuntimeInitialized: t
+ }, BASIS(n);
+ }).then(() => {
+ n.initializeBasis(), n.KTX2File === void 0 && console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder.");
+ });
+ }
+ function c(e) {
+ let t = new n.KTX2File(new Uint8Array(e));
+ function r() {
+ t.close(), t.delete();
+ }
+ if (!t.isValid()) throw r(), Error("THREE.KTX2Loader: Invalid or unsupported .ktx2 file");
+ let a;
+ if (t.isUASTC()) a = o.UASTC;
+ else if (t.isETC1S()) a = o.ETC1S;
+ else if (t.isHDR()) a = o.UASTC_HDR;
+ else throw Error("THREE.KTX2Loader: Unknown Basis encoding");
+ let s = t.getWidth(), c = t.getHeight(), l = t.getLayers() || 1, u = t.getLevels(), f = t.getFaces(), m = t.getHasAlpha(), h = t.getDFDFlags(), { transcoderFormat: g, engineFormat: _, engineType: v } = d(a, s, c, m);
+ if (!s || !c || !u) throw r(), Error("THREE.KTX2Loader: Invalid texture");
+ if (!t.startTranscoding()) throw r(), Error("THREE.KTX2Loader: .startTranscoding failed");
+ let y = [], b = [];
+ for (let e = 0; e < f; e++) {
+ let n = [];
+ for (let a = 0; a < u; a++) {
+ let o = [], s, c;
+ for (let n = 0; n < l; n++) {
+ let l = t.getImageLevelInfo(a, n, e);
+ e === 0 && a === 0 && n === 0 && (l.origWidth % 4 != 0 || l.origHeight % 4 != 0) && console.warn("THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions."), u > 1 ? (s = l.origWidth, c = l.origHeight) : (s = l.width, c = l.height);
+ let d = new Uint8Array(t.getImageTranscodedSizeInBytes(a, n, 0, g)), f = t.transcodeImage(d, a, n, e, g, 0, -1, -1);
+ if (v === i.HalfFloatType && (d = new Uint16Array(d.buffer, d.byteOffset, d.byteLength / Uint16Array.BYTES_PER_ELEMENT)), !f) throw r(), Error("THREE.KTX2Loader: .transcodeImage failed.");
+ o.push(d);
+ }
+ let d = p(o);
+ n.push({
+ data: d,
+ width: s,
+ height: c
+ }), b.push(d.buffer);
+ }
+ y.push({
+ mipmaps: n,
+ width: s,
+ height: c,
+ format: _,
+ type: v
+ });
+ }
+ return r(), {
+ faces: y,
+ buffers: b,
+ width: s,
+ height: c,
+ hasAlpha: m,
+ dfdFlags: h,
+ format: _,
+ type: v
+ };
+ }
+ let l = [
+ {
+ if: "astcSupported",
+ basisFormat: [o.UASTC],
+ transcoderFormat: [a.ASTC_4x4, a.ASTC_4x4],
+ engineFormat: [r.RGBA_ASTC_4x4_Format, r.RGBA_ASTC_4x4_Format],
+ engineType: [i.UnsignedByteType],
+ priorityETC1S: Infinity,
+ priorityUASTC: 1,
+ needsPowerOfTwo: !1
+ },
+ {
+ if: "bptcSupported",
+ basisFormat: [o.ETC1S, o.UASTC],
+ transcoderFormat: [a.BC7_M5, a.BC7_M5],
+ engineFormat: [r.RGBA_BPTC_Format, r.RGBA_BPTC_Format],
+ engineType: [i.UnsignedByteType],
+ priorityETC1S: 3,
+ priorityUASTC: 2,
+ needsPowerOfTwo: !1
+ },
+ {
+ if: "dxtSupported",
+ basisFormat: [o.ETC1S, o.UASTC],
+ transcoderFormat: [a.BC1, a.BC3],
+ engineFormat: [r.RGBA_S3TC_DXT1_Format, r.RGBA_S3TC_DXT5_Format],
+ engineType: [i.UnsignedByteType],
+ priorityETC1S: 4,
+ priorityUASTC: 5,
+ needsPowerOfTwo: !1
+ },
+ {
+ if: "etc2Supported",
+ basisFormat: [o.ETC1S, o.UASTC],
+ transcoderFormat: [a.ETC1, a.ETC2],
+ engineFormat: [r.RGB_ETC2_Format, r.RGBA_ETC2_EAC_Format],
+ engineType: [i.UnsignedByteType],
+ priorityETC1S: 1,
+ priorityUASTC: 3,
+ needsPowerOfTwo: !1
+ },
+ {
+ if: "etc1Supported",
+ basisFormat: [o.ETC1S, o.UASTC],
+ transcoderFormat: [a.ETC1],
+ engineFormat: [r.RGB_ETC1_Format],
+ engineType: [i.UnsignedByteType],
+ priorityETC1S: 2,
+ priorityUASTC: 4,
+ needsPowerOfTwo: !1
+ },
+ {
+ if: "pvrtcSupported",
+ basisFormat: [o.ETC1S, o.UASTC],
+ transcoderFormat: [a.PVRTC1_4_RGB, a.PVRTC1_4_RGBA],
+ engineFormat: [r.RGB_PVRTC_4BPPV1_Format, r.RGBA_PVRTC_4BPPV1_Format],
+ engineType: [i.UnsignedByteType],
+ priorityETC1S: 5,
+ priorityUASTC: 6,
+ needsPowerOfTwo: !0
+ },
+ {
+ if: "bptcSupported",
+ basisFormat: [o.UASTC_HDR],
+ transcoderFormat: [a.BC6H],
+ engineFormat: [r.RGB_BPTC_UNSIGNED_Format],
+ engineType: [i.HalfFloatType],
+ priorityHDR: 1,
+ needsPowerOfTwo: !1
+ },
+ {
+ basisFormat: [o.ETC1S, o.UASTC],
+ transcoderFormat: [a.RGBA32, a.RGBA32],
+ engineFormat: [r.RGBAFormat, r.RGBAFormat],
+ engineType: [i.UnsignedByteType, i.UnsignedByteType],
+ priorityETC1S: 100,
+ priorityUASTC: 100,
+ needsPowerOfTwo: !1
+ },
+ {
+ basisFormat: [o.UASTC_HDR],
+ transcoderFormat: [a.RGBA_HALF],
+ engineFormat: [r.RGBAFormat],
+ engineType: [i.HalfFloatType],
+ priorityHDR: 100,
+ needsPowerOfTwo: !1
+ }
+ ], u = {
+ [o.ETC1S]: l.filter((e) => e.basisFormat.includes(o.ETC1S)).sort((e, t) => e.priorityUASTC - t.priorityUASTC),
+ [o.UASTC]: l.filter((e) => e.basisFormat.includes(o.UASTC)).sort((e, t) => e.priorityUASTC - t.priorityUASTC),
+ [o.UASTC_HDR]: l.filter((e) => e.basisFormat.includes(o.UASTC_HDR)).sort((e, t) => e.priorityHDR - t.priorityHDR)
+ };
+ function d(t, n, r, i) {
+ let a = u[t];
+ for (let o = 0; o < a.length; o++) {
+ let s = a[o];
+ if (!(s.if && !e[s.if]) && s.basisFormat.includes(t) && !(i && s.transcoderFormat.length < 2) && !(s.needsPowerOfTwo && !(f(n) && f(r)))) return {
+ transcoderFormat: s.transcoderFormat[+!!i],
+ engineFormat: s.engineFormat[+!!i],
+ engineType: s.engineType[0]
+ };
+ }
+ throw Error("THREE.KTX2Loader: Failed to identify transcoding target.");
+ }
+ function f(e) {
+ return e <= 2 ? !0 : (e & e - 1) == 0 && e !== 0;
+ }
+ function p(e) {
+ if (e.length === 1) return e[0];
+ let t = 0;
+ for (let n = 0; n < e.length; n++) {
+ let r = e[n];
+ t += r.byteLength;
+ }
+ let n = new Uint8Array(t), r = 0;
+ for (let t = 0; t < e.length; t++) {
+ let i = e[t];
+ n.set(i, r), r += i.byteLength;
+ }
+ return n;
+ }
+};
+var qg = new Set([
+ O,
+ ne,
+ A
+]), Jg = {
+ 109: O,
+ 97: O,
+ 37: O,
+ 43: O,
+ 103: ne,
+ 83: ne,
+ 16: ne,
+ 22: ne,
+ 100: A,
+ 76: A,
+ 15: A,
+ 9: A,
+ [kg]: ge,
+ 166: be,
+ 165: be
+}, Yg = {
+ 109: b,
+ 97: x,
+ 37: m,
+ 43: m,
+ 103: b,
+ 83: x,
+ 16: m,
+ 22: m,
+ 100: b,
+ 76: x,
+ 15: m,
+ 9: m,
+ [kg]: x,
+ 166: m,
+ 165: m
+};
+async function Xg(e) {
+ let { vkFormat: t } = e;
+ if (Jg[t] === void 0) throw Error("THREE.KTX2Loader: Unsupported vkFormat.");
+ let n;
+ e.supercompressionScheme === 2 && (Gg ||= new Promise(async (e) => {
+ let t = new zg();
+ await t.init(), e(t);
+ }), n = await Gg);
+ let r = [];
+ for (let i = 0; i < e.levels.length; i++) {
+ let a = Math.max(1, e.pixelWidth >> i), o = Math.max(1, e.pixelHeight >> i), s = e.pixelDepth ? Math.max(1, e.pixelDepth >> i) : 0, c = e.levels[i], l;
+ if (e.supercompressionScheme === 0) l = c.levelData;
+ else if (e.supercompressionScheme === 2) l = n.decode(c.levelData, c.uncompressedByteLength);
+ else throw Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");
+ let u;
+ u = Yg[t] === 1015 ? new Float32Array(l.buffer, l.byteOffset, l.byteLength / Float32Array.BYTES_PER_ELEMENT) : Yg[t] === 1016 ? new Uint16Array(l.buffer, l.byteOffset, l.byteLength / Uint16Array.BYTES_PER_ELEMENT) : l, r.push({
+ data: u,
+ width: a,
+ height: o,
+ depth: s
+ });
+ }
+ let i;
+ if (qg.has(Jg[t])) i = e.pixelDepth === 0 ? new Hi(r[0].data, e.pixelWidth, e.pixelHeight) : new Qt(r[0].data, e.pixelWidth, e.pixelHeight, e.pixelDepth);
+ else {
+ if (e.pixelDepth > 0) throw Error("THREE.KTX2Loader: Unsupported pixelDepth.");
+ i = new ka(r, e.pixelWidth, e.pixelHeight), i.minFilter = r.length === 1 ? d : p, i.magFilter = d;
+ }
+ return i.mipmaps = r, i.type = Yg[t], i.format = Jg[t], i.colorSpace = Zg(e), i.needsUpdate = !0, Promise.resolve(i);
+}
+function Zg(e) {
+ let t = e.dataFormatDescriptor[0];
+ return t.colorPrimaries === 1 ? t.transferFunction === 2 ? Ge : Ke : t.colorPrimaries === 10 ? t.transferFunction === 2 ? Vg : Hg : (t.colorPrimaries === 0 || console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${t.colorPrimaries}"`), "");
+}
+//#endregion
+//#region src/viewer/internal.js
+var Qg = "[default]", $g = { ASSET_GENERATOR: "assetgenerator" }, e_ = new ao(), t_ = "https://unpkg.com/[email protected]", n_ = new Eg(e_).setDecoderPath(`${t_}/examples/jsm/libs/draco/gltf/`), r_ = new Kg(e_).setTranscoderPath(`${t_}/examples/jsm/libs/basis/`);
+function i_(e, t) {
+ let n = /* @__PURE__ */ new Set();
+ e.traverse((e) => {
+ e.geometry && (Array.isArray(e.material) ? e.material : [e.material]).forEach((e) => {
+ e && !n.has(e.uuid) && (n.add(e.uuid), t(e));
+ });
+ });
+}
+//#endregion
+//#region src/viewer/lights.js
+function a_(e) {
+ let { state: t, options: n } = e;
+ if (n.preset === $g.ASSET_GENERATOR) {
+ let t = new go();
+ t.name = "hemi_light", e.scene.add(t), e.lights.push(t);
+ return;
+ }
+ let r = new jo(t.ambientColor, t.ambientIntensity);
+ r.name = "ambient_light", e.defaultCamera.add(r);
+ let i = new Ao(t.directColor, t.directIntensity);
+ i.position.set(.5, 0, .866), i.name = "main_light", e.defaultCamera.add(i), e.lights.push(r, i);
+}
+function o_(e) {
+ e.lights.forEach((e) => e.parent.remove(e)), e.lights.length = 0;
+}
+//#endregion
+//#region node_modules/three/examples/jsm/libs/fflate.module.js
+var s_ = Uint8Array, c_ = Uint16Array, l_ = Int32Array, u_ = new s_([
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 1,
+ 1,
+ 1,
+ 2,
+ 2,
+ 2,
+ 2,
+ 3,
+ 3,
+ 3,
+ 3,
+ 4,
+ 4,
+ 4,
+ 4,
+ 5,
+ 5,
+ 5,
+ 5,
+ 0,
+ 0,
+ 0,
+ 0
+]), d_ = new s_([
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 1,
+ 2,
+ 2,
+ 3,
+ 3,
+ 4,
+ 4,
+ 5,
+ 5,
+ 6,
+ 6,
+ 7,
+ 7,
+ 8,
+ 8,
+ 9,
+ 9,
+ 10,
+ 10,
+ 11,
+ 11,
+ 12,
+ 12,
+ 13,
+ 13,
+ 0,
+ 0
+]), f_ = new s_([
+ 16,
+ 17,
+ 18,
+ 0,
+ 8,
+ 7,
+ 9,
+ 6,
+ 10,
+ 5,
+ 11,
+ 4,
+ 12,
+ 3,
+ 13,
+ 2,
+ 14,
+ 1,
+ 15
+]), p_ = function(e, t) {
+ for (var n = new c_(31), r = 0; r < 31; ++r) n[r] = t += 1 << e[r - 1];
+ for (var i = new l_(n[30]), r = 1; r < 30; ++r) for (var a = n[r]; a < n[r + 1]; ++a) i[a] = a - n[r] << 5 | r;
+ return {
+ b: n,
+ r: i
+ };
+}, m_ = p_(u_, 2), h_ = m_.b, g_ = m_.r;
+h_[28] = 258, g_[258] = 28;
+var __ = p_(d_, 0), v_ = __.b;
+__.r;
+for (var y_ = new c_(32768), b_ = 0; b_ < 32768; ++b_) {
+ var x_ = (b_ & 43690) >> 1 | (b_ & 21845) << 1;
+ x_ = (x_ & 52428) >> 2 | (x_ & 13107) << 2, x_ = (x_ & 61680) >> 4 | (x_ & 3855) << 4, y_[b_] = ((x_ & 65280) >> 8 | (x_ & 255) << 8) >> 1;
+}
+for (var S_ = (function(e, t, n) {
+ for (var r = e.length, i = 0, a = new c_(t); i < r; ++i) e[i] && ++a[e[i] - 1];
+ var o = new c_(t);
+ for (i = 1; i < t; ++i) o[i] = o[i - 1] + a[i - 1] << 1;
+ var s;
+ if (n) {
+ s = new c_(1 << t);
+ var c = 15 - t;
+ for (i = 0; i < r; ++i) if (e[i]) for (var l = i << 4 | e[i], u = t - e[i], d = o[e[i] - 1]++ << u, f = d | (1 << u) - 1; d <= f; ++d) s[y_[d] >> c] = l;
+ } else for (s = new c_(r), i = 0; i < r; ++i) e[i] && (s[i] = y_[o[e[i] - 1]++] >> 15 - e[i]);
+ return s;
+}), C_ = new s_(288), b_ = 0; b_ < 144; ++b_) C_[b_] = 8;
+for (var b_ = 144; b_ < 256; ++b_) C_[b_] = 9;
+for (var b_ = 256; b_ < 280; ++b_) C_[b_] = 7;
+for (var b_ = 280; b_ < 288; ++b_) C_[b_] = 8;
+for (var w_ = new s_(32), b_ = 0; b_ < 32; ++b_) w_[b_] = 5;
+var T_ = /* @__PURE__ */ S_(C_, 9, 1), E_ = /* @__PURE__ */ S_(w_, 5, 1), D_ = function(e) {
+ for (var t = e[0], n = 1; n < e.length; ++n) e[n] > t && (t = e[n]);
+ return t;
+}, O_ = function(e, t, n) {
+ var r = t / 8 | 0;
+ return (e[r] | e[r + 1] << 8) >> (t & 7) & n;
+}, k_ = function(e, t) {
+ var n = t / 8 | 0;
+ return (e[n] | e[n + 1] << 8 | e[n + 2] << 16) >> (t & 7);
+}, A_ = function(e) {
+ return (e + 7) / 8 | 0;
+}, j_ = function(e, t, n) {
+ return (t == null || t < 0) && (t = 0), (n == null || n > e.length) && (n = e.length), new s_(e.subarray(t, n));
+}, M_ = [
+ "unexpected EOF",
+ "invalid block type",
+ "invalid length/literal",
+ "invalid distance",
+ "stream finished",
+ "no stream handler",
+ ,
+ "no callback",
+ "invalid UTF-8 data",
+ "extra field too long",
+ "date not in range 1980-2099",
+ "filename too long",
+ "stream finishing",
+ "invalid zip data"
+], N_ = function(e, t, n) {
+ var r = Error(t || M_[e]);
+ if (r.code = e, Error.captureStackTrace && Error.captureStackTrace(r, N_), !n) throw r;
+ return r;
+}, P_ = function(e, t, n, r) {
+ var i = e.length, a = r ? r.length : 0;
+ if (!i || t.f && !t.l) return n || new s_(0);
+ var o = !n, s = o || t.i != 2, c = t.i;
+ o && (n = new s_(i * 3));
+ var l = function(e) {
+ var t = n.length;
+ if (e > t) {
+ var r = new s_(Math.max(t * 2, e));
+ r.set(n), n = r;
+ }
+ }, u = t.f || 0, d = t.p || 0, f = t.b || 0, p = t.l, m = t.d, h = t.m, g = t.n, _ = i * 8;
+ do {
+ if (!p) {
+ u = O_(e, d, 1);
+ var v = O_(e, d + 1, 3);
+ if (d += 3, !v) {
+ var y = A_(d) + 4, b = e[y - 4] | e[y - 3] << 8, x = y + b;
+ if (x > i) {
+ c && N_(0);
+ break;
+ }
+ s && l(f + b), n.set(e.subarray(y, x), f), t.b = f += b, t.p = d = x * 8, t.f = u;
+ continue;
+ } else if (v == 1) p = T_, m = E_, h = 9, g = 5;
+ else if (v == 2) {
+ var S = O_(e, d, 31) + 257, C = O_(e, d + 10, 15) + 4, w = S + O_(e, d + 5, 31) + 1;
+ d += 14;
+ for (var T = new s_(w), E = new s_(19), D = 0; D < C; ++D) E[f_[D]] = O_(e, d + D * 3, 7);
+ d += C * 3;
+ for (var O = D_(E), k = (1 << O) - 1, ee = S_(E, O, 1), D = 0; D < w;) {
+ var A = ee[O_(e, d, k)];
+ d += A & 15;
+ var y = A >> 4;
+ if (y < 16) T[D++] = y;
+ else {
+ var te = 0, ne = 0;
+ for (y == 16 ? (ne = 3 + O_(e, d, 3), d += 2, te = T[D - 1]) : y == 17 ? (ne = 3 + O_(e, d, 7), d += 3) : y == 18 && (ne = 11 + O_(e, d, 127), d += 7); ne--;) T[D++] = te;
+ }
+ }
+ var re = T.subarray(0, S), ie = T.subarray(S);
+ h = D_(re), g = D_(ie), p = S_(re, h, 1), m = S_(ie, g, 1);
+ } else N_(1);
+ if (d > _) {
+ c && N_(0);
+ break;
+ }
+ }
+ s && l(f + 131072);
+ for (var ae = (1 << h) - 1, oe = (1 << g) - 1, se = d;; se = d) {
+ var te = p[k_(e, d) & ae], ce = te >> 4;
+ if (d += te & 15, d > _) {
+ c && N_(0);
+ break;
+ }
+ if (te || N_(2), ce < 256) n[f++] = ce;
+ else if (ce == 256) {
+ se = d, p = null;
+ break;
+ } else {
+ var le = ce - 254;
+ if (ce > 264) {
+ var D = ce - 257, ue = u_[D];
+ le = O_(e, d, (1 << ue) - 1) + h_[D], d += ue;
+ }
+ var de = m[k_(e, d) & oe], fe = de >> 4;
+ de || N_(3), d += de & 15;
+ var ie = v_[fe];
+ if (fe > 3) {
+ var ue = d_[fe];
+ ie += k_(e, d) & (1 << ue) - 1, d += ue;
+ }
+ if (d > _) {
+ c && N_(0);
+ break;
+ }
+ s && l(f + 131072);
+ var pe = f + le;
+ if (f < ie) {
+ var me = a - ie, he = Math.min(ie, pe);
+ for (me + f < 0 && N_(3); f < he; ++f) n[f] = r[me + f];
+ }
+ for (; f < pe; ++f) n[f] = n[f - ie];
+ }
+ }
+ t.l = p, t.p = se, t.b = f, t.f = u, p && (u = 1, t.m = h, t.d = m, t.n = g);
+ } while (!u);
+ return f != n.length && o ? j_(n, 0, f) : n.subarray(0, f);
+}, F_ = /* @__PURE__ */ new s_(0), I_ = function(e, t) {
+ return ((e[0] & 15) != 8 || e[0] >> 4 > 7 || (e[0] << 8 | e[1]) % 31) && N_(6, "invalid zlib data"), (e[1] >> 5 & 1) == +!t && N_(6, "invalid zlib data: " + (e[1] & 32 ? "need" : "unexpected") + " dictionary"), (e[1] >> 3 & 4) + 2;
+};
+function L_(e, t) {
+ return P_(e.subarray(I_(e, t && t.dictionary), -4), { i: 2 }, t && t.out, t && t.dictionary);
+}
+var R_ = typeof TextDecoder < "u" && /* @__PURE__ */ new TextDecoder();
+try {
+ R_.decode(F_, { stream: !0 });
+} catch {}
+//#endregion
+//#region node_modules/three/examples/jsm/loaders/EXRLoader.js
+var z_ = class extends po {
+ constructor(e) {
+ super(e), this.type = x;
+ }
+ parse(e) {
+ let t = 65536, n = t >> 3, r = 65537, i = 16384, a = i - 1, o = 65535, s = 2.7182818 ** 2.2;
+ function c(e, n) {
+ let r = 0;
+ for (let i = 0; i < t; ++i) (i == 0 || e[i >> 3] & 1 << (i & 7)) && (n[r++] = i);
+ let i = r - 1;
+ for (; r < t;) n[r++] = 0;
+ return i;
+ }
+ function l(e) {
+ for (let t = 0; t < i; t++) e[t] = {}, e[t].len = 0, e[t].lit = 0, e[t].p = null;
+ }
+ let u = {
+ l: 0,
+ c: 0,
+ lc: 0
+ };
+ function d(e, t, n, r, i) {
+ for (; n < e;) t = t << 8 | we(r, i), n += 8;
+ n -= e, u.l = t >> n & (1 << e) - 1, u.c = t, u.lc = n;
+ }
+ let f = Array(59);
+ function p(e) {
+ for (let e = 0; e <= 58; ++e) f[e] = 0;
+ for (let t = 0; t < r; ++t) f[e[t]] += 1;
+ let t = 0;
+ for (let e = 58; e > 0; --e) {
+ let n = t + f[e] >> 1;
+ f[e] = t, t = n;
+ }
+ for (let t = 0; t < r; ++t) {
+ let n = e[t];
+ n > 0 && (e[t] = n | f[n]++ << 6);
+ }
+ }
+ function m(e, t, n, r, i, a) {
+ let o = t, s = 0, c = 0;
+ for (; r <= i; r++) {
+ if (o.value - t.value > n) return !1;
+ d(6, s, c, e, o);
+ let l = u.l;
+ if (s = u.c, c = u.lc, a[r] = l, l == 63) {
+ if (o.value - t.value > n) throw Error("Something wrong with hufUnpackEncTable");
+ d(8, s, c, e, o);
+ let l = u.l + 6;
+ if (s = u.c, c = u.lc, r + l > i + 1) throw Error("Something wrong with hufUnpackEncTable");
+ for (; l--;) a[r++] = 0;
+ r--;
+ } else if (l >= 59) {
+ let e = l - 59 + 2;
+ if (r + e > i + 1) throw Error("Something wrong with hufUnpackEncTable");
+ for (; e--;) a[r++] = 0;
+ r--;
+ }
+ }
+ p(a);
+ }
+ function h(e) {
+ return e & 63;
+ }
+ function g(e) {
+ return e >> 6;
+ }
+ function _(e, t, n, r) {
+ for (; t <= n; t++) {
+ let n = g(e[t]), i = h(e[t]);
+ if (n >> i) throw Error("Invalid table entry");
+ if (i > 14) {
+ let e = r[n >> i - 14];
+ if (e.len) throw Error("Invalid table entry");
+ if (e.lit++, e.p) {
+ let t = e.p;
+ e.p = Array(e.lit);
+ for (let n = 0; n < e.lit - 1; ++n) e.p[n] = t[n];
+ } else e.p = [,];
+ e.p[e.lit - 1] = t;
+ } else if (i) {
+ let e = 0;
+ for (let a = 1 << 14 - i; a > 0; a--) {
+ let a = r[(n << 14 - i) + e];
+ if (a.len || a.p) throw Error("Invalid table entry");
+ a.len = i, a.lit = t, e++;
+ }
+ }
+ }
+ return !0;
+ }
+ let v = {
+ c: 0,
+ lc: 0
+ };
+ function y(e, t, n, r) {
+ e = e << 8 | we(n, r), t += 8, v.c = e, v.lc = t;
+ }
+ let S = {
+ c: 0,
+ lc: 0
+ };
+ function C(e, t, n, r, i, a, o, s, c) {
+ if (e == t) {
+ r < 8 && (y(n, r, i, a), n = v.c, r = v.lc), r -= 8;
+ let e = n >> r;
+ if (e = new Uint8Array([e])[0], s.value + e > c) return !1;
+ let t = o[s.value - 1];
+ for (; e-- > 0;) o[s.value++] = t;
+ } else if (s.value < c) o[s.value++] = e;
+ else return !1;
+ S.c = n, S.lc = r;
+ }
+ function w(e) {
+ return e & 65535;
+ }
+ function T(e) {
+ let t = w(e);
+ return t > 32767 ? t - 65536 : t;
+ }
+ let E = {
+ a: 0,
+ b: 0
+ };
+ function D(e, t) {
+ let n = T(e), r = T(t), i = n + (r & 1) + (r >> 1), a = i, o = i - r;
+ E.a = a, E.b = o;
+ }
+ function k(e, t) {
+ let n = w(e), r = w(t), i = n - (r >> 1) & o;
+ E.a = r + i - 32768 & o, E.b = i;
+ }
+ function ee(e, t, n, r, i, a, o) {
+ let s = o < 16384, c = n > i ? i : n, l = 1, u, d;
+ for (; l <= c;) l <<= 1;
+ for (l >>= 1, u = l, l >>= 1; l >= 1;) {
+ d = 0;
+ let o = d + a * (i - u), c = a * l, f = a * u, p = r * l, m = r * u, h, g, _, v;
+ for (; d <= o; d += f) {
+ let i = d, a = d + r * (n - u);
+ for (; i <= a; i += m) {
+ let n = i + p, r = i + c, a = r + p;
+ s ? (D(e[i + t], e[r + t]), h = E.a, _ = E.b, D(e[n + t], e[a + t]), g = E.a, v = E.b, D(h, g), e[i + t] = E.a, e[n + t] = E.b, D(_, v), e[r + t] = E.a, e[a + t] = E.b) : (k(e[i + t], e[r + t]), h = E.a, _ = E.b, k(e[n + t], e[a + t]), g = E.a, v = E.b, k(h, g), e[i + t] = E.a, e[n + t] = E.b, k(_, v), e[r + t] = E.a, e[a + t] = E.b);
+ }
+ if (n & l) {
+ let n = i + c;
+ s ? D(e[i + t], e[n + t]) : k(e[i + t], e[n + t]), h = E.a, e[n + t] = E.b, e[i + t] = h;
+ }
+ }
+ if (i & l) {
+ let i = d, a = d + r * (n - u);
+ for (; i <= a; i += m) {
+ let n = i + p;
+ s ? D(e[i + t], e[n + t]) : k(e[i + t], e[n + t]), h = E.a, e[n + t] = E.b, e[i + t] = h;
+ }
+ }
+ u = l, l >>= 1;
+ }
+ return d;
+ }
+ function te(e, t, n, r, i, o, s, c, l) {
+ let u = 0, d = 0, f = s, p = Math.trunc(r.value + (i + 7) / 8);
+ for (; r.value < p;) for (y(u, d, n, r), u = v.c, d = v.lc; d >= 14;) {
+ let i = t[u >> d - 14 & a];
+ if (i.len) d -= i.len, C(i.lit, o, u, d, n, r, c, l, f), u = S.c, d = S.lc;
+ else {
+ if (!i.p) throw Error("hufDecode issues");
+ let t;
+ for (t = 0; t < i.lit; t++) {
+ let a = h(e[i.p[t]]);
+ for (; d < a && r.value < p;) y(u, d, n, r), u = v.c, d = v.lc;
+ if (d >= a && g(e[i.p[t]]) == (u >> d - a & (1 << a) - 1)) {
+ d -= a, C(i.p[t], o, u, d, n, r, c, l, f), u = S.c, d = S.lc;
+ break;
+ }
+ }
+ if (t == i.lit) throw Error("hufDecode issues");
+ }
+ }
+ let m = 8 - i & 7;
+ for (u >>= m, d -= m; d > 0;) {
+ let e = t[u << 14 - d & a];
+ if (e.len) d -= e.len, C(e.lit, o, u, d, n, r, c, l, f), u = S.c, d = S.lc;
+ else throw Error("hufDecode issues");
+ }
+ return !0;
+ }
+ function ne(e, t, n, a, o, s) {
+ let c = { value: 0 }, u = n.value, d = M(t, n), f = M(t, n);
+ n.value += 4;
+ let p = M(t, n);
+ if (n.value += 4, d < 0 || d >= r || f < 0 || f >= r) throw Error("Something wrong with HUF_ENCSIZE");
+ let h = Array(r), g = Array(i);
+ if (l(g), m(e, n, a - (n.value - u), d, f, h), p > 8 * (a - (n.value - u))) throw Error("Something wrong with hufUncompress");
+ _(h, d, f, g), te(h, g, e, n, p, f, s, o, c);
+ }
+ function re(e, t, n) {
+ for (let r = 0; r < n; ++r) t[r] = e[t[r]];
+ }
+ function ie(e) {
+ for (let t = 1; t < e.length; t++) e[t] = e[t - 1] + e[t] - 128;
+ }
+ function ae(e, t) {
+ let n = 0, r = Math.floor((e.length + 1) / 2), i = 0, a = e.length - 1;
+ for (; !(i > a || (t[i++] = e[n++], i > a));) t[i++] = e[r++];
+ }
+ function oe(e) {
+ let t = e.byteLength, n = [], r = 0, i = new DataView(e);
+ for (; t > 0;) {
+ let e = i.getInt8(r++);
+ if (e < 0) {
+ let a = -e;
+ t -= a + 1;
+ for (let e = 0; e < a; e++) n.push(i.getUint8(r++));
+ } else {
+ let a = e;
+ t -= 2;
+ let o = i.getUint8(r++);
+ for (let e = 0; e < a + 1; e++) n.push(o);
+ }
+ }
+ return n;
+ }
+ function se(e, t, n, r, i, a) {
+ let o = new DataView(a.buffer), s = n[e.idx[0]].width, c = n[e.idx[0]].height, l = Math.floor(s / 8), u = Math.ceil(s / 8), d = Math.ceil(c / 8), f = s - (u - 1) * 8, p = c - (d - 1) * 8, m = { value: 0 }, h = [
+ ,
+ ,
+ ,
+ ], g = [
+ ,
+ ,
+ ,
+ ], _ = [
+ ,
+ ,
+ ,
+ ], v = [
+ ,
+ ,
+ ,
+ ], y = [
+ ,
+ ,
+ ,
+ ];
+ for (let n = 0; n < 3; ++n) y[n] = t[e.idx[n]], h[n] = n < 1 ? 0 : h[n - 1] + u * d, g[n] = new Float32Array(64), _[n] = new Uint16Array(64), v[n] = new Uint16Array(u * 64);
+ for (let t = 0; t < d; ++t) {
+ let a = 8;
+ t == d - 1 && (a = p);
+ let s = 8;
+ for (let e = 0; e < u; ++e) {
+ e == u - 1 && (s = f);
+ for (let e = 0; e < 3; ++e) _[e].fill(0), _[e][0] = i[h[e]++], ce(m, r, _[e]), le(_[e], g[e]), ue(g[e]);
+ de(g);
+ for (let t = 0; t < 3; ++t) fe(g[t], v[t], e * 64);
+ }
+ let c = 0;
+ for (let r = 0; r < 3; ++r) {
+ let i = n[e.idx[r]].type;
+ for (let e = 8 * t; e < 8 * t + a; ++e) {
+ c = y[r][e];
+ for (let t = 0; t < l; ++t) {
+ let n = t * 64 + (e & 7) * 8;
+ o.setUint16(c + 0 * i, v[r][n + 0], !0), o.setUint16(c + 2 * i, v[r][n + 1], !0), o.setUint16(c + 4 * i, v[r][n + 2], !0), o.setUint16(c + 6 * i, v[r][n + 3], !0), o.setUint16(c + 8 * i, v[r][n + 4], !0), o.setUint16(c + 10 * i, v[r][n + 5], !0), o.setUint16(c + 12 * i, v[r][n + 6], !0), o.setUint16(c + 14 * i, v[r][n + 7], !0), c += 16 * i;
+ }
+ }
+ if (l != u) for (let e = 8 * t; e < 8 * t + a; ++e) {
+ let t = y[r][e] + 8 * l * 2 * i, n = l * 64 + (e & 7) * 8;
+ for (let e = 0; e < s; ++e) o.setUint16(t + e * 2 * i, v[r][n + e], !0);
+ }
+ }
+ }
+ let b = new Uint16Array(s);
+ o = new DataView(a.buffer);
+ for (let t = 0; t < 3; ++t) {
+ n[e.idx[t]].decoded = !0;
+ let r = n[e.idx[t]].type;
+ if (n[t].type == 2) for (let e = 0; e < c; ++e) {
+ let n = y[t][e];
+ for (let e = 0; e < s; ++e) b[e] = o.getUint16(n + e * 2 * r, !0);
+ for (let e = 0; e < s; ++e) o.setFloat32(n + e * 2 * r, F(b[e]), !0);
+ }
+ }
+ }
+ function ce(e, t, n) {
+ let r, i = 1;
+ for (; i < 64;) r = t[e.value], r == 65280 ? i = 64 : r >> 8 == 255 ? i += r & 255 : (n[i] = r, i++), e.value++;
+ }
+ function le(e, t) {
+ t[0] = F(e[0]), t[1] = F(e[1]), t[2] = F(e[5]), t[3] = F(e[6]), t[4] = F(e[14]), t[5] = F(e[15]), t[6] = F(e[27]), t[7] = F(e[28]), t[8] = F(e[2]), t[9] = F(e[4]), t[10] = F(e[7]), t[11] = F(e[13]), t[12] = F(e[16]), t[13] = F(e[26]), t[14] = F(e[29]), t[15] = F(e[42]), t[16] = F(e[3]), t[17] = F(e[8]), t[18] = F(e[12]), t[19] = F(e[17]), t[20] = F(e[25]), t[21] = F(e[30]), t[22] = F(e[41]), t[23] = F(e[43]), t[24] = F(e[9]), t[25] = F(e[11]), t[26] = F(e[18]), t[27] = F(e[24]), t[28] = F(e[31]), t[29] = F(e[40]), t[30] = F(e[44]), t[31] = F(e[53]), t[32] = F(e[10]), t[33] = F(e[19]), t[34] = F(e[23]), t[35] = F(e[32]), t[36] = F(e[39]), t[37] = F(e[45]), t[38] = F(e[52]), t[39] = F(e[54]), t[40] = F(e[20]), t[41] = F(e[22]), t[42] = F(e[33]), t[43] = F(e[38]), t[44] = F(e[46]), t[45] = F(e[51]), t[46] = F(e[55]), t[47] = F(e[60]), t[48] = F(e[21]), t[49] = F(e[34]), t[50] = F(e[37]), t[51] = F(e[47]), t[52] = F(e[50]), t[53] = F(e[56]), t[54] = F(e[59]), t[55] = F(e[61]), t[56] = F(e[35]), t[57] = F(e[36]), t[58] = F(e[48]), t[59] = F(e[49]), t[60] = F(e[57]), t[61] = F(e[58]), t[62] = F(e[62]), t[63] = F(e[63]);
+ }
+ function ue(e) {
+ let t = .5 * Math.cos(3.14159 / 4), n = .5 * Math.cos(3.14159 / 16), r = .5 * Math.cos(3.14159 / 8), i = .5 * Math.cos(3 * 3.14159 / 16), a = .5 * Math.cos(5 * 3.14159 / 16), o = .5 * Math.cos(3 * 3.14159 / 8), s = .5 * Math.cos(7 * 3.14159 / 16), c = [
+ ,
+ ,
+ ,
+ ,
+ ], l = [
+ ,
+ ,
+ ,
+ ,
+ ], u = [
+ ,
+ ,
+ ,
+ ,
+ ], d = [
+ ,
+ ,
+ ,
+ ,
+ ];
+ for (let f = 0; f < 8; ++f) {
+ let p = f * 8;
+ c[0] = r * e[p + 2], c[1] = o * e[p + 2], c[2] = r * e[p + 6], c[3] = o * e[p + 6], l[0] = n * e[p + 1] + i * e[p + 3] + a * e[p + 5] + s * e[p + 7], l[1] = i * e[p + 1] - s * e[p + 3] - n * e[p + 5] - a * e[p + 7], l[2] = a * e[p + 1] - n * e[p + 3] + s * e[p + 5] + i * e[p + 7], l[3] = s * e[p + 1] - a * e[p + 3] + i * e[p + 5] - n * e[p + 7], u[0] = t * (e[p + 0] + e[p + 4]), u[3] = t * (e[p + 0] - e[p + 4]), u[1] = c[0] + c[3], u[2] = c[1] - c[2], d[0] = u[0] + u[1], d[1] = u[3] + u[2], d[2] = u[3] - u[2], d[3] = u[0] - u[1], e[p + 0] = d[0] + l[0], e[p + 1] = d[1] + l[1], e[p + 2] = d[2] + l[2], e[p + 3] = d[3] + l[3], e[p + 4] = d[3] - l[3], e[p + 5] = d[2] - l[2], e[p + 6] = d[1] - l[1], e[p + 7] = d[0] - l[0];
+ }
+ for (let f = 0; f < 8; ++f) c[0] = r * e[16 + f], c[1] = o * e[16 + f], c[2] = r * e[48 + f], c[3] = o * e[48 + f], l[0] = n * e[8 + f] + i * e[24 + f] + a * e[40 + f] + s * e[56 + f], l[1] = i * e[8 + f] - s * e[24 + f] - n * e[40 + f] - a * e[56 + f], l[2] = a * e[8 + f] - n * e[24 + f] + s * e[40 + f] + i * e[56 + f], l[3] = s * e[8 + f] - a * e[24 + f] + i * e[40 + f] - n * e[56 + f], u[0] = t * (e[f] + e[32 + f]), u[3] = t * (e[f] - e[32 + f]), u[1] = c[0] + c[3], u[2] = c[1] - c[2], d[0] = u[0] + u[1], d[1] = u[3] + u[2], d[2] = u[3] - u[2], d[3] = u[0] - u[1], e[0 + f] = d[0] + l[0], e[8 + f] = d[1] + l[1], e[16 + f] = d[2] + l[2], e[24 + f] = d[3] + l[3], e[32 + f] = d[3] - l[3], e[40 + f] = d[2] - l[2], e[48 + f] = d[1] - l[1], e[56 + f] = d[0] - l[0];
+ }
+ function de(e) {
+ for (let t = 0; t < 64; ++t) {
+ let n = e[0][t], r = e[1][t], i = e[2][t];
+ e[0][t] = n + 1.5747 * i, e[1][t] = n - .1873 * r - .4682 * i, e[2][t] = n + 1.8556 * r;
+ }
+ }
+ function fe(e, t, n) {
+ for (let r = 0; r < 64; ++r) t[n + r] = kr.toHalfFloat(pe(e[r]));
+ }
+ function pe(e) {
+ return e <= 1 ? Math.sign(e) * Math.abs(e) ** 2.2 : Math.sign(e) * s ** (Math.abs(e) - 1);
+ }
+ function me(e) {
+ return new DataView(e.array.buffer, e.offset.value, e.size);
+ }
+ function he(e) {
+ let t = e.viewer.buffer.slice(e.offset.value, e.offset.value + e.size), n = new Uint8Array(oe(t)), r = new Uint8Array(n.length);
+ return ie(n), ae(n, r), new DataView(r.buffer);
+ }
+ function ge(e) {
+ let t = L_(e.array.slice(e.offset.value, e.offset.value + e.size)), n = new Uint8Array(t.length);
+ return ie(t), ae(t, n), new DataView(n.buffer);
+ }
+ function _e(e) {
+ let r = e.viewer, i = { value: e.offset.value }, a = new Uint16Array(e.columns * e.lines * (e.inputChannels.length * e.type)), o = new Uint8Array(n), s = 0, l = Array(e.inputChannels.length);
+ for (let t = 0, n = e.inputChannels.length; t < n; t++) l[t] = {}, l[t].start = s, l[t].end = l[t].start, l[t].nx = e.columns, l[t].ny = e.lines, l[t].size = e.type, s += l[t].nx * l[t].ny * l[t].size;
+ let u = De(r, i), d = De(r, i);
+ if (d >= n) throw Error("Something is wrong with PIZ_COMPRESSION BITMAP_SIZE");
+ if (u <= d) for (let e = 0; e < d - u + 1; e++) o[e + u] = N(r, i);
+ let f = new Uint16Array(t), p = c(o, f), m = M(r, i);
+ ne(e.array, r, i, m, a, s);
+ for (let t = 0; t < e.inputChannels.length; ++t) {
+ let e = l[t];
+ for (let n = 0; n < l[t].size; ++n) ee(a, e.start + n, e.nx, e.size, e.ny, e.nx * e.size, p);
+ }
+ re(f, a, s);
+ let h = 0, g = new Uint8Array(a.buffer.byteLength);
+ for (let t = 0; t < e.lines; t++) for (let t = 0; t < e.inputChannels.length; t++) {
+ let e = l[t], n = e.nx * e.size, r = new Uint8Array(a.buffer, e.end * 2, n * 2);
+ g.set(r, h), h += n * 2, e.end += n;
+ }
+ return new DataView(g.buffer);
+ }
+ function ve(e) {
+ let t = L_(e.array.slice(e.offset.value, e.offset.value + e.size)), n = e.inputChannels.length * e.lines * e.columns * e.totalBytes, r = new ArrayBuffer(n), i = new DataView(r), a = 0, o = 0, s = [
+ ,
+ ,
+ ,
+ ,
+ ];
+ for (let n = 0; n < e.lines; n++) for (let n = 0; n < e.inputChannels.length; n++) {
+ let r = 0;
+ switch (e.inputChannels[n].pixelType) {
+ case 1:
+ s[0] = a, s[1] = s[0] + e.columns, a = s[1] + e.columns;
+ for (let n = 0; n < e.columns; ++n) {
+ let e = t[s[0]++] << 8 | t[s[1]++];
+ r += e, i.setUint16(o, r, !0), o += 2;
+ }
+ break;
+ case 2:
+ s[0] = a, s[1] = s[0] + e.columns, s[2] = s[1] + e.columns, a = s[2] + e.columns;
+ for (let n = 0; n < e.columns; ++n) {
+ let e = t[s[0]++] << 24 | t[s[1]++] << 16 | t[s[2]++] << 8;
+ r += e, i.setUint32(o, r, !0), o += 4;
+ }
+ break;
+ }
+ }
+ return i;
+ }
+ function ye(e) {
+ let t = e.viewer, n = { value: e.offset.value }, r = new Uint8Array(e.columns * e.lines * (e.inputChannels.length * e.type * 2)), i = {
+ version: P(t, n),
+ unknownUncompressedSize: P(t, n),
+ unknownCompressedSize: P(t, n),
+ acCompressedSize: P(t, n),
+ dcCompressedSize: P(t, n),
+ rleCompressedSize: P(t, n),
+ rleUncompressedSize: P(t, n),
+ rleRawSize: P(t, n),
+ totalAcUncompressedCount: P(t, n),
+ totalDcUncompressedCount: P(t, n),
+ acCompression: P(t, n)
+ };
+ if (i.version < 2) throw Error("EXRLoader.parse: " + Xe.compression + " version " + i.version + " is unsupported");
+ let a = [], o = De(t, n) - 2;
+ for (; o > 0;) {
+ let e = be(t.buffer, n), r = N(t, n), i = r >> 2 & 3, s = (r >> 4) - 1, c = new Int8Array([s])[0], l = N(t, n);
+ a.push({
+ name: e,
+ index: c,
+ type: l,
+ compression: i
+ }), o -= e.length + 3;
+ }
+ let s = Xe.channels, c = Array(e.inputChannels.length);
+ for (let t = 0; t < e.inputChannels.length; ++t) {
+ let n = c[t] = {}, r = s[t];
+ n.name = r.name, n.compression = 0, n.decoded = !1, n.type = r.pixelType, n.pLinear = r.pLinear, n.width = e.columns, n.height = e.lines;
+ }
+ let l = { idx: [
+ ,
+ ,
+ ,
+ ] };
+ for (let t = 0; t < e.inputChannels.length; ++t) {
+ let e = c[t];
+ for (let n = 0; n < a.length; ++n) {
+ let r = a[n];
+ e.name == r.name && (e.compression = r.compression, r.index >= 0 && (l.idx[r.index] = t), e.offset = t);
+ }
+ }
+ let u, d, f;
+ if (i.acCompressedSize > 0) switch (i.acCompression) {
+ case 0:
+ u = new Uint16Array(i.totalAcUncompressedCount), ne(e.array, t, n, i.acCompressedSize, u, i.totalAcUncompressedCount);
+ break;
+ case 1:
+ let r = L_(e.array.slice(n.value, n.value + i.totalAcUncompressedCount));
+ u = new Uint16Array(r.buffer), n.value += i.totalAcUncompressedCount;
+ break;
+ }
+ if (i.dcCompressedSize > 0) {
+ let t = {
+ array: e.array,
+ offset: n,
+ size: i.dcCompressedSize
+ };
+ d = new Uint16Array(ge(t).buffer), n.value += i.dcCompressedSize;
+ }
+ i.rleRawSize > 0 && (f = oe(L_(e.array.slice(n.value, n.value + i.rleCompressedSize)).buffer), n.value += i.rleCompressedSize);
+ let p = 0, m = Array(c.length);
+ for (let e = 0; e < m.length; ++e) m[e] = [];
+ for (let t = 0; t < e.lines; ++t) for (let t = 0; t < c.length; ++t) m[t].push(p), p += c[t].width * e.type * 2;
+ se(l, m, c, u, d, r);
+ for (let t = 0; t < c.length; ++t) {
+ let n = c[t];
+ if (!n.decoded) switch (n.compression) {
+ case 2:
+ let i = 0, a = 0;
+ for (let o = 0; o < e.lines; ++o) {
+ let e = m[t][i];
+ for (let t = 0; t < n.width; ++t) {
+ for (let t = 0; t < 2 * n.type; ++t) r[e++] = f[a + t * n.width * n.height];
+ a++;
+ }
+ i++;
+ }
+ break;
+ default: throw Error("EXRLoader.parse: unsupported channel compression");
+ }
+ }
+ return new DataView(r.buffer);
+ }
+ function be(e, t) {
+ let n = new Uint8Array(e), r = 0;
+ for (; n[t.value + r] != 0;) r += 1;
+ let i = new TextDecoder().decode(n.slice(t.value, t.value + r));
+ return t.value = t.value + r + 1, i;
+ }
+ function j(e, t, n) {
+ let r = new TextDecoder().decode(new Uint8Array(e).slice(t.value, t.value + n));
+ return t.value += n, r;
+ }
+ function xe(e, t) {
+ return [Ce(e, t), M(e, t)];
+ }
+ function Se(e, t) {
+ return [M(e, t), M(e, t)];
+ }
+ function Ce(e, t) {
+ let n = e.getInt32(t.value, !0);
+ return t.value += 4, n;
+ }
+ function M(e, t) {
+ let n = e.getUint32(t.value, !0);
+ return t.value += 4, n;
+ }
+ function we(e, t) {
+ let n = e[t.value];
+ return t.value += 1, n;
+ }
+ function N(e, t) {
+ let n = e.getUint8(t.value);
+ return t.value += 1, n;
+ }
+ let P = function(e, t) {
+ let n;
+ return n = "getBigInt64" in DataView.prototype ? Number(e.getBigInt64(t.value, !0)) : e.getUint32(t.value + 4, !0) + Number(e.getUint32(t.value, !0) << 32), t.value += 8, n;
+ };
+ function Te(e, t) {
+ let n = e.getFloat32(t.value, !0);
+ return t.value += 4, n;
+ }
+ function Ee(e, t) {
+ return kr.toHalfFloat(Te(e, t));
+ }
+ function F(e) {
+ let t = (e & 31744) >> 10, n = e & 1023;
+ return (e >> 15 ? -1 : 1) * (t ? t === 31 ? n ? NaN : Infinity : 2 ** (t - 15) * (1 + n / 1024) : n / 1024 * 6103515625e-14);
+ }
+ function De(e, t) {
+ let n = e.getUint16(t.value, !0);
+ return t.value += 2, n;
+ }
+ function Oe(e, t) {
+ return F(De(e, t));
+ }
+ function ke(e, t, n, r) {
+ let i = n.value, a = [];
+ for (; n.value < i + r - 1;) {
+ let r = be(t, n), i = Ce(e, n), o = N(e, n);
+ n.value += 3;
+ let s = Ce(e, n), c = Ce(e, n);
+ a.push({
+ name: r,
+ pixelType: i,
+ pLinear: o,
+ xSampling: s,
+ ySampling: c
+ });
+ }
+ return n.value += 1, a;
+ }
+ function Ae(e, t) {
+ return {
+ redX: Te(e, t),
+ redY: Te(e, t),
+ greenX: Te(e, t),
+ greenY: Te(e, t),
+ blueX: Te(e, t),
+ blueY: Te(e, t),
+ whiteX: Te(e, t),
+ whiteY: Te(e, t)
+ };
+ }
+ function je(e, t) {
+ return [
+ "NO_COMPRESSION",
+ "RLE_COMPRESSION",
+ "ZIPS_COMPRESSION",
+ "ZIP_COMPRESSION",
+ "PIZ_COMPRESSION",
+ "PXR24_COMPRESSION",
+ "B44_COMPRESSION",
+ "B44A_COMPRESSION",
+ "DWAA_COMPRESSION",
+ "DWAB_COMPRESSION"
+ ][N(e, t)];
+ }
+ function Me(e, t) {
+ return {
+ xMin: Ce(e, t),
+ yMin: Ce(e, t),
+ xMax: Ce(e, t),
+ yMax: Ce(e, t)
+ };
+ }
+ function Ne(e, t) {
+ return [
+ "INCREASING_Y",
+ "DECREASING_Y",
+ "RANDOM_Y"
+ ][N(e, t)];
+ }
+ function Pe(e, t) {
+ return ["ENVMAP_LATLONG", "ENVMAP_CUBE"][N(e, t)];
+ }
+ function Fe(e, t) {
+ let n = [
+ "ONE_LEVEL",
+ "MIPMAP_LEVELS",
+ "RIPMAP_LEVELS"
+ ], r = ["ROUND_DOWN", "ROUND_UP"], i = M(e, t), a = M(e, t), o = N(e, t);
+ return {
+ xSize: i,
+ ySize: a,
+ levelMode: n[o & 15],
+ roundingMode: r[o >> 4]
+ };
+ }
+ function Ie(e, t) {
+ return [Te(e, t), Te(e, t)];
+ }
+ function Le(e, t) {
+ return [
+ Te(e, t),
+ Te(e, t),
+ Te(e, t)
+ ];
+ }
+ function Re(e, t, n, r, i) {
+ if (r === "string" || r === "stringvector" || r === "iccProfile") return j(t, n, i);
+ if (r === "chlist") return ke(e, t, n, i);
+ if (r === "chromaticities") return Ae(e, n);
+ if (r === "compression") return je(e, n);
+ if (r === "box2i") return Me(e, n);
+ if (r === "envmap") return Pe(e, n);
+ if (r === "tiledesc") return Fe(e, n);
+ if (r === "lineOrder") return Ne(e, n);
+ if (r === "float") return Te(e, n);
+ if (r === "v2f") return Ie(e, n);
+ if (r === "v3f") return Le(e, n);
+ if (r === "int") return Ce(e, n);
+ if (r === "rational") return xe(e, n);
+ if (r === "timecode") return Se(e, n);
+ if (r === "preview") return n.value += i, "skipped";
+ n.value += i;
+ }
+ function ze(e, t) {
+ let n = Math.log2(e);
+ return t == "ROUND_DOWN" ? Math.floor(n) : Math.ceil(n);
+ }
+ function Be(e, t, n) {
+ let r = 0;
+ switch (e.levelMode) {
+ case "ONE_LEVEL":
+ r = 1;
+ break;
+ case "MIPMAP_LEVELS":
+ r = ze(Math.max(t, n), e.roundingMode) + 1;
+ break;
+ case "RIPMAP_LEVELS": throw Error("THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.");
+ }
+ return r;
+ }
+ function Ve(e, t, n, r) {
+ let i = Array(e);
+ for (let a = 0; a < e; a++) {
+ let e = 1 << a, o = t / e | 0;
+ r == "ROUND_UP" && o * e < t && (o += 1), i[a] = (Math.max(o, 1) + n - 1) / n | 0;
+ }
+ return i;
+ }
+ function He() {
+ let e = this, t = e.offset, n = { value: 0 };
+ for (let r = 0; r < e.tileCount; r++) {
+ let r = Ce(e.viewer, t), i = Ce(e.viewer, t);
+ t.value += 8, e.size = M(e.viewer, t);
+ let a = r * e.blockWidth, o = i * e.blockHeight;
+ e.columns = a + e.blockWidth > e.width ? e.width - a : e.blockWidth, e.lines = o + e.blockHeight > e.height ? e.height - o : e.blockHeight;
+ let s = e.columns * e.totalBytes, c = e.size < e.lines * s ? e.uncompress(e) : me(e);
+ t.value += e.size;
+ for (let t = 0; t < e.lines; t++) {
+ let r = t * e.columns * e.totalBytes;
+ for (let i = 0; i < e.inputChannels.length; i++) {
+ let s = Xe.channels[i].name, l = e.channelByteOffsets[s] * e.columns, u = e.decodeChannels[s];
+ if (u === void 0) continue;
+ n.value = r + l;
+ let d = (e.height - (1 + o + t)) * e.outLineWidth;
+ for (let t = 0; t < e.columns; t++) {
+ let r = d + (t + a) * e.outputChannels + u;
+ e.byteArray[r] = e.getter(c, n);
+ }
+ }
+ }
+ }
+ }
+ function Ue() {
+ let e = this, t = e.offset, n = { value: 0 };
+ for (let r = 0; r < e.height / e.blockHeight; r++) {
+ let i = Ce(e.viewer, t) - Xe.dataWindow.yMin;
+ e.size = M(e.viewer, t), e.lines = i + e.blockHeight > e.height ? e.height - i : e.blockHeight;
+ let a = e.columns * e.totalBytes, o = e.size < e.lines * a ? e.uncompress(e) : me(e);
+ t.value += e.size;
+ for (let t = 0; t < e.blockHeight; t++) {
+ let i = r * e.blockHeight, s = t + e.scanOrder(i);
+ if (s >= e.height) continue;
+ let c = t * a, l = (e.height - 1 - s) * e.outLineWidth;
+ for (let t = 0; t < e.inputChannels.length; t++) {
+ let r = Xe.channels[t].name, i = e.channelByteOffsets[r] * e.columns, a = e.decodeChannels[r];
+ if (a !== void 0) {
+ n.value = c + i;
+ for (let t = 0; t < e.columns; t++) {
+ let r = l + t * e.outputChannels + a;
+ e.byteArray[r] = e.getter(o, n);
+ }
+ }
+ }
+ }
+ }
+ }
+ function We(e, t, n) {
+ let r = {};
+ if (e.getUint32(0, !0) != 20000630) throw Error("THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.");
+ r.version = e.getUint8(4);
+ let i = e.getUint8(5);
+ r.spec = {
+ singleTile: !!(i & 2),
+ longName: !!(i & 4),
+ deepFormat: !!(i & 8),
+ multiPart: !!(i & 16)
+ }, n.value = 8;
+ let a = !0;
+ for (; a;) {
+ let i = be(t, n);
+ if (i === "") a = !1;
+ else {
+ let a = be(t, n), o = Re(e, t, n, a, M(e, n));
+ o === void 0 ? console.warn(`THREE.EXRLoader: Skipped unknown header attribute type \'${a}\'.`) : r[i] = o;
+ }
+ }
+ if (i & -7) throw console.error("THREE.EXRHeader:", r), Error("THREE.EXRLoader: Provided file is currently unsupported.");
+ return r;
+ }
+ function Ge(e, t, n, r, i) {
+ let a = {
+ size: 0,
+ viewer: t,
+ array: n,
+ offset: r,
+ width: e.dataWindow.xMax - e.dataWindow.xMin + 1,
+ height: e.dataWindow.yMax - e.dataWindow.yMin + 1,
+ inputChannels: e.channels,
+ channelByteOffsets: {},
+ scanOrder: null,
+ totalBytes: null,
+ columns: null,
+ lines: null,
+ type: null,
+ uncompress: null,
+ getter: null,
+ format: null,
+ colorSpace: Ke
+ };
+ switch (e.compression) {
+ case "NO_COMPRESSION":
+ a.blockHeight = 1, a.uncompress = me;
+ break;
+ case "RLE_COMPRESSION":
+ a.blockHeight = 1, a.uncompress = he;
+ break;
+ case "ZIPS_COMPRESSION":
+ a.blockHeight = 1, a.uncompress = ge;
+ break;
+ case "ZIP_COMPRESSION":
+ a.blockHeight = 16, a.uncompress = ge;
+ break;
+ case "PIZ_COMPRESSION":
+ a.blockHeight = 32, a.uncompress = _e;
+ break;
+ case "PXR24_COMPRESSION":
+ a.blockHeight = 16, a.uncompress = ve;
+ break;
+ case "DWAA_COMPRESSION":
+ a.blockHeight = 32, a.uncompress = ye;
+ break;
+ case "DWAB_COMPRESSION":
+ a.blockHeight = 256, a.uncompress = ye;
+ break;
+ default: throw Error("EXRLoader.parse: " + e.compression + " is unsupported");
+ }
+ let o = {};
+ for (let t of e.channels) switch (t.name) {
+ case "Y":
+ case "R":
+ case "G":
+ case "B":
+ case "A": o[t.name] = !0, a.type = t.pixelType;
+ }
+ let s = !1;
+ if (o.R && o.G && o.B) s = !o.A, a.outputChannels = 4, a.decodeChannels = {
+ R: 0,
+ G: 1,
+ B: 2,
+ A: 3
+ };
+ else if (o.Y) a.outputChannels = 1, a.decodeChannels = { Y: 0 };
+ else throw Error("EXRLoader.parse: file contains unsupported data channels.");
+ if (a.type == 1) switch (i) {
+ case b:
+ a.getter = Oe;
+ break;
+ case x:
+ a.getter = De;
+ break;
+ }
+ else if (a.type == 2) switch (i) {
+ case b:
+ a.getter = Te;
+ break;
+ case x: a.getter = Ee;
+ }
+ else throw Error("EXRLoader.parse: unsupported pixelType " + a.type + " for " + e.compression + ".");
+ a.columns = a.width;
+ let c = a.width * a.height * a.outputChannels;
+ switch (i) {
+ case b:
+ a.byteArray = new Float32Array(c), s && a.byteArray.fill(1, 0, c);
+ break;
+ case x:
+ a.byteArray = new Uint16Array(c), s && a.byteArray.fill(15360, 0, c);
+ break;
+ default:
+ console.error("THREE.EXRLoader: unsupported type: ", i);
+ break;
+ }
+ let l = 0;
+ for (let t of e.channels) a.decodeChannels[t.name] !== void 0 && (a.channelByteOffsets[t.name] = l), l += t.pixelType * 2;
+ if (a.totalBytes = l, a.outLineWidth = a.width * a.outputChannels, e.lineOrder === "INCREASING_Y" ? a.scanOrder = (e) => e : a.scanOrder = (e) => a.height - 1 - e, a.outputChannels == 4 ? (a.format = O, a.colorSpace = Ke) : (a.format = A, a.colorSpace = ""), e.spec.singleTile) {
+ a.blockHeight = e.tiles.ySize, a.blockWidth = e.tiles.xSize;
+ let n = Be(e.tiles, a.width, a.height), i = Ve(n, a.width, e.tiles.xSize, e.tiles.roundingMode), o = Ve(n, a.height, e.tiles.ySize, e.tiles.roundingMode);
+ a.tileCount = i[0] * o[0];
+ for (let e = 0; e < n; e++) for (let n = 0; n < o[e]; n++) for (let n = 0; n < i[e]; n++) P(t, r);
+ a.decode = He.bind(a);
+ } else {
+ a.blockWidth = a.width;
+ let e = Math.ceil(a.height / a.blockHeight);
+ for (let n = 0; n < e; n++) P(t, r);
+ a.decode = Ue.bind(a);
+ }
+ return a;
+ }
+ let qe = { value: 0 }, Je = new DataView(e), Ye = new Uint8Array(e), Xe = We(Je, e, qe), Ze = Ge(Xe, Je, Ye, qe, this.type);
+ return Ze.decode(), {
+ header: Xe,
+ width: Ze.width,
+ height: Ze.height,
+ data: Ze.byteArray,
+ format: Ze.format,
+ colorSpace: Ze.colorSpace,
+ type: this.type
+ };
+ }
+ setDataType(e) {
+ return this.type = e, this;
+ }
+ load(e, t, n, r) {
+ function i(e, n) {
+ e.colorSpace = n.colorSpace, e.minFilter = d, e.magFilter = d, e.generateMipmaps = !1, e.flipY = !1, t && t(e, n);
+ }
+ return super.load(e, i, n, r);
+ }
+};
+//#endregion
+//#region src/viewer/environment.js
+function B_(e, t) {
+ let { id: n, path: r } = t;
+ return n === "neutral" ? Promise.resolve({ envMap: e.neutralEnvironment }) : n === "" ? Promise.resolve({ envMap: null }) : new Promise((t, n) => {
+ new z_().load(r, (n) => {
+ let r = e.pmremGenerator.fromEquirectangular(n).texture;
+ n.dispose(), e._loadedEnvironment && e._loadedEnvironment !== r && e._loadedEnvironment.dispose(), e._loadedEnvironment = r, t({ envMap: r });
+ }, void 0, n);
+ });
+}
+//#endregion
+//#region src/viewer/screenshot.js
+function V_(e) {
+ e.renderer.render(e.scene, e.activeCamera), e.renderer.domElement.toBlob((e) => {
+ if (!e) return;
+ let t = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19), n = URL.createObjectURL(e), r = document.createElement("a");
+ r.download = `3d-screenshot-${t}.png`, r.href = n, r.click(), URL.revokeObjectURL(n);
+ }, "image/png"), H_(e);
+}
+function H_(e) {
+ let t = document.createElement("div");
+ t.className = "screenshot-flash", e.el.appendChild(t), t.addEventListener("animationend", () => t.remove());
+}
+//#endregion
+//#region src/viewer/animation.js
+function U_(e, t) {
+ e.mixer &&= (e.mixer.stopAllAction(), e.mixer.uncacheRoot(e.mixer.getRoot()), null), e.clips = t, t.length && (e.mixer = new Xo(e.content));
+}
+function W_(e) {
+ e.clips.forEach((t) => {
+ e.mixer.clipAction(t).reset().play(), e.state.actionStates[t.name] = !0;
+ }), e.invalidate();
+}
+//#endregion
+//#region src/animation-manager.js
+var G_ = .35, K_ = class {
+ constructor() {
+ this.model = null, this.mixer = null, this.clips = /* @__PURE__ */ new Map(), this.actions = /* @__PURE__ */ new Map(), this.currentName = null, this.currentAction = null, this.loader = new fu(), this.onChange = null, this._animationDefs = [];
+ }
+ attach(e) {
+ this.detach(), this.model = e, this.mixer = new Xo(e), this.actions.clear(), this.currentAction = null, this.currentName = null;
+ for (let [e, t] of this.clips) {
+ let n = this._retargetClip(t, e), r = this.mixer.clipAction(n);
+ r.enabled = !0, this.actions.set(e, r);
+ }
+ }
+ detach() {
+ this.mixer &&= (this.mixer.stopAllAction(), this.mixer.uncacheRoot(this.mixer.getRoot()), null), this.model = null, this.actions.clear(), this.currentAction = null, this.currentName = null;
+ }
+ setAnimationDefs(e) {
+ this._animationDefs = e;
+ }
+ getAnimationDefs() {
+ return this._animationDefs;
+ }
+ async loadAnimation(e, t, n = {}) {
+ if (this.clips.has(e)) return this.clips.get(e);
+ let r = (await new Promise((e, n) => {
+ this.loader.load(t, e, void 0, n);
+ })).animations[0];
+ if (!r) throw Error(`No animation found in ${t}`);
+ if (r.name = e, this.clips.set(e, r), this.model && this.mixer) {
+ let t = this._retargetClip(r, e), i = this.mixer.clipAction(t);
+ i.enabled = !0, i.setLoop(n.loop === !1 ? Me : Ne), n.loop === !1 && (i.clampWhenFinished = !0), this.actions.set(e, i);
+ }
+ return r;
+ }
+ async loadAll() {
+ let e = this._animationDefs.map(async (e) => {
+ try {
+ await this.loadAnimation(e.name, e.url, { loop: e.loop !== !1 });
+ } catch (t) {
+ console.warn(`[AnimationManager] Failed to load "${e.name}" from ${e.url}:`, t);
+ }
+ });
+ await Promise.all(e);
+ }
+ play(e) {
+ let t = this.actions.get(e);
+ if (!t) {
+ console.warn(`[AnimationManager] Animation "${e}" not loaded`);
+ return;
+ }
+ this.currentAction && this.currentAction !== t && this.currentAction.fadeOut(.01), t.reset().fadeIn(.01).play(), this.currentAction = t, this.currentName = e, this.onChange && this.onChange(e);
+ }
+ crossfadeTo(e, t = G_) {
+ if (e === this.currentName) return;
+ let n = this.actions.get(e);
+ if (!n) {
+ console.warn(`[AnimationManager] Animation "${e}" not loaded`);
+ return;
+ }
+ n.reset(), n.play(), this.currentAction ? this.currentAction.crossFadeTo(n, t, !0) : n.fadeIn(t), this.currentAction = n, this.currentName = e, this.onChange && this.onChange(e);
+ }
+ stopAll() {
+ this.mixer && this.mixer.stopAllAction(), this.currentAction = null, this.currentName = null, this.onChange && this.onChange(null);
+ }
+ update(e) {
+ this.mixer && this.mixer.update(e);
+ }
+ _retargetClip(e, t) {
+ if (!this.model) return e;
+ let n = /* @__PURE__ */ new Set();
+ if (this.model.traverse((e) => {
+ e.isBone && n.add(e.name);
+ }), n.size === 0) return e;
+ let r = /* @__PURE__ */ new Set();
+ for (let t of e.tracks) {
+ let e = t.name.split(".")[0];
+ r.add(e);
+ }
+ let i = 0;
+ for (let e of r) n.has(e) && i++;
+ if (i / r.size > .5) return e;
+ let a = this._buildBoneNameMap(n, r);
+ return a ? (e.tracks.map((e) => {
+ let t = e.name.split("."), n = t[0], r = t.slice(1).join("."), i = a.get(n);
+ if (!i) return null;
+ let o = e.clone();
+ return o.name = `${i}.${r}`, o;
+ }).filter(Boolean), e.clone().resetDuration()) : e;
+ }
+ _buildBoneNameMap(e, t) {
+ let n = /* @__PURE__ */ new Map(), r = [...e], i = [...t], a = (e) => e.replace(/^mixamorig\d*[_:]?/i, "").replace(/^Armature[_/]?/i, ""), o = new Map(r.map((e) => [a(e), e])), s = 0;
+ for (let e of i) {
+ let t = a(e);
+ o.has(t) && (n.set(e, o.get(t)), s++);
+ }
+ if (s / i.length > .5) return n;
+ let c = new Map(r.map((e) => [e.toLowerCase(), e]));
+ n.clear(), s = 0;
+ for (let e of i) c.has(e.toLowerCase()) && (n.set(e, c.get(e.toLowerCase())), s++);
+ return s / i.length > .5 ? n : null;
+ }
+ getLoadedNames() {
+ return [...this.clips.keys()];
+ }
+ isLoaded(e) {
+ return this.clips.has(e);
+ }
+ dispose() {
+ this.detach(), this.clips.clear(), this._animationDefs = [];
+ }
+};
+//#endregion
+//#region src/viewer.js
+io.enabled = !0;
+var q_ = class {
+ constructor(e, t) {
+ this.el = e, this.options = t, this.lights = [], this.content = null, this.mixer = null, this.clips = [], this.gui = null, this.animationManager = new K_(), this._animPanelEl = null, this.state = {
+ environment: t.preset === $g.ASSET_GENERATOR ? np.find((e) => e.id === "footprint-court").name : np[1].name,
+ background: !1,
+ playbackSpeed: 1,
+ actionStates: {},
+ camera: Qg,
+ wireframe: !1,
+ skeleton: !1,
+ grid: !1,
+ autoRotate: !1,
+ punctualLights: !0,
+ exposure: 0,
+ toneMapping: 1,
+ ambientIntensity: .3,
+ ambientColor: "#FFFFFF",
+ directIntensity: .8 * Math.PI,
+ directColor: "#FFFFFF",
+ bgColor: "#000000",
+ transparentBg: !1,
+ pointSize: 1,
+ showInfo: !0,
+ showLabels: !1
+ }, this.prevTime = 0, this.stats = new uu(), this.stats.dom.height = "48px", [].forEach.call(this.stats.dom.children, (e) => e.style.display = ""), this.backgroundColor = new B(this.state.bgColor), this.scene = new Di(), this.scene.background = this.backgroundColor, this.defaultCamera = new vi(t.preset === $g.ASSET_GENERATOR ? .8 * 180 / Math.PI : 60, e.clientWidth / e.clientHeight, .01, 1e3), this.activeCamera = this.defaultCamera, this.scene.add(this.defaultCamera), this.renderer = window.renderer = new lu({
+ antialias: !0,
+ alpha: !0
+ }), this.renderer.setClearColor(0, 1), this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)), this.renderer.setSize(e.clientWidth, e.clientHeight), this.pmremGenerator = new Ns(this.renderer), this.pmremGenerator.compileEquirectangularShader(), this.neutralEnvironment = this.pmremGenerator.fromScene(new Fd()).texture, this.controls = new Sd(this.defaultCamera, this.renderer.domElement), this.controls.screenSpacePanning = !0, this._onControlsChange = () => this.invalidate(), this.controls.addEventListener("change", this._onControlsChange), this.el.appendChild(this.renderer.domElement), this.cameraCtrl = null, this.cameraFolder = null, this.animFolder = null, this.animCtrls = [], this.morphFolder = null, this.morphCtrls = [], this.skeletonHelpers = [], this.gridHelper = null, this.axesHelper = null, this.modelInfo = null, this.annotationEls = [], this._tempVec = new R(), this.addAxesHelper(), this.addGUI(), t.kiosk && this.gui.close(), this.animate = this.animate.bind(this), this._rafId = null, this._visible = !0, this._tabVisible = !document.hidden, this._disposed = !1, this._loadedEnvironment = null, this._guiWrap = null, this._needsRender = !0, this._animating = !1, this._onVisibilityChange = () => {
+ let e = !this._tabVisible;
+ this._tabVisible = !document.hidden, e && this._tabVisible && (this._needsRender = !0), this._updateRenderLoop();
+ }, document.addEventListener("visibilitychange", this._onVisibilityChange), typeof IntersectionObserver < "u" && (this._intersectionObserver = new IntersectionObserver((e) => {
+ let t = !this._visible;
+ this._visible = e[e.length - 1].isIntersecting, t && this._visible && (this._needsRender = !0), this._updateRenderLoop();
+ }, { threshold: 0 }), this._intersectionObserver.observe(this.el)), this._onResize = this.resize.bind(this), this._onKeyDown = (e) => {
+ (e.key === "p" || e.key === "P") && !this.isInputFocused() && this.takeScreenshot();
+ }, this._updateRenderLoop(), window.addEventListener("resize", this._onResize, !1), window.addEventListener("keydown", this._onKeyDown);
+ }
+ invalidate() {
+ this._disposed || (this._needsRender = !0, this._updateRenderLoop());
+ }
+ _recomputeAnimating() {
+ let e = !1;
+ if (this.state && this.state.autoRotate && (e = !0), !e && this.mixer && this.state) {
+ for (let t in this.state.actionStates) if (this.state.actionStates[t]) {
+ e = !0;
+ break;
+ }
+ }
+ !e && this.animationManager.currentAction && (e = !0), this._animating = e;
+ }
+ _updateRenderLoop() {
+ if (this._disposed) return;
+ let e = this._visible && this._tabVisible;
+ e && (this._needsRender || this._animating) && this._rafId === null ? (this.prevTime = performance.now(), this._rafId = requestAnimationFrame(this.animate)) : !e && this._rafId !== null && (cancelAnimationFrame(this._rafId), this._rafId = null);
+ }
+ animate(e) {
+ let t = (e - this.prevTime) / 1e3;
+ if (this.prevTime = e, this._recomputeAnimating(), this.controls.update(), this.stats.update(), this.mixer && this.mixer.update(t), this.animationManager.update(t), this._afterAnimateHooks) for (let e = 0; e < this._afterAnimateHooks.length; e++) this._afterAnimateHooks[e](t);
+ this.render(), this._needsRender = !1, this._animating && this._visible && this._tabVisible && !this._disposed ? this._rafId = requestAnimationFrame(this.animate) : this._rafId = null;
+ }
+ isInputFocused() {
+ let e = document.activeElement;
+ return e && (e.tagName === "INPUT" || e.tagName === "TEXTAREA" || e.isContentEditable);
+ }
+ render() {
+ this.renderer.render(this.scene, this.activeCamera), this.state.grid && (this.axesCamera.position.copy(this.defaultCamera.position), this.axesCamera.lookAt(this.axesScene.position), this.axesRenderer.render(this.axesScene, this.axesCamera)), this.projectAnnotations();
+ }
+ takeScreenshot() {
+ V_(this);
+ }
+ resize() {
+ let { clientHeight: e, clientWidth: t } = this.el;
+ this.defaultCamera.aspect = t / e, this.defaultCamera.updateProjectionMatrix(), this.renderer.setSize(t, e), this.axesCamera.aspect = this.axesDiv.clientWidth / this.axesDiv.clientHeight, this.axesCamera.updateProjectionMatrix(), this.axesRenderer.setSize(this.axesDiv.clientWidth, this.axesDiv.clientHeight), this.invalidate();
+ }
+ load(e, t, n) {
+ let r = Mo.extractUrlBase(e);
+ return new Promise((i, a) => {
+ e_.setURLModifier((e, i) => {
+ let a = t + decodeURI(e).replace(r, "").replace(/^(\.?\/)/, "");
+ if (n.has(a)) {
+ let e = n.get(a), t = URL.createObjectURL(e);
+ return s.push(t), t;
+ }
+ return (i || "") + e;
+ });
+ let o = new fu(e_).setCrossOrigin("anonymous").setDRACOLoader(n_).setKTX2Loader(r_.detectSupport(this.renderer)).setMeshoptDecoder(dd), s = [];
+ o.load(e, (e) => {
+ window.VIEWER.json = e;
+ let t = e.scene || e.scenes[0], n = e.animations || [];
+ if (!t) throw Error("This model contains no scene, and cannot be viewed here. However, it may contain individual 3D resources.");
+ this.setContent(t, n), s.forEach(URL.revokeObjectURL), i(e);
+ }, void 0, a);
+ });
+ }
+ setContent(e, t) {
+ this.clear(), e.updateMatrixWorld();
+ let n = new nn().setFromObject(e), r = n.getSize(new R()).length(), i = n.getCenter(new R());
+ this.controls.reset(), e.position.x -= i.x, e.position.y -= i.y, e.position.z -= i.z, this.controls.maxDistance = r * 10, this.defaultCamera.near = r / 100, this.defaultCamera.far = r * 100, this.defaultCamera.updateProjectionMatrix(), this.options.cameraPosition ? (this.defaultCamera.position.fromArray(this.options.cameraPosition), this.defaultCamera.lookAt(new R())) : (this.defaultCamera.position.copy(i), this.defaultCamera.position.x += r / 2, this.defaultCamera.position.y += r / 5, this.defaultCamera.position.z += r / 2, this.defaultCamera.lookAt(i)), this.setCamera(Qg), this.axesCamera.position.copy(this.defaultCamera.position), this.axesCamera.lookAt(this.axesScene.position), this.axesCamera.near = r / 100, this.axesCamera.far = r * 100, this.axesCamera.updateProjectionMatrix(), this.axesCorner.scale.set(r, r, r), this.controls.saveState(), this.scene.add(e), this.content = e, this.state.punctualLights = !0, this.content.traverse((e) => {
+ e.isLight && (this.state.punctualLights = !1);
+ }), this.setClips(t), this.animationManager.attach(this.content), this._setupAnimationPanel(), this.updateLights(), this.updateGUI(), this.updateEnvironment(), this.updateDisplay(), this.updateModelInfo(e, t), this.updateAnnotations(), window.VIEWER.scene = this.content, this.printGraph(this.content), this.invalidate();
+ }
+ printGraph(e) {
+ console.group(" <" + e.type + "> " + e.name), e.children.forEach((e) => this.printGraph(e)), console.groupEnd();
+ }
+ setClips(e) {
+ U_(this, e);
+ }
+ playAllClips() {
+ W_(this);
+ }
+ setCamera(e) {
+ e === "[default]" ? (this.controls.enabled = !0, this.activeCamera = this.defaultCamera) : (this.controls.enabled = !1, this.content.traverse((t) => {
+ t.isCamera && t.name === e && (this.activeCamera = t);
+ })), this.invalidate();
+ }
+ updateLights() {
+ let e = this.state, t = this.lights;
+ e.punctualLights && !t.length ? a_(this) : !e.punctualLights && t.length && o_(this), this.renderer.toneMapping = Number(e.toneMapping), this.renderer.toneMappingExposure = 2 ** e.exposure, t.length === 2 && (t[0].intensity = e.ambientIntensity, t[0].color.set(e.ambientColor), t[1].intensity = e.directIntensity, t[1].color.set(e.directColor)), this.invalidate();
+ }
+ updateEnvironment() {
+ let e = np.filter((e) => e.name === this.state.environment)[0];
+ B_(this, e).then(({ envMap: e }) => {
+ this._disposed || !this.scene || (this.scene.environment = e, this.scene.background = this.state.transparentBg ? null : this.state.background ? e : this.backgroundColor, this.invalidate());
+ });
+ }
+ updateDisplay() {
+ this.skeletonHelpers.length && this.skeletonHelpers.forEach((e) => this.scene.remove(e)), i_(this.content, (e) => {
+ e.wireframe = this.state.wireframe, e instanceof Sa && (e.size = this.state.pointSize);
+ }), this.content.traverse((e) => {
+ if (e.geometry && e.skeleton && this.state.skeleton) {
+ let t = new ts(e.skeleton.bones[0].parent);
+ t.material.linewidth = 3, this.scene.add(t), this.skeletonHelpers.push(t);
+ }
+ }), this.state.grid !== !!this.gridHelper && (this.state.grid ? (this.gridHelper = new rs(), this.axesHelper = new is(), this.axesHelper.renderOrder = 999, this.axesHelper.onBeforeRender = (e) => e.clearDepth(), this.scene.add(this.gridHelper), this.scene.add(this.axesHelper)) : (this.scene.remove(this.gridHelper), this.scene.remove(this.axesHelper), this.gridHelper = null, this.axesHelper = null, this.axesRenderer.clear())), this.controls.autoRotate = this.state.autoRotate, this.invalidate();
+ }
+ updateBackground() {
+ this.backgroundColor.set(this.state.bgColor), this.state.transparentBg ? (this.scene.background = null, this.renderer.setClearColor(0, 0)) : (this.scene.background = this.backgroundColor, this.renderer.setClearColor(0, 1), this.updateEnvironment()), this.invalidate();
+ }
+ updateModelInfo(e, t) {
+ this.modelInfo &&= (this.modelInfo.remove(), null), this.state.showInfo && e && (this.modelInfo = fg(this.el, e, t));
+ }
+ updateAnnotations() {
+ this.annotationEls.forEach((e) => e.el.remove()), this.annotationEls = [], !(!this.state.showLabels || !this.content) && (xg(this.content).forEach((e) => {
+ let t = Sg(e), n = document.createElement("div");
+ n.classList.add("annotation-label"), n.appendChild(t), this.el.appendChild(n), this.annotationEls.push({
+ el: n,
+ position: e.position
+ });
+ }), this.invalidate());
+ }
+ projectAnnotations() {
+ if (this.annotationEls.length === 0) return;
+ let e = this.el.clientWidth, t = this.el.clientHeight, n = e / 2, r = t / 2, i = this._tempVec;
+ this.annotationEls.forEach(({ el: e, position: t }) => {
+ if (i.copy(t), i.project(this.activeCamera), i.z > 1) {
+ e.style.display = "none";
+ return;
+ }
+ let a = i.x * n + n, o = -(i.y * r) + r;
+ e.style.display = "", e.style.left = a + "px", e.style.top = o + "px";
+ });
+ }
+ addAxesHelper() {
+ this.axesDiv = document.createElement("div"), this.el.appendChild(this.axesDiv), this.axesDiv.classList.add("axes");
+ let { clientWidth: e, clientHeight: t } = this.axesDiv;
+ this.axesScene = new Di(), this.axesCamera = new vi(50, e / t, .1, 10), this.axesScene.add(this.axesCamera), this.axesRenderer = new lu({ alpha: !0 }), this.axesRenderer.setPixelRatio(window.devicePixelRatio), this.axesRenderer.setSize(this.axesDiv.clientWidth, this.axesDiv.clientHeight), this.axesCamera.up = this.defaultCamera.up, this.axesCorner = new is(5), this.axesScene.add(this.axesCorner), this.axesDiv.appendChild(this.axesRenderer.domElement);
+ }
+ addGUI() {
+ let e = window.innerWidth <= 700, t = this.gui = new tp({
+ autoPlace: !1,
+ width: e ? 220 : 260,
+ hideable: !0
+ }), n = t.addFolder("Display");
+ n.add(this.state, "background").onChange(() => this.updateEnvironment()), n.add(this.state, "autoRotate").onChange(() => this.updateDisplay()), n.add(this.state, "wireframe").onChange(() => this.updateDisplay()), n.add(this.state, "skeleton").onChange(() => this.updateDisplay()), n.add(this.state, "grid").onChange(() => this.updateDisplay()), n.add(this.controls, "screenSpacePanning"), n.add(this.state, "pointSize", 1, 16).onChange(() => this.updateDisplay()), n.add(this.state, "transparentBg").name("transparent bg").onChange(() => this.updateBackground()), n.addColor(this.state, "bgColor").onChange(() => this.updateBackground()), n.add({ screenshot: () => this.takeScreenshot() }, "screenshot").name("Screenshot [P]"), n.add(this.state, "showInfo").name("model info").onChange(() => this.updateModelInfo(this.content, this.clips)), n.add(this.state, "showLabels").name("mesh labels").onChange(() => this.updateAnnotations());
+ let r = t.addFolder("Lighting");
+ r.add(this.state, "environment", np.map((e) => e.name)).onChange(() => this.updateEnvironment()), [
+ r.add(this.state, "toneMapping", {
+ Linear: 1,
+ "ACES Filmic": 4
+ }),
+ r.add(this.state, "exposure", -10, 10, .01),
+ r.add(this.state, "punctualLights").listen(),
+ r.add(this.state, "ambientIntensity", 0, 2),
+ r.addColor(this.state, "ambientColor"),
+ r.add(this.state, "directIntensity", 0, 4),
+ r.addColor(this.state, "directColor")
+ ].forEach((e) => e.onChange(() => this.updateLights())), this.animFolder = t.addFolder("Animation"), this.animFolder.domElement.style.display = "none", this.animFolder.add(this.state, "playbackSpeed", 0, 1).onChange((e) => {
+ this.mixer && (this.mixer.timeScale = e);
+ }), this.animFolder.add({ playAll: () => this.playAllClips() }, "playAll"), this.morphFolder = t.addFolder("Morph Targets"), this.morphFolder.domElement.style.display = "none", this.cameraFolder = t.addFolder("Cameras"), this.cameraFolder.domElement.style.display = "none";
+ let i = t.addFolder("Performance"), a = document.createElement("li");
+ this.stats.dom.style.position = "static", a.appendChild(this.stats.dom), a.classList.add("gui-stats"), i.__ul.appendChild(a);
+ let o = document.createElement("div");
+ this.el.appendChild(o), o.classList.add("gui-wrap"), o.appendChild(t.domElement), this._guiWrap = o, e ? t.close() : t.open();
+ }
+ updateGUI() {
+ this.cameraFolder.domElement.style.display = "none", this.morphCtrls.forEach((e) => e.remove()), this.morphCtrls.length = 0, this.morphFolder.domElement.style.display = "none", this.animCtrls.forEach((e) => e.remove()), this.animCtrls.length = 0, this.animFolder.domElement.style.display = "none";
+ let e = [], t = [];
+ if (this.content.traverse((n) => {
+ n.geometry && n.morphTargetInfluences && t.push(n), n.isCamera && (n.name = n.name || `VIEWER__camera_${e.length + 1}`, e.push(n.name));
+ }), e.length) {
+ this.cameraFolder.domElement.style.display = "", this.cameraCtrl && this.cameraCtrl.remove();
+ let t = [Qg].concat(e);
+ this.cameraCtrl = this.cameraFolder.add(this.state, "camera", t), this.cameraCtrl.onChange((e) => this.setCamera(e));
+ }
+ if (t.length && (this.morphFolder.domElement.style.display = "", t.forEach((e) => {
+ if (e.morphTargetInfluences.length) {
+ let t = this.morphFolder.add({ name: e.name || "Untitled" }, "name");
+ this.morphCtrls.push(t);
+ }
+ for (let t = 0; t < e.morphTargetInfluences.length; t++) {
+ let n = this.morphFolder.add(e.morphTargetInfluences, t, 0, 1, .01).listen();
+ Object.keys(e.morphTargetDictionary).forEach((r) => {
+ r && e.morphTargetDictionary[r] === t && n.name(r);
+ }), this.morphCtrls.push(n);
+ }
+ })), this.clips.length) {
+ this.animFolder.domElement.style.display = "";
+ let e = this.state.actionStates = {};
+ this.clips.forEach((t, n) => {
+ t.name = `${n + 1}. ${t.name}`;
+ let r;
+ n === 0 ? (e[t.name] = !0, r = this.mixer.clipAction(t), r.play()) : e[t.name] = !1;
+ let i = this.animFolder.add(e, t.name).listen();
+ i.onChange((e) => {
+ r ||= this.mixer.clipAction(t), r.setEffectiveTimeScale(1), e ? r.play() : r.stop(), this.invalidate();
+ }), this.animCtrls.push(i);
+ });
+ }
+ }
+ setAnimationDefs(e) {
+ this.animationManager.setAnimationDefs(e), this.content && this._setupAnimationPanel();
+ }
+ _setupAnimationPanel() {
+ this._animPanelEl &&= (this._animPanelEl.remove(), null);
+ let e = this.animationManager.getAnimationDefs();
+ if (e.length === 0) return;
+ let t = !1;
+ if (this.content.traverse((e) => {
+ e.isSkinnedMesh && (t = !0);
+ }), !t) return;
+ let n = document.createElement("div");
+ n.className = "anim-panel", n.innerHTML = "<div class=\"anim-panel__header\"><span class=\"anim-panel__title\">Animations</span><button class=\"anim-panel__stop\" title=\"Stop all\">⏹</button></div><div class=\"anim-panel__grid\"></div>", this.el.appendChild(n), this._animPanelEl = n, this._renderAnimButtons(), this.animationManager.loadAll().then(() => {
+ if (this._renderAnimButtons(), !this.animationManager.currentName && e.length > 0) {
+ let t = e[0].name;
+ this.animationManager.isLoaded(t) && (this.animationManager.play(t), this._renderAnimButtons(), this.invalidate(), this._recomputeAnimating(), this._updateRenderLoop());
+ }
+ }), n.querySelector(".anim-panel__stop").addEventListener("click", () => {
+ this.animationManager.stopAll(), this._renderAnimButtons(), this.invalidate();
+ }), this.animationManager.onChange = () => {
+ this._renderAnimButtons();
+ };
+ }
+ _renderAnimButtons() {
+ if (!this._animPanelEl) return;
+ let e = this._animPanelEl.querySelector(".anim-panel__grid"), t = this.animationManager.getAnimationDefs(), n = this.animationManager.currentName, r = {
+ idle: "🧍",
+ breathing: "🧍",
+ standing: "🧍",
+ walking: "🚶",
+ walk: "🚶",
+ running: "🏃",
+ run: "🏃",
+ waving: "👋",
+ wave: "👋",
+ dancing: "💃",
+ dance: "💃",
+ sitting: "🪑",
+ sit: "🪑",
+ jumping: "🦘",
+ jump: "🦘",
+ talking: "🗣️",
+ talk: "🗣️",
+ clapping: "👏",
+ clap: "👏",
+ punching: "👊",
+ punch: "👊",
+ kicking: "🦵",
+ kick: "🦵"
+ };
+ e.innerHTML = t.map((e) => {
+ let t = this.animationManager.isLoaded(e.name), i = n === e.name, a = e.icon || r[e.name.toLowerCase()] || "▶", o = e.label || e.name.charAt(0).toUpperCase() + e.name.slice(1);
+ return "<button class=\"anim-btn" + (i ? " anim-btn--active" : "") + (t ? "" : " anim-btn--loading") + "\" data-anim=\"" + e.name + "\" title=\"" + o + "\"" + (t ? "" : " disabled") + "><span class=\"anim-btn__icon\">" + a + "</span><span class=\"anim-btn__label\">" + o + "</span></button>";
+ }).join(""), e.querySelectorAll(".anim-btn:not([disabled])").forEach((e) => {
+ e.addEventListener("click", () => {
+ let t = e.dataset.anim;
+ this.animationManager.crossfadeTo(t), this.invalidate(), this._recomputeAnimating(), this._updateRenderLoop();
+ });
+ });
+ }
+ clear() {
+ this.content && (this.animationManager.detach(), this._animPanelEl &&= (this._animPanelEl.remove(), null), this.modelInfo &&= (this.modelInfo.remove(), null), this.annotationEls.forEach((e) => e.el.remove()), this.annotationEls = [], this.scene.remove(this.content), this.content.traverse((e) => {
+ e.geometry && e.geometry.dispose();
+ }), i_(this.content, (e) => {
+ for (let t in e) t !== "envMap" && e[t] && e[t].isTexture && e[t].dispose();
+ }), this.content = null, this._disposed || this.invalidate());
+ }
+ dispose() {
+ if (!this._disposed) {
+ if (this._disposed = !0, this._rafId !== null && (cancelAnimationFrame(this._rafId), this._rafId = null), document.removeEventListener("visibilitychange", this._onVisibilityChange), window.removeEventListener("resize", this._onResize, !1), window.removeEventListener("keydown", this._onKeyDown), this._intersectionObserver &&= (this._intersectionObserver.disconnect(), null), this.clear(), this.mixer) {
+ this.mixer.stopAllAction();
+ let e = this.mixer.getRoot();
+ e && this.mixer.uncacheRoot(e), this.mixer = null;
+ }
+ this.clips = [], this.animationManager.dispose(), this._animPanelEl &&= (this._animPanelEl.remove(), null), this.skeletonHelpers.length && (this.skeletonHelpers.forEach((e) => {
+ this.scene.remove(e), e.dispose?.();
+ }), this.skeletonHelpers.length = 0), this.gridHelper &&= (this.scene.remove(this.gridHelper), this.gridHelper.geometry?.dispose(), this.gridHelper.material?.dispose(), null), this.axesHelper &&= (this.scene.remove(this.axesHelper), this.axesHelper.geometry?.dispose(), this.axesHelper.material?.dispose(), null), this.axesCorner &&= (this.axesScene?.remove(this.axesCorner), this.axesCorner.geometry?.dispose(), this.axesCorner.material?.dispose(), null), this.lights.forEach((e) => e.parent?.remove(e)), this.lights = [], this.annotationEls.length && (this.annotationEls.forEach((e) => e.el.remove()), this.annotationEls = []), this.modelInfo &&= (this.modelInfo.remove(), null), this.gui &&= (this.gui.destroy(), null), this._guiWrap &&= (this._guiWrap.remove(), null), this.stats?.dom && this.stats.dom.remove(), this.controls?.dispose(), this.controls = null, this._loadedEnvironment &&= (this._loadedEnvironment.dispose(), null), this.neutralEnvironment &&= (this.neutralEnvironment.dispose(), null), this.scene && (this.scene.environment = null, this.scene.background = null), this.pmremGenerator &&= (this.pmremGenerator.dispose(), null), this.axesRenderer &&= (this.axesRenderer.dispose(), this.axesRenderer.forceContextLoss?.(), this.axesRenderer.domElement?.remove(), null), this.axesDiv &&= (this.axesDiv.remove(), null), this.axesScene = null, this.axesCamera = null, this.renderer &&= (this.renderer.dispose(), this.renderer.forceContextLoss?.(), this.renderer.domElement?.remove(), window.renderer === this.renderer && (window.renderer = null), null), this.scene = null, this.content = null, this.activeCamera = null, this.defaultCamera = null, this._afterAnimateHooks = null;
+ }
+ }
+}, J_ = class {
+ constructor({ model: e = "claude-opus-4-6", proxyURL: t, apiKey: n, temperature: r = .7, maxTokens: i = 4096, thinking: a = "auto" } = {}) {
+ this.model = e, this.proxyURL = t, this.apiKey = n, this.temperature = r, this.maxTokens = i, this.thinking = a;
+ }
+ async complete({ system: e, messages: t, tools: n }) {
+ let r = {
+ model: this.model,
+ max_tokens: this.maxTokens,
+ temperature: this.temperature,
+ system: e,
+ messages: t
+ };
+ n && n.length && (r.tools = n), this.thinking === "always" && (r.thinking = {
+ type: "enabled",
+ budget_tokens: 2048
+ });
+ let i = this.proxyURL || "https://api.anthropic.com/v1/messages", a = { "content-type": "application/json" };
+ this.apiKey && (a["x-api-key"] = this.apiKey, a["anthropic-version"] = "2023-06-01", a["anthropic-dangerous-direct-browser-access"] = "true");
+ let o = await fetch(i, {
+ method: "POST",
+ headers: a,
+ body: JSON.stringify(r)
+ });
+ if (!o.ok) {
+ let e = await o.text();
+ throw Error(`Anthropic ${o.status}: ${e}`);
+ }
+ let s = await o.json();
+ return this._normalize(s);
+ }
+ _normalize(e) {
+ let t = {
+ text: "",
+ toolCalls: [],
+ thinking: "",
+ stopReason: e.stop_reason
+ };
+ for (let n of e.content || []) n.type === "text" ? t.text += n.text : n.type === "thinking" ? t.thinking += n.thinking || "" : n.type === "tool_use" && t.toolCalls.push({
+ id: n.id,
+ name: n.name,
+ input: n.input
+ });
+ return t;
+ }
+ formatToolResults(e) {
+ return {
+ role: "user",
+ content: e.map((e) => ({
+ type: "tool_result",
+ tool_use_id: e.id,
+ content: typeof e.output == "string" ? e.output : JSON.stringify(e.output),
+ is_error: !!e.isError
+ }))
+ };
+ }
+ formatAssistantWithToolCalls(e, t) {
+ let n = [];
+ e && n.push({
+ type: "text",
+ text: e
+ });
+ for (let e of t) n.push({
+ type: "tool_use",
+ id: e.id,
+ name: e.name,
+ input: e.input
+ });
+ return {
+ role: "assistant",
+ content: n
+ };
+ }
+}, Y_ = class {
+ async complete() {
+ return {
+ text: "",
+ toolCalls: [],
+ stopReason: "end_turn"
+ };
+ }
+ formatToolResults() {
+ return {
+ role: "user",
+ content: []
+ };
+ }
+ formatAssistantWithToolCalls(e) {
+ return {
+ role: "assistant",
+ content: e || ""
+ };
+ }
+};
+function X_(e = {}) {
+ let t = e.provider || "anthropic";
+ if (t === "anthropic") return new J_(e);
+ if (t === "none") return new Y_();
+ throw Error(`Unsupported provider: ${t}. Supported: anthropic, none`);
+}
+//#endregion
+//#region src/runtime/speech.js
+var Z_ = class {
+ constructor({ voiceId: e = "default", rate: t = 1, pitch: n = 1, lang: r = "en-US" } = {}) {
+ this.voiceId = e, this.rate = t, this.pitch = n, this.lang = r, this._queue = [], this._speaking = !1;
+ }
+ async speak(e, { onStart: t, onEnd: n } = {}) {
+ if ("speechSynthesis" in window) return new Promise((r) => {
+ let i = new SpeechSynthesisUtterance(e);
+ i.rate = this.rate, i.pitch = this.pitch, i.lang = this.lang;
+ let a = this._pickVoice();
+ a && (i.voice = a), i.onstart = () => {
+ this._speaking = !0, t?.();
+ }, i.onend = () => {
+ this._speaking = !1, n?.(), r();
+ }, i.onerror = () => {
+ this._speaking = !1, r();
+ }, window.speechSynthesis.speak(i);
+ });
+ }
+ cancel() {
+ "speechSynthesis" in window && window.speechSynthesis.cancel(), this._speaking = !1;
+ }
+ get speaking() {
+ return this._speaking;
+ }
+ _pickVoice() {
+ if (!("speechSynthesis" in window)) return null;
+ let e = window.speechSynthesis.getVoices();
+ if (this.voiceId && this.voiceId !== "default") {
+ let t = e.find((e) => e.name === this.voiceId || e.voiceURI === this.voiceId);
+ if (t) return t;
+ }
+ return e.find((e) => e.lang?.startsWith(this.lang.slice(0, 2))) || null;
+ }
+}, Q_ = class {
+ constructor({ language: e = "en-US", continuous: t = !1, interimResults: n = !0 } = {}) {
+ this.language = e, this.continuous = t, this.interimResults = n, this._recognition = null, this._listening = !1;
+ }
+ _ensure() {
+ if (this._recognition) return this._recognition;
+ let e = window.SpeechRecognition || window.webkitSpeechRecognition;
+ if (!e) return null;
+ let t = new e();
+ return t.lang = this.language, t.continuous = this.continuous, t.interimResults = this.interimResults, this._recognition = t, t;
+ }
+ async listen({ onInterim: e, onFinal: t } = {}) {
+ let n = this._ensure();
+ if (!n) throw Error("SpeechRecognition unavailable in this browser");
+ return new Promise((r, i) => {
+ let a = "";
+ n.onresult = (n) => {
+ for (let r = n.resultIndex; r < n.results.length; r++) {
+ let i = n.results[r], o = i[0].transcript;
+ i.isFinal ? (a += o, t?.(o)) : e?.(o);
+ }
+ }, n.onerror = (e) => {
+ this._listening = !1, i(e.error);
+ }, n.onend = () => {
+ this._listening = !1, r(a.trim());
+ }, this._listening = !0;
+ try {
+ n.start();
+ } catch (e) {
+ this._listening = !1, i(e);
+ }
+ });
+ }
+ stop() {
+ this._recognition && this._listening && this._recognition.stop();
+ }
+ get listening() {
+ return this._listening;
+ }
+};
+function $_(e = {}) {
+ let t = e.provider || "browser";
+ if (t === "none") return null;
+ if (t === "browser") return new Z_(e);
+ throw Error(`TTS provider "${t}" not implemented yet`);
+}
+function ev(e = {}) {
+ let t = e.provider || "browser";
+ if (t === "none") return null;
+ if (t === "browser") return new Q_(e);
+ throw Error(`STT provider "${t}" not implemented yet`);
+}
+//#endregion
+//#region src/runtime/tools.js
+var tv = [
+ {
+ name: "wave",
+ description: "Wave at the user. Use for greetings, farewells, or acknowledgments.",
+ input_schema: {
+ type: "object",
+ properties: { duration_ms: {
+ type: "integer",
+ minimum: 500,
+ maximum: 5e3,
+ default: 1500
+ } }
+ }
+ },
+ {
+ name: "lookAt",
+ description: "Direct the agent's gaze toward a target.",
+ input_schema: {
+ type: "object",
+ properties: { target: {
+ type: "string",
+ enum: [
+ "user",
+ "camera",
+ "center"
+ ],
+ description: "Where to look"
+ } },
+ required: ["target"]
+ }
+ },
+ {
+ name: "play_clip",
+ description: "Play a named animation clip from the loaded body.",
+ input_schema: {
+ type: "object",
+ properties: {
+ name: { type: "string" },
+ loop: {
+ type: "boolean",
+ default: !1
+ },
+ fade_ms: {
+ type: "integer",
+ default: 200
+ }
+ },
+ required: ["name"]
+ }
+ },
+ {
+ name: "setExpression",
+ description: "Set facial expression via morph target preset.",
+ input_schema: {
+ type: "object",
+ properties: {
+ preset: {
+ type: "string",
+ enum: [
+ "neutral",
+ "happy",
+ "sad",
+ "surprised",
+ "confused",
+ "focused"
+ ]
+ },
+ intensity: {
+ type: "number",
+ minimum: 0,
+ maximum: 1,
+ default: 1
+ }
+ },
+ required: ["preset"]
+ }
+ },
+ {
+ name: "speak",
+ description: "Say something out loud via TTS. Use this instead of plain text when voice is on.",
+ input_schema: {
+ type: "object",
+ properties: { text: { type: "string" } },
+ required: ["text"]
+ }
+ },
+ {
+ name: "remember",
+ description: "Save a durable memory about the user, a feedback rule, a project fact, or a reference.",
+ input_schema: {
+ type: "object",
+ properties: {
+ key: {
+ type: "string",
+ description: "short snake_case filename, e.g. \"user_role\""
+ },
+ name: { type: "string" },
+ description: { type: "string" },
+ type: {
+ type: "string",
+ enum: [
+ "user",
+ "feedback",
+ "project",
+ "reference"
+ ]
+ },
+ body: { type: "string" }
+ },
+ required: [
+ "key",
+ "name",
+ "description",
+ "type",
+ "body"
+ ]
+ }
+ }
+], nv = {
+ async wave(e, t) {
+ let n = e.duration_ms || 1500;
+ return await t.viewer.playAnimationByHint?.("wave", { duration: n }), t.memory.note("waved", { duration_ms: n }), { ok: !0 };
+ },
+ async lookAt(e, t) {
+ let n = e.target || "user";
+ return t.viewer.lookAt?.(n), {
+ ok: !0,
+ target: n
+ };
+ },
+ async play_clip(e, t) {
+ let { name: n, loop: r = !1, fade_ms: i = 200 } = e;
+ return t.viewer.playClipByName?.(n, {
+ loop: r,
+ fade_ms: i
+ }) ? {
+ ok: !0,
+ name: n
+ } : {
+ ok: !1,
+ error: `No clip named "${n}"`
+ };
+ },
+ async setExpression(e, t) {
+ let { preset: n, intensity: r = 1 } = e;
+ return t.viewer.setExpression?.(n, r), {
+ ok: !0,
+ preset: n
+ };
+ },
+ async speak(e, t) {
+ return await t.speak(e.text), { ok: !0 };
+ },
+ async remember(e, t) {
+ let { key: n, name: r, description: i, type: a, body: o } = e;
+ return t.memory.write(n, {
+ name: r,
+ description: i,
+ type: a,
+ body: o
+ }), {
+ ok: !0,
+ saved: n
+ };
+ }
+}, rv = 8, iv = class extends EventTarget {
+ constructor({ manifest: e, viewer: t, memory: n, skills: r, providerConfig: i = {}, voiceConfig: a = {} } = {}) {
+ super(), this.manifest = e || {}, this.viewer = t, this.memory = n, this.skills = r, this.provider = X_({
+ ...this.manifest.brain,
+ ...i
+ }), this.tts = $_({
+ ...this.manifest.voice?.tts,
+ ...a.tts
+ }), this.stt = ev({
+ ...this.manifest.voice?.stt,
+ ...a.stt
+ }), this.messages = [], this._busy = !1;
+ }
+ get systemPrompt() {
+ let e = [];
+ return this.manifest.instructions && e.push(this.manifest.instructions), this.memory && e.push("\n\n<memory>\n" + this.memory.contextBlock({ maxTokens: this.manifest.memory?.maxTokens || 8192 }) + "\n</memory>"), this.skills && e.push(this.skills.systemPrompt()), e.join("");
+ }
+ get tools() {
+ let e = new Set(this.manifest.tools || tv.map((e) => e.name)), t = tv.filter((t) => e.has(t.name)), n = this.skills ? this.skills.allTools() : [];
+ return [...t, ...n];
+ }
+ async send(e, { voice: t = !1 } = {}) {
+ if (this._busy) throw Error("Runtime busy — wait for current turn to finish");
+ this._busy = !0;
+ try {
+ this.memory?.note("user_said", { text: e }), this.messages.push({
+ role: "user",
+ content: e
+ }), this.dispatchEvent(new CustomEvent("brain:message", { detail: {
+ role: "user",
+ content: e
+ } }));
+ let n = await this._loop();
+ return t && n.text && this.tts && (this.dispatchEvent(new CustomEvent("voice:speech-start", { detail: { text: n.text } })), await this.tts.speak(n.text), this.dispatchEvent(new CustomEvent("voice:speech-end", {}))), n;
+ } finally {
+ this._busy = !1;
+ }
+ }
+ async _loop() {
+ let e = 0, t = "";
+ for (; e++ < rv;) {
+ let e = await this.provider.complete({
+ system: this.systemPrompt,
+ messages: this.messages,
+ tools: this.tools
+ });
+ if (e.thinking && this.dispatchEvent(new CustomEvent("brain:thinking", { detail: { content: e.thinking } })), !e.toolCalls.length) {
+ t = e.text, this.messages.push({
+ role: "assistant",
+ content: e.text
+ }), this.dispatchEvent(new CustomEvent("brain:message", { detail: {
+ role: "assistant",
+ content: e.text
+ } }));
+ break;
+ }
+ this.messages.push(this.provider.formatAssistantWithToolCalls(e.text, e.toolCalls)), e.text && this.dispatchEvent(new CustomEvent("brain:message", { detail: {
+ role: "assistant",
+ content: e.text
+ } }));
+ let n = [];
+ for (let t of e.toolCalls) {
+ let e, r = !1;
+ try {
+ e = await this._dispatchTool(t);
+ } catch (t) {
+ e = { error: t.message || String(t) }, r = !0;
+ }
+ this.dispatchEvent(new CustomEvent("skill:tool-called", { detail: {
+ tool: t.name,
+ args: t.input,
+ result: e
+ } })), n.push({
+ id: t.id,
+ output: e,
+ isError: r
+ });
+ }
+ this.messages.push(this.provider.formatToolResults(n));
+ }
+ return { text: t };
+ }
+ async _dispatchTool(e) {
+ let t = this._context(), n = this.skills?.findSkillForTool(e.name);
+ if (n) return n.invoke(e.name, e.input, t);
+ let r = nv[e.name];
+ if (!r) throw Error(`Unknown tool: ${e.name}`);
+ return r(e.input, t);
+ }
+ _context() {
+ return this.skills, {
+ viewer: this.viewer,
+ memory: this.memory,
+ llm: { complete: (e, t) => this.provider.complete({
+ system: t?.system || "",
+ messages: [{
+ role: "user",
+ content: e
+ }],
+ tools: t?.tools
+ }) },
+ speak: async (e) => {
+ this.tts && (this.dispatchEvent(new CustomEvent("voice:speech-start", { detail: { text: e } })), await this.tts.speak(e), this.dispatchEvent(new CustomEvent("voice:speech-end", {})));
+ },
+ listen: (e) => this.stt?.listen(e),
+ fetch: (e, t) => fetch(e, t),
+ loadGLB: async (e) => this.viewer.loadGLB?.(e),
+ loadClip: async (e) => this.viewer.loadClip?.(e),
+ loadJSON: async (e) => (await fetch(e)).json(),
+ call: async (e, t) => this._dispatchTool({
+ name: e,
+ input: t
+ })
+ };
+ }
+ async listen({ onInterim: e, onFinal: t } = {}) {
+ if (!this.stt) throw Error("STT not configured");
+ return this.dispatchEvent(new CustomEvent("voice:listen-start", {})), await this.stt.listen({
+ onInterim: (t) => {
+ this.dispatchEvent(new CustomEvent("voice:transcript", { detail: {
+ text: t,
+ final: !1
+ } })), e?.(t);
+ },
+ onFinal: (e) => {
+ this.dispatchEvent(new CustomEvent("voice:transcript", { detail: {
+ text: e,
+ final: !0
+ } })), t?.(e);
+ }
+ });
+ }
+ clearConversation() {
+ this.messages = [];
+ }
+ pause() {
+ this.tts?.cancel(), this.stt?.stop();
+ }
+ destroy() {
+ this.pause(), this.messages = [];
+ }
+}, av = [
+ "https://dweb.link/ipfs/",
+ "https://cloudflare-ipfs.com/ipfs/",
+ "https://ipfs.io/ipfs/"
+], ov = "https://arweave.net/";
+function sv(e, t = 0) {
+ if (!e) return e;
+ let n = e.match(/^ipfs:\/\/(.+)$/i);
+ if (n) return av[t % av.length] + n[1];
+ let r = e.match(/^ar:\/\/(.+)$/i);
+ return r ? ov + r[1] : e;
+}
+async function cv(e) {
+ let t;
+ for (let n = 0; n < av.length; n++) {
+ let r = sv(e, n);
+ try {
+ let e = await fetch(r);
+ if (e.ok) return e;
+ } catch (e) {
+ t = e;
+ }
+ }
+ throw t || /* @__PURE__ */ Error("All IPFS gateways failed for " + e);
+}
+//#endregion
+//#region src/runtime/scene.js
+var lv = {
+ neutral: {},
+ happy: {
+ mouthSmile: 1,
+ browInnerUp: .3,
+ cheekSquintL: .4,
+ cheekSquintR: .4
+ },
+ sad: {
+ mouthFrownL: .8,
+ mouthFrownR: .8,
+ browDownL: .6,
+ browDownR: .6
+ },
+ surprised: {
+ jawOpen: .5,
+ eyeWideL: .8,
+ eyeWideR: .8,
+ browInnerUp: .9
+ },
+ confused: {
+ browInnerUp: .5,
+ browOuterUpL: .4,
+ mouthPressL: .3,
+ mouthPressR: .3
+ },
+ focused: {
+ browDownL: .4,
+ browDownR: .4,
+ eyeSquintL: .3,
+ eyeSquintR: .3
+ }
+}, uv = class {
+ constructor(e) {
+ this.viewer = e, this._loader = new fu(), this._userTarget = new R(0, 1.6, 2);
+ }
+ get scene() {
+ return this.viewer.scene;
+ }
+ get mixer() {
+ return this.viewer.mixer;
+ }
+ get clips() {
+ return this.viewer.clips || [];
+ }
+ get content() {
+ return this.viewer.content;
+ }
+ async load(e, t = "", n = /* @__PURE__ */ new Map()) {
+ return this.viewer.load(e, t, n);
+ }
+ playClipByName(e, { loop: t = !1, fade_ms: n = 200 } = {}) {
+ let r = this._findClip(e);
+ if (!r || !this.viewer.mixer) return !1;
+ let i = this.viewer.mixer.clipAction(r);
+ return i.reset(), i.setLoop(t ? 2201 : 2200), i.clampWhenFinished = !t, i.fadeIn(n / 1e3), i.play(), this.viewer.state.actionStates[r.name] = !0, this.viewer.invalidate(), !0;
+ }
+ playAnimationByHint(e, t) {
+ let n = e.toLowerCase(), r = this.clips.find((e) => e.name.toLowerCase().includes(n));
+ return r ? this.playClipByName(r.name, t) : !1;
+ }
+ stopClip(e) {
+ if (!this.viewer.mixer) return;
+ let t = e ? this._findClip(e) : null;
+ if (t) {
+ let e = this.viewer.mixer.existingAction(t);
+ e && e.fadeOut(.2), this.viewer.state.actionStates[t.name] = !1;
+ } else {
+ this.viewer.mixer.stopAllAction();
+ for (let e in this.viewer.state.actionStates) this.viewer.state.actionStates[e] = !1;
+ }
+ this.viewer.invalidate();
+ }
+ async play(e, t) {
+ if (typeof e == "string") return this.playClipByName(e, t);
+ if (!this.viewer.mixer || !e) return !1;
+ let n = this.viewer.mixer.clipAction(e);
+ return n.reset(), n.fadeIn(t?.blend ?? .2), n.play(), this.viewer.invalidate(), !0;
+ }
+ async loadClip(e) {
+ let t = sv(e);
+ return new Promise((e, n) => {
+ this._loader.load(t, (t) => e(t.animations?.[0] || null), void 0, n);
+ });
+ }
+ async loadGLB(e) {
+ let t = sv(e);
+ return new Promise((e, n) => {
+ this._loader.load(t, e, void 0, n);
+ });
+ }
+ lookAt(e) {
+ let t = this._resolveTarget(e);
+ if (!t || !this.viewer.content) return;
+ let n = this._findBone([
+ "Head",
+ "head",
+ "mixamorigHead"
+ ]);
+ n ? n.lookAt(t) : this.viewer.content.lookAt(t.x, this.viewer.content.position.y, t.z), this.viewer.invalidate();
+ }
+ _resolveTarget(e) {
+ return e instanceof R ? e : e === "camera" ? this.viewer.activeCamera.position.clone() : e === "center" ? new R(0, 1, 0) : e === "user" ? this._userTarget.clone() : null;
+ }
+ _findBone(e) {
+ if (!this.viewer.content) return null;
+ let t = null;
+ return this.viewer.content.traverse((n) => {
+ t || n.isBone && e.includes(n.name) && (t = n);
+ }), t;
+ }
+ setExpression(e, t = 1) {
+ let n = lv[e] || lv.neutral;
+ this.viewer.content && (this.viewer.content.traverse((e) => {
+ if (!(!e.morphTargetDictionary || !e.morphTargetInfluences)) {
+ for (let t = 0; t < e.morphTargetInfluences.length; t++) e.morphTargetInfluences[t] = 0;
+ for (let [r, i] of Object.entries(n)) {
+ let n = e.morphTargetDictionary[r];
+ n !== void 0 && (e.morphTargetInfluences[n] = i * t);
+ }
+ }
+ }), this.viewer.invalidate());
+ }
+ moveTo(e, { duration: t = 600 } = {}) {
+ if (!this.viewer.content) return;
+ let n = this.viewer.content.position.clone(), r = new R(e.x || 0, e.y || n.y, e.z || 0), i = performance.now(), a = (e) => {
+ let o = performance.now() - i, s = Math.min(o / t, 1), c = s < .5 ? 2 * s * s : 1 - (-2 * s + 2) ** 2 / 2;
+ this.viewer.content.position.lerpVectors(n, r, c), this.viewer.invalidate(), s >= 1 && this._removeHook(a);
+ };
+ this._addHook(a);
+ }
+ _addHook(e) {
+ this.viewer._afterAnimateHooks || (this.viewer._afterAnimateHooks = []), this.viewer._afterAnimateHooks.push(e), this.viewer._animating = !0, this.viewer.invalidate();
+ }
+ _removeHook(e) {
+ let t = this.viewer._afterAnimateHooks;
+ if (!t) return;
+ let n = t.indexOf(e);
+ n >= 0 && t.splice(n, 1);
+ }
+ _findClip(e) {
+ if (!this.clips.length) return null;
+ let t = this.clips.find((t) => t.name === e);
+ if (t) return t;
+ let n = e.toLowerCase();
+ return this.clips.find((e) => e.name.toLowerCase() === n) || this.clips.find((e) => e.name.toLowerCase().includes(n));
+ }
+};
+//#endregion
+//#region src/skills/index.js
+function dv(e, t) {
+ return /^([a-z]+:|\/)/i.test(t) ? t : (e.endsWith("/") || (e += "/"), e + t);
+}
+var fv = class {
+ constructor({ uri: e, manifest: t, instructions: n, tools: r, handlers: i }) {
+ this.uri = e, this.manifest = t, this.name = t.name, this.version = t.version, this.instructions = n, this.tools = r || [], this.handlers = i || {};
+ }
+ async invoke(e, t, n) {
+ let r = this.handlers[e];
+ if (!r) throw Error(`Skill "${this.name}" has no handler for tool "${e}"`);
+ return r(t, {
+ ...n,
+ skillBaseURI: this.uri
+ });
+ }
+ systemPromptFragment() {
+ return this.instructions ? `\n\n<skill name="${this.name}" version="${this.version}">\n${this.instructions}\n</skill>` : "";
+ }
+}, pv = class {
+ constructor({ fetchFn: e = fetch.bind(globalThis), trust: t = "owned-only", ownerAddress: n } = {}) {
+ this.fetchFn = e, this.trust = t, this.ownerAddress = n?.toLowerCase(), this.skills = /* @__PURE__ */ new Map();
+ }
+ async install(e, { bundleBase: t } = {}) {
+ let n = this._resolveBundleURI(e.uri, t);
+ if (this.skills.has(n)) return this.skills.get(n);
+ let r = await this._fetchJSON(`${n}manifest.json`);
+ this._enforceTrust(r);
+ let [i, a, o] = await Promise.all([
+ this._fetchText(`${n}SKILL.md`).catch(() => ""),
+ this._fetchJSON(`${n}tools.json`).catch(() => ({ tools: [] })),
+ this._fetchHandlers(`${n}handlers.js`).catch(() => null)
+ ]), s = new fv({
+ uri: n,
+ manifest: r,
+ instructions: i,
+ tools: a.tools || [],
+ handlers: o || {}
+ });
+ if (r.dependencies) for (let [e, t] of Object.entries(r.dependencies)) await this.install({
+ uri: e,
+ version: t
+ });
+ return this.skills.set(n, s), s;
+ }
+ uninstall(e) {
+ for (let [t, n] of this.skills) if (n.name === e) return this.skills.delete(t), !0;
+ return !1;
+ }
+ all() {
+ return Array.from(this.skills.values());
+ }
+ allTools() {
+ let e = /* @__PURE__ */ new Map();
+ for (let t of this.skills.values()) for (let n of t.tools) e.has(n.name) && console.warn(`[skills] tool "${n.name}" overridden by skill "${t.name}"`), e.set(n.name, {
+ ...n,
+ _skill: t.name
+ });
+ return Array.from(e.values());
+ }
+ findSkillForTool(e) {
+ for (let t of this.skills.values()) if (t.tools.some((t) => t.name === e)) return t;
+ return null;
+ }
+ systemPrompt() {
+ return this.all().map((e) => e.systemPromptFragment()).join("");
+ }
+ _resolveBundleURI(e, t) {
+ let n = e;
+ return !/^([a-z]+:|\/)/i.test(e) && t && (n = dv(t, e)), n.endsWith("/") || (n += "/"), (n.startsWith("ipfs://") || n.startsWith("ar://")) && (n = sv(n)), n;
+ }
+ async _fetchJSON(e) {
+ let t = await this.fetchFn(e);
+ if (!t.ok) throw Error(`Fetch failed: ${e} (${t.status})`);
+ return t.json();
+ }
+ async _fetchText(e) {
+ let t = await this.fetchFn(e);
+ if (!t.ok) throw Error(`Fetch failed: ${e} (${t.status})`);
+ return t.text();
+ }
+ async _fetchHandlers(e) {
+ try {
+ return await import(
+ /* @vite-ignore */
+ e
+);
+ } catch (t) {
+ return console.warn(`[skills] handlers load failed: ${e}`, t), null;
+ }
+ }
+ _enforceTrust(e) {
+ if (this.trust !== "any") {
+ if (this.trust === "owned-only") {
+ let t = (e.author || "").toLowerCase();
+ if (t && this.ownerAddress && t !== this.ownerAddress) throw Error(`Skill "${e.name}" author ${t} not trusted under owned-only policy`);
+ }
+ this.trust;
+ }
+ }
+}, mv = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/;
+function hv(e) {
+ let t = e.match(mv);
+ if (!t) return {
+ meta: {},
+ body: e
+ };
+ let n = {};
+ for (let e of t[1].split("\n")) {
+ let [t, ...r] = e.split(":");
+ t && (n[t.trim()] = r.join(":").trim());
+ }
+ return {
+ meta: n,
+ body: t[2]
+ };
+}
+function gv(e, t) {
+ let n = ["---"];
+ for (let [t, r] of Object.entries(e)) n.push(`${t}: ${r}`);
+ return n.push("---", "", t), n.join("\n");
+}
+var _v = class e {
+ constructor({ mode: e = "local", namespace: t, index: n = {}, files: r = {}, timeline: i = [] } = {}) {
+ this.mode = e, this.namespace = t, this.files = new Map(Object.entries(r)), this.timeline = i, this.indexText = n.text || "", this._dirty = !1;
+ }
+ static async load({ mode: t = "local", namespace: n, manifestURI: r, fetchFn: i }) {
+ if (t === "none") return new e({
+ mode: "none",
+ namespace: n
+ });
+ if (t === "local") return e._loadLocal(n);
+ if (t === "ipfs" || t === "encrypted-ipfs") return e._loadIPFS({
+ mode: t,
+ namespace: n,
+ manifestURI: r,
+ fetchFn: i
+ });
+ throw Error(`Unknown memory mode: ${t}`);
+ }
+ static _loadLocal(t) {
+ let n = `agent:${t}:memory`;
+ try {
+ let r = localStorage.getItem(n);
+ return r ? new e({
+ mode: "local",
+ namespace: t,
+ ...JSON.parse(r)
+ }) : new e({
+ mode: "local",
+ namespace: t
+ });
+ } catch {
+ return new e({
+ mode: "local",
+ namespace: t
+ });
+ }
+ }
+ static async _loadIPFS({ mode: t, namespace: n, manifestURI: r, fetchFn: i }) {
+ let a = r.replace(/manifest\.json$/, "");
+ try {
+ let r = await i(`${a}memory/MEMORY.md`), o = r.ok ? await r.text() : "", s = {}, c = /\[([^\]]+)\]\(([^)]+\.md)\)/g, l;
+ for (; l = c.exec(o);) {
+ let e = l[2];
+ try {
+ let t = await i(`${a}memory/${e}`);
+ t.ok && (s[e] = await t.text());
+ } catch {}
+ }
+ return new e({
+ mode: t,
+ namespace: n,
+ index: { text: o },
+ files: s
+ });
+ } catch {
+ return new e({
+ mode: t,
+ namespace: n
+ });
+ }
+ }
+ read(e) {
+ let t = e.endsWith(".md") ? e : `${e}.md`, n = this.files.get(t);
+ return n ? hv(n) : null;
+ }
+ write(e, { name: t, description: n, type: r, body: i, decay: a }) {
+ let o = e.endsWith(".md") ? e : `${e}.md`, s = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10), c = this.files.get(o), l = {
+ name: t,
+ description: n,
+ type: r,
+ created: c && hv(c).meta.created || s,
+ updated: s
+ };
+ a && (l.decay = a), this.files.set(o, gv(l, i || "")), this._rebuildIndex(), this._dirty = !0, this._persist();
+ }
+ note(e, t) {
+ let n = {
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
+ type: e,
+ ...t
+ };
+ this.timeline.push(n), this.timeline.length > 1e3 && (this.timeline = this.timeline.slice(-1e3)), this._dirty = !0, this._persist();
+ }
+ async recall(e, { limit: t = 5 } = {}) {
+ let n = e.toLowerCase(), r = [];
+ for (let [e, t] of this.files) {
+ let { meta: i, body: a } = hv(t), o = `${i.name || ""} ${i.description || ""} ${a}`.toLowerCase();
+ o.includes(n) && r.push({
+ file: e,
+ meta: i,
+ body: a,
+ score: o.split(n).length - 1
+ });
+ }
+ return r.sort((e, t) => t.score - e.score).slice(0, t);
+ }
+ _rebuildIndex() {
+ let e = {
+ user: [],
+ feedback: [],
+ project: [],
+ reference: []
+ };
+ for (let [t, n] of this.files) {
+ let { meta: r } = hv(n), i = r.type || "user";
+ e[i] || (e[i] = []), e[i].push({
+ file: t,
+ name: r.name || t,
+ description: r.description || ""
+ });
+ }
+ let t = ["# Memory", ""], n = {
+ user: "## User",
+ feedback: "## Feedback",
+ project: "## Project",
+ reference: "## Reference"
+ };
+ for (let [r, i] of Object.entries(e)) if (i.length) {
+ t.push(n[r] || `## ${r}`);
+ for (let e of i) t.push(`- [${e.name}](${e.file}) — ${e.description}`);
+ t.push("");
+ }
+ this.indexText = t.join("\n");
+ }
+ _persist() {
+ if (this.mode !== "local" || !this.namespace) return;
+ let e = `agent:${this.namespace}:memory`, t = {
+ index: { text: this.indexText },
+ files: Object.fromEntries(this.files),
+ timeline: this.timeline.slice(-200)
+ };
+ try {
+ localStorage.setItem(e, JSON.stringify(t));
+ } catch (e) {
+ console.warn("[memory] persist failed", e);
+ }
+ }
+ contextBlock({ maxTokens: e = 8192 } = {}) {
+ let t = e * 4, n = [
+ "# Agent Memory",
+ "",
+ this.indexText
+ ], r = n.join("\n").length;
+ for (let [e, i] of this.files) {
+ if (r + i.length > t) break;
+ n.push("", `## ${e}`, i), r += i.length;
+ }
+ if (this.timeline.length) {
+ let e = this.timeline.slice(-20).map((e) => JSON.stringify(e)).join("\n");
+ r + e.length < t && n.push("", "## Recent timeline", "```", e, "```");
+ }
+ return n.join("\n");
+ }
+ async export() {
+ return {
+ version: "memory/0.1",
+ index: this.indexText,
+ files: Object.fromEntries(this.files),
+ timeline: this.timeline
+ };
+ }
+ async import(e, { strategy: t = "merge" } = {}) {
+ if (t === "replace") this.files = new Map(Object.entries(e.files || {})), this.timeline = e.timeline || [];
+ else {
+ for (let [t, n] of Object.entries(e.files || {})) this.files.has(t) || this.files.set(t, n);
+ this.timeline = [...this.timeline, ...e.timeline || []].slice(-1e3);
+ }
+ this._rebuildIndex(), this._persist();
+ }
+}, vv = "6.16.0";
+//#endregion
+//#region node_modules/ethers/lib.esm/utils/properties.js
+function yv(e, t, n) {
+ let r = t.split("|").map((e) => e.trim());
+ for (let n = 0; n < r.length; n++) switch (t) {
+ case "any": return;
+ case "bigint":
+ case "boolean":
+ case "number":
+ case "string": if (typeof e === t) return;
+ }
+ let i = /* @__PURE__ */ Error(`invalid value for type ${t}`);
+ throw i.code = "INVALID_ARGUMENT", i.argument = `value.${n}`, i.value = e, i;
+}
+async function bv(e) {
+ let t = Object.keys(e);
+ return (await Promise.all(t.map((t) => Promise.resolve(e[t])))).reduce((e, n, r) => (e[t[r]] = n, e), {});
+}
+function G(e, t, n) {
+ for (let r in t) {
+ let i = t[r], a = n ? n[r] : null;
+ a && yv(i, a, r), Object.defineProperty(e, r, {
+ enumerable: !0,
+ value: i,
+ writable: !1
+ });
+ }
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/utils/errors.js
+function xv(e, t) {
+ if (e == null) return "null";
+ if (t ??= /* @__PURE__ */ new Set(), typeof e == "object") {
+ if (t.has(e)) return "[Circular]";
+ t.add(e);
+ }
+ if (Array.isArray(e)) return "[ " + e.map((e) => xv(e, t)).join(", ") + " ]";
+ if (e instanceof Uint8Array) {
+ let t = "0123456789abcdef", n = "0x";
+ for (let r = 0; r < e.length; r++) n += t[e[r] >> 4], n += t[e[r] & 15];
+ return n;
+ }
+ if (typeof e == "object" && typeof e.toJSON == "function") return xv(e.toJSON(), t);
+ switch (typeof e) {
+ case "boolean":
+ case "number":
+ case "symbol": return e.toString();
+ case "bigint": return BigInt(e).toString();
+ case "string": return JSON.stringify(e);
+ case "object": {
+ let n = Object.keys(e);
+ return n.sort(), "{ " + n.map((n) => `${xv(n, t)}: ${xv(e[n], t)}`).join(", ") + " }";
+ }
+ }
+ return "[ COULD NOT SERIALIZE ]";
+}
+function Sv(e, t) {
+ return e && e.code === t;
+}
+function Cv(e) {
+ return Sv(e, "CALL_EXCEPTION");
+}
+function wv(e, t, n) {
+ let r = e;
+ {
+ let r = [];
+ if (n) {
+ if ("message" in n || "code" in n || "name" in n) throw Error(`value will overwrite populated values: ${xv(n)}`);
+ for (let e in n) {
+ if (e === "shortMessage") continue;
+ let t = n[e];
+ r.push(e + "=" + xv(t));
+ }
+ }
+ r.push(`code=${t}`), r.push(`version=${vv}`), r.length && (e += " (" + r.join(", ") + ")");
+ }
+ let i;
+ switch (t) {
+ case "INVALID_ARGUMENT":
+ i = TypeError(e);
+ break;
+ case "NUMERIC_FAULT":
+ case "BUFFER_OVERRUN":
+ i = RangeError(e);
+ break;
+ default: i = Error(e);
+ }
+ return G(i, { code: t }), n && Object.assign(i, n), i.shortMessage ?? G(i, { shortMessage: r }), i;
+}
+function K(e, t, n, r) {
+ if (!e) throw wv(t, n, r);
+}
+function q(e, t, n, r) {
+ K(e, t, "INVALID_ARGUMENT", {
+ argument: n,
+ value: r
+ });
+}
+function Tv(e, t, n) {
+ n ??= "", n &&= ": " + n, K(e >= t, "missing argument" + n, "MISSING_ARGUMENT", {
+ count: e,
+ expectedCount: t
+ }), K(e <= t, "too many arguments" + n, "UNEXPECTED_ARGUMENT", {
+ count: e,
+ expectedCount: t
+ });
+}
+var Ev = [
+ "NFD",
+ "NFC",
+ "NFKD",
+ "NFKC"
+].reduce((e, t) => {
+ try {
+ /* c8 ignore start */
+ if ("test".normalize(t) !== "test") throw Error("bad");
+ /* c8 ignore stop */
+ if (t === "NFD" && "é".normalize("NFD") !== "é") throw Error("broken");
+ e.push(t);
+ } catch {}
+ return e;
+}, []);
+function Dv(e) {
+ K(Ev.indexOf(e) >= 0, "platform missing String.prototype.normalize", "UNSUPPORTED_OPERATION", {
+ operation: "String.prototype.normalize",
+ info: { form: e }
+ });
+}
+function Ov(e, t, n) {
+ if (n ??= "", e !== t) {
+ let e = n, t = "new";
+ n && (e += ".", t += " " + n), K(!1, `private constructor; use ${e}from* methods`, "UNSUPPORTED_OPERATION", { operation: t });
+ }
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/utils/data.js
+function kv(e, t, n) {
+ if (e instanceof Uint8Array) return n ? new Uint8Array(e) : e;
+ if (typeof e == "string" && e.length % 2 == 0 && e.match(/^0x[0-9a-f]*$/i)) {
+ let t = new Uint8Array((e.length - 2) / 2), n = 2;
+ for (let r = 0; r < t.length; r++) t[r] = parseInt(e.substring(n, n + 2), 16), n += 2;
+ return t;
+ }
+ q(!1, "invalid BytesLike value", t || "value", e);
+}
+function J(e, t) {
+ return kv(e, t, !1);
+}
+function Av(e, t) {
+ return kv(e, t, !0);
+}
+function jv(e, t) {
+ return !(typeof e != "string" || !e.match(/^0x[0-9A-Fa-f]*$/) || typeof t == "number" && e.length !== 2 + 2 * t || t === !0 && e.length % 2 != 0);
+}
+function Mv(e) {
+ return jv(e, !0) || e instanceof Uint8Array;
+}
+var Nv = "0123456789abcdef";
+function Y(e) {
+ let t = J(e), n = "0x";
+ for (let e = 0; e < t.length; e++) {
+ let r = t[e];
+ n += Nv[(r & 240) >> 4] + Nv[r & 15];
+ }
+ return n;
+}
+function Pv(e) {
+ return "0x" + e.map((e) => Y(e).substring(2)).join("");
+}
+function Fv(e) {
+ return jv(e, !0) ? (e.length - 2) / 2 : J(e).length;
+}
+function Iv(e, t, n) {
+ let r = J(e);
+ return n != null && n > r.length && K(!1, "cannot slice beyond data bounds", "BUFFER_OVERRUN", {
+ buffer: r,
+ length: r.length,
+ offset: n
+ }), Y(r.slice(t ?? 0, n ?? r.length));
+}
+function Lv(e, t, n) {
+ let r = J(e);
+ K(t >= r.length, "padding exceeds data length", "BUFFER_OVERRUN", {
+ buffer: new Uint8Array(r),
+ length: t,
+ offset: t + 1
+ });
+ let i = new Uint8Array(t);
+ return i.fill(0), n ? i.set(r, t - r.length) : i.set(r, 0), Y(i);
+}
+function Rv(e, t) {
+ return Lv(e, t, !0);
+}
+function zv(e, t) {
+ return Lv(e, t, !1);
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/utils/maths.js
+var Bv = BigInt(0), Vv = BigInt(1), Hv = 9007199254740991;
+function Uv(e, t) {
+ let n = Kv(e, "value"), r = BigInt(Z(t, "width"));
+ if (K(n >> r === Bv, "overflow", "NUMERIC_FAULT", {
+ operation: "fromTwos",
+ fault: "overflow",
+ value: e
+ }), n >> r - Vv) {
+ let e = (Vv << r) - Vv;
+ return -((~n & e) + Vv);
+ }
+ return n;
+}
+function Wv(e, t) {
+ let n = X(e, "value"), r = BigInt(Z(t, "width")), i = Vv << r - Vv;
+ if (n < Bv) {
+ n = -n, K(n <= i, "too low", "NUMERIC_FAULT", {
+ operation: "toTwos",
+ fault: "overflow",
+ value: e
+ });
+ let t = (Vv << r) - Vv;
+ return (~n & t) + Vv;
+ } else K(n < i, "too high", "NUMERIC_FAULT", {
+ operation: "toTwos",
+ fault: "overflow",
+ value: e
+ });
+ return n;
+}
+function Gv(e, t) {
+ return Kv(e, "value") & (Vv << BigInt(Z(t, "bits"))) - Vv;
+}
+function X(e, t) {
+ switch (typeof e) {
+ case "bigint": return e;
+ case "number": return q(Number.isInteger(e), "underflow", t || "value", e), q(e >= -Hv && e <= Hv, "overflow", t || "value", e), BigInt(e);
+ case "string": try {
+ if (e === "") throw Error("empty string");
+ return e[0] === "-" && e[1] !== "-" ? -BigInt(e.substring(1)) : BigInt(e);
+ } catch (n) {
+ q(!1, `invalid BigNumberish string: ${n.message}`, t || "value", e);
+ }
+ }
+ q(!1, "invalid BigNumberish value", t || "value", e);
+}
+function Kv(e, t) {
+ let n = X(e, t);
+ return K(n >= Bv, "unsigned value cannot be negative", "NUMERIC_FAULT", {
+ fault: "overflow",
+ operation: "getUint",
+ value: e
+ }), n;
+}
+var qv = "0123456789abcdef";
+function Jv(e) {
+ if (e instanceof Uint8Array) {
+ let t = "0x0";
+ for (let n of e) t += qv[n >> 4], t += qv[n & 15];
+ return BigInt(t);
+ }
+ return X(e);
+}
+function Z(e, t) {
+ switch (typeof e) {
+ case "bigint": return q(e >= -Hv && e <= Hv, "overflow", t || "value", e), Number(e);
+ case "number": return q(Number.isInteger(e), "underflow", t || "value", e), q(e >= -Hv && e <= Hv, "overflow", t || "value", e), e;
+ case "string": try {
+ if (e === "") throw Error("empty string");
+ return Z(BigInt(e), t);
+ } catch (n) {
+ q(!1, `invalid numeric string: ${n.message}`, t || "value", e);
+ }
+ }
+ q(!1, "invalid numeric value", t || "value", e);
+}
+function Yv(e) {
+ return Z(Jv(e));
+}
+function Xv(e, t) {
+ let n = Kv(e, "value"), r = n.toString(16);
+ if (t == null) r.length % 2 && (r = "0" + r);
+ else {
+ let i = Z(t, "width");
+ if (i === 0 && n === Bv) return "0x";
+ for (K(i * 2 >= r.length, `value exceeds width (${i} bytes)`, "NUMERIC_FAULT", {
+ operation: "toBeHex",
+ fault: "overflow",
+ value: e
+ }); r.length < i * 2;) r = "0" + r;
+ }
+ return "0x" + r;
+}
+function Zv(e, t) {
+ let n = Kv(e, "value");
+ if (n === Bv) {
+ let e = t == null ? 0 : Z(t, "width");
+ return new Uint8Array(e);
+ }
+ let r = n.toString(16);
+ if (r.length % 2 && (r = "0" + r), t != null) {
+ let n = Z(t, "width");
+ for (; r.length < n * 2;) r = "00" + r;
+ K(n * 2 === r.length, `value exceeds width (${n} bytes)`, "NUMERIC_FAULT", {
+ operation: "toBeArray",
+ fault: "overflow",
+ value: e
+ });
+ }
+ let i = new Uint8Array(r.length / 2);
+ for (let e = 0; e < i.length; e++) {
+ let t = e * 2;
+ i[e] = parseInt(r.substring(t, t + 2), 16);
+ }
+ return i;
+}
+function Qv(e) {
+ let t = Y(Mv(e) ? e : Zv(e)).substring(2);
+ for (; t.startsWith("0");) t = t.substring(1);
+ return t === "" && (t = "0"), "0x" + t;
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/utils/base58.js
+var $v = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz", ey = BigInt(58);
+function ty(e) {
+ let t = J(e), n = Jv(t), r = "";
+ for (; n;) r = $v[Number(n % ey)] + r, n /= ey;
+ for (let e = 0; e < t.length && !t[e]; e++) r = $v[0] + r;
+ return r;
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/utils/base64-browser.js
+function ny(e) {
+ e = atob(e);
+ let t = new Uint8Array(e.length);
+ for (let n = 0; n < e.length; n++) t[n] = e.charCodeAt(n);
+ return J(t);
+}
+function ry(e) {
+ let t = J(e), n = "";
+ for (let e = 0; e < t.length; e++) n += String.fromCharCode(t[e]);
+ return btoa(n);
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/utils/events.js
+var iy = class {
+ filter;
+ emitter;
+ #e;
+ constructor(e, t, n) {
+ this.#e = t, G(this, {
+ emitter: e,
+ filter: n
+ });
+ }
+ async removeListener() {
+ this.#e != null && await this.emitter.off(this.filter, this.#e);
+ }
+};
+//#endregion
+//#region node_modules/ethers/lib.esm/utils/utf8.js
+function ay(e, t, n, r, i) {
+ q(!1, `invalid codepoint at offset ${t}; ${e}`, "bytes", n);
+}
+function oy(e, t, n, r, i) {
+ if (e === "BAD_PREFIX" || e === "UNEXPECTED_CONTINUE") {
+ let e = 0;
+ for (let r = t + 1; r < n.length && n[r] >> 6 == 2; r++) e++;
+ return e;
+ }
+ return e === "OVERRUN" ? n.length - t - 1 : 0;
+}
+function sy(e, t, n, r, i) {
+ return e === "OVERLONG" ? (q(typeof i == "number", "invalid bad code point for replacement", "badCodepoint", i), r.push(i), 0) : (r.push(65533), oy(e, t, n, r, i));
+}
+var cy = Object.freeze({
+ error: ay,
+ ignore: oy,
+ replace: sy
+});
+function ly(e, t) {
+ t ??= cy.error;
+ let n = J(e, "bytes"), r = [], i = 0;
+ for (; i < n.length;) {
+ let e = n[i++];
+ if (!(e >> 7)) {
+ r.push(e);
+ continue;
+ }
+ let a = null, o = null;
+ if ((e & 224) == 192) a = 1, o = 127;
+ else if ((e & 240) == 224) a = 2, o = 2047;
+ else if ((e & 248) == 240) a = 3, o = 65535;
+ else {
+ (e & 192) == 128 ? i += t("UNEXPECTED_CONTINUE", i - 1, n, r) : i += t("BAD_PREFIX", i - 1, n, r);
+ continue;
+ }
+ if (i - 1 + a >= n.length) {
+ i += t("OVERRUN", i - 1, n, r);
+ continue;
+ }
+ let s = e & (1 << 8 - a - 1) - 1;
+ for (let e = 0; e < a; e++) {
+ let e = n[i];
+ if ((e & 192) != 128) {
+ i += t("MISSING_CONTINUE", i, n, r), s = null;
+ break;
+ }
+ s = s << 6 | e & 63, i++;
+ }
+ if (s !== null) {
+ if (s > 1114111) {
+ i += t("OUT_OF_RANGE", i - 1 - a, n, r, s);
+ continue;
+ }
+ if (s >= 55296 && s <= 57343) {
+ i += t("UTF16_SURROGATE", i - 1 - a, n, r, s);
+ continue;
+ }
+ if (s <= o) {
+ i += t("OVERLONG", i - 1 - a, n, r, s);
+ continue;
+ }
+ r.push(s);
+ }
+ }
+ return r;
+}
+function uy(e, t) {
+ q(typeof e == "string", "invalid string value", "str", e), t != null && (Dv(t), e = e.normalize(t));
+ let n = [];
+ for (let t = 0; t < e.length; t++) {
+ let r = e.charCodeAt(t);
+ if (r < 128) n.push(r);
+ else if (r < 2048) n.push(r >> 6 | 192), n.push(r & 63 | 128);
+ else if ((r & 64512) == 55296) {
+ t++;
+ let i = e.charCodeAt(t);
+ q(t < e.length && (i & 64512) == 56320, "invalid surrogate pair", "str", e);
+ let a = 65536 + ((r & 1023) << 10) + (i & 1023);
+ n.push(a >> 18 | 240), n.push(a >> 12 & 63 | 128), n.push(a >> 6 & 63 | 128), n.push(a & 63 | 128);
+ } else n.push(r >> 12 | 224), n.push(r >> 6 & 63 | 128), n.push(r & 63 | 128);
+ }
+ return new Uint8Array(n);
+}
+function dy(e) {
+ return e.map((e) => e <= 65535 ? String.fromCharCode(e) : (e -= 65536, String.fromCharCode((e >> 10 & 1023) + 55296, (e & 1023) + 56320))).join("");
+}
+function fy(e, t) {
+ return dy(ly(e, t));
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/utils/geturl-browser.js
+function py(e) {
+ async function t(t, n) {
+ K(n == null || !n.cancelled, "request cancelled before sending", "CANCELLED");
+ let r = t.url.split(":")[0].toLowerCase();
+ K(r === "http" || r === "https", `unsupported protocol ${r}`, "UNSUPPORTED_OPERATION", {
+ info: { protocol: r },
+ operation: "request"
+ }), K(r === "https" || !t.credentials || t.allowInsecureAuthentication, "insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", { operation: "request" });
+ let i = null, a = new AbortController(), o = setTimeout(() => {
+ i = wv("request timeout", "TIMEOUT"), a.abort();
+ }, t.timeout);
+ n && n.addListener(() => {
+ i = wv("request cancelled", "CANCELLED"), a.abort();
+ });
+ let s = Object.assign({}, e, {
+ method: t.method,
+ headers: new Headers(Array.from(t)),
+ body: t.body || void 0,
+ signal: a.signal
+ }), c;
+ try {
+ c = await fetch(t.url, s);
+ } catch (e) {
+ throw clearTimeout(o), i || e;
+ }
+ clearTimeout(o);
+ let l = {};
+ c.headers.forEach((e, t) => {
+ l[t.toLowerCase()] = e;
+ });
+ let u = await c.arrayBuffer(), d = u == null ? null : new Uint8Array(u);
+ return {
+ statusCode: c.status,
+ statusMessage: c.statusText,
+ headers: l,
+ body: d
+ };
+ }
+ return t;
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/utils/fetch.js
+var my = 12, hy = 250, gy = py(), _y = /* @__PURE__ */ RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i"), vy = /* @__PURE__ */ RegExp("^ipfs://(ipfs/)?(.*)$", "i"), yy = !1;
+async function by(e, t) {
+ try {
+ let t = e.match(_y);
+ if (!t) throw Error("invalid data");
+ return new Dy(200, "OK", { "content-type": t[1] || "text/plain" }, t[2] ? ny(t[3]) : ky(t[3]));
+ } catch {
+ return new Dy(599, "BAD REQUEST (invalid data: URI)", {}, null, new Ey(e));
+ }
+}
+function xy(e) {
+ async function t(t, n) {
+ try {
+ let n = t.match(vy);
+ if (!n) throw Error("invalid link");
+ return new Ey(`${e}${n[2]}`);
+ } catch {
+ return new Dy(599, "BAD REQUEST (invalid IPFS URI)", {}, null, new Ey(t));
+ }
+ }
+ return t;
+}
+var Sy = {
+ data: by,
+ ipfs: xy("https://gateway.ipfs.io/ipfs/")
+}, Cy = /* @__PURE__ */ new WeakMap(), wy = class {
+ #e;
+ #t;
+ constructor(e) {
+ this.#e = [], this.#t = !1, Cy.set(e, () => {
+ if (!this.#t) {
+ this.#t = !0;
+ for (let e of this.#e) setTimeout(() => {
+ e();
+ }, 0);
+ this.#e = [];
+ }
+ });
+ }
+ addListener(e) {
+ K(!this.#t, "singal already cancelled", "UNSUPPORTED_OPERATION", { operation: "fetchCancelSignal.addCancelListener" }), this.#e.push(e);
+ }
+ get cancelled() {
+ return this.#t;
+ }
+ checkSignal() {
+ K(!this.cancelled, "cancelled", "CANCELLED", {});
+ }
+};
+function Ty(e) {
+ if (e == null) throw Error("missing signal; should not happen");
+ return e.checkSignal(), e;
+}
+var Ey = class e {
+ #e;
+ #t;
+ #n;
+ #r;
+ #i;
+ #a;
+ #o;
+ #s;
+ #c;
+ #l;
+ #u;
+ #d;
+ #f;
+ #p;
+ #m;
+ get url() {
+ return this.#a;
+ }
+ set url(e) {
+ this.#a = String(e);
+ }
+ get body() {
+ return this.#o == null ? null : new Uint8Array(this.#o);
+ }
+ set body(e) {
+ if (e == null) this.#o = void 0, this.#s = void 0;
+ else if (typeof e == "string") this.#o = uy(e), this.#s = "text/plain";
+ else if (e instanceof Uint8Array) this.#o = e, this.#s = "application/octet-stream";
+ else if (typeof e == "object") this.#o = uy(JSON.stringify(e)), this.#s = "application/json";
+ else throw Error("invalid body");
+ }
+ hasBody() {
+ return this.#o != null;
+ }
+ get method() {
+ return this.#r ? this.#r : this.hasBody() ? "POST" : "GET";
+ }
+ set method(e) {
+ e ??= "", this.#r = String(e).toUpperCase();
+ }
+ get headers() {
+ let e = Object.assign({}, this.#n);
+ return this.#c && (e.authorization = `Basic ${ry(uy(this.#c))}`), this.allowGzip && (e["accept-encoding"] = "gzip"), e["content-type"] == null && this.#s && (e["content-type"] = this.#s), this.body && (e["content-length"] = String(this.body.length)), e;
+ }
+ getHeader(e) {
+ return this.headers[e.toLowerCase()];
+ }
+ setHeader(e, t) {
+ this.#n[String(e).toLowerCase()] = String(t);
+ }
+ clearHeaders() {
+ this.#n = {};
+ }
+ [Symbol.iterator]() {
+ let e = this.headers, t = Object.keys(e), n = 0;
+ return { next: () => {
+ if (n < t.length) {
+ let r = t[n++];
+ return {
+ value: [r, e[r]],
+ done: !1
+ };
+ }
+ return {
+ value: void 0,
+ done: !0
+ };
+ } };
+ }
+ get credentials() {
+ return this.#c || null;
+ }
+ setCredentials(e, t) {
+ q(!e.match(/:/), "invalid basic authentication username", "username", "[REDACTED]"), this.#c = `${e}:${t}`;
+ }
+ get allowGzip() {
+ return this.#t;
+ }
+ set allowGzip(e) {
+ this.#t = !!e;
+ }
+ get allowInsecureAuthentication() {
+ return !!this.#e;
+ }
+ set allowInsecureAuthentication(e) {
+ this.#e = !!e;
+ }
+ get timeout() {
+ return this.#i;
+ }
+ set timeout(e) {
+ q(e >= 0, "timeout must be non-zero", "timeout", e), this.#i = e;
+ }
+ get preflightFunc() {
+ return this.#l || null;
+ }
+ set preflightFunc(e) {
+ this.#l = e;
+ }
+ get processFunc() {
+ return this.#u || null;
+ }
+ set processFunc(e) {
+ this.#u = e;
+ }
+ get retryFunc() {
+ return this.#d || null;
+ }
+ set retryFunc(e) {
+ this.#d = e;
+ }
+ get getUrlFunc() {
+ return this.#m || gy;
+ }
+ set getUrlFunc(e) {
+ this.#m = e;
+ }
+ constructor(e) {
+ this.#a = String(e), this.#e = !1, this.#t = !0, this.#n = {}, this.#r = "", this.#i = 3e5, this.#p = {
+ slotInterval: hy,
+ maxAttempts: my
+ }, this.#m = null;
+ }
+ toString() {
+ return `<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${this.#o ? Y(this.#o) : "null"}>`;
+ }
+ setThrottleParams(e) {
+ e.slotInterval != null && (this.#p.slotInterval = e.slotInterval), e.maxAttempts != null && (this.#p.maxAttempts = e.maxAttempts);
+ }
+ async #h(e, t, n, r, i) {
+ if (e >= this.#p.maxAttempts) return i.makeServerError("exceeded maximum retry limit");
+ K(Oy() <= t, "timeout", "TIMEOUT", {
+ operation: "request.send",
+ reason: "timeout",
+ request: r
+ }), n > 0 && await Ay(n);
+ let a = this.clone(), o = (a.url.split(":")[0] || "").toLowerCase();
+ if (o in Sy) {
+ let e = await Sy[o](a.url, Ty(r.#f));
+ if (e instanceof Dy) {
+ let t = e;
+ if (this.processFunc) {
+ Ty(r.#f);
+ try {
+ t = await this.processFunc(a, t);
+ } catch (e) {
+ (e.throttle == null || typeof e.stall != "number") && t.makeServerError("error in post-processing function", e).assertOk();
+ }
+ }
+ return t;
+ }
+ a = e;
+ }
+ this.preflightFunc && (a = await this.preflightFunc(a));
+ let s = await this.getUrlFunc(a, Ty(r.#f)), c = new Dy(s.statusCode, s.statusMessage, s.headers, s.body, r);
+ if (c.statusCode === 301 || c.statusCode === 302) {
+ try {
+ let n = c.headers.location || "";
+ return a.redirect(n).#h(e + 1, t, 0, r, c);
+ } catch {}
+ return c;
+ } else if (c.statusCode === 429 && (this.retryFunc == null || await this.retryFunc(a, c, e))) {
+ let n = c.headers["retry-after"], i = this.#p.slotInterval * Math.trunc(Math.random() * 2 ** e);
+ return typeof n == "string" && n.match(/^[1-9][0-9]*$/) && (i = parseInt(n)), a.clone().#h(e + 1, t, i, r, c);
+ }
+ if (this.processFunc) {
+ Ty(r.#f);
+ try {
+ c = await this.processFunc(a, c);
+ } catch (n) {
+ (n.throttle == null || typeof n.stall != "number") && c.makeServerError("error in post-processing function", n).assertOk();
+ let i = this.#p.slotInterval * Math.trunc(Math.random() * 2 ** e);
+ return n.stall >= 0 && (i = n.stall), a.clone().#h(e + 1, t, i, r, c);
+ }
+ }
+ return c;
+ }
+ send() {
+ return K(this.#f == null, "request already sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.send" }), this.#f = new wy(this), this.#h(0, Oy() + this.timeout, 0, this, new Dy(0, "", {}, null, this));
+ }
+ cancel() {
+ K(this.#f != null, "request has not been sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.cancel" });
+ let e = Cy.get(this);
+ if (!e) throw Error("missing signal; should not happen");
+ e();
+ }
+ redirect(t) {
+ let n = this.url.split(":")[0].toLowerCase(), r = t.split(":")[0].toLowerCase();
+ K(this.method === "GET" && (n !== "https" || r !== "http") && t.match(/^https?:/), "unsupported redirect", "UNSUPPORTED_OPERATION", { operation: `redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(t)})` });
+ let i = new e(t);
+ return i.method = "GET", i.allowGzip = this.allowGzip, i.timeout = this.timeout, i.#n = Object.assign({}, this.#n), this.#o && (i.#o = new Uint8Array(this.#o)), i.#s = this.#s, i;
+ }
+ clone() {
+ let t = new e(this.url);
+ return t.#r = this.#r, this.#o && (t.#o = this.#o), t.#s = this.#s, t.#n = Object.assign({}, this.#n), t.#c = this.#c, this.allowGzip && (t.allowGzip = !0), t.timeout = this.timeout, this.allowInsecureAuthentication && (t.allowInsecureAuthentication = !0), t.#l = this.#l, t.#u = this.#u, t.#d = this.#d, t.#p = Object.assign({}, this.#p), t.#m = this.#m, t;
+ }
+ static lockConfig() {
+ yy = !0;
+ }
+ static getGateway(e) {
+ return Sy[e.toLowerCase()] || null;
+ }
+ static registerGateway(e, t) {
+ if (e = e.toLowerCase(), e === "http" || e === "https") throw Error(`cannot intercept ${e}; use registerGetUrl`);
+ if (yy) throw Error("gateways locked");
+ Sy[e] = t;
+ }
+ static registerGetUrl(e) {
+ if (yy) throw Error("gateways locked");
+ gy = e;
+ }
+ static createGetUrlFunc(e) {
+ return py(e);
+ }
+ static createDataGateway() {
+ return by;
+ }
+ static createIpfsGatewayFunc(e) {
+ return xy(e);
+ }
+}, Dy = class e {
+ #e;
+ #t;
+ #n;
+ #r;
+ #i;
+ #a;
+ toString() {
+ return `<FetchResponse status=${this.statusCode} body=${this.#r ? Y(this.#r) : "null"}>`;
+ }
+ get statusCode() {
+ return this.#e;
+ }
+ get statusMessage() {
+ return this.#t;
+ }
+ get headers() {
+ return Object.assign({}, this.#n);
+ }
+ get body() {
+ return this.#r == null ? null : new Uint8Array(this.#r);
+ }
+ get bodyText() {
+ try {
+ return this.#r == null ? "" : fy(this.#r);
+ } catch {
+ K(!1, "response body is not valid UTF-8 data", "UNSUPPORTED_OPERATION", {
+ operation: "bodyText",
+ info: { response: this }
+ });
+ }
+ }
+ get bodyJson() {
+ try {
+ return JSON.parse(this.bodyText);
+ } catch {
+ K(!1, "response body is not valid JSON", "UNSUPPORTED_OPERATION", {
+ operation: "bodyJson",
+ info: { response: this }
+ });
+ }
+ }
+ [Symbol.iterator]() {
+ let e = this.headers, t = Object.keys(e), n = 0;
+ return { next: () => {
+ if (n < t.length) {
+ let r = t[n++];
+ return {
+ value: [r, e[r]],
+ done: !1
+ };
+ }
+ return {
+ value: void 0,
+ done: !0
+ };
+ } };
+ }
+ constructor(e, t, n, r, i) {
+ this.#e = e, this.#t = t, this.#n = Object.keys(n).reduce((e, t) => (e[t.toLowerCase()] = String(n[t]), e), {}), this.#r = r == null ? null : new Uint8Array(r), this.#i = i || null, this.#a = { message: "" };
+ }
+ makeServerError(t, n) {
+ let r;
+ t ? r = `CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${t})` : (t = `${this.statusCode} ${this.statusMessage}`, r = `CLIENT ESCALATED SERVER ERROR (${t})`);
+ let i = new e(599, r, this.headers, this.body, this.#i || void 0);
+ return i.#a = {
+ message: t,
+ error: n
+ }, i;
+ }
+ throwThrottleError(e, t) {
+ t == null ? t = -1 : q(Number.isInteger(t) && t >= 0, "invalid stall timeout", "stall", t);
+ let n = Error(e || "throttling requests");
+ throw G(n, {
+ stall: t,
+ throttle: !0
+ }), n;
+ }
+ getHeader(e) {
+ return this.headers[e.toLowerCase()];
+ }
+ hasBody() {
+ return this.#r != null;
+ }
+ get request() {
+ return this.#i;
+ }
+ ok() {
+ return this.#a.message === "" && this.statusCode >= 200 && this.statusCode < 300;
+ }
+ assertOk() {
+ if (this.ok()) return;
+ let { message: e, error: t } = this.#a;
+ e === "" && (e = `server response ${this.statusCode} ${this.statusMessage}`);
+ let n = null;
+ this.request && (n = this.request.url);
+ let r = null;
+ try {
+ this.#r && (r = fy(this.#r));
+ } catch {}
+ K(!1, e, "SERVER_ERROR", {
+ request: this.request || "unknown request",
+ response: this,
+ error: t,
+ info: {
+ requestUrl: n,
+ responseBody: r,
+ responseStatus: `${this.statusCode} ${this.statusMessage}`
+ }
+ });
+ }
+};
+function Oy() {
+ return (/* @__PURE__ */ new Date()).getTime();
+}
+function ky(e) {
+ return uy(e.replace(/%([0-9a-f][0-9a-f])/gi, (e, t) => String.fromCharCode(parseInt(t, 16))));
+}
+function Ay(e) {
+ return new Promise((t) => setTimeout(t, e));
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/utils/rlp-decode.js
+function jy(e) {
+ let t = e.toString(16);
+ for (; t.length < 2;) t = "0" + t;
+ return "0x" + t;
+}
+function My(e, t, n) {
+ let r = 0;
+ for (let i = 0; i < n; i++) r = r * 256 + e[t + i];
+ return r;
+}
+function Ny(e, t, n, r) {
+ let i = [];
+ for (; n < t + 1 + r;) {
+ let a = Py(e, n);
+ i.push(a.result), n += a.consumed, K(n <= t + 1 + r, "child data too short", "BUFFER_OVERRUN", {
+ buffer: e,
+ length: r,
+ offset: t
+ });
+ }
+ return {
+ consumed: 1 + r,
+ result: i
+ };
+}
+function Py(e, t) {
+ K(e.length !== 0, "data too short", "BUFFER_OVERRUN", {
+ buffer: e,
+ length: 0,
+ offset: 1
+ });
+ let n = (t) => {
+ K(t <= e.length, "data short segment too short", "BUFFER_OVERRUN", {
+ buffer: e,
+ length: e.length,
+ offset: t
+ });
+ };
+ if (e[t] >= 248) {
+ let r = e[t] - 247;
+ n(t + 1 + r);
+ let i = My(e, t + 1, r);
+ return n(t + 1 + r + i), Ny(e, t, t + 1 + r, r + i);
+ } else if (e[t] >= 192) {
+ let r = e[t] - 192;
+ return n(t + 1 + r), Ny(e, t, t + 1, r);
+ } else if (e[t] >= 184) {
+ let r = e[t] - 183;
+ n(t + 1 + r);
+ let i = My(e, t + 1, r);
+ n(t + 1 + r + i);
+ let a = Y(e.slice(t + 1 + r, t + 1 + r + i));
+ return {
+ consumed: 1 + r + i,
+ result: a
+ };
+ } else if (e[t] >= 128) {
+ let r = e[t] - 128;
+ n(t + 1 + r);
+ let i = Y(e.slice(t + 1, t + 1 + r));
+ return {
+ consumed: 1 + r,
+ result: i
+ };
+ }
+ return {
+ consumed: 1,
+ result: jy(e[t])
+ };
+}
+function Fy(e) {
+ let t = J(e, "data"), n = Py(t, 0);
+ return q(n.consumed === t.length, "unexpected junk after rlp payload", "data", e), n.result;
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/utils/rlp-encode.js
+function Iy(e) {
+ let t = [];
+ for (; e;) t.unshift(e & 255), e >>= 8;
+ return t;
+}
+function Ly(e) {
+ if (Array.isArray(e)) {
+ let t = [];
+ if (e.forEach(function(e) {
+ t = t.concat(Ly(e));
+ }), t.length <= 55) return t.unshift(192 + t.length), t;
+ let n = Iy(t.length);
+ return n.unshift(247 + n.length), n.concat(t);
+ }
+ let t = Array.prototype.slice.call(J(e, "object"));
+ if (t.length === 1 && t[0] <= 127) return t;
+ if (t.length <= 55) return t.unshift(128 + t.length), t;
+ let n = Iy(t.length);
+ return n.unshift(183 + n.length), n.concat(t);
+}
+var Ry = "0123456789abcdef";
+function zy(e) {
+ let t = "0x";
+ for (let n of Ly(e)) t += Ry[n >> 4], t += Ry[n & 15];
+ return t;
+}
+var By = new Uint8Array(32), Vy = ["then"], Hy = {}, Uy = /* @__PURE__ */ new WeakMap();
+function Wy(e) {
+ return Uy.get(e);
+}
+function Gy(e, t) {
+ Uy.set(e, t);
+}
+function Ky(e, t) {
+ let n = /* @__PURE__ */ Error(`deferred error during ABI decoding triggered accessing ${e}`);
+ throw n.error = t, n;
+}
+function qy(e, t, n) {
+ return e.indexOf(null) >= 0 ? t.map((e, t) => e instanceof Jy ? qy(Wy(e), e, n) : e) : e.reduce((e, r, i) => {
+ let a = t.getValue(r);
+ return r in e || (n && a instanceof Jy && (a = qy(Wy(a), a, n)), e[r] = a), e;
+ }, {});
+}
+var Jy = class e extends Array {
+ #e;
+ constructor(...e) {
+ let t = e[0], n = e[1], r = (e[2] || []).slice(), i = !0;
+ t !== Hy && (n = e, r = [], i = !1), super(n.length), n.forEach((e, t) => {
+ this[t] = e;
+ });
+ let a = r.reduce((e, t) => (typeof t == "string" && e.set(t, (e.get(t) || 0) + 1), e), /* @__PURE__ */ new Map());
+ if (Gy(this, Object.freeze(n.map((e, t) => {
+ let n = r[t];
+ return n != null && a.get(n) === 1 ? n : null;
+ }))), this.#e = [], this.#e ?? this.#e, !i) return;
+ Object.freeze(this);
+ let o = new Proxy(this, { get: (e, t, n) => {
+ if (typeof t == "string") {
+ if (t.match(/^[0-9]+$/)) {
+ let n = Z(t, "%index");
+ if (n < 0 || n >= this.length) throw RangeError("out of result range");
+ let r = e[n];
+ return r instanceof Error && Ky(`index ${n}`, r), r;
+ }
+ if (Vy.indexOf(t) >= 0) return Reflect.get(e, t, n);
+ let r = e[t];
+ if (r instanceof Function) return function(...t) {
+ return r.apply(this === n ? e : this, t);
+ };
+ if (!(t in e)) return e.getValue.apply(this === n ? e : this, [t]);
+ }
+ return Reflect.get(e, t, n);
+ } });
+ return Gy(o, Wy(this)), o;
+ }
+ toArray(t) {
+ let n = [];
+ return this.forEach((r, i) => {
+ r instanceof Error && Ky(`index ${i}`, r), t && r instanceof e && (r = r.toArray(t)), n.push(r);
+ }), n;
+ }
+ toObject(e) {
+ let t = Wy(this);
+ return t.reduce((n, r, i) => (K(r != null, `value at index ${i} unnamed`, "UNSUPPORTED_OPERATION", { operation: "toObject()" }), qy(t, this, e)), {});
+ }
+ slice(t, n) {
+ t ??= 0, t < 0 && (t += this.length, t < 0 && (t = 0)), n ??= this.length, n < 0 && (n += this.length, n < 0 && (n = 0)), n > this.length && (n = this.length);
+ let r = Wy(this), i = [], a = [];
+ for (let e = t; e < n; e++) i.push(this[e]), a.push(r[e]);
+ return new e(Hy, i, a);
+ }
+ filter(t, n) {
+ let r = Wy(this), i = [], a = [];
+ for (let e = 0; e < this.length; e++) {
+ let o = this[e];
+ o instanceof Error && Ky(`index ${e}`, o), t.call(n, o, e, this) && (i.push(o), a.push(r[e]));
+ }
+ return new e(Hy, i, a);
+ }
+ map(e, t) {
+ let n = [];
+ for (let r = 0; r < this.length; r++) {
+ let i = this[r];
+ i instanceof Error && Ky(`index ${r}`, i), n.push(e.call(t, i, r, this));
+ }
+ return n;
+ }
+ getValue(e) {
+ let t = Wy(this).indexOf(e);
+ if (t === -1) return;
+ let n = this[t];
+ return n instanceof Error && Ky(`property ${JSON.stringify(e)}`, n.error), n;
+ }
+ static fromItems(t, n) {
+ return new e(Hy, t, n);
+ }
+};
+function Yy(e) {
+ let t = Zv(e);
+ return K(t.length <= 32, "value out-of-bounds", "BUFFER_OVERRUN", {
+ buffer: t,
+ length: 32,
+ offset: t.length
+ }), t.length !== 32 && (t = Av(Pv([By.slice(t.length % 32), t]))), t;
+}
+var Xy = class {
+ name;
+ type;
+ localName;
+ dynamic;
+ constructor(e, t, n, r) {
+ G(this, {
+ name: e,
+ type: t,
+ localName: n,
+ dynamic: r
+ }, {
+ name: "string",
+ type: "string",
+ localName: "string",
+ dynamic: "boolean"
+ });
+ }
+ _throwError(e, t) {
+ q(!1, e, this.localName, t);
+ }
+}, Zy = class {
+ #e;
+ #t;
+ constructor() {
+ this.#e = [], this.#t = 0;
+ }
+ get data() {
+ return Pv(this.#e);
+ }
+ get length() {
+ return this.#t;
+ }
+ #n(e) {
+ return this.#e.push(e), this.#t += e.length, e.length;
+ }
+ appendWriter(e) {
+ return this.#n(Av(e.data));
+ }
+ writeBytes(e) {
+ let t = Av(e), n = t.length % 32;
+ return n && (t = Av(Pv([t, By.slice(n)]))), this.#n(t);
+ }
+ writeValue(e) {
+ return this.#n(Yy(e));
+ }
+ writeUpdatableValue() {
+ let e = this.#e.length;
+ return this.#e.push(By), this.#t += 32, (t) => {
+ this.#e[e] = Yy(t);
+ };
+ }
+}, Qy = class e {
+ allowLoose;
+ #e;
+ #t;
+ #n;
+ #r;
+ #i;
+ constructor(e, t, n) {
+ G(this, { allowLoose: !!t }), this.#e = Av(e), this.#n = 0, this.#r = null, this.#i = n ?? 1024, this.#t = 0;
+ }
+ get data() {
+ return Y(this.#e);
+ }
+ get dataLength() {
+ return this.#e.length;
+ }
+ get consumed() {
+ return this.#t;
+ }
+ get bytes() {
+ return new Uint8Array(this.#e);
+ }
+ #a(e) {
+ if (this.#r) return this.#r.#a(e);
+ this.#n += e, K(this.#i < 1 || this.#n <= this.#i * this.dataLength, `compressed ABI data exceeds inflation ratio of ${this.#i} ( see: https:/\/github.com/ethers-io/ethers.js/issues/4537 )`, "BUFFER_OVERRUN", {
+ buffer: Av(this.#e),
+ offset: this.#t,
+ length: e,
+ info: {
+ bytesRead: this.#n,
+ dataLength: this.dataLength
+ }
+ });
+ }
+ #o(e, t, n) {
+ let r = Math.ceil(t / 32) * 32;
+ return this.#t + r > this.#e.length && (this.allowLoose && n && this.#t + t <= this.#e.length ? r = t : K(!1, "data out-of-bounds", "BUFFER_OVERRUN", {
+ buffer: Av(this.#e),
+ length: this.#e.length,
+ offset: this.#t + r
+ })), this.#e.slice(this.#t, this.#t + r);
+ }
+ subReader(t) {
+ let n = new e(this.#e.slice(this.#t + t), this.allowLoose, this.#i);
+ return n.#r = this, n;
+ }
+ readBytes(e, t) {
+ let n = this.#o(0, e, !!t);
+ return this.#a(e), this.#t += n.length, n.slice(0, e);
+ }
+ readValue() {
+ return Jv(this.readBytes(32));
+ }
+ readIndex() {
+ return Yv(this.readBytes(32));
+ }
+};
+//#endregion
+//#region node_modules/@noble/hashes/esm/_assert.js
+function $y(e) {
+ if (!Number.isSafeInteger(e) || e < 0) throw Error(`Wrong positive integer: ${e}`);
+}
+function eb(e, ...t) {
+ if (!(e instanceof Uint8Array)) throw Error("Expected Uint8Array");
+ if (t.length > 0 && !t.includes(e.length)) throw Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`);
+}
+function tb(e) {
+ if (typeof e != "function" || typeof e.create != "function") throw Error("Hash should be wrapped by utils.wrapConstructor");
+ $y(e.outputLen), $y(e.blockLen);
+}
+function nb(e, t = !0) {
+ if (e.destroyed) throw Error("Hash instance has been destroyed");
+ if (t && e.finished) throw Error("Hash#digest() has already been called");
+}
+function rb(e, t) {
+ eb(e);
+ let n = t.outputLen;
+ if (e.length < n) throw Error(`digestInto() expects output buffer of length at least ${n}`);
+}
+//#endregion
+//#region node_modules/@noble/hashes/esm/crypto.js
+var ib = typeof globalThis == "object" && "crypto" in globalThis ? globalThis.crypto : void 0, ab = (e) => e instanceof Uint8Array, ob = (e) => new Uint32Array(e.buffer, e.byteOffset, Math.floor(e.byteLength / 4)), sb = (e) => new DataView(e.buffer, e.byteOffset, e.byteLength), cb = (e, t) => e << 32 - t | e >>> t;
+if (new Uint8Array(new Uint32Array([287454020]).buffer)[0] !== 68) throw Error("Non little-endian hardware is not supported");
+function lb(e) {
+ if (typeof e != "string") throw Error(`utf8ToBytes expected string, got ${typeof e}`);
+ return new Uint8Array(new TextEncoder().encode(e));
+}
+function ub(e) {
+ if (typeof e == "string" && (e = lb(e)), !ab(e)) throw Error(`expected Uint8Array, got ${typeof e}`);
+ return e;
+}
+function db(...e) {
+ let t = new Uint8Array(e.reduce((e, t) => e + t.length, 0)), n = 0;
+ return e.forEach((e) => {
+ if (!ab(e)) throw Error("Uint8Array expected");
+ t.set(e, n), n += e.length;
+ }), t;
+}
+var fb = class {
+ clone() {
+ return this._cloneInto();
+ }
+};
+({}).toString;
+function pb(e) {
+ let t = (t) => e().update(ub(t)).digest(), n = e();
+ return t.outputLen = n.outputLen, t.blockLen = n.blockLen, t.create = () => e(), t;
+}
+function mb(e = 32) {
+ if (ib && typeof ib.getRandomValues == "function") return ib.getRandomValues(new Uint8Array(e));
+ throw Error("crypto.getRandomValues must be defined");
+}
+//#endregion
+//#region node_modules/@noble/hashes/esm/hmac.js
+var hb = class extends fb {
+ constructor(e, t) {
+ super(), this.finished = !1, this.destroyed = !1, tb(e);
+ let n = ub(t);
+ if (this.iHash = e.create(), typeof this.iHash.update != "function") throw Error("Expected instance of class which extends utils.Hash");
+ this.blockLen = this.iHash.blockLen, this.outputLen = this.iHash.outputLen;
+ let r = this.blockLen, i = new Uint8Array(r);
+ i.set(n.length > r ? e.create().update(n).digest() : n);
+ for (let e = 0; e < i.length; e++) i[e] ^= 54;
+ this.iHash.update(i), this.oHash = e.create();
+ for (let e = 0; e < i.length; e++) i[e] ^= 106;
+ this.oHash.update(i), i.fill(0);
+ }
+ update(e) {
+ return nb(this), this.iHash.update(e), this;
+ }
+ digestInto(e) {
+ nb(this), eb(e, this.outputLen), this.finished = !0, this.iHash.digestInto(e), this.oHash.update(e), this.oHash.digestInto(e), this.destroy();
+ }
+ digest() {
+ let e = new Uint8Array(this.oHash.outputLen);
+ return this.digestInto(e), e;
+ }
+ _cloneInto(e) {
+ e ||= Object.create(Object.getPrototypeOf(this), {});
+ let { oHash: t, iHash: n, finished: r, destroyed: i, blockLen: a, outputLen: o } = this;
+ return e = e, e.finished = r, e.destroyed = i, e.blockLen = a, e.outputLen = o, e.oHash = t._cloneInto(e.oHash), e.iHash = n._cloneInto(e.iHash), e;
+ }
+ destroy() {
+ this.destroyed = !0, this.oHash.destroy(), this.iHash.destroy();
+ }
+}, gb = (e, t, n) => new hb(e, t).update(n).digest();
+gb.create = (e, t) => new hb(e, t);
+//#endregion
+//#region node_modules/@noble/hashes/esm/_sha2.js
+function _b(e, t, n, r) {
+ if (typeof e.setBigUint64 == "function") return e.setBigUint64(t, n, r);
+ let i = BigInt(32), a = BigInt(4294967295), o = Number(n >> i & a), s = Number(n & a), c = r ? 4 : 0, l = r ? 0 : 4;
+ e.setUint32(t + c, o, r), e.setUint32(t + l, s, r);
+}
+var vb = class extends fb {
+ constructor(e, t, n, r) {
+ super(), this.blockLen = e, this.outputLen = t, this.padOffset = n, this.isLE = r, this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.buffer = new Uint8Array(e), this.view = sb(this.buffer);
+ }
+ update(e) {
+ nb(this);
+ let { view: t, buffer: n, blockLen: r } = this;
+ e = ub(e);
+ let i = e.length;
+ for (let a = 0; a < i;) {
+ let o = Math.min(r - this.pos, i - a);
+ if (o === r) {
+ let t = sb(e);
+ for (; r <= i - a; a += r) this.process(t, a);
+ continue;
+ }
+ n.set(e.subarray(a, a + o), this.pos), this.pos += o, a += o, this.pos === r && (this.process(t, 0), this.pos = 0);
+ }
+ return this.length += e.length, this.roundClean(), this;
+ }
+ digestInto(e) {
+ nb(this), rb(e, this), this.finished = !0;
+ let { buffer: t, view: n, blockLen: r, isLE: i } = this, { pos: a } = this;
+ t[a++] = 128, this.buffer.subarray(a).fill(0), this.padOffset > r - a && (this.process(n, 0), a = 0);
+ for (let e = a; e < r; e++) t[e] = 0;
+ _b(n, r - 8, BigInt(this.length * 8), i), this.process(n, 0);
+ let o = sb(e), s = this.outputLen;
+ if (s % 4) throw Error("_sha2: outputLen should be aligned to 32bit");
+ let c = s / 4, l = this.get();
+ if (c > l.length) throw Error("_sha2: outputLen bigger than state");
+ for (let e = 0; e < c; e++) o.setUint32(4 * e, l[e], i);
+ }
+ digest() {
+ let { buffer: e, outputLen: t } = this;
+ this.digestInto(e);
+ let n = e.slice(0, t);
+ return this.destroy(), n;
+ }
+ _cloneInto(e) {
+ e ||= new this.constructor(), e.set(...this.get());
+ let { blockLen: t, buffer: n, length: r, finished: i, destroyed: a, pos: o } = this;
+ return e.length = r, e.pos = o, e.finished = i, e.destroyed = a, r % t && e.buffer.set(n), e;
+ }
+}, yb = (e, t, n) => e & t ^ ~e & n, bb = (e, t, n) => e & t ^ e & n ^ t & n, xb = /* @__PURE__ */ new Uint32Array([
+ 1116352408,
+ 1899447441,
+ 3049323471,
+ 3921009573,
+ 961987163,
+ 1508970993,
+ 2453635748,
+ 2870763221,
+ 3624381080,
+ 310598401,
+ 607225278,
+ 1426881987,
+ 1925078388,
+ 2162078206,
+ 2614888103,
+ 3248222580,
+ 3835390401,
+ 4022224774,
+ 264347078,
+ 604807628,
+ 770255983,
+ 1249150122,
+ 1555081692,
+ 1996064986,
+ 2554220882,
+ 2821834349,
+ 2952996808,
+ 3210313671,
+ 3336571891,
+ 3584528711,
+ 113926993,
+ 338241895,
+ 666307205,
+ 773529912,
+ 1294757372,
+ 1396182291,
+ 1695183700,
+ 1986661051,
+ 2177026350,
+ 2456956037,
+ 2730485921,
+ 2820302411,
+ 3259730800,
+ 3345764771,
+ 3516065817,
+ 3600352804,
+ 4094571909,
+ 275423344,
+ 430227734,
+ 506948616,
+ 659060556,
+ 883997877,
+ 958139571,
+ 1322822218,
+ 1537002063,
+ 1747873779,
+ 1955562222,
+ 2024104815,
+ 2227730452,
+ 2361852424,
+ 2428436474,
+ 2756734187,
+ 3204031479,
+ 3329325298
+]), Sb = /* @__PURE__ */ new Uint32Array([
+ 1779033703,
+ 3144134277,
+ 1013904242,
+ 2773480762,
+ 1359893119,
+ 2600822924,
+ 528734635,
+ 1541459225
+]), Cb = /* @__PURE__ */ new Uint32Array(64), wb = class extends vb {
+ constructor() {
+ super(64, 32, 8, !1), this.A = Sb[0] | 0, this.B = Sb[1] | 0, this.C = Sb[2] | 0, this.D = Sb[3] | 0, this.E = Sb[4] | 0, this.F = Sb[5] | 0, this.G = Sb[6] | 0, this.H = Sb[7] | 0;
+ }
+ get() {
+ let { A: e, B: t, C: n, D: r, E: i, F: a, G: o, H: s } = this;
+ return [
+ e,
+ t,
+ n,
+ r,
+ i,
+ a,
+ o,
+ s
+ ];
+ }
+ set(e, t, n, r, i, a, o, s) {
+ this.A = e | 0, this.B = t | 0, this.C = n | 0, this.D = r | 0, this.E = i | 0, this.F = a | 0, this.G = o | 0, this.H = s | 0;
+ }
+ process(e, t) {
+ for (let n = 0; n < 16; n++, t += 4) Cb[n] = e.getUint32(t, !1);
+ for (let e = 16; e < 64; e++) {
+ let t = Cb[e - 15], n = Cb[e - 2], r = cb(t, 7) ^ cb(t, 18) ^ t >>> 3;
+ Cb[e] = (cb(n, 17) ^ cb(n, 19) ^ n >>> 10) + Cb[e - 7] + r + Cb[e - 16] | 0;
+ }
+ let { A: n, B: r, C: i, D: a, E: o, F: s, G: c, H: l } = this;
+ for (let e = 0; e < 64; e++) {
+ let t = cb(o, 6) ^ cb(o, 11) ^ cb(o, 25), u = l + t + yb(o, s, c) + xb[e] + Cb[e] | 0, d = (cb(n, 2) ^ cb(n, 13) ^ cb(n, 22)) + bb(n, r, i) | 0;
+ l = c, c = s, s = o, o = a + u | 0, a = i, i = r, r = n, n = u + d | 0;
+ }
+ n = n + this.A | 0, r = r + this.B | 0, i = i + this.C | 0, a = a + this.D | 0, o = o + this.E | 0, s = s + this.F | 0, c = c + this.G | 0, l = l + this.H | 0, this.set(n, r, i, a, o, s, c, l);
+ }
+ roundClean() {
+ Cb.fill(0);
+ }
+ destroy() {
+ this.set(0, 0, 0, 0, 0, 0, 0, 0), this.buffer.fill(0);
+ }
+}, Tb = /* @__PURE__ */ pb(() => new wb()), Eb = /* @__PURE__ */ BigInt(2 ** 32 - 1), Db = /* @__PURE__ */ BigInt(32);
+function Ob(e, t = !1) {
+ return t ? {
+ h: Number(e & Eb),
+ l: Number(e >> Db & Eb)
+ } : {
+ h: Number(e >> Db & Eb) | 0,
+ l: Number(e & Eb) | 0
+ };
+}
+function kb(e, t = !1) {
+ let n = new Uint32Array(e.length), r = new Uint32Array(e.length);
+ for (let i = 0; i < e.length; i++) {
+ let { h: a, l: o } = Ob(e[i], t);
+ [n[i], r[i]] = [a, o];
+ }
+ return [n, r];
+}
+var Ab = (e, t) => BigInt(e >>> 0) << Db | BigInt(t >>> 0), jb = (e, t, n) => e >>> n, Mb = (e, t, n) => e << 32 - n | t >>> n, Nb = (e, t, n) => e >>> n | t << 32 - n, Pb = (e, t, n) => e << 32 - n | t >>> n, Fb = (e, t, n) => e << 64 - n | t >>> n - 32, Ib = (e, t, n) => e >>> n - 32 | t << 64 - n, Lb = (e, t) => t, Rb = (e, t) => e, zb = (e, t, n) => e << n | t >>> 32 - n, Bb = (e, t, n) => t << n | e >>> 32 - n, Vb = (e, t, n) => t << n - 32 | e >>> 64 - n, Hb = (e, t, n) => e << n - 32 | t >>> 64 - n;
+function Ub(e, t, n, r) {
+ let i = (t >>> 0) + (r >>> 0);
+ return {
+ h: e + n + (i / 2 ** 32 | 0) | 0,
+ l: i | 0
+ };
+}
+var Q = {
+ fromBig: Ob,
+ split: kb,
+ toBig: Ab,
+ shrSH: jb,
+ shrSL: Mb,
+ rotrSH: Nb,
+ rotrSL: Pb,
+ rotrBH: Fb,
+ rotrBL: Ib,
+ rotr32H: Lb,
+ rotr32L: Rb,
+ rotlSH: zb,
+ rotlSL: Bb,
+ rotlBH: Vb,
+ rotlBL: Hb,
+ add: Ub,
+ add3L: (e, t, n) => (e >>> 0) + (t >>> 0) + (n >>> 0),
+ add3H: (e, t, n, r) => t + n + r + (e / 2 ** 32 | 0) | 0,
+ add4L: (e, t, n, r) => (e >>> 0) + (t >>> 0) + (n >>> 0) + (r >>> 0),
+ add4H: (e, t, n, r, i) => t + n + r + i + (e / 2 ** 32 | 0) | 0,
+ add5H: (e, t, n, r, i, a) => t + n + r + i + a + (e / 2 ** 32 | 0) | 0,
+ add5L: (e, t, n, r, i) => (e >>> 0) + (t >>> 0) + (n >>> 0) + (r >>> 0) + (i >>> 0)
+}, [Wb, Gb] = Q.split((/* @__PURE__ */ "0x428a2f98d728ae22.0x7137449123ef65cd.0xb5c0fbcfec4d3b2f.0xe9b5dba58189dbbc.0x3956c25bf348b538.0x59f111f1b605d019.0x923f82a4af194f9b.0xab1c5ed5da6d8118.0xd807aa98a3030242.0x12835b0145706fbe.0x243185be4ee4b28c.0x550c7dc3d5ffb4e2.0x72be5d74f27b896f.0x80deb1fe3b1696b1.0x9bdc06a725c71235.0xc19bf174cf692694.0xe49b69c19ef14ad2.0xefbe4786384f25e3.0x0fc19dc68b8cd5b5.0x240ca1cc77ac9c65.0x2de92c6f592b0275.0x4a7484aa6ea6e483.0x5cb0a9dcbd41fbd4.0x76f988da831153b5.0x983e5152ee66dfab.0xa831c66d2db43210.0xb00327c898fb213f.0xbf597fc7beef0ee4.0xc6e00bf33da88fc2.0xd5a79147930aa725.0x06ca6351e003826f.0x142929670a0e6e70.0x27b70a8546d22ffc.0x2e1b21385c26c926.0x4d2c6dfc5ac42aed.0x53380d139d95b3df.0x650a73548baf63de.0x766a0abb3c77b2a8.0x81c2c92e47edaee6.0x92722c851482353b.0xa2bfe8a14cf10364.0xa81a664bbc423001.0xc24b8b70d0f89791.0xc76c51a30654be30.0xd192e819d6ef5218.0xd69906245565a910.0xf40e35855771202a.0x106aa07032bbd1b8.0x19a4c116b8d2d0c8.0x1e376c085141ab53.0x2748774cdf8eeb99.0x34b0bcb5e19b48a8.0x391c0cb3c5c95a63.0x4ed8aa4ae3418acb.0x5b9cca4f7763e373.0x682e6ff3d6b2b8a3.0x748f82ee5defb2fc.0x78a5636f43172f60.0x84c87814a1f0ab72.0x8cc702081a6439ec.0x90befffa23631e28.0xa4506cebde82bde9.0xbef9a3f7b2c67915.0xc67178f2e372532b.0xca273eceea26619c.0xd186b8c721c0c207.0xeada7dd6cde0eb1e.0xf57d4f7fee6ed178.0x06f067aa72176fba.0x0a637dc5a2c898a6.0x113f9804bef90dae.0x1b710b35131c471b.0x28db77f523047d84.0x32caab7b40c72493.0x3c9ebe0a15c9bebc.0x431d67c49c100d4c.0x4cc5d4becb3e42b6.0x597f299cfc657e2a.0x5fcb6fab3ad6faec.0x6c44198c4a475817".split(".")).map((e) => BigInt(e))), Kb = /* @__PURE__ */ new Uint32Array(80), qb = /* @__PURE__ */ new Uint32Array(80), Jb = class extends vb {
+ constructor() {
+ super(128, 64, 16, !1), this.Ah = 1779033703, this.Al = -205731576, this.Bh = -1150833019, this.Bl = -2067093701, this.Ch = 1013904242, this.Cl = -23791573, this.Dh = -1521486534, this.Dl = 1595750129, this.Eh = 1359893119, this.El = -1377402159, this.Fh = -1694144372, this.Fl = 725511199, this.Gh = 528734635, this.Gl = -79577749, this.Hh = 1541459225, this.Hl = 327033209;
+ }
+ get() {
+ let { Ah: e, Al: t, Bh: n, Bl: r, Ch: i, Cl: a, Dh: o, Dl: s, Eh: c, El: l, Fh: u, Fl: d, Gh: f, Gl: p, Hh: m, Hl: h } = this;
+ return [
+ e,
+ t,
+ n,
+ r,
+ i,
+ a,
+ o,
+ s,
+ c,
+ l,
+ u,
+ d,
+ f,
+ p,
+ m,
+ h
+ ];
+ }
+ set(e, t, n, r, i, a, o, s, c, l, u, d, f, p, m, h) {
+ this.Ah = e | 0, this.Al = t | 0, this.Bh = n | 0, this.Bl = r | 0, this.Ch = i | 0, this.Cl = a | 0, this.Dh = o | 0, this.Dl = s | 0, this.Eh = c | 0, this.El = l | 0, this.Fh = u | 0, this.Fl = d | 0, this.Gh = f | 0, this.Gl = p | 0, this.Hh = m | 0, this.Hl = h | 0;
+ }
+ process(e, t) {
+ for (let n = 0; n < 16; n++, t += 4) Kb[n] = e.getUint32(t), qb[n] = e.getUint32(t += 4);
+ for (let e = 16; e < 80; e++) {
+ let t = Kb[e - 15] | 0, n = qb[e - 15] | 0, r = Q.rotrSH(t, n, 1) ^ Q.rotrSH(t, n, 8) ^ Q.shrSH(t, n, 7), i = Q.rotrSL(t, n, 1) ^ Q.rotrSL(t, n, 8) ^ Q.shrSL(t, n, 7), a = Kb[e - 2] | 0, o = qb[e - 2] | 0, s = Q.rotrSH(a, o, 19) ^ Q.rotrBH(a, o, 61) ^ Q.shrSH(a, o, 6), c = Q.rotrSL(a, o, 19) ^ Q.rotrBL(a, o, 61) ^ Q.shrSL(a, o, 6), l = Q.add4L(i, c, qb[e - 7], qb[e - 16]);
+ Kb[e] = Q.add4H(l, r, s, Kb[e - 7], Kb[e - 16]) | 0, qb[e] = l | 0;
+ }
+ let { Ah: n, Al: r, Bh: i, Bl: a, Ch: o, Cl: s, Dh: c, Dl: l, Eh: u, El: d, Fh: f, Fl: p, Gh: m, Gl: h, Hh: g, Hl: _ } = this;
+ for (let e = 0; e < 80; e++) {
+ let t = Q.rotrSH(u, d, 14) ^ Q.rotrSH(u, d, 18) ^ Q.rotrBH(u, d, 41), v = Q.rotrSL(u, d, 14) ^ Q.rotrSL(u, d, 18) ^ Q.rotrBL(u, d, 41), y = u & f ^ ~u & m, b = d & p ^ ~d & h, x = Q.add5L(_, v, b, Gb[e], qb[e]), S = Q.add5H(x, g, t, y, Wb[e], Kb[e]), C = x | 0, w = Q.rotrSH(n, r, 28) ^ Q.rotrBH(n, r, 34) ^ Q.rotrBH(n, r, 39), T = Q.rotrSL(n, r, 28) ^ Q.rotrBL(n, r, 34) ^ Q.rotrBL(n, r, 39), E = n & i ^ n & o ^ i & o, D = r & a ^ r & s ^ a & s;
+ g = m | 0, _ = h | 0, m = f | 0, h = p | 0, f = u | 0, p = d | 0, {h: u, l: d} = Q.add(c | 0, l | 0, S | 0, C | 0), c = o | 0, l = s | 0, o = i | 0, s = a | 0, i = n | 0, a = r | 0;
+ let O = Q.add3L(C, T, D);
+ n = Q.add3H(O, S, w, E), r = O | 0;
+ }
+ ({h: n, l: r} = Q.add(this.Ah | 0, this.Al | 0, n | 0, r | 0)), {h: i, l: a} = Q.add(this.Bh | 0, this.Bl | 0, i | 0, a | 0), {h: o, l: s} = Q.add(this.Ch | 0, this.Cl | 0, o | 0, s | 0), {h: c, l: l} = Q.add(this.Dh | 0, this.Dl | 0, c | 0, l | 0), {h: u, l: d} = Q.add(this.Eh | 0, this.El | 0, u | 0, d | 0), {h: f, l: p} = Q.add(this.Fh | 0, this.Fl | 0, f | 0, p | 0), {h: m, l: h} = Q.add(this.Gh | 0, this.Gl | 0, m | 0, h | 0), {h: g, l: _} = Q.add(this.Hh | 0, this.Hl | 0, g | 0, _ | 0), this.set(n, r, i, a, o, s, c, l, u, d, f, p, m, h, g, _);
+ }
+ roundClean() {
+ Kb.fill(0), qb.fill(0);
+ }
+ destroy() {
+ this.buffer.fill(0), this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
+ }
+}, Yb = /* @__PURE__ */ pb(() => new Jb());
+//#endregion
+//#region node_modules/ethers/lib.esm/crypto/crypto-browser.js
+function Xb() {
+ if (typeof self < "u") return self;
+ if (typeof window < "u") return window;
+ if (typeof global < "u") return global;
+ throw Error("unable to locate global object");
+}
+var Zb = Xb();
+Zb.crypto || Zb.msCrypto;
+function Qb(e) {
+ switch (e) {
+ case "sha256": return Tb.create();
+ case "sha512": return Yb.create();
+ }
+ q(!1, "invalid hashing algorithm name", "algorithm", e);
+}
+//#endregion
+//#region node_modules/@noble/hashes/esm/sha3.js
+var [$b, ex, tx] = [
+ [],
+ [],
+ []
+], nx = /* @__PURE__ */ BigInt(0), rx = /* @__PURE__ */ BigInt(1), ix = /* @__PURE__ */ BigInt(2), ax = /* @__PURE__ */ BigInt(7), ox = /* @__PURE__ */ BigInt(256), sx = /* @__PURE__ */ BigInt(113);
+for (let e = 0, t = rx, n = 1, r = 0; e < 24; e++) {
+ [n, r] = [r, (2 * n + 3 * r) % 5], $b.push(2 * (5 * r + n)), ex.push((e + 1) * (e + 2) / 2 % 64);
+ let i = nx;
+ for (let e = 0; e < 7; e++) t = (t << rx ^ (t >> ax) * sx) % ox, t & ix && (i ^= rx << (rx << /* @__PURE__ */ BigInt(e)) - rx);
+ tx.push(i);
+}
+var [cx, lx] = /* @__PURE__ */ kb(tx, !0), ux = (e, t, n) => n > 32 ? Vb(e, t, n) : zb(e, t, n), dx = (e, t, n) => n > 32 ? Hb(e, t, n) : Bb(e, t, n);
+function fx(e, t = 24) {
+ let n = new Uint32Array(10);
+ for (let r = 24 - t; r < 24; r++) {
+ for (let t = 0; t < 10; t++) n[t] = e[t] ^ e[t + 10] ^ e[t + 20] ^ e[t + 30] ^ e[t + 40];
+ for (let t = 0; t < 10; t += 2) {
+ let r = (t + 8) % 10, i = (t + 2) % 10, a = n[i], o = n[i + 1], s = ux(a, o, 1) ^ n[r], c = dx(a, o, 1) ^ n[r + 1];
+ for (let n = 0; n < 50; n += 10) e[t + n] ^= s, e[t + n + 1] ^= c;
+ }
+ let t = e[2], i = e[3];
+ for (let n = 0; n < 24; n++) {
+ let r = ex[n], a = ux(t, i, r), o = dx(t, i, r), s = $b[n];
+ t = e[s], i = e[s + 1], e[s] = a, e[s + 1] = o;
+ }
+ for (let t = 0; t < 50; t += 10) {
+ for (let r = 0; r < 10; r++) n[r] = e[t + r];
+ for (let r = 0; r < 10; r++) e[t + r] ^= ~n[(r + 2) % 10] & n[(r + 4) % 10];
+ }
+ e[0] ^= cx[r], e[1] ^= lx[r];
+ }
+ n.fill(0);
+}
+var px = class e extends fb {
+ constructor(e, t, n, r = !1, i = 24) {
+ if (super(), this.blockLen = e, this.suffix = t, this.outputLen = n, this.enableXOF = r, this.rounds = i, this.pos = 0, this.posOut = 0, this.finished = !1, this.destroyed = !1, $y(n), 0 >= this.blockLen || this.blockLen >= 200) throw Error("Sha3 supports only keccak-f1600 function");
+ this.state = new Uint8Array(200), this.state32 = ob(this.state);
+ }
+ keccak() {
+ fx(this.state32, this.rounds), this.posOut = 0, this.pos = 0;
+ }
+ update(e) {
+ nb(this);
+ let { blockLen: t, state: n } = this;
+ e = ub(e);
+ let r = e.length;
+ for (let i = 0; i < r;) {
+ let a = Math.min(t - this.pos, r - i);
+ for (let t = 0; t < a; t++) n[this.pos++] ^= e[i++];
+ this.pos === t && this.keccak();
+ }
+ return this;
+ }
+ finish() {
+ if (this.finished) return;
+ this.finished = !0;
+ let { state: e, suffix: t, pos: n, blockLen: r } = this;
+ e[n] ^= t, t & 128 && n === r - 1 && this.keccak(), e[r - 1] ^= 128, this.keccak();
+ }
+ writeInto(e) {
+ nb(this, !1), eb(e), this.finish();
+ let t = this.state, { blockLen: n } = this;
+ for (let r = 0, i = e.length; r < i;) {
+ this.posOut >= n && this.keccak();
+ let a = Math.min(n - this.posOut, i - r);
+ e.set(t.subarray(this.posOut, this.posOut + a), r), this.posOut += a, r += a;
+ }
+ return e;
+ }
+ xofInto(e) {
+ if (!this.enableXOF) throw Error("XOF is not possible for this instance");
+ return this.writeInto(e);
+ }
+ xof(e) {
+ return $y(e), this.xofInto(new Uint8Array(e));
+ }
+ digestInto(e) {
+ if (rb(e, this), this.finished) throw Error("digest() was already called");
+ return this.writeInto(e), this.destroy(), e;
+ }
+ digest() {
+ return this.digestInto(new Uint8Array(this.outputLen));
+ }
+ destroy() {
+ this.destroyed = !0, this.state.fill(0);
+ }
+ _cloneInto(t) {
+ let { blockLen: n, suffix: r, outputLen: i, rounds: a, enableXOF: o } = this;
+ return t ||= new e(n, r, i, o, a), t.state32.set(this.state32), t.pos = this.pos, t.posOut = this.posOut, t.finished = this.finished, t.rounds = a, t.suffix = r, t.outputLen = i, t.enableXOF = o, t.destroyed = this.destroyed, t;
+ }
+}, mx = /* @__PURE__ */ ((e, t, n) => pb(() => new px(t, e, n)))(1, 136, 256 / 8), hx = !1, gx = function(e) {
+ return mx(e);
+}, _x = gx;
+function vx(e) {
+ let t = J(e, "data");
+ return Y(_x(t));
+}
+vx._ = gx, vx.lock = function() {
+ hx = !0;
+}, vx.register = function(e) {
+ if (hx) throw TypeError("keccak256 is locked");
+ _x = e;
+}, Object.freeze(vx);
+//#endregion
+//#region node_modules/ethers/lib.esm/crypto/sha2.js
+var yx = function(e) {
+ return Qb("sha256").update(e).digest();
+}, bx = function(e) {
+ return Qb("sha512").update(e).digest();
+}, xx = yx, Sx = bx, Cx = !1, wx = !1;
+function Tx(e) {
+ let t = J(e, "data");
+ return Y(xx(t));
+}
+Tx._ = yx, Tx.lock = function() {
+ Cx = !0;
+}, Tx.register = function(e) {
+ if (Cx) throw Error("sha256 is locked");
+ xx = e;
+}, Object.freeze(Tx);
+function Ex(e) {
+ let t = J(e, "data");
+ return Y(Sx(t));
+}
+Ex._ = bx, Ex.lock = function() {
+ wx = !0;
+}, Ex.register = function(e) {
+ if (wx) throw Error("sha512 is locked");
+ Sx = e;
+}, Object.freeze(Tx);
+//#endregion
+//#region node_modules/@noble/curves/esm/abstract/utils.js
+var Dx = /* @__PURE__ */ t({
+ bitGet: () => qx,
+ bitLen: () => Kx,
+ bitMask: () => Yx,
+ bitSet: () => Jx,
+ bytesToHex: () => Nx,
+ bytesToNumberBE: () => Lx,
+ bytesToNumberLE: () => Rx,
+ concatBytes: () => Ux,
+ createHmacDrbg: () => Qx,
+ ensureBytes: () => Hx,
+ equalBytes: () => Wx,
+ hexToBytes: () => Ix,
+ hexToNumber: () => Fx,
+ numberToBytesBE: () => zx,
+ numberToBytesLE: () => Bx,
+ numberToHexUnpadded: () => Px,
+ numberToVarBytesBE: () => Vx,
+ utf8ToBytes: () => Gx,
+ validateObject: () => eS
+}), Ox = BigInt(0), kx = BigInt(1), Ax = BigInt(2), jx = (e) => e instanceof Uint8Array, Mx = /* @__PURE__ */ Array.from({ length: 256 }, (e, t) => t.toString(16).padStart(2, "0"));
+function Nx(e) {
+ if (!jx(e)) throw Error("Uint8Array expected");
+ let t = "";
+ for (let n = 0; n < e.length; n++) t += Mx[e[n]];
+ return t;
+}
+function Px(e) {
+ let t = e.toString(16);
+ return t.length & 1 ? `0${t}` : t;
+}
+function Fx(e) {
+ if (typeof e != "string") throw Error("hex string expected, got " + typeof e);
+ return BigInt(e === "" ? "0" : `0x${e}`);
+}
+function Ix(e) {
+ if (typeof e != "string") throw Error("hex string expected, got " + typeof e);
+ let t = e.length;
+ if (t % 2) throw Error("padded hex string expected, got unpadded hex of length " + t);
+ let n = new Uint8Array(t / 2);
+ for (let t = 0; t < n.length; t++) {
+ let r = t * 2, i = e.slice(r, r + 2), a = Number.parseInt(i, 16);
+ if (Number.isNaN(a) || a < 0) throw Error("Invalid byte sequence");
+ n[t] = a;
+ }
+ return n;
+}
+function Lx(e) {
+ return Fx(Nx(e));
+}
+function Rx(e) {
+ if (!jx(e)) throw Error("Uint8Array expected");
+ return Fx(Nx(Uint8Array.from(e).reverse()));
+}
+function zx(e, t) {
+ return Ix(e.toString(16).padStart(t * 2, "0"));
+}
+function Bx(e, t) {
+ return zx(e, t).reverse();
+}
+function Vx(e) {
+ return Ix(Px(e));
+}
+function Hx(e, t, n) {
+ let r;
+ if (typeof t == "string") try {
+ r = Ix(t);
+ } catch (n) {
+ throw Error(`${e} must be valid hex string, got "${t}". Cause: ${n}`);
+ }
+ else if (jx(t)) r = Uint8Array.from(t);
+ else throw Error(`${e} must be hex string or Uint8Array`);
+ let i = r.length;
+ if (typeof n == "number" && i !== n) throw Error(`${e} expected ${n} bytes, got ${i}`);
+ return r;
+}
+function Ux(...e) {
+ let t = new Uint8Array(e.reduce((e, t) => e + t.length, 0)), n = 0;
+ return e.forEach((e) => {
+ if (!jx(e)) throw Error("Uint8Array expected");
+ t.set(e, n), n += e.length;
+ }), t;
+}
+function Wx(e, t) {
+ if (e.length !== t.length) return !1;
+ for (let n = 0; n < e.length; n++) if (e[n] !== t[n]) return !1;
+ return !0;
+}
+function Gx(e) {
+ if (typeof e != "string") throw Error(`utf8ToBytes expected string, got ${typeof e}`);
+ return new Uint8Array(new TextEncoder().encode(e));
+}
+function Kx(e) {
+ let t;
+ for (t = 0; e > Ox; e >>= kx, t += 1);
+ return t;
+}
+function qx(e, t) {
+ return e >> BigInt(t) & kx;
+}
+var Jx = (e, t, n) => e | (n ? kx : Ox) << BigInt(t), Yx = (e) => (Ax << BigInt(e - 1)) - kx, Xx = (e) => new Uint8Array(e), Zx = (e) => Uint8Array.from(e);
+function Qx(e, t, n) {
+ if (typeof e != "number" || e < 2) throw Error("hashLen must be a number");
+ if (typeof t != "number" || t < 2) throw Error("qByteLen must be a number");
+ if (typeof n != "function") throw Error("hmacFn must be a function");
+ let r = Xx(e), i = Xx(e), a = 0, o = () => {
+ r.fill(1), i.fill(0), a = 0;
+ }, s = (...e) => n(i, r, ...e), c = (e = Xx()) => {
+ i = s(Zx([0]), e), r = s(), e.length !== 0 && (i = s(Zx([1]), e), r = s());
+ }, l = () => {
+ if (a++ >= 1e3) throw Error("drbg: tried 1000 values");
+ let e = 0, n = [];
+ for (; e < t;) {
+ r = s();
+ let t = r.slice();
+ n.push(t), e += r.length;
+ }
+ return Ux(...n);
+ };
+ return (e, t) => {
+ o(), c(e);
+ let n;
+ for (; !(n = t(l()));) c();
+ return o(), n;
+ };
+}
+var $x = {
+ bigint: (e) => typeof e == "bigint",
+ function: (e) => typeof e == "function",
+ boolean: (e) => typeof e == "boolean",
+ string: (e) => typeof e == "string",
+ stringOrUint8Array: (e) => typeof e == "string" || e instanceof Uint8Array,
+ isSafeInteger: (e) => Number.isSafeInteger(e),
+ array: (e) => Array.isArray(e),
+ field: (e, t) => t.Fp.isValid(e),
+ hash: (e) => typeof e == "function" && Number.isSafeInteger(e.outputLen)
+};
+function eS(e, t, n = {}) {
+ let r = (t, n, r) => {
+ let i = $x[n];
+ if (typeof i != "function") throw Error(`Invalid validator "${n}", expected function`);
+ let a = e[t];
+ if (!(r && a === void 0) && !i(a, e)) throw Error(`Invalid param ${String(t)}=${a} (${typeof a}), expected ${n}`);
+ };
+ for (let [e, n] of Object.entries(t)) r(e, n, !1);
+ for (let [e, t] of Object.entries(n)) r(e, t, !0);
+ return e;
+}
+//#endregion
+//#region node_modules/@noble/curves/esm/abstract/modular.js
+var tS = BigInt(0), nS = BigInt(1), rS = BigInt(2), iS = BigInt(3), aS = BigInt(4), oS = BigInt(5), sS = BigInt(8), cS = BigInt(16);
+function lS(e, t) {
+ let n = e % t;
+ return n >= tS ? n : t + n;
+}
+function uS(e, t, n) {
+ if (n <= tS || t < tS) throw Error("Expected power/modulo > 0");
+ if (n === nS) return tS;
+ let r = nS;
+ for (; t > tS;) t & nS && (r = r * e % n), e = e * e % n, t >>= nS;
+ return r;
+}
+function dS(e, t, n) {
+ let r = e;
+ for (; t-- > tS;) r *= r, r %= n;
+ return r;
+}
+function fS(e, t) {
+ if (e === tS || t <= tS) throw Error(`invert: expected positive integers, got n=${e} mod=${t}`);
+ let n = lS(e, t), r = t, i = tS, a = nS, o = nS, s = tS;
+ for (; n !== tS;) {
+ let e = r / n, t = r % n, c = i - o * e, l = a - s * e;
+ r = n, n = t, i = o, a = s, o = c, s = l;
+ }
+ if (r !== nS) throw Error("invert: does not exist");
+ return lS(i, t);
+}
+function pS(e) {
+ let t = (e - nS) / rS, n, r, i;
+ for (n = e - nS, r = 0; n % rS === tS; n /= rS, r++);
+ for (i = rS; i < e && uS(i, t, e) !== e - nS; i++);
+ if (r === 1) {
+ let t = (e + nS) / aS;
+ return function(e, n) {
+ let r = e.pow(n, t);
+ if (!e.eql(e.sqr(r), n)) throw Error("Cannot find square root");
+ return r;
+ };
+ }
+ let a = (n + nS) / rS;
+ return function(e, o) {
+ if (e.pow(o, t) === e.neg(e.ONE)) throw Error("Cannot find square root");
+ let s = r, c = e.pow(e.mul(e.ONE, i), n), l = e.pow(o, a), u = e.pow(o, n);
+ for (; !e.eql(u, e.ONE);) {
+ if (e.eql(u, e.ZERO)) return e.ZERO;
+ let t = 1;
+ for (let n = e.sqr(u); t < s && !e.eql(n, e.ONE); t++) n = e.sqr(n);
+ let n = e.pow(c, nS << BigInt(s - t - 1));
+ c = e.sqr(n), l = e.mul(l, n), u = e.mul(u, c), s = t;
+ }
+ return l;
+ };
+}
+function mS(e) {
+ if (e % aS === iS) {
+ let t = (e + nS) / aS;
+ return function(e, n) {
+ let r = e.pow(n, t);
+ if (!e.eql(e.sqr(r), n)) throw Error("Cannot find square root");
+ return r;
+ };
+ }
+ if (e % sS === oS) {
+ let t = (e - oS) / sS;
+ return function(e, n) {
+ let r = e.mul(n, rS), i = e.pow(r, t), a = e.mul(n, i), o = e.mul(e.mul(a, rS), i), s = e.mul(a, e.sub(o, e.ONE));
+ if (!e.eql(e.sqr(s), n)) throw Error("Cannot find square root");
+ return s;
+ };
+ }
+ return e % cS, pS(e);
+}
+var hS = [
+ "create",
+ "isValid",
+ "is0",
+ "neg",
+ "inv",
+ "sqrt",
+ "sqr",
+ "eql",
+ "add",
+ "sub",
+ "mul",
+ "pow",
+ "div",
+ "addN",
+ "subN",
+ "mulN",
+ "sqrN"
+];
+function gS(e) {
+ return eS(e, hS.reduce((e, t) => (e[t] = "function", e), {
+ ORDER: "bigint",
+ MASK: "bigint",
+ BYTES: "isSafeInteger",
+ BITS: "isSafeInteger"
+ }));
+}
+function _S(e, t, n) {
+ if (n < tS) throw Error("Expected power > 0");
+ if (n === tS) return e.ONE;
+ if (n === nS) return t;
+ let r = e.ONE, i = t;
+ for (; n > tS;) n & nS && (r = e.mul(r, i)), i = e.sqr(i), n >>= nS;
+ return r;
+}
+function vS(e, t) {
+ let n = Array(t.length), r = t.reduce((t, r, i) => e.is0(r) ? t : (n[i] = t, e.mul(t, r)), e.ONE), i = e.inv(r);
+ return t.reduceRight((t, r, i) => e.is0(r) ? t : (n[i] = e.mul(t, n[i]), e.mul(t, r)), i), n;
+}
+function yS(e, t) {
+ let n = t === void 0 ? e.toString(2).length : t;
+ return {
+ nBitLength: n,
+ nByteLength: Math.ceil(n / 8)
+ };
+}
+function bS(e, t, n = !1, r = {}) {
+ if (e <= tS) throw Error(`Expected Field ORDER > 0, got ${e}`);
+ let { nBitLength: i, nByteLength: a } = yS(e, t);
+ if (a > 2048) throw Error("Field lengths over 2048 bytes are not supported");
+ let o = mS(e), s = Object.freeze({
+ ORDER: e,
+ BITS: i,
+ BYTES: a,
+ MASK: Yx(i),
+ ZERO: tS,
+ ONE: nS,
+ create: (t) => lS(t, e),
+ isValid: (t) => {
+ if (typeof t != "bigint") throw Error(`Invalid field element: expected bigint, got ${typeof t}`);
+ return tS <= t && t < e;
+ },
+ is0: (e) => e === tS,
+ isOdd: (e) => (e & nS) === nS,
+ neg: (t) => lS(-t, e),
+ eql: (e, t) => e === t,
+ sqr: (t) => lS(t * t, e),
+ add: (t, n) => lS(t + n, e),
+ sub: (t, n) => lS(t - n, e),
+ mul: (t, n) => lS(t * n, e),
+ pow: (e, t) => _S(s, e, t),
+ div: (t, n) => lS(t * fS(n, e), e),
+ sqrN: (e) => e * e,
+ addN: (e, t) => e + t,
+ subN: (e, t) => e - t,
+ mulN: (e, t) => e * t,
+ inv: (t) => fS(t, e),
+ sqrt: r.sqrt || ((e) => o(s, e)),
+ invertBatch: (e) => vS(s, e),
+ cmov: (e, t, n) => n ? t : e,
+ toBytes: (e) => n ? Bx(e, a) : zx(e, a),
+ fromBytes: (e) => {
+ if (e.length !== a) throw Error(`Fp.fromBytes: expected ${a}, got ${e.length}`);
+ return n ? Rx(e) : Lx(e);
+ }
+ });
+ return Object.freeze(s);
+}
+function xS(e) {
+ if (typeof e != "bigint") throw Error("field order must be bigint");
+ let t = e.toString(2).length;
+ return Math.ceil(t / 8);
+}
+function SS(e) {
+ let t = xS(e);
+ return t + Math.ceil(t / 2);
+}
+function CS(e, t, n = !1) {
+ let r = e.length, i = xS(t), a = SS(t);
+ if (r < 16 || r < a || r > 1024) throw Error(`expected ${a}-1024 bytes of input, got ${r}`);
+ let o = lS(n ? Lx(e) : Rx(e), t - nS) + nS;
+ return n ? Bx(o, i) : zx(o, i);
+}
+//#endregion
+//#region node_modules/@noble/curves/esm/abstract/curve.js
+var wS = BigInt(0), TS = BigInt(1);
+function ES(e, t) {
+ let n = (e, t) => {
+ let n = t.negate();
+ return e ? n : t;
+ }, r = (e) => ({
+ windows: Math.ceil(t / e) + 1,
+ windowSize: 2 ** (e - 1)
+ });
+ return {
+ constTimeNegate: n,
+ unsafeLadder(t, n) {
+ let r = e.ZERO, i = t;
+ for (; n > wS;) n & TS && (r = r.add(i)), i = i.double(), n >>= TS;
+ return r;
+ },
+ precomputeWindow(e, t) {
+ let { windows: n, windowSize: i } = r(t), a = [], o = e, s = o;
+ for (let e = 0; e < n; e++) {
+ s = o, a.push(s);
+ for (let e = 1; e < i; e++) s = s.add(o), a.push(s);
+ o = s.double();
+ }
+ return a;
+ },
+ wNAF(t, i, a) {
+ let { windows: o, windowSize: s } = r(t), c = e.ZERO, l = e.BASE, u = BigInt(2 ** t - 1), d = 2 ** t, f = BigInt(t);
+ for (let e = 0; e < o; e++) {
+ let t = e * s, r = Number(a & u);
+ a >>= f, r > s && (r -= d, a += TS);
+ let o = t, p = t + Math.abs(r) - 1, m = e % 2 != 0, h = r < 0;
+ r === 0 ? l = l.add(n(m, i[o])) : c = c.add(n(h, i[p]));
+ }
+ return {
+ p: c,
+ f: l
+ };
+ },
+ wNAFCached(e, t, n, r) {
+ let i = e._WINDOW_SIZE || 1, a = t.get(e);
+ return a || (a = this.precomputeWindow(e, i), i !== 1 && t.set(e, r(a))), this.wNAF(i, a, n);
+ }
+ };
+}
+function DS(e) {
+ return gS(e.Fp), eS(e, {
+ n: "bigint",
+ h: "bigint",
+ Gx: "field",
+ Gy: "field"
+ }, {
+ nBitLength: "isSafeInteger",
+ nByteLength: "isSafeInteger"
+ }), Object.freeze({
+ ...yS(e.n, e.nBitLength),
+ ...e,
+ p: e.Fp.ORDER
+ });
+}
+//#endregion
+//#region node_modules/@noble/curves/esm/abstract/weierstrass.js
+function OS(e) {
+ let t = DS(e);
+ eS(t, {
+ a: "field",
+ b: "field"
+ }, {
+ allowedPrivateKeyLengths: "array",
+ wrapPrivateKey: "boolean",
+ isTorsionFree: "function",
+ clearCofactor: "function",
+ allowInfinityPoint: "boolean",
+ fromBytes: "function",
+ toBytes: "function"
+ });
+ let { endo: n, Fp: r, a: i } = t;
+ if (n) {
+ if (!r.eql(i, r.ZERO)) throw Error("Endomorphism can only be defined for Koblitz curves that have a=0");
+ if (typeof n != "object" || typeof n.beta != "bigint" || typeof n.splitScalar != "function") throw Error("Expected endomorphism with beta: bigint and splitScalar: function");
+ }
+ return Object.freeze({ ...t });
+}
+var { bytesToNumberBE: kS, hexToBytes: AS } = Dx, jS = {
+ Err: class extends Error {
+ constructor(e = "") {
+ super(e);
+ }
+ },
+ _parseInt(e) {
+ let { Err: t } = jS;
+ if (e.length < 2 || e[0] !== 2) throw new t("Invalid signature integer tag");
+ let n = e[1], r = e.subarray(2, n + 2);
+ if (!n || r.length !== n) throw new t("Invalid signature integer: wrong length");
+ if (r[0] & 128) throw new t("Invalid signature integer: negative");
+ if (r[0] === 0 && !(r[1] & 128)) throw new t("Invalid signature integer: unnecessary leading zero");
+ return {
+ d: kS(r),
+ l: e.subarray(n + 2)
+ };
+ },
+ toSig(e) {
+ let { Err: t } = jS, n = typeof e == "string" ? AS(e) : e;
+ if (!(n instanceof Uint8Array)) throw Error("ui8a expected");
+ let r = n.length;
+ if (r < 2 || n[0] != 48) throw new t("Invalid signature tag");
+ if (n[1] !== r - 2) throw new t("Invalid signature: incorrect length");
+ let { d: i, l: a } = jS._parseInt(n.subarray(2)), { d: o, l: s } = jS._parseInt(a);
+ if (s.length) throw new t("Invalid signature: left bytes after parsing");
+ return {
+ r: i,
+ s: o
+ };
+ },
+ hexFromSig(e) {
+ let t = (e) => Number.parseInt(e[0], 16) & 8 ? "00" + e : e, n = (e) => {
+ let t = e.toString(16);
+ return t.length & 1 ? `0${t}` : t;
+ }, r = t(n(e.s)), i = t(n(e.r)), a = r.length / 2, o = i.length / 2, s = n(a), c = n(o);
+ return `30${n(o + a + 4)}02${c}${i}02${s}${r}`;
+ }
+}, MS = BigInt(0), NS = BigInt(1), PS = BigInt(2), FS = BigInt(3), IS = BigInt(4);
+function LS(e) {
+ let t = OS(e), { Fp: n } = t, r = t.toBytes || ((e, t, r) => {
+ let i = t.toAffine();
+ return Ux(Uint8Array.from([4]), n.toBytes(i.x), n.toBytes(i.y));
+ }), i = t.fromBytes || ((e) => {
+ let t = e.subarray(1);
+ return {
+ x: n.fromBytes(t.subarray(0, n.BYTES)),
+ y: n.fromBytes(t.subarray(n.BYTES, 2 * n.BYTES))
+ };
+ });
+ function a(e) {
+ let { a: r, b: i } = t, a = n.sqr(e), o = n.mul(a, e);
+ return n.add(n.add(o, n.mul(e, r)), i);
+ }
+ if (!n.eql(n.sqr(t.Gy), a(t.Gx))) throw Error("bad generator point: equation left != right");
+ function o(e) {
+ return typeof e == "bigint" && MS < e && e < t.n;
+ }
+ function s(e) {
+ if (!o(e)) throw Error("Expected valid bigint: 0 < bigint < curve.n");
+ }
+ function c(e) {
+ let { allowedPrivateKeyLengths: n, nByteLength: r, wrapPrivateKey: i, n: a } = t;
+ if (n && typeof e != "bigint") {
+ if (e instanceof Uint8Array && (e = Nx(e)), typeof e != "string" || !n.includes(e.length)) throw Error("Invalid key");
+ e = e.padStart(r * 2, "0");
+ }
+ let o;
+ try {
+ o = typeof e == "bigint" ? e : Lx(Hx("private key", e, r));
+ } catch {
+ throw Error(`private key must be ${r} bytes, hex or bigint, not ${typeof e}`);
+ }
+ return i && (o = lS(o, a)), s(o), o;
+ }
+ let l = /* @__PURE__ */ new Map();
+ function u(e) {
+ if (!(e instanceof d)) throw Error("ProjectivePoint expected");
+ }
+ class d {
+ constructor(e, t, r) {
+ if (this.px = e, this.py = t, this.pz = r, e == null || !n.isValid(e)) throw Error("x required");
+ if (t == null || !n.isValid(t)) throw Error("y required");
+ if (r == null || !n.isValid(r)) throw Error("z required");
+ }
+ static fromAffine(e) {
+ let { x: t, y: r } = e || {};
+ if (!e || !n.isValid(t) || !n.isValid(r)) throw Error("invalid affine point");
+ if (e instanceof d) throw Error("projective point not allowed");
+ let i = (e) => n.eql(e, n.ZERO);
+ return i(t) && i(r) ? d.ZERO : new d(t, r, n.ONE);
+ }
+ get x() {
+ return this.toAffine().x;
+ }
+ get y() {
+ return this.toAffine().y;
+ }
+ static normalizeZ(e) {
+ let t = n.invertBatch(e.map((e) => e.pz));
+ return e.map((e, n) => e.toAffine(t[n])).map(d.fromAffine);
+ }
+ static fromHex(e) {
+ let t = d.fromAffine(i(Hx("pointHex", e)));
+ return t.assertValidity(), t;
+ }
+ static fromPrivateKey(e) {
+ return d.BASE.multiply(c(e));
+ }
+ _setWindowSize(e) {
+ this._WINDOW_SIZE = e, l.delete(this);
+ }
+ assertValidity() {
+ if (this.is0()) {
+ if (t.allowInfinityPoint && !n.is0(this.py)) return;
+ throw Error("bad point: ZERO");
+ }
+ let { x: e, y: r } = this.toAffine();
+ if (!n.isValid(e) || !n.isValid(r)) throw Error("bad point: x or y not FE");
+ let i = n.sqr(r), o = a(e);
+ if (!n.eql(i, o)) throw Error("bad point: equation left != right");
+ if (!this.isTorsionFree()) throw Error("bad point: not in prime-order subgroup");
+ }
+ hasEvenY() {
+ let { y: e } = this.toAffine();
+ if (n.isOdd) return !n.isOdd(e);
+ throw Error("Field doesn't support isOdd");
+ }
+ equals(e) {
+ u(e);
+ let { px: t, py: r, pz: i } = this, { px: a, py: o, pz: s } = e, c = n.eql(n.mul(t, s), n.mul(a, i)), l = n.eql(n.mul(r, s), n.mul(o, i));
+ return c && l;
+ }
+ negate() {
+ return new d(this.px, n.neg(this.py), this.pz);
+ }
+ double() {
+ let { a: e, b: r } = t, i = n.mul(r, FS), { px: a, py: o, pz: s } = this, c = n.ZERO, l = n.ZERO, u = n.ZERO, f = n.mul(a, a), p = n.mul(o, o), m = n.mul(s, s), h = n.mul(a, o);
+ return h = n.add(h, h), u = n.mul(a, s), u = n.add(u, u), c = n.mul(e, u), l = n.mul(i, m), l = n.add(c, l), c = n.sub(p, l), l = n.add(p, l), l = n.mul(c, l), c = n.mul(h, c), u = n.mul(i, u), m = n.mul(e, m), h = n.sub(f, m), h = n.mul(e, h), h = n.add(h, u), u = n.add(f, f), f = n.add(u, f), f = n.add(f, m), f = n.mul(f, h), l = n.add(l, f), m = n.mul(o, s), m = n.add(m, m), f = n.mul(m, h), c = n.sub(c, f), u = n.mul(m, p), u = n.add(u, u), u = n.add(u, u), new d(c, l, u);
+ }
+ add(e) {
+ u(e);
+ let { px: r, py: i, pz: a } = this, { px: o, py: s, pz: c } = e, l = n.ZERO, f = n.ZERO, p = n.ZERO, m = t.a, h = n.mul(t.b, FS), g = n.mul(r, o), _ = n.mul(i, s), v = n.mul(a, c), y = n.add(r, i), b = n.add(o, s);
+ y = n.mul(y, b), b = n.add(g, _), y = n.sub(y, b), b = n.add(r, a);
+ let x = n.add(o, c);
+ return b = n.mul(b, x), x = n.add(g, v), b = n.sub(b, x), x = n.add(i, a), l = n.add(s, c), x = n.mul(x, l), l = n.add(_, v), x = n.sub(x, l), p = n.mul(m, b), l = n.mul(h, v), p = n.add(l, p), l = n.sub(_, p), p = n.add(_, p), f = n.mul(l, p), _ = n.add(g, g), _ = n.add(_, g), v = n.mul(m, v), b = n.mul(h, b), _ = n.add(_, v), v = n.sub(g, v), v = n.mul(m, v), b = n.add(b, v), g = n.mul(_, b), f = n.add(f, g), g = n.mul(x, b), l = n.mul(y, l), l = n.sub(l, g), g = n.mul(y, _), p = n.mul(x, p), p = n.add(p, g), new d(l, f, p);
+ }
+ subtract(e) {
+ return this.add(e.negate());
+ }
+ is0() {
+ return this.equals(d.ZERO);
+ }
+ wNAF(e) {
+ return p.wNAFCached(this, l, e, (e) => {
+ let t = n.invertBatch(e.map((e) => e.pz));
+ return e.map((e, n) => e.toAffine(t[n])).map(d.fromAffine);
+ });
+ }
+ multiplyUnsafe(e) {
+ let r = d.ZERO;
+ if (e === MS) return r;
+ if (s(e), e === NS) return this;
+ let { endo: i } = t;
+ if (!i) return p.unsafeLadder(this, e);
+ let { k1neg: a, k1: o, k2neg: c, k2: l } = i.splitScalar(e), u = r, f = r, m = this;
+ for (; o > MS || l > MS;) o & NS && (u = u.add(m)), l & NS && (f = f.add(m)), m = m.double(), o >>= NS, l >>= NS;
+ return a && (u = u.negate()), c && (f = f.negate()), f = new d(n.mul(f.px, i.beta), f.py, f.pz), u.add(f);
+ }
+ multiply(e) {
+ s(e);
+ let r = e, i, a, { endo: o } = t;
+ if (o) {
+ let { k1neg: e, k1: t, k2neg: s, k2: c } = o.splitScalar(r), { p: l, f: u } = this.wNAF(t), { p: f, f: m } = this.wNAF(c);
+ l = p.constTimeNegate(e, l), f = p.constTimeNegate(s, f), f = new d(n.mul(f.px, o.beta), f.py, f.pz), i = l.add(f), a = u.add(m);
+ } else {
+ let { p: e, f: t } = this.wNAF(r);
+ i = e, a = t;
+ }
+ return d.normalizeZ([i, a])[0];
+ }
+ multiplyAndAddUnsafe(e, t, n) {
+ let r = d.BASE, i = (e, t) => t === MS || t === NS || !e.equals(r) ? e.multiplyUnsafe(t) : e.multiply(t), a = i(this, t).add(i(e, n));
+ return a.is0() ? void 0 : a;
+ }
+ toAffine(e) {
+ let { px: t, py: r, pz: i } = this, a = this.is0();
+ e ??= a ? n.ONE : n.inv(i);
+ let o = n.mul(t, e), s = n.mul(r, e), c = n.mul(i, e);
+ if (a) return {
+ x: n.ZERO,
+ y: n.ZERO
+ };
+ if (!n.eql(c, n.ONE)) throw Error("invZ was invalid");
+ return {
+ x: o,
+ y: s
+ };
+ }
+ isTorsionFree() {
+ let { h: e, isTorsionFree: n } = t;
+ if (e === NS) return !0;
+ if (n) return n(d, this);
+ throw Error("isTorsionFree() has not been declared for the elliptic curve");
+ }
+ clearCofactor() {
+ let { h: e, clearCofactor: n } = t;
+ return e === NS ? this : n ? n(d, this) : this.multiplyUnsafe(t.h);
+ }
+ toRawBytes(e = !0) {
+ return this.assertValidity(), r(d, this, e);
+ }
+ toHex(e = !0) {
+ return Nx(this.toRawBytes(e));
+ }
+ }
+ d.BASE = new d(t.Gx, t.Gy, n.ONE), d.ZERO = new d(n.ZERO, n.ONE, n.ZERO);
+ let f = t.nBitLength, p = ES(d, t.endo ? Math.ceil(f / 2) : f);
+ return {
+ CURVE: t,
+ ProjectivePoint: d,
+ normPrivateKeyToScalar: c,
+ weierstrassEquation: a,
+ isWithinCurveOrder: o
+ };
+}
+function RS(e) {
+ let t = DS(e);
+ return eS(t, {
+ hash: "hash",
+ hmac: "function",
+ randomBytes: "function"
+ }, {
+ bits2int: "function",
+ bits2int_modN: "function",
+ lowS: "boolean"
+ }), Object.freeze({
+ lowS: !0,
+ ...t
+ });
+}
+function zS(e) {
+ let t = RS(e), { Fp: n, n: r } = t, i = n.BYTES + 1, a = 2 * n.BYTES + 1;
+ function o(e) {
+ return MS < e && e < n.ORDER;
+ }
+ function s(e) {
+ return lS(e, r);
+ }
+ function c(e) {
+ return fS(e, r);
+ }
+ let { ProjectivePoint: l, normPrivateKeyToScalar: u, weierstrassEquation: d, isWithinCurveOrder: f } = LS({
+ ...t,
+ toBytes(e, t, r) {
+ let i = t.toAffine(), a = n.toBytes(i.x), o = Ux;
+ return r ? o(Uint8Array.from([t.hasEvenY() ? 2 : 3]), a) : o(Uint8Array.from([4]), a, n.toBytes(i.y));
+ },
+ fromBytes(e) {
+ let t = e.length, r = e[0], s = e.subarray(1);
+ if (t === i && (r === 2 || r === 3)) {
+ let e = Lx(s);
+ if (!o(e)) throw Error("Point is not on curve");
+ let t = d(e), i = n.sqrt(t), a = (i & NS) === NS;
+ return (r & 1) == 1 !== a && (i = n.neg(i)), {
+ x: e,
+ y: i
+ };
+ } else if (t === a && r === 4) return {
+ x: n.fromBytes(s.subarray(0, n.BYTES)),
+ y: n.fromBytes(s.subarray(n.BYTES, 2 * n.BYTES))
+ };
+ else throw Error(`Point of length ${t} was invalid. Expected ${i} compressed bytes or ${a} uncompressed bytes`);
+ }
+ }), p = (e) => Nx(zx(e, t.nByteLength));
+ function m(e) {
+ return e > r >> NS;
+ }
+ function h(e) {
+ return m(e) ? s(-e) : e;
+ }
+ let g = (e, t, n) => Lx(e.slice(t, n));
+ class _ {
+ constructor(e, t, n) {
+ this.r = e, this.s = t, this.recovery = n, this.assertValidity();
+ }
+ static fromCompact(e) {
+ let n = t.nByteLength;
+ return e = Hx("compactSignature", e, n * 2), new _(g(e, 0, n), g(e, n, 2 * n));
+ }
+ static fromDER(e) {
+ let { r: t, s: n } = jS.toSig(Hx("DER", e));
+ return new _(t, n);
+ }
+ assertValidity() {
+ if (!f(this.r)) throw Error("r must be 0 < r < CURVE.n");
+ if (!f(this.s)) throw Error("s must be 0 < s < CURVE.n");
+ }
+ addRecoveryBit(e) {
+ return new _(this.r, this.s, e);
+ }
+ recoverPublicKey(e) {
+ let { r, s: i, recovery: a } = this, o = C(Hx("msgHash", e));
+ if (a == null || ![
+ 0,
+ 1,
+ 2,
+ 3
+ ].includes(a)) throw Error("recovery id invalid");
+ let u = a === 2 || a === 3 ? r + t.n : r;
+ if (u >= n.ORDER) throw Error("recovery id 2 or 3 invalid");
+ let d = a & 1 ? "03" : "02", f = l.fromHex(d + p(u)), m = c(u), h = s(-o * m), g = s(i * m), _ = l.BASE.multiplyAndAddUnsafe(f, h, g);
+ if (!_) throw Error("point at infinify");
+ return _.assertValidity(), _;
+ }
+ hasHighS() {
+ return m(this.s);
+ }
+ normalizeS() {
+ return this.hasHighS() ? new _(this.r, s(-this.s), this.recovery) : this;
+ }
+ toDERRawBytes() {
+ return Ix(this.toDERHex());
+ }
+ toDERHex() {
+ return jS.hexFromSig({
+ r: this.r,
+ s: this.s
+ });
+ }
+ toCompactRawBytes() {
+ return Ix(this.toCompactHex());
+ }
+ toCompactHex() {
+ return p(this.r) + p(this.s);
+ }
+ }
+ let v = {
+ isValidPrivateKey(e) {
+ try {
+ return u(e), !0;
+ } catch {
+ return !1;
+ }
+ },
+ normPrivateKeyToScalar: u,
+ randomPrivateKey: () => {
+ let e = SS(t.n);
+ return CS(t.randomBytes(e), t.n);
+ },
+ precompute(e = 8, t = l.BASE) {
+ return t._setWindowSize(e), t.multiply(BigInt(3)), t;
+ }
+ };
+ function y(e, t = !0) {
+ return l.fromPrivateKey(e).toRawBytes(t);
+ }
+ function b(e) {
+ let t = e instanceof Uint8Array, n = typeof e == "string", r = (t || n) && e.length;
+ return t ? r === i || r === a : n ? r === 2 * i || r === 2 * a : e instanceof l;
+ }
+ function x(e, t, n = !0) {
+ if (b(e)) throw Error("first arg must be private key");
+ if (!b(t)) throw Error("second arg must be public key");
+ return l.fromHex(t).multiply(u(e)).toRawBytes(n);
+ }
+ let S = t.bits2int || function(e) {
+ let n = Lx(e), r = e.length * 8 - t.nBitLength;
+ return r > 0 ? n >> BigInt(r) : n;
+ }, C = t.bits2int_modN || function(e) {
+ return s(S(e));
+ }, w = Yx(t.nBitLength);
+ function T(e) {
+ if (typeof e != "bigint") throw Error("bigint expected");
+ if (!(MS <= e && e < w)) throw Error(`bigint expected < 2^${t.nBitLength}`);
+ return zx(e, t.nByteLength);
+ }
+ function E(e, r, i = D) {
+ if (["recovered", "canonical"].some((e) => e in i)) throw Error("sign() legacy options not supported");
+ let { hash: a, randomBytes: o } = t, { lowS: d, prehash: p, extraEntropy: g } = i;
+ d ??= !0, e = Hx("msgHash", e), p && (e = Hx("prehashed msgHash", a(e)));
+ let v = C(e), y = u(r), b = [T(y), T(v)];
+ if (g != null) {
+ let e = g === !0 ? o(n.BYTES) : g;
+ b.push(Hx("extraEntropy", e));
+ }
+ let x = Ux(...b), w = v;
+ function E(e) {
+ let t = S(e);
+ if (!f(t)) return;
+ let n = c(t), r = l.BASE.multiply(t).toAffine(), i = s(r.x);
+ if (i === MS) return;
+ let a = s(n * s(w + i * y));
+ if (a === MS) return;
+ let o = (r.x === i ? 0 : 2) | Number(r.y & NS), u = a;
+ return d && m(a) && (u = h(a), o ^= 1), new _(i, u, o);
+ }
+ return {
+ seed: x,
+ k2sig: E
+ };
+ }
+ let D = {
+ lowS: t.lowS,
+ prehash: !1
+ }, O = {
+ lowS: t.lowS,
+ prehash: !1
+ };
+ function k(e, n, r = D) {
+ let { seed: i, k2sig: a } = E(e, n, r), o = t;
+ return Qx(o.hash.outputLen, o.nByteLength, o.hmac)(i, a);
+ }
+ l.BASE._setWindowSize(8);
+ function ee(e, n, r, i = O) {
+ let a = e;
+ if (n = Hx("msgHash", n), r = Hx("publicKey", r), "strict" in i) throw Error("options.strict was renamed to lowS");
+ let { lowS: o, prehash: u } = i, d, f;
+ try {
+ if (typeof a == "string" || a instanceof Uint8Array) try {
+ d = _.fromDER(a);
+ } catch (e) {
+ if (!(e instanceof jS.Err)) throw e;
+ d = _.fromCompact(a);
+ }
+ else if (typeof a == "object" && typeof a.r == "bigint" && typeof a.s == "bigint") {
+ let { r: e, s: t } = a;
+ d = new _(e, t);
+ } else throw Error("PARSE");
+ f = l.fromHex(r);
+ } catch (e) {
+ if (e.message === "PARSE") throw Error("signature must be Signature instance, Uint8Array or hex string");
+ return !1;
+ }
+ if (o && d.hasHighS()) return !1;
+ u && (n = t.hash(n));
+ let { r: p, s: m } = d, h = C(n), g = c(m), v = s(h * g), y = s(p * g), b = l.BASE.multiplyAndAddUnsafe(f, v, y)?.toAffine();
+ return b ? s(b.x) === p : !1;
+ }
+ return {
+ CURVE: t,
+ getPublicKey: y,
+ getSharedSecret: x,
+ sign: k,
+ verify: ee,
+ ProjectivePoint: l,
+ Signature: _,
+ utils: v
+ };
+}
+function BS(e, t) {
+ let n = e.ORDER, r = MS;
+ for (let e = n - NS; e % PS === MS; e /= PS) r += NS;
+ let i = r, a = PS << i - NS - NS, o = a * PS, s = (n - NS) / o, c = (s - NS) / PS, l = o - NS, u = a, d = e.pow(t, s), f = e.pow(t, (s + NS) / PS), p = (t, n) => {
+ let r = d, a = e.pow(n, l), o = e.sqr(a);
+ o = e.mul(o, n);
+ let s = e.mul(t, o);
+ s = e.pow(s, c), s = e.mul(s, a), a = e.mul(s, n), o = e.mul(s, t);
+ let p = e.mul(o, a);
+ s = e.pow(p, u);
+ let m = e.eql(s, e.ONE);
+ a = e.mul(o, f), s = e.mul(p, r), o = e.cmov(a, o, m), p = e.cmov(s, p, m);
+ for (let t = i; t > NS; t--) {
+ let n = t - PS;
+ n = PS << n - NS;
+ let i = e.pow(p, n), s = e.eql(i, e.ONE);
+ a = e.mul(o, r), r = e.mul(r, r), i = e.mul(p, r), o = e.cmov(a, o, s), p = e.cmov(i, p, s);
+ }
+ return {
+ isValid: m,
+ value: o
+ };
+ };
+ if (e.ORDER % IS === FS) {
+ let n = (e.ORDER - FS) / IS, r = e.sqrt(e.neg(t));
+ p = (t, i) => {
+ let a = e.sqr(i), o = e.mul(t, i);
+ a = e.mul(a, o);
+ let s = e.pow(a, n);
+ s = e.mul(s, o);
+ let c = e.mul(s, r), l = e.mul(e.sqr(s), i), u = e.eql(l, t);
+ return {
+ isValid: u,
+ value: e.cmov(c, s, u)
+ };
+ };
+ }
+ return p;
+}
+function VS(e, t) {
+ if (gS(e), !e.isValid(t.A) || !e.isValid(t.B) || !e.isValid(t.Z)) throw Error("mapToCurveSimpleSWU: invalid opts");
+ let n = BS(e, t.Z);
+ if (!e.isOdd) throw Error("Fp.isOdd is not implemented!");
+ return (r) => {
+ let i, a, o, s, c, l, u, d;
+ i = e.sqr(r), i = e.mul(i, t.Z), a = e.sqr(i), a = e.add(a, i), o = e.add(a, e.ONE), o = e.mul(o, t.B), s = e.cmov(t.Z, e.neg(a), !e.eql(a, e.ZERO)), s = e.mul(s, t.A), a = e.sqr(o), l = e.sqr(s), c = e.mul(l, t.A), a = e.add(a, c), a = e.mul(a, o), l = e.mul(l, s), c = e.mul(l, t.B), a = e.add(a, c), u = e.mul(i, o);
+ let { isValid: f, value: p } = n(a, l);
+ d = e.mul(i, r), d = e.mul(d, p), u = e.cmov(u, o, f), d = e.cmov(d, p, f);
+ let m = e.isOdd(r) === e.isOdd(d);
+ return d = e.cmov(e.neg(d), d, m), u = e.div(u, s), {
+ x: u,
+ y: d
+ };
+ };
+}
+//#endregion
+//#region node_modules/@noble/curves/esm/abstract/hash-to-curve.js
+function HS(e) {
+ if (e instanceof Uint8Array) return e;
+ if (typeof e == "string") return Gx(e);
+ throw Error("DST must be Uint8Array or string");
+}
+var US = Lx;
+function WS(e, t) {
+ if (e < 0 || e >= 1 << 8 * t) throw Error(`bad I2OSP call: value=${e} length=${t}`);
+ let n = Array.from({ length: t }).fill(0);
+ for (let r = t - 1; r >= 0; r--) n[r] = e & 255, e >>>= 8;
+ return new Uint8Array(n);
+}
+function GS(e, t) {
+ let n = new Uint8Array(e.length);
+ for (let r = 0; r < e.length; r++) n[r] = e[r] ^ t[r];
+ return n;
+}
+function KS(e) {
+ if (!(e instanceof Uint8Array)) throw Error("Uint8Array expected");
+}
+function qS(e) {
+ if (!Number.isSafeInteger(e)) throw Error("number expected");
+}
+function JS(e, t, n, r) {
+ KS(e), KS(t), qS(n), t.length > 255 && (t = r(Ux(Gx("H2C-OVERSIZE-DST-"), t)));
+ let { outputLen: i, blockLen: a } = r, o = Math.ceil(n / i);
+ if (o > 255) throw Error("Invalid xmd length");
+ let s = Ux(t, WS(t.length, 1)), c = WS(0, a), l = WS(n, 2), u = Array(o), d = r(Ux(c, e, l, WS(0, 1), s));
+ u[0] = r(Ux(d, WS(1, 1), s));
+ for (let e = 1; e <= o; e++) u[e] = r(Ux(GS(d, u[e - 1]), WS(e + 1, 1), s));
+ return Ux(...u).slice(0, n);
+}
+function YS(e, t, n, r, i) {
+ if (KS(e), KS(t), qS(n), t.length > 255) {
+ let e = Math.ceil(2 * r / 8);
+ t = i.create({ dkLen: e }).update(Gx("H2C-OVERSIZE-DST-")).update(t).digest();
+ }
+ if (n > 65535 || t.length > 255) throw Error("expand_message_xof: invalid lenInBytes");
+ return i.create({ dkLen: n }).update(e).update(WS(n, 2)).update(t).update(WS(t.length, 1)).digest();
+}
+function XS(e, t, n) {
+ eS(n, {
+ DST: "stringOrUint8Array",
+ p: "bigint",
+ m: "isSafeInteger",
+ k: "isSafeInteger",
+ hash: "hash"
+ });
+ let { p: r, k: i, m: a, hash: o, expand: s, DST: c } = n;
+ KS(e), qS(t);
+ let l = HS(c), u = r.toString(2).length, d = Math.ceil((u + i) / 8), f = t * a * d, p;
+ if (s === "xmd") p = JS(e, l, f, o);
+ else if (s === "xof") p = YS(e, l, f, i, o);
+ else if (s === "_internal_pass") p = e;
+ else throw Error("expand must be \"xmd\" or \"xof\"");
+ let m = Array(t);
+ for (let e = 0; e < t; e++) {
+ let t = Array(a);
+ for (let n = 0; n < a; n++) {
+ let i = d * (n + e * a);
+ t[n] = lS(US(p.subarray(i, i + d)), r);
+ }
+ m[e] = t;
+ }
+ return m;
+}
+function ZS(e, t) {
+ let n = t.map((e) => Array.from(e).reverse());
+ return (t, r) => {
+ let [i, a, o, s] = n.map((n) => n.reduce((n, r) => e.add(e.mul(n, t), r)));
+ return t = e.div(i, a), r = e.mul(r, e.div(o, s)), {
+ x: t,
+ y: r
+ };
+ };
+}
+function QS(e, t, n) {
+ if (typeof t != "function") throw Error("mapToCurve() must be defined");
+ return {
+ hashToCurve(r, i) {
+ let a = XS(r, 2, {
+ ...n,
+ DST: n.DST,
+ ...i
+ }), o = e.fromAffine(t(a[0])), s = e.fromAffine(t(a[1])), c = o.add(s).clearCofactor();
+ return c.assertValidity(), c;
+ },
+ encodeToCurve(r, i) {
+ let a = XS(r, 1, {
+ ...n,
+ DST: n.encodeDST,
+ ...i
+ }), o = e.fromAffine(t(a[0])).clearCofactor();
+ return o.assertValidity(), o;
+ }
+ };
+}
+//#endregion
+//#region node_modules/@noble/curves/esm/_shortw_utils.js
+function $S(e) {
+ return {
+ hash: e,
+ hmac: (t, ...n) => gb(e, t, db(...n)),
+ randomBytes: mb
+ };
+}
+function eC(e, t) {
+ let n = (t) => zS({
+ ...e,
+ ...$S(t)
+ });
+ return Object.freeze({
+ ...n(t),
+ create: n
+ });
+}
+//#endregion
+//#region node_modules/@noble/curves/esm/secp256k1.js
+var tC = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"), nC = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"), rC = BigInt(1), iC = BigInt(2), aC = (e, t) => (e + t / iC) / t;
+function oC(e) {
+ let t = tC, n = BigInt(3), r = BigInt(6), i = BigInt(11), a = BigInt(22), o = BigInt(23), s = BigInt(44), c = BigInt(88), l = e * e * e % t, u = l * l * e % t, d = dS(dS(dS(u, n, t) * u % t, n, t) * u % t, iC, t) * l % t, f = dS(d, i, t) * d % t, p = dS(f, a, t) * f % t, m = dS(p, s, t) * p % t, h = dS(dS(dS(dS(dS(dS(m, c, t) * m % t, s, t) * p % t, n, t) * u % t, o, t) * f % t, r, t) * l % t, iC, t);
+ if (!sC.eql(sC.sqr(h), e)) throw Error("Cannot find square root");
+ return h;
+}
+var sC = bS(tC, void 0, void 0, { sqrt: oC }), cC = eC({
+ a: BigInt(0),
+ b: BigInt(7),
+ Fp: sC,
+ n: nC,
+ Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),
+ Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),
+ h: BigInt(1),
+ lowS: !0,
+ endo: {
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
+ splitScalar: (e) => {
+ let t = nC, n = BigInt("0x3086d221a7d46bcde86c90e49284eb15"), r = -rC * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"), i = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), a = n, o = BigInt("0x100000000000000000000000000000000"), s = aC(a * e, t), c = aC(-r * e, t), l = lS(e - s * n - c * i, t), u = lS(-s * r - c * a, t), d = l > o, f = u > o;
+ if (d && (l = t - l), f && (u = t - u), l > o || u > o) throw Error("splitScalar: Endomorphism failed, k=" + e);
+ return {
+ k1neg: d,
+ k1: l,
+ k2neg: f,
+ k2: u
+ };
+ }
+ }
+}, Tb);
+cC.ProjectivePoint, cC.utils.randomPrivateKey;
+var lC = ZS(sC, [
+ [
+ "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7",
+ "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581",
+ "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262",
+ "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"
+ ],
+ [
+ "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b",
+ "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14",
+ "0x0000000000000000000000000000000000000000000000000000000000000001"
+ ],
+ [
+ "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c",
+ "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3",
+ "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931",
+ "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"
+ ],
+ [
+ "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b",
+ "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573",
+ "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f",
+ "0x0000000000000000000000000000000000000000000000000000000000000001"
+ ]
+].map((e) => e.map((e) => BigInt(e)))), uC = VS(sC, {
+ A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),
+ B: BigInt("1771"),
+ Z: sC.create(BigInt("-11"))
+}), dC = QS(cC.ProjectivePoint, (e) => {
+ let { x: t, y: n } = uC(sC.create(e[0]));
+ return lC(t, n);
+}, {
+ DST: "secp256k1_XMD:SHA-256_SSWU_RO_",
+ encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_",
+ p: sC.ORDER,
+ m: 1,
+ k: 128,
+ expand: "xmd",
+ hash: Tb
+});
+dC.hashToCurve, dC.encodeToCurve;
+//#endregion
+//#region node_modules/ethers/lib.esm/constants/addresses.js
+var fC = "0x0000000000000000000000000000000000000000", pC = "0x0000000000000000000000000000000000000000000000000000000000000000", mC = BigInt(0), hC = BigInt(1), gC = BigInt(2), _C = BigInt(27), vC = BigInt(28), yC = BigInt(35), bC = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"), xC = bC / gC, SC = Symbol.for("nodejs.util.inspect.custom"), CC = {};
+function wC(e) {
+ return Rv(Zv(e), 32);
+}
+var TC = class e {
+ #e;
+ #t;
+ #n;
+ #r;
+ get r() {
+ return this.#e;
+ }
+ set r(e) {
+ q(Fv(e) === 32, "invalid r", "value", e), this.#e = Y(e);
+ }
+ get s() {
+ return q(parseInt(this.#t.substring(0, 3)) < 8, "non-canonical s; use ._s", "s", this.#t), this.#t;
+ }
+ set s(e) {
+ q(Fv(e) === 32, "invalid s", "value", e), this.#t = Y(e);
+ }
+ get _s() {
+ return this.#t;
+ }
+ isValid() {
+ return BigInt(this.#t) <= xC;
+ }
+ get v() {
+ return this.#n;
+ }
+ set v(e) {
+ let t = Z(e, "value");
+ q(t === 27 || t === 28, "invalid v", "v", e), this.#n = t;
+ }
+ get networkV() {
+ return this.#r;
+ }
+ get legacyChainId() {
+ let t = this.networkV;
+ return t == null ? null : e.getChainId(t);
+ }
+ get yParity() {
+ return this.v === 27 ? 0 : 1;
+ }
+ get yParityAndS() {
+ let e = J(this.s);
+ return this.yParity && (e[0] |= 128), Y(e);
+ }
+ get compactSerialized() {
+ return Pv([this.r, this.yParityAndS]);
+ }
+ get serialized() {
+ return Pv([
+ this.r,
+ this.s,
+ this.yParity ? "0x1c" : "0x1b"
+ ]);
+ }
+ constructor(e, t, n, r) {
+ Ov(e, CC, "Signature"), this.#e = t, this.#t = n, this.#n = r, this.#r = null;
+ }
+ getCanonical() {
+ if (this.isValid()) return this;
+ let t = bC - BigInt(this._s), n = 55 - this.v, r = new e(CC, this.r, wC(t), n);
+ return this.networkV && (r.#r = this.networkV), r;
+ }
+ clone() {
+ let t = new e(CC, this.r, this._s, this.v);
+ return this.networkV && (t.#r = this.networkV), t;
+ }
+ toJSON() {
+ let e = this.networkV;
+ return {
+ _type: "signature",
+ networkV: e == null ? null : e.toString(),
+ r: this.r,
+ s: this._s,
+ v: this.v
+ };
+ }
+ [SC]() {
+ return this.toString();
+ }
+ toString() {
+ return this.isValid() ? `Signature { r: ${this.r}, s: ${this._s}, v: ${this.v} }` : `Signature { r: ${this.r}, s: ${this._s}, v: ${this.v}, valid: false }`;
+ }
+ static getChainId(e) {
+ let t = X(e, "v");
+ return t == _C || t == vC ? mC : (q(t >= yC, "invalid EIP-155 v", "v", e), (t - yC) / gC);
+ }
+ static getChainIdV(e, t) {
+ return X(e) * gC + BigInt(35 + t - 27);
+ }
+ static getNormalizedV(e) {
+ let t = X(e);
+ return t === mC || t === _C ? 27 : t === hC || t === vC ? 28 : (q(t >= yC, "invalid v", "v", e), t & hC ? 27 : 28);
+ }
+ static from(t) {
+ function n(e, n) {
+ q(e, n, "signature", t);
+ }
+ if (t == null) return new e(CC, pC, pC, 27);
+ if (typeof t == "string") {
+ let r = J(t, "signature");
+ if (r.length === 64) {
+ let t = Y(r.slice(0, 32)), n = r.slice(32, 64), i = n[0] & 128 ? 28 : 27;
+ return n[0] &= 127, new e(CC, t, Y(n), i);
+ }
+ if (r.length === 65) return new e(CC, Y(r.slice(0, 32)), Y(r.slice(32, 64)), e.getNormalizedV(r[64]));
+ n(!1, "invalid raw signature length");
+ }
+ if (t instanceof e) return t.clone();
+ let r = t.r;
+ n(r != null, "missing r");
+ let i = wC(r), a = (function(e, t) {
+ if (e != null) return wC(e);
+ if (t != null) {
+ n(jv(t, 32), "invalid yParityAndS");
+ let e = J(t);
+ return e[0] &= 127, Y(e);
+ }
+ n(!1, "missing s");
+ })(t.s, t.yParityAndS), { networkV: o, v: s } = (function(t, r, i) {
+ if (t != null) {
+ let n = X(t);
+ return {
+ networkV: n >= yC ? n : void 0,
+ v: e.getNormalizedV(n)
+ };
+ }
+ if (r != null) return n(jv(r, 32), "invalid yParityAndS"), { v: J(r)[0] & 128 ? 28 : 27 };
+ if (i != null) {
+ switch (Z(i, "sig.yParity")) {
+ case 0: return { v: 27 };
+ case 1: return { v: 28 };
+ }
+ n(!1, "invalid yParity");
+ }
+ n(!1, "missing v");
+ })(t.v, t.yParityAndS, t.yParity), c = new e(CC, i, a, s);
+ return o && (c.#r = o), n(t.yParity == null || Z(t.yParity, "sig.yParity") === c.yParity, "yParity mismatch"), n(t.yParityAndS == null || t.yParityAndS === c.yParityAndS, "yParityAndS mismatch"), c;
+ }
+}, EC = class e {
+ #e;
+ constructor(e) {
+ q(Fv(e) === 32, "invalid private key", "privateKey", "[REDACTED]"), this.#e = Y(e);
+ }
+ get privateKey() {
+ return this.#e;
+ }
+ get publicKey() {
+ return e.computePublicKey(this.#e);
+ }
+ get compressedPublicKey() {
+ return e.computePublicKey(this.#e, !0);
+ }
+ sign(e) {
+ q(Fv(e) === 32, "invalid digest length", "digest", e);
+ let t = cC.sign(Av(e), Av(this.#e), { lowS: !0 });
+ return TC.from({
+ r: Xv(t.r, 32),
+ s: Xv(t.s, 32),
+ v: t.recovery ? 28 : 27
+ });
+ }
+ computeSharedSecret(t) {
+ let n = e.computePublicKey(t);
+ return Y(cC.getSharedSecret(Av(this.#e), J(n), !1));
+ }
+ static computePublicKey(e, t) {
+ let n = J(e, "key");
+ if (n.length === 32) return Y(cC.getPublicKey(n, !!t));
+ if (n.length === 64) {
+ let e = new Uint8Array(65);
+ e[0] = 4, e.set(n, 1), n = e;
+ }
+ return Y(cC.ProjectivePoint.fromHex(n).toRawBytes(t));
+ }
+ static recoverPublicKey(e, t) {
+ q(Fv(e) === 32, "invalid digest length", "digest", e);
+ let n = TC.from(t), r = cC.Signature.fromCompact(Av(Pv([n.r, n.s])));
+ r = r.addRecoveryBit(n.yParity);
+ let i = r.recoverPublicKey(Av(e));
+ return q(i != null, "invalid signature for digest", "signature", t), "0x" + i.toHex(!1);
+ }
+ static addPoints(t, n, r) {
+ let i = cC.ProjectivePoint.fromHex(e.computePublicKey(t).substring(2)), a = cC.ProjectivePoint.fromHex(e.computePublicKey(n).substring(2));
+ return "0x" + i.add(a).toHex(!!r);
+ }
+}, DC = BigInt(0), OC = BigInt(36);
+function kC(e) {
+ e = e.toLowerCase();
+ let t = e.substring(2).split(""), n = new Uint8Array(40);
+ for (let e = 0; e < 40; e++) n[e] = t[e].charCodeAt(0);
+ let r = J(vx(n));
+ for (let e = 0; e < 40; e += 2) r[e >> 1] >> 4 >= 8 && (t[e] = t[e].toUpperCase()), (r[e >> 1] & 15) >= 8 && (t[e + 1] = t[e + 1].toUpperCase());
+ return "0x" + t.join("");
+}
+var AC = {};
+for (let e = 0; e < 10; e++) AC[String(e)] = String(e);
+for (let e = 0; e < 26; e++) AC[String.fromCharCode(65 + e)] = String(10 + e);
+var jC = 15;
+function MC(e) {
+ e = e.toUpperCase(), e = e.substring(4) + e.substring(0, 2) + "00";
+ let t = e.split("").map((e) => AC[e]).join("");
+ for (; t.length >= jC;) {
+ let e = t.substring(0, jC);
+ t = parseInt(e, 10) % 97 + t.substring(e.length);
+ }
+ let n = String(98 - parseInt(t, 10) % 97);
+ for (; n.length < 2;) n = "0" + n;
+ return n;
+}
+var NC = (function() {
+ let e = {};
+ for (let t = 0; t < 36; t++) {
+ let n = "0123456789abcdefghijklmnopqrstuvwxyz"[t];
+ e[n] = BigInt(t);
+ }
+ return e;
+})();
+function PC(e) {
+ e = e.toLowerCase();
+ let t = DC;
+ for (let n = 0; n < e.length; n++) t = t * OC + NC[e[n]];
+ return t;
+}
+function FC(e) {
+ if (q(typeof e == "string", "invalid address", "address", e), e.match(/^(0x)?[0-9a-fA-F]{40}$/)) {
+ e.startsWith("0x") || (e = "0x" + e);
+ let t = kC(e);
+ return q(!e.match(/([A-F].*[a-f])|([a-f].*[A-F])/) || t === e, "bad address checksum", "address", e), t;
+ }
+ if (e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) {
+ q(e.substring(2, 4) === MC(e), "bad icap checksum", "address", e);
+ let t = PC(e.substring(4)).toString(16);
+ for (; t.length < 40;) t = "0" + t;
+ return kC("0x" + t);
+ }
+ q(!1, "invalid address", "address", e);
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/address/contract-address.js
+function IC(e) {
+ let t = FC(e.from), n = X(e.nonce, "tx.nonce").toString(16);
+ return n = n === "0" ? "0x" : n.length % 2 ? "0x0" + n : "0x" + n, FC(Iv(vx(zy([t, n])), 12));
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/address/checks.js
+function LC(e) {
+ return e && typeof e.getAddress == "function";
+}
+async function RC(e, t) {
+ let n = await t;
+ return (n == null || n === "0x0000000000000000000000000000000000000000") && (K(typeof e != "string", "unconfigured name", "UNCONFIGURED_NAME", { value: e }), q(!1, "invalid AddressLike value; did not resolve to a value address", "target", e)), FC(n);
+}
+function zC(e, t) {
+ if (typeof e == "string") return e.match(/^0x[0-9a-f]{40}$/i) ? FC(e) : (K(t != null, "ENS resolution requires a provider", "UNSUPPORTED_OPERATION", { operation: "resolveName" }), RC(e, t.resolveName(e)));
+ if (LC(e)) return RC(e, e.getAddress());
+ if (e && typeof e.then == "function") return RC(e, e);
+ q(!1, "unsupported addressable value", "target", e);
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/abi/typed.js
+var BC = {};
+function $(e, t) {
+ let n = !1;
+ return t < 0 && (n = !0, t *= -1), new UC(BC, `${n ? "" : "u"}int${t}`, e, {
+ signed: n,
+ width: t
+ });
+}
+function VC(e, t) {
+ return new UC(BC, `bytes${t || ""}`, e, { size: t });
+}
+var HC = Symbol.for("_ethers_typed"), UC = class e {
+ type;
+ value;
+ #e;
+ _typedSymbol;
+ constructor(e, t, n, r) {
+ r ??= null, Ov(BC, e, "Typed"), G(this, {
+ _typedSymbol: HC,
+ type: t,
+ value: n
+ }), this.#e = r, this.format();
+ }
+ format() {
+ if (this.type === "array" || this.type === "dynamicArray") throw Error("");
+ return this.type === "tuple" ? `tuple(${this.value.map((e) => e.format()).join(",")})` : this.type;
+ }
+ defaultValue() {
+ return 0;
+ }
+ minValue() {
+ return 0;
+ }
+ maxValue() {
+ return 0;
+ }
+ isBigInt() {
+ return !!this.type.match(/^u?int[0-9]+$/);
+ }
+ isData() {
+ return this.type.startsWith("bytes");
+ }
+ isString() {
+ return this.type === "string";
+ }
+ get tupleName() {
+ if (this.type !== "tuple") throw TypeError("not a tuple");
+ return this.#e;
+ }
+ get arrayLength() {
+ if (this.type !== "array") throw TypeError("not an array");
+ return this.#e === !0 ? -1 : this.#e === !1 ? this.value.length : null;
+ }
+ static from(t, n) {
+ return new e(BC, t, n);
+ }
+ static uint8(e) {
+ return $(e, 8);
+ }
+ static uint16(e) {
+ return $(e, 16);
+ }
+ static uint24(e) {
+ return $(e, 24);
+ }
+ static uint32(e) {
+ return $(e, 32);
+ }
+ static uint40(e) {
+ return $(e, 40);
+ }
+ static uint48(e) {
+ return $(e, 48);
+ }
+ static uint56(e) {
+ return $(e, 56);
+ }
+ static uint64(e) {
+ return $(e, 64);
+ }
+ static uint72(e) {
+ return $(e, 72);
+ }
+ static uint80(e) {
+ return $(e, 80);
+ }
+ static uint88(e) {
+ return $(e, 88);
+ }
+ static uint96(e) {
+ return $(e, 96);
+ }
+ static uint104(e) {
+ return $(e, 104);
+ }
+ static uint112(e) {
+ return $(e, 112);
+ }
+ static uint120(e) {
+ return $(e, 120);
+ }
+ static uint128(e) {
+ return $(e, 128);
+ }
+ static uint136(e) {
+ return $(e, 136);
+ }
+ static uint144(e) {
+ return $(e, 144);
+ }
+ static uint152(e) {
+ return $(e, 152);
+ }
+ static uint160(e) {
+ return $(e, 160);
+ }
+ static uint168(e) {
+ return $(e, 168);
+ }
+ static uint176(e) {
+ return $(e, 176);
+ }
+ static uint184(e) {
+ return $(e, 184);
+ }
+ static uint192(e) {
+ return $(e, 192);
+ }
+ static uint200(e) {
+ return $(e, 200);
+ }
+ static uint208(e) {
+ return $(e, 208);
+ }
+ static uint216(e) {
+ return $(e, 216);
+ }
+ static uint224(e) {
+ return $(e, 224);
+ }
+ static uint232(e) {
+ return $(e, 232);
+ }
+ static uint240(e) {
+ return $(e, 240);
+ }
+ static uint248(e) {
+ return $(e, 248);
+ }
+ static uint256(e) {
+ return $(e, 256);
+ }
+ static uint(e) {
+ return $(e, 256);
+ }
+ static int8(e) {
+ return $(e, -8);
+ }
+ static int16(e) {
+ return $(e, -16);
+ }
+ static int24(e) {
+ return $(e, -24);
+ }
+ static int32(e) {
+ return $(e, -32);
+ }
+ static int40(e) {
+ return $(e, -40);
+ }
+ static int48(e) {
+ return $(e, -48);
+ }
+ static int56(e) {
+ return $(e, -56);
+ }
+ static int64(e) {
+ return $(e, -64);
+ }
+ static int72(e) {
+ return $(e, -72);
+ }
+ static int80(e) {
+ return $(e, -80);
+ }
+ static int88(e) {
+ return $(e, -88);
+ }
+ static int96(e) {
+ return $(e, -96);
+ }
+ static int104(e) {
+ return $(e, -104);
+ }
+ static int112(e) {
+ return $(e, -112);
+ }
+ static int120(e) {
+ return $(e, -120);
+ }
+ static int128(e) {
+ return $(e, -128);
+ }
+ static int136(e) {
+ return $(e, -136);
+ }
+ static int144(e) {
+ return $(e, -144);
+ }
+ static int152(e) {
+ return $(e, -152);
+ }
+ static int160(e) {
+ return $(e, -160);
+ }
+ static int168(e) {
+ return $(e, -168);
+ }
+ static int176(e) {
+ return $(e, -176);
+ }
+ static int184(e) {
+ return $(e, -184);
+ }
+ static int192(e) {
+ return $(e, -192);
+ }
+ static int200(e) {
+ return $(e, -200);
+ }
+ static int208(e) {
+ return $(e, -208);
+ }
+ static int216(e) {
+ return $(e, -216);
+ }
+ static int224(e) {
+ return $(e, -224);
+ }
+ static int232(e) {
+ return $(e, -232);
+ }
+ static int240(e) {
+ return $(e, -240);
+ }
+ static int248(e) {
+ return $(e, -248);
+ }
+ static int256(e) {
+ return $(e, -256);
+ }
+ static int(e) {
+ return $(e, -256);
+ }
+ static bytes1(e) {
+ return VC(e, 1);
+ }
+ static bytes2(e) {
+ return VC(e, 2);
+ }
+ static bytes3(e) {
+ return VC(e, 3);
+ }
+ static bytes4(e) {
+ return VC(e, 4);
+ }
+ static bytes5(e) {
+ return VC(e, 5);
+ }
+ static bytes6(e) {
+ return VC(e, 6);
+ }
+ static bytes7(e) {
+ return VC(e, 7);
+ }
+ static bytes8(e) {
+ return VC(e, 8);
+ }
+ static bytes9(e) {
+ return VC(e, 9);
+ }
+ static bytes10(e) {
+ return VC(e, 10);
+ }
+ static bytes11(e) {
+ return VC(e, 11);
+ }
+ static bytes12(e) {
+ return VC(e, 12);
+ }
+ static bytes13(e) {
+ return VC(e, 13);
+ }
+ static bytes14(e) {
+ return VC(e, 14);
+ }
+ static bytes15(e) {
+ return VC(e, 15);
+ }
+ static bytes16(e) {
+ return VC(e, 16);
+ }
+ static bytes17(e) {
+ return VC(e, 17);
+ }
+ static bytes18(e) {
+ return VC(e, 18);
+ }
+ static bytes19(e) {
+ return VC(e, 19);
+ }
+ static bytes20(e) {
+ return VC(e, 20);
+ }
+ static bytes21(e) {
+ return VC(e, 21);
+ }
+ static bytes22(e) {
+ return VC(e, 22);
+ }
+ static bytes23(e) {
+ return VC(e, 23);
+ }
+ static bytes24(e) {
+ return VC(e, 24);
+ }
+ static bytes25(e) {
+ return VC(e, 25);
+ }
+ static bytes26(e) {
+ return VC(e, 26);
+ }
+ static bytes27(e) {
+ return VC(e, 27);
+ }
+ static bytes28(e) {
+ return VC(e, 28);
+ }
+ static bytes29(e) {
+ return VC(e, 29);
+ }
+ static bytes30(e) {
+ return VC(e, 30);
+ }
+ static bytes31(e) {
+ return VC(e, 31);
+ }
+ static bytes32(e) {
+ return VC(e, 32);
+ }
+ static address(t) {
+ return new e(BC, "address", t);
+ }
+ static bool(t) {
+ return new e(BC, "bool", !!t);
+ }
+ static bytes(t) {
+ return new e(BC, "bytes", t);
+ }
+ static string(t) {
+ return new e(BC, "string", t);
+ }
+ static array(e, t) {
+ throw Error("not implemented yet");
+ }
+ static tuple(e, t) {
+ throw Error("not implemented yet");
+ }
+ static overrides(t) {
+ return new e(BC, "overrides", Object.assign({}, t));
+ }
+ static isTyped(e) {
+ return e && typeof e == "object" && "_typedSymbol" in e && e._typedSymbol === HC;
+ }
+ static dereference(t, n) {
+ if (e.isTyped(t)) {
+ if (t.type !== n) throw Error(`invalid type: expecetd ${n}, got ${t.type}`);
+ return t.value;
+ }
+ return t;
+ }
+}, WC = class extends Xy {
+ constructor(e) {
+ super("address", "address", e, !1);
+ }
+ defaultValue() {
+ return "0x0000000000000000000000000000000000000000";
+ }
+ encode(e, t) {
+ let n = UC.dereference(t, "string");
+ try {
+ n = FC(n);
+ } catch (e) {
+ return this._throwError(e.message, t);
+ }
+ return e.writeValue(n);
+ }
+ decode(e) {
+ return FC(Xv(e.readValue(), 20));
+ }
+}, GC = class extends Xy {
+ coder;
+ constructor(e) {
+ super(e.name, e.type, "_", e.dynamic), this.coder = e;
+ }
+ defaultValue() {
+ return this.coder.defaultValue();
+ }
+ encode(e, t) {
+ return this.coder.encode(e, t);
+ }
+ decode(e) {
+ return this.coder.decode(e);
+ }
+};
+//#endregion
+//#region node_modules/ethers/lib.esm/abi/coders/array.js
+function KC(e, t, n) {
+ let r = [];
+ if (Array.isArray(n)) r = n;
+ else if (n && typeof n == "object") {
+ let e = {};
+ r = t.map((t) => {
+ let r = t.localName;
+ return K(r, "cannot encode object for signature with missing names", "INVALID_ARGUMENT", {
+ argument: "values",
+ info: { coder: t },
+ value: n
+ }), K(!e[r], "cannot encode object for signature with duplicate names", "INVALID_ARGUMENT", {
+ argument: "values",
+ info: { coder: t },
+ value: n
+ }), e[r] = !0, n[r];
+ });
+ } else q(!1, "invalid tuple value", "tuple", n);
+ q(t.length === r.length, "types/value length mismatch", "tuple", n);
+ let i = new Zy(), a = new Zy(), o = [];
+ t.forEach((e, t) => {
+ let n = r[t];
+ if (e.dynamic) {
+ let t = a.length;
+ e.encode(a, n);
+ let r = i.writeUpdatableValue();
+ o.push((e) => {
+ r(e + t);
+ });
+ } else e.encode(i, n);
+ }), o.forEach((e) => {
+ e(i.length);
+ });
+ let s = e.appendWriter(i);
+ return s += e.appendWriter(a), s;
+}
+function qC(e, t) {
+ let n = [], r = [], i = e.subReader(0);
+ return t.forEach((t) => {
+ let a = null;
+ if (t.dynamic) {
+ let n = e.readIndex(), r = i.subReader(n);
+ try {
+ a = t.decode(r);
+ } catch (e) {
+ if (Sv(e, "BUFFER_OVERRUN")) throw e;
+ a = e, a.baseType = t.name, a.name = t.localName, a.type = t.type;
+ }
+ } else try {
+ a = t.decode(e);
+ } catch (e) {
+ if (Sv(e, "BUFFER_OVERRUN")) throw e;
+ a = e, a.baseType = t.name, a.name = t.localName, a.type = t.type;
+ }
+ if (a == null) throw Error("investigate");
+ n.push(a), r.push(t.localName || null);
+ }), Jy.fromItems(n, r);
+}
+var JC = class extends Xy {
+ coder;
+ length;
+ constructor(e, t, n) {
+ let r = e.type + "[" + (t >= 0 ? t : "") + "]", i = t === -1 || e.dynamic;
+ super("array", r, n, i), G(this, {
+ coder: e,
+ length: t
+ });
+ }
+ defaultValue() {
+ let e = this.coder.defaultValue(), t = [];
+ for (let n = 0; n < this.length; n++) t.push(e);
+ return t;
+ }
+ encode(e, t) {
+ let n = UC.dereference(t, "array");
+ Array.isArray(n) || this._throwError("expected array value", n);
+ let r = this.length;
+ r === -1 && (r = n.length, e.writeValue(n.length)), Tv(n.length, r, "coder array" + (this.localName ? " " + this.localName : ""));
+ let i = [];
+ for (let e = 0; e < n.length; e++) i.push(this.coder);
+ return KC(e, i, n);
+ }
+ decode(e) {
+ let t = this.length;
+ t === -1 && (t = e.readIndex(), K(t * 32 <= e.dataLength, "insufficient data length", "BUFFER_OVERRUN", {
+ buffer: e.bytes,
+ offset: t * 32,
+ length: e.dataLength
+ }));
+ let n = [];
+ for (let e = 0; e < t; e++) n.push(new GC(this.coder));
+ return qC(e, n);
+ }
+}, YC = class extends Xy {
+ constructor(e) {
+ super("bool", "bool", e, !1);
+ }
+ defaultValue() {
+ return !1;
+ }
+ encode(e, t) {
+ let n = UC.dereference(t, "bool");
+ return e.writeValue(+!!n);
+ }
+ decode(e) {
+ return !!e.readValue();
+ }
+}, XC = class extends Xy {
+ constructor(e, t) {
+ super(e, e, t, !0);
+ }
+ defaultValue() {
+ return "0x";
+ }
+ encode(e, t) {
+ t = Av(t);
+ let n = e.writeValue(t.length);
+ return n += e.writeBytes(t), n;
+ }
+ decode(e) {
+ return e.readBytes(e.readIndex(), !0);
+ }
+}, ZC = class extends XC {
+ constructor(e) {
+ super("bytes", e);
+ }
+ decode(e) {
+ return Y(super.decode(e));
+ }
+}, QC = class extends Xy {
+ size;
+ constructor(e, t) {
+ let n = "bytes" + String(e);
+ super(n, n, t, !1), G(this, { size: e }, { size: "number" });
+ }
+ defaultValue() {
+ return "0x0000000000000000000000000000000000000000000000000000000000000000".substring(0, 2 + this.size * 2);
+ }
+ encode(e, t) {
+ let n = Av(UC.dereference(t, this.type));
+ return n.length !== this.size && this._throwError("incorrect data length", t), e.writeBytes(n);
+ }
+ decode(e) {
+ return Y(e.readBytes(this.size));
+ }
+}, $C = new Uint8Array([]), ew = class extends Xy {
+ constructor(e) {
+ super("null", "", e, !1);
+ }
+ defaultValue() {
+ return null;
+ }
+ encode(e, t) {
+ return t != null && this._throwError("not null", t), e.writeBytes($C);
+ }
+ decode(e) {
+ return e.readBytes(0), null;
+ }
+}, tw = BigInt(0), nw = BigInt(1), rw = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), iw = class extends Xy {
+ size;
+ signed;
+ constructor(e, t, n) {
+ let r = (t ? "int" : "uint") + e * 8;
+ super(r, r, n, !1), G(this, {
+ size: e,
+ signed: t
+ }, {
+ size: "number",
+ signed: "boolean"
+ });
+ }
+ defaultValue() {
+ return 0;
+ }
+ encode(e, t) {
+ let n = X(UC.dereference(t, this.type)), r = Gv(rw, 256);
+ if (this.signed) {
+ let e = Gv(r, this.size * 8 - 1);
+ (n > e || n < -(e + nw)) && this._throwError("value out-of-bounds", t), n = Wv(n, 256);
+ } else (n < tw || n > Gv(r, this.size * 8)) && this._throwError("value out-of-bounds", t);
+ return e.writeValue(n);
+ }
+ decode(e) {
+ let t = Gv(e.readValue(), this.size * 8);
+ return this.signed && (t = Uv(t, this.size * 8)), t;
+ }
+}, aw = class extends XC {
+ constructor(e) {
+ super("string", e);
+ }
+ defaultValue() {
+ return "";
+ }
+ encode(e, t) {
+ return super.encode(e, uy(UC.dereference(t, "string")));
+ }
+ decode(e) {
+ return fy(super.decode(e));
+ }
+}, ow = class extends Xy {
+ coders;
+ constructor(e, t) {
+ let n = !1, r = [];
+ e.forEach((e) => {
+ e.dynamic && (n = !0), r.push(e.type);
+ });
+ let i = "tuple(" + r.join(",") + ")";
+ super("tuple", i, t, n), G(this, { coders: Object.freeze(e.slice()) });
+ }
+ defaultValue() {
+ let e = [];
+ this.coders.forEach((t) => {
+ e.push(t.defaultValue());
+ });
+ let t = this.coders.reduce((e, t) => {
+ let n = t.localName;
+ return n && (e[n] || (e[n] = 0), e[n]++), e;
+ }, {});
+ return this.coders.forEach((n, r) => {
+ let i = n.localName;
+ !i || t[i] !== 1 || (i === "length" && (i = "_length"), e[i] ?? (e[i] = e[r]));
+ }), Object.freeze(e);
+ }
+ encode(e, t) {
+ let n = UC.dereference(t, "tuple");
+ return KC(e, this.coders, n);
+ }
+ decode(e) {
+ return qC(e, this.coders);
+ }
+};
+//#endregion
+//#region node_modules/ethers/lib.esm/transaction/accesslist.js
+function sw(e, t) {
+ return {
+ address: FC(e),
+ storageKeys: t.map((e, t) => (q(jv(e, 32), "invalid slot", `storageKeys[${t}]`, e), e.toLowerCase()))
+ };
+}
+function cw(e) {
+ if (Array.isArray(e)) return e.map((t, n) => Array.isArray(t) ? (q(t.length === 2, "invalid slot set", `value[${n}]`, t), sw(t[0], t[1])) : (q(typeof t == "object" && !!t, "invalid address-slot set", "value", e), sw(t.address, t.storageKeys)));
+ q(typeof e == "object" && !!e, "invalid access list", "value", e);
+ let t = Object.keys(e).map((t) => {
+ let n = e[t].reduce((e, t) => (e[t] = !0, e), {});
+ return sw(t, Object.keys(n).sort());
+ });
+ return t.sort((e, t) => e.address.localeCompare(t.address)), t;
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/transaction/authorization.js
+function lw(e) {
+ return {
+ address: FC(e.address),
+ nonce: X(e.nonce == null ? 0 : e.nonce),
+ chainId: X(e.chainId == null ? 0 : e.chainId),
+ signature: TC.from(e.signature)
+ };
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/transaction/address.js
+function uw(e) {
+ let t;
+ return t = typeof e == "string" ? EC.computePublicKey(e, !1) : e.publicKey, FC(vx("0x" + t.substring(4)).substring(26));
+}
+function dw(e, t) {
+ return uw(EC.recoverPublicKey(e, t));
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/transaction/transaction.js
+var fw = BigInt(0), pw = BigInt(2), mw = BigInt(27), hw = BigInt(28), gw = BigInt(35), _w = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), vw = Symbol.for("nodejs.util.inspect.custom"), yw = 4096 * 32, bw = 128;
+function xw(e) {
+ return {
+ blobToKzgCommitment: (t) => {
+ if ("computeBlobProof" in e) {
+ if ("blobToKzgCommitment" in e && typeof e.blobToKzgCommitment == "function") return J(e.blobToKzgCommitment(Y(t)));
+ } else if ("blobToKzgCommitment" in e && typeof e.blobToKzgCommitment == "function") return J(e.blobToKzgCommitment(t));
+ if ("blobToKZGCommitment" in e && typeof e.blobToKZGCommitment == "function") return J(e.blobToKZGCommitment(Y(t)));
+ q(!1, "unsupported KZG library", "kzg", e);
+ },
+ computeBlobKzgProof: (t, n) => {
+ if ("computeBlobProof" in e && typeof e.computeBlobProof == "function") return J(e.computeBlobProof(Y(t), Y(n)));
+ if ("computeBlobKzgProof" in e && typeof e.computeBlobKzgProof == "function") return e.computeBlobKzgProof(t, n);
+ if ("computeBlobKZGProof" in e && typeof e.computeBlobKZGProof == "function") return J(e.computeBlobKZGProof(Y(t), Y(n)));
+ q(!1, "unsupported KZG library", "kzg", e);
+ }
+ };
+}
+function Sw(e, t) {
+ let n = e.toString(16);
+ for (; n.length < 2;) n = "0" + n;
+ return n += Tx(t).substring(4), "0x" + n;
+}
+function Cw(e) {
+ return e === "0x" ? null : FC(e);
+}
+function ww(e, t) {
+ try {
+ return cw(e);
+ } catch (n) {
+ q(!1, n.message, t, e);
+ }
+}
+function Tw(e, t) {
+ try {
+ if (!Array.isArray(e)) throw Error("authorizationList: invalid array");
+ let t = [];
+ for (let n = 0; n < e.length; n++) {
+ let r = e[n];
+ if (!Array.isArray(r)) throw Error(`authorization[${n}]: invalid array`);
+ if (r.length !== 6) throw Error(`authorization[${n}]: wrong length`);
+ if (!r[1]) throw Error(`authorization[${n}]: null address`);
+ t.push({
+ address: Cw(r[1]),
+ nonce: Dw(r[2], "nonce"),
+ chainId: Dw(r[0], "chainId"),
+ signature: TC.from({
+ yParity: Ew(r[3], "yParity"),
+ r: Rv(r[4], 32),
+ s: Rv(r[5], 32)
+ })
+ });
+ }
+ return t;
+ } catch (n) {
+ q(!1, n.message, t, e);
+ }
+}
+function Ew(e, t) {
+ return e === "0x" ? 0 : Z(e, t);
+}
+function Dw(e, t) {
+ if (e === "0x") return fw;
+ let n = X(e, t);
+ return q(n <= _w, "value exceeds uint size", t, n), n;
+}
+function Ow(e, t) {
+ let n = X(e, "value"), r = Zv(n);
+ return q(r.length <= 32, "value too large", `tx.${t}`, n), r;
+}
+function kw(e) {
+ return cw(e).map((e) => [e.address, e.storageKeys]);
+}
+function Aw(e) {
+ return e.map((e) => [
+ Ow(e.chainId, "chainId"),
+ e.address,
+ Ow(e.nonce, "nonce"),
+ Ow(e.signature.yParity, "yParity"),
+ Zv(e.signature.r),
+ Zv(e.signature._s)
+ ]);
+}
+function jw(e, t) {
+ q(Array.isArray(e), `invalid ${t}`, "value", e);
+ for (let t = 0; t < e.length; t++) q(jv(e[t], 32), "invalid ${ param } hash", `value[${t}]`, e[t]);
+ return e;
+}
+function Mw(e) {
+ let t = Fy(e);
+ q(Array.isArray(t) && (t.length === 9 || t.length === 6), "invalid field count for legacy transaction", "data", e);
+ let n = {
+ type: 0,
+ nonce: Ew(t[0], "nonce"),
+ gasPrice: Dw(t[1], "gasPrice"),
+ gasLimit: Dw(t[2], "gasLimit"),
+ to: Cw(t[3]),
+ value: Dw(t[4], "value"),
+ data: Y(t[5]),
+ chainId: fw
+ };
+ if (t.length === 6) return n;
+ let r = Dw(t[6], "v"), i = Dw(t[7], "r"), a = Dw(t[8], "s");
+ if (i === fw && a === fw) n.chainId = r;
+ else {
+ let e = (r - gw) / pw;
+ e < fw && (e = fw), n.chainId = e, q(e !== fw || r === mw || r === hw, "non-canonical legacy v", "v", t[6]), n.signature = TC.from({
+ r: Rv(t[7], 32),
+ s: Rv(t[8], 32),
+ v: r
+ });
+ }
+ return n;
+}
+function Nw(e, t) {
+ let n = [
+ Ow(e.nonce, "nonce"),
+ Ow(e.gasPrice || 0, "gasPrice"),
+ Ow(e.gasLimit, "gasLimit"),
+ e.to || "0x",
+ Ow(e.value, "value"),
+ e.data
+ ], r = fw;
+ if (e.chainId != fw) r = X(e.chainId, "tx.chainId"), q(!t || t.networkV == null || t.legacyChainId === r, "tx.chainId/sig.v mismatch", "sig", t);
+ else if (e.signature) {
+ let t = e.signature.legacyChainId;
+ t != null && (r = t);
+ }
+ if (!t) return r !== fw && (n.push(Zv(r)), n.push("0x"), n.push("0x")), zy(n);
+ let i = BigInt(27 + t.yParity);
+ return r === fw ? BigInt(t.v) !== i && q(!1, "tx.chainId/sig.v mismatch", "sig", t) : i = TC.getChainIdV(r, t.v), n.push(Zv(i)), n.push(Zv(t.r)), n.push(Zv(t._s)), zy(n);
+}
+function Pw(e, t) {
+ let n;
+ try {
+ if (n = Ew(t[0], "yParity"), n !== 0 && n !== 1) throw Error("bad yParity");
+ } catch {
+ q(!1, "invalid yParity", "yParity", t[0]);
+ }
+ let r = Rv(t[1], 32), i = Rv(t[2], 32);
+ e.signature = TC.from({
+ r,
+ s: i,
+ yParity: n
+ });
+}
+function Fw(e) {
+ let t = Fy(J(e).slice(1));
+ q(Array.isArray(t) && (t.length === 9 || t.length === 12), "invalid field count for transaction type: 2", "data", Y(e));
+ let n = {
+ type: 2,
+ chainId: Dw(t[0], "chainId"),
+ nonce: Ew(t[1], "nonce"),
+ maxPriorityFeePerGas: Dw(t[2], "maxPriorityFeePerGas"),
+ maxFeePerGas: Dw(t[3], "maxFeePerGas"),
+ gasPrice: null,
+ gasLimit: Dw(t[4], "gasLimit"),
+ to: Cw(t[5]),
+ value: Dw(t[6], "value"),
+ data: Y(t[7]),
+ accessList: ww(t[8], "accessList")
+ };
+ return t.length === 9 || Pw(n, t.slice(9)), n;
+}
+function Iw(e, t) {
+ let n = [
+ Ow(e.chainId, "chainId"),
+ Ow(e.nonce, "nonce"),
+ Ow(e.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"),
+ Ow(e.maxFeePerGas || 0, "maxFeePerGas"),
+ Ow(e.gasLimit, "gasLimit"),
+ e.to || "0x",
+ Ow(e.value, "value"),
+ e.data,
+ kw(e.accessList || [])
+ ];
+ return t && (n.push(Ow(t.yParity, "yParity")), n.push(Zv(t.r)), n.push(Zv(t.s))), Pv(["0x02", zy(n)]);
+}
+function Lw(e) {
+ let t = Fy(J(e).slice(1));
+ q(Array.isArray(t) && (t.length === 8 || t.length === 11), "invalid field count for transaction type: 1", "data", Y(e));
+ let n = {
+ type: 1,
+ chainId: Dw(t[0], "chainId"),
+ nonce: Ew(t[1], "nonce"),
+ gasPrice: Dw(t[2], "gasPrice"),
+ gasLimit: Dw(t[3], "gasLimit"),
+ to: Cw(t[4]),
+ value: Dw(t[5], "value"),
+ data: Y(t[6]),
+ accessList: ww(t[7], "accessList")
+ };
+ return t.length === 8 || Pw(n, t.slice(8)), n;
+}
+function Rw(e, t) {
+ let n = [
+ Ow(e.chainId, "chainId"),
+ Ow(e.nonce, "nonce"),
+ Ow(e.gasPrice || 0, "gasPrice"),
+ Ow(e.gasLimit, "gasLimit"),
+ e.to || "0x",
+ Ow(e.value, "value"),
+ e.data,
+ kw(e.accessList || [])
+ ];
+ return t && (n.push(Ow(t.yParity, "recoveryParam")), n.push(Zv(t.r)), n.push(Zv(t.s))), Pv(["0x01", zy(n)]);
+}
+function zw(e) {
+ let t = Fy(J(e).slice(1)), n = "3", r = null, i = null;
+ if (t.length === 4 && Array.isArray(t[0])) {
+ n = "3 (network format)";
+ let e = t[1], r = t[2], a = t[3];
+ q(Array.isArray(e), "invalid network format: blobs not an array", "fields[1]", e), q(Array.isArray(r), "invalid network format: commitments not an array", "fields[2]", r), q(Array.isArray(a), "invalid network format: proofs not an array", "fields[3]", a), q(e.length === r.length, "invalid network format: blobs/commitments length mismatch", "fields", t), q(e.length === a.length, "invalid network format: blobs/proofs length mismatch", "fields", t), i = [];
+ for (let n = 0; n < t[1].length; n++) i.push({
+ data: e[n],
+ commitment: r[n],
+ proof: a[n]
+ });
+ t = t[0];
+ } else if (t.length === 5 && Array.isArray(t[0])) {
+ n = "3 (EIP-7594 network format)", r = Z(t[1]);
+ let e = t[2], a = t[3], o = t[4];
+ q(r === 1, `unsupported EIP-7594 network format version: ${r}`, "fields[1]", r), q(Array.isArray(e), "invalid EIP-7594 network format: blobs not an array", "fields[2]", e), q(Array.isArray(a), "invalid EIP-7594 network format: commitments not an array", "fields[3]", a), q(Array.isArray(o), "invalid EIP-7594 network format: proofs not an array", "fields[4]", o), q(e.length === a.length, "invalid network format: blobs/commitments length mismatch", "fields", t), q(e.length * bw === o.length, "invalid network format: blobs/proofs length mismatch", "fields", t), i = [];
+ for (let t = 0; t < e.length; t++) {
+ let n = [];
+ for (let e = 0; e < bw; e++) n.push(o[t * bw + e]);
+ i.push({
+ data: e[t],
+ commitment: a[t],
+ proof: Pv(n)
+ });
+ }
+ t = t[0];
+ }
+ q(Array.isArray(t) && (t.length === 11 || t.length === 14), `invalid field count for transaction type: ${n}`, "data", Y(e));
+ let a = {
+ type: 3,
+ chainId: Dw(t[0], "chainId"),
+ nonce: Ew(t[1], "nonce"),
+ maxPriorityFeePerGas: Dw(t[2], "maxPriorityFeePerGas"),
+ maxFeePerGas: Dw(t[3], "maxFeePerGas"),
+ gasPrice: null,
+ gasLimit: Dw(t[4], "gasLimit"),
+ to: Cw(t[5]),
+ value: Dw(t[6], "value"),
+ data: Y(t[7]),
+ accessList: ww(t[8], "accessList"),
+ maxFeePerBlobGas: Dw(t[9], "maxFeePerBlobGas"),
+ blobVersionedHashes: t[10],
+ blobWrapperVersion: r
+ };
+ i && (a.blobs = i), q(a.to != null, `invalid address for transaction type: ${n}`, "data", e), q(Array.isArray(a.blobVersionedHashes), "invalid blobVersionedHashes: must be an array", "data", e);
+ for (let t = 0; t < a.blobVersionedHashes.length; t++) q(jv(a.blobVersionedHashes[t], 32), `invalid blobVersionedHash at index ${t}: must be length 32`, "data", e);
+ return t.length === 11 || Pw(a, t.slice(11)), a;
+}
+function Bw(e, t, n) {
+ let r = [
+ Ow(e.chainId, "chainId"),
+ Ow(e.nonce, "nonce"),
+ Ow(e.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"),
+ Ow(e.maxFeePerGas || 0, "maxFeePerGas"),
+ Ow(e.gasLimit, "gasLimit"),
+ e.to || "0x0000000000000000000000000000000000000000",
+ Ow(e.value, "value"),
+ e.data,
+ kw(e.accessList || []),
+ Ow(e.maxFeePerBlobGas || 0, "maxFeePerBlobGas"),
+ jw(e.blobVersionedHashes || [], "blobVersionedHashes")
+ ];
+ if (t && (r.push(Ow(t.yParity, "yParity")), r.push(Zv(t.r)), r.push(Zv(t.s)), n)) {
+ if (e.blobWrapperVersion != null) {
+ let t = Zv(e.blobWrapperVersion), i = [];
+ for (let { proof: e } of n) {
+ let t = J(e), n = t.length / bw;
+ for (let e = 0; e < t.length; e += n) i.push(t.subarray(e, e + n));
+ }
+ return Pv(["0x03", zy([
+ r,
+ t,
+ n.map((e) => e.data),
+ n.map((e) => e.commitment),
+ i
+ ])]);
+ }
+ return Pv(["0x03", zy([
+ r,
+ n.map((e) => e.data),
+ n.map((e) => e.commitment),
+ n.map((e) => e.proof)
+ ])]);
+ }
+ return Pv(["0x03", zy(r)]);
+}
+function Vw(e) {
+ let t = Fy(J(e).slice(1));
+ q(Array.isArray(t) && (t.length === 10 || t.length === 13), "invalid field count for transaction type: 4", "data", Y(e));
+ let n = {
+ type: 4,
+ chainId: Dw(t[0], "chainId"),
+ nonce: Ew(t[1], "nonce"),
+ maxPriorityFeePerGas: Dw(t[2], "maxPriorityFeePerGas"),
+ maxFeePerGas: Dw(t[3], "maxFeePerGas"),
+ gasPrice: null,
+ gasLimit: Dw(t[4], "gasLimit"),
+ to: Cw(t[5]),
+ value: Dw(t[6], "value"),
+ data: Y(t[7]),
+ accessList: ww(t[8], "accessList"),
+ authorizationList: Tw(t[9], "authorizationList")
+ };
+ return t.length === 10 || Pw(n, t.slice(10)), n;
+}
+function Hw(e, t) {
+ let n = [
+ Ow(e.chainId, "chainId"),
+ Ow(e.nonce, "nonce"),
+ Ow(e.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"),
+ Ow(e.maxFeePerGas || 0, "maxFeePerGas"),
+ Ow(e.gasLimit, "gasLimit"),
+ e.to || "0x",
+ Ow(e.value, "value"),
+ e.data,
+ kw(e.accessList || []),
+ Aw(e.authorizationList || [])
+ ];
+ return t && (n.push(Ow(t.yParity, "yParity")), n.push(Zv(t.r)), n.push(Zv(t.s))), Pv(["0x04", zy(n)]);
+}
+var Uw = class e {
+ #e;
+ #t;
+ #n;
+ #r;
+ #i;
+ #a;
+ #o;
+ #s;
+ #c;
+ #l;
+ #u;
+ #d;
+ #f;
+ #p;
+ #m;
+ #h;
+ #g;
+ #_;
+ get type() {
+ return this.#e;
+ }
+ set type(e) {
+ switch (e) {
+ case null:
+ this.#e = null;
+ break;
+ case 0:
+ case "legacy":
+ this.#e = 0;
+ break;
+ case 1:
+ case "berlin":
+ case "eip-2930":
+ this.#e = 1;
+ break;
+ case 2:
+ case "london":
+ case "eip-1559":
+ this.#e = 2;
+ break;
+ case 3:
+ case "cancun":
+ case "eip-4844":
+ this.#e = 3;
+ break;
+ case 4:
+ case "pectra":
+ case "eip-7702":
+ this.#e = 4;
+ break;
+ default: q(!1, "unsupported transaction type", "type", e);
+ }
+ }
+ get typeName() {
+ switch (this.type) {
+ case 0: return "legacy";
+ case 1: return "eip-2930";
+ case 2: return "eip-1559";
+ case 3: return "eip-4844";
+ case 4: return "eip-7702";
+ }
+ return null;
+ }
+ get to() {
+ let e = this.#t;
+ return e == null && this.type === 3 ? fC : e;
+ }
+ set to(e) {
+ this.#t = e == null ? null : FC(e);
+ }
+ get nonce() {
+ return this.#r;
+ }
+ set nonce(e) {
+ this.#r = Z(e, "value");
+ }
+ get gasLimit() {
+ return this.#i;
+ }
+ set gasLimit(e) {
+ this.#i = X(e);
+ }
+ get gasPrice() {
+ let e = this.#a;
+ return e == null && (this.type === 0 || this.type === 1) ? fw : e;
+ }
+ set gasPrice(e) {
+ this.#a = e == null ? null : X(e, "gasPrice");
+ }
+ get maxPriorityFeePerGas() {
+ return this.#o ?? (this.type === 2 || this.type === 3 ? fw : null);
+ }
+ set maxPriorityFeePerGas(e) {
+ this.#o = e == null ? null : X(e, "maxPriorityFeePerGas");
+ }
+ get maxFeePerGas() {
+ return this.#s ?? (this.type === 2 || this.type === 3 ? fw : null);
+ }
+ set maxFeePerGas(e) {
+ this.#s = e == null ? null : X(e, "maxFeePerGas");
+ }
+ get data() {
+ return this.#n;
+ }
+ set data(e) {
+ this.#n = Y(e);
+ }
+ get value() {
+ return this.#c;
+ }
+ set value(e) {
+ this.#c = X(e, "value");
+ }
+ get chainId() {
+ return this.#l;
+ }
+ set chainId(e) {
+ this.#l = X(e);
+ }
+ get signature() {
+ return this.#u || null;
+ }
+ set signature(e) {
+ this.#u = e == null ? null : TC.from(e);
+ }
+ isValid() {
+ let e = this.signature;
+ if (e && !e.isValid()) return !1;
+ let t = this.authorizationList;
+ if (t) {
+ for (let e of t) if (!e.signature.isValid()) return !1;
+ }
+ return !0;
+ }
+ get accessList() {
+ return (this.#d || null) ?? (this.type === 1 || this.type === 2 || this.type === 3 ? [] : null);
+ }
+ set accessList(e) {
+ this.#d = e == null ? null : cw(e);
+ }
+ get authorizationList() {
+ let e = this.#g || null;
+ return e == null && this.type === 4 ? [] : e;
+ }
+ set authorizationList(e) {
+ this.#g = e == null ? null : e.map((e) => lw(e));
+ }
+ get maxFeePerBlobGas() {
+ let e = this.#f;
+ return e == null && this.type === 3 ? fw : e;
+ }
+ set maxFeePerBlobGas(e) {
+ this.#f = e == null ? null : X(e, "maxFeePerBlobGas");
+ }
+ get blobVersionedHashes() {
+ let e = this.#p;
+ return e == null && this.type === 3 ? [] : e;
+ }
+ set blobVersionedHashes(e) {
+ if (e != null) {
+ q(Array.isArray(e), "blobVersionedHashes must be an Array", "value", e), e = e.slice();
+ for (let t = 0; t < e.length; t++) q(jv(e[t], 32), "invalid blobVersionedHash", `value[${t}]`, e[t]);
+ }
+ this.#p = e;
+ }
+ get blobs() {
+ return this.#h == null ? null : this.#h.map((e) => Object.assign({}, e));
+ }
+ set blobs(e) {
+ if (e == null) {
+ this.#h = null;
+ return;
+ }
+ let t = [], n = [];
+ for (let r = 0; r < e.length; r++) {
+ let i = e[r];
+ if (Mv(i)) {
+ K(this.#m, "adding a raw blob requires a KZG library", "UNSUPPORTED_OPERATION", { operation: "set blobs()" });
+ let e = J(i);
+ if (q(e.length <= yw, "blob is too large", `blobs[${r}]`, i), e.length !== yw) {
+ let t = new Uint8Array(yw);
+ t.set(e), e = t;
+ }
+ let a = this.#m.blobToKzgCommitment(e), o = Y(this.#m.computeBlobKzgProof(e, a));
+ t.push({
+ data: Y(e),
+ commitment: Y(a),
+ proof: o
+ }), n.push(Sw(1, a));
+ } else {
+ let e = Y(i.data), r = Y(i.commitment), a = Y(i.proof);
+ t.push({
+ data: e,
+ commitment: r,
+ proof: a
+ }), n.push(Sw(1, r));
+ }
+ }
+ this.#h = t, this.#p = n;
+ }
+ get kzg() {
+ return this.#m;
+ }
+ set kzg(e) {
+ e == null ? this.#m = null : this.#m = xw(e);
+ }
+ get blobWrapperVersion() {
+ return this.#_;
+ }
+ set blobWrapperVersion(e) {
+ this.#_ = e;
+ }
+ constructor() {
+ this.#e = null, this.#t = null, this.#r = 0, this.#i = fw, this.#a = null, this.#o = null, this.#s = null, this.#n = "0x", this.#c = fw, this.#l = fw, this.#u = null, this.#d = null, this.#f = null, this.#p = null, this.#m = null, this.#h = null, this.#g = null, this.#_ = null;
+ }
+ get hash() {
+ return this.signature == null ? null : vx(this.#v(!0, !1));
+ }
+ get unsignedHash() {
+ return vx(this.unsignedSerialized);
+ }
+ get from() {
+ return this.signature == null ? null : dw(this.unsignedHash, this.signature.getCanonical());
+ }
+ get fromPublicKey() {
+ return this.signature == null ? null : EC.recoverPublicKey(this.unsignedHash, this.signature.getCanonical());
+ }
+ isSigned() {
+ return this.signature != null;
+ }
+ #v(e, t) {
+ K(!e || this.signature != null, "cannot serialize unsigned transaction; maybe you meant .unsignedSerialized", "UNSUPPORTED_OPERATION", { operation: ".serialized" });
+ let n = e ? this.signature : null;
+ switch (this.inferType()) {
+ case 0: return Nw(this, n);
+ case 1: return Rw(this, n);
+ case 2: return Iw(this, n);
+ case 3: return Bw(this, n, t ? this.blobs : null);
+ case 4: return Hw(this, n);
+ }
+ K(!1, "unsupported transaction type", "UNSUPPORTED_OPERATION", { operation: ".serialized" });
+ }
+ get serialized() {
+ return this.#v(!0, !0);
+ }
+ get unsignedSerialized() {
+ return this.#v(!1, !1);
+ }
+ inferType() {
+ let e = this.inferTypes();
+ return e.indexOf(2) >= 0 ? 2 : e.pop();
+ }
+ inferTypes() {
+ let e = this.gasPrice != null, t = this.maxFeePerGas != null || this.maxPriorityFeePerGas != null, n = this.accessList != null, r = this.#f != null || this.#p;
+ this.maxFeePerGas != null && this.maxPriorityFeePerGas != null && K(this.maxFeePerGas >= this.maxPriorityFeePerGas, "priorityFee cannot be more than maxFee", "BAD_DATA", { value: this }), K(!t || this.type !== 0 && this.type !== 1, "transaction type cannot have maxFeePerGas or maxPriorityFeePerGas", "BAD_DATA", { value: this }), K(this.type !== 0 || !n, "legacy transaction cannot have accessList", "BAD_DATA", { value: this });
+ let i = [];
+ return this.type == null ? this.authorizationList && this.authorizationList.length ? i.push(4) : t ? i.push(2) : e ? (i.push(1), n || i.push(0)) : n ? (i.push(1), i.push(2)) : r && this.to ? i.push(3) : (i.push(0), i.push(1), i.push(2), i.push(3)) : i.push(this.type), i.sort(), i;
+ }
+ isLegacy() {
+ return this.type === 0;
+ }
+ isBerlin() {
+ return this.type === 1;
+ }
+ isLondon() {
+ return this.type === 2;
+ }
+ isCancun() {
+ return this.type === 3;
+ }
+ clone() {
+ return e.from(this);
+ }
+ toJSON() {
+ let e = (e) => e == null ? null : e.toString();
+ return {
+ type: this.type,
+ to: this.to,
+ data: this.data,
+ nonce: this.nonce,
+ gasLimit: e(this.gasLimit),
+ gasPrice: e(this.gasPrice),
+ maxPriorityFeePerGas: e(this.maxPriorityFeePerGas),
+ maxFeePerGas: e(this.maxFeePerGas),
+ value: e(this.value),
+ chainId: e(this.chainId),
+ sig: this.signature ? this.signature.toJSON() : null,
+ accessList: this.accessList
+ };
+ }
+ [vw]() {
+ return this.toString();
+ }
+ toString() {
+ let e = [], t = (t) => {
+ let n = this[t];
+ typeof n == "string" && (n = JSON.stringify(n)), e.push(`${t}: ${n}`);
+ };
+ this.type && t("type"), t("to"), t("data"), t("nonce"), t("gasLimit"), t("value"), this.chainId != null && t("chainId"), this.signature && (t("from"), e.push(`signature: ${this.signature.toString()}`));
+ let n = this.authorizationList;
+ if (n) {
+ let t = [];
+ for (let e of n) {
+ let n = [];
+ n.push(`address: ${JSON.stringify(e.address)}`), e.nonce != null && n.push(`nonce: ${e.nonce}`), e.chainId != null && n.push(`chainId: ${e.chainId}`), e.signature && n.push(`signature: ${e.signature.toString()}`), t.push(`Authorization { ${n.join(", ")} }`);
+ }
+ e.push(`authorizations: [ ${t.join(", ")} ]`);
+ }
+ return `Transaction { ${e.join(", ")} }`;
+ }
+ static from(t) {
+ if (t == null) return new e();
+ if (typeof t == "string") {
+ let n = J(t);
+ if (n[0] >= 127) return e.from(Mw(n));
+ switch (n[0]) {
+ case 1: return e.from(Lw(n));
+ case 2: return e.from(Fw(n));
+ case 3: return e.from(zw(n));
+ case 4: return e.from(Vw(n));
+ }
+ K(!1, "unsupported transaction type", "UNSUPPORTED_OPERATION", { operation: "from" });
+ }
+ let n = new e();
+ return t.type != null && (n.type = t.type), t.to != null && (n.to = t.to), t.nonce != null && (n.nonce = t.nonce), t.gasLimit != null && (n.gasLimit = t.gasLimit), t.gasPrice != null && (n.gasPrice = t.gasPrice), t.maxPriorityFeePerGas != null && (n.maxPriorityFeePerGas = t.maxPriorityFeePerGas), t.maxFeePerGas != null && (n.maxFeePerGas = t.maxFeePerGas), t.maxFeePerBlobGas != null && (n.maxFeePerBlobGas = t.maxFeePerBlobGas), t.data != null && (n.data = t.data), t.value != null && (n.value = t.value), t.chainId != null && (n.chainId = t.chainId), t.signature != null && (n.signature = TC.from(t.signature)), t.accessList != null && (n.accessList = t.accessList), t.authorizationList != null && (n.authorizationList = t.authorizationList), t.blobVersionedHashes != null && (n.blobVersionedHashes = t.blobVersionedHashes), t.kzg != null && (n.kzg = t.kzg), t.blobWrapperVersion != null && (n.blobWrapperVersion = t.blobWrapperVersion), t.blobs != null && (n.blobs = t.blobs), t.hash != null && (q(n.isSigned(), "unsigned transaction cannot define '.hash'", "tx", t), q(n.hash === t.hash, "hash mismatch", "tx", t)), t.from != null && (q(n.isSigned(), "unsigned transaction cannot define '.from'", "tx", t), q(n.from.toLowerCase() === (t.from || "").toLowerCase(), "from mismatch", "tx", t)), n;
+ }
+};
+//#endregion
+//#region node_modules/ethers/lib.esm/hash/id.js
+function Ww(e) {
+ return vx(uy(e));
+}
+//#endregion
+//#region node_modules/@adraffy/ens-normalize/dist/index.mjs
+var Gw = "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", Kw = new Map([
+ [8217, "apostrophe"],
+ [8260, "fraction slash"],
+ [12539, "middle dot"]
+]), qw = 4;
+function Jw(e) {
+ let t = 0;
+ function n() {
+ return e[t++] << 8 | e[t++];
+ }
+ let r = n(), i = 1, a = [0, 1];
+ for (let e = 1; e < r; e++) a.push(i += n());
+ let o = n(), s = t;
+ t += o;
+ let c = 0, l = 0;
+ function u() {
+ return c == 0 && (l = l << 8 | e[t++], c = 8), l >> --c & 1;
+ }
+ let d = 2 ** 31, f = d >>> 1, p = f >> 1, m = d - 1, h = 0;
+ for (let e = 0; e < 31; e++) h = h << 1 | u();
+ let g = [], _ = 0, v = d;
+ for (;;) {
+ let e = Math.floor(((h - _ + 1) * i - 1) / v), t = 0, n = r;
+ for (; n - t > 1;) {
+ let r = t + n >>> 1;
+ e < a[r] ? n = r : t = r;
+ }
+ if (t == 0) break;
+ g.push(t);
+ let o = _ + Math.floor(v * a[t] / i), s = _ + Math.floor(v * a[t + 1] / i) - 1;
+ for (; ((o ^ s) & f) == 0;) h = h << 1 & m | u(), o = o << 1 & m, s = s << 1 & m | 1;
+ for (; o & ~s & p;) h = h & f | h << 1 & m >>> 1 | u(), o = o << 1 ^ f, s = (s ^ f) << 1 | f | 1;
+ _ = o, v = 1 + s - o;
+ }
+ let y = r - 4;
+ return g.map((t) => {
+ switch (t - y) {
+ case 3: return y + 65792 + (e[s++] << 16 | e[s++] << 8 | e[s++]);
+ case 2: return y + 256 + (e[s++] << 8 | e[s++]);
+ case 1: return y + e[s++];
+ default: return t - 1;
+ }
+ });
+}
+function Yw(e) {
+ let t = 0;
+ return () => e[t++];
+}
+function Xw(e) {
+ return Yw(Jw(Zw(e)));
+}
+function Zw(e) {
+ let t = [];
+ [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"].forEach((e, n) => t[e.charCodeAt(0)] = n);
+ let n = e.length, r = new Uint8Array(6 * n >> 3);
+ for (let i = 0, a = 0, o = 0, s = 0; i < n; i++) s = s << 6 | t[e.charCodeAt(i)], o += 6, o >= 8 && (r[a++] = s >> (o -= 8));
+ return r;
+}
+function Qw(e) {
+ return e & 1 ? ~e >> 1 : e >> 1;
+}
+function $w(e, t) {
+ let n = Array(e);
+ for (let r = 0, i = 0; r < e; r++) n[r] = i += Qw(t());
+ return n;
+}
+function eT(e, t = 0) {
+ let n = [];
+ for (;;) {
+ let r = e(), i = e();
+ if (!i) break;
+ t += r;
+ for (let e = 0; e < i; e++) n.push(t + e);
+ t += i + 1;
+ }
+ return n;
+}
+function tT(e) {
+ return rT(() => {
+ let t = eT(e);
+ if (t.length) return t;
+ });
+}
+function nT(e) {
+ let t = [];
+ for (;;) {
+ let n = e();
+ if (n == 0) break;
+ t.push(aT(n, e));
+ }
+ for (;;) {
+ let n = e() - 1;
+ if (n < 0) break;
+ t.push(oT(n, e));
+ }
+ return t.flat();
+}
+function rT(e) {
+ let t = [];
+ for (;;) {
+ let n = e(t.length);
+ if (!n) break;
+ t.push(n);
+ }
+ return t;
+}
+function iT(e, t, n) {
+ let r = Array(e).fill().map(() => []);
+ for (let i = 0; i < t; i++) $w(e, n).forEach((e, t) => r[t].push(e));
+ return r;
+}
+function aT(e, t) {
+ let n = 1 + t(), r = t(), i = rT(t);
+ return iT(i.length, 1 + e, t).flatMap((e, t) => {
+ let [a, ...o] = e;
+ return Array(i[t]).fill().map((e, t) => {
+ let i = t * r;
+ return [a + t * n, o.map((e) => e + i)];
+ });
+ });
+}
+function oT(e, t) {
+ return iT(1 + t(), 1 + e, t).map((e) => [e[0], e.slice(1)]);
+}
+function sT(e) {
+ let t = [], n = eT(e);
+ return i(r([]), []), t;
+ function r(t) {
+ return {
+ S: e(),
+ B: rT(() => {
+ let t = eT(e).map((e) => n[e]);
+ if (t.length) return r(t);
+ }),
+ Q: t
+ };
+ }
+ function i({ S: e, B: n }, r, a) {
+ if (!(e & 4 && a === r[r.length - 1])) {
+ e & 2 && (a = r[r.length - 1]), e & 1 && t.push(r);
+ for (let e of n) for (let t of e.Q) i(e, [...r, t], a);
+ }
+ }
+}
+function cT(e) {
+ return e.toString(16).toUpperCase().padStart(2, "0");
+}
+function lT(e) {
+ return `{${cT(e)}}`;
+}
+function uT(e) {
+ let t = [];
+ for (let n = 0, r = e.length; n < r;) {
+ let r = e.codePointAt(n);
+ n += r < 65536 ? 1 : 2, t.push(r);
+ }
+ return t;
+}
+function dT(e) {
+ let t = 4096, n = e.length;
+ if (n < t) return String.fromCodePoint(...e);
+ let r = [];
+ for (let i = 0; i < n;) r.push(String.fromCodePoint(...e.slice(i, i += t)));
+ return r.join("");
+}
+function fT(e, t) {
+ let n = e.length, r = n - t.length;
+ for (let i = 0; r == 0 && i < n; i++) r = e[i] - t[i];
+ return r;
+}
+var pT = "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", mT = 44032, hT = 4352, gT = 4449, _T = 4519, vT = 19, yT = 21, bT = 28, xT = yT * bT, ST = mT + vT * xT, CT = hT + vT, wT = gT + yT, TT = _T + bT;
+function ET(e) {
+ return e >> 24 & 255;
+}
+function DT(e) {
+ return e & 16777215;
+}
+var OT, kT, AT, jT;
+function MT() {
+ let e = Xw(pT);
+ OT = new Map(tT(e).flatMap((e, t) => e.map((e) => [e, t + 1 << 24]))), kT = new Set(eT(e)), AT = /* @__PURE__ */ new Map(), jT = /* @__PURE__ */ new Map();
+ for (let [t, n] of nT(e)) {
+ if (!kT.has(t) && n.length == 2) {
+ let [e, r] = n, i = jT.get(e);
+ i || (i = /* @__PURE__ */ new Map(), jT.set(e, i)), i.set(r, t);
+ }
+ AT.set(t, n.reverse());
+ }
+}
+function NT(e) {
+ return e >= mT && e < ST;
+}
+function PT(e, t) {
+ if (e >= hT && e < CT && t >= gT && t < wT) return mT + (e - hT) * xT + (t - gT) * bT;
+ if (NT(e) && t > _T && t < TT && (e - mT) % bT == 0) return e + (t - _T);
+ {
+ let n = jT.get(e);
+ return n && (n = n.get(t), n) ? n : -1;
+ }
+}
+function FT(e) {
+ OT || MT();
+ let t = [], n = [], r = !1;
+ function i(e) {
+ let n = OT.get(e);
+ n && (r = !0, e |= n), t.push(e);
+ }
+ for (let r of e) for (;;) {
+ if (r < 128) t.push(r);
+ else if (NT(r)) {
+ let e = r - mT, t = e / xT | 0, n = e % xT / bT | 0, a = e % bT;
+ i(hT + t), i(gT + n), a > 0 && i(_T + a);
+ } else {
+ let e = AT.get(r);
+ e ? n.push(...e) : i(r);
+ }
+ if (!n.length) break;
+ r = n.pop();
+ }
+ if (r && t.length > 1) {
+ let e = ET(t[0]);
+ for (let n = 1; n < t.length; n++) {
+ let r = ET(t[n]);
+ if (r == 0 || e <= r) {
+ e = r;
+ continue;
+ }
+ let i = n - 1;
+ for (;;) {
+ let n = t[i + 1];
+ if (t[i + 1] = t[i], t[i] = n, !i || (e = ET(t[--i]), e <= r)) break;
+ }
+ e = ET(t[n]);
+ }
+ }
+ return t;
+}
+function IT(e) {
+ let t = [], n = [], r = -1, i = 0;
+ for (let a of e) {
+ let e = ET(a), o = DT(a);
+ if (r == -1) e == 0 ? r = o : t.push(o);
+ else if (i > 0 && i >= e) e == 0 ? (t.push(r, ...n), n.length = 0, r = o) : n.push(o), i = e;
+ else {
+ let a = PT(r, o);
+ a >= 0 ? r = a : i == 0 && e == 0 ? (t.push(r), r = o) : (n.push(o), i = e);
+ }
+ }
+ return r >= 0 && t.push(r, ...n), t;
+}
+function LT(e) {
+ return FT(e).map(DT);
+}
+function RT(e) {
+ return IT(FT(e));
+}
+var zT = 45, BT = ".", VT = 65039, HT = 1, UT = (e) => Array.from(e);
+function WT(e, t) {
+ return e.P.has(t) || e.Q.has(t);
+}
+var GT = class extends Array {
+ get is_emoji() {
+ return !0;
+ }
+}, KT, qT, JT, YT, XT, ZT, QT, $T, eE, tE, nE;
+function rE() {
+ if (KT) return;
+ let e = Xw(Gw), t = () => eT(e), n = () => new Set(t()), r = (e, t) => t.forEach((t) => e.add(t));
+ KT = new Map(nT(e)), qT = n(), JT = t(), YT = new Set(t().map((e) => JT[e])), JT = new Set(JT), XT = n(), n();
+ let i = tT(e), a = e(), o = () => {
+ let e = /* @__PURE__ */ new Set();
+ return t().forEach((t) => r(e, i[t])), r(e, t()), e;
+ };
+ ZT = rT((t) => {
+ let n = rT(e).map((e) => e + 96);
+ if (n.length) {
+ let r = t >= a;
+ n[0] -= 32, n = dT(n), r && (n = `Restricted[${n}]`);
+ let i = o(), s = o(), c = !e();
+ return {
+ N: n,
+ P: i,
+ Q: s,
+ M: c,
+ R: r
+ };
+ }
+ }), QT = n(), $T = /* @__PURE__ */ new Map();
+ let s = t().concat(UT(QT)).sort((e, t) => e - t);
+ s.forEach((t, n) => {
+ let r = e(), i = s[n] = r ? s[n - r] : {
+ V: [],
+ M: /* @__PURE__ */ new Map()
+ };
+ i.V.push(t), QT.has(t) || $T.set(t, i);
+ });
+ for (let { V: e, M: t } of new Set($T.values())) {
+ let n = [];
+ for (let t of e) {
+ let e = ZT.filter((e) => WT(e, t)), i = n.find(({ G: t }) => e.some((e) => t.has(e)));
+ i || (i = {
+ G: /* @__PURE__ */ new Set(),
+ V: []
+ }, n.push(i)), i.V.push(t), r(i.G, e);
+ }
+ let i = n.flatMap((e) => UT(e.G));
+ for (let { G: e, V: r } of n) {
+ let n = new Set(i.filter((t) => !e.has(t)));
+ for (let e of r) t.set(e, n);
+ }
+ }
+ eE = /* @__PURE__ */ new Set();
+ let c = /* @__PURE__ */ new Set(), l = (e) => eE.has(e) ? c.add(e) : eE.add(e);
+ for (let e of ZT) {
+ for (let t of e.P) l(t);
+ for (let t of e.Q) l(t);
+ }
+ for (let e of eE) !$T.has(e) && !c.has(e) && $T.set(e, HT);
+ r(eE, LT(eE)), tE = sT(e).map((e) => GT.from(e)).sort(fT), nE = /* @__PURE__ */ new Map();
+ for (let e of tE) {
+ let t = [nE];
+ for (let n of e) {
+ let e = t.map((e) => {
+ let t = e.get(n);
+ return t || (t = /* @__PURE__ */ new Map(), e.set(n, t)), t;
+ });
+ n === VT ? t.push(...e) : t = e;
+ }
+ for (let n of t) n.V = e;
+ }
+}
+function iE(e) {
+ return (dE(e) ? "" : `${aE(lE([e]))} `) + lT(e);
+}
+function aE(e) {
+ return `"${e}"\u200E`;
+}
+function oE(e) {
+ if (e.length >= 4 && e[2] == zT && e[3] == zT) throw Error(`invalid label extension: "${dT(e.slice(0, 4))}"`);
+}
+function sE(e) {
+ for (let t = e.lastIndexOf(95); t > 0;) if (e[--t] !== 95) throw Error("underscore allowed only at start");
+}
+function cE(e) {
+ let t = e[0], n = Kw.get(t);
+ if (n) throw yE(`leading ${n}`);
+ let r = e.length, i = -1;
+ for (let a = 1; a < r; a++) {
+ t = e[a];
+ let r = Kw.get(t);
+ if (r) {
+ if (i == a) throw yE(`${n} + ${r}`);
+ i = a + 1, n = r;
+ }
+ }
+ if (i == r) throw yE(`trailing ${n}`);
+}
+function lE(e, t = Infinity, n = lT) {
+ let r = [];
+ uE(e[0]) && r.push("◌"), e.length > t && (t >>= 1, e = [
+ ...e.slice(0, t),
+ 8230,
+ ...e.slice(-t)
+ ]);
+ let i = 0, a = e.length;
+ for (let t = 0; t < a; t++) {
+ let a = e[t];
+ dE(a) && (r.push(dT(e.slice(i, t))), r.push(n(a)), i = t + 1);
+ }
+ return r.push(dT(e.slice(i, a))), r.join("");
+}
+function uE(e) {
+ return rE(), JT.has(e);
+}
+function dE(e) {
+ return rE(), XT.has(e);
+}
+function fE(e) {
+ return gE(pE(e, RT, SE));
+}
+function pE(e, t, n) {
+ if (!e) return [];
+ rE();
+ let r = 0;
+ return e.split(BT).map((e) => {
+ let i = uT(e), a = {
+ input: i,
+ offset: r
+ };
+ r += i.length + 1;
+ try {
+ let e = a.tokens = xE(i, t, n), r = e.length, o;
+ if (!r) throw Error("empty label");
+ let s = a.output = e.flat();
+ if (sE(s), !(a.emoji = r > 1 || e[0].is_emoji) && s.every((e) => e < 128)) oE(s), o = "ASCII";
+ else {
+ let t = e.flatMap((e) => e.is_emoji ? [] : e);
+ if (!t.length) o = "Emoji";
+ else {
+ if (JT.has(s[0])) throw yE("leading combining mark");
+ for (let t = 1; t < r; t++) {
+ let n = e[t];
+ if (!n.is_emoji && JT.has(n[0])) throw yE(`emoji + combining mark: "${dT(e[t - 1])} + ${lE([n[0]])}"`);
+ }
+ cE(s);
+ let n = UT(new Set(t)), [i] = hE(n);
+ bE(i, t), mE(i, n), o = i.N;
+ }
+ }
+ a.type = o;
+ } catch (e) {
+ a.error = e;
+ }
+ return a;
+ });
+}
+function mE(e, t) {
+ let n, r = [];
+ for (let e of t) {
+ let t = $T.get(e);
+ if (t === HT) return;
+ if (t) {
+ let r = t.M.get(e);
+ if (n = n ? n.filter((e) => r.has(e)) : UT(r), !n.length) return;
+ } else r.push(e);
+ }
+ if (n) {
+ for (let t of n) if (r.every((e) => WT(t, e))) throw Error(`whole-script confusable: ${e.N}/${t.N}`);
+ }
+}
+function hE(e) {
+ let t = ZT;
+ for (let n of e) {
+ let e = t.filter((e) => WT(e, n));
+ if (!e.length) throw ZT.some((e) => WT(e, n)) ? vE(t[0], n) : _E(n);
+ if (t = e, e.length == 1) break;
+ }
+ return t;
+}
+function gE(e) {
+ return e.map(({ input: t, error: n, output: r }) => {
+ if (n) {
+ let r = n.message;
+ throw Error(e.length == 1 ? r : `Invalid label ${aE(lE(t, 63))}: ${r}`);
+ }
+ return dT(r);
+ }).join(BT);
+}
+function _E(e) {
+ return /* @__PURE__ */ Error(`disallowed character: ${iE(e)}`);
+}
+function vE(e, t) {
+ let n = iE(t), r = ZT.find((e) => e.P.has(t));
+ return r && (n = `${r.N} ${n}`), /* @__PURE__ */ Error(`illegal mixture: ${e.N} + ${n}`);
+}
+function yE(e) {
+ return /* @__PURE__ */ Error(`illegal placement: ${e}`);
+}
+function bE(e, t) {
+ for (let n of t) if (!WT(e, n)) throw vE(e, n);
+ if (e.M) {
+ let e = LT(t);
+ for (let t = 1, n = e.length; t < n; t++) if (YT.has(e[t])) {
+ let r = t + 1;
+ for (let i; r < n && YT.has(i = e[r]); r++) for (let n = t; n < r; n++) if (e[n] == i) throw Error(`duplicate non-spacing marks: ${iE(i)}`);
+ if (r - t > qw) throw Error(`excessive non-spacing marks: ${aE(lE(e.slice(t - 1, r)))} (${r - t}/${qw})`);
+ t = r;
+ }
+ }
+}
+function xE(e, t, n) {
+ let r = [], i = [];
+ for (e = e.slice().reverse(); e.length;) {
+ let a = CE(e);
+ if (a) i.length && (r.push(t(i)), i = []), r.push(n(a));
+ else {
+ let t = e.pop();
+ if (eE.has(t)) i.push(t);
+ else {
+ let e = KT.get(t);
+ if (e) i.push(...e);
+ else if (!qT.has(t)) throw _E(t);
+ }
+ }
+ }
+ return i.length && r.push(t(i)), r;
+}
+function SE(e) {
+ return e.filter((e) => e != VT);
+}
+function CE(e, t) {
+ let n = nE, r, i = e.length;
+ for (; i && (n = n.get(e[--i]), n);) {
+ let { V: a } = n;
+ a && (r = a, t && t.push(...e.slice(i).reverse()), e.length = i);
+ }
+ return r;
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/hash/namehash.js
+var wE = new Uint8Array(32);
+wE.fill(0);
+function TE(e) {
+ return q(e.length !== 0, "invalid ENS name; empty component", "comp", e), e;
+}
+function EE(e) {
+ let t = uy(DE(e)), n = [];
+ if (e.length === 0) return n;
+ let r = 0;
+ for (let e = 0; e < t.length; e++) t[e] === 46 && (n.push(TE(t.slice(r, e))), r = e + 1);
+ return q(r < t.length, "invalid ENS name; empty component", "name", e), n.push(TE(t.slice(r))), n;
+}
+function DE(e) {
+ try {
+ if (e.length === 0) throw Error("empty label");
+ return fE(e);
+ } catch (t) {
+ q(!1, `invalid ENS name (${t.message})`, "name", e);
+ }
+}
+function OE(e) {
+ q(typeof e == "string", "invalid ENS name; not a string", "name", e), q(e.length, "invalid ENS name (empty label)", "name", e);
+ let t = wE, n = EE(e);
+ for (; n.length;) t = vx(Pv([t, vx(n.pop())]));
+ return Y(t);
+}
+function kE(e, t) {
+ let n = t ?? 63;
+ return q(n <= 255, "DNS encoded label cannot exceed 255", "length", n), Y(Pv(EE(e).map((t) => {
+ q(t.length <= n, `label ${JSON.stringify(e)} exceeds ${n} bytes`, "name", e);
+ let r = new Uint8Array(t.length + 1);
+ return r.set(t, 1), r[0] = r.length - 1, r;
+ }))) + "00";
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/hash/typed-data.js
+var AE = new Uint8Array(32);
+AE.fill(0);
+var jE = BigInt(-1), ME = BigInt(0), NE = BigInt(1), PE = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
+function FE(e) {
+ let t = J(e), n = t.length % 32;
+ return n ? Pv([t, AE.slice(n)]) : Y(t);
+}
+var IE = Xv(NE, 32), LE = Xv(ME, 32), RE = {
+ name: "string",
+ version: "string",
+ chainId: "uint256",
+ verifyingContract: "address",
+ salt: "bytes32"
+}, zE = [
+ "name",
+ "version",
+ "chainId",
+ "verifyingContract",
+ "salt"
+];
+function BE(e) {
+ return function(t) {
+ return q(typeof t == "string", `invalid domain value for ${JSON.stringify(e)}`, `domain.${e}`, t), t;
+ };
+}
+var VE = {
+ name: BE("name"),
+ version: BE("version"),
+ chainId: function(e) {
+ let t = X(e, "domain.chainId");
+ return q(t >= 0, "invalid chain ID", "domain.chainId", e), Number.isSafeInteger(t) ? Number(t) : Qv(t);
+ },
+ verifyingContract: function(e) {
+ try {
+ return FC(e).toLowerCase();
+ } catch {}
+ q(!1, "invalid domain value \"verifyingContract\"", "domain.verifyingContract", e);
+ },
+ salt: function(e) {
+ let t = J(e, "domain.salt");
+ return q(t.length === 32, "invalid domain value \"salt\"", "domain.salt", e), Y(t);
+ }
+};
+function HE(e) {
+ {
+ let t = e.match(/^(u?)int(\d+)$/);
+ if (t) {
+ let n = t[1] === "", r = parseInt(t[2]);
+ q(r % 8 == 0 && r !== 0 && r <= 256 && t[2] === String(r), "invalid numeric width", "type", e);
+ let i = Gv(PE, n ? r - 1 : r), a = n ? (i + NE) * jE : ME;
+ return function(t) {
+ let r = X(t, "value");
+ return q(r >= a && r <= i, `value out-of-bounds for ${e}`, "value", r), Xv(n ? Wv(r, 256) : r, 32);
+ };
+ }
+ }
+ {
+ let t = e.match(/^bytes(\d+)$/);
+ if (t) {
+ let n = parseInt(t[1]);
+ return q(n !== 0 && n <= 32 && t[1] === String(n), "invalid bytes width", "type", e), function(t) {
+ return q(J(t).length === n, `invalid length for ${e}`, "value", t), FE(t);
+ };
+ }
+ }
+ switch (e) {
+ case "address": return function(e) {
+ return Rv(FC(e), 32);
+ };
+ case "bool": return function(e) {
+ return e ? IE : LE;
+ };
+ case "bytes": return function(e) {
+ return vx(e);
+ };
+ case "string": return function(e) {
+ return Ww(e);
+ };
+ }
+ return null;
+}
+function UE(e, t) {
+ return `${e}(${t.map(({ name: e, type: t }) => t + " " + e).join(",")})`;
+}
+function WE(e) {
+ let t = e.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/);
+ return t ? {
+ base: t[1],
+ index: t[2] + t[4],
+ array: {
+ base: t[1],
+ prefix: t[1] + t[2],
+ count: t[5] ? parseInt(t[5]) : -1
+ }
+ } : { base: e };
+}
+var GE = class e {
+ primaryType;
+ #e;
+ get types() {
+ return JSON.parse(this.#e);
+ }
+ #t;
+ #n;
+ constructor(e) {
+ this.#t = /* @__PURE__ */ new Map(), this.#n = /* @__PURE__ */ new Map();
+ let t = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map(), i = {};
+ Object.keys(e).forEach((a) => {
+ i[a] = e[a].map(({ name: t, type: n }) => {
+ let { base: r, index: i } = WE(n);
+ return r === "int" && !e.int && (r = "int256"), r === "uint" && !e.uint && (r = "uint256"), {
+ name: t,
+ type: r + (i || "")
+ };
+ }), t.set(a, /* @__PURE__ */ new Set()), n.set(a, []), r.set(a, /* @__PURE__ */ new Set());
+ }), this.#e = JSON.stringify(i);
+ for (let r in i) {
+ let a = /* @__PURE__ */ new Set();
+ for (let o of i[r]) {
+ q(!a.has(o.name), `duplicate variable name ${JSON.stringify(o.name)} in ${JSON.stringify(r)}`, "types", e), a.add(o.name);
+ let i = WE(o.type).base;
+ q(i !== r, `circular type reference to ${JSON.stringify(i)}`, "types", e), !HE(i) && (q(n.has(i), `unknown type ${JSON.stringify(i)}`, "types", e), n.get(i).push(r), t.get(r).add(i));
+ }
+ }
+ let a = Array.from(n.keys()).filter((e) => n.get(e).length === 0);
+ q(a.length !== 0, "missing primary type", "types", e), q(a.length === 1, `ambiguous primary types or unused types: ${a.map((e) => JSON.stringify(e)).join(", ")}`, "types", e), G(this, { primaryType: a[0] });
+ function o(i, a) {
+ q(!a.has(i), `circular type reference to ${JSON.stringify(i)}`, "types", e), a.add(i);
+ for (let e of t.get(i)) if (n.has(e)) {
+ o(e, a);
+ for (let t of a) r.get(t).add(e);
+ }
+ a.delete(i);
+ }
+ o(this.primaryType, /* @__PURE__ */ new Set());
+ for (let [e, t] of r) {
+ let n = Array.from(t);
+ n.sort(), this.#t.set(e, UE(e, i[e]) + n.map((e) => UE(e, i[e])).join(""));
+ }
+ }
+ getEncoder(e) {
+ let t = this.#n.get(e);
+ return t || (t = this.#r(e), this.#n.set(e, t)), t;
+ }
+ #r(e) {
+ {
+ let t = HE(e);
+ if (t) return t;
+ }
+ let t = WE(e).array;
+ if (t) {
+ let e = t.prefix, n = this.getEncoder(e);
+ return (r) => {
+ q(t.count === -1 || t.count === r.length, `array length mismatch; expected length ${t.count}`, "value", r);
+ let i = r.map(n);
+ return this.#t.has(e) && (i = i.map(vx)), vx(Pv(i));
+ };
+ }
+ let n = this.types[e];
+ if (n) {
+ let t = Ww(this.#t.get(e));
+ return (e) => {
+ let r = n.map(({ name: t, type: n }) => {
+ let r = this.getEncoder(n)(e[t]);
+ return this.#t.has(n) ? vx(r) : r;
+ });
+ return r.unshift(t), Pv(r);
+ };
+ }
+ q(!1, `unknown type: ${e}`, "type", e);
+ }
+ encodeType(e) {
+ let t = this.#t.get(e);
+ return q(t, `unknown type: ${JSON.stringify(e)}`, "name", e), t;
+ }
+ encodeData(e, t) {
+ return this.getEncoder(e)(t);
+ }
+ hashStruct(e, t) {
+ return vx(this.encodeData(e, t));
+ }
+ encode(e) {
+ return this.encodeData(this.primaryType, e);
+ }
+ hash(e) {
+ return this.hashStruct(this.primaryType, e);
+ }
+ _visit(e, t, n) {
+ if (HE(e)) return n(e, t);
+ let r = WE(e).array;
+ if (r) return q(r.count === -1 || r.count === t.length, `array length mismatch; expected length ${r.count}`, "value", t), t.map((e) => this._visit(r.prefix, e, n));
+ let i = this.types[e];
+ if (i) return i.reduce((e, { name: r, type: i }) => (e[r] = this._visit(i, t[r], n), e), {});
+ q(!1, `unknown type: ${e}`, "type", e);
+ }
+ visit(e, t) {
+ return this._visit(this.primaryType, e, t);
+ }
+ static from(t) {
+ return new e(t);
+ }
+ static getPrimaryType(t) {
+ return e.from(t).primaryType;
+ }
+ static hashStruct(t, n, r) {
+ return e.from(n).hashStruct(t, r);
+ }
+ static hashDomain(t) {
+ let n = [];
+ for (let e in t) {
+ if (t[e] == null) continue;
+ let r = RE[e];
+ q(r, `invalid typed-data domain key: ${JSON.stringify(e)}`, "domain", t), n.push({
+ name: e,
+ type: r
+ });
+ }
+ return n.sort((e, t) => zE.indexOf(e.name) - zE.indexOf(t.name)), e.hashStruct("EIP712Domain", { EIP712Domain: n }, t);
+ }
+ static encode(t, n, r) {
+ return Pv([
+ "0x1901",
+ e.hashDomain(t),
+ e.from(n).hash(r)
+ ]);
+ }
+ static hash(t, n, r) {
+ return vx(e.encode(t, n, r));
+ }
+ static async resolveNames(t, n, r, i) {
+ t = Object.assign({}, t);
+ for (let e in t) t[e] ?? delete t[e];
+ let a = {};
+ t.verifyingContract && !jv(t.verifyingContract, 20) && (a[t.verifyingContract] = "0x");
+ let o = e.from(n);
+ o.visit(r, (e, t) => (e === "address" && !jv(t, 20) && (a[t] = "0x"), t));
+ for (let e in a) a[e] = await i(e);
+ return t.verifyingContract && a[t.verifyingContract] && (t.verifyingContract = a[t.verifyingContract]), r = o.visit(r, (e, t) => e === "address" && a[t] ? a[t] : t), {
+ domain: t,
+ value: r
+ };
+ }
+ static getPayload(t, n, r) {
+ e.hashDomain(t);
+ let i = {}, a = [];
+ zE.forEach((e) => {
+ let n = t[e];
+ n != null && (i[e] = VE[e](n), a.push({
+ name: e,
+ type: RE[e]
+ }));
+ });
+ let o = e.from(n);
+ n = o.types;
+ let s = Object.assign({}, n);
+ return q(s.EIP712Domain == null, "types must not contain EIP712Domain type", "types.EIP712Domain", n), s.EIP712Domain = a, o.encode(r), {
+ types: s,
+ domain: i,
+ primaryType: o.primaryType,
+ message: o.visit(r, (e, t) => {
+ if (e.match(/^bytes(\d*)/)) return Y(J(t));
+ if (e.match(/^u?int/)) return X(t).toString();
+ switch (e) {
+ case "address": return t.toLowerCase();
+ case "bool": return !!t;
+ case "string": return q(typeof t == "string", "invalid string", "value", t), t;
+ }
+ q(!1, "unsupported type", "type", e);
+ })
+ };
+ }
+};
+//#endregion
+//#region node_modules/ethers/lib.esm/abi/fragments.js
+function KE(e) {
+ let t = /* @__PURE__ */ new Set();
+ return e.forEach((e) => t.add(e)), Object.freeze(t);
+}
+var qE = KE("external public payable override".split(" ")), JE = "constant external internal payable private public pure view override", YE = KE(JE.split(" ")), XE = "constructor error event fallback function receive struct", ZE = KE(XE.split(" ")), QE = "calldata memory storage payable indexed", $E = KE(QE.split(" ")), eD = KE([
+ XE,
+ QE,
+ "tuple returns",
+ JE
+].join(" ").split(" ")), tD = {
+ "(": "OPEN_PAREN",
+ ")": "CLOSE_PAREN",
+ "[": "OPEN_BRACKET",
+ "]": "CLOSE_BRACKET",
+ ",": "COMMA",
+ "@": "AT"
+}, nD = /* @__PURE__ */ RegExp("^(\\s*)"), rD = /* @__PURE__ */ RegExp("^([0-9]+)"), iD = /* @__PURE__ */ RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"), aD = /* @__PURE__ */ RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"), oD = /* @__PURE__ */ RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$"), sD = class e {
+ #e;
+ #t;
+ get offset() {
+ return this.#e;
+ }
+ get length() {
+ return this.#t.length - this.#e;
+ }
+ constructor(e) {
+ this.#e = 0, this.#t = e.slice();
+ }
+ clone() {
+ return new e(this.#t);
+ }
+ reset() {
+ this.#e = 0;
+ }
+ #n(t = 0, n = 0) {
+ return new e(this.#t.slice(t, n).map((e) => Object.freeze(Object.assign({}, e, {
+ match: e.match - t,
+ linkBack: e.linkBack - t,
+ linkNext: e.linkNext - t
+ }))));
+ }
+ popKeyword(e) {
+ let t = this.peek();
+ if (t.type !== "KEYWORD" || !e.has(t.text)) throw Error(`expected keyword ${t.text}`);
+ return this.pop().text;
+ }
+ popType(e) {
+ if (this.peek().type !== e) {
+ let t = this.peek();
+ throw Error(`expected ${e}; got ${t.type} ${JSON.stringify(t.text)}`);
+ }
+ return this.pop().text;
+ }
+ popParen() {
+ let e = this.peek();
+ if (e.type !== "OPEN_PAREN") throw Error("bad start");
+ let t = this.#n(this.#e + 1, e.match + 1);
+ return this.#e = e.match + 1, t;
+ }
+ popParams() {
+ let e = this.peek();
+ if (e.type !== "OPEN_PAREN") throw Error("bad start");
+ let t = [];
+ for (; this.#e < e.match - 1;) {
+ let e = this.peek().linkNext;
+ t.push(this.#n(this.#e + 1, e)), this.#e = e;
+ }
+ return this.#e = e.match + 1, t;
+ }
+ peek() {
+ if (this.#e >= this.#t.length) throw Error("out-of-bounds");
+ return this.#t[this.#e];
+ }
+ peekKeyword(e) {
+ let t = this.peekType("KEYWORD");
+ return t != null && e.has(t) ? t : null;
+ }
+ peekType(e) {
+ if (this.length === 0) return null;
+ let t = this.peek();
+ return t.type === e ? t.text : null;
+ }
+ pop() {
+ let e = this.peek();
+ return this.#e++, e;
+ }
+ toString() {
+ let e = [];
+ for (let t = this.#e; t < this.#t.length; t++) {
+ let n = this.#t[t];
+ e.push(`${n.type}:${n.text}`);
+ }
+ return `<TokenString ${e.join(" ")}>`;
+ }
+};
+function cD(e) {
+ let t = [], n = (t) => {
+ let n = a < e.length ? JSON.stringify(e[a]) : "$EOI";
+ throw Error(`invalid token ${n} at ${a}: ${t}`);
+ }, r = [], i = [], a = 0;
+ for (; a < e.length;) {
+ let o = e.substring(a), s = o.match(nD);
+ s && (a += s[1].length, o = e.substring(a));
+ let c = {
+ depth: r.length,
+ linkBack: -1,
+ linkNext: -1,
+ match: -1,
+ type: "",
+ text: "",
+ offset: a,
+ value: -1
+ };
+ t.push(c);
+ let l = tD[o[0]] || "";
+ if (l) {
+ if (c.type = l, c.text = o[0], a++, l === "OPEN_PAREN") r.push(t.length - 1), i.push(t.length - 1);
+ else if (l == "CLOSE_PAREN") r.length === 0 && n("no matching open bracket"), c.match = r.pop(), t[c.match].match = t.length - 1, c.depth--, c.linkBack = i.pop(), t[c.linkBack].linkNext = t.length - 1;
+ else if (l === "COMMA") c.linkBack = i.pop(), t[c.linkBack].linkNext = t.length - 1, i.push(t.length - 1);
+ else if (l === "OPEN_BRACKET") c.type = "BRACKET";
+ else if (l === "CLOSE_BRACKET") {
+ let e = t.pop().text;
+ if (t.length > 0 && t[t.length - 1].type === "NUMBER") {
+ let n = t.pop().text;
+ e = n + e, t[t.length - 1].value = Z(n);
+ }
+ if (t.length === 0 || t[t.length - 1].type !== "BRACKET") throw Error("missing opening bracket");
+ t[t.length - 1].text += e;
+ }
+ continue;
+ }
+ if (s = o.match(iD), s) {
+ if (c.text = s[1], a += c.text.length, eD.has(c.text)) {
+ c.type = "KEYWORD";
+ continue;
+ }
+ if (c.text.match(oD)) {
+ c.type = "TYPE";
+ continue;
+ }
+ c.type = "ID";
+ continue;
+ }
+ if (s = o.match(rD), s) {
+ c.text = s[1], c.type = "NUMBER", a += c.text.length;
+ continue;
+ }
+ throw Error(`unexpected token ${JSON.stringify(o[0])} at position ${a}`);
+ }
+ return new sD(t.map((e) => Object.freeze(e)));
+}
+function lD(e, t) {
+ let n = [];
+ for (let r in t.keys()) e.has(r) && n.push(r);
+ if (n.length > 1) throw Error(`conflicting types: ${n.join(", ")}`);
+}
+function uD(e, t) {
+ if (t.peekKeyword(ZE)) {
+ let n = t.pop().text;
+ if (n !== e) throw Error(`expected ${e}, got ${n}`);
+ }
+ return t.popType("ID");
+}
+function dD(e, t) {
+ let n = /* @__PURE__ */ new Set();
+ for (;;) {
+ let r = e.peekType("KEYWORD");
+ if (r == null || t && !t.has(r)) break;
+ if (e.pop(), n.has(r)) throw Error(`duplicate keywords: ${JSON.stringify(r)}`);
+ n.add(r);
+ }
+ return Object.freeze(n);
+}
+function fD(e) {
+ let t = dD(e, YE);
+ return lD(t, KE("constant payable nonpayable".split(" "))), lD(t, KE("pure view payable nonpayable".split(" "))), t.has("view") ? "view" : t.has("pure") ? "pure" : t.has("payable") ? "payable" : t.has("nonpayable") ? "nonpayable" : t.has("constant") ? "view" : "nonpayable";
+}
+function pD(e, t) {
+ return e.popParams().map((e) => DD.from(e, t));
+}
+function mD(e) {
+ if (e.peekType("AT")) {
+ if (e.pop(), e.peekType("NUMBER")) return X(e.pop().text);
+ throw Error("invalid gas");
+ }
+ return null;
+}
+function hD(e) {
+ if (e.length) throw Error(`unexpected tokens at offset ${e.offset}: ${e.toString()}`);
+}
+var gD = /* @__PURE__ */ new RegExp(/^(.*)\[([0-9]*)\]$/);
+function _D(e) {
+ let t = e.match(oD);
+ if (q(t, "invalid type", "type", e), e === "uint") return "uint256";
+ if (e === "int") return "int256";
+ if (t[2]) {
+ let n = parseInt(t[2]);
+ q(n !== 0 && n <= 32, "invalid bytes length", "type", e);
+ } else if (t[3]) {
+ let n = parseInt(t[3]);
+ q(n !== 0 && n <= 256 && n % 8 == 0, "invalid numeric width", "type", e);
+ }
+ return e;
+}
+var vD = {}, yD = Symbol.for("_ethers_internal"), bD = "_ParamTypeInternal", xD = "_ErrorInternal", SD = "_EventInternal", CD = "_ConstructorInternal", wD = "_FallbackInternal", TD = "_FunctionInternal", ED = "_StructInternal", DD = class e {
+ name;
+ type;
+ baseType;
+ indexed;
+ components;
+ arrayLength;
+ arrayChildren;
+ constructor(e, t, n, r, i, a, o, s) {
+ if (Ov(e, vD, "ParamType"), Object.defineProperty(this, yD, { value: bD }), a &&= Object.freeze(a.slice()), r === "array") {
+ if (o == null || s == null) throw Error("");
+ } else if (o != null || s != null) throw Error("");
+ if (r === "tuple") {
+ if (a == null) throw Error("");
+ } else if (a != null) throw Error("");
+ G(this, {
+ name: t,
+ type: n,
+ baseType: r,
+ indexed: i,
+ components: a,
+ arrayLength: o,
+ arrayChildren: s
+ });
+ }
+ format(e) {
+ if (e ??= "sighash", e === "json") {
+ let t = this.name || "";
+ if (this.isArray()) {
+ let e = JSON.parse(this.arrayChildren.format("json"));
+ return e.name = t, e.type += `[${this.arrayLength < 0 ? "" : String(this.arrayLength)}]`, JSON.stringify(e);
+ }
+ let n = {
+ type: this.baseType === "tuple" ? "tuple" : this.type,
+ name: t
+ };
+ return typeof this.indexed == "boolean" && (n.indexed = this.indexed), this.isTuple() && (n.components = this.components.map((t) => JSON.parse(t.format(e)))), JSON.stringify(n);
+ }
+ let t = "";
+ return this.isArray() ? (t += this.arrayChildren.format(e), t += `[${this.arrayLength < 0 ? "" : String(this.arrayLength)}]`) : this.isTuple() ? t += "(" + this.components.map((t) => t.format(e)).join(e === "full" ? ", " : ",") + ")" : t += this.type, e !== "sighash" && (this.indexed === !0 && (t += " indexed"), e === "full" && this.name && (t += " " + this.name)), t;
+ }
+ isArray() {
+ return this.baseType === "array";
+ }
+ isTuple() {
+ return this.baseType === "tuple";
+ }
+ isIndexable() {
+ return this.indexed != null;
+ }
+ walk(e, t) {
+ if (this.isArray()) {
+ if (!Array.isArray(e)) throw Error("invalid array value");
+ if (this.arrayLength !== -1 && e.length !== this.arrayLength) throw Error("array is wrong length");
+ let n = this;
+ return e.map((e) => n.arrayChildren.walk(e, t));
+ }
+ if (this.isTuple()) {
+ if (!Array.isArray(e)) throw Error("invalid tuple value");
+ if (e.length !== this.components.length) throw Error("array is wrong length");
+ let n = this;
+ return e.map((e, r) => n.components[r].walk(e, t));
+ }
+ return t(this.type, e);
+ }
+ #e(e, t, n, r) {
+ if (this.isArray()) {
+ if (!Array.isArray(t)) throw Error("invalid array value");
+ if (this.arrayLength !== -1 && t.length !== this.arrayLength) throw Error("array is wrong length");
+ let i = this.arrayChildren, a = t.slice();
+ a.forEach((t, r) => {
+ i.#e(e, t, n, (e) => {
+ a[r] = e;
+ });
+ }), r(a);
+ return;
+ }
+ if (this.isTuple()) {
+ let i = this.components, a;
+ if (Array.isArray(t)) a = t.slice();
+ else {
+ if (typeof t != "object" || !t) throw Error("invalid tuple value");
+ a = i.map((e) => {
+ if (!e.name) throw Error("cannot use object value with unnamed components");
+ if (!(e.name in t)) throw Error(`missing value for component ${e.name}`);
+ return t[e.name];
+ });
+ }
+ if (a.length !== this.components.length) throw Error("array is wrong length");
+ a.forEach((t, r) => {
+ i[r].#e(e, t, n, (e) => {
+ a[r] = e;
+ });
+ }), r(a);
+ return;
+ }
+ let i = n(this.type, t);
+ i.then ? e.push((async function() {
+ r(await i);
+ })()) : r(i);
+ }
+ async walkAsync(e, t) {
+ let n = [], r = [e];
+ return this.#e(n, e, t, (e) => {
+ r[0] = e;
+ }), n.length && await Promise.all(n), r[0];
+ }
+ static from(t, n) {
+ if (e.isParamType(t)) return t;
+ if (typeof t == "string") try {
+ return e.from(cD(t), n);
+ } catch {
+ q(!1, "invalid param type", "obj", t);
+ }
+ else if (t instanceof sD) {
+ let r = "", i = "", a = null;
+ dD(t, KE(["tuple"])).has("tuple") || t.peekType("OPEN_PAREN") ? (i = "tuple", a = t.popParams().map((t) => e.from(t)), r = `tuple(${a.map((e) => e.format()).join(",")})`) : (r = _D(t.popType("TYPE")), i = r);
+ let o = null, s = null;
+ for (; t.length && t.peekType("BRACKET");) {
+ let n = t.pop();
+ o = new e(vD, "", r, i, null, a, s, o), s = n.value, r += n.text, i = "array", a = null;
+ }
+ let c = null;
+ if (dD(t, $E).has("indexed")) {
+ if (!n) throw Error("");
+ c = !0;
+ }
+ let l = t.peekType("ID") ? t.pop().text : "";
+ if (t.length) throw Error("leftover tokens");
+ return new e(vD, l, r, i, c, a, s, o);
+ }
+ let r = t.name;
+ q(!r || typeof r == "string" && r.match(aD), "invalid name", "obj.name", r);
+ let i = t.indexed;
+ i != null && (q(n, "parameter cannot be indexed", "obj.indexed", t.indexed), i = !!i);
+ let a = t.type, o = a.match(gD);
+ if (o) {
+ let n = parseInt(o[2] || "-1"), s = e.from({
+ type: o[1],
+ components: t.components
+ });
+ return new e(vD, r || "", a, "array", i, null, n, s);
+ }
+ if (a === "tuple" || a.startsWith("tuple(") || a.startsWith("(")) {
+ let n = t.components == null ? null : t.components.map((t) => e.from(t));
+ return new e(vD, r || "", a, "tuple", i, n, null, null);
+ }
+ return a = _D(t.type), new e(vD, r || "", a, a, i, null, null, null);
+ }
+ static isParamType(e) {
+ return e && e[yD] === bD;
+ }
+}, OD = class e {
+ type;
+ inputs;
+ constructor(e, t, n) {
+ Ov(e, vD, "Fragment"), n = Object.freeze(n.slice()), G(this, {
+ type: t,
+ inputs: n
+ });
+ }
+ static from(t) {
+ if (typeof t == "string") {
+ try {
+ e.from(JSON.parse(t));
+ } catch {}
+ return e.from(cD(t));
+ }
+ if (t instanceof sD) switch (t.peekKeyword(ZE)) {
+ case "constructor": return ND.from(t);
+ case "error": return jD.from(t);
+ case "event": return MD.from(t);
+ case "fallback":
+ case "receive": return PD.from(t);
+ case "function": return FD.from(t);
+ case "struct": return ID.from(t);
+ }
+ else if (typeof t == "object") {
+ switch (t.type) {
+ case "constructor": return ND.from(t);
+ case "error": return jD.from(t);
+ case "event": return MD.from(t);
+ case "fallback":
+ case "receive": return PD.from(t);
+ case "function": return FD.from(t);
+ case "struct": return ID.from(t);
+ }
+ K(!1, `unsupported type: ${t.type}`, "UNSUPPORTED_OPERATION", { operation: "Fragment.from" });
+ }
+ q(!1, "unsupported frgament object", "obj", t);
+ }
+ static isConstructor(e) {
+ return ND.isFragment(e);
+ }
+ static isError(e) {
+ return jD.isFragment(e);
+ }
+ static isEvent(e) {
+ return MD.isFragment(e);
+ }
+ static isFunction(e) {
+ return FD.isFragment(e);
+ }
+ static isStruct(e) {
+ return ID.isFragment(e);
+ }
+}, kD = class extends OD {
+ name;
+ constructor(e, t, n, r) {
+ super(e, t, r), q(typeof n == "string" && n.match(aD), "invalid identifier", "name", n), r = Object.freeze(r.slice()), G(this, { name: n });
+ }
+};
+function AD(e, t) {
+ return "(" + t.map((t) => t.format(e)).join(e === "full" ? ", " : ",") + ")";
+}
+var jD = class e extends kD {
+ constructor(e, t, n) {
+ super(e, "error", t, n), Object.defineProperty(this, yD, { value: xD });
+ }
+ get selector() {
+ return Ww(this.format("sighash")).substring(0, 10);
+ }
+ format(e) {
+ if (e ??= "sighash", e === "json") return JSON.stringify({
+ type: "error",
+ name: this.name,
+ inputs: this.inputs.map((t) => JSON.parse(t.format(e)))
+ });
+ let t = [];
+ return e !== "sighash" && t.push("error"), t.push(this.name + AD(e, this.inputs)), t.join(" ");
+ }
+ static from(t) {
+ if (e.isFragment(t)) return t;
+ if (typeof t == "string") return e.from(cD(t));
+ if (t instanceof sD) {
+ let n = uD("error", t), r = pD(t);
+ return hD(t), new e(vD, n, r);
+ }
+ return new e(vD, t.name, t.inputs ? t.inputs.map(DD.from) : []);
+ }
+ static isFragment(e) {
+ return e && e[yD] === xD;
+ }
+}, MD = class e extends kD {
+ anonymous;
+ constructor(e, t, n, r) {
+ super(e, "event", t, n), Object.defineProperty(this, yD, { value: SD }), G(this, { anonymous: r });
+ }
+ get topicHash() {
+ return Ww(this.format("sighash"));
+ }
+ format(e) {
+ if (e ??= "sighash", e === "json") return JSON.stringify({
+ type: "event",
+ anonymous: this.anonymous,
+ name: this.name,
+ inputs: this.inputs.map((t) => JSON.parse(t.format(e)))
+ });
+ let t = [];
+ return e !== "sighash" && t.push("event"), t.push(this.name + AD(e, this.inputs)), e !== "sighash" && this.anonymous && t.push("anonymous"), t.join(" ");
+ }
+ static getTopicHash(t, n) {
+ return n = (n || []).map((e) => DD.from(e)), new e(vD, t, n, !1).topicHash;
+ }
+ static from(t) {
+ if (e.isFragment(t)) return t;
+ if (typeof t == "string") try {
+ return e.from(cD(t));
+ } catch {
+ q(!1, "invalid event fragment", "obj", t);
+ }
+ else if (t instanceof sD) {
+ let n = uD("event", t), r = pD(t, !0), i = !!dD(t, KE(["anonymous"])).has("anonymous");
+ return hD(t), new e(vD, n, r, i);
+ }
+ return new e(vD, t.name, t.inputs ? t.inputs.map((e) => DD.from(e, !0)) : [], !!t.anonymous);
+ }
+ static isFragment(e) {
+ return e && e[yD] === SD;
+ }
+}, ND = class e extends OD {
+ payable;
+ gas;
+ constructor(e, t, n, r, i) {
+ super(e, t, n), Object.defineProperty(this, yD, { value: CD }), G(this, {
+ payable: r,
+ gas: i
+ });
+ }
+ format(e) {
+ if (K(e != null && e !== "sighash", "cannot format a constructor for sighash", "UNSUPPORTED_OPERATION", { operation: "format(sighash)" }), e === "json") return JSON.stringify({
+ type: "constructor",
+ stateMutability: this.payable ? "payable" : "undefined",
+ payable: this.payable,
+ gas: this.gas == null ? void 0 : this.gas,
+ inputs: this.inputs.map((t) => JSON.parse(t.format(e)))
+ });
+ let t = [`constructor${AD(e, this.inputs)}`];
+ return this.payable && t.push("payable"), this.gas != null && t.push(`@${this.gas.toString()}`), t.join(" ");
+ }
+ static from(t) {
+ if (e.isFragment(t)) return t;
+ if (typeof t == "string") try {
+ return e.from(cD(t));
+ } catch {
+ q(!1, "invalid constuctor fragment", "obj", t);
+ }
+ else if (t instanceof sD) {
+ dD(t, KE(["constructor"]));
+ let n = pD(t), r = !!dD(t, qE).has("payable"), i = mD(t);
+ return hD(t), new e(vD, "constructor", n, r, i);
+ }
+ return new e(vD, "constructor", t.inputs ? t.inputs.map(DD.from) : [], !!t.payable, t.gas == null ? null : t.gas);
+ }
+ static isFragment(e) {
+ return e && e[yD] === CD;
+ }
+}, PD = class e extends OD {
+ payable;
+ constructor(e, t, n) {
+ super(e, "fallback", t), Object.defineProperty(this, yD, { value: wD }), G(this, { payable: n });
+ }
+ format(e) {
+ let t = this.inputs.length === 0 ? "receive" : "fallback";
+ if (e === "json") {
+ let e = this.payable ? "payable" : "nonpayable";
+ return JSON.stringify({
+ type: t,
+ stateMutability: e
+ });
+ }
+ return `${t}()${this.payable ? " payable" : ""}`;
+ }
+ static from(t) {
+ if (e.isFragment(t)) return t;
+ if (typeof t == "string") try {
+ return e.from(cD(t));
+ } catch {
+ q(!1, "invalid fallback fragment", "obj", t);
+ }
+ else if (t instanceof sD) {
+ let n = t.toString();
+ if (q(t.peekKeyword(KE(["fallback", "receive"])), "type must be fallback or receive", "obj", n), t.popKeyword(KE(["fallback", "receive"])) === "receive") {
+ let n = pD(t);
+ return q(n.length === 0, "receive cannot have arguments", "obj.inputs", n), dD(t, KE(["payable"])), hD(t), new e(vD, [], !0);
+ }
+ let r = pD(t);
+ r.length ? q(r.length === 1 && r[0].type === "bytes", "invalid fallback inputs", "obj.inputs", r.map((e) => e.format("minimal")).join(", ")) : r = [DD.from("bytes")];
+ let i = fD(t);
+ if (q(i === "nonpayable" || i === "payable", "fallback cannot be constants", "obj.stateMutability", i), dD(t, KE(["returns"])).has("returns")) {
+ let e = pD(t);
+ q(e.length === 1 && e[0].type === "bytes", "invalid fallback outputs", "obj.outputs", e.map((e) => e.format("minimal")).join(", "));
+ }
+ return hD(t), new e(vD, r, i === "payable");
+ }
+ if (t.type === "receive") return new e(vD, [], !0);
+ if (t.type === "fallback") return new e(vD, [DD.from("bytes")], t.stateMutability === "payable");
+ q(!1, "invalid fallback description", "obj", t);
+ }
+ static isFragment(e) {
+ return e && e[yD] === wD;
+ }
+}, FD = class e extends kD {
+ constant;
+ outputs;
+ stateMutability;
+ payable;
+ gas;
+ constructor(e, t, n, r, i, a) {
+ super(e, "function", t, r), Object.defineProperty(this, yD, { value: TD }), i = Object.freeze(i.slice()), G(this, {
+ constant: n === "view" || n === "pure",
+ gas: a,
+ outputs: i,
+ payable: n === "payable",
+ stateMutability: n
+ });
+ }
+ get selector() {
+ return Ww(this.format("sighash")).substring(0, 10);
+ }
+ format(e) {
+ if (e ??= "sighash", e === "json") return JSON.stringify({
+ type: "function",
+ name: this.name,
+ constant: this.constant,
+ stateMutability: this.stateMutability === "nonpayable" ? void 0 : this.stateMutability,
+ payable: this.payable,
+ gas: this.gas == null ? void 0 : this.gas,
+ inputs: this.inputs.map((t) => JSON.parse(t.format(e))),
+ outputs: this.outputs.map((t) => JSON.parse(t.format(e)))
+ });
+ let t = [];
+ return e !== "sighash" && t.push("function"), t.push(this.name + AD(e, this.inputs)), e !== "sighash" && (this.stateMutability !== "nonpayable" && t.push(this.stateMutability), this.outputs && this.outputs.length && (t.push("returns"), t.push(AD(e, this.outputs))), this.gas != null && t.push(`@${this.gas.toString()}`)), t.join(" ");
+ }
+ static getSelector(t, n) {
+ return n = (n || []).map((e) => DD.from(e)), new e(vD, t, "view", n, [], null).selector;
+ }
+ static from(t) {
+ if (e.isFragment(t)) return t;
+ if (typeof t == "string") try {
+ return e.from(cD(t));
+ } catch {
+ q(!1, "invalid function fragment", "obj", t);
+ }
+ else if (t instanceof sD) {
+ let n = uD("function", t), r = pD(t), i = fD(t), a = [];
+ dD(t, KE(["returns"])).has("returns") && (a = pD(t));
+ let o = mD(t);
+ return hD(t), new e(vD, n, i, r, a, o);
+ }
+ let n = t.stateMutability;
+ return n ?? (n = "payable", typeof t.constant == "boolean" ? (n = "view", t.constant || (n = "payable", typeof t.payable == "boolean" && !t.payable && (n = "nonpayable"))) : typeof t.payable == "boolean" && !t.payable && (n = "nonpayable")), new e(vD, t.name, n, t.inputs ? t.inputs.map(DD.from) : [], t.outputs ? t.outputs.map(DD.from) : [], t.gas == null ? null : t.gas);
+ }
+ static isFragment(e) {
+ return e && e[yD] === TD;
+ }
+}, ID = class e extends kD {
+ constructor(e, t, n) {
+ super(e, "struct", t, n), Object.defineProperty(this, yD, { value: ED });
+ }
+ format() {
+ throw Error("@TODO");
+ }
+ static from(t) {
+ if (typeof t == "string") try {
+ return e.from(cD(t));
+ } catch {
+ q(!1, "invalid struct fragment", "obj", t);
+ }
+ else if (t instanceof sD) {
+ let n = uD("struct", t), r = pD(t);
+ return hD(t), new e(vD, n, r);
+ }
+ return new e(vD, t.name, t.inputs ? t.inputs.map(DD.from) : []);
+ }
+ static isFragment(e) {
+ return e && e[yD] === ED;
+ }
+}, LD = /* @__PURE__ */ new Map();
+LD.set(0, "GENERIC_PANIC"), LD.set(1, "ASSERT_FALSE"), LD.set(17, "OVERFLOW"), LD.set(18, "DIVIDE_BY_ZERO"), LD.set(33, "ENUM_RANGE_ERROR"), LD.set(34, "BAD_STORAGE_DATA"), LD.set(49, "STACK_UNDERFLOW"), LD.set(50, "ARRAY_RANGE_ERROR"), LD.set(65, "OUT_OF_MEMORY"), LD.set(81, "UNINITIALIZED_FUNCTION_CALL");
+var RD = /* @__PURE__ */ new RegExp(/^bytes([0-9]*)$/), zD = /* @__PURE__ */ new RegExp(/^(u?int)([0-9]*)$/), BD = null, VD = 1024;
+function HD(e, t, n, r) {
+ let i = "missing revert data", a = null, o = null;
+ if (n) {
+ i = "execution reverted";
+ let e = J(n);
+ if (n = Y(n), e.length === 0) i += " (no data present; likely require(false) occurred", a = "require(false)";
+ else if (e.length % 32 != 4) i += " (could not decode reason; invalid data length)";
+ else if (Y(e.slice(0, 4)) === "0x08c379a0") try {
+ a = r.decode(["string"], e.slice(4))[0], o = {
+ signature: "Error(string)",
+ name: "Error",
+ args: [a]
+ }, i += `: ${JSON.stringify(a)}`;
+ } catch {
+ i += " (could not decode reason; invalid string data)";
+ }
+ else if (Y(e.slice(0, 4)) === "0x4e487b71") try {
+ let t = Number(r.decode(["uint256"], e.slice(4))[0]);
+ o = {
+ signature: "Panic(uint256)",
+ name: "Panic",
+ args: [t]
+ }, a = `Panic due to ${LD.get(t) || "UNKNOWN"}(${t})`, i += `: ${a}`;
+ } catch {
+ i += " (could not decode panic code)";
+ }
+ else i += " (unknown custom error)";
+ }
+ let s = {
+ to: t.to ? FC(t.to) : null,
+ data: t.data || "0x"
+ };
+ return t.from && (s.from = FC(t.from)), wv(i, "CALL_EXCEPTION", {
+ action: e,
+ data: n,
+ reason: a,
+ transaction: s,
+ invocation: null,
+ revert: o
+ });
+}
+var UD = class e {
+ #e(e) {
+ if (e.isArray()) return new JC(this.#e(e.arrayChildren), e.arrayLength, e.name);
+ if (e.isTuple()) return new ow(e.components.map((e) => this.#e(e)), e.name);
+ switch (e.baseType) {
+ case "address": return new WC(e.name);
+ case "bool": return new YC(e.name);
+ case "string": return new aw(e.name);
+ case "bytes": return new ZC(e.name);
+ case "": return new ew(e.name);
+ }
+ let t = e.type.match(zD);
+ if (t) {
+ let n = parseInt(t[2] || "256");
+ return q(n !== 0 && n <= 256 && n % 8 == 0, "invalid " + t[1] + " bit length", "param", e), new iw(n / 8, t[1] === "int", e.name);
+ }
+ if (t = e.type.match(RD), t) {
+ let n = parseInt(t[1]);
+ return q(n !== 0 && n <= 32, "invalid bytes length", "param", e), new QC(n, e.name);
+ }
+ q(!1, "invalid type", "type", e.type);
+ }
+ getDefaultValue(e) {
+ return new ow(e.map((e) => this.#e(DD.from(e))), "_").defaultValue();
+ }
+ encode(e, t) {
+ Tv(t.length, e.length, "types/values length mismatch");
+ let n = new ow(e.map((e) => this.#e(DD.from(e))), "_"), r = new Zy();
+ return n.encode(r, t), r.data;
+ }
+ decode(e, t, n) {
+ return new ow(e.map((e) => this.#e(DD.from(e))), "_").decode(new Qy(t, n, VD));
+ }
+ static _setDefaultMaxInflation(e) {
+ q(typeof e == "number" && Number.isInteger(e), "invalid defaultMaxInflation factor", "value", e), VD = e;
+ }
+ static defaultAbiCoder() {
+ return BD ??= new e(), BD;
+ }
+ static getBuiltinCallException(t, n, r) {
+ return HD(t, n, r, e.defaultAbiCoder());
+ }
+}, WD = class {
+ fragment;
+ name;
+ signature;
+ topic;
+ args;
+ constructor(e, t, n) {
+ let r = e.name, i = e.format();
+ G(this, {
+ fragment: e,
+ name: r,
+ signature: i,
+ topic: t,
+ args: n
+ });
+ }
+}, GD = class {
+ fragment;
+ name;
+ args;
+ signature;
+ selector;
+ value;
+ constructor(e, t, n, r) {
+ let i = e.name, a = e.format();
+ G(this, {
+ fragment: e,
+ name: i,
+ args: n,
+ signature: a,
+ selector: t,
+ value: r
+ });
+ }
+}, KD = class {
+ fragment;
+ name;
+ args;
+ signature;
+ selector;
+ constructor(e, t, n) {
+ let r = e.name, i = e.format();
+ G(this, {
+ fragment: e,
+ name: r,
+ args: n,
+ signature: i,
+ selector: t
+ });
+ }
+}, qD = class {
+ hash;
+ _isIndexed;
+ static isIndexed(e) {
+ return !!(e && e._isIndexed);
+ }
+ constructor(e) {
+ G(this, {
+ hash: e,
+ _isIndexed: !0
+ });
+ }
+}, JD = {
+ 0: "generic panic",
+ 1: "assert(false)",
+ 17: "arithmetic overflow",
+ 18: "division or modulo by zero",
+ 33: "enum overflow",
+ 34: "invalid encoded storage byte array accessed",
+ 49: "out-of-bounds array access; popping on an empty array",
+ 50: "out-of-bounds access of an array or bytesN",
+ 65: "out of memory",
+ 81: "uninitialized function"
+}, YD = {
+ "0x08c379a0": {
+ signature: "Error(string)",
+ name: "Error",
+ inputs: ["string"],
+ reason: (e) => `reverted with reason string ${JSON.stringify(e)}`
+ },
+ "0x4e487b71": {
+ signature: "Panic(uint256)",
+ name: "Panic",
+ inputs: ["uint256"],
+ reason: (e) => {
+ let t = "unknown panic code";
+ return e >= 0 && e <= 255 && JD[e.toString()] && (t = JD[e.toString()]), `reverted with panic code 0x${e.toString(16)} (${t})`;
+ }
+ }
+}, XD = class e {
+ fragments;
+ deploy;
+ fallback;
+ receive;
+ #e;
+ #t;
+ #n;
+ #r;
+ constructor(e) {
+ let t = [];
+ t = typeof e == "string" ? JSON.parse(e) : e, this.#n = /* @__PURE__ */ new Map(), this.#e = /* @__PURE__ */ new Map(), this.#t = /* @__PURE__ */ new Map();
+ let n = [];
+ for (let e of t) try {
+ n.push(OD.from(e));
+ } catch (t) {
+ console.log(`[Warning] Invalid Fragment ${JSON.stringify(e)}:`, t.message);
+ }
+ G(this, { fragments: Object.freeze(n) });
+ let r = null, i = !1;
+ this.#r = this.getAbiCoder(), this.fragments.forEach((e, t) => {
+ let n;
+ switch (e.type) {
+ case "constructor":
+ if (this.deploy) {
+ console.log("duplicate definition - constructor");
+ return;
+ }
+ G(this, { deploy: e });
+ return;
+ case "fallback":
+ e.inputs.length === 0 ? i = !0 : (q(!r || e.payable !== r.payable, "conflicting fallback fragments", `fragments[${t}]`, e), r = e, i = r.payable);
+ return;
+ case "function":
+ n = this.#n;
+ break;
+ case "event":
+ n = this.#t;
+ break;
+ case "error":
+ n = this.#e;
+ break;
+ default: return;
+ }
+ let a = e.format();
+ n.has(a) || n.set(a, e);
+ }), this.deploy || G(this, { deploy: ND.from("constructor()") }), G(this, {
+ fallback: r,
+ receive: i
+ });
+ }
+ format(e) {
+ let t = e ? "minimal" : "full";
+ return this.fragments.map((e) => e.format(t));
+ }
+ formatJson() {
+ let e = this.fragments.map((e) => e.format("json"));
+ return JSON.stringify(e.map((e) => JSON.parse(e)));
+ }
+ getAbiCoder() {
+ return UD.defaultAbiCoder();
+ }
+ #i(e, t, n) {
+ if (jv(e)) {
+ let t = e.toLowerCase();
+ for (let e of this.#n.values()) if (t === e.selector) return e;
+ return null;
+ }
+ if (e.indexOf("(") === -1) {
+ let r = [];
+ for (let [t, n] of this.#n) t.split("(")[0] === e && r.push(n);
+ if (t) {
+ let e = t.length > 0 ? t[t.length - 1] : null, n = t.length, i = !0;
+ UC.isTyped(e) && e.type === "overrides" && (i = !1, n--);
+ for (let e = r.length - 1; e >= 0; e--) {
+ let t = r[e].inputs.length;
+ t !== n && (!i || t !== n - 1) && r.splice(e, 1);
+ }
+ for (let e = r.length - 1; e >= 0; e--) {
+ let n = r[e].inputs;
+ for (let i = 0; i < t.length; i++) if (UC.isTyped(t[i])) {
+ if (i >= n.length) {
+ if (t[i].type === "overrides") continue;
+ r.splice(e, 1);
+ break;
+ }
+ if (t[i].type !== n[i].baseType) {
+ r.splice(e, 1);
+ break;
+ }
+ }
+ }
+ }
+ if (r.length === 1 && t && t.length !== r[0].inputs.length) {
+ let e = t[t.length - 1];
+ (e == null || Array.isArray(e) || typeof e != "object") && r.splice(0, 1);
+ }
+ return r.length === 0 ? null : (r.length > 1 && n && q(!1, `ambiguous function description (i.e. matches ${r.map((e) => JSON.stringify(e.format())).join(", ")})`, "key", e), r[0]);
+ }
+ return this.#n.get(FD.from(e).format()) || null;
+ }
+ getFunctionName(e) {
+ let t = this.#i(e, null, !1);
+ return q(t, "no matching function", "key", e), t.name;
+ }
+ hasFunction(e) {
+ return !!this.#i(e, null, !1);
+ }
+ getFunction(e, t) {
+ return this.#i(e, t || null, !0);
+ }
+ forEachFunction(e) {
+ let t = Array.from(this.#n.keys());
+ t.sort((e, t) => e.localeCompare(t));
+ for (let n = 0; n < t.length; n++) {
+ let r = t[n];
+ e(this.#n.get(r), n);
+ }
+ }
+ #a(e, t, n) {
+ if (jv(e)) {
+ let t = e.toLowerCase();
+ for (let e of this.#t.values()) if (t === e.topicHash) return e;
+ return null;
+ }
+ if (e.indexOf("(") === -1) {
+ let r = [];
+ for (let [t, n] of this.#t) t.split("(")[0] === e && r.push(n);
+ if (t) {
+ for (let e = r.length - 1; e >= 0; e--) r[e].inputs.length < t.length && r.splice(e, 1);
+ for (let e = r.length - 1; e >= 0; e--) {
+ let n = r[e].inputs;
+ for (let i = 0; i < t.length; i++) if (UC.isTyped(t[i]) && t[i].type !== n[i].baseType) {
+ r.splice(e, 1);
+ break;
+ }
+ }
+ }
+ return r.length === 0 ? null : (r.length > 1 && n && q(!1, `ambiguous event description (i.e. matches ${r.map((e) => JSON.stringify(e.format())).join(", ")})`, "key", e), r[0]);
+ }
+ return this.#t.get(MD.from(e).format()) || null;
+ }
+ getEventName(e) {
+ let t = this.#a(e, null, !1);
+ return q(t, "no matching event", "key", e), t.name;
+ }
+ hasEvent(e) {
+ return !!this.#a(e, null, !1);
+ }
+ getEvent(e, t) {
+ return this.#a(e, t || null, !0);
+ }
+ forEachEvent(e) {
+ let t = Array.from(this.#t.keys());
+ t.sort((e, t) => e.localeCompare(t));
+ for (let n = 0; n < t.length; n++) {
+ let r = t[n];
+ e(this.#t.get(r), n);
+ }
+ }
+ getError(e, t) {
+ if (jv(e)) {
+ let t = e.toLowerCase();
+ if (YD[t]) return jD.from(YD[t].signature);
+ for (let e of this.#e.values()) if (t === e.selector) return e;
+ return null;
+ }
+ if (e.indexOf("(") === -1) {
+ let t = [];
+ for (let [n, r] of this.#e) n.split("(")[0] === e && t.push(r);
+ return t.length === 0 ? e === "Error" ? jD.from("error Error(string)") : e === "Panic" ? jD.from("error Panic(uint256)") : null : (t.length > 1 && q(!1, `ambiguous error description (i.e. ${t.map((e) => JSON.stringify(e.format())).join(", ")})`, "name", e), t[0]);
+ }
+ return e = jD.from(e).format(), e === "Error(string)" ? jD.from("error Error(string)") : e === "Panic(uint256)" ? jD.from("error Panic(uint256)") : this.#e.get(e) || null;
+ }
+ forEachError(e) {
+ let t = Array.from(this.#e.keys());
+ t.sort((e, t) => e.localeCompare(t));
+ for (let n = 0; n < t.length; n++) {
+ let r = t[n];
+ e(this.#e.get(r), n);
+ }
+ }
+ _decodeParams(e, t) {
+ return this.#r.decode(e, t);
+ }
+ _encodeParams(e, t) {
+ return this.#r.encode(e, t);
+ }
+ encodeDeploy(e) {
+ return this._encodeParams(this.deploy.inputs, e || []);
+ }
+ decodeErrorResult(e, t) {
+ if (typeof e == "string") {
+ let t = this.getError(e);
+ q(t, "unknown error", "fragment", e), e = t;
+ }
+ return q(Iv(t, 0, 4) === e.selector, `data signature does not match error ${e.name}.`, "data", t), this._decodeParams(e.inputs, Iv(t, 4));
+ }
+ encodeErrorResult(e, t) {
+ if (typeof e == "string") {
+ let t = this.getError(e);
+ q(t, "unknown error", "fragment", e), e = t;
+ }
+ return Pv([e.selector, this._encodeParams(e.inputs, t || [])]);
+ }
+ decodeFunctionData(e, t) {
+ if (typeof e == "string") {
+ let t = this.getFunction(e);
+ q(t, "unknown function", "fragment", e), e = t;
+ }
+ return q(Iv(t, 0, 4) === e.selector, `data signature does not match function ${e.name}.`, "data", t), this._decodeParams(e.inputs, Iv(t, 4));
+ }
+ encodeFunctionData(e, t) {
+ if (typeof e == "string") {
+ let t = this.getFunction(e);
+ q(t, "unknown function", "fragment", e), e = t;
+ }
+ return Pv([e.selector, this._encodeParams(e.inputs, t || [])]);
+ }
+ decodeFunctionResult(e, t) {
+ if (typeof e == "string") {
+ let t = this.getFunction(e);
+ q(t, "unknown function", "fragment", e), e = t;
+ }
+ let n = "invalid length for result data", r = Av(t);
+ if (r.length % 32 == 0) try {
+ return this.#r.decode(e.outputs, r);
+ } catch {
+ n = "could not decode result data";
+ }
+ K(!1, n, "BAD_DATA", {
+ value: Y(r),
+ info: {
+ method: e.name,
+ signature: e.format()
+ }
+ });
+ }
+ makeError(e, t) {
+ let n = J(e, "data"), r = UD.getBuiltinCallException("call", t, n);
+ if (r.message.startsWith("execution reverted (unknown custom error)")) {
+ let e = Y(n.slice(0, 4)), t = this.getError(e);
+ if (t) try {
+ let e = this.#r.decode(t.inputs, n.slice(4));
+ r.revert = {
+ name: t.name,
+ signature: t.format(),
+ args: e
+ }, r.reason = r.revert.signature, r.message = `execution reverted: ${r.reason}`;
+ } catch {
+ r.message = "execution reverted (coult not decode custom error)";
+ }
+ }
+ let i = this.parseTransaction(t);
+ return i && (r.invocation = {
+ method: i.name,
+ signature: i.signature,
+ args: i.args
+ }), r;
+ }
+ encodeFunctionResult(e, t) {
+ if (typeof e == "string") {
+ let t = this.getFunction(e);
+ q(t, "unknown function", "fragment", e), e = t;
+ }
+ return Y(this.#r.encode(e.outputs, t || []));
+ }
+ encodeFilterTopics(e, t) {
+ if (typeof e == "string") {
+ let t = this.getEvent(e);
+ q(t, "unknown event", "eventFragment", e), e = t;
+ }
+ K(t.length <= e.inputs.length, `too many arguments for ${e.format()}`, "UNEXPECTED_ARGUMENT", {
+ count: t.length,
+ expectedCount: e.inputs.length
+ });
+ let n = [];
+ e.anonymous || n.push(e.topicHash);
+ let r = (e, t) => e.type === "string" ? Ww(t) : e.type === "bytes" ? vx(Y(t)) : (e.type === "bool" && typeof t == "boolean" ? t = t ? "0x01" : "0x00" : e.type.match(/^u?int/) ? t = Xv(t) : e.type.match(/^bytes/) ? t = zv(t, 32) : e.type === "address" && this.#r.encode(["address"], [t]), Rv(Y(t), 32));
+ for (t.forEach((t, i) => {
+ let a = e.inputs[i];
+ if (!a.indexed) {
+ q(t == null, "cannot filter non-indexed parameters; must be null", "contract." + a.name, t);
+ return;
+ }
+ t == null ? n.push(null) : a.baseType === "array" || a.baseType === "tuple" ? q(!1, "filtering with tuples or arrays not supported", "contract." + a.name, t) : Array.isArray(t) ? n.push(t.map((e) => r(a, e))) : n.push(r(a, t));
+ }); n.length && n[n.length - 1] === null;) n.pop();
+ return n;
+ }
+ encodeEventLog(e, t) {
+ if (typeof e == "string") {
+ let t = this.getEvent(e);
+ q(t, "unknown event", "eventFragment", e), e = t;
+ }
+ let n = [], r = [], i = [];
+ return e.anonymous || n.push(e.topicHash), q(t.length === e.inputs.length, "event arguments/values mismatch", "values", t), e.inputs.forEach((e, a) => {
+ let o = t[a];
+ if (e.indexed) if (e.type === "string") n.push(Ww(o));
+ else if (e.type === "bytes") n.push(vx(o));
+ else if (e.baseType === "tuple" || e.baseType === "array") throw Error("not implemented");
+ else n.push(this.#r.encode([e.type], [o]));
+ else r.push(e), i.push(o);
+ }), {
+ data: this.#r.encode(r, i),
+ topics: n
+ };
+ }
+ decodeEventLog(e, t, n) {
+ if (typeof e == "string") {
+ let t = this.getEvent(e);
+ q(t, "unknown event", "eventFragment", e), e = t;
+ }
+ if (n != null && !e.anonymous) {
+ let t = e.topicHash;
+ q(jv(n[0], 32) && n[0].toLowerCase() === t, "fragment/topic mismatch", "topics[0]", n[0]), n = n.slice(1);
+ }
+ let r = [], i = [], a = [];
+ e.inputs.forEach((e, t) => {
+ e.indexed ? e.type === "string" || e.type === "bytes" || e.baseType === "tuple" || e.baseType === "array" ? (r.push(DD.from({
+ type: "bytes32",
+ name: e.name
+ })), a.push(!0)) : (r.push(e), a.push(!1)) : (i.push(e), a.push(!1));
+ });
+ let o = n == null ? null : this.#r.decode(r, Pv(n)), s = this.#r.decode(i, t, !0), c = [], l = [], u = 0, d = 0;
+ return e.inputs.forEach((e, t) => {
+ let n = null;
+ if (e.indexed) if (o == null) n = new qD(null);
+ else if (a[t]) n = new qD(o[d++]);
+ else try {
+ n = o[d++];
+ } catch (e) {
+ n = e;
+ }
+ else try {
+ n = s[u++];
+ } catch (e) {
+ n = e;
+ }
+ c.push(n), l.push(e.name || null);
+ }), Jy.fromItems(c, l);
+ }
+ parseTransaction(e) {
+ let t = J(e.data, "tx.data"), n = X(e.value == null ? 0 : e.value, "tx.value"), r = this.getFunction(Y(t.slice(0, 4)));
+ if (!r) return null;
+ let i = this.#r.decode(r.inputs, t.slice(4));
+ return new GD(r, r.selector, i, n);
+ }
+ parseCallResult(e) {
+ throw Error("@TODO");
+ }
+ parseLog(e) {
+ let t = this.getEvent(e.topics[0]);
+ return !t || t.anonymous ? null : new WD(t, t.topicHash, this.decodeEventLog(t, e.data, e.topics));
+ }
+ parseError(e) {
+ let t = Y(e), n = this.getError(Iv(t, 0, 4));
+ if (!n) return null;
+ let r = this.#r.decode(n.inputs, Iv(t, 4));
+ return new KD(n, n.selector, r);
+ }
+ static from(t) {
+ return t instanceof e ? t : typeof t == "string" ? new e(JSON.parse(t)) : typeof t.formatJson == "function" ? new e(t.formatJson()) : typeof t.format == "function" ? new e(t.format("json")) : new e(t);
+ }
+}, ZD = BigInt(0);
+function QD(e) {
+ return e ?? null;
+}
+function $D(e) {
+ return e == null ? null : e.toString();
+}
+var eO = class {
+ gasPrice;
+ maxFeePerGas;
+ maxPriorityFeePerGas;
+ constructor(e, t, n) {
+ G(this, {
+ gasPrice: QD(e),
+ maxFeePerGas: QD(t),
+ maxPriorityFeePerGas: QD(n)
+ });
+ }
+ toJSON() {
+ let { gasPrice: e, maxFeePerGas: t, maxPriorityFeePerGas: n } = this;
+ return {
+ _type: "FeeData",
+ gasPrice: $D(e),
+ maxFeePerGas: $D(t),
+ maxPriorityFeePerGas: $D(n)
+ };
+ }
+};
+function tO(e) {
+ let t = {};
+ e.to && (t.to = e.to), e.from && (t.from = e.from), e.data && (t.data = Y(e.data));
+ let n = "chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);
+ for (let r of n) !(r in e) || e[r] == null || (t[r] = X(e[r], `request.${r}`));
+ let r = "type,nonce".split(/,/);
+ for (let n of r) !(n in e) || e[n] == null || (t[n] = Z(e[n], `request.${n}`));
+ return e.accessList && (t.accessList = cw(e.accessList)), e.authorizationList && (t.authorizationList = e.authorizationList.slice()), "blockTag" in e && (t.blockTag = e.blockTag), "enableCcipRead" in e && (t.enableCcipRead = !!e.enableCcipRead), "customData" in e && (t.customData = e.customData), "blobVersionedHashes" in e && e.blobVersionedHashes && (t.blobVersionedHashes = e.blobVersionedHashes.slice()), "kzg" in e && (t.kzg = e.kzg), "blobWrapperVersion" in e && (t.blobWrapperVersion = e.blobWrapperVersion), "blobs" in e && e.blobs && (t.blobs = e.blobs.map((e) => Mv(e) ? Y(e) : Object.assign({}, e))), t;
+}
+var nO = class {
+ provider;
+ number;
+ hash;
+ timestamp;
+ parentHash;
+ parentBeaconBlockRoot;
+ nonce;
+ difficulty;
+ gasLimit;
+ gasUsed;
+ stateRoot;
+ receiptsRoot;
+ blobGasUsed;
+ excessBlobGas;
+ miner;
+ prevRandao;
+ extraData;
+ baseFeePerGas;
+ #e;
+ constructor(e, t) {
+ this.#e = e.transactions.map((e) => typeof e == "string" ? e : new aO(e, t)), G(this, {
+ provider: t,
+ hash: QD(e.hash),
+ number: e.number,
+ timestamp: e.timestamp,
+ parentHash: e.parentHash,
+ parentBeaconBlockRoot: e.parentBeaconBlockRoot,
+ nonce: e.nonce,
+ difficulty: e.difficulty,
+ gasLimit: e.gasLimit,
+ gasUsed: e.gasUsed,
+ blobGasUsed: e.blobGasUsed,
+ excessBlobGas: e.excessBlobGas,
+ miner: e.miner,
+ prevRandao: QD(e.prevRandao),
+ extraData: e.extraData,
+ baseFeePerGas: QD(e.baseFeePerGas),
+ stateRoot: e.stateRoot,
+ receiptsRoot: e.receiptsRoot
+ });
+ }
+ get transactions() {
+ return this.#e.map((e) => typeof e == "string" ? e : e.hash);
+ }
+ get prefetchedTransactions() {
+ let e = this.#e.slice();
+ return e.length === 0 ? [] : (K(typeof e[0] == "object", "transactions were not prefetched with block request", "UNSUPPORTED_OPERATION", { operation: "transactionResponses()" }), e);
+ }
+ toJSON() {
+ let { baseFeePerGas: e, difficulty: t, extraData: n, gasLimit: r, gasUsed: i, hash: a, miner: o, prevRandao: s, nonce: c, number: l, parentHash: u, parentBeaconBlockRoot: d, stateRoot: f, receiptsRoot: p, timestamp: m, transactions: h } = this;
+ return {
+ _type: "Block",
+ baseFeePerGas: $D(e),
+ difficulty: $D(t),
+ extraData: n,
+ gasLimit: $D(r),
+ gasUsed: $D(i),
+ blobGasUsed: $D(this.blobGasUsed),
+ excessBlobGas: $D(this.excessBlobGas),
+ hash: a,
+ miner: o,
+ prevRandao: s,
+ nonce: c,
+ number: l,
+ parentHash: u,
+ timestamp: m,
+ parentBeaconBlockRoot: d,
+ stateRoot: f,
+ receiptsRoot: p,
+ transactions: h
+ };
+ }
+ [Symbol.iterator]() {
+ let e = 0, t = this.transactions;
+ return { next: () => e < this.length ? {
+ value: t[e++],
+ done: !1
+ } : {
+ value: void 0,
+ done: !0
+ } };
+ }
+ get length() {
+ return this.#e.length;
+ }
+ get date() {
+ return this.timestamp == null ? null : /* @__PURE__ */ new Date(this.timestamp * 1e3);
+ }
+ async getTransaction(e) {
+ let t;
+ if (typeof e == "number") t = this.#e[e];
+ else {
+ let n = e.toLowerCase();
+ for (let e of this.#e) if (typeof e == "string") {
+ if (e !== n) continue;
+ t = e;
+ break;
+ } else {
+ if (e.hash !== n) continue;
+ t = e;
+ break;
+ }
+ }
+ if (t == null) throw Error("no such tx");
+ return typeof t == "string" ? await this.provider.getTransaction(t) : t;
+ }
+ getPrefetchedTransaction(e) {
+ let t = this.prefetchedTransactions;
+ if (typeof e == "number") return t[e];
+ e = e.toLowerCase();
+ for (let n of t) if (n.hash === e) return n;
+ q(!1, "no matching transaction", "indexOrHash", e);
+ }
+ isMined() {
+ return !!this.hash;
+ }
+ isLondon() {
+ return !!this.baseFeePerGas;
+ }
+ orphanedEvent() {
+ if (!this.isMined()) throw Error("");
+ return oO(this);
+ }
+}, rO = class {
+ provider;
+ transactionHash;
+ blockHash;
+ blockNumber;
+ removed;
+ address;
+ data;
+ topics;
+ index;
+ transactionIndex;
+ constructor(e, t) {
+ this.provider = t;
+ let n = Object.freeze(e.topics.slice());
+ G(this, {
+ transactionHash: e.transactionHash,
+ blockHash: e.blockHash,
+ blockNumber: e.blockNumber,
+ removed: e.removed,
+ address: e.address,
+ data: e.data,
+ topics: n,
+ index: e.index,
+ transactionIndex: e.transactionIndex
+ });
+ }
+ toJSON() {
+ let { address: e, blockHash: t, blockNumber: n, data: r, index: i, removed: a, topics: o, transactionHash: s, transactionIndex: c } = this;
+ return {
+ _type: "log",
+ address: e,
+ blockHash: t,
+ blockNumber: n,
+ data: r,
+ index: i,
+ removed: a,
+ topics: o,
+ transactionHash: s,
+ transactionIndex: c
+ };
+ }
+ async getBlock() {
+ let e = await this.provider.getBlock(this.blockHash);
+ return K(!!e, "failed to find transaction", "UNKNOWN_ERROR", {}), e;
+ }
+ async getTransaction() {
+ let e = await this.provider.getTransaction(this.transactionHash);
+ return K(!!e, "failed to find transaction", "UNKNOWN_ERROR", {}), e;
+ }
+ async getTransactionReceipt() {
+ let e = await this.provider.getTransactionReceipt(this.transactionHash);
+ return K(!!e, "failed to find transaction receipt", "UNKNOWN_ERROR", {}), e;
+ }
+ removedEvent() {
+ return lO(this);
+ }
+}, iO = class {
+ provider;
+ to;
+ from;
+ contractAddress;
+ hash;
+ index;
+ blockHash;
+ blockNumber;
+ logsBloom;
+ gasUsed;
+ blobGasUsed;
+ cumulativeGasUsed;
+ gasPrice;
+ blobGasPrice;
+ type;
+ status;
+ root;
+ #e;
+ constructor(e, t) {
+ this.#e = Object.freeze(e.logs.map((e) => new rO(e, t)));
+ let n = ZD;
+ e.effectiveGasPrice == null ? e.gasPrice != null && (n = e.gasPrice) : n = e.effectiveGasPrice, G(this, {
+ provider: t,
+ to: e.to,
+ from: e.from,
+ contractAddress: e.contractAddress,
+ hash: e.hash,
+ index: e.index,
+ blockHash: e.blockHash,
+ blockNumber: e.blockNumber,
+ logsBloom: e.logsBloom,
+ gasUsed: e.gasUsed,
+ cumulativeGasUsed: e.cumulativeGasUsed,
+ blobGasUsed: e.blobGasUsed,
+ gasPrice: n,
+ blobGasPrice: e.blobGasPrice,
+ type: e.type,
+ status: e.status,
+ root: e.root
+ });
+ }
+ get logs() {
+ return this.#e;
+ }
+ toJSON() {
+ let { to: e, from: t, contractAddress: n, hash: r, index: i, blockHash: a, blockNumber: o, logsBloom: s, logs: c, status: l, root: u } = this;
+ return {
+ _type: "TransactionReceipt",
+ blockHash: a,
+ blockNumber: o,
+ contractAddress: n,
+ cumulativeGasUsed: $D(this.cumulativeGasUsed),
+ from: t,
+ gasPrice: $D(this.gasPrice),
+ blobGasUsed: $D(this.blobGasUsed),
+ blobGasPrice: $D(this.blobGasPrice),
+ gasUsed: $D(this.gasUsed),
+ hash: r,
+ index: i,
+ logs: c,
+ logsBloom: s,
+ root: u,
+ status: l,
+ to: e
+ };
+ }
+ get length() {
+ return this.logs.length;
+ }
+ [Symbol.iterator]() {
+ let e = 0;
+ return { next: () => e < this.length ? {
+ value: this.logs[e++],
+ done: !1
+ } : {
+ value: void 0,
+ done: !0
+ } };
+ }
+ get fee() {
+ return this.gasUsed * this.gasPrice;
+ }
+ async getBlock() {
+ let e = await this.provider.getBlock(this.blockHash);
+ if (e == null) throw Error("TODO");
+ return e;
+ }
+ async getTransaction() {
+ let e = await this.provider.getTransaction(this.hash);
+ if (e == null) throw Error("TODO");
+ return e;
+ }
+ async getResult() {
+ return await this.provider.getTransactionResult(this.hash);
+ }
+ async confirmations() {
+ return await this.provider.getBlockNumber() - this.blockNumber + 1;
+ }
+ removedEvent() {
+ return cO(this);
+ }
+ reorderedEvent(e) {
+ return K(!e || e.isMined(), "unmined 'other' transction cannot be orphaned", "UNSUPPORTED_OPERATION", { operation: "reorderedEvent(other)" }), sO(this, e);
+ }
+}, aO = class e {
+ provider;
+ blockNumber;
+ blockHash;
+ index;
+ hash;
+ type;
+ to;
+ from;
+ nonce;
+ gasLimit;
+ gasPrice;
+ maxPriorityFeePerGas;
+ maxFeePerGas;
+ maxFeePerBlobGas;
+ data;
+ value;
+ chainId;
+ signature;
+ accessList;
+ blobVersionedHashes;
+ authorizationList;
+ #e;
+ constructor(e, t) {
+ this.provider = t, this.blockNumber = e.blockNumber == null ? null : e.blockNumber, this.blockHash = e.blockHash == null ? null : e.blockHash, this.hash = e.hash, this.index = e.index, this.type = e.type, this.from = e.from, this.to = e.to || null, this.gasLimit = e.gasLimit, this.nonce = e.nonce, this.data = e.data, this.value = e.value, this.gasPrice = e.gasPrice, this.maxPriorityFeePerGas = e.maxPriorityFeePerGas == null ? null : e.maxPriorityFeePerGas, this.maxFeePerGas = e.maxFeePerGas == null ? null : e.maxFeePerGas, this.maxFeePerBlobGas = e.maxFeePerBlobGas == null ? null : e.maxFeePerBlobGas, this.chainId = e.chainId, this.signature = e.signature, this.accessList = e.accessList == null ? null : e.accessList, this.blobVersionedHashes = e.blobVersionedHashes == null ? null : e.blobVersionedHashes, this.authorizationList = e.authorizationList == null ? null : e.authorizationList, this.#e = -1;
+ }
+ toJSON() {
+ let { blockNumber: e, blockHash: t, index: n, hash: r, type: i, to: a, from: o, nonce: s, data: c, signature: l, accessList: u, blobVersionedHashes: d } = this;
+ return {
+ _type: "TransactionResponse",
+ accessList: u,
+ blockNumber: e,
+ blockHash: t,
+ blobVersionedHashes: d,
+ chainId: $D(this.chainId),
+ data: c,
+ from: o,
+ gasLimit: $D(this.gasLimit),
+ gasPrice: $D(this.gasPrice),
+ hash: r,
+ maxFeePerGas: $D(this.maxFeePerGas),
+ maxPriorityFeePerGas: $D(this.maxPriorityFeePerGas),
+ maxFeePerBlobGas: $D(this.maxFeePerBlobGas),
+ nonce: s,
+ signature: l,
+ to: a,
+ index: n,
+ type: i,
+ value: $D(this.value)
+ };
+ }
+ async getBlock() {
+ let e = this.blockNumber;
+ if (e == null) {
+ let t = await this.getTransaction();
+ t && (e = t.blockNumber);
+ }
+ if (e == null) return null;
+ let t = this.provider.getBlock(e);
+ if (t == null) throw Error("TODO");
+ return t;
+ }
+ async getTransaction() {
+ return this.provider.getTransaction(this.hash);
+ }
+ async confirmations() {
+ if (this.blockNumber == null) {
+ let { tx: e, blockNumber: t } = await bv({
+ tx: this.getTransaction(),
+ blockNumber: this.provider.getBlockNumber()
+ });
+ return e == null || e.blockNumber == null ? 0 : t - e.blockNumber + 1;
+ }
+ return await this.provider.getBlockNumber() - this.blockNumber + 1;
+ }
+ async wait(e, t) {
+ let n = e ?? 1, r = t ?? 0, i = this.#e, a = -1, o = i === -1, s = async () => {
+ if (o) return null;
+ let { blockNumber: e, nonce: t } = await bv({
+ blockNumber: this.provider.getBlockNumber(),
+ nonce: this.provider.getTransactionCount(this.from)
+ });
+ if (t < this.nonce) {
+ i = e;
+ return;
+ }
+ if (o) return null;
+ let r = await this.getTransaction();
+ if (!(r && r.blockNumber != null)) for (a === -1 && (a = i - 3, a < this.#e && (a = this.#e)); a <= e;) {
+ if (o) return null;
+ let t = await this.provider.getBlock(a, !0);
+ if (t == null) return;
+ for (let e of t) if (e === this.hash) return;
+ for (let r = 0; r < t.length; r++) {
+ let a = await t.getTransaction(r);
+ if (a.from === this.from && a.nonce === this.nonce) {
+ if (o) return null;
+ let t = await this.provider.getTransactionReceipt(a.hash);
+ if (t == null || e - t.blockNumber + 1 < n) return;
+ let r = "replaced";
+ a.data === this.data && a.to === this.to && a.value === this.value ? r = "repriced" : a.data === "0x" && a.from === a.to && a.value === ZD && (r = "cancelled"), K(!1, "transaction was replaced", "TRANSACTION_REPLACED", {
+ cancelled: r === "replaced" || r === "cancelled",
+ reason: r,
+ replacement: a.replaceableTransaction(i),
+ hash: a.hash,
+ receipt: t
+ });
+ }
+ }
+ a++;
+ }
+ }, c = (e) => {
+ if (e == null || e.status !== 0) return e;
+ K(!1, "transaction execution reverted", "CALL_EXCEPTION", {
+ action: "sendTransaction",
+ data: null,
+ reason: null,
+ invocation: null,
+ revert: null,
+ transaction: {
+ to: e.to,
+ from: e.from,
+ data: ""
+ },
+ receipt: e
+ });
+ }, l = await this.provider.getTransactionReceipt(this.hash);
+ if (n === 0) return c(l);
+ if (l) {
+ if (n === 1 || await l.confirmations() >= n) return c(l);
+ } else if (await s(), n === 0) return null;
+ return await new Promise((e, t) => {
+ let a = [], l = () => {
+ a.forEach((e) => e());
+ };
+ if (a.push(() => {
+ o = !0;
+ }), r > 0) {
+ let e = setTimeout(() => {
+ l(), t(wv("wait for transaction timeout", "TIMEOUT"));
+ }, r);
+ a.push(() => {
+ clearTimeout(e);
+ });
+ }
+ let u = async (r) => {
+ if (await r.confirmations() >= n) {
+ l();
+ try {
+ e(c(r));
+ } catch (e) {
+ t(e);
+ }
+ }
+ };
+ if (a.push(() => {
+ this.provider.off(this.hash, u);
+ }), this.provider.on(this.hash, u), i >= 0) {
+ let e = async () => {
+ try {
+ await s();
+ } catch (e) {
+ if (Sv(e, "TRANSACTION_REPLACED")) {
+ l(), t(e);
+ return;
+ }
+ }
+ o || this.provider.once("block", e);
+ };
+ a.push(() => {
+ this.provider.off("block", e);
+ }), this.provider.once("block", e);
+ }
+ });
+ }
+ isMined() {
+ return this.blockHash != null;
+ }
+ isLegacy() {
+ return this.type === 0;
+ }
+ isBerlin() {
+ return this.type === 1;
+ }
+ isLondon() {
+ return this.type === 2;
+ }
+ isCancun() {
+ return this.type === 3;
+ }
+ removedEvent() {
+ return K(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }), cO(this);
+ }
+ reorderedEvent(e) {
+ return K(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }), K(!e || e.isMined(), "unmined 'other' transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" }), sO(this, e);
+ }
+ replaceableTransaction(t) {
+ q(Number.isInteger(t) && t >= 0, "invalid startBlock", "startBlock", t);
+ let n = new e(this, this.provider);
+ return n.#e = t, n;
+ }
+};
+function oO(e) {
+ return {
+ orphan: "drop-block",
+ hash: e.hash,
+ number: e.number
+ };
+}
+function sO(e, t) {
+ return {
+ orphan: "reorder-transaction",
+ tx: e,
+ other: t
+ };
+}
+function cO(e) {
+ return {
+ orphan: "drop-transaction",
+ tx: e
+ };
+}
+function lO(e) {
+ return {
+ orphan: "drop-log",
+ log: {
+ transactionHash: e.transactionHash,
+ blockHash: e.blockHash,
+ blockNumber: e.blockNumber,
+ address: e.address,
+ data: e.data,
+ topics: Object.freeze(e.topics.slice()),
+ index: e.index
+ }
+ };
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/contract/wrappers.js
+var uO = class extends rO {
+ interface;
+ fragment;
+ args;
+ constructor(e, t, n) {
+ super(e, e.provider);
+ let r = t.decodeEventLog(n, e.data, e.topics);
+ G(this, {
+ args: r,
+ fragment: n,
+ interface: t
+ });
+ }
+ get eventName() {
+ return this.fragment.name;
+ }
+ get eventSignature() {
+ return this.fragment.format();
+ }
+}, dO = class extends rO {
+ error;
+ constructor(e, t) {
+ super(e, e.provider), G(this, { error: t });
+ }
+}, fO = class extends iO {
+ #e;
+ constructor(e, t, n) {
+ super(n, t), this.#e = e;
+ }
+ get logs() {
+ return super.logs.map((e) => {
+ let t = e.topics.length ? this.#e.getEvent(e.topics[0]) : null;
+ if (t) try {
+ return new uO(e, this.#e, t);
+ } catch (t) {
+ return new dO(e, t);
+ }
+ return e;
+ });
+ }
+}, pO = class extends aO {
+ #e;
+ constructor(e, t, n) {
+ super(n, t), this.#e = e;
+ }
+ async wait(e, t) {
+ let n = await super.wait(e, t);
+ return n == null ? null : new fO(this.#e, this.provider, n);
+ }
+}, mO = class extends iy {
+ log;
+ constructor(e, t, n, r) {
+ super(e, t, n), G(this, { log: r });
+ }
+ async getBlock() {
+ return await this.log.getBlock();
+ }
+ async getTransaction() {
+ return await this.log.getTransaction();
+ }
+ async getTransactionReceipt() {
+ return await this.log.getTransactionReceipt();
+ }
+}, hO = class extends mO {
+ constructor(e, t, n, r, i) {
+ super(e, t, n, new uO(i, e.interface, r));
+ let a = e.interface.decodeEventLog(r, this.log.data, this.log.topics);
+ G(this, {
+ args: a,
+ fragment: r
+ });
+ }
+ get eventName() {
+ return this.fragment.name;
+ }
+ get eventSignature() {
+ return this.fragment.format();
+ }
+}, gO = BigInt(0);
+function _O(e) {
+ return e && typeof e.call == "function";
+}
+function vO(e) {
+ return e && typeof e.estimateGas == "function";
+}
+function yO(e) {
+ return e && typeof e.resolveName == "function";
+}
+function bO(e) {
+ return e && typeof e.sendTransaction == "function";
+}
+function xO(e) {
+ if (e != null) {
+ if (yO(e)) return e;
+ if (e.provider) return e.provider;
+ }
+}
+var SO = class {
+ #e;
+ fragment;
+ constructor(e, t, n) {
+ if (G(this, { fragment: t }), t.inputs.length < n.length) throw Error("too many arguments");
+ let r = CO(e.runner, "resolveName"), i = yO(r) ? r : null;
+ this.#e = (async function() {
+ let r = await Promise.all(t.inputs.map((e, t) => n[t] == null ? null : e.walkAsync(n[t], (e, t) => e === "address" ? Array.isArray(t) ? Promise.all(t.map((e) => zC(e, i))) : zC(t, i) : t)));
+ return e.interface.encodeFilterTopics(t, r);
+ })();
+ }
+ getTopicFilter() {
+ return this.#e;
+ }
+};
+function CO(e, t) {
+ return e == null ? null : typeof e[t] == "function" ? e : e.provider && typeof e.provider[t] == "function" ? e.provider : null;
+}
+function wO(e) {
+ return e == null ? null : e.provider || null;
+}
+async function TO(e, t) {
+ let n = UC.dereference(e, "overrides");
+ q(typeof n == "object", "invalid overrides parameter", "overrides", e);
+ let r = tO(n);
+ return q(r.to == null || (t || []).indexOf("to") >= 0, "cannot override to", "overrides.to", r.to), q(r.data == null || (t || []).indexOf("data") >= 0, "cannot override data", "overrides.data", r.data), r.from &&= r.from, r;
+}
+async function EO(e, t, n) {
+ let r = CO(e, "resolveName"), i = yO(r) ? r : null;
+ return await Promise.all(t.map((e, t) => e.walkAsync(n[t], (e, t) => (t = UC.dereference(t, e), e === "address" ? zC(t, i) : t))));
+}
+function DO(e) {
+ let t = async function(t) {
+ let n = await TO(t, ["data"]);
+ n.to = await e.getAddress(), n.from &&= await zC(n.from, xO(e.runner));
+ let r = e.interface, i = X(n.value || gO, "overrides.value") === gO, a = (n.data || "0x") === "0x";
+ return r.fallback && !r.fallback.payable && r.receive && !a && !i && q(!1, "cannot send data to receive or send value to non-payable fallback", "overrides", t), q(r.fallback || a, "cannot send data to receive-only contract", "overrides.data", n.data), q(r.receive || r.fallback && r.fallback.payable || i, "cannot send value to non-payable fallback", "overrides.value", n.value), q(r.fallback || a, "cannot send data to receive-only contract", "overrides.data", n.data), n;
+ }, n = async function(n) {
+ let r = CO(e.runner, "call");
+ K(_O(r), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" });
+ let i = await t(n);
+ try {
+ return await r.call(i);
+ } catch (t) {
+ throw Cv(t) && t.data ? e.interface.makeError(t.data, i) : t;
+ }
+ }, r = async function(n) {
+ let r = e.runner;
+ K(bO(r), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" });
+ let i = await r.sendTransaction(await t(n)), a = wO(e.runner);
+ return new pO(e.interface, a, i);
+ }, i = async function(n) {
+ let r = CO(e.runner, "estimateGas");
+ return K(vO(r), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" }), await r.estimateGas(await t(n));
+ }, a = async (e) => await r(e);
+ return G(a, {
+ _contract: e,
+ estimateGas: i,
+ populateTransaction: t,
+ send: r,
+ staticCall: n
+ }), a;
+}
+function OO(e, t) {
+ let n = function(...n) {
+ let r = e.interface.getFunction(t, n);
+ return K(r, "no matching fragment", "UNSUPPORTED_OPERATION", {
+ operation: "fragment",
+ info: {
+ key: t,
+ args: n
+ }
+ }), r;
+ }, r = async function(...t) {
+ let r = n(...t), i = {};
+ if (r.inputs.length + 1 === t.length && (i = await TO(t.pop()), i.from &&= await zC(i.from, xO(e.runner))), r.inputs.length !== t.length) throw Error("internal error: fragment inputs doesn't match arguments; should not happen");
+ let a = await EO(e.runner, r.inputs, t);
+ return Object.assign({}, i, await bv({
+ to: e.getAddress(),
+ data: e.interface.encodeFunctionData(r, a)
+ }));
+ }, i = async function(...e) {
+ let t = await s(...e);
+ return t.length === 1 ? t[0] : t;
+ }, a = async function(...t) {
+ let n = e.runner;
+ K(bO(n), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" });
+ let i = await n.sendTransaction(await r(...t)), a = wO(e.runner);
+ return new pO(e.interface, a, i);
+ }, o = async function(...t) {
+ let n = CO(e.runner, "estimateGas");
+ return K(vO(n), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" }), await n.estimateGas(await r(...t));
+ }, s = async function(...t) {
+ let i = CO(e.runner, "call");
+ K(_O(i), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" });
+ let a = await r(...t), o = "0x";
+ try {
+ o = await i.call(a);
+ } catch (t) {
+ throw Cv(t) && t.data ? e.interface.makeError(t.data, a) : t;
+ }
+ let s = n(...t);
+ return e.interface.decodeFunctionResult(s, o);
+ }, c = async (...e) => n(...e).constant ? await i(...e) : await a(...e);
+ return G(c, {
+ name: e.interface.getFunctionName(t),
+ _contract: e,
+ _key: t,
+ getFragment: n,
+ estimateGas: o,
+ populateTransaction: r,
+ send: a,
+ staticCall: i,
+ staticCallResult: s
+ }), Object.defineProperty(c, "fragment", {
+ configurable: !1,
+ enumerable: !0,
+ get: () => {
+ let n = e.interface.getFunction(t);
+ return K(n, "no matching fragment", "UNSUPPORTED_OPERATION", {
+ operation: "fragment",
+ info: { key: t }
+ }), n;
+ }
+ }), c;
+}
+function kO(e, t) {
+ let n = function(...n) {
+ let r = e.interface.getEvent(t, n);
+ return K(r, "no matching fragment", "UNSUPPORTED_OPERATION", {
+ operation: "fragment",
+ info: {
+ key: t,
+ args: n
+ }
+ }), r;
+ }, r = function(...t) {
+ return new SO(e, n(...t), t);
+ };
+ return G(r, {
+ name: e.interface.getEventName(t),
+ _contract: e,
+ _key: t,
+ getFragment: n
+ }), Object.defineProperty(r, "fragment", {
+ configurable: !1,
+ enumerable: !0,
+ get: () => {
+ let n = e.interface.getEvent(t);
+ return K(n, "no matching fragment", "UNSUPPORTED_OPERATION", {
+ operation: "fragment",
+ info: { key: t }
+ }), n;
+ }
+ }), r;
+}
+var AO = Symbol.for("_ethersInternal_contract"), jO = /* @__PURE__ */ new WeakMap();
+function MO(e, t) {
+ jO.set(e[AO], t);
+}
+function NO(e) {
+ return jO.get(e[AO]);
+}
+function PO(e) {
+ return e && typeof e == "object" && "getTopicFilter" in e && typeof e.getTopicFilter == "function" && e.fragment;
+}
+async function FO(e, t) {
+ let n, r = null;
+ if (Array.isArray(t)) {
+ let r = function(t) {
+ if (jv(t, 32)) return t;
+ let n = e.interface.getEvent(t);
+ return q(n, "unknown fragment", "name", t), n.topicHash;
+ };
+ n = t.map((e) => e == null ? null : Array.isArray(e) ? e.map(r) : r(e));
+ } else t === "*" ? n = [null] : typeof t == "string" ? jv(t, 32) ? n = [t] : (r = e.interface.getEvent(t), q(r, "unknown fragment", "event", t), n = [r.topicHash]) : PO(t) ? n = await t.getTopicFilter() : "fragment" in t ? (r = t.fragment, n = [r.topicHash]) : q(!1, "unknown event name", "event", t);
+ n = n.map((e) => {
+ if (e == null) return null;
+ if (Array.isArray(e)) {
+ let t = Array.from(new Set(e.map((e) => e.toLowerCase())).values());
+ return t.length === 1 ? t[0] : (t.sort(), t);
+ }
+ return e.toLowerCase();
+ });
+ let i = n.map((e) => e == null ? "null" : Array.isArray(e) ? e.join("|") : e).join("&");
+ return {
+ fragment: r,
+ tag: i,
+ topics: n
+ };
+}
+async function IO(e, t) {
+ let { subs: n } = NO(e);
+ return n.get((await FO(e, t)).tag) || null;
+}
+async function LO(e, t, n) {
+ let r = wO(e.runner);
+ K(r, "contract runner does not support subscribing", "UNSUPPORTED_OPERATION", { operation: t });
+ let { fragment: i, tag: a, topics: o } = await FO(e, n), { addr: s, subs: c } = NO(e), l = c.get(a);
+ if (!l) {
+ let t = {
+ address: s || e,
+ topics: o
+ }, u = (t) => {
+ let r = i;
+ if (r == null) try {
+ r = e.interface.getEvent(t.topics[0]);
+ } catch {}
+ if (r) {
+ let a = r;
+ BO(e, n, i ? e.interface.decodeEventLog(i, t.data, t.topics) : [], (r) => new hO(e, r, n, a, t));
+ } else BO(e, n, [], (r) => new mO(e, r, n, t));
+ }, d = [];
+ l = {
+ tag: a,
+ listeners: [],
+ start: () => {
+ d.length || d.push(r.on(t, u));
+ },
+ stop: async () => {
+ if (d.length == 0) return;
+ let e = d;
+ d = [], await Promise.all(e), r.off(t, u);
+ }
+ }, c.set(a, l);
+ }
+ return l;
+}
+var RO = Promise.resolve();
+async function zO(e, t, n, r) {
+ await RO;
+ let i = await IO(e, t);
+ if (!i) return !1;
+ let a = i.listeners.length;
+ return i.listeners = i.listeners.filter(({ listener: t, once: i }) => {
+ let a = Array.from(n);
+ r && a.push(r(i ? null : t));
+ try {
+ t.call(e, ...a);
+ } catch {}
+ return !i;
+ }), i.listeners.length === 0 && (i.stop(), NO(e).subs.delete(i.tag)), a > 0;
+}
+async function BO(e, t, n, r) {
+ try {
+ await RO;
+ } catch {}
+ let i = zO(e, t, n, r);
+ return RO = i, await i;
+}
+var VO = ["then"], HO = class e {
+ target;
+ interface;
+ runner;
+ filters;
+ [AO];
+ fallback;
+ constructor(e, t, n, r) {
+ q(typeof e == "string" || LC(e), "invalid value for Contract target", "target", e), n ??= null;
+ let i = XD.from(t);
+ G(this, {
+ target: e,
+ runner: n,
+ interface: i
+ }), Object.defineProperty(this, AO, { value: {} });
+ let a, o = null, s = null;
+ if (r) {
+ let e = wO(n);
+ s = new pO(this.interface, e, r);
+ }
+ let c = /* @__PURE__ */ new Map();
+ if (typeof e == "string") if (jv(e)) o = e, a = Promise.resolve(e);
+ else {
+ let t = CO(n, "resolveName");
+ if (!yO(t)) throw wv("contract runner does not support name resolution", "UNSUPPORTED_OPERATION", { operation: "resolveName" });
+ a = t.resolveName(e).then((t) => {
+ if (t == null) throw wv("an ENS name used for a contract target must be correctly configured", "UNCONFIGURED_NAME", { value: e });
+ return NO(this).addr = t, t;
+ });
+ }
+ else a = e.getAddress().then((e) => {
+ if (e == null) throw Error("TODO");
+ return NO(this).addr = e, e;
+ });
+ MO(this, {
+ addrPromise: a,
+ addr: o,
+ deployTx: s,
+ subs: c
+ });
+ let l = new Proxy({}, {
+ get: (e, t, n) => {
+ if (typeof t == "symbol" || VO.indexOf(t) >= 0) return Reflect.get(e, t, n);
+ try {
+ return this.getEvent(t);
+ } catch (e) {
+ if (!Sv(e, "INVALID_ARGUMENT") || e.argument !== "key") throw e;
+ }
+ },
+ has: (e, t) => VO.indexOf(t) >= 0 ? Reflect.has(e, t) : Reflect.has(e, t) || this.interface.hasEvent(String(t))
+ });
+ return G(this, { filters: l }), G(this, { fallback: i.receive || i.fallback ? DO(this) : null }), new Proxy(this, {
+ get: (e, t, n) => {
+ if (typeof t == "symbol" || t in e || VO.indexOf(t) >= 0) return Reflect.get(e, t, n);
+ try {
+ return e.getFunction(t);
+ } catch (e) {
+ if (!Sv(e, "INVALID_ARGUMENT") || e.argument !== "key") throw e;
+ }
+ },
+ has: (e, t) => typeof t == "symbol" || t in e || VO.indexOf(t) >= 0 ? Reflect.has(e, t) : e.interface.hasFunction(t)
+ });
+ }
+ connect(t) {
+ return new e(this.target, this.interface, t);
+ }
+ attach(t) {
+ return new e(t, this.interface, this.runner);
+ }
+ async getAddress() {
+ return await NO(this).addrPromise;
+ }
+ async getDeployedCode() {
+ let e = wO(this.runner);
+ K(e, "runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "getDeployedCode" });
+ let t = await e.getCode(await this.getAddress());
+ return t === "0x" ? null : t;
+ }
+ async waitForDeployment() {
+ let e = this.deploymentTransaction();
+ if (e) return await e.wait(), this;
+ if (await this.getDeployedCode() != null) return this;
+ let t = wO(this.runner);
+ return K(t != null, "contract runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "waitForDeployment" }), new Promise((e, n) => {
+ let r = async () => {
+ try {
+ if (await this.getDeployedCode() != null) return e(this);
+ t.once("block", r);
+ } catch (e) {
+ n(e);
+ }
+ };
+ r();
+ });
+ }
+ deploymentTransaction() {
+ return NO(this).deployTx;
+ }
+ getFunction(e) {
+ return typeof e != "string" && (e = e.format()), OO(this, e);
+ }
+ getEvent(e) {
+ return typeof e != "string" && (e = e.format()), kO(this, e);
+ }
+ async queryTransaction(e) {
+ throw Error("@TODO");
+ }
+ async queryFilter(e, t, n) {
+ t ??= 0, n ??= "latest";
+ let { addr: r, addrPromise: i } = NO(this), a = r || await i, { fragment: o, topics: s } = await FO(this, e), c = {
+ address: a,
+ topics: s,
+ fromBlock: t,
+ toBlock: n
+ }, l = wO(this.runner);
+ return K(l, "contract runner does not have a provider", "UNSUPPORTED_OPERATION", { operation: "queryFilter" }), (await l.getLogs(c)).map((e) => {
+ let t = o;
+ if (t == null) try {
+ t = this.interface.getEvent(e.topics[0]);
+ } catch {}
+ if (t) try {
+ return new uO(e, this.interface, t);
+ } catch (t) {
+ return new dO(e, t);
+ }
+ return new rO(e, l);
+ });
+ }
+ async on(e, t) {
+ let n = await LO(this, "on", e);
+ return n.listeners.push({
+ listener: t,
+ once: !1
+ }), n.start(), this;
+ }
+ async once(e, t) {
+ let n = await LO(this, "once", e);
+ return n.listeners.push({
+ listener: t,
+ once: !0
+ }), n.start(), this;
+ }
+ async emit(e, ...t) {
+ return await BO(this, e, t, null);
+ }
+ async listenerCount(e) {
+ if (e) {
+ let t = await IO(this, e);
+ return t ? t.listeners.length : 0;
+ }
+ let { subs: t } = NO(this), n = 0;
+ for (let { listeners: e } of t.values()) n += e.length;
+ return n;
+ }
+ async listeners(e) {
+ if (e) {
+ let t = await IO(this, e);
+ return t ? t.listeners.map(({ listener: e }) => e) : [];
+ }
+ let { subs: t } = NO(this), n = [];
+ for (let { listeners: e } of t.values()) n = n.concat(e.map(({ listener: e }) => e));
+ return n;
+ }
+ async off(e, t) {
+ let n = await IO(this, e);
+ if (!n) return this;
+ if (t) {
+ let e = n.listeners.map(({ listener: e }) => e).indexOf(t);
+ e >= 0 && n.listeners.splice(e, 1);
+ }
+ return (t == null || n.listeners.length === 0) && (n.stop(), NO(this).subs.delete(n.tag)), this;
+ }
+ async removeAllListeners(e) {
+ if (e) {
+ let t = await IO(this, e);
+ if (!t) return this;
+ t.stop(), NO(this).subs.delete(t.tag);
+ } else {
+ let { subs: e } = NO(this);
+ for (let { tag: t, stop: n } of e.values()) n(), e.delete(t);
+ }
+ return this;
+ }
+ async addListener(e, t) {
+ return await this.on(e, t);
+ }
+ async removeListener(e, t) {
+ return await this.off(e, t);
+ }
+ static buildClass(t) {
+ class n extends e {
+ constructor(e, n = null) {
+ super(e, t, n);
+ }
+ }
+ return n;
+ }
+ static from(e, t, n) {
+ return n ??= null, new this(e, t, n);
+ }
+};
+function UO() {
+ return HO;
+}
+var WO = class extends UO() {};
+//#endregion
+//#region node_modules/ethers/lib.esm/providers/ens-resolver.js
+function GO(e) {
+ return e.match(/^ipfs:\/\/ipfs\//i) ? e = e.substring(12) : e.match(/^ipfs:\/\//i) ? e = e.substring(7) : q(!1, "unsupported IPFS format", "link", e), `https:/\/gateway.ipfs.io/ipfs/${e}`;
+}
+var KO = class {
+ name;
+ constructor(e) {
+ G(this, { name: e });
+ }
+ connect(e) {
+ return this;
+ }
+ supportsCoinType(e) {
+ return !1;
+ }
+ async encodeAddress(e, t) {
+ throw Error("unsupported coin");
+ }
+ async decodeAddress(e, t) {
+ throw Error("unsupported coin");
+ }
+}, qO = /* @__PURE__ */ RegExp("^(ipfs)://(.*)$", "i"), JO = [
+ /* @__PURE__ */ RegExp("^(https)://(.*)$", "i"),
+ /* @__PURE__ */ RegExp("^(data):(.*)$", "i"),
+ qO,
+ /* @__PURE__ */ RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i")
+], YO = class e {
+ provider;
+ address;
+ name;
+ #e;
+ #t;
+ constructor(e, t, n) {
+ G(this, {
+ provider: e,
+ address: t,
+ name: n
+ }), this.#e = null, this.#t = new WO(t, [
+ "function supportsInterface(bytes4) view returns (bool)",
+ "function resolve(bytes, bytes) view returns (bytes)",
+ "function addr(bytes32) view returns (address)",
+ "function addr(bytes32, uint) view returns (bytes)",
+ "function text(bytes32, string) view returns (string)",
+ "function contenthash(bytes32) view returns (bytes)"
+ ], e);
+ }
+ async supportsWildcard() {
+ return this.#e ??= (async () => {
+ try {
+ return await this.#t.supportsInterface("0x9061b923");
+ } catch (e) {
+ if (Sv(e, "CALL_EXCEPTION")) return !1;
+ throw this.#e = null, e;
+ }
+ })(), await this.#e;
+ }
+ async #n(e, t) {
+ t = (t || []).slice();
+ let n = this.#t.interface;
+ t.unshift(OE(this.name));
+ let r = null;
+ await this.supportsWildcard() && (r = n.getFunction(e), K(r, "missing fragment", "UNKNOWN_ERROR", { info: { funcName: e } }), t = [kE(this.name, 255), n.encodeFunctionData(r, t)], e = "resolve(bytes,bytes)"), t.push({ enableCcipRead: !0 });
+ try {
+ let i = await this.#t[e](...t);
+ return r ? n.decodeFunctionResult(r, i)[0] : i;
+ } catch (e) {
+ if (!Sv(e, "CALL_EXCEPTION")) throw e;
+ }
+ return null;
+ }
+ async getAddress(e) {
+ if (e ??= 60, e === 60) try {
+ let e = await this.#n("addr(bytes32)");
+ return e == null || e === "0x0000000000000000000000000000000000000000" ? null : e;
+ } catch (e) {
+ if (Sv(e, "CALL_EXCEPTION")) return null;
+ throw e;
+ }
+ if (e >= 0 && e < 2147483648) {
+ let t = e + 2147483648, n = await this.#n("addr(bytes32,uint)", [t]);
+ if (jv(n, 20)) return FC(n);
+ }
+ let t = null;
+ for (let n of this.provider.plugins) if (n instanceof KO && n.supportsCoinType(e)) {
+ t = n;
+ break;
+ }
+ if (t == null) return null;
+ let n = await this.#n("addr(bytes32,uint)", [e]);
+ if (n == null || n === "0x") return null;
+ let r = await t.decodeAddress(e, n);
+ if (r != null) return r;
+ K(!1, "invalid coin data", "UNSUPPORTED_OPERATION", {
+ operation: `getAddress(${e})`,
+ info: {
+ coinType: e,
+ data: n
+ }
+ });
+ }
+ async getText(e) {
+ let t = await this.#n("text(bytes32,string)", [e]);
+ return t == null || t === "0x" ? null : t;
+ }
+ async getContentHash() {
+ let e = await this.#n("contenthash(bytes32)");
+ if (e == null || e === "0x") return null;
+ let t = e.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);
+ if (t) {
+ let e = t[1] === "e3010170" ? "ipfs" : "ipns", n = parseInt(t[4], 16);
+ if (t[5].length === n * 2) return `${e}:/\/${ty("0x" + t[2])}`;
+ }
+ let n = e.match(/^0xe40101fa011b20([0-9a-f]*)$/);
+ if (n && n[1].length === 64) return `bzz:/\/${n[1]}`;
+ K(!1, "invalid or unsupported content hash data", "UNSUPPORTED_OPERATION", {
+ operation: "getContentHash()",
+ info: { data: e }
+ });
+ }
+ async getAvatar() {
+ return (await this._getAvatar()).url;
+ }
+ async _getAvatar() {
+ let e = [{
+ type: "name",
+ value: this.name
+ }];
+ try {
+ let t = await this.getText("avatar");
+ if (t == null) return e.push({
+ type: "!avatar",
+ value: ""
+ }), {
+ url: null,
+ linkage: e
+ };
+ e.push({
+ type: "avatar",
+ value: t
+ });
+ for (let n = 0; n < JO.length; n++) {
+ let r = t.match(JO[n]);
+ if (r == null) continue;
+ let i = r[1].toLowerCase();
+ switch (i) {
+ case "https":
+ case "data": return e.push({
+ type: "url",
+ value: t
+ }), {
+ linkage: e,
+ url: t
+ };
+ case "ipfs": {
+ let n = GO(t);
+ return e.push({
+ type: "ipfs",
+ value: t
+ }), e.push({
+ type: "url",
+ value: n
+ }), {
+ linkage: e,
+ url: n
+ };
+ }
+ case "erc721":
+ case "erc1155": {
+ let n = i === "erc721" ? "tokenURI(uint256)" : "uri(uint256)";
+ e.push({
+ type: i,
+ value: t
+ });
+ let a = await this.getAddress();
+ if (a == null) return e.push({
+ type: "!owner",
+ value: ""
+ }), {
+ url: null,
+ linkage: e
+ };
+ let o = (r[2] || "").split("/");
+ if (o.length !== 2) return e.push({
+ type: `!${i}caip`,
+ value: r[2] || ""
+ }), {
+ url: null,
+ linkage: e
+ };
+ let s = o[1], c = new WO(o[0], [
+ "function tokenURI(uint) view returns (string)",
+ "function ownerOf(uint) view returns (address)",
+ "function uri(uint) view returns (string)",
+ "function balanceOf(address, uint256) view returns (uint)"
+ ], this.provider);
+ if (i === "erc721") {
+ let t = await c.ownerOf(s);
+ if (a !== t) return e.push({
+ type: "!owner",
+ value: t
+ }), {
+ url: null,
+ linkage: e
+ };
+ e.push({
+ type: "owner",
+ value: t
+ });
+ } else if (i === "erc1155") {
+ let t = await c.balanceOf(a, s);
+ if (!t) return e.push({
+ type: "!balance",
+ value: "0"
+ }), {
+ url: null,
+ linkage: e
+ };
+ e.push({
+ type: "balance",
+ value: t.toString()
+ });
+ }
+ let l = await c[n](s);
+ if (l == null || l === "0x") return e.push({
+ type: "!metadata-url",
+ value: ""
+ }), {
+ url: null,
+ linkage: e
+ };
+ e.push({
+ type: "metadata-url-base",
+ value: l
+ }), i === "erc1155" && (l = l.replace("{id}", Xv(s, 32).substring(2)), e.push({
+ type: "metadata-url-expanded",
+ value: l
+ })), l.match(/^ipfs:/i) && (l = GO(l)), e.push({
+ type: "metadata-url",
+ value: l
+ });
+ let u = {}, d = await new Ey(l).send();
+ d.assertOk();
+ try {
+ u = d.bodyJson;
+ } catch {
+ try {
+ e.push({
+ type: "!metadata",
+ value: d.bodyText
+ });
+ } catch {
+ let t = d.body;
+ return t && e.push({
+ type: "!metadata",
+ value: Y(t)
+ }), {
+ url: null,
+ linkage: e
+ };
+ }
+ return {
+ url: null,
+ linkage: e
+ };
+ }
+ if (!u) return e.push({
+ type: "!metadata",
+ value: ""
+ }), {
+ url: null,
+ linkage: e
+ };
+ e.push({
+ type: "metadata",
+ value: JSON.stringify(u)
+ });
+ let f = u.image;
+ if (typeof f != "string") return e.push({
+ type: "!imageUrl",
+ value: ""
+ }), {
+ url: null,
+ linkage: e
+ };
+ if (!f.match(/^(https:\/\/|data:)/i)) {
+ if (f.match(qO) == null) return e.push({
+ type: "!imageUrl-ipfs",
+ value: f
+ }), {
+ url: null,
+ linkage: e
+ };
+ e.push({
+ type: "imageUrl-ipfs",
+ value: f
+ }), f = GO(f);
+ }
+ return e.push({
+ type: "url",
+ value: f
+ }), {
+ linkage: e,
+ url: f
+ };
+ }
+ }
+ }
+ } catch {}
+ return {
+ linkage: e,
+ url: null
+ };
+ }
+ static async getEnsAddress(e) {
+ let t = await e.getNetwork(), n = t.getPlugin("org.ethers.plugins.network.Ens");
+ return K(n, "network does not support ENS", "UNSUPPORTED_OPERATION", {
+ operation: "getEnsAddress",
+ info: { network: t }
+ }), n.address;
+ }
+ static async #r(t, n) {
+ let r = await e.getEnsAddress(t);
+ try {
+ let e = await new WO(r, ["function resolver(bytes32) view returns (address)"], t).resolver(OE(n), { enableCcipRead: !0 });
+ return e === "0x0000000000000000000000000000000000000000" ? null : e;
+ } catch (e) {
+ throw e;
+ }
+ return null;
+ }
+ static async fromName(t, n) {
+ let r = n;
+ for (;;) {
+ if (r === "" || r === "." || n !== "eth" && r === "eth") return null;
+ let i = await e.#r(t, r);
+ if (i != null) {
+ let a = new e(t, i, n);
+ return r !== n && !await a.supportsWildcard() ? null : a;
+ }
+ r = r.split(".").slice(1).join(".");
+ }
+ }
+}, XO = BigInt(0);
+function ZO(e, t) {
+ return (function(n) {
+ return n == null ? t : e(n);
+ });
+}
+function QO(e, t) {
+ return ((n) => {
+ if (t && n == null) return null;
+ if (!Array.isArray(n)) throw Error("not an array");
+ return n.map((t) => e(t));
+ });
+}
+function $O(e, t) {
+ return ((n) => {
+ let r = {};
+ for (let i in e) {
+ let a = i;
+ if (t && i in t && !(a in n)) {
+ for (let e of t[i]) if (e in n) {
+ a = e;
+ break;
+ }
+ }
+ try {
+ let t = e[i](n[a]);
+ t !== void 0 && (r[i] = t);
+ } catch (e) {
+ K(!1, `invalid value for value.${i} (${e instanceof Error ? e.message : "not-an-error"})`, "BAD_DATA", { value: n });
+ }
+ }
+ return r;
+ });
+}
+function ek(e) {
+ switch (e) {
+ case !0:
+ case "true": return !0;
+ case !1:
+ case "false": return !1;
+ }
+ q(!1, `invalid boolean; ${JSON.stringify(e)}`, "value", e);
+}
+function tk(e) {
+ return q(jv(e, !0), "invalid data", "value", e), e;
+}
+function nk(e) {
+ return q(jv(e, 32), "invalid hash", "value", e), e;
+}
+var rk = $O({
+ address: FC,
+ blockHash: nk,
+ blockNumber: Z,
+ data: tk,
+ index: Z,
+ removed: ZO(ek, !1),
+ topics: QO(nk),
+ transactionHash: nk,
+ transactionIndex: Z
+}, { index: ["logIndex"] });
+function ik(e) {
+ return rk(e);
+}
+var ak = $O({
+ hash: ZO(nk),
+ parentHash: nk,
+ parentBeaconBlockRoot: ZO(nk, null),
+ number: Z,
+ timestamp: Z,
+ nonce: ZO(tk),
+ difficulty: X,
+ gasLimit: X,
+ gasUsed: X,
+ stateRoot: ZO(nk, null),
+ receiptsRoot: ZO(nk, null),
+ blobGasUsed: ZO(X, null),
+ excessBlobGas: ZO(X, null),
+ miner: ZO(FC),
+ prevRandao: ZO(nk, null),
+ extraData: tk,
+ baseFeePerGas: ZO(X)
+}, { prevRandao: ["mixHash"] });
+function ok(e) {
+ let t = ak(e);
+ return t.transactions = e.transactions.map((e) => typeof e == "string" ? e : dk(e)), t;
+}
+var sk = $O({
+ transactionIndex: Z,
+ blockNumber: Z,
+ transactionHash: nk,
+ address: FC,
+ topics: QO(nk),
+ data: tk,
+ index: Z,
+ blockHash: nk
+}, { index: ["logIndex"] });
+function ck(e) {
+ return sk(e);
+}
+var lk = $O({
+ to: ZO(FC, null),
+ from: ZO(FC, null),
+ contractAddress: ZO(FC, null),
+ index: Z,
+ root: ZO(Y),
+ gasUsed: X,
+ blobGasUsed: ZO(X, null),
+ logsBloom: ZO(tk),
+ blockHash: nk,
+ hash: nk,
+ logs: QO(ck),
+ blockNumber: Z,
+ cumulativeGasUsed: X,
+ effectiveGasPrice: ZO(X),
+ blobGasPrice: ZO(X, null),
+ status: ZO(Z),
+ type: ZO(Z, 0)
+}, {
+ effectiveGasPrice: ["gasPrice"],
+ hash: ["transactionHash"],
+ index: ["transactionIndex"]
+});
+function uk(e) {
+ return lk(e);
+}
+function dk(e) {
+ e.to && X(e.to) === XO && (e.to = "0x0000000000000000000000000000000000000000");
+ let t = $O({
+ hash: nk,
+ index: ZO(Z, void 0),
+ type: (e) => e === "0x" || e == null ? 0 : Z(e),
+ accessList: ZO(cw, null),
+ blobVersionedHashes: ZO(QO(nk, !0), null),
+ authorizationList: ZO(QO((e) => {
+ let t;
+ if (e.signature) t = e.signature;
+ else {
+ let n = e.yParity;
+ n === "0x1b" ? n = 0 : n === "0x1c" && (n = 1), t = Object.assign({}, e, { yParity: n });
+ }
+ return {
+ address: FC(e.address),
+ chainId: X(e.chainId),
+ nonce: X(e.nonce),
+ signature: TC.from(t)
+ };
+ }, !1), null),
+ blockHash: ZO(nk, null),
+ blockNumber: ZO(Z, null),
+ transactionIndex: ZO(Z, null),
+ from: FC,
+ gasPrice: ZO(X),
+ maxPriorityFeePerGas: ZO(X),
+ maxFeePerGas: ZO(X),
+ maxFeePerBlobGas: ZO(X, null),
+ gasLimit: X,
+ to: ZO(FC, null),
+ value: X,
+ nonce: Z,
+ data: tk,
+ creates: ZO(FC, null),
+ chainId: ZO(X, null)
+ }, {
+ data: ["input"],
+ gasLimit: ["gas"],
+ index: ["transactionIndex"]
+ })(e);
+ if (t.to == null && t.creates == null && (t.creates = IC(t)), (e.type === 1 || e.type === 2) && e.accessList == null && (t.accessList = []), e.signature ? t.signature = TC.from(e.signature) : t.signature = TC.from(e), t.chainId == null) {
+ let e = t.signature.legacyChainId;
+ e != null && (t.chainId = e);
+ }
+ return t.blockHash && X(t.blockHash) === XO && (t.blockHash = null), t;
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/providers/plugins-network.js
+var fk = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", pk = class e {
+ name;
+ constructor(e) {
+ G(this, { name: e });
+ }
+ clone() {
+ return new e(this.name);
+ }
+}, mk = class e extends pk {
+ effectiveBlock;
+ txBase;
+ txCreate;
+ txDataZero;
+ txDataNonzero;
+ txAccessListStorageKey;
+ txAccessListAddress;
+ constructor(e, t) {
+ e ??= 0, super(`org.ethers.network.plugins.GasCost#${e || 0}`);
+ let n = { effectiveBlock: e };
+ function r(e, r) {
+ let i = (t || {})[e];
+ i ??= r, q(typeof i == "number", `invalud value for ${e}`, "costs", t), n[e] = i;
+ }
+ r("txBase", 21e3), r("txCreate", 32e3), r("txDataZero", 4), r("txDataNonzero", 16), r("txAccessListStorageKey", 1900), r("txAccessListAddress", 2400), G(this, n);
+ }
+ clone() {
+ return new e(this.effectiveBlock, this);
+ }
+}, hk = class e extends pk {
+ address;
+ targetNetwork;
+ constructor(e, t) {
+ super("org.ethers.plugins.network.Ens"), G(this, {
+ address: e || fk,
+ targetNetwork: t ?? 1
+ });
+ }
+ clone() {
+ return new e(this.address, this.targetNetwork);
+ }
+}, gk = class extends pk {
+ #e;
+ #t;
+ get url() {
+ return this.#e;
+ }
+ get processFunc() {
+ return this.#t;
+ }
+ constructor(e, t) {
+ super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"), this.#e = e, this.#t = t;
+ }
+ clone() {
+ return this;
+ }
+}, _k = /* @__PURE__ */ new Map(), vk = class e {
+ #e;
+ #t;
+ #n;
+ constructor(e, t) {
+ this.#e = e, this.#t = X(t), this.#n = /* @__PURE__ */ new Map();
+ }
+ toJSON() {
+ return {
+ name: this.name,
+ chainId: String(this.chainId)
+ };
+ }
+ get name() {
+ return this.#e;
+ }
+ set name(e) {
+ this.#e = e;
+ }
+ get chainId() {
+ return this.#t;
+ }
+ set chainId(e) {
+ this.#t = X(e, "chainId");
+ }
+ matches(e) {
+ if (e == null) return !1;
+ if (typeof e == "string") {
+ try {
+ return this.chainId === X(e);
+ } catch {}
+ return this.name === e;
+ }
+ if (typeof e == "number" || typeof e == "bigint") {
+ try {
+ return this.chainId === X(e);
+ } catch {}
+ return !1;
+ }
+ if (typeof e == "object") {
+ if (e.chainId != null) {
+ try {
+ return this.chainId === X(e.chainId);
+ } catch {}
+ return !1;
+ }
+ return e.name == null ? !1 : this.name === e.name;
+ }
+ return !1;
+ }
+ get plugins() {
+ return Array.from(this.#n.values());
+ }
+ attachPlugin(e) {
+ if (this.#n.get(e.name)) throw Error(`cannot replace existing plugin: ${e.name} `);
+ return this.#n.set(e.name, e.clone()), this;
+ }
+ getPlugin(e) {
+ return this.#n.get(e) || null;
+ }
+ getPlugins(e) {
+ return this.plugins.filter((t) => t.name.split("#")[0] === e);
+ }
+ clone() {
+ let t = new e(this.name, this.chainId);
+ return this.plugins.forEach((e) => {
+ t.attachPlugin(e.clone());
+ }), t;
+ }
+ computeIntrinsicGas(e) {
+ let t = this.getPlugin("org.ethers.plugins.network.GasCost") || new mk(), n = t.txBase;
+ if (e.to ?? (n += t.txCreate), e.data) for (let r = 2; r < e.data.length; r += 2) e.data.substring(r, r + 2) === "00" ? n += t.txDataZero : n += t.txDataNonzero;
+ if (e.accessList) {
+ let r = cw(e.accessList);
+ for (let e in r) n += t.txAccessListAddress + t.txAccessListStorageKey * r[e].storageKeys.length;
+ }
+ return n;
+ }
+ static from(t) {
+ if (Sk(), t == null) return e.from("mainnet");
+ if (typeof t == "number" && (t = BigInt(t)), typeof t == "string" || typeof t == "bigint") {
+ let n = _k.get(t);
+ if (n) return n();
+ if (typeof t == "bigint") return new e("unknown", t);
+ q(!1, "unknown network", "network", t);
+ }
+ if (typeof t.clone == "function") return t.clone();
+ if (typeof t == "object") {
+ q(typeof t.name == "string" && typeof t.chainId == "number", "invalid network object name or chainId", "network", t);
+ let n = new e(t.name, t.chainId);
+ return (t.ensAddress || t.ensNetwork != null) && n.attachPlugin(new hk(t.ensAddress, t.ensNetwork)), n;
+ }
+ q(!1, "invalid network", "network", t);
+ }
+ static register(e, t) {
+ typeof e == "number" && (e = BigInt(e));
+ let n = _k.get(e);
+ n && q(!1, `conflicting network for ${JSON.stringify(n.name)}`, "nameOrChainId", e), _k.set(e, t);
+ }
+};
+function yk(e, t) {
+ let n = String(e);
+ if (!n.match(/^[0-9.]+$/)) throw Error(`invalid gwei value: ${e}`);
+ let r = n.split(".");
+ if (r.length === 1 && r.push(""), r.length !== 2) throw Error(`invalid gwei value: ${e}`);
+ for (; r[1].length < t;) r[1] += "0";
+ if (r[1].length > 9) {
+ let e = BigInt(r[1].substring(0, 9));
+ r[1].substring(9).match(/^0+$/) || e++, r[1] = e.toString();
+ }
+ return BigInt(r[0] + r[1]);
+}
+function bk(e) {
+ return new gk(e, async (e, t, n) => {
+ n.setHeader("User-Agent", "ethers");
+ let r;
+ try {
+ let [t, i] = await Promise.all([n.send(), e()]);
+ r = t;
+ let a = r.bodyJson.standard;
+ return {
+ gasPrice: i.gasPrice,
+ maxFeePerGas: yk(a.maxFee, 9),
+ maxPriorityFeePerGas: yk(a.maxPriorityFee, 9)
+ };
+ } catch (e) {
+ K(!1, `error encountered with polygon gas station (${JSON.stringify(n.url)})`, "SERVER_ERROR", {
+ request: n,
+ response: r,
+ error: e
+ });
+ }
+ });
+}
+var xk = !1;
+function Sk() {
+ if (xk) return;
+ xk = !0;
+ function e(e, t, n) {
+ let r = function() {
+ let r = new vk(e, t);
+ return n.ensNetwork != null && r.attachPlugin(new hk(null, n.ensNetwork)), r.attachPlugin(new mk()), (n.plugins || []).forEach((e) => {
+ r.attachPlugin(e);
+ }), r;
+ };
+ vk.register(e, r), vk.register(t, r), n.altNames && n.altNames.forEach((e) => {
+ vk.register(e, r);
+ });
+ }
+ e("mainnet", 1, {
+ ensNetwork: 1,
+ altNames: ["homestead"]
+ }), e("ropsten", 3, { ensNetwork: 3 }), e("rinkeby", 4, { ensNetwork: 4 }), e("goerli", 5, { ensNetwork: 5 }), e("kovan", 42, { ensNetwork: 42 }), e("sepolia", 11155111, { ensNetwork: 11155111 }), e("holesky", 17e3, { ensNetwork: 17e3 }), e("classic", 61, {}), e("classicKotti", 6, {}), e("arbitrum", 42161, { ensNetwork: 1 }), e("arbitrum-goerli", 421613, {}), e("arbitrum-sepolia", 421614, {}), e("base", 8453, { ensNetwork: 1 }), e("base-goerli", 84531, {}), e("base-sepolia", 84532, {}), e("bnb", 56, { ensNetwork: 1 }), e("bnbt", 97, {}), e("filecoin", 314, {}), e("filecoin-calibration", 314159, {}), e("linea", 59144, { ensNetwork: 1 }), e("linea-goerli", 59140, {}), e("linea-sepolia", 59141, {}), e("matic", 137, {
+ ensNetwork: 1,
+ plugins: [bk("https://gasstation.polygon.technology/v2")]
+ }), e("matic-amoy", 80002, {}), e("matic-mumbai", 80001, {
+ altNames: ["maticMumbai", "maticmum"],
+ plugins: [bk("https://gasstation-testnet.polygon.technology/v2")]
+ }), e("optimism", 10, {
+ ensNetwork: 1,
+ plugins: []
+ }), e("optimism-goerli", 420, {}), e("optimism-sepolia", 11155420, {}), e("xdai", 100, { ensNetwork: 1 });
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/providers/subscriber-polling.js
+function Ck(e) {
+ return JSON.parse(JSON.stringify(e));
+}
+var wk = class {
+ #e;
+ #t;
+ #n;
+ #r;
+ constructor(e) {
+ this.#e = e, this.#t = null, this.#n = 4e3, this.#r = -2;
+ }
+ get pollingInterval() {
+ return this.#n;
+ }
+ set pollingInterval(e) {
+ this.#n = e;
+ }
+ async #i() {
+ try {
+ let e = await this.#e.getBlockNumber();
+ if (this.#r === -2) {
+ this.#r = e;
+ return;
+ }
+ if (e !== this.#r) {
+ for (let t = this.#r + 1; t <= e; t++) {
+ if (this.#t == null) return;
+ await this.#e.emit("block", t);
+ }
+ this.#r = e;
+ }
+ } catch {}
+ this.#t != null && (this.#t = this.#e._setTimeout(this.#i.bind(this), this.#n));
+ }
+ start() {
+ this.#t || (this.#t = this.#e._setTimeout(this.#i.bind(this), this.#n), this.#i());
+ }
+ stop() {
+ this.#t &&= (this.#e._clearTimeout(this.#t), null);
+ }
+ pause(e) {
+ this.stop(), e && (this.#r = -2);
+ }
+ resume() {
+ this.start();
+ }
+}, Tk = class {
+ #e;
+ #t;
+ #n;
+ constructor(e) {
+ this.#e = e, this.#n = !1, this.#t = (e) => {
+ this._poll(e, this.#e);
+ };
+ }
+ async _poll(e, t) {
+ throw Error("sub-classes must override this");
+ }
+ start() {
+ this.#n || (this.#n = !0, this.#t(-2), this.#e.on("block", this.#t));
+ }
+ stop() {
+ this.#n && (this.#n = !1, this.#e.off("block", this.#t));
+ }
+ pause(e) {
+ this.stop();
+ }
+ resume() {
+ this.start();
+ }
+}, Ek = class extends Tk {
+ #e;
+ #t;
+ constructor(e, t) {
+ super(e), this.#e = t, this.#t = -2;
+ }
+ pause(e) {
+ e && (this.#t = -2), super.pause(e);
+ }
+ async _poll(e, t) {
+ let n = await t.getBlock(this.#e);
+ n != null && (this.#t === -2 ? this.#t = n.number : n.number > this.#t && (t.emit(this.#e, n.number), this.#t = n.number));
+ }
+}, Dk = class extends Tk {
+ #e;
+ constructor(e, t) {
+ super(e), this.#e = Ck(t);
+ }
+ async _poll(e, t) {
+ throw Error("@TODO");
+ }
+}, Ok = class extends Tk {
+ #e;
+ constructor(e, t) {
+ super(e), this.#e = t;
+ }
+ async _poll(e, t) {
+ let n = await t.getTransactionReceipt(this.#e);
+ n && t.emit(this.#e, n);
+ }
+}, kk = class {
+ #e;
+ #t;
+ #n;
+ #r;
+ #i;
+ constructor(e, t) {
+ this.#e = e, this.#t = Ck(t), this.#n = this.#a.bind(this), this.#r = !1, this.#i = -2;
+ }
+ async #a(e) {
+ if (this.#i === -2) return;
+ let t = Ck(this.#t);
+ t.fromBlock = this.#i + 1, t.toBlock = e;
+ let n = await this.#e.getLogs(t);
+ if (n.length === 0) {
+ this.#i < e - 60 && (this.#i = e - 60);
+ return;
+ }
+ for (let e of n) this.#e.emit(this.#t, e), this.#i = e.blockNumber;
+ }
+ start() {
+ this.#r || (this.#r = !0, this.#i === -2 && this.#e.getBlockNumber().then((e) => {
+ this.#i = e;
+ }), this.#e.on("block", this.#n));
+ }
+ stop() {
+ this.#r && (this.#r = !1, this.#e.off("block", this.#n));
+ }
+ pause(e) {
+ this.stop(), e && (this.#i = -2);
+ }
+ resume() {
+ this.start();
+ }
+}, Ak = BigInt(2), jk = 10;
+function Mk(e) {
+ return e && typeof e.then == "function";
+}
+function Nk(e, t) {
+ return e + ":" + JSON.stringify(t, (e, t) => {
+ if (t == null) return "null";
+ if (typeof t == "bigint") return `bigint:${t.toString()}`;
+ if (typeof t == "string") return t.toLowerCase();
+ if (typeof t == "object" && !Array.isArray(t)) {
+ let e = Object.keys(t);
+ return e.sort(), e.reduce((e, n) => (e[n] = t[n], e), {});
+ }
+ return t;
+ });
+}
+var Pk = class {
+ name;
+ constructor(e) {
+ G(this, { name: e });
+ }
+ start() {}
+ stop() {}
+ pause(e) {}
+ resume() {}
+};
+function Fk(e) {
+ return JSON.parse(JSON.stringify(e));
+}
+function Ik(e) {
+ return e = Array.from(new Set(e).values()), e.sort(), e;
+}
+async function Lk(e, t) {
+ if (e == null) throw Error("invalid event");
+ if (Array.isArray(e) && (e = { topics: e }), typeof e == "string") switch (e) {
+ case "block":
+ case "debug":
+ case "error":
+ case "finalized":
+ case "network":
+ case "pending":
+ case "safe": return {
+ type: e,
+ tag: e
+ };
+ }
+ if (jv(e, 32)) {
+ let t = e.toLowerCase();
+ return {
+ type: "transaction",
+ tag: Nk("tx", { hash: t }),
+ hash: t
+ };
+ }
+ if (e.orphan) {
+ let t = e;
+ return {
+ type: "orphan",
+ tag: Nk("orphan", t),
+ filter: Fk(t)
+ };
+ }
+ if (e.address || e.topics) {
+ let n = e, r = { topics: (n.topics || []).map((e) => e == null ? null : Array.isArray(e) ? Ik(e.map((e) => e.toLowerCase())) : e.toLowerCase()) };
+ if (n.address) {
+ let e = [], i = [], a = (n) => {
+ jv(n) ? e.push(n) : i.push((async () => {
+ e.push(await zC(n, t));
+ })());
+ };
+ Array.isArray(n.address) ? n.address.forEach(a) : a(n.address), i.length && await Promise.all(i), r.address = Ik(e.map((e) => e.toLowerCase()));
+ }
+ return {
+ filter: r,
+ tag: Nk("event", r),
+ type: "event"
+ };
+ }
+ q(!1, "unknown ProviderEvent", "event", e);
+}
+function Rk() {
+ return (/* @__PURE__ */ new Date()).getTime();
+}
+var zk = {
+ cacheTimeout: 250,
+ pollingInterval: 4e3
+}, Bk = class {
+ #e;
+ #t;
+ #n;
+ #r;
+ #i;
+ #a;
+ #o;
+ #s;
+ #c;
+ #l;
+ #u;
+ #d;
+ constructor(e, t) {
+ if (this.#d = Object.assign({}, zk, t || {}), e === "any") this.#a = !0, this.#i = null;
+ else if (e) {
+ let t = vk.from(e);
+ this.#a = !1, this.#i = Promise.resolve(t), setTimeout(() => {
+ this.emit("network", t, null);
+ }, 0);
+ } else this.#a = !1, this.#i = null;
+ this.#s = -1, this.#o = /* @__PURE__ */ new Map(), this.#e = /* @__PURE__ */ new Map(), this.#t = /* @__PURE__ */ new Map(), this.#n = null, this.#r = !1, this.#c = 1, this.#l = /* @__PURE__ */ new Map(), this.#u = !1;
+ }
+ get pollingInterval() {
+ return this.#d.pollingInterval;
+ }
+ get provider() {
+ return this;
+ }
+ get plugins() {
+ return Array.from(this.#t.values());
+ }
+ attachPlugin(e) {
+ if (this.#t.get(e.name)) throw Error(`cannot replace existing plugin: ${e.name} `);
+ return this.#t.set(e.name, e.connect(this)), this;
+ }
+ getPlugin(e) {
+ return this.#t.get(e) || null;
+ }
+ get disableCcipRead() {
+ return this.#u;
+ }
+ set disableCcipRead(e) {
+ this.#u = !!e;
+ }
+ async #f(e) {
+ let t = this.#d.cacheTimeout;
+ if (t < 0) return await this._perform(e);
+ let n = Nk(e.method, e), r = this.#o.get(n);
+ return r || (r = this._perform(e), this.#o.set(n, r), setTimeout(() => {
+ this.#o.get(n) === r && this.#o.delete(n);
+ }, t)), await r;
+ }
+ async ccipReadFetch(e, t, n) {
+ if (this.disableCcipRead || n.length === 0 || e.to == null) return null;
+ let r = e.to.toLowerCase(), i = t.toLowerCase(), a = [];
+ for (let t = 0; t < n.length; t++) {
+ let o = n[t], s = new Ey(o.replace("{sender}", r).replace("{data}", i));
+ o.indexOf("{data}") === -1 && (s.body = {
+ data: i,
+ sender: r
+ }), this.emit("debug", {
+ action: "sendCcipReadFetchRequest",
+ request: s,
+ index: t,
+ urls: n
+ });
+ let c = "unknown error", l;
+ try {
+ l = await s.send();
+ } catch (e) {
+ a.push(e.message), this.emit("debug", {
+ action: "receiveCcipReadFetchError",
+ request: s,
+ result: { error: e }
+ });
+ continue;
+ }
+ try {
+ let e = l.bodyJson;
+ if (e.data) return this.emit("debug", {
+ action: "receiveCcipReadFetchResult",
+ request: s,
+ result: e
+ }), e.data;
+ e.message && (c = e.message), this.emit("debug", {
+ action: "receiveCcipReadFetchError",
+ request: s,
+ result: e
+ });
+ } catch {}
+ K(l.statusCode < 400 || l.statusCode >= 500, `response not found during CCIP fetch: ${c}`, "OFFCHAIN_FAULT", {
+ reason: "404_MISSING_RESOURCE",
+ transaction: e,
+ info: {
+ url: o,
+ errorMessage: c
+ }
+ }), a.push(c);
+ }
+ K(!1, `error encountered during CCIP fetch: ${a.map((e) => JSON.stringify(e)).join(", ")}`, "OFFCHAIN_FAULT", {
+ reason: "500_SERVER_ERROR",
+ transaction: e,
+ info: {
+ urls: n,
+ errorMessages: a
+ }
+ });
+ }
+ _wrapBlock(e, t) {
+ return new nO(ok(e), this);
+ }
+ _wrapLog(e, t) {
+ return new rO(ik(e), this);
+ }
+ _wrapTransactionReceipt(e, t) {
+ return new iO(uk(e), this);
+ }
+ _wrapTransactionResponse(e, t) {
+ return new aO(dk(e), this);
+ }
+ _detectNetwork() {
+ K(!1, "sub-classes must implement this", "UNSUPPORTED_OPERATION", { operation: "_detectNetwork" });
+ }
+ async _perform(e) {
+ K(!1, `unsupported method: ${e.method}`, "UNSUPPORTED_OPERATION", {
+ operation: e.method,
+ info: e
+ });
+ }
+ async getBlockNumber() {
+ let e = Z(await this.#f({ method: "getBlockNumber" }), "%response");
+ return this.#s >= 0 && (this.#s = e), e;
+ }
+ _getAddress(e) {
+ return zC(e, this);
+ }
+ _getBlockTag(e) {
+ if (e == null) return "latest";
+ switch (e) {
+ case "earliest": return "0x0";
+ case "finalized":
+ case "latest":
+ case "pending":
+ case "safe": return e;
+ }
+ if (jv(e)) return jv(e, 32) ? e : Qv(e);
+ if (typeof e == "bigint" && (e = Z(e, "blockTag")), typeof e == "number") return e >= 0 ? Qv(e) : this.#s >= 0 ? Qv(this.#s + e) : this.getBlockNumber().then((t) => Qv(t + e));
+ q(!1, "invalid blockTag", "blockTag", e);
+ }
+ _getFilter(e) {
+ let t = (e.topics || []).map((e) => e == null ? null : Array.isArray(e) ? Ik(e.map((e) => e.toLowerCase())) : e.toLowerCase()), n = "blockHash" in e ? e.blockHash : void 0, r = (e, r, i) => {
+ let a;
+ switch (e.length) {
+ case 0: break;
+ case 1:
+ a = e[0];
+ break;
+ default: e.sort(), a = e;
+ }
+ if (n && (r != null || i != null)) throw Error("invalid filter");
+ let o = {};
+ return a && (o.address = a), t.length && (o.topics = t), r && (o.fromBlock = r), i && (o.toBlock = i), n && (o.blockHash = n), o;
+ }, i = [];
+ if (e.address) if (Array.isArray(e.address)) for (let t of e.address) i.push(this._getAddress(t));
+ else i.push(this._getAddress(e.address));
+ let a;
+ "fromBlock" in e && (a = this._getBlockTag(e.fromBlock));
+ let o;
+ return "toBlock" in e && (o = this._getBlockTag(e.toBlock)), i.filter((e) => typeof e != "string").length || a != null && typeof a != "string" || o != null && typeof o != "string" ? Promise.all([
+ Promise.all(i),
+ a,
+ o
+ ]).then((e) => r(e[0], e[1], e[2])) : r(i, a, o);
+ }
+ _getTransactionRequest(e) {
+ let t = tO(e), n = [];
+ if (["to", "from"].forEach((e) => {
+ if (t[e] == null) return;
+ let r = zC(t[e], this);
+ Mk(r) ? n.push((async function() {
+ t[e] = await r;
+ })()) : t[e] = r;
+ }), t.blockTag != null) {
+ let e = this._getBlockTag(t.blockTag);
+ Mk(e) ? n.push((async function() {
+ t.blockTag = await e;
+ })()) : t.blockTag = e;
+ }
+ return n.length ? (async function() {
+ return await Promise.all(n), t;
+ })() : t;
+ }
+ async getNetwork() {
+ if (this.#i == null) {
+ let e = (async () => {
+ try {
+ let e = await this._detectNetwork();
+ return this.emit("network", e, null), e;
+ } catch (t) {
+ throw this.#i === e && (this.#i = null), t;
+ }
+ })();
+ return this.#i = e, (await e).clone();
+ }
+ let e = this.#i, [t, n] = await Promise.all([e, this._detectNetwork()]);
+ return t.chainId !== n.chainId && (this.#a ? (this.emit("network", n, t), this.#i === e && (this.#i = Promise.resolve(n))) : K(!1, `network changed: ${t.chainId} => ${n.chainId} `, "NETWORK_ERROR", { event: "changed" })), t.clone();
+ }
+ async getFeeData() {
+ let e = await this.getNetwork(), t = async () => {
+ let { _block: t, gasPrice: n, priorityFee: r } = await bv({
+ _block: this.#g("latest", !1),
+ gasPrice: (async () => {
+ try {
+ return X(await this.#f({ method: "getGasPrice" }), "%response");
+ } catch {}
+ return null;
+ })(),
+ priorityFee: (async () => {
+ try {
+ return X(await this.#f({ method: "getPriorityFee" }), "%response");
+ } catch {}
+ return null;
+ })()
+ }), i = null, a = null, o = this._wrapBlock(t, e);
+ return o && o.baseFeePerGas && (a = r ?? BigInt("1000000000"), i = o.baseFeePerGas * Ak + a), new eO(n, i, a);
+ }, n = e.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin");
+ if (n) {
+ let e = new Ey(n.url), r = await n.processFunc(t, this, e);
+ return new eO(r.gasPrice, r.maxFeePerGas, r.maxPriorityFeePerGas);
+ }
+ return await t();
+ }
+ async estimateGas(e) {
+ let t = this._getTransactionRequest(e);
+ return Mk(t) && (t = await t), X(await this.#f({
+ method: "estimateGas",
+ transaction: t
+ }), "%response");
+ }
+ async #p(e, t, n) {
+ K(n < jk, "CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", {
+ reason: "TOO_MANY_REDIRECTS",
+ transaction: Object.assign({}, e, {
+ blockTag: t,
+ enableCcipRead: !0
+ })
+ });
+ let r = tO(e);
+ try {
+ return Y(await this._perform({
+ method: "call",
+ transaction: r,
+ blockTag: t
+ }));
+ } catch (e) {
+ if (!this.disableCcipRead && Cv(e) && e.data && n >= 0 && t === "latest" && r.to != null && Iv(e.data, 0, 4) === "0x556f1830") {
+ let i = e.data, a = await zC(r.to, this), o;
+ try {
+ o = Jk(Iv(e.data, 4));
+ } catch (e) {
+ K(!1, e.message, "OFFCHAIN_FAULT", {
+ reason: "BAD_DATA",
+ transaction: r,
+ info: { data: i }
+ });
+ }
+ K(o.sender.toLowerCase() === a.toLowerCase(), "CCIP Read sender mismatch", "CALL_EXCEPTION", {
+ action: "call",
+ data: i,
+ reason: "OffchainLookup",
+ transaction: r,
+ invocation: null,
+ revert: {
+ signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
+ name: "OffchainLookup",
+ args: o.errorArgs
+ }
+ });
+ let s = await this.ccipReadFetch(r, o.calldata, o.urls);
+ K(s != null, "CCIP Read failed to fetch data", "OFFCHAIN_FAULT", {
+ reason: "FETCH_FAILED",
+ transaction: r,
+ info: {
+ data: e.data,
+ errorArgs: o.errorArgs
+ }
+ });
+ let c = {
+ to: a,
+ data: Pv([o.selector, Kk([s, o.extraData])])
+ };
+ this.emit("debug", {
+ action: "sendCcipReadCall",
+ transaction: c
+ });
+ try {
+ let e = await this.#p(c, t, n + 1);
+ return this.emit("debug", {
+ action: "receiveCcipReadCallResult",
+ transaction: Object.assign({}, c),
+ result: e
+ }), e;
+ } catch (e) {
+ throw this.emit("debug", {
+ action: "receiveCcipReadCallError",
+ transaction: Object.assign({}, c),
+ error: e
+ }), e;
+ }
+ }
+ throw e;
+ }
+ }
+ async #m(e) {
+ let { value: t } = await bv({
+ network: this.getNetwork(),
+ value: e
+ });
+ return t;
+ }
+ async call(e) {
+ let { tx: t, blockTag: n } = await bv({
+ tx: this._getTransactionRequest(e),
+ blockTag: this._getBlockTag(e.blockTag)
+ });
+ return await this.#m(this.#p(t, n, e.enableCcipRead ? 0 : -1));
+ }
+ async #h(e, t, n) {
+ let r = this._getAddress(t), i = this._getBlockTag(n);
+ return (typeof r != "string" || typeof i != "string") && ([r, i] = await Promise.all([r, i])), await this.#m(this.#f(Object.assign(e, {
+ address: r,
+ blockTag: i
+ })));
+ }
+ async getBalance(e, t) {
+ return X(await this.#h({ method: "getBalance" }, e, t), "%response");
+ }
+ async getTransactionCount(e, t) {
+ return Z(await this.#h({ method: "getTransactionCount" }, e, t), "%response");
+ }
+ async getCode(e, t) {
+ return Y(await this.#h({ method: "getCode" }, e, t));
+ }
+ async getStorage(e, t, n) {
+ let r = X(t, "position");
+ return Y(await this.#h({
+ method: "getStorage",
+ position: r
+ }, e, n));
+ }
+ async broadcastTransaction(e) {
+ let { blockNumber: t, hash: n, network: r } = await bv({
+ blockNumber: this.getBlockNumber(),
+ hash: this._perform({
+ method: "broadcastTransaction",
+ signedTransaction: e
+ }),
+ network: this.getNetwork()
+ }), i = Uw.from(e);
+ if (i.hash !== n) throw Error("@TODO: the returned hash did not match");
+ return this._wrapTransactionResponse(i, r).replaceableTransaction(t);
+ }
+ async #g(e, t) {
+ if (jv(e, 32)) return await this.#f({
+ method: "getBlock",
+ blockHash: e,
+ includeTransactions: t
+ });
+ let n = this._getBlockTag(e);
+ return typeof n != "string" && (n = await n), await this.#f({
+ method: "getBlock",
+ blockTag: n,
+ includeTransactions: t
+ });
+ }
+ async getBlock(e, t) {
+ let { network: n, params: r } = await bv({
+ network: this.getNetwork(),
+ params: this.#g(e, !!t)
+ });
+ return r == null ? null : this._wrapBlock(r, n);
+ }
+ async getTransaction(e) {
+ let { network: t, params: n } = await bv({
+ network: this.getNetwork(),
+ params: this.#f({
+ method: "getTransaction",
+ hash: e
+ })
+ });
+ return n == null ? null : this._wrapTransactionResponse(n, t);
+ }
+ async getTransactionReceipt(e) {
+ let { network: t, params: n } = await bv({
+ network: this.getNetwork(),
+ params: this.#f({
+ method: "getTransactionReceipt",
+ hash: e
+ })
+ });
+ if (n == null) return null;
+ if (n.gasPrice == null && n.effectiveGasPrice == null) {
+ let t = await this.#f({
+ method: "getTransaction",
+ hash: e
+ });
+ if (t == null) throw Error("report this; could not find tx or effectiveGasPrice");
+ n.effectiveGasPrice = t.gasPrice;
+ }
+ return this._wrapTransactionReceipt(n, t);
+ }
+ async getTransactionResult(e) {
+ let { result: t } = await bv({
+ network: this.getNetwork(),
+ result: this.#f({
+ method: "getTransactionResult",
+ hash: e
+ })
+ });
+ return t == null ? null : Y(t);
+ }
+ async getLogs(e) {
+ let t = this._getFilter(e);
+ Mk(t) && (t = await t);
+ let { network: n, params: r } = await bv({
+ network: this.getNetwork(),
+ params: this.#f({
+ method: "getLogs",
+ filter: t
+ })
+ });
+ return r.map((e) => this._wrapLog(e, n));
+ }
+ _getProvider(e) {
+ K(!1, "provider cannot connect to target network", "UNSUPPORTED_OPERATION", { operation: "_getProvider()" });
+ }
+ async getResolver(e) {
+ return await YO.fromName(this, e);
+ }
+ async getAvatar(e) {
+ let t = await this.getResolver(e);
+ return t ? await t.getAvatar() : null;
+ }
+ async resolveName(e) {
+ let t = await this.getResolver(e);
+ return t ? await t.getAddress() : null;
+ }
+ async lookupAddress(e) {
+ e = FC(e);
+ let t = OE(e.substring(2).toLowerCase() + ".addr.reverse");
+ try {
+ let n = await new WO(await YO.getEnsAddress(this), ["function resolver(bytes32) view returns (address)"], this).resolver(t);
+ if (n == null || n === "0x0000000000000000000000000000000000000000") return null;
+ let r = await new WO(n, ["function name(bytes32) view returns (string)"], this).name(t);
+ return await this.resolveName(r) === e ? r : null;
+ } catch (e) {
+ if (Sv(e, "BAD_DATA") && e.value === "0x" || Sv(e, "CALL_EXCEPTION")) return null;
+ throw e;
+ }
+ return null;
+ }
+ async waitForTransaction(e, t, n) {
+ let r = t ?? 1;
+ return r === 0 ? this.getTransactionReceipt(e) : new Promise(async (t, i) => {
+ let a = null, o = (async (n) => {
+ try {
+ let i = await this.getTransactionReceipt(e);
+ if (i != null && n - i.blockNumber + 1 >= r) {
+ t(i), a &&= (clearTimeout(a), null);
+ return;
+ }
+ } catch (e) {
+ console.log("EEE", e);
+ }
+ this.once("block", o);
+ });
+ n != null && (a = setTimeout(() => {
+ a != null && (a = null, this.off("block", o), i(wv("timeout", "TIMEOUT", { reason: "timeout" })));
+ }, n)), o(await this.getBlockNumber());
+ });
+ }
+ async waitForBlock(e) {
+ K(!1, "not implemented yet", "NOT_IMPLEMENTED", { operation: "waitForBlock" });
+ }
+ _clearTimeout(e) {
+ let t = this.#l.get(e);
+ t && (t.timer && clearTimeout(t.timer), this.#l.delete(e));
+ }
+ _setTimeout(e, t) {
+ t ??= 0;
+ let n = this.#c++, r = () => {
+ this.#l.delete(n), e();
+ };
+ if (this.paused) this.#l.set(n, {
+ timer: null,
+ func: r,
+ time: t
+ });
+ else {
+ let e = setTimeout(r, t);
+ this.#l.set(n, {
+ timer: e,
+ func: r,
+ time: Rk()
+ });
+ }
+ return n;
+ }
+ _forEachSubscriber(e) {
+ for (let t of this.#e.values()) e(t.subscriber);
+ }
+ _getSubscriber(e) {
+ switch (e.type) {
+ case "debug":
+ case "error":
+ case "network": return new Pk(e.type);
+ case "block": {
+ let e = new wk(this);
+ return e.pollingInterval = this.pollingInterval, e;
+ }
+ case "safe":
+ case "finalized": return new Ek(this, e.type);
+ case "event": return new kk(this, e.filter);
+ case "transaction": return new Ok(this, e.hash);
+ case "orphan": return new Dk(this, e.filter);
+ }
+ throw Error(`unsupported event: ${e.type}`);
+ }
+ _recoverSubscriber(e, t) {
+ for (let n of this.#e.values()) if (n.subscriber === e) {
+ n.started && n.subscriber.stop(), n.subscriber = t, n.started && t.start(), this.#n != null && t.pause(this.#n);
+ break;
+ }
+ }
+ async #_(e, t) {
+ let n = await Lk(e, this);
+ return n.type === "event" && t && t.length > 0 && t[0].removed === !0 && (n = await Lk({
+ orphan: "drop-log",
+ log: t[0]
+ }, this)), this.#e.get(n.tag) || null;
+ }
+ async #v(e) {
+ let t = await Lk(e, this), n = t.tag, r = this.#e.get(n);
+ return r || (r = {
+ subscriber: this._getSubscriber(t),
+ tag: n,
+ addressableMap: /* @__PURE__ */ new WeakMap(),
+ nameMap: /* @__PURE__ */ new Map(),
+ started: !1,
+ listeners: []
+ }, this.#e.set(n, r)), r;
+ }
+ async on(e, t) {
+ let n = await this.#v(e);
+ return n.listeners.push({
+ listener: t,
+ once: !1
+ }), n.started || (n.subscriber.start(), n.started = !0, this.#n != null && n.subscriber.pause(this.#n)), this;
+ }
+ async once(e, t) {
+ let n = await this.#v(e);
+ return n.listeners.push({
+ listener: t,
+ once: !0
+ }), n.started || (n.subscriber.start(), n.started = !0, this.#n != null && n.subscriber.pause(this.#n)), this;
+ }
+ async emit(e, ...t) {
+ let n = await this.#_(e, t);
+ if (!n || n.listeners.length === 0) return !1;
+ let r = n.listeners.length;
+ return n.listeners = n.listeners.filter(({ listener: n, once: r }) => {
+ let i = new iy(this, r ? null : n, e);
+ try {
+ n.call(this, ...t, i);
+ } catch {}
+ return !r;
+ }), n.listeners.length === 0 && (n.started && n.subscriber.stop(), this.#e.delete(n.tag)), r > 0;
+ }
+ async listenerCount(e) {
+ if (e) {
+ let t = await this.#_(e);
+ return t ? t.listeners.length : 0;
+ }
+ let t = 0;
+ for (let { listeners: e } of this.#e.values()) t += e.length;
+ return t;
+ }
+ async listeners(e) {
+ if (e) {
+ let t = await this.#_(e);
+ return t ? t.listeners.map(({ listener: e }) => e) : [];
+ }
+ let t = [];
+ for (let { listeners: e } of this.#e.values()) t = t.concat(e.map(({ listener: e }) => e));
+ return t;
+ }
+ async off(e, t) {
+ let n = await this.#_(e);
+ if (!n) return this;
+ if (t) {
+ let e = n.listeners.map(({ listener: e }) => e).indexOf(t);
+ e >= 0 && n.listeners.splice(e, 1);
+ }
+ return (!t || n.listeners.length === 0) && (n.started && n.subscriber.stop(), this.#e.delete(n.tag)), this;
+ }
+ async removeAllListeners(e) {
+ if (e) {
+ let { tag: t, started: n, subscriber: r } = await this.#v(e);
+ n && r.stop(), this.#e.delete(t);
+ } else for (let [e, { started: t, subscriber: n }] of this.#e) t && n.stop(), this.#e.delete(e);
+ return this;
+ }
+ async addListener(e, t) {
+ return await this.on(e, t);
+ }
+ async removeListener(e, t) {
+ return this.off(e, t);
+ }
+ get destroyed() {
+ return this.#r;
+ }
+ destroy() {
+ this.removeAllListeners();
+ for (let e of this.#l.keys()) this._clearTimeout(e);
+ this.#r = !0;
+ }
+ get paused() {
+ return this.#n != null;
+ }
+ set paused(e) {
+ !!e !== this.paused && (this.paused ? this.resume() : this.pause(!1));
+ }
+ pause(e) {
+ if (this.#s = -1, this.#n != null) {
+ if (this.#n == !!e) return;
+ K(!1, "cannot change pause type; resume first", "UNSUPPORTED_OPERATION", { operation: "pause" });
+ }
+ this._forEachSubscriber((t) => t.pause(e)), this.#n = !!e;
+ for (let e of this.#l.values()) e.timer && clearTimeout(e.timer), e.time = Rk() - e.time;
+ }
+ resume() {
+ if (this.#n != null) {
+ this._forEachSubscriber((e) => e.resume()), this.#n = null;
+ for (let e of this.#l.values()) {
+ let t = e.time;
+ t < 0 && (t = 0), e.time = Rk(), setTimeout(e.func, t);
+ }
+ }
+ }
+};
+function Vk(e, t) {
+ try {
+ let n = Hk(e, t);
+ if (n) return fy(n);
+ } catch {}
+ return null;
+}
+function Hk(e, t) {
+ if (e === "0x") return null;
+ try {
+ let n = Z(Iv(e, t, t + 32)), r = Z(Iv(e, n, n + 32));
+ return Iv(e, n + 32, n + 32 + r);
+ } catch {}
+ return null;
+}
+function Uk(e) {
+ let t = Zv(e);
+ if (t.length > 32) throw Error("internal; should not happen");
+ let n = new Uint8Array(32);
+ return n.set(t, 32 - t.length), n;
+}
+function Wk(e) {
+ if (e.length % 32 == 0) return e;
+ let t = new Uint8Array(Math.ceil(e.length / 32) * 32);
+ return t.set(e), t;
+}
+var Gk = new Uint8Array([]);
+function Kk(e) {
+ let t = [], n = 0;
+ for (let r = 0; r < e.length; r++) t.push(Gk), n += 32;
+ for (let r = 0; r < e.length; r++) {
+ let i = J(e[r]);
+ t[r] = Uk(n), t.push(Uk(i.length)), t.push(Wk(i)), n += 32 + Math.ceil(i.length / 32) * 32;
+ }
+ return Pv(t);
+}
+var qk = "0x0000000000000000000000000000000000000000000000000000000000000000";
+function Jk(e) {
+ let t = {
+ sender: "",
+ urls: [],
+ calldata: "",
+ selector: "",
+ extraData: "",
+ errorArgs: []
+ };
+ K(Fv(e) >= 160, "insufficient OffchainLookup data", "OFFCHAIN_FAULT", { reason: "insufficient OffchainLookup data" });
+ let n = Iv(e, 0, 32);
+ K(Iv(n, 0, 12) === Iv(qk, 0, 12), "corrupt OffchainLookup sender", "OFFCHAIN_FAULT", { reason: "corrupt OffchainLookup sender" }), t.sender = Iv(n, 12);
+ try {
+ let n = [], r = Z(Iv(e, 32, 64)), i = Z(Iv(e, r, r + 32)), a = Iv(e, r + 32);
+ for (let e = 0; e < i; e++) {
+ let t = Vk(a, e * 32);
+ if (t == null) throw Error("abort");
+ n.push(t);
+ }
+ t.urls = n;
+ } catch {
+ K(!1, "corrupt OffchainLookup urls", "OFFCHAIN_FAULT", { reason: "corrupt OffchainLookup urls" });
+ }
+ try {
+ let n = Hk(e, 64);
+ if (n == null) throw Error("abort");
+ t.calldata = n;
+ } catch {
+ K(!1, "corrupt OffchainLookup calldata", "OFFCHAIN_FAULT", { reason: "corrupt OffchainLookup calldata" });
+ }
+ K(Iv(e, 100, 128) === Iv(qk, 0, 28), "corrupt OffchainLookup callbaackSelector", "OFFCHAIN_FAULT", { reason: "corrupt OffchainLookup callbaackSelector" }), t.selector = Iv(e, 96, 100);
+ try {
+ let n = Hk(e, 128);
+ if (n == null) throw Error("abort");
+ t.extraData = n;
+ } catch {
+ K(!1, "corrupt OffchainLookup extraData", "OFFCHAIN_FAULT", { reason: "corrupt OffchainLookup extraData" });
+ }
+ return t.errorArgs = "sender,urls,calldata,selector,extraData".split(/,/).map((e) => t[e]), t;
+}
+//#endregion
+//#region node_modules/ethers/lib.esm/providers/abstract-signer.js
+function Yk(e, t) {
+ if (e.provider) return e.provider;
+ K(!1, "missing provider", "UNSUPPORTED_OPERATION", { operation: t });
+}
+async function Xk(e, t) {
+ let n = tO(t);
+ if (n.to != null && (n.to = zC(n.to, e)), n.from != null) {
+ let t = n.from;
+ n.from = Promise.all([e.getAddress(), zC(t, e)]).then(([e, t]) => (q(e.toLowerCase() === t.toLowerCase(), "transaction from mismatch", "tx.from", t), e));
+ } else n.from = e.getAddress();
+ return await bv(n);
+}
+var Zk = class {
+ provider;
+ constructor(e) {
+ G(this, { provider: e || null });
+ }
+ async getNonce(e) {
+ return Yk(this, "getTransactionCount").getTransactionCount(await this.getAddress(), e);
+ }
+ async populateCall(e) {
+ return await Xk(this, e);
+ }
+ async populateTransaction(e) {
+ let t = Yk(this, "populateTransaction"), n = await Xk(this, e);
+ n.nonce ??= await this.getNonce("pending"), n.gasLimit ??= await this.estimateGas(n);
+ let r = await this.provider.getNetwork();
+ n.chainId == null ? n.chainId = r.chainId : q(X(n.chainId) === r.chainId, "transaction chainId mismatch", "tx.chainId", e.chainId);
+ let i = n.maxFeePerGas != null || n.maxPriorityFeePerGas != null;
+ if (n.gasPrice != null && (n.type === 2 || i) ? q(!1, "eip-1559 transaction do not support gasPrice", "tx", e) : (n.type === 0 || n.type === 1) && i && q(!1, "pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas", "tx", e), (n.type === 2 || n.type == null) && n.maxFeePerGas != null && n.maxPriorityFeePerGas != null) n.type = 2;
+ else if (n.type === 0 || n.type === 1) {
+ let e = await t.getFeeData();
+ K(e.gasPrice != null, "network does not support gasPrice", "UNSUPPORTED_OPERATION", { operation: "getGasPrice" }), n.gasPrice ??= e.gasPrice;
+ } else {
+ let e = await t.getFeeData();
+ if (n.type == null) if (e.maxFeePerGas != null && e.maxPriorityFeePerGas != null) if (n.authorizationList && n.authorizationList.length ? n.type = 4 : n.type = 2, n.gasPrice != null) {
+ let e = n.gasPrice;
+ delete n.gasPrice, n.maxFeePerGas = e, n.maxPriorityFeePerGas = e;
+ } else n.maxFeePerGas ??= e.maxFeePerGas, n.maxPriorityFeePerGas ??= e.maxPriorityFeePerGas;
+ else e.gasPrice == null ? K(!1, "failed to get consistent fee data", "UNSUPPORTED_OPERATION", { operation: "signer.getFeeData" }) : (K(!i, "network does not support EIP-1559", "UNSUPPORTED_OPERATION", { operation: "populateTransaction" }), n.gasPrice ??= e.gasPrice, n.type = 0);
+ else (n.type === 2 || n.type === 3 || n.type === 4) && (n.maxFeePerGas ??= e.maxFeePerGas, n.maxPriorityFeePerGas ??= e.maxPriorityFeePerGas);
+ }
+ return await bv(n);
+ }
+ async populateAuthorization(e) {
+ let t = Object.assign({}, e);
+ return t.chainId ??= (await Yk(this, "getNetwork").getNetwork()).chainId, t.nonce ??= await this.getNonce(), t;
+ }
+ async estimateGas(e) {
+ return Yk(this, "estimateGas").estimateGas(await this.populateCall(e));
+ }
+ async call(e) {
+ return Yk(this, "call").call(await this.populateCall(e));
+ }
+ async resolveName(e) {
+ return await Yk(this, "resolveName").resolveName(e);
+ }
+ async sendTransaction(e) {
+ let t = Yk(this, "sendTransaction"), n = await this.populateTransaction(e);
+ delete n.from;
+ let r = Uw.from(n);
+ return await t.broadcastTransaction(await this.signTransaction(r));
+ }
+ authorize(e) {
+ K(!1, "authorization not implemented for this signer", "UNSUPPORTED_OPERATION", { operation: "authorize" });
+ }
+};
+//#endregion
+//#region node_modules/ethers/lib.esm/providers/subscriber-filterid.js
+function Qk(e) {
+ return JSON.parse(JSON.stringify(e));
+}
+var $k = class {
+ #e;
+ #t;
+ #n;
+ #r;
+ #i;
+ #a;
+ constructor(e) {
+ this.#e = e, this.#t = null, this.#n = this.#o.bind(this), this.#r = !1, this.#i = null, this.#a = !1;
+ }
+ _subscribe(e) {
+ throw Error("subclasses must override this");
+ }
+ _emitResults(e, t) {
+ throw Error("subclasses must override this");
+ }
+ _recover(e) {
+ throw Error("subclasses must override this");
+ }
+ async #o(e) {
+ try {
+ this.#t ??= this._subscribe(this.#e);
+ let e = null;
+ try {
+ e = await this.#t;
+ } catch (e) {
+ if (!Sv(e, "UNSUPPORTED_OPERATION") || e.operation !== "eth_newFilter") throw e;
+ }
+ if (e == null) {
+ this.#t = null, this.#e._recoverSubscriber(this, this._recover(this.#e));
+ return;
+ }
+ let t = await this.#e.getNetwork();
+ if (this.#i ||= t, this.#i.chainId !== t.chainId) throw Error("chaid changed");
+ if (this.#a) return;
+ let n = await this.#e.send("eth_getFilterChanges", [e]);
+ await this._emitResults(this.#e, n);
+ } catch (e) {
+ console.log("@TODO", e);
+ }
+ this.#e.once("block", this.#n);
+ }
+ #s() {
+ let e = this.#t;
+ e && (this.#t = null, e.then((e) => {
+ this.#e.destroyed || this.#e.send("eth_uninstallFilter", [e]);
+ }));
+ }
+ start() {
+ this.#r || (this.#r = !0, this.#o(-2));
+ }
+ stop() {
+ this.#r && (this.#r = !1, this.#a = !0, this.#s(), this.#e.off("block", this.#n));
+ }
+ pause(e) {
+ e && this.#s(), this.#e.off("block", this.#n);
+ }
+ resume() {
+ this.start();
+ }
+}, eA = class extends $k {
+ #e;
+ constructor(e, t) {
+ super(e), this.#e = Qk(t);
+ }
+ _recover(e) {
+ return new kk(e, this.#e);
+ }
+ async _subscribe(e) {
+ return await e.send("eth_newFilter", [this.#e]);
+ }
+ async _emitResults(e, t) {
+ for (let n of t) e.emit(this.#e, e._wrapLog(n, e._network));
+ }
+}, tA = class extends $k {
+ async _subscribe(e) {
+ return await e.send("eth_newPendingTransactionFilter", []);
+ }
+ async _emitResults(e, t) {
+ for (let n of t) e.emit("pending", n);
+ }
+}, nA = "bigint,boolean,function,number,string,symbol".split(/,/g);
+function rA(e) {
+ if (e == null || nA.indexOf(typeof e) >= 0 || typeof e.getAddress == "function") return e;
+ if (Array.isArray(e)) return e.map(rA);
+ if (typeof e == "object") return Object.keys(e).reduce((t, n) => (t[n] = e[n], t), {});
+ throw Error(`should not happen: ${e} (${typeof e})`);
+}
+function iA(e) {
+ return new Promise((t) => {
+ setTimeout(t, e);
+ });
+}
+function aA(e) {
+ return e && e.toLowerCase();
+}
+function oA(e) {
+ return e && typeof e.pollingInterval == "number";
+}
+var sA = {
+ polling: !1,
+ staticNetwork: null,
+ batchStallTime: 10,
+ batchMaxSize: 1 << 20,
+ batchMaxCount: 100,
+ cacheTimeout: 250,
+ pollingInterval: 4e3
+}, cA = class extends Zk {
+ address;
+ constructor(e, t) {
+ super(e), t = FC(t), G(this, { address: t });
+ }
+ connect(e) {
+ K(!1, "cannot reconnect JsonRpcSigner", "UNSUPPORTED_OPERATION", { operation: "signer.connect" });
+ }
+ async getAddress() {
+ return this.address;
+ }
+ async populateTransaction(e) {
+ return await this.populateCall(e);
+ }
+ async sendUncheckedTransaction(e) {
+ let t = rA(e), n = [];
+ if (t.from) {
+ let r = t.from;
+ n.push((async () => {
+ let n = await zC(r, this.provider);
+ q(n != null && n.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", e), t.from = n;
+ })());
+ } else t.from = this.address;
+ if (t.gasLimit ?? n.push((async () => {
+ t.gasLimit = await this.provider.estimateGas({
+ ...t,
+ from: this.address
+ });
+ })()), t.to != null) {
+ let e = t.to;
+ n.push((async () => {
+ t.to = await zC(e, this.provider);
+ })());
+ }
+ n.length && await Promise.all(n);
+ let r = this.provider.getRpcTransaction(t);
+ return this.provider.send("eth_sendTransaction", [r]);
+ }
+ async sendTransaction(e) {
+ let t = await this.provider.getBlockNumber(), n = await this.sendUncheckedTransaction(e);
+ return await new Promise((e, r) => {
+ let i = [1e3, 100], a = 0, o = async () => {
+ try {
+ let r = await this.provider.getTransaction(n);
+ if (r != null) {
+ e(r.replaceableTransaction(t));
+ return;
+ }
+ } catch (e) {
+ if (Sv(e, "CANCELLED") || Sv(e, "BAD_DATA") || Sv(e, "NETWORK_ERROR") || Sv(e, "UNSUPPORTED_OPERATION")) {
+ e.info ??= {}, e.info.sendTransactionHash = n, r(e);
+ return;
+ }
+ if (Sv(e, "INVALID_ARGUMENT") && (a++, e.info ??= {}, e.info.sendTransactionHash = n, a > 10)) {
+ r(e);
+ return;
+ }
+ this.provider.emit("error", wv("failed to fetch transation after sending (will try again)", "UNKNOWN_ERROR", { error: e }));
+ }
+ this.provider._setTimeout(() => {
+ o();
+ }, i.pop() || 4e3);
+ };
+ o();
+ });
+ }
+ async signTransaction(e) {
+ let t = rA(e);
+ if (t.from) {
+ let n = await zC(t.from, this.provider);
+ q(n != null && n.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", e), t.from = n;
+ } else t.from = this.address;
+ let n = this.provider.getRpcTransaction(t);
+ return await this.provider.send("eth_signTransaction", [n]);
+ }
+ async signMessage(e) {
+ let t = typeof e == "string" ? uy(e) : e;
+ return await this.provider.send("personal_sign", [Y(t), this.address.toLowerCase()]);
+ }
+ async signTypedData(e, t, n) {
+ let r = rA(n), i = await GE.resolveNames(e, t, r, async (e) => {
+ let t = await zC(e);
+ return q(t != null, "TypedData does not support null address", "value", e), t;
+ });
+ return await this.provider.send("eth_signTypedData_v4", [this.address.toLowerCase(), JSON.stringify(GE.getPayload(i.domain, t, i.value))]);
+ }
+ async unlock(e) {
+ return this.provider.send("personal_unlockAccount", [
+ this.address.toLowerCase(),
+ e,
+ null
+ ]);
+ }
+ async _legacySignMessage(e) {
+ let t = typeof e == "string" ? uy(e) : e;
+ return await this.provider.send("eth_sign", [this.address.toLowerCase(), Y(t)]);
+ }
+}, lA = class extends Bk {
+ #e;
+ #t;
+ #n;
+ #r;
+ #i;
+ #a;
+ #o;
+ #s() {
+ if (this.#r) return;
+ let e = this._getOption("batchMaxCount") === 1 ? 0 : this._getOption("batchStallTime");
+ this.#r = setTimeout(() => {
+ this.#r = null;
+ let e = this.#n;
+ for (this.#n = []; e.length;) {
+ let t = [e.shift()];
+ for (; e.length && t.length !== this.#e.batchMaxCount;) if (t.push(e.shift()), JSON.stringify(t.map((e) => e.payload)).length > this.#e.batchMaxSize) {
+ e.unshift(t.pop());
+ break;
+ }
+ (async () => {
+ let e = t.length === 1 ? t[0].payload : t.map((e) => e.payload);
+ this.emit("debug", {
+ action: "sendRpcPayload",
+ payload: e
+ });
+ try {
+ let n = await this._send(e);
+ this.emit("debug", {
+ action: "receiveRpcResult",
+ result: n
+ });
+ for (let { resolve: e, reject: r, payload: i } of t) {
+ if (this.destroyed) {
+ r(wv("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: i.method }));
+ continue;
+ }
+ let t = n.filter((e) => e.id === i.id)[0];
+ if (t == null) {
+ let e = wv("missing response for request", "BAD_DATA", {
+ value: n,
+ info: { payload: i }
+ });
+ this.emit("error", e), r(e);
+ continue;
+ }
+ if ("error" in t) {
+ r(this.getRpcError(i, t));
+ continue;
+ }
+ e(t.result);
+ }
+ } catch (e) {
+ this.emit("debug", {
+ action: "receiveRpcError",
+ error: e
+ });
+ for (let { reject: n } of t) n(e);
+ }
+ })();
+ }
+ }, e);
+ }
+ constructor(e, t) {
+ super(e, t), this.#t = 1, this.#e = Object.assign({}, sA, t || {}), this.#n = [], this.#r = null, this.#a = null, this.#o = null;
+ {
+ let e = null;
+ this.#i = {
+ promise: new Promise((t) => {
+ e = t;
+ }),
+ resolve: e
+ };
+ }
+ let n = this._getOption("staticNetwork");
+ typeof n == "boolean" ? (q(!n || e !== "any", "staticNetwork cannot be used on special network 'any'", "options", t), n && e != null && (this.#a = vk.from(e))) : n && (q(e == null || n.matches(e), "staticNetwork MUST match network object", "options", t), this.#a = n);
+ }
+ _getOption(e) {
+ return this.#e[e];
+ }
+ get _network() {
+ return K(this.#a, "network is not available yet", "NETWORK_ERROR"), this.#a;
+ }
+ async _perform(e) {
+ if (e.method === "call" || e.method === "estimateGas") {
+ let t = e.transaction;
+ if (t && t.type != null && X(t.type) && t.maxFeePerGas == null && t.maxPriorityFeePerGas == null) {
+ let n = await this.getFeeData();
+ n.maxFeePerGas == null && n.maxPriorityFeePerGas == null && (e = Object.assign({}, e, { transaction: Object.assign({}, t, { type: void 0 }) }));
+ }
+ }
+ let t = this.getRpcRequest(e);
+ return t == null ? super._perform(e) : await this.send(t.method, t.args);
+ }
+ async _detectNetwork() {
+ let e = this._getOption("staticNetwork");
+ if (e) if (e === !0) {
+ if (this.#a) return this.#a;
+ } else return e;
+ return this.#o ? await this.#o : this.ready ? (this.#o = (async () => {
+ try {
+ let e = vk.from(X(await this.send("eth_chainId", [])));
+ return this.#o = null, e;
+ } catch (e) {
+ throw this.#o = null, e;
+ }
+ })(), await this.#o) : (this.#o = (async () => {
+ let e = {
+ id: this.#t++,
+ method: "eth_chainId",
+ params: [],
+ jsonrpc: "2.0"
+ };
+ this.emit("debug", {
+ action: "sendRpcPayload",
+ payload: e
+ });
+ let t;
+ try {
+ t = (await this._send(e))[0], this.#o = null;
+ } catch (e) {
+ throw this.#o = null, this.emit("debug", {
+ action: "receiveRpcError",
+ error: e
+ }), e;
+ }
+ if (this.emit("debug", {
+ action: "receiveRpcResult",
+ result: t
+ }), "result" in t) return vk.from(X(t.result));
+ throw this.getRpcError(e, t);
+ })(), await this.#o);
+ }
+ _start() {
+ this.#i == null || this.#i.resolve == null || (this.#i.resolve(), this.#i = null, (async () => {
+ for (; this.#a == null && !this.destroyed;) try {
+ this.#a = await this._detectNetwork();
+ } catch (e) {
+ if (this.destroyed) break;
+ console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"), this.emit("error", wv("failed to bootstrap network detection", "NETWORK_ERROR", {
+ event: "initial-network-discovery",
+ info: { error: e }
+ })), await iA(1e3);
+ }
+ this.#s();
+ })());
+ }
+ async _waitUntilReady() {
+ if (this.#i != null) return await this.#i.promise;
+ }
+ _getSubscriber(e) {
+ return e.type === "pending" ? new tA(this) : e.type === "event" ? this._getOption("polling") ? new kk(this, e.filter) : new eA(this, e.filter) : e.type === "orphan" && e.filter.orphan === "drop-log" ? new Pk("orphan") : super._getSubscriber(e);
+ }
+ get ready() {
+ return this.#i == null;
+ }
+ getRpcTransaction(e) {
+ let t = {};
+ return [
+ "chainId",
+ "gasLimit",
+ "gasPrice",
+ "type",
+ "maxFeePerGas",
+ "maxPriorityFeePerGas",
+ "nonce",
+ "value"
+ ].forEach((n) => {
+ if (e[n] == null) return;
+ let r = n;
+ n === "gasLimit" && (r = "gas"), t[r] = Qv(X(e[n], `tx.${n}`));
+ }), [
+ "from",
+ "to",
+ "data"
+ ].forEach((n) => {
+ e[n] != null && (t[n] = Y(e[n]));
+ }), e.accessList && (t.accessList = cw(e.accessList)), e.blobVersionedHashes && (t.blobVersionedHashes = e.blobVersionedHashes.map((e) => e.toLowerCase())), e.authorizationList && (t.authorizationList = e.authorizationList.map((e) => {
+ let t = lw(e);
+ return {
+ address: t.address,
+ nonce: Qv(t.nonce),
+ chainId: Qv(t.chainId),
+ yParity: Qv(t.signature.yParity),
+ r: Qv(t.signature.r),
+ s: Qv(t.signature.s)
+ };
+ })), t;
+ }
+ getRpcRequest(e) {
+ switch (e.method) {
+ case "chainId": return {
+ method: "eth_chainId",
+ args: []
+ };
+ case "getBlockNumber": return {
+ method: "eth_blockNumber",
+ args: []
+ };
+ case "getGasPrice": return {
+ method: "eth_gasPrice",
+ args: []
+ };
+ case "getPriorityFee": return {
+ method: "eth_maxPriorityFeePerGas",
+ args: []
+ };
+ case "getBalance": return {
+ method: "eth_getBalance",
+ args: [aA(e.address), e.blockTag]
+ };
+ case "getTransactionCount": return {
+ method: "eth_getTransactionCount",
+ args: [aA(e.address), e.blockTag]
+ };
+ case "getCode": return {
+ method: "eth_getCode",
+ args: [aA(e.address), e.blockTag]
+ };
+ case "getStorage": return {
+ method: "eth_getStorageAt",
+ args: [
+ aA(e.address),
+ "0x" + e.position.toString(16),
+ e.blockTag
+ ]
+ };
+ case "broadcastTransaction": return {
+ method: "eth_sendRawTransaction",
+ args: [e.signedTransaction]
+ };
+ case "getBlock":
+ if ("blockTag" in e) return {
+ method: "eth_getBlockByNumber",
+ args: [e.blockTag, !!e.includeTransactions]
+ };
+ if ("blockHash" in e) return {
+ method: "eth_getBlockByHash",
+ args: [e.blockHash, !!e.includeTransactions]
+ };
+ break;
+ case "getTransaction": return {
+ method: "eth_getTransactionByHash",
+ args: [e.hash]
+ };
+ case "getTransactionReceipt": return {
+ method: "eth_getTransactionReceipt",
+ args: [e.hash]
+ };
+ case "call": return {
+ method: "eth_call",
+ args: [this.getRpcTransaction(e.transaction), e.blockTag]
+ };
+ case "estimateGas": return {
+ method: "eth_estimateGas",
+ args: [this.getRpcTransaction(e.transaction)]
+ };
+ case "getLogs": return e.filter && e.filter.address != null && (Array.isArray(e.filter.address) ? e.filter.address = e.filter.address.map(aA) : e.filter.address = aA(e.filter.address)), {
+ method: "eth_getLogs",
+ args: [e.filter]
+ };
+ }
+ return null;
+ }
+ getRpcError(e, t) {
+ let { method: n } = e, { error: r } = t;
+ if (n === "eth_estimateGas" && r.message) {
+ let t = r.message;
+ if (!t.match(/revert/i) && t.match(/insufficient funds/i)) return wv("insufficient funds", "INSUFFICIENT_FUNDS", {
+ transaction: e.params[0],
+ info: {
+ payload: e,
+ error: r
+ }
+ });
+ if (t.match(/nonce/i) && t.match(/too low/i)) return wv("nonce has already been used", "NONCE_EXPIRED", {
+ transaction: e.params[0],
+ info: {
+ payload: e,
+ error: r
+ }
+ });
+ }
+ if (n === "eth_call" || n === "eth_estimateGas") {
+ let t = fA(r), i = UD.getBuiltinCallException(n === "eth_call" ? "call" : "estimateGas", e.params[0], t ? t.data : null);
+ return i.info = {
+ error: r,
+ payload: e
+ }, i;
+ }
+ let i = JSON.stringify(mA(r));
+ if (typeof r.message == "string" && r.message.match(/user denied|ethers-user-denied/i)) return wv("user rejected action", "ACTION_REJECTED", {
+ action: {
+ eth_sign: "signMessage",
+ personal_sign: "signMessage",
+ eth_signTypedData_v4: "signTypedData",
+ eth_signTransaction: "signTransaction",
+ eth_sendTransaction: "sendTransaction",
+ eth_requestAccounts: "requestAccess",
+ wallet_requestAccounts: "requestAccess"
+ }[n] || "unknown",
+ reason: "rejected",
+ info: {
+ payload: e,
+ error: r
+ }
+ });
+ if (n === "eth_sendRawTransaction" || n === "eth_sendTransaction") {
+ let t = e.params[0];
+ if (i.match(/insufficient funds|base fee exceeds gas limit/i)) return wv("insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", {
+ transaction: t,
+ info: { error: r }
+ });
+ if (i.match(/nonce/i) && i.match(/too low/i)) return wv("nonce has already been used", "NONCE_EXPIRED", {
+ transaction: t,
+ info: { error: r }
+ });
+ if (i.match(/replacement transaction/i) && i.match(/underpriced/i)) return wv("replacement fee too low", "REPLACEMENT_UNDERPRICED", {
+ transaction: t,
+ info: { error: r }
+ });
+ if (i.match(/only replay-protected/i)) return wv("legacy pre-eip-155 transactions not supported", "UNSUPPORTED_OPERATION", {
+ operation: n,
+ info: {
+ transaction: t,
+ info: { error: r }
+ }
+ });
+ }
+ let a = !!i.match(/the method .* does not exist/i);
+ return a || r && r.details && r.details.startsWith("Unauthorized method:") && (a = !0), a ? wv("unsupported operation", "UNSUPPORTED_OPERATION", {
+ operation: e.method,
+ info: {
+ error: r,
+ payload: e
+ }
+ }) : wv("could not coalesce error", "UNKNOWN_ERROR", {
+ error: r,
+ payload: e
+ });
+ }
+ send(e, t) {
+ if (this.destroyed) return Promise.reject(wv("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: e }));
+ let n = this.#t++, r = new Promise((r, i) => {
+ this.#n.push({
+ resolve: r,
+ reject: i,
+ payload: {
+ method: e,
+ params: t,
+ id: n,
+ jsonrpc: "2.0"
+ }
+ });
+ });
+ return this.#s(), r;
+ }
+ async getSigner(e) {
+ e ??= 0;
+ let t = this.send("eth_accounts", []);
+ if (typeof e == "number") {
+ let n = await t;
+ if (e >= n.length) throw Error("no such account");
+ return new cA(this, n[e]);
+ }
+ let { accounts: n } = await bv({
+ network: this.getNetwork(),
+ accounts: t
+ });
+ e = FC(e);
+ for (let t of n) if (FC(t) === e) return new cA(this, e);
+ throw Error("invalid account");
+ }
+ async listAccounts() {
+ return (await this.send("eth_accounts", [])).map((e) => new cA(this, e));
+ }
+ destroy() {
+ this.#r &&= (clearTimeout(this.#r), null);
+ for (let { payload: e, reject: t } of this.#n) t(wv("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: e.method }));
+ this.#n = [], super.destroy();
+ }
+}, uA = class extends lA {
+ #e;
+ constructor(e, t) {
+ super(e, t);
+ let n = this._getOption("pollingInterval");
+ n ??= sA.pollingInterval, this.#e = n;
+ }
+ _getSubscriber(e) {
+ let t = super._getSubscriber(e);
+ return oA(t) && (t.pollingInterval = this.#e), t;
+ }
+ get pollingInterval() {
+ return this.#e;
+ }
+ set pollingInterval(e) {
+ if (!Number.isInteger(e) || e < 0) throw Error("invalid interval");
+ this.#e = e, this._forEachSubscriber((e) => {
+ oA(e) && (e.pollingInterval = this.#e);
+ });
+ }
+}, dA = class extends uA {
+ #e;
+ constructor(e, t, n) {
+ e ??= "http://localhost:8545", super(t, n), typeof e == "string" ? this.#e = new Ey(e) : this.#e = e.clone();
+ }
+ _getConnection() {
+ return this.#e.clone();
+ }
+ async send(e, t) {
+ return await this._start(), await super.send(e, t);
+ }
+ async _send(e) {
+ let t = this._getConnection();
+ t.body = JSON.stringify(e), t.setHeader("content-type", "application/json");
+ let n = await t.send();
+ n.assertOk();
+ let r = n.bodyJson;
+ return Array.isArray(r) || (r = [r]), r;
+ }
+};
+function fA(e) {
+ if (e == null) return null;
+ if (typeof e.message == "string" && e.message.match(/revert/i) && jv(e.data)) return {
+ message: e.message,
+ data: e.data
+ };
+ if (typeof e == "object") {
+ for (let t in e) {
+ let n = fA(e[t]);
+ if (n) return n;
+ }
+ return null;
+ }
+ if (typeof e == "string") try {
+ return fA(JSON.parse(e));
+ } catch {}
+ return null;
+}
+function pA(e, t) {
+ if (e != null) {
+ if (typeof e.message == "string" && t.push(e.message), typeof e == "object") for (let n in e) pA(e[n], t);
+ if (typeof e == "string") try {
+ return pA(JSON.parse(e), t);
+ } catch {}
+ }
+}
+function mA(e) {
+ let t = [];
+ return pA(e, t), t;
+}
+//#endregion
+//#region src/erc8004/abi.js
+var hA = [
+ "function register(string agentURI) external returns (uint256 agentId)",
+ "function register(string agentURI, tuple(string metadataKey, bytes metadataValue)[] metadata) external returns (uint256 agentId)",
+ "function register() external returns (uint256 agentId)",
+ "function setAgentURI(uint256 agentId, string newURI) external",
+ "function tokenURI(uint256 agentId) external view returns (string)",
+ "function setAgentWallet(uint256 agentId, address newWallet, uint256 deadline, bytes signature) external",
+ "function getAgentWallet(uint256 agentId) external view returns (address)",
+ "function unsetAgentWallet(uint256 agentId) external",
+ "function nonces(address owner) external view returns (uint256)",
+ "function DOMAIN_SEPARATOR() external view returns (bytes32)",
+ "function getMetadata(uint256 agentId, string metadataKey) external view returns (bytes)",
+ "function setMetadata(uint256 agentId, string metadataKey, bytes metadataValue) external",
+ "function ownerOf(uint256 tokenId) external view returns (address)",
+ "function balanceOf(address owner) external view returns (uint256)",
+ "function totalSupply() external view returns (uint256)",
+ "function isAgent(uint256 agentId) external view returns (bool)",
+ "event Registered(uint256 indexed agentId, string agentURI, address indexed owner)",
+ "event URIUpdated(uint256 indexed agentId, string newURI, address indexed updatedBy)",
+ "event WalletSet(uint256 indexed agentId, address indexed wallet)",
+ "event WalletUnset(uint256 indexed agentId)",
+ "event MetadataSet(uint256 indexed agentId, string indexed indexedMetadataKey, string metadataKey, bytes metadataValue)",
+ "event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)"
+], gA = {
+ 8453: {
+ identityRegistry: "",
+ reputationRegistry: "",
+ validationRegistry: ""
+ },
+ 84532: {
+ identityRegistry: "",
+ reputationRegistry: "",
+ validationRegistry: ""
+ },
+ 1: {
+ identityRegistry: "",
+ reputationRegistry: "",
+ validationRegistry: ""
+ }
+}, _A = {
+ base: 8453,
+ "base-mainnet": 8453,
+ "base-sepolia": 84532,
+ ethereum: 1,
+ mainnet: 1
+}, vA = {
+ 8453: "https://mainnet.base.org",
+ 84532: "https://sepolia.base.org",
+ 1: "https://eth.llamarpc.com"
+};
+async function yA(e, { rpcURL: t, registry: n } = {}) {
+ if (!e) throw Error("loadManifest: source required");
+ if (e.startsWith("agent://")) return bA(e, {
+ rpcURL: t,
+ registryOverride: n
+ });
+ if (e.startsWith("ipfs://") || e.startsWith("ar://")) {
+ let t = sv(e);
+ return SA(await xA(t), { baseURI: CA(t) });
+ }
+ if (e.startsWith("http")) return SA(await xA(e), { baseURI: CA(e) });
+ throw Error(`Unsupported manifest source: ${e}`);
+}
+async function bA(e, { rpcURL: t, registryOverride: n }) {
+ let r = e.match(/^agent:\/\/([^/]+)\/(\d+)$/);
+ if (!r) throw Error(`Malformed agent URI: ${e}`);
+ let [, i, a] = r, o = _A[i.toLowerCase()] || Number(i);
+ if (!o) throw Error(`Unknown chain: ${i}`);
+ let s = gA[o], c = n || s?.identityRegistry;
+ if (!c) throw Error(`No registry deployed on chain ${o}. Pass registry= override.`);
+ let l = new WO(c, hA, new dA(t || vA[o])), u = BigInt(a), d = await l.tokenURI(u);
+ if (!d) throw Error(`Agent ${a} on chain ${o} has no URI`);
+ let f = sv(d), p = SA(await xA(f), { baseURI: CA(f) });
+ return p.id = {
+ ...p.id,
+ chain: i,
+ chainId: o,
+ registry: c,
+ agentId: a
+ }, p;
+}
+async function xA(e) {
+ let t;
+ try {
+ t = await fetch(e);
+ } catch {
+ t = await cv(e);
+ }
+ if (!t.ok) throw Error(`Manifest fetch failed: ${e} (${t.status})`);
+ return t.json();
+}
+function SA(e, { baseURI: t = "" } = {}) {
+ if (e.spec && e.spec.startsWith("agent-manifest/")) {
+ let n = {
+ ...e,
+ _baseURI: t
+ };
+ return n.body = n.body || {}, !n.body.uri && n.image && (n.body.uri = n.image), n;
+ }
+ return e.type && e.type.includes("eip-8004") ? {
+ spec: "agent-manifest/0.1",
+ _baseURI: t,
+ _source: "erc8004-registration",
+ id: { agentId: (e.registrations?.[0] || {}).agentId?.toString() },
+ name: e.name,
+ description: e.description,
+ image: e.image,
+ body: {
+ uri: e.image,
+ format: "gltf-binary"
+ },
+ brain: { provider: "none" },
+ voice: {
+ tts: { provider: "browser" },
+ stt: { provider: "browser" }
+ },
+ skills: [],
+ memory: { mode: "local" },
+ tools: [
+ "wave",
+ "lookAt",
+ "play_clip",
+ "setExpression"
+ ],
+ version: "0.1.0"
+ } : {
+ spec: "agent-manifest/0.1",
+ _baseURI: t,
+ name: e.name || "Unnamed agent",
+ description: e.description || "",
+ body: {
+ uri: e.body?.uri || e.image || e.model || "",
+ format: e.body?.format || "gltf-binary"
+ },
+ brain: e.brain || { provider: "none" },
+ voice: e.voice || {
+ tts: { provider: "browser" },
+ stt: { provider: "browser" }
+ },
+ skills: e.skills || [],
+ memory: e.memory || { mode: "local" },
+ tools: e.tools || [
+ "wave",
+ "lookAt",
+ "play_clip",
+ "setExpression"
+ ],
+ version: e.version || "0.1.0"
+ };
+}
+function CA(e) {
+ let t = e.lastIndexOf("/");
+ return t >= 0 ? e.slice(0, t + 1) : e;
+}
+async function wA(e, t) {
+ if (!e._baseURI) return null;
+ try {
+ let n = new URL(t, e._baseURI).href, r = await fetch(n);
+ return r.ok ? r.text() : null;
+ } catch {
+ return null;
+ }
+}
+//#endregion
+//#region src/element.js
+var TA = [
+ "inline",
+ "floating",
+ "section",
+ "fullscreen"
+], EA = "\n :host {\n display: block;\n position: relative;\n width: 100%;\n height: 480px;\n --agent-bubble-radius: 16px;\n --agent-accent: #3b82f6;\n --agent-surface: rgba(17, 24, 39, 0.92);\n --agent-on-surface: #f9fafb;\n --agent-chat-font: system-ui, -apple-system, sans-serif;\n --agent-mic-glow: #22c55e;\n --agent-shadow: 0 20px 60px rgba(0,0,0,0.3);\n contain: layout style;\n }\n :host([mode=\"floating\"]) {\n position: fixed;\n z-index: 2147483000;\n width: var(--agent-width, 320px);\n height: var(--agent-height, 420px);\n border-radius: var(--agent-bubble-radius);\n overflow: hidden;\n box-shadow: var(--agent-shadow);\n }\n :host([mode=\"fullscreen\"]) {\n position: fixed;\n inset: 0;\n width: 100vw;\n height: 100vh;\n z-index: 2147483000;\n }\n :host([hidden]) { display: none; }\n .stage {\n position: absolute;\n inset: 0;\n width: 100%;\n height: 100%;\n }\n .stage canvas { display: block; }\n .chrome {\n position: absolute;\n left: 12px;\n right: 12px;\n bottom: 12px;\n display: flex;\n gap: 8px;\n align-items: flex-end;\n pointer-events: none;\n }\n .chrome > * { pointer-events: auto; }\n .chat {\n flex: 1;\n max-height: 40%;\n overflow-y: auto;\n background: var(--agent-surface);\n color: var(--agent-on-surface);\n font: 14px/1.4 var(--agent-chat-font);\n border-radius: 12px;\n padding: 10px 12px;\n backdrop-filter: blur(12px);\n }\n .chat:empty { display: none; }\n .msg { margin: 4px 0; }\n .msg .role { opacity: 0.55; font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; }\n .input-row {\n display: flex;\n gap: 6px;\n background: var(--agent-surface);\n border-radius: 999px;\n padding: 4px 4px 4px 14px;\n backdrop-filter: blur(12px);\n flex: 1;\n }\n .input-row input {\n flex: 1;\n background: transparent;\n border: 0;\n color: var(--agent-on-surface);\n font: 14px var(--agent-chat-font);\n outline: none;\n }\n button.icon {\n width: 36px;\n height: 36px;\n border-radius: 50%;\n border: 0;\n background: var(--agent-accent);\n color: white;\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n }\n button.icon.mic[data-listening=\"true\"] { box-shadow: 0 0 0 4px var(--agent-mic-glow); }\n .poster {\n position: absolute;\n inset: 0;\n background-size: contain;\n background-position: center;\n background-repeat: no-repeat;\n transition: opacity 0.4s;\n pointer-events: none;\n }\n .loading {\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translate(-50%, -50%);\n color: var(--agent-on-surface);\n font: 14px var(--agent-chat-font);\n background: var(--agent-surface);\n padding: 8px 14px;\n border-radius: 999px;\n }\n .error {\n position: absolute;\n inset: 16px;\n display: grid;\n place-items: center;\n color: var(--agent-on-surface);\n background: var(--agent-surface);\n border-radius: 12px;\n padding: 16px;\n font: 14px var(--agent-chat-font);\n }\n", DA = class extends HTMLElement {
+ static get observedAttributes() {
+ return [
+ "src",
+ "manifest",
+ "body",
+ "mode",
+ "position",
+ "width",
+ "height",
+ "voice",
+ "api-key",
+ "key-proxy"
+ ];
+ }
+ constructor() {
+ super(), this.attachShadow({ mode: "open" }), this._viewer = null, this._scene = null, this._runtime = null, this._memory = null, this._skills = null, this._manifest = null, this._mounted = !1, this._booting = !1, this._listening = !1;
+ }
+ connectedCallback() {
+ this._renderShell(), this._applyLayout(), this._observeViewport(), this.hasAttribute("eager") && this._boot();
+ }
+ disconnectedCallback() {
+ this._teardown();
+ }
+ attributeChangedCallback(e, t, n) {
+ this._mounted && ([
+ "mode",
+ "position",
+ "width",
+ "height"
+ ].includes(e) && this._applyLayout(), [
+ "src",
+ "manifest",
+ "body"
+ ].includes(e) && (this._teardown(), this._boot()));
+ }
+ _renderShell() {
+ let e = document.createElement("style");
+ e.textContent = EA, this.shadowRoot.appendChild(e);
+ let t = document.createElement("div");
+ t.className = "stage", t.part = "stage", this.shadowRoot.appendChild(t), this._stageEl = t;
+ let n = document.createElement("div");
+ n.className = "poster", this.getAttribute("poster") && (n.style.backgroundImage = `url(${this.getAttribute("poster")})`), this.shadowRoot.appendChild(n), this._posterEl = n;
+ let r = document.createElement("div");
+ if (r.className = "loading", r.textContent = "Loading...", r.hidden = !0, this.shadowRoot.appendChild(r), this._loadingEl = r, !this.hasAttribute("kiosk")) {
+ let e = document.createElement("div");
+ e.className = "chrome", e.part = "chrome";
+ let t = document.createElement("div");
+ t.className = "chat", t.part = "chat";
+ let n = document.createElement("div");
+ n.className = "input-row";
+ let r = document.createElement("input");
+ r.type = "text", r.placeholder = "Say something...", r.addEventListener("keydown", (e) => {
+ if (e.key === "Enter" && r.value.trim()) {
+ let e = r.value.trim();
+ r.value = "", this.say(e);
+ }
+ });
+ let i = document.createElement("button");
+ i.className = "icon mic", i.title = "Push to talk", i.innerHTML = "🎙", i.addEventListener("click", () => this._toggleMic()), n.appendChild(r), n.appendChild(i), e.appendChild(t), e.appendChild(n), this.shadowRoot.appendChild(e), this._chatEl = t, this._inputEl = r, this._micEl = i;
+ }
+ }
+ _applyLayout() {
+ let e = this.getAttribute("mode") || "inline";
+ if (!TA.includes(e)) return;
+ if (e === "floating") {
+ let e = this.getAttribute("position") || "bottom-right", t = (this.getAttribute("offset") || "24px 24px").split(/\s+/), [n, r] = [t[0], t[1] || t[0]];
+ this.style.top = this.style.bottom = this.style.left = this.style.right = "", e.includes("top") ? this.style.top = n : this.style.bottom = n, e.includes("left") ? this.style.left = r : e.includes("right") ? this.style.right = r : e.includes("center") && (this.style.left = "50%", this.style.transform = "translateX(-50%)");
+ } else this.style.top = this.style.bottom = this.style.left = this.style.right = this.style.transform = "";
+ let t = this.getAttribute("width"), n = this.getAttribute("height");
+ t && this.style.setProperty("--agent-width", t), n && this.style.setProperty("--agent-height", n), e === "inline" && (t && (this.style.width = t), n && (this.style.height = n));
+ }
+ _observeViewport() {
+ if (!this.hasAttribute("eager")) {
+ if (typeof IntersectionObserver > "u") {
+ this._boot();
+ return;
+ }
+ this._io = new IntersectionObserver((e) => {
+ e.some((e) => e.isIntersecting) && (this._io.disconnect(), this._boot());
+ }), this._io.observe(this);
+ }
+ }
+ async _boot() {
+ if (!(this._booting || this._mounted)) {
+ this._booting = !0;
+ try {
+ this._loadingEl.hidden = !1, this.dispatchEvent(new CustomEvent("agent:load-progress", { detail: {
+ phase: "manifest",
+ pct: .1
+ } }));
+ let e = await this._resolveManifest();
+ if (this._manifest = e, this.dispatchEvent(new CustomEvent("agent:load-progress", { detail: {
+ phase: "manifest",
+ pct: .3
+ } })), typeof e.brain?.instructions == "string" && e.brain.instructions.endsWith(".md")) {
+ let t = await wA(e, e.brain.instructions);
+ t && (e.instructions = OA(t));
+ } else e.brain?.instructions && (e.instructions = e.brain.instructions);
+ this.dispatchEvent(new CustomEvent("agent:load-progress", { detail: {
+ phase: "body",
+ pct: .45
+ } }));
+ let t = new q_(this._stageEl, { kiosk: this.hasAttribute("kiosk") });
+ this._viewer = t;
+ let n = sv(e.body?.uri);
+ n && await t.load(n, "", /* @__PURE__ */ new Map()), this._scene = new uv(t), this.dispatchEvent(new CustomEvent("agent:load-progress", { detail: {
+ phase: "memory",
+ pct: .6
+ } }));
+ let r = e.id?.agentId || this.getAttribute("memory-key") || e.name || "anon";
+ this._memory = await _v.load({
+ mode: this.getAttribute("memory") || e.memory?.mode || "local",
+ namespace: r,
+ manifestURI: e._baseURI + "manifest.json",
+ fetchFn: fetch.bind(globalThis)
+ }), this.dispatchEvent(new CustomEvent("agent:load-progress", { detail: {
+ phase: "skills",
+ pct: .75
+ } })), this._skills = new pv({
+ trust: this.getAttribute("skill-trust") || "owned-only",
+ ownerAddress: e.id?.owner
+ });
+ let i = e.skills || [];
+ for (let t of i) try {
+ let n = await this._skills.install(t, { bundleBase: e._baseURI });
+ this.dispatchEvent(new CustomEvent("skill:loaded", { detail: {
+ name: n.name,
+ uri: n.uri
+ } }));
+ } catch (e) {
+ console.warn("[agent-3d] skill load failed", t, e);
+ }
+ this.dispatchEvent(new CustomEvent("agent:load-progress", { detail: {
+ phase: "brain",
+ pct: .9
+ } }));
+ let a = {
+ apiKey: this.getAttribute("api-key") || void 0,
+ proxyURL: this.getAttribute("key-proxy") || void 0
+ };
+ this._runtime = new iv({
+ manifest: e,
+ viewer: this._scene,
+ memory: this._memory,
+ skills: this._skills,
+ providerConfig: a
+ });
+ for (let e of [
+ "brain:thinking",
+ "brain:message",
+ "skill:tool-called",
+ "voice:speech-start",
+ "voice:speech-end",
+ "voice:transcript",
+ "voice:listen-start",
+ "memory:write"
+ ]) this._runtime.addEventListener(e, (t) => {
+ this.dispatchEvent(new CustomEvent(e, {
+ detail: t.detail,
+ bubbles: !0,
+ composed: !0
+ })), e === "brain:message" && this._chatEl && this._renderMessage(t.detail);
+ });
+ this._mounted = !0, this._loadingEl.hidden = !0, this._posterEl.style.opacity = "0", this.dispatchEvent(new CustomEvent("agent:ready", {
+ detail: {
+ agent: this,
+ manifest: e
+ },
+ bubbles: !0,
+ composed: !0
+ }));
+ } catch (e) {
+ console.error("[agent-3d] boot failed", e), this._loadingEl.hidden = !0, this._showError(e), this.dispatchEvent(new CustomEvent("agent:error", {
+ detail: {
+ phase: "boot",
+ error: e
+ },
+ bubbles: !0,
+ composed: !0
+ }));
+ } finally {
+ this._booting = !1;
+ }
+ }
+ }
+ async _resolveManifest() {
+ let e = this.getAttribute("src"), t = this.getAttribute("manifest"), n = this.getAttribute("body");
+ if (e) return yA(e, {
+ rpcURL: this.getAttribute("rpc-url"),
+ registry: this.getAttribute("registry")
+ });
+ if (t) return yA(t);
+ if (n) {
+ let e = this.getAttribute("instructions");
+ return {
+ spec: "agent-manifest/0.1",
+ _baseURI: "",
+ name: this.getAttribute("name") || "Agent",
+ body: {
+ uri: n,
+ format: "gltf-binary"
+ },
+ brain: {
+ provider: this.getAttribute("brain") ? "anthropic" : "none",
+ model: this.getAttribute("brain") || void 0,
+ instructions: e || "You are an embodied 3D agent."
+ },
+ instructions: e || "You are an embodied 3D agent.",
+ voice: {
+ tts: { provider: "browser" },
+ stt: { provider: "browser" }
+ },
+ skills: (this.getAttribute("skills") || "").split(",").map((e) => e.trim()).filter(Boolean).map((e) => ({ uri: e })),
+ memory: { mode: this.getAttribute("memory") || "local" },
+ tools: [
+ "wave",
+ "lookAt",
+ "play_clip",
+ "setExpression",
+ "speak",
+ "remember"
+ ],
+ version: "0.1.0"
+ };
+ }
+ throw Error("<agent-3d> requires src=, manifest=, or body= attribute");
+ }
+ _renderMessage({ role: e, content: t }) {
+ if (!this._chatEl || !t) return;
+ let n = document.createElement("div");
+ n.className = "msg", n.innerHTML = `<div class="role">${e}</div><div class="body"></div>`, n.querySelector(".body").textContent = t, this._chatEl.appendChild(n), this._chatEl.scrollTop = this._chatEl.scrollHeight;
+ }
+ _showError(e) {
+ let t = document.createElement("div");
+ t.className = "error", t.textContent = `Couldn't load agent: ${e.message || e}`, this.shadowRoot.appendChild(t);
+ }
+ async _toggleMic() {
+ if (this._runtime) {
+ if (this._listening) {
+ this._runtime.stt?.stop(), this._listening = !1, this._micEl.dataset.listening = "false";
+ return;
+ }
+ this._listening = !0, this._micEl.dataset.listening = "true";
+ try {
+ let e = await this._runtime.listen();
+ e && await this.say(e, { voice: !0 });
+ } catch (e) {
+ console.warn("[agent-3d] listen failed", e);
+ } finally {
+ this._listening = !1, this._micEl.dataset.listening = "false";
+ }
+ }
+ }
+ _teardown() {
+ try {
+ this._io?.disconnect();
+ } catch {}
+ try {
+ this._runtime?.destroy();
+ } catch {}
+ try {
+ this._viewer?.dispose?.();
+ } catch {}
+ this._mounted = !1, this._runtime = this._viewer = this._scene = this._memory = this._skills = null;
+ }
+ async say(e, t = {}) {
+ return this._runtime || await this._waitForReady(), this._runtime.send(e, { voice: t.voice ?? this.hasAttribute("voice") });
+ }
+ async ask(e, t = {}) {
+ return (await this.say(e, t))?.text || "";
+ }
+ clearConversation() {
+ this._runtime?.clearConversation();
+ }
+ async wave(e) {
+ return this._scene?.playAnimationByHint("wave", e);
+ }
+ async lookAt(e) {
+ return this._scene?.lookAt(e);
+ }
+ async play(e, t) {
+ return this._scene?.playClipByName(e, t);
+ }
+ async installSkill(e) {
+ if (!this._skills) throw Error("Agent not mounted");
+ return this._skills.install({ uri: e });
+ }
+ uninstallSkill(e) {
+ return this._skills?.uninstall(e);
+ }
+ get skills() {
+ return this._skills?.all() || [];
+ }
+ get memory() {
+ return this._memory;
+ }
+ get manifest() {
+ return this._manifest;
+ }
+ get runtime() {
+ return this._runtime;
+ }
+ setMode(e) {
+ this.setAttribute("mode", e);
+ }
+ setPosition(e, t) {
+ this.setAttribute("position", e), t && this.setAttribute("offset", t);
+ }
+ setSize(e, t) {
+ this.setAttribute("width", e), this.setAttribute("height", t);
+ }
+ pause() {
+ this._runtime?.pause();
+ }
+ resume() {}
+ destroy() {
+ this._teardown();
+ }
+ _waitForReady() {
+ return this._mounted ? Promise.resolve() : new Promise((e) => {
+ let t = () => {
+ this.removeEventListener("agent:ready", t), e();
+ };
+ this.addEventListener("agent:ready", t), this._booting || this._boot();
+ });
+ }
+};
+function OA(e) {
+ let t = e.match(/^---\n[\s\S]*?\n---\n?([\s\S]*)$/);
+ return t ? t[1] : e;
+}
+customElements.get("agent-3d") || customElements.define("agent-3d", DA);
+//#endregion
+//#region src/lib.js
+var kA = (e = "agent-3d") => {
+ customElements.get(e) || customElements.define(e, DA);
+};
+//#endregion
+export { DA as Agent3DElement, _v as Memory, iv as Runtime, uv as SceneController, fv as Skill, pv as SkillRegistry, q_ as Viewer, kA as defineElement, wA as fetchRelative, cv as fetchWithFallback, yA as loadManifest, SA as normalize, sv as resolveURI };
diff --git a/dist-lib/agent-3d.umd.cjs b/dist-lib/agent-3d.umd.cjs
new file mode 100644
index 000000000..c07d58960
--- /dev/null
+++ b/dist-lib/agent-3d.umd.cjs
@@ -0,0 +1,3981 @@
+(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.Agent3D={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.defineProperty,n=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},r={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},i={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},a=`attached`,o=1e3,s=1001,c=1002,l=1003,u=1004,d=1005,f=1006,p=1007,m=1008,h=1009,g=1010,_=1011,v=1012,y=1013,b=1014,x=1015,S=1016,C=1017,w=1018,T=1020,E=35902,D=1021,O=1022,k=1023,ee=1026,te=1027,ne=1028,re=1029,A=1030,ie=1031,ae=1033,oe=33776,se=33777,ce=33778,le=33779,ue=35840,de=35841,fe=35842,pe=35843,me=36196,he=37492,ge=37496,_e=37808,ve=37809,ye=37810,be=37811,j=37812,xe=37813,Se=37814,Ce=37815,M=37816,we=37817,N=37818,P=37819,Te=37820,Ee=37821,F=36492,De=36494,Oe=36495,ke=36283,Ae=36284,je=36285,Me=36286,Ne=2200,Pe=2201,Fe=2202,Ie=2300,Le=2301,Re=2302,ze=2400,Be=2401,Ve=2402,He=2500,Ue=2501,We=3200,Ge=3201,Ke=`srgb`,qe=`srgb-linear`,Je=`linear`,Ye=`srgb`,Xe=7680,Ze=35044,Qe=2e3,$e=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let t=n.slice(0);for(let n=0,r=t.length;n<r;n++)t[n].call(this,e);e.target=null}}},et=`00.01.02.03.04.05.06.07.08.09.0a.0b.0c.0d.0e.0f.10.11.12.13.14.15.16.17.18.19.1a.1b.1c.1d.1e.1f.20.21.22.23.24.25.26.27.28.29.2a.2b.2c.2d.2e.2f.30.31.32.33.34.35.36.37.38.39.3a.3b.3c.3d.3e.3f.40.41.42.43.44.45.46.47.48.49.4a.4b.4c.4d.4e.4f.50.51.52.53.54.55.56.57.58.59.5a.5b.5c.5d.5e.5f.60.61.62.63.64.65.66.67.68.69.6a.6b.6c.6d.6e.6f.70.71.72.73.74.75.76.77.78.79.7a.7b.7c.7d.7e.7f.80.81.82.83.84.85.86.87.88.89.8a.8b.8c.8d.8e.8f.90.91.92.93.94.95.96.97.98.99.9a.9b.9c.9d.9e.9f.a0.a1.a2.a3.a4.a5.a6.a7.a8.a9.aa.ab.ac.ad.ae.af.b0.b1.b2.b3.b4.b5.b6.b7.b8.b9.ba.bb.bc.bd.be.bf.c0.c1.c2.c3.c4.c5.c6.c7.c8.c9.ca.cb.cc.cd.ce.cf.d0.d1.d2.d3.d4.d5.d6.d7.d8.d9.da.db.dc.dd.de.df.e0.e1.e2.e3.e4.e5.e6.e7.e8.e9.ea.eb.ec.ed.ee.ef.f0.f1.f2.f3.f4.f5.f6.f7.f8.f9.fa.fb.fc.fd.fe.ff`.split(`.`),tt=1234567,nt=Math.PI/180,rt=180/Math.PI;function it(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(et[e&255]+et[e>>8&255]+et[e>>16&255]+et[e>>24&255]+`-`+et[t&255]+et[t>>8&255]+`-`+et[t>>16&15|64]+et[t>>24&255]+`-`+et[n&63|128]+et[n>>8&255]+`-`+et[n>>16&255]+et[n>>24&255]+et[r&255]+et[r>>8&255]+et[r>>16&255]+et[r>>24&255]).toLowerCase()}function I(e,t,n){return Math.max(t,Math.min(n,e))}function at(e,t){return(e%t+t)%t}function ot(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)}function st(e,t,n){return e===t?0:(n-e)/(t-e)}function ct(e,t,n){return(1-n)*e+n*t}function lt(e,t,n,r){return ct(e,t,1-Math.exp(-n*r))}function ut(e,t=1){return t-Math.abs(at(e,t*2)-t)}function dt(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*(3-2*e))}function ft(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10))}function pt(e,t){return e+Math.floor(Math.random()*(t-e+1))}function mt(e,t){return e+Math.random()*(t-e)}function ht(e){return e*(.5-Math.random())}function gt(e){e!==void 0&&(tt=e);let t=tt+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function _t(e){return e*nt}function vt(e){return e*rt}function yt(e){return(e&e-1)==0&&e!==0}function bt(e){return 2**Math.ceil(Math.log(e)/Math.LN2)}function xt(e){return 2**Math.floor(Math.log(e)/Math.LN2)}function St(e,t,n,r,i){let a=Math.cos,o=Math.sin,s=a(n/2),c=o(n/2),l=a((t+r)/2),u=o((t+r)/2),d=a((t-r)/2),f=o((t-r)/2),p=a((r-t)/2),m=o((r-t)/2);switch(i){case`XYX`:e.set(s*u,c*d,c*f,s*l);break;case`YZY`:e.set(c*f,s*u,c*d,s*l);break;case`ZXZ`:e.set(c*d,c*f,s*u,s*l);break;case`XZX`:e.set(s*u,c*m,c*p,s*l);break;case`YXY`:e.set(c*p,s*u,c*m,s*l);break;case`ZYZ`:e.set(c*m,c*p,s*u,s*l);break;default:console.warn(`THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: `+i)}}function Ct(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`Invalid component type.`)}}function wt(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`Invalid component type.`)}}var Tt={DEG2RAD:nt,RAD2DEG:rt,generateUUID:it,clamp:I,euclideanModulo:at,mapLinear:ot,inverseLerp:st,lerp:ct,damp:lt,pingpong:ut,smoothstep:dt,smootherstep:ft,randInt:pt,randFloat:mt,randFloatSpread:ht,seededRandom:gt,degToRad:_t,radToDeg:vt,isPowerOfTwo:yt,ceilPowerOfTwo:bt,floorPowerOfTwo:xt,setQuaternionFromProperEuler:St,normalize:wt,denormalize:Ct},L=class e{constructor(t=0,n=0){e.prototype.isVector2=!0,this.x=t,this.y=n}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=I(this.x,e.x,t.x),this.y=I(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=I(this.x,e,t),this.y=I(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(I(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(I(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},Et=class e{constructor(t,n,r,i,a,o,s,c,l){e.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,n,r,i,a,o,s,c,l)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(Dt.makeScale(e,t)),this}rotate(e){return this.premultiply(Dt.makeRotation(-e)),this}translate(e,t){return this.premultiply(Dt.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},Dt=new Et;function Ot(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function kt(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function At(){let e=kt(`canvas`);return e.style.display=`block`,e}var jt={};function Mt(e){e in jt||(jt[e]=!0,console.warn(e))}function Nt(e,t,n){return new Promise(function(r,i){function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:r()}}setTimeout(a,n)})}function Pt(e){let t=e.elements;t[2]=.5*t[2]+.5*t[3],t[6]=.5*t[6]+.5*t[7],t[10]=.5*t[10]+.5*t[11],t[14]=.5*t[14]+.5*t[15]}function Ft(e){let t=e.elements;t[11]===-1?(t[10]=-t[10]-1,t[14]=-t[14]):(t[10]=-t[10],t[14]=-t[14]+1)}var It=new Et().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Lt=new Et().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Rt(){let e={enabled:!0,workingColorSpace:qe,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=Bt(e.r),e.g=Bt(e.g),e.b=Bt(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===`srgb`&&(e.r=Vt(e.r),e.g=Vt(e.g),e.b=Vt(e.b)),e)},fromWorkingColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},toWorkingColorSpace:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===``?Je:this.spaces[e].transfer},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[qe]:{primaries:t,whitePoint:r,transfer:Je,toXYZ:It,fromXYZ:Lt,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:Ke},outputColorSpaceConfig:{drawingBufferColorSpace:Ke}},[Ke]:{primaries:t,whitePoint:r,transfer:Ye,toXYZ:It,fromXYZ:Lt,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:Ke}}}),e}var zt=Rt();function Bt(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function Vt(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var Ht,Ut=class{static getDataURL(e,t=`image/png`){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>`u`)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Ht===void 0&&(Ht=kt(`canvas`)),Ht.width=e.width,Ht.height=e.height;let t=Ht.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=Ht}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap){let t=kt(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e<i.length;e++)i[e]=Bt(i[e]/255)*255;return n.putImageData(r,0,0),t}else if(e.data){let t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(Bt(t[e]/255)*255):t[e]=Bt(t[e]);return{data:t,width:e.width,height:e.height}}else return console.warn(`THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.`),e}},Wt=0,Gt=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,`id`,{value:Wt++}),this.uuid=it(),this.data=e,this.dataReady=!0,this.version=0}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:``},r=this.data;if(r!==null){let e;if(Array.isArray(r)){e=[];for(let t=0,n=r.length;t<n;t++)r[t].isDataTexture?e.push(Kt(r[t].image)):e.push(Kt(r[t]))}else e=Kt(r);n.url=e}return t||(e.images[this.uuid]=n),n}};function Kt(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?Ut.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(console.warn(`THREE.Texture: Unable to serialize Texture.`),{})}var qt=0,Jt=class e extends $e{constructor(t=e.DEFAULT_IMAGE,n=e.DEFAULT_MAPPING,r=s,i=s,a=f,o=m,c=k,l=h,u=e.DEFAULT_ANISOTROPY,d=``){super(),this.isTexture=!0,Object.defineProperty(this,`id`,{value:qt++}),this.uuid=it(),this.name=``,this.source=new Gt(t),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=r,this.wrapT=i,this.magFilter=a,this.minFilter=o,this.anisotropy=u,this.format=c,this.internalFormat=null,this.type=l,this.offset=new L(0,0),this.repeat=new L(1,1),this.center=new L(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Et,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=d,this.userData={},this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isTextureArray=!1,this.pmremVersion=0}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isTextureArray=e.isTextureArray,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.6,type:`Texture`,generator:`Texture.toJSON`},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:`dispose`})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case o:e.x-=Math.floor(e.x);break;case s:e.x=e.x<0?0:1;break;case c:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case o:e.y-=Math.floor(e.y);break;case s:e.y=e.y<0?0:1;break;case c:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};Jt.DEFAULT_IMAGE=null,Jt.DEFAULT_MAPPING=300,Jt.DEFAULT_ANISOTROPY=1;var Yt=class e{constructor(t=0,n=0,r=0,i=1){e.prototype.isVector4=!0,this.x=t,this.y=n,this.z=r,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w===void 0?1:e.w,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)<a&&Math.abs(u-m)<a&&Math.abs(p-h)<a){if(Math.abs(l+d)<o&&Math.abs(u+m)<o&&Math.abs(p+h)<o&&Math.abs(c+f+g-3)<o)return this.set(1,0,0,0),this;t=Math.PI;let e=(c+1)/2,s=(f+1)/2,_=(g+1)/2,v=(l+d)/4,y=(u+m)/4,b=(p+h)/4;return e>s&&e>_?e<a?(n=0,r=.707106781,i=.707106781):(n=Math.sqrt(e),r=v/n,i=y/n):s>_?s<a?(n=.707106781,r=0,i=.707106781):(r=Math.sqrt(s),n=v/r,i=b/r):_<a?(n=.707106781,r=.707106781,i=0):(i=Math.sqrt(_),n=y/i,r=b/i),this.set(n,r,i,t),this}let _=Math.sqrt((h-p)*(h-p)+(u-m)*(u-m)+(d-l)*(d-l));return Math.abs(_)<.001&&(_=1),this.x=(h-p)/_,this.y=(u-m)/_,this.z=(d-l)/_,this.w=Math.acos((c+f+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=I(this.x,e.x,t.x),this.y=I(this.y,e.y,t.y),this.z=I(this.z,e.z,t.z),this.w=I(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=I(this.x,e,t),this.y=I(this.y,e,t),this.z=I(this.z,e,t),this.w=I(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(I(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},Xt=class extends $e{constructor(e=1,t=1,n={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth?n.depth:1,this.scissor=new Yt(0,0,e,t),this.scissorTest=!1,this.viewport=new Yt(0,0,e,t);let r={width:e,height:t,depth:this.depth};n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:f,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,multiview:!1},n);let i=new Jt(r,n.mapping,n.wrapS,n.wrapT,n.magFilter,n.minFilter,n.format,n.type,n.anisotropy,n.colorSpace);i.flipY=!1,i.generateMipmaps=n.generateMipmaps,i.internalFormat=n.internalFormat,this.textures=[];let a=n.count;for(let e=0;e<a;e++)this.textures[e]=i.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let r=0,i=this.textures.length;r<i;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=n;this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let n=Object.assign({},e.textures[t].image);this.textures[t].source=new Gt(n)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:`dispose`})}},Zt=class extends Xt{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},Qt=class extends Jt{constructor(e=null,t=1,n=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=l,this.minFilter=l,this.wrapR=s,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},$t=class extends Jt{constructor(e=null,t=1,n=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=l,this.minFilter=l,this.wrapR=s,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},en=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(o===0){e[t+0]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u;return}if(o===1){e[t+0]=d,e[t+1]=f,e[t+2]=p,e[t+3]=m;return}if(u!==m||s!==d||c!==f||l!==p){let e=1-o,t=s*d+c*f+l*p+u*m,n=t>=0?1:-1,r=1-t*t;if(r>2**-52){let i=Math.sqrt(r),a=Math.atan2(i,t*n);e=Math.sin(e*a)/i,o=Math.sin(o*a)/i}let i=o*n;if(s=s*e+d*i,c=c*e+f*i,l=l*e+p*i,u=u*e+m*i,e===1-o){let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:console.warn(`THREE.Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<2**-52?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(I(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);let n=this._x,r=this._y,i=this._z,a=this._w,o=a*e._w+n*e._x+r*e._y+i*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=a,this._x=n,this._y=r,this._z=i,this;let s=1-o*o;if(s<=2**-52){let e=1-t;return this._w=e*a+t*this._w,this._x=e*n+t*this._x,this._y=e*r+t*this._y,this._z=e*i+t*this._z,this.normalize(),this}let c=Math.sqrt(s),l=Math.atan2(c,o),u=Math.sin((1-t)*l)/c,d=Math.sin(t*l)/c;return this._w=a*u+this._w*d,this._x=n*u+this._x*d,this._y=r*u+this._y*d,this._z=i*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},R=class e{constructor(t=0,n=0,r=0){e.prototype.isVector3=!0,this.x=t,this.y=n,this.z=r}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(nn.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(nn.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=I(this.x,e.x,t.x),this.y=I(this.y,e.y,t.y),this.z=I(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=I(this.x,e,t),this.y=I(this.y,e,t),this.z=I(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(I(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return tn.copy(this).projectOnVector(e),this.sub(tn)}reflect(e){return this.sub(tn.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(I(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},tn=new R,nn=new en,rn=class{constructor(e=new R(1/0,1/0,1/0),t=new R(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(on.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(on.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=on.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let n=e.geometry;if(n!==void 0){let r=n.getAttribute(`position`);if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let t=0,n=r.count;t<n;t++)e.isMesh===!0?e.getVertexPosition(t,on):on.fromBufferAttribute(r,t),on.applyMatrix4(e.matrixWorld),this.expandByPoint(on);else e.boundingBox===void 0?(n.boundingBox===null&&n.computeBoundingBox(),sn.copy(n.boundingBox)):(e.boundingBox===null&&e.computeBoundingBox(),sn.copy(e.boundingBox)),sn.applyMatrix4(e.matrixWorld),this.union(sn)}let r=e.children;for(let e=0,n=r.length;e<n;e++)this.expandByObject(r[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,on),on.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(mn),hn.subVectors(this.max,mn),cn.subVectors(e.a,mn),ln.subVectors(e.b,mn),un.subVectors(e.c,mn),dn.subVectors(ln,cn),fn.subVectors(un,ln),pn.subVectors(cn,un);let t=[0,-dn.z,dn.y,0,-fn.z,fn.y,0,-pn.z,pn.y,dn.z,0,-dn.x,fn.z,0,-fn.x,pn.z,0,-pn.x,-dn.y,dn.x,0,-fn.y,fn.x,0,-pn.y,pn.x,0];return!vn(t,cn,ln,un,hn)||(t=[1,0,0,0,1,0,0,0,1],!vn(t,cn,ln,un,hn))?!1:(gn.crossVectors(dn,fn),t=[gn.x,gn.y,gn.z],vn(t,cn,ln,un,hn))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,on).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(on).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(an[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),an[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),an[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),an[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),an[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),an[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),an[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),an[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(an),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}},an=[new R,new R,new R,new R,new R,new R,new R,new R],on=new R,sn=new rn,cn=new R,ln=new R,un=new R,dn=new R,fn=new R,pn=new R,mn=new R,hn=new R,gn=new R,_n=new R;function vn(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){_n.fromArray(e,a);let o=i.x*Math.abs(_n.x)+i.y*Math.abs(_n.y)+i.z*Math.abs(_n.z),s=t.dot(_n),c=n.dot(_n),l=r.dot(_n);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var yn=new rn,bn=new R,xn=new R,Sn=class{constructor(e=new R,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let n=this.center;t===void 0?yn.setFromPoints(e).getCenter(n):n.copy(t);let r=0;for(let t=0,i=e.length;t<i;t++)r=Math.max(r,n.distanceToSquared(e[t]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius*=e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;bn.subVectors(e,this.center);let t=bn.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(bn,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(xn.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(bn.copy(e.center).add(xn)),this.expandByPoint(bn.copy(e.center).sub(xn))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}},Cn=new R,wn=new R,Tn=new R,En=new R,Dn=new R,On=new R,kn=new R,An=class{constructor(e=new R,t=new R(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Cn)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=Cn.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Cn.copy(this.origin).addScaledVector(this.direction,t),Cn.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){wn.copy(e).add(t).multiplyScalar(.5),Tn.copy(t).sub(e).normalize(),En.copy(this.origin).sub(wn);let i=e.distanceTo(t)*.5,a=-this.direction.dot(Tn),o=En.dot(this.direction),s=-En.dot(Tn),c=En.lengthSq(),l=Math.abs(1-a*a),u,d,f,p;if(l>0)if(u=a*s-o,d=a*o-s,p=i*l,u>=0)if(d>=-p)if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c);else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(wn).addScaledVector(Tn,d),f}intersectSphere(e,t){Cn.subVectors(e.center,this.origin);let n=Cn.dot(this.direction),r=Cn.dot(Cn)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r||((i>n||isNaN(n))&&(n=i),(a<r||isNaN(r))&&(r=a),u>=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r)||((o>n||n!==n)&&(n=o),(s<r||r!==r)&&(r=s),r<0)?null:this.at(n>=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,Cn)!==null}intersectTriangle(e,t,n,r,i){Dn.subVectors(t,e),On.subVectors(n,e),kn.crossVectors(Dn,On);let a=this.direction.dot(kn),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;En.subVectors(this.origin,e);let s=o*this.direction.dot(On.crossVectors(En,On));if(s<0)return null;let c=o*this.direction.dot(Dn.cross(En));if(c<0||s+c>a)return null;let l=-o*En.dot(kn);return l<0?null:this.at(l/a,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},z=class e{constructor(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g){e.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],t!==void 0&&this.set(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g)}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=r,g[1]=i,g[5]=a,g[9]=o,g[13]=s,g[2]=c,g[6]=l,g[10]=u,g[14]=d,g[3]=f,g[7]=p,g[11]=m,g[15]=h,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new e().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){let t=this.elements,n=e.elements,r=1/jn.setFromMatrixColumn(e,0).length(),i=1/jn.setFromMatrixColumn(e,1).length(),a=1/jn.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*i,t[5]=n[5]*i,t[6]=n[6]*i,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,r=e.y,i=e.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(r),c=Math.sin(r),l=Math.cos(i),u=Math.sin(i);if(e.order===`XYZ`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=-s*u,t[8]=c,t[1]=n+r*c,t[5]=e-i*c,t[9]=-o*s,t[2]=i-e*c,t[6]=r+n*c,t[10]=a*s}else if(e.order===`YXZ`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e+i*o,t[4]=r*o-n,t[8]=a*c,t[1]=a*u,t[5]=a*l,t[9]=-o,t[2]=n*o-r,t[6]=i+e*o,t[10]=a*s}else if(e.order===`ZXY`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e-i*o,t[4]=-a*u,t[8]=r+n*o,t[1]=n+r*o,t[5]=a*l,t[9]=i-e*o,t[2]=-a*c,t[6]=o,t[10]=a*s}else if(e.order===`ZYX`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=r*c-n,t[8]=e*c+i,t[1]=s*u,t[5]=i*c+e,t[9]=n*c-r,t[2]=-c,t[6]=o*s,t[10]=a*s}else if(e.order===`YZX`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=i-e*u,t[8]=r*u+n,t[1]=u,t[5]=a*l,t[9]=-o*l,t[2]=-c*l,t[6]=n*u+r,t[10]=e-i*u}else if(e.order===`XZY`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=-u,t[8]=c*l,t[1]=e*u+i,t[5]=a*l,t[9]=n*u-r,t[2]=r*u-n,t[6]=o*l,t[10]=i*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Nn,e,Pn)}lookAt(e,t,n){let r=this.elements;return Ln.subVectors(e,t),Ln.lengthSq()===0&&(Ln.z=1),Ln.normalize(),Fn.crossVectors(n,Ln),Fn.lengthSq()===0&&(Math.abs(n.z)===1?Ln.x+=1e-4:Ln.z+=1e-4,Ln.normalize(),Fn.crossVectors(n,Ln)),Fn.normalize(),In.crossVectors(Ln,Fn),r[0]=Fn.x,r[4]=In.x,r[8]=Ln.x,r[1]=Fn.y,r[5]=In.y,r[9]=Ln.y,r[2]=Fn.z,r[6]=In.z,r[10]=Ln.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[4],s=n[8],c=n[12],l=n[1],u=n[5],d=n[9],f=n[13],p=n[2],m=n[6],h=n[10],g=n[14],_=n[3],v=n[7],y=n[11],b=n[15],x=r[0],S=r[4],C=r[8],w=r[12],T=r[1],E=r[5],D=r[9],O=r[13],k=r[2],ee=r[6],te=r[10],ne=r[14],re=r[3],A=r[7],ie=r[11],ae=r[15];return i[0]=a*x+o*T+s*k+c*re,i[4]=a*S+o*E+s*ee+c*A,i[8]=a*C+o*D+s*te+c*ie,i[12]=a*w+o*O+s*ne+c*ae,i[1]=l*x+u*T+d*k+f*re,i[5]=l*S+u*E+d*ee+f*A,i[9]=l*C+u*D+d*te+f*ie,i[13]=l*w+u*O+d*ne+f*ae,i[2]=p*x+m*T+h*k+g*re,i[6]=p*S+m*E+h*ee+g*A,i[10]=p*C+m*D+h*te+g*ie,i[14]=p*w+m*O+h*ne+g*ae,i[3]=_*x+v*T+y*k+b*re,i[7]=_*S+v*E+y*ee+b*A,i[11]=_*C+v*D+y*te+b*ie,i[15]=_*w+v*O+y*ne+b*ae,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[12],a=e[1],o=e[5],s=e[9],c=e[13],l=e[2],u=e[6],d=e[10],f=e[14],p=e[3],m=e[7],h=e[11],g=e[15];return p*(+i*s*u-r*c*u-i*o*d+n*c*d+r*o*f-n*s*f)+m*(+t*s*f-t*c*d+i*a*d-r*a*f+r*c*l-i*s*l)+h*(+t*c*u-t*o*f-i*a*u+n*a*f+i*o*l-n*c*l)+g*(-r*o*l-t*s*u+t*o*d+r*a*u-n*a*d+n*s*l)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){let r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=u*h*c-m*d*c+m*s*f-o*h*f-u*s*g+o*d*g,v=p*d*c-l*h*c-p*s*f+a*h*f+l*s*g-a*d*g,y=l*m*c-p*u*c+p*o*f-a*m*f-l*o*g+a*u*g,b=p*u*s-l*m*s-p*o*d+a*m*d+l*o*h-a*u*h,x=t*_+n*v+r*y+i*b;if(x===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let S=1/x;return e[0]=_*S,e[1]=(m*d*i-u*h*i-m*r*f+n*h*f+u*r*g-n*d*g)*S,e[2]=(o*h*i-m*s*i+m*r*c-n*h*c-o*r*g+n*s*g)*S,e[3]=(u*s*i-o*d*i-u*r*c+n*d*c+o*r*f-n*s*f)*S,e[4]=v*S,e[5]=(l*h*i-p*d*i+p*r*f-t*h*f-l*r*g+t*d*g)*S,e[6]=(p*s*i-a*h*i-p*r*c+t*h*c+a*r*g-t*s*g)*S,e[7]=(a*d*i-l*s*i+l*r*c-t*d*c-a*r*f+t*s*f)*S,e[8]=y*S,e[9]=(p*u*i-l*m*i-p*n*f+t*m*f+l*n*g-t*u*g)*S,e[10]=(a*m*i-p*o*i+p*n*c-t*m*c-a*n*g+t*o*g)*S,e[11]=(l*o*i-a*u*i-l*n*c+t*u*c+a*n*f-t*o*f)*S,e[12]=b*S,e[13]=(l*m*r-p*u*r+p*n*d-t*m*d-l*n*h+t*u*h)*S,e[14]=(p*o*r-a*m*r-p*n*s+t*m*s+a*n*h-t*o*h)*S,e[15]=(a*u*r-l*o*r+l*n*s-t*u*s-a*n*d+t*o*d)*S,this}scale(e){let t=this.elements,n=e.x,r=e.y,i=e.z;return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),r=Math.sin(t),i=1-n,a=e.x,o=e.y,s=e.z,c=i*a,l=i*o;return this.set(c*a+n,c*o-r*s,c*s+r*o,0,c*o+r*s,l*o+n,l*s-r*a,0,c*s-r*o,l*s+r*a,i*s*s+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,i,a){return this.set(1,n,i,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){let r=this.elements,i=t._x,a=t._y,o=t._z,s=t._w,c=i+i,l=a+a,u=o+o,d=i*c,f=i*l,p=i*u,m=a*l,h=a*u,g=o*u,_=s*c,v=s*l,y=s*u,b=n.x,x=n.y,S=n.z;return r[0]=(1-(m+g))*b,r[1]=(f+y)*b,r[2]=(p-v)*b,r[3]=0,r[4]=(f-y)*x,r[5]=(1-(d+g))*x,r[6]=(h+_)*x,r[7]=0,r[8]=(p+v)*S,r[9]=(h-_)*S,r[10]=(1-(d+m))*S,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){let r=this.elements,i=jn.set(r[0],r[1],r[2]).length(),a=jn.set(r[4],r[5],r[6]).length(),o=jn.set(r[8],r[9],r[10]).length();this.determinant()<0&&(i=-i),e.x=r[12],e.y=r[13],e.z=r[14],Mn.copy(this);let s=1/i,c=1/a,l=1/o;return Mn.elements[0]*=s,Mn.elements[1]*=s,Mn.elements[2]*=s,Mn.elements[4]*=c,Mn.elements[5]*=c,Mn.elements[6]*=c,Mn.elements[8]*=l,Mn.elements[9]*=l,Mn.elements[10]*=l,t.setFromRotationMatrix(Mn),n.x=i,n.y=a,n.z=o,this}makePerspective(e,t,n,r,i,a,o=Qe){let s=this.elements,c=2*i/(t-e),l=2*i/(n-r),u=(t+e)/(t-e),d=(n+r)/(n-r),f,p;if(o===2e3)f=-(a+i)/(a-i),p=-2*a*i/(a-i);else if(o===2001)f=-a/(a-i),p=-a*i/(a-i);else throw Error(`THREE.Matrix4.makePerspective(): Invalid coordinate system: `+o);return s[0]=c,s[4]=0,s[8]=u,s[12]=0,s[1]=0,s[5]=l,s[9]=d,s[13]=0,s[2]=0,s[6]=0,s[10]=f,s[14]=p,s[3]=0,s[7]=0,s[11]=-1,s[15]=0,this}makeOrthographic(e,t,n,r,i,a,o=Qe){let s=this.elements,c=1/(t-e),l=1/(n-r),u=1/(a-i),d=(t+e)*c,f=(n+r)*l,p,m;if(o===2e3)p=(a+i)*u,m=-2*u;else if(o===2001)p=i*u,m=-1*u;else throw Error(`THREE.Matrix4.makeOrthographic(): Invalid coordinate system: `+o);return s[0]=2*c,s[4]=0,s[8]=0,s[12]=-d,s[1]=0,s[5]=2*l,s[9]=0,s[13]=-f,s[2]=0,s[6]=0,s[10]=m,s[14]=-p,s[3]=0,s[7]=0,s[11]=0,s[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}},jn=new R,Mn=new z,Nn=new R(0,0,0),Pn=new R(1,1,1),Fn=new R,In=new R,Ln=new R,Rn=new z,zn=new en,Bn=class e{constructor(t=0,n=0,r=0,i=e.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=n,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let r=e.elements,i=r[0],a=r[4],o=r[8],s=r[1],c=r[5],l=r[9],u=r[2],d=r[6],f=r[10];switch(t){case`XYZ`:this._y=Math.asin(I(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,f),this._z=Math.atan2(-a,i)):(this._x=Math.atan2(d,c),this._z=0);break;case`YXZ`:this._x=Math.asin(-I(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(s,c)):(this._y=Math.atan2(-u,i),this._z=0);break;case`ZXY`:this._x=Math.asin(I(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(s,i));break;case`ZYX`:this._y=Math.asin(-I(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(s,i)):(this._x=0,this._z=Math.atan2(-a,c));break;case`YZX`:this._z=Math.asin(I(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,i)):(this._x=0,this._y=Math.atan2(o,f));break;case`XZY`:this._z=Math.asin(-I(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,i)):(this._x=Math.atan2(-l,f),this._y=0);break;default:console.warn(`THREE.Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return Rn.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Rn,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return zn.setFromEuler(this),this.setFromQuaternion(zn,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};Bn.DEFAULT_ORDER=`XYZ`;var Vn=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!=0}},Hn=0,Un=new R,Wn=new en,Gn=new z,Kn=new R,qn=new R,Jn=new R,Yn=new en,Xn=new R(1,0,0),Zn=new R(0,1,0),Qn=new R(0,0,1),$n={type:`added`},er={type:`removed`},tr={type:`childadded`,child:null},nr={type:`childremoved`,child:null},rr=class e extends $e{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,`id`,{value:Hn++}),this.uuid=it(),this.name=``,this.type=`Object3D`,this.parent=null,this.children=[],this.up=e.DEFAULT_UP.clone();let t=new R,n=new Bn,r=new en,i=new R(1,1,1);function a(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(a),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new z},normalMatrix:{value:new Et}}),this.matrix=new z,this.matrixWorld=new z,this.matrixAutoUpdate=e.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Vn,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Wn.setFromAxisAngle(e,t),this.quaternion.multiply(Wn),this}rotateOnWorldAxis(e,t){return Wn.setFromAxisAngle(e,t),this.quaternion.premultiply(Wn),this}rotateX(e){return this.rotateOnAxis(Xn,e)}rotateY(e){return this.rotateOnAxis(Zn,e)}rotateZ(e){return this.rotateOnAxis(Qn,e)}translateOnAxis(e,t){return Un.copy(e).applyQuaternion(this.quaternion),this.position.add(Un.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Xn,e)}translateY(e){return this.translateOnAxis(Zn,e)}translateZ(e){return this.translateOnAxis(Qn,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Gn.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?Kn.copy(e):Kn.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),qn.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Gn.lookAt(qn,Kn,this.up):Gn.lookAt(Kn,qn,this.up),this.quaternion.setFromRotationMatrix(Gn),r&&(Gn.extractRotation(r.matrixWorld),Wn.setFromRotationMatrix(Gn),this.quaternion.premultiply(Wn.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(console.error(`THREE.Object3D.add: object can't be added as a child of itself.`,e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent($n),tr.child=e,this.dispatchEvent(tr),tr.child=null):console.error(`THREE.Object3D.add: object not an instance of THREE.Object3D.`,e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(er),nr.child=e,this.dispatchEvent(nr),nr.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Gn.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Gn.multiply(e.parent.matrixWorld)),e.applyMatrix4(Gn),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent($n),tr.child=e,this.dispatchEvent(tr),tr.child=null,this}getObjectById(e){return this.getObjectByProperty(`id`,e)}getObjectByName(e){return this.getObjectByProperty(`name`,e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,r=this.children.length;n<r;n++){let r=this.children[n].getObjectByProperty(e,t);if(r!==void 0)return r}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let r=this.children;for(let i=0,a=r.length;i<a;i++)r[i].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(qn,e,Jn),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(qn,Yn,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){let n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){let e=this.children;for(let t=0,n=e.length;t<n;t++)e[t].updateWorldMatrix(!1,!0)}}toJSON(e){let t=e===void 0||typeof e==`string`,n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.6,type:`Object`,generator:`Object3D.toJSON`});let r={};r.uuid=this.uuid,r.type=this.type,this.name!==``&&(r.name=this.name),this.castShadow===!0&&(r.castShadow=!0),this.receiveShadow===!0&&(r.receiveShadow=!0),this.visible===!1&&(r.visible=!1),this.frustumCulled===!1&&(r.frustumCulled=!1),this.renderOrder!==0&&(r.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?{min:e.boundingBox.min.toArray(),max:e.boundingBox.max.toArray()}:void 0,boundingSphere:e.boundingSphere?{radius:e.boundingSphere.radius,center:e.boundingSphere.center.toArray()}:void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere={center:this.boundingSphere.center.toArray(),radius:this.boundingSphere.radius}),this.boundingBox!==null&&(r.boundingBox={min:this.boundingBox.min.toArray(),max:this.boundingBox.max.toArray()}));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t<r;t++){let r=n[t];i(e.shapes,r)}else i(e.shapes,n)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(i(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){let t=[];for(let n=0,r=this.material.length;n<r;n++)t.push(i(e.materials,this.material[n]));r.material=t}else r.material=i(e.materials,this.material);if(this.children.length>0){r.children=[];for(let t=0;t<this.children.length;t++)r.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let t=0;t<this.animations.length;t++){let n=this.animations[t];r.animations.push(i(e.animations,n))}}if(t){let t=a(e.geometries),r=a(e.materials),i=a(e.textures),o=a(e.images),s=a(e.shapes),c=a(e.skeletons),l=a(e.animations),u=a(e.nodes);t.length>0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let t=0;t<e.children.length;t++){let n=e.children[t];this.add(n.clone())}return this}};rr.DEFAULT_UP=new R(0,1,0),rr.DEFAULT_MATRIX_AUTO_UPDATE=!0,rr.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var ir=new R,ar=new R,or=new R,sr=new R,cr=new R,lr=new R,ur=new R,dr=new R,fr=new R,pr=new R,mr=new Yt,hr=new Yt,gr=new Yt,_r=class e{constructor(e=new R,t=new R,n=new R){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),ir.subVectors(e,t),r.cross(ir);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){ir.subVectors(r,t),ar.subVectors(n,t),or.subVectors(e,t);let a=ir.dot(ir),o=ir.dot(ar),s=ir.dot(or),c=ar.dot(ar),l=ar.dot(or),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,sr)===null?!1:sr.x>=0&&sr.y>=0&&sr.x+sr.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,sr)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,sr.x),s.addScaledVector(a,sr.y),s.addScaledVector(o,sr.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return mr.setScalar(0),hr.setScalar(0),gr.setScalar(0),mr.fromBufferAttribute(e,t),hr.fromBufferAttribute(e,n),gr.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(mr,i.x),a.addScaledVector(hr,i.y),a.addScaledVector(gr,i.z),a}static isFrontFacing(e,t,n,r){return ir.subVectors(n,t),ar.subVectors(e,t),ir.cross(ar).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return ir.subVectors(this.c,this.b),ar.subVectors(this.a,this.b),ir.cross(ar).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;cr.subVectors(r,n),lr.subVectors(i,n),dr.subVectors(e,n);let s=cr.dot(dr),c=lr.dot(dr);if(s<=0&&c<=0)return t.copy(n);fr.subVectors(e,r);let l=cr.dot(fr),u=lr.dot(fr);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(cr,a);pr.subVectors(e,i);let f=cr.dot(pr),p=lr.dot(pr);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(lr,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return ur.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(ur,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(cr,a).addScaledVector(lr,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},vr={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},yr={h:0,s:0,l:0},br={h:0,s:0,l:0};function xr(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var B=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Ke){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,zt.toWorkingColorSpace(this,t),this}setRGB(e,t,n,r=zt.workingColorSpace){return this.r=e,this.g=t,this.b=n,zt.toWorkingColorSpace(this,r),this}setHSL(e,t,n,r=zt.workingColorSpace){if(e=at(e,1),t=I(t,0,1),n=I(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=xr(i,r,e+1/3),this.g=xr(i,r,e),this.b=xr(i,r,e-1/3)}return zt.toWorkingColorSpace(this,r),this}setStyle(e,t=Ke){function n(t){t!==void 0&&parseFloat(t)<1&&console.warn(`THREE.Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:console.warn(`THREE.Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);console.warn(`THREE.Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Ke){let n=vr[e.toLowerCase()];return n===void 0?console.warn(`THREE.Color: Unknown color `+e):this.setHex(n,t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Bt(e.r),this.g=Bt(e.g),this.b=Bt(e.b),this}copyLinearToSRGB(e){return this.r=Vt(e.r),this.g=Vt(e.g),this.b=Vt(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Ke){return zt.fromWorkingColorSpace(Sr.copy(this),e),Math.round(I(Sr.r*255,0,255))*65536+Math.round(I(Sr.g*255,0,255))*256+Math.round(I(Sr.b*255,0,255))}getHexString(e=Ke){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=zt.workingColorSpace){zt.fromWorkingColorSpace(Sr.copy(this),t);let n=Sr.r,r=Sr.g,i=Sr.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r<i?6:0);break;case r:s=(i-n)/e+2;break;case i:s=(n-r)/e+4;break}s/=6}return e.h=s,e.s=c,e.l=l,e}getRGB(e,t=zt.workingColorSpace){return zt.fromWorkingColorSpace(Sr.copy(this),t),e.r=Sr.r,e.g=Sr.g,e.b=Sr.b,e}getStyle(e=Ke){zt.fromWorkingColorSpace(Sr.copy(this),e);let t=Sr.r,n=Sr.g,r=Sr.b;return e===`srgb`?`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(r*255)})`:`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`}offsetHSL(e,t,n){return this.getHSL(yr),this.setHSL(yr.h+e,yr.s+t,yr.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(yr),e.getHSL(br);let n=ct(yr.h,br.h,t),r=ct(yr.s,br.s,t),i=ct(yr.l,br.l,t);return this.setHSL(n,r,i),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,r=this.b,i=e.elements;return this.r=i[0]*t+i[3]*n+i[6]*r,this.g=i[1]*t+i[4]*n+i[7]*r,this.b=i[2]*t+i[5]*n+i[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},Sr=new B;B.NAMES=vr;var Cr=0,wr=class extends $e{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,`id`,{value:Cr++}),this.uuid=it(),this.name=``,this.type=`Material`,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new B(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Xe,this.stencilZFail=Xe,this.stencilZPass=Xe,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.6,type:`Material`,generator:`Material.toJSON`}};n.uuid=this.uuid,n.type=this.type,this.name!==``&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(n.blending=this.blending),this.side!==0&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==204&&(n.blendSrc=this.blendSrc),this.blendDst!==205&&(n.blendDst=this.blendDst),this.blendEquation!==100&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==7680&&(n.stencilFail=this.stencilFail),this.stencilZFail!==7680&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==7680&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==`round`&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==`round`&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:`dispose`})}set needsUpdate(e){e===!0&&this.version++}},Tr=class extends wr{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new B(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Bn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},Er=Dr();function Dr(){let e=new ArrayBuffer(4),t=new Float32Array(e),n=new Uint32Array(e),r=new Uint32Array(512),i=new Uint32Array(512);for(let e=0;e<256;++e){let t=e-127;t<-27?(r[e]=0,r[e|256]=32768,i[e]=24,i[e|256]=24):t<-14?(r[e]=1024>>-t-14,r[e|256]=1024>>-t-14|32768,i[e]=-t-1,i[e|256]=-t-1):t<=15?(r[e]=t+15<<10,r[e|256]=t+15<<10|32768,i[e]=13,i[e|256]=13):t<128?(r[e]=31744,r[e|256]=64512,i[e]=24,i[e|256]=24):(r[e]=31744,r[e|256]=64512,i[e]=13,i[e|256]=13)}let a=new Uint32Array(2048),o=new Uint32Array(64),s=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,n=0;for(;!(t&8388608);)t<<=1,n-=8388608;t&=-8388609,n+=947912704,a[e]=t|n}for(let e=1024;e<2048;++e)a[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)o[e]=e<<23;o[31]=1199570944,o[32]=2147483648;for(let e=33;e<63;++e)o[e]=2147483648+(e-32<<23);o[63]=3347054592;for(let e=1;e<64;++e)e!==32&&(s[e]=1024);return{floatView:t,uint32View:n,baseTable:r,shiftTable:i,mantissaTable:a,exponentTable:o,offsetTable:s}}function Or(e){Math.abs(e)>65504&&console.warn(`THREE.DataUtils.toHalfFloat(): Value out of range.`),e=I(e,-65504,65504),Er.floatView[0]=e;let t=Er.uint32View[0],n=t>>23&511;return Er.baseTable[n]+((t&8388607)>>Er.shiftTable[n])}function kr(e){let t=e>>10;return Er.uint32View[0]=Er.mantissaTable[Er.offsetTable[t]+(e&1023)]+Er.exponentTable[t],Er.floatView[0]}var Ar=class{static toHalfFloat(e){return Or(e)}static fromHalfFloat(e){return kr(e)}},jr=new R,Mr=new L,Nr=0,Pr=class{constructor(e,t,n=!1){if(Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,`id`,{value:Nr++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=Ze,this.updateRanges=[],this.gpuType=x,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;r<i;r++)this.array[e+r]=t.array[n+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)Mr.fromBufferAttribute(this,t),Mr.applyMatrix3(e),this.setXY(t,Mr.x,Mr.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)jr.fromBufferAttribute(this,t),jr.applyMatrix3(e),this.setXYZ(t,jr.x,jr.y,jr.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)jr.fromBufferAttribute(this,t),jr.applyMatrix4(e),this.setXYZ(t,jr.x,jr.y,jr.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)jr.fromBufferAttribute(this,t),jr.applyNormalMatrix(e),this.setXYZ(t,jr.x,jr.y,jr.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)jr.fromBufferAttribute(this,t),jr.transformDirection(e),this.setXYZ(t,jr.x,jr.y,jr.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=Ct(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=wt(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Ct(t,this.array)),t}setX(e,t){return this.normalized&&(t=wt(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Ct(t,this.array)),t}setY(e,t){return this.normalized&&(t=wt(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Ct(t,this.array)),t}setZ(e,t){return this.normalized&&(t=wt(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Ct(t,this.array)),t}setW(e,t){return this.normalized&&(t=wt(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=wt(t,this.array),n=wt(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=wt(t,this.array),n=wt(n,this.array),r=wt(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=wt(t,this.array),n=wt(n,this.array),r=wt(r,this.array),i=wt(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this.array[e+3]=i,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==``&&(e.name=this.name),this.usage!==35044&&(e.usage=this.usage),e}},Fr=class extends Pr{constructor(e,t,n){super(new Uint16Array(e),t,n)}},Ir=class extends Pr{constructor(e,t,n){super(new Uint32Array(e),t,n)}},Lr=class extends Pr{constructor(e,t,n){super(new Float32Array(e),t,n)}},Rr=0,zr=new z,Br=new rr,Vr=new R,Hr=new rn,Ur=new rn,Wr=new R,Gr=class e extends $e{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,`id`,{value:Rr++}),this.uuid=it(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(Ot(e)?Ir:Fr)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new Et().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return zr.makeRotationFromQuaternion(e),this.applyMatrix4(zr),this}rotateX(e){return zr.makeRotationX(e),this.applyMatrix4(zr),this}rotateY(e){return zr.makeRotationY(e),this.applyMatrix4(zr),this}rotateZ(e){return zr.makeRotationZ(e),this.applyMatrix4(zr),this}translate(e,t,n){return zr.makeTranslation(e,t,n),this.applyMatrix4(zr),this}scale(e,t,n){return zr.makeScale(e,t,n),this.applyMatrix4(zr),this}lookAt(e){return Br.lookAt(e),Br.updateMatrix(),this.applyMatrix4(Br.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Vr).negate(),this.translate(Vr.x,Vr.y,Vr.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;n<r;n++){let r=e[n];t.push(r.x,r.y,r.z||0)}this.setAttribute(`position`,new Lr(t,3))}else{let n=Math.min(e.length,t.count);for(let r=0;r<n;r++){let n=e[r];t.setXYZ(r,n.x,n.y,n.z||0)}e.length>t.count&&console.warn(`THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.`),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new rn);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error(`THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new R(-1/0,-1/0,-1/0),new R(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];Hr.setFromBufferAttribute(n),this.morphTargetsRelative?(Wr.addVectors(this.boundingBox.min,Hr.min),this.boundingBox.expandByPoint(Wr),Wr.addVectors(this.boundingBox.max,Hr.max),this.boundingBox.expandByPoint(Wr)):(this.boundingBox.expandByPoint(Hr.min),this.boundingBox.expandByPoint(Hr.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error(`THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.`,this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Sn);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error(`THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.`,this),this.boundingSphere.set(new R,1/0);return}if(e){let n=this.boundingSphere.center;if(Hr.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];Ur.setFromBufferAttribute(n),this.morphTargetsRelative?(Wr.addVectors(Hr.min,Ur.min),Hr.expandByPoint(Wr),Wr.addVectors(Hr.max,Ur.max),Hr.expandByPoint(Wr)):(Hr.expandByPoint(Ur.min),Hr.expandByPoint(Ur.max))}Hr.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)Wr.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(Wr));if(t)for(let i=0,a=t.length;i<a;i++){let a=t[i],o=this.morphTargetsRelative;for(let t=0,i=a.count;t<i;t++)Wr.fromBufferAttribute(a,t),o&&(Vr.fromBufferAttribute(e,t),Wr.add(Vr)),r=Math.max(r,n.distanceToSquared(Wr))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&console.error(`THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.`,this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){console.error(`THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)`);return}let n=t.position,r=t.normal,i=t.uv;this.hasAttribute(`tangent`)===!1&&this.setAttribute(`tangent`,new Pr(new Float32Array(4*n.count),4));let a=this.getAttribute(`tangent`),o=[],s=[];for(let e=0;e<n.count;e++)o[e]=new R,s[e]=new R;let c=new R,l=new R,u=new R,d=new L,f=new L,p=new L,m=new R,h=new R;function g(e,t,r){c.fromBufferAttribute(n,e),l.fromBufferAttribute(n,t),u.fromBufferAttribute(n,r),d.fromBufferAttribute(i,e),f.fromBufferAttribute(i,t),p.fromBufferAttribute(i,r),l.sub(c),u.sub(c),f.sub(d),p.sub(d);let a=1/(f.x*p.y-p.x*f.y);isFinite(a)&&(m.copy(l).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(a),h.copy(u).multiplyScalar(f.x).addScaledVector(l,-p.x).multiplyScalar(a),o[e].add(m),o[t].add(m),o[r].add(m),s[e].add(h),s[t].add(h),s[r].add(h))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}let v=new R,y=new R,b=new R,x=new R;function S(e){b.fromBufferAttribute(r,e),x.copy(b);let t=o[e];v.copy(t),v.sub(b.multiplyScalar(b.dot(t))).normalize(),y.crossVectors(x,t);let n=y.dot(s[e])<0?-1:1;a.setXYZW(e,v.x,v.y,v.z,n)}for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)S(e.getX(t+0)),S(e.getX(t+1)),S(e.getX(t+2))}}computeVertexNormals(){let e=this.index,t=this.getAttribute(`position`);if(t!==void 0){let n=this.getAttribute(`normal`);if(n===void 0)n=new Pr(new Float32Array(t.count*3),3),this.setAttribute(`normal`,n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);let r=new R,i=new R,a=new R,o=new R,s=new R,c=new R,l=new R,u=new R;if(e)for(let d=0,f=e.count;d<f;d+=3){let f=e.getX(d+0),p=e.getX(d+1),m=e.getX(d+2);r.fromBufferAttribute(t,f),i.fromBufferAttribute(t,p),a.fromBufferAttribute(t,m),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),o.fromBufferAttribute(n,f),s.fromBufferAttribute(n,p),c.fromBufferAttribute(n,m),o.add(l),s.add(l),c.add(l),n.setXYZ(f,o.x,o.y,o.z),n.setXYZ(p,s.x,s.y,s.z),n.setXYZ(m,c.x,c.y,c.z)}else for(let e=0,o=t.count;e<o;e+=3)r.fromBufferAttribute(t,e+0),i.fromBufferAttribute(t,e+1),a.fromBufferAttribute(t,e+2),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),n.setXYZ(e+0,l.x,l.y,l.z),n.setXYZ(e+1,l.x,l.y,l.z),n.setXYZ(e+2,l.x,l.y,l.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)Wr.fromBufferAttribute(e,t),Wr.normalize(),e.setXYZ(t,Wr.x,Wr.y,Wr.z)}toNonIndexed(){function t(e,t){let n=e.array,r=e.itemSize,i=e.normalized,a=new n.constructor(t.length*r),o=0,s=0;for(let i=0,c=t.length;i<c;i++){o=e.isInterleavedBufferAttribute?t[i]*e.data.stride+e.offset:t[i]*r;for(let e=0;e<r;e++)a[s++]=n[o++]}return new Pr(a,r,i)}if(this.index===null)return console.warn(`THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.`),this;let n=new e,r=this.index.array,i=this.attributes;for(let e in i){let a=i[e],o=t(a,r);n.setAttribute(e,o)}let a=this.morphAttributes;for(let e in a){let i=[],o=a[e];for(let e=0,n=o.length;e<n;e++){let n=o[e],a=t(n,r);i.push(a)}n.morphAttributes[e]=i}n.morphTargetsRelative=this.morphTargetsRelative;let o=this.groups;for(let e=0,t=o.length;e<t;e++){let t=o[e];n.addGroup(t.start,t.count,t.materialIndex)}return n}toJSON(){let e={metadata:{version:4.6,type:`BufferGeometry`,generator:`BufferGeometry.toJSON`}};if(e.uuid=this.uuid,e.type=this.type,this.name!==``&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t<r;t++){let r=n[t];a.push(r.toJSON(e.data))}a.length>0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e<i;e++)n.push(r[e].clone(t));this.morphAttributes[e]=n}this.morphTargetsRelative=e.morphTargetsRelative;let a=e.groups;for(let e=0,t=a.length;e<t;e++){let t=a[e];this.addGroup(t.start,t.count,t.materialIndex)}let o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());let s=e.boundingSphere;return s!==null&&(this.boundingSphere=s.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:`dispose`})}},Kr=new z,qr=new An,Jr=new Sn,Yr=new R,Xr=new R,Zr=new R,Qr=new R,$r=new R,ei=new R,ti=new R,ni=new R,ri=class extends rr{constructor(e=new Gr,t=new Tr){super(),this.isMesh=!0,this.type=`Mesh`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){let n=this.geometry,r=n.attributes.position,i=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(r,e);let o=this.morphTargetInfluences;if(i&&o){ei.set(0,0,0);for(let n=0,r=i.length;n<r;n++){let r=o[n],s=i[n];r!==0&&($r.fromBufferAttribute(s,e),a?ei.addScaledVector($r,r):ei.addScaledVector($r.sub(t),r))}t.add(ei)}return t}raycast(e,t){let n=this.geometry,r=this.material,i=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),Jr.copy(n.boundingSphere),Jr.applyMatrix4(i),qr.copy(e.ray).recast(e.near),!(Jr.containsPoint(qr.origin)===!1&&(qr.intersectSphere(Jr,Yr)===null||qr.origin.distanceToSquared(Yr)>(e.far-e.near)**2))&&(Kr.copy(i).invert(),qr.copy(e.ray).applyMatrix4(Kr),!(n.boundingBox!==null&&qr.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,qr)))}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null)if(Array.isArray(a))for(let i=0,s=d.length;i<s;i++){let s=d[i],p=a[s.materialIndex],m=Math.max(s.start,f.start),h=Math.min(o.count,Math.min(s.start+s.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=o.getX(i),d=o.getX(i+1),f=o.getX(i+2);r=ai(this,p,e,n,c,l,u,a,d,f),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=s.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),s=Math.min(o.count,f.start+f.count);for(let d=i,f=s;d<f;d+=3){let i=o.getX(d),s=o.getX(d+1),f=o.getX(d+2);r=ai(this,a,e,n,c,l,u,i,s,f),r&&(r.faceIndex=Math.floor(d/3),t.push(r))}}else if(s!==void 0)if(Array.isArray(a))for(let i=0,o=d.length;i<o;i++){let o=d[i],p=a[o.materialIndex],m=Math.max(o.start,f.start),h=Math.min(s.count,Math.min(o.start+o.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=i,s=i+1,d=i+2;r=ai(this,p,e,n,c,l,u,a,s,d),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=o.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),o=Math.min(s.count,f.start+f.count);for(let s=i,d=o;s<d;s+=3){let i=s,o=s+1,d=s+2;r=ai(this,a,e,n,c,l,u,i,o,d),r&&(r.faceIndex=Math.floor(s/3),t.push(r))}}}};function ii(e,t,n,r,i,a,o,s){let c;if(c=t.side===1?r.intersectTriangle(o,a,i,!0,s):r.intersectTriangle(i,a,o,t.side===0,s),c===null)return null;ni.copy(s),ni.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(ni);return l<n.near||l>n.far?null:{distance:l,point:ni.clone(),object:e}}function ai(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,Xr),e.getVertexPosition(c,Zr),e.getVertexPosition(l,Qr);let u=ii(e,t,n,r,Xr,Zr,Qr,ti);if(u){let e=new R;_r.getBarycoord(ti,Xr,Zr,Qr,e),i&&(u.uv=_r.getInterpolatedAttribute(i,s,c,l,e,new L)),a&&(u.uv1=_r.getInterpolatedAttribute(a,s,c,l,e,new L)),o&&(u.normal=_r.getInterpolatedAttribute(o,s,c,l,e,new R),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new R,materialIndex:0};_r.getNormal(Xr,Zr,Qr,t.normal),u.face=t,u.barycoord=e}return u}var oi=class e extends Gr{constructor(e=1,t=1,n=1,r=1,i=1,a=1){super(),this.type=`BoxGeometry`,this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:i,depthSegments:a};let o=this;r=Math.floor(r),i=Math.floor(i),a=Math.floor(a);let s=[],c=[],l=[],u=[],d=0,f=0;p(`z`,`y`,`x`,-1,-1,n,t,e,a,i,0),p(`z`,`y`,`x`,1,-1,n,t,-e,a,i,1),p(`x`,`z`,`y`,1,1,e,n,t,r,a,2),p(`x`,`z`,`y`,1,-1,e,n,-t,r,a,3),p(`x`,`y`,`z`,1,-1,e,t,n,r,i,4),p(`x`,`y`,`z`,-1,-1,e,t,-n,r,i,5),this.setIndex(s),this.setAttribute(`position`,new Lr(c,3)),this.setAttribute(`normal`,new Lr(l,3)),this.setAttribute(`uv`,new Lr(u,2));function p(e,t,n,r,i,a,p,m,h,g,_){let v=a/h,y=p/g,b=a/2,x=p/2,S=m/2,C=h+1,w=g+1,T=0,E=0,D=new R;for(let a=0;a<w;a++){let o=a*y-x;for(let s=0;s<C;s++)D[e]=(s*v-b)*r,D[t]=o*i,D[n]=S,c.push(D.x,D.y,D.z),D[e]=0,D[t]=0,D[n]=m>0?1:-1,l.push(D.x,D.y,D.z),u.push(s/h),u.push(1-a/g),T+=1}for(let e=0;e<g;e++)for(let t=0;t<h;t++){let n=d+t+C*e,r=d+t+C*(e+1),i=d+(t+1)+C*(e+1),a=d+(t+1)+C*e;s.push(n,r,a),s.push(r,i,a),E+=6}o.addGroup(f,E,_),f+=E,d+=T}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}};function si(e){let t={};for(let n in e){t[n]={};for(let r in e[n]){let i=e[n][r];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(console.warn(`UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().`),t[n][r]=null):t[n][r]=i.clone():Array.isArray(i)?t[n][r]=i.slice():t[n][r]=i}}return t}function ci(e){let t={};for(let n=0;n<e.length;n++){let r=si(e[n]);for(let e in r)t[e]=r[e]}return t}function li(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function ui(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:zt.workingColorSpace}var di={clone:si,merge:ci},fi=`void main() {
+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
+}`,pi=`void main() {
+ gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
+}`,mi=class extends wr{constructor(e){super(),this.isShaderMaterial=!0,this.type=`ShaderMaterial`,this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=fi,this.fragmentShader=pi,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=si(e.uniforms),this.uniformsGroups=li(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let n in this.uniforms){let r=this.uniforms[n].value;r&&r.isTexture?t.uniforms[n]={type:`t`,value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[n]={type:`c`,value:r.getHex()}:r&&r.isVector2?t.uniforms[n]={type:`v2`,value:r.toArray()}:r&&r.isVector3?t.uniforms[n]={type:`v3`,value:r.toArray()}:r&&r.isVector4?t.uniforms[n]={type:`v4`,value:r.toArray()}:r&&r.isMatrix3?t.uniforms[n]={type:`m3`,value:r.toArray()}:r&&r.isMatrix4?t.uniforms[n]={type:`m4`,value:r.toArray()}:t.uniforms[n]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let e in this.extensions)this.extensions[e]===!0&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}},hi=class extends rr{constructor(){super(),this.isCamera=!0,this.type=`Camera`,this.matrixWorldInverse=new z,this.projectionMatrix=new z,this.projectionMatrixInverse=new z,this.coordinateSystem=Qe}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}},gi=new R,_i=new L,vi=new L,yi=class extends hi{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type=`PerspectiveCamera`,this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=rt*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(nt*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return rt*2*Math.atan(Math.tan(nt*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){gi.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(gi.x,gi.y).multiplyScalar(-e/gi.z),gi.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(gi.x,gi.y).multiplyScalar(-e/gi.z)}getViewSize(e,t){return this.getViewBounds(e,_i,vi),t.subVectors(vi,_i)}setViewOffset(e,t,n,r,i,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(nt*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,i=-.5*r,a=this.view;if(this.view!==null&&this.view.enabled){let e=a.fullWidth,o=a.fullHeight;i+=a.offsetX*r/e,t-=a.offsetY*n/o,r*=a.width/e,n*=a.height/o}let o=this.filmOffset;o!==0&&(i+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-n,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},bi=-90,xi=1,Si=class extends rr{constructor(e,t,n){super(),this.type=`CubeCamera`,this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new yi(bi,xi,e,t);r.layers=this.layers,this.add(r);let i=new yi(bi,xi,e,t);i.layers=this.layers,this.add(i);let a=new yi(bi,xi,e,t);a.layers=this.layers,this.add(a);let o=new yi(bi,xi,e,t);o.layers=this.layers,this.add(o);let s=new yi(bi,xi,e,t);s.layers=this.layers,this.add(s);let c=new yi(bi,xi,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,i,a,o,s]=t;for(let e of t)this.remove(e);if(e===2e3)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),s.up.set(0,1,0),s.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),s.up.set(0,-1,0),s.lookAt(0,0,-1);else throw Error(`THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: `+e);for(let e of t)this.add(e),e.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[i,a,o,s,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,r),e.render(t,i),e.setRenderTarget(n,1,r),e.render(t,a),e.setRenderTarget(n,2,r),e.render(t,o),e.setRenderTarget(n,3,r),e.render(t,s),e.setRenderTarget(n,4,r),e.render(t,c),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,r),e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}},Ci=class extends Jt{constructor(e=[],t=301,n,r,i,a,o,s,c,l){super(e,t,n,r,i,a,o,s,c,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},wi=class extends Zt{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1};this.texture=new Ci([n,n,n,n,n,n],t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=t.generateMipmaps===void 0?!1:t.generateMipmaps,this.texture.minFilter=t.minFilter===void 0?f:t.minFilter}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:`
+
+ varying vec3 vWorldDirection;
+
+ vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
+
+ return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
+
+ }
+
+ void main() {
+
+ vWorldDirection = transformDirection( position, modelMatrix );
+
+ #include <begin_vertex>
+ #include <project_vertex>
+
+ }
+ `,fragmentShader:`
+
+ uniform sampler2D tEquirect;
+
+ varying vec3 vWorldDirection;
+
+ #include <common>
+
+ void main() {
+
+ vec3 direction = normalize( vWorldDirection );
+
+ vec2 sampleUV = equirectUv( direction );
+
+ gl_FragColor = texture2D( tEquirect, sampleUV );
+
+ }
+ `},r=new oi(5,5,5),i=new mi({name:`CubemapFromEquirect`,uniforms:si(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});i.uniforms.tEquirect.value=t;let a=new ri(r,i),o=t.minFilter;return t.minFilter===1008&&(t.minFilter=f),new Si(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){let i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,n,r);e.setRenderTarget(i)}},Ti=class extends rr{constructor(){super(),this.isGroup=!0,this.type=`Group`}},Ei={type:`move`},Di=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Ti,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Ti,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new R,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new R),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Ti,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new R,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new R),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){let t=this._hand;if(t)for(let n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:`connected`,data:e}),this}disconnect(e){return this.dispatchEvent({type:`disconnected`,data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let r=null,i=null,a=null,o=this._targetRay,s=this._grip,c=this._hand;if(e&&t.session.visibilityState!==`visible-blurred`){if(c&&e.hand){a=!0;for(let r of e.hand.values()){let e=t.getJointPose(r,n),i=this._getHandJoint(c,r);e!==null&&(i.matrix.fromArray(e.transform.matrix),i.matrix.decompose(i.position,i.rotation,i.scale),i.matrixWorldNeedsUpdate=!0,i.jointRadius=e.radius),i.visible=e!==null}let r=c.joints[`index-finger-tip`],i=c.joints[`thumb-tip`],o=r.position.distanceTo(i.position),s=.02,l=.005;c.inputState.pinching&&o>s+l?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=s-l&&(c.inputState.pinching=!0,this.dispatchEvent({type:`pinchstart`,handedness:e.handedness,target:this}))}else s!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&i!==null&&(r=i),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(Ei)))}return o!==null&&(o.visible=r!==null),s!==null&&(s.visible=i!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new Ti;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},Oi=class extends rr{constructor(){super(),this.isScene=!0,this.type=`Scene`,this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Bn,this.environmentIntensity=1,this.environmentRotation=new Bn,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},ki=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e===void 0?0:e.length/t,this.usage=Ze,this.updateRanges=[],this.version=0,this.uuid=it()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let r=0,i=this.stride;r<i;r++)this.array[e+r]=t.array[n+r];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=it()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);let t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),n=new this.constructor(t,this.stride);return n.setUsage(this.usage),n}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=it()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}},Ai=new R,ji=class e{constructor(e,t,n,r=!1){this.isInterleavedBufferAttribute=!0,this.name=``,this.data=e,this.itemSize=t,this.offset=n,this.normalized=r}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,n=this.data.count;t<n;t++)Ai.fromBufferAttribute(this,t),Ai.applyMatrix4(e),this.setXYZ(t,Ai.x,Ai.y,Ai.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Ai.fromBufferAttribute(this,t),Ai.applyNormalMatrix(e),this.setXYZ(t,Ai.x,Ai.y,Ai.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Ai.fromBufferAttribute(this,t),Ai.transformDirection(e),this.setXYZ(t,Ai.x,Ai.y,Ai.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=Ct(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=wt(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=wt(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=wt(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=wt(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=wt(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=Ct(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=Ct(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=Ct(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=Ct(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=wt(t,this.array),n=wt(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=wt(t,this.array),n=wt(n,this.array),r=wt(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=wt(t,this.array),n=wt(n,this.array),r=wt(r,this.array),i=wt(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=r,this.data.array[e+3]=i,this}clone(t){if(t===void 0){console.log(`THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.`);let e=[];for(let t=0;t<this.count;t++){let n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return new Pr(new this.array.constructor(e),this.itemSize,this.normalized)}else return t.interleavedBuffers===void 0&&(t.interleavedBuffers={}),t.interleavedBuffers[this.data.uuid]===void 0&&(t.interleavedBuffers[this.data.uuid]=this.data.clone(t)),new e(t.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){console.log(`THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.`);let e=[];for(let t=0;t<this.count;t++){let n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}},Mi=new R,Ni=new Yt,Pi=new Yt,Fi=new R,Ii=new z,Li=new R,Ri=new Sn,zi=new z,Bi=new An,Vi=class extends ri{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type=`SkinnedMesh`,this.bindMode=a,this.bindMatrix=new z,this.bindMatrixInverse=new z,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;this.boundingBox===null&&(this.boundingBox=new rn),this.boundingBox.makeEmpty();let t=e.getAttribute(`position`);for(let e=0;e<t.count;e++)this.getVertexPosition(e,Li),this.boundingBox.expandByPoint(Li)}computeBoundingSphere(){let e=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new Sn),this.boundingSphere.makeEmpty();let t=e.getAttribute(`position`);for(let e=0;e<t.count;e++)this.getVertexPosition(e,Li),this.boundingSphere.expandByPoint(Li)}copy(e,t){return super.copy(e,t),this.bindMode=e.bindMode,this.bindMatrix.copy(e.bindMatrix),this.bindMatrixInverse.copy(e.bindMatrixInverse),this.skeleton=e.skeleton,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}raycast(e,t){let n=this.material,r=this.matrixWorld;n!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),Ri.copy(this.boundingSphere),Ri.applyMatrix4(r),e.ray.intersectsSphere(Ri)!==!1&&(zi.copy(r).invert(),Bi.copy(e.ray).applyMatrix4(zi),!(this.boundingBox!==null&&Bi.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(e,t,Bi)))}getVertexPosition(e,t){return super.getVertexPosition(e,t),this.applyBoneTransform(e,t),t}bind(e,t){this.skeleton=e,t===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),t=this.matrixWorld),this.bindMatrix.copy(t),this.bindMatrixInverse.copy(t).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){let e=new Yt,t=this.geometry.attributes.skinWeight;for(let n=0,r=t.count;n<r;n++){e.fromBufferAttribute(t,n);let r=1/e.manhattanLength();r===1/0?e.set(1,0,0,0):e.multiplyScalar(r),t.setXYZW(n,e.x,e.y,e.z,e.w)}}updateMatrixWorld(e){super.updateMatrixWorld(e),this.bindMode===`attached`?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===`detached`?this.bindMatrixInverse.copy(this.bindMatrix).invert():console.warn(`THREE.SkinnedMesh: Unrecognized bindMode: `+this.bindMode)}applyBoneTransform(e,t){let n=this.skeleton,r=this.geometry;Ni.fromBufferAttribute(r.attributes.skinIndex,e),Pi.fromBufferAttribute(r.attributes.skinWeight,e),Mi.copy(t).applyMatrix4(this.bindMatrix),t.set(0,0,0);for(let e=0;e<4;e++){let r=Pi.getComponent(e);if(r!==0){let i=Ni.getComponent(e);Ii.multiplyMatrices(n.bones[i].matrixWorld,n.boneInverses[i]),t.addScaledVector(Fi.copy(Mi).applyMatrix4(Ii),r)}}return t.applyMatrix4(this.bindMatrixInverse)}},Hi=class extends rr{constructor(){super(),this.isBone=!0,this.type=`Bone`}},Ui=class extends Jt{constructor(e=null,t=1,n=1,r,i,a,o,s,c=l,u=l,d,f){super(null,a,o,s,c,u,r,i,d,f),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},Wi=new z,Gi=new z,Ki=class e{constructor(e=[],t=[]){this.uuid=it(),this.bones=e.slice(0),this.boneInverses=t,this.boneMatrices=null,this.boneTexture=null,this.init()}init(){let e=this.bones,t=this.boneInverses;if(this.boneMatrices=new Float32Array(e.length*16),t.length===0)this.calculateInverses();else if(e.length!==t.length){console.warn(`THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.`),this.boneInverses=[];for(let e=0,t=this.bones.length;e<t;e++)this.boneInverses.push(new z)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){let t=new z;this.bones[e]&&t.copy(this.bones[e].matrixWorld).invert(),this.boneInverses.push(t)}}pose(){for(let e=0,t=this.bones.length;e<t;e++){let t=this.bones[e];t&&t.matrixWorld.copy(this.boneInverses[e]).invert()}for(let e=0,t=this.bones.length;e<t;e++){let t=this.bones[e];t&&(t.parent&&t.parent.isBone?(t.matrix.copy(t.parent.matrixWorld).invert(),t.matrix.multiply(t.matrixWorld)):t.matrix.copy(t.matrixWorld),t.matrix.decompose(t.position,t.quaternion,t.scale))}}update(){let e=this.bones,t=this.boneInverses,n=this.boneMatrices,r=this.boneTexture;for(let r=0,i=e.length;r<i;r++){let i=e[r]?e[r].matrixWorld:Gi;Wi.multiplyMatrices(i,t[r]),Wi.toArray(n,r*16)}r!==null&&(r.needsUpdate=!0)}clone(){return new e(this.bones,this.boneInverses)}computeBoneTexture(){let e=Math.sqrt(this.bones.length*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);let t=new Float32Array(e*e*4);t.set(this.boneMatrices);let n=new Ui(t,e,e,k,x);return n.needsUpdate=!0,this.boneMatrices=t,this.boneTexture=n,this}getBoneByName(e){for(let t=0,n=this.bones.length;t<n;t++){let n=this.bones[t];if(n.name===e)return n}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(e,t){this.uuid=e.uuid;for(let n=0,r=e.bones.length;n<r;n++){let r=e.bones[n],i=t[r];i===void 0&&(console.warn(`THREE.Skeleton: No bone found with UUID:`,r),i=new Hi),this.bones.push(i),this.boneInverses.push(new z().fromArray(e.boneInverses[n]))}return this.init(),this}toJSON(){let e={metadata:{version:4.6,type:`Skeleton`,generator:`Skeleton.toJSON`},bones:[],boneInverses:[]};e.uuid=this.uuid;let t=this.bones,n=this.boneInverses;for(let r=0,i=t.length;r<i;r++){let i=t[r];e.bones.push(i.uuid);let a=n[r];e.boneInverses.push(a.toArray())}return e}},qi=class extends Pr{constructor(e,t,n,r=1){super(e,t,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=r}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){let e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}},Ji=new z,Yi=new z,Xi=[],Zi=new rn,Qi=new z,$i=new ri,ea=new Sn,ta=class extends ri{constructor(e,t,n){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new qi(new Float32Array(n*16),16),this.instanceColor=null,this.morphTexture=null,this.count=n,this.boundingBox=null,this.boundingSphere=null;for(let e=0;e<n;e++)this.setMatrixAt(e,Qi)}computeBoundingBox(){let e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new rn),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,Ji),Zi.copy(e.boundingBox).applyMatrix4(Ji),this.boundingBox.union(Zi)}computeBoundingSphere(){let e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new Sn),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,Ji),ea.copy(e.boundingSphere).applyMatrix4(Ji),this.boundingSphere.union(ea)}copy(e,t){return super.copy(e,t),this.instanceMatrix.copy(e.instanceMatrix),e.morphTexture!==null&&(this.morphTexture=e.morphTexture.clone()),e.instanceColor!==null&&(this.instanceColor=e.instanceColor.clone()),this.count=e.count,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}getColorAt(e,t){t.fromArray(this.instanceColor.array,e*3)}getMatrixAt(e,t){t.fromArray(this.instanceMatrix.array,e*16)}getMorphAt(e,t){let n=t.morphTargetInfluences,r=this.morphTexture.source.data.data,i=e*(n.length+1)+1;for(let e=0;e<n.length;e++)n[e]=r[i+e]}raycast(e,t){let n=this.matrixWorld,r=this.count;if($i.geometry=this.geometry,$i.material=this.material,$i.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),ea.copy(this.boundingSphere),ea.applyMatrix4(n),e.ray.intersectsSphere(ea)!==!1))for(let i=0;i<r;i++){this.getMatrixAt(i,Ji),Yi.multiplyMatrices(n,Ji),$i.matrixWorld=Yi,$i.raycast(e,Xi);for(let e=0,n=Xi.length;e<n;e++){let n=Xi[e];n.instanceId=i,n.object=this,t.push(n)}Xi.length=0}}setColorAt(e,t){this.instanceColor===null&&(this.instanceColor=new qi(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),t.toArray(this.instanceColor.array,e*3)}setMatrixAt(e,t){t.toArray(this.instanceMatrix.array,e*16)}setMorphAt(e,t){let n=t.morphTargetInfluences,r=n.length+1;this.morphTexture===null&&(this.morphTexture=new Ui(new Float32Array(r*this.count),r,this.count,ne,x));let i=this.morphTexture.source.data.data,a=0;for(let e=0;e<n.length;e++)a+=n[e];let o=this.geometry.morphTargetsRelative?1:1-a,s=r*e;i[s]=o,i.set(n,s+1)}updateMorphTargets(){}dispose(){this.dispatchEvent({type:`dispose`}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}},na=new R,ra=new R,ia=new Et,aa=class{constructor(e=new R(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let r=na.subVectors(n,t).cross(ra.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){let n=e.delta(na),r=this.normal.dot(n);if(r===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let i=-(e.start.dot(this.normal)+this.constant)/r;return i<0||i>1?null:t.copy(e.start).addScaledVector(n,i)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||ia.getNormalMatrix(e),r=this.coplanarPoint(na).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},oa=new Sn,sa=new R,ca=class{constructor(e=new aa,t=new aa,n=new aa,r=new aa,i=new aa,a=new aa){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=Qe){let n=this.planes,r=e.elements,i=r[0],a=r[1],o=r[2],s=r[3],c=r[4],l=r[5],u=r[6],d=r[7],f=r[8],p=r[9],m=r[10],h=r[11],g=r[12],_=r[13],v=r[14],y=r[15];if(n[0].setComponents(s-i,d-c,h-f,y-g).normalize(),n[1].setComponents(s+i,d+c,h+f,y+g).normalize(),n[2].setComponents(s+a,d+l,h+p,y+_).normalize(),n[3].setComponents(s-a,d-l,h-p,y-_).normalize(),n[4].setComponents(s-o,d-u,h-m,y-v).normalize(),t===2e3)n[5].setComponents(s+o,d+u,h+m,y+v).normalize();else if(t===2001)n[5].setComponents(o,u,m,v).normalize();else throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),oa.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),oa.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(oa)}intersectsSprite(e){return oa.center.set(0,0,0),oa.radius=.7071067811865476,oa.applyMatrix4(e.matrixWorld),this.intersectsSphere(oa)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)<r)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let r=t[n];if(sa.x=r.normal.x>0?e.max.x:e.min.x,sa.y=r.normal.y>0?e.max.y:e.min.y,sa.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(sa)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},la=class extends wr{constructor(e){super(),this.isLineBasicMaterial=!0,this.type=`LineBasicMaterial`,this.color=new B(16777215),this.map=null,this.linewidth=1,this.linecap=`round`,this.linejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}},ua=new R,da=new R,fa=new z,pa=new An,ma=new Sn,ha=new R,ga=new R,_a=class extends rr{constructor(e=new Gr,t=new la){super(),this.isLine=!0,this.type=`Line`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[0];for(let e=1,r=t.count;e<r;e++)ua.fromBufferAttribute(t,e-1),da.fromBufferAttribute(t,e),n[e]=n[e-1],n[e]+=ua.distanceTo(da);e.setAttribute(`lineDistance`,new Lr(n,1))}else console.warn(`THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.`);return this}raycast(e,t){let n=this.geometry,r=this.matrixWorld,i=e.params.Line.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),ma.copy(n.boundingSphere),ma.applyMatrix4(r),ma.radius+=i,e.ray.intersectsSphere(ma)===!1)return;fa.copy(r).invert(),pa.copy(e.ray).applyMatrix4(fa);let o=i/((this.scale.x+this.scale.y+this.scale.z)/3),s=o*o,c=this.isLineSegments?2:1,l=n.index,u=n.attributes.position;if(l!==null){let n=Math.max(0,a.start),r=Math.min(l.count,a.start+a.count);for(let i=n,a=r-1;i<a;i+=c){let n=l.getX(i),r=l.getX(i+1),a=va(this,e,pa,s,n,r,i);a&&t.push(a)}if(this.isLineLoop){let i=l.getX(r-1),a=l.getX(n),o=va(this,e,pa,s,i,a,r-1);o&&t.push(o)}}else{let n=Math.max(0,a.start),r=Math.min(u.count,a.start+a.count);for(let i=n,a=r-1;i<a;i+=c){let n=va(this,e,pa,s,i,i+1,i);n&&t.push(n)}if(this.isLineLoop){let i=va(this,e,pa,s,r-1,n,r-1);i&&t.push(i)}}}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}};function va(e,t,n,r,i,a,o){let s=e.geometry.attributes.position;if(ua.fromBufferAttribute(s,i),da.fromBufferAttribute(s,a),n.distanceSqToSegment(ua,da,ha,ga)>r)return;ha.applyMatrix4(e.matrixWorld);let c=t.ray.origin.distanceTo(ha);if(!(c<t.near||c>t.far))return{distance:c,point:ga.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}var ya=new R,ba=new R,xa=class extends _a{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type=`LineSegments`}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[];for(let e=0,r=t.count;e<r;e+=2)ya.fromBufferAttribute(t,e),ba.fromBufferAttribute(t,e+1),n[e]=e===0?0:n[e-1],n[e+1]=n[e]+ya.distanceTo(ba);e.setAttribute(`lineDistance`,new Lr(n,1))}else console.warn(`THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.`);return this}},Sa=class extends _a{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type=`LineLoop`}},Ca=class extends wr{constructor(e){super(),this.isPointsMaterial=!0,this.type=`PointsMaterial`,this.color=new B(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},wa=new z,Ta=new An,Ea=new Sn,Da=new R,Oa=class extends rr{constructor(e=new Gr,t=new Ca){super(),this.isPoints=!0,this.type=`Points`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){let n=this.geometry,r=this.matrixWorld,i=e.params.Points.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Ea.copy(n.boundingSphere),Ea.applyMatrix4(r),Ea.radius+=i,e.ray.intersectsSphere(Ea)===!1)return;wa.copy(r).invert(),Ta.copy(e.ray).applyMatrix4(wa);let o=i/((this.scale.x+this.scale.y+this.scale.z)/3),s=o*o,c=n.index,l=n.attributes.position;if(c!==null){let n=Math.max(0,a.start),i=Math.min(c.count,a.start+a.count);for(let a=n,o=i;a<o;a++){let n=c.getX(a);Da.fromBufferAttribute(l,n),ka(Da,n,s,r,e,t,this)}}else{let n=Math.max(0,a.start),i=Math.min(l.count,a.start+a.count);for(let a=n,o=i;a<o;a++)Da.fromBufferAttribute(l,a),ka(Da,a,s,r,e,t,this)}}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}};function ka(e,t,n,r,i,a,o){let s=Ta.distanceSqToPoint(e);if(s<n){let n=new R;Ta.closestPointToPoint(e,n),n.applyMatrix4(r);let c=i.ray.origin.distanceTo(n);if(c<i.near||c>i.far)return;a.push({distance:c,distanceToRay:Math.sqrt(s),point:n,index:t,face:null,faceIndex:null,barycoord:null,object:o})}}var Aa=class extends Jt{constructor(e,t,n,r,i,a,o,s,c,l,u,d){super(null,a,o,s,c,l,r,i,u,d),this.isCompressedTexture=!0,this.image={width:t,height:n},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}},ja=class extends Aa{constructor(e,t,n,r,i,a){super(e,t,n,i,a),this.isCompressedArrayTexture=!0,this.image.depth=r,this.wrapR=s,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},Ma=class extends Aa{constructor(e,t,n){super(void 0,e[0].width,e[0].height,t,n,301),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}},Na=class extends Jt{constructor(e,t,n=b,r,i,a,o=l,s=l,c,u=ee){if(u!==1026&&u!==1027)throw Error(`DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat`);super(null,r,i,a,o,s,u,n,c),this.isDepthTexture=!0,this.image={width:e,height:t},this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Gt(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}},Pa=class e extends Gr{constructor(e=1,t=1,n=1,r=1){super(),this.type=`PlaneGeometry`,this.parameters={width:e,height:t,widthSegments:n,heightSegments:r};let i=e/2,a=t/2,o=Math.floor(n),s=Math.floor(r),c=o+1,l=s+1,u=e/o,d=t/s,f=[],p=[],m=[],h=[];for(let e=0;e<l;e++){let t=e*d-a;for(let n=0;n<c;n++){let r=n*u-i;p.push(r,-t,0),m.push(0,0,1),h.push(n/o),h.push(1-e/s)}}for(let e=0;e<s;e++)for(let t=0;t<o;t++){let n=t+c*e,r=t+c*(e+1),i=t+1+c*(e+1),a=t+1+c*e;f.push(n,r,a),f.push(r,i,a)}this.setIndex(f),this.setAttribute(`position`,new Lr(p,3)),this.setAttribute(`normal`,new Lr(m,3)),this.setAttribute(`uv`,new Lr(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.widthSegments,t.heightSegments)}},Fa=class extends wr{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type=`MeshStandardMaterial`,this.defines={STANDARD:``},this.color=new B(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new B(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new L(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Bn,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:``},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Ia=class extends Fa{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:``,PHYSICAL:``},this.type=`MeshPhysicalMaterial`,this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new L(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,`reflectivity`,{get:function(){return I(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new B(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new B(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new B(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:``,PHYSICAL:``},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}},La=class extends wr{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type=`MeshDepthMaterial`,this.depthPacking=We,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},Ra=class extends wr{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type=`MeshDistanceMaterial`,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}};function za(e,t){return!e||e.constructor===t?e:typeof t.BYTES_PER_ELEMENT==`number`?new t(e):Array.prototype.slice.call(e)}function Ba(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Va(e){function t(t,n){return e[t]-e[n]}let n=e.length,r=Array(n);for(let e=0;e!==n;++e)r[e]=e;return r.sort(t),r}function Ha(e,t,n){let r=e.length,i=new e.constructor(r);for(let a=0,o=0;o!==r;++a){let r=n[a]*t;for(let n=0;n!==t;++n)i[o++]=e[r+n]}return i}function Ua(e,t,n,r){let i=1,a=e[0];for(;a!==void 0&&a[r]===void 0;)a=e[i++];if(a===void 0)return;let o=a[r];if(o!==void 0)if(Array.isArray(o))do o=a[r],o!==void 0&&(t.push(a.time),n.push(...o)),a=e[i++];while(a!==void 0);else if(o.toArray!==void 0)do o=a[r],o!==void 0&&(t.push(a.time),o.toArray(n,n.length)),a=e[i++];while(a!==void 0);else do o=a[r],o!==void 0&&(t.push(a.time),n.push(o)),a=e[i++];while(a!==void 0)}var Wa=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r===void 0?new t.constructor(n):r,this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],i=t[n-1];validate_interval:{seek:{let a;linear_scan:{forward_scan:if(!(e<r)){for(let a=n+2;;){if(r===void 0){if(e<i)break forward_scan;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(i=r,r=t[++n],e<r)break seek}a=t.length;break linear_scan}if(!(e>=i)){let o=t[1];e<o&&(n=2,i=o);for(let a=n-2;;){if(i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===a)break;if(r=i,i=t[--n-1],e>=i)break seek}a=n,n=0;break linear_scan}break validate_interval}for(;n<a;){let r=n+a>>>1;e<t[r]?a=r:n=r+1}if(r=t[n],i=t[n-1],i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(r===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,i,r)}return this.interpolate_(n,i,e,r)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r;for(let e=0;e!==r;++e)t[e]=n[i+e];return t}interpolate_(){throw Error(`call to abstract method`)}intervalChanged_(){}},Ga=class extends Wa{constructor(e,t,n,r){super(e,t,n,r),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:ze,endingEnd:ze}}intervalChanged_(e,t,n){let r=this.parameterPositions,i=e-2,a=e+1,o=r[i],s=r[a];if(o===void 0)switch(this.getSettings_().endingStart){case Be:i=e,o=2*t-n;break;case Ve:i=r.length-2,o=t+r[i]-r[i+1];break;default:i=e,o=n}if(s===void 0)switch(this.getSettings_().endingEnd){case Be:a=e,s=2*n-t;break;case Ve:a=1,s=n+r[1]-r[0];break;default:a=e-1,s=t}let c=(n-t)*.5,l=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(s-n),this._offsetPrev=i*l,this._offsetNext=a*l}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,p=(n-t)/(r-t),m=p*p,h=m*p,g=-d*h+2*d*m-d*p,_=(1+d)*h+(-1.5-2*d)*m+(-.5+d)*p+1,v=(-1-f)*h+(1.5+f)*m+.5*p,y=f*h-f*m;for(let e=0;e!==o;++e)i[e]=g*a[l+e]+_*a[c+e]+v*a[s+e]+y*a[u+e];return i}},Ka=class extends Wa{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=(n-t)/(r-t),u=1-l;for(let e=0;e!==o;++e)i[e]=a[c+e]*u+a[s+e]*l;return i}},qa=class extends Wa{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e){return this.copySampleValue_(e-1)}},Ja=class{constructor(e,t,n,r){if(e===void 0)throw Error(`THREE.KeyframeTrack: track name is undefined`);if(t===void 0||t.length===0)throw Error(`THREE.KeyframeTrack: no keyframes in track named `+e);this.name=e,this.times=za(t,this.TimeBufferType),this.values=za(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:za(e.times,Array),values:za(e.values,Array)};let t=e.getInterpolation();t!==e.DefaultInterpolation&&(n.interpolation=t)}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new qa(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new Ka(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Ga(this.times,this.values,this.getValueSize(),e)}setInterpolation(e){let t;switch(e){case Ie:t=this.InterpolantFactoryMethodDiscrete;break;case Le:t=this.InterpolantFactoryMethodLinear;break;case Re:t=this.InterpolantFactoryMethodSmooth;break}if(t===void 0){let t=`unsupported interpolation for `+this.ValueTypeName+` keyframe track named `+this.name;if(this.createInterpolant===void 0)if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(t);return console.warn(`THREE.KeyframeTrack:`,t),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return Ie;case this.InterpolantFactoryMethodLinear:return Le;case this.InterpolantFactoryMethodSmooth:return Re}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]*=e}return this}trim(e,t){let n=this.times,r=n.length,i=0,a=r-1;for(;i!==r&&n[i]<e;)++i;for(;a!==-1&&n[a]>t;)--a;if(++a,i!==0||a!==r){i>=a&&(a=Math.max(a,1),i=a-1);let e=this.getValueSize();this.times=n.slice(i,a),this.values=this.values.slice(i*e,a*e)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(console.error(`THREE.KeyframeTrack: Invalid value size in track.`,this),e=!1);let n=this.times,r=this.values,i=n.length;i===0&&(console.error(`THREE.KeyframeTrack: Track is empty.`,this),e=!1);let a=null;for(let t=0;t!==i;t++){let r=n[t];if(typeof r==`number`&&isNaN(r)){console.error(`THREE.KeyframeTrack: Time is not a valid number.`,this,t,r),e=!1;break}if(a!==null&&a>r){console.error(`THREE.KeyframeTrack: Out of order keys.`,this,t,r,a),e=!1;break}a=r}if(r!==void 0&&Ba(r))for(let t=0,n=r.length;t!==n;++t){let n=r[t];if(isNaN(n)){console.error(`THREE.KeyframeTrack: Value is not a valid number.`,this,t,n),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===Re,i=e.length-1,a=1;for(let o=1;o<i;++o){let i=!1,s=e[o];if(s!==e[o+1]&&(o!==1||s!==e[0]))if(r)i=!0;else{let e=o*n,r=e-n,a=e+n;for(let o=0;o!==n;++o){let n=t[e+o];if(n!==t[r+o]||n!==t[a+o]){i=!0;break}}}if(i){if(o!==a){e[a]=e[o];let r=o*n,i=a*n;for(let e=0;e!==n;++e)t[i+e]=t[r+e]}++a}}if(i>0){e[a]=e[i];for(let e=i*n,r=a*n,o=0;o!==n;++o)t[r+o]=t[e+o];++a}return a===e.length?(this.times=e,this.values=t):(this.times=e.slice(0,a),this.values=t.slice(0,a*n)),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}};Ja.prototype.ValueTypeName=``,Ja.prototype.TimeBufferType=Float32Array,Ja.prototype.ValueBufferType=Float32Array,Ja.prototype.DefaultInterpolation=Le;var Ya=class extends Ja{constructor(e,t,n){super(e,t,n)}};Ya.prototype.ValueTypeName=`bool`,Ya.prototype.ValueBufferType=Array,Ya.prototype.DefaultInterpolation=Ie,Ya.prototype.InterpolantFactoryMethodLinear=void 0,Ya.prototype.InterpolantFactoryMethodSmooth=void 0;var Xa=class extends Ja{constructor(e,t,n,r){super(e,t,n,r)}};Xa.prototype.ValueTypeName=`color`;var Za=class extends Ja{constructor(e,t,n,r){super(e,t,n,r)}};Za.prototype.ValueTypeName=`number`;var Qa=class extends Wa{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=(n-t)/(r-t),c=e*o;for(let e=c+o;c!==e;c+=4)en.slerpFlat(i,0,a,c-o,a,c,s);return i}},$a=class extends Ja{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new Qa(this.times,this.values,this.getValueSize(),e)}};$a.prototype.ValueTypeName=`quaternion`,$a.prototype.InterpolantFactoryMethodSmooth=void 0;var eo=class extends Ja{constructor(e,t,n){super(e,t,n)}};eo.prototype.ValueTypeName=`string`,eo.prototype.ValueBufferType=Array,eo.prototype.DefaultInterpolation=Ie,eo.prototype.InterpolantFactoryMethodLinear=void 0,eo.prototype.InterpolantFactoryMethodSmooth=void 0;var to=class extends Ja{constructor(e,t,n,r){super(e,t,n,r)}};to.prototype.ValueTypeName=`vector`;var no=class{constructor(e=``,t=-1,n=[],r=He){this.name=e,this.tracks=n,this.duration=t,this.blendMode=r,this.uuid=it(),this.duration<0&&this.resetDuration()}static parse(e){let t=[],n=e.tracks,r=1/(e.fps||1);for(let e=0,i=n.length;e!==i;++e)t.push(io(n[e]).scale(r));let i=new this(e.name,e.duration,t,e.blendMode);return i.uuid=e.uuid,i}static toJSON(e){let t=[],n=e.tracks,r={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let e=0,r=n.length;e!==r;++e)t.push(Ja.toJSON(n[e]));return r}static CreateFromMorphTargetSequence(e,t,n,r){let i=t.length,a=[];for(let e=0;e<i;e++){let o=[],s=[];o.push((e+i-1)%i,e,(e+1)%i),s.push(0,1,0);let c=Va(o);o=Ha(o,1,c),s=Ha(s,1,c),!r&&o[0]===0&&(o.push(i),s.push(s[0])),a.push(new Za(`.morphTargetInfluences[`+t[e].name+`]`,o,s).scale(1/n))}return new this(e,-1,a)}static findByName(e,t){let n=e;if(!Array.isArray(e)){let t=e;n=t.geometry&&t.geometry.animations||t.animations}for(let e=0;e<n.length;e++)if(n[e].name===t)return n[e];return null}static CreateClipsFromMorphTargetSequences(e,t,n){let r={},i=/^([\w-]*?)([\d]+)$/;for(let t=0,n=e.length;t<n;t++){let n=e[t],a=n.name.match(i);if(a&&a.length>1){let e=a[1],t=r[e];t||(r[e]=t=[]),t.push(n)}}let a=[];for(let e in r)a.push(this.CreateFromMorphTargetSequence(e,r[e],t,n));return a}static parseAnimation(e,t){if(console.warn(`THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185`),!e)return console.error(`THREE.AnimationClip: No animation in JSONLoader data.`),null;let n=function(e,t,n,r,i){if(n.length!==0){let a=[],o=[];Ua(n,a,o,r),a.length!==0&&i.push(new e(t,a,o))}},r=[],i=e.name||`default`,a=e.fps||30,o=e.blendMode,s=e.length||-1,c=e.hierarchy||[];for(let e=0;e<c.length;e++){let i=c[e].keys;if(!(!i||i.length===0))if(i[0].morphTargets){let e={},t;for(t=0;t<i.length;t++)if(i[t].morphTargets)for(let n=0;n<i[t].morphTargets.length;n++)e[i[t].morphTargets[n]]=-1;for(let n in e){let e=[],a=[];for(let r=0;r!==i[t].morphTargets.length;++r){let r=i[t];e.push(r.time),a.push(+(r.morphTarget===n))}r.push(new Za(`.morphTargetInfluence[`+n+`]`,e,a))}s=e.length*a}else{let a=`.bones[`+t[e].name+`]`;n(to,a+`.position`,i,`pos`,r),n($a,a+`.quaternion`,i,`rot`,r),n(to,a+`.scale`,i,`scl`,r)}}return r.length===0?null:new this(i,s,r,o)}resetDuration(){let e=this.tracks,t=0;for(let n=0,r=e.length;n!==r;++n){let e=this.tracks[n];t=Math.max(t,e.times[e.times.length-1])}return this.duration=t,this}trim(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].trim(0,this.duration);return this}validate(){let e=!0;for(let t=0;t<this.tracks.length;t++)e&&=this.tracks[t].validate();return e}optimize(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].optimize();return this}clone(){let e=[];for(let t=0;t<this.tracks.length;t++)e.push(this.tracks[t].clone());return new this.constructor(this.name,this.duration,e,this.blendMode)}toJSON(){return this.constructor.toJSON(this)}};function ro(e){switch(e.toLowerCase()){case`scalar`:case`double`:case`float`:case`number`:case`integer`:return Za;case`vector`:case`vector2`:case`vector3`:case`vector4`:return to;case`color`:return Xa;case`quaternion`:return $a;case`bool`:case`boolean`:return Ya;case`string`:return eo}throw Error(`THREE.KeyframeTrack: Unsupported typeName: `+e)}function io(e){if(e.type===void 0)throw Error(`THREE.KeyframeTrack: track type undefined, can not parse`);let t=ro(e.type);if(e.times===void 0){let t=[],n=[];Ua(e.keys,t,n,`value`),e.times=t,e.values=n}return t.parse===void 0?new t(e.name,e.times,e.values,e.interpolation):t.parse(e)}var ao={enabled:!1,files:{},add:function(e,t){this.enabled!==!1&&(this.files[e]=t)},get:function(e){if(this.enabled!==!1)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}},oo=class{constructor(e,t,n){let r=this,i=!1,a=0,o=0,s,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this.itemStart=function(e){o++,i===!1&&r.onStart!==void 0&&r.onStart(e,a,o),i=!0},this.itemEnd=function(e){a++,r.onProgress!==void 0&&r.onProgress(e,a,o),a===o&&(i=!1,r.onLoad!==void 0&&r.onLoad())},this.itemError=function(e){r.onError!==void 0&&r.onError(e)},this.resolveURL=function(e){return s?s(e):e},this.setURLModifier=function(e){return s=e,this},this.addHandler=function(e,t){return c.push(e,t),this},this.removeHandler=function(e){let t=c.indexOf(e);return t!==-1&&c.splice(t,2),this},this.getHandler=function(e){for(let t=0,n=c.length;t<n;t+=2){let n=c[t],r=c[t+1];if(n.global&&(n.lastIndex=0),n.test(e))return r}return null}}},so=new oo,co=class{constructor(e){this.manager=e===void 0?so:e,this.crossOrigin=`anonymous`,this.withCredentials=!1,this.path=``,this.resourcePath=``,this.requestHeader={}}load(){}loadAsync(e,t){let n=this;return new Promise(function(r,i){n.load(e,r,t,i)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}};co.DEFAULT_MATERIAL_NAME=`__DEFAULT`;var lo={},uo=class extends Error{constructor(e,t){super(e),this.response=t}},fo=class extends co{constructor(e){super(e),this.mimeType=``,this.responseType=``}load(e,t,n,r){e===void 0&&(e=``),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=ao.get(e);if(i!==void 0)return this.manager.itemStart(e),setTimeout(()=>{t&&t(i),this.manager.itemEnd(e)},0),i;if(lo[e]!==void 0){lo[e].push({onLoad:t,onProgress:n,onError:r});return}lo[e]=[],lo[e].push({onLoad:t,onProgress:n,onError:r});let a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?`include`:`same-origin`}),o=this.mimeType,s=this.responseType;fetch(a).then(t=>{if(t.status===200||t.status===0){if(t.status===0&&console.warn(`THREE.FileLoader: HTTP Status 0 received.`),typeof ReadableStream>`u`||t.body===void 0||t.body.getReader===void 0)return t;let n=lo[e],r=t.body.getReader(),i=t.headers.get(`X-File-Size`)||t.headers.get(`Content-Length`),a=i?parseInt(i):0,o=a!==0,s=0,c=new ReadableStream({start(e){t();function t(){r.read().then(({done:r,value:i})=>{if(r)e.close();else{s+=i.byteLength;let r=new ProgressEvent(`progress`,{lengthComputable:o,loaded:s,total:a});for(let e=0,t=n.length;e<t;e++){let t=n[e];t.onProgress&&t.onProgress(r)}e.enqueue(i),t()}},t=>{e.error(t)})}}});return new Response(c)}else throw new uo(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`,t)}).then(e=>{switch(s){case`arraybuffer`:return e.arrayBuffer();case`blob`:return e.blob();case`document`:return e.text().then(e=>new DOMParser().parseFromString(e,o));case`json`:return e.json();default:if(o===``)return e.text();{let t=/charset="?([^;"\s]*)"?/i.exec(o),n=t&&t[1]?t[1].toLowerCase():void 0,r=new TextDecoder(n);return e.arrayBuffer().then(e=>r.decode(e))}}}).then(t=>{ao.add(e,t);let n=lo[e];delete lo[e];for(let e=0,r=n.length;e<r;e++){let r=n[e];r.onLoad&&r.onLoad(t)}}).catch(t=>{let n=lo[e];if(n===void 0)throw this.manager.itemError(e),t;delete lo[e];for(let e=0,r=n.length;e<r;e++){let r=n[e];r.onError&&r.onError(t)}this.manager.itemError(e)}).finally(()=>{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}},po=class extends co{constructor(e){super(e)}load(e,t,n,r){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=this,a=ao.get(e);if(a!==void 0)return i.manager.itemStart(e),setTimeout(function(){t&&t(a),i.manager.itemEnd(e)},0),a;let o=kt(`img`);function s(){l(),ao.add(e,this),t&&t(this),i.manager.itemEnd(e)}function c(t){l(),r&&r(t),i.manager.itemError(e),i.manager.itemEnd(e)}function l(){o.removeEventListener(`load`,s,!1),o.removeEventListener(`error`,c,!1)}return o.addEventListener(`load`,s,!1),o.addEventListener(`error`,c,!1),e.slice(0,5)!==`data:`&&this.crossOrigin!==void 0&&(o.crossOrigin=this.crossOrigin),i.manager.itemStart(e),o.src=e,o}},mo=class extends co{constructor(e){super(e)}load(e,t,n,r){let i=this,a=new Ui,o=new fo(this.manager);return o.setResponseType(`arraybuffer`),o.setRequestHeader(this.requestHeader),o.setPath(this.path),o.setWithCredentials(i.withCredentials),o.load(e,function(e){let n;try{n=i.parse(e)}catch(e){if(r!==void 0)r(e);else{console.error(e);return}}n.image===void 0?n.data!==void 0&&(a.image.width=n.width,a.image.height=n.height,a.image.data=n.data):a.image=n.image,a.wrapS=n.wrapS===void 0?s:n.wrapS,a.wrapT=n.wrapT===void 0?s:n.wrapT,a.magFilter=n.magFilter===void 0?f:n.magFilter,a.minFilter=n.minFilter===void 0?f:n.minFilter,a.anisotropy=n.anisotropy===void 0?1:n.anisotropy,n.colorSpace!==void 0&&(a.colorSpace=n.colorSpace),n.flipY!==void 0&&(a.flipY=n.flipY),n.format!==void 0&&(a.format=n.format),n.type!==void 0&&(a.type=n.type),n.mipmaps!==void 0&&(a.mipmaps=n.mipmaps,a.minFilter=m),n.mipmapCount===1&&(a.minFilter=f),n.generateMipmaps!==void 0&&(a.generateMipmaps=n.generateMipmaps),a.needsUpdate=!0,t&&t(a,n)},n,r),a}},ho=class extends co{constructor(e){super(e)}load(e,t,n,r){let i=new Jt,a=new po(this.manager);return a.setCrossOrigin(this.crossOrigin),a.setPath(this.path),a.load(e,function(e){i.image=e,i.needsUpdate=!0,t!==void 0&&t(i)},n,r),i}},go=class extends rr{constructor(e,t=1){super(),this.isLight=!0,this.type=`Light`,this.color=new B(e),this.intensity=t}dispose(){}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){let t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,this.groundColor!==void 0&&(t.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(t.object.distance=this.distance),this.angle!==void 0&&(t.object.angle=this.angle),this.decay!==void 0&&(t.object.decay=this.decay),this.penumbra!==void 0&&(t.object.penumbra=this.penumbra),this.shadow!==void 0&&(t.object.shadow=this.shadow.toJSON()),this.target!==void 0&&(t.object.target=this.target.uuid),t}},_o=class extends go{constructor(e,t,n){super(e,n),this.isHemisphereLight=!0,this.type=`HemisphereLight`,this.position.copy(rr.DEFAULT_UP),this.updateMatrix(),this.groundColor=new B(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}},vo=new z,yo=new R,bo=new R,xo=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new L(512,512),this.mapType=h,this.map=null,this.mapPass=null,this.matrix=new z,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new ca,this._frameExtents=new L(1,1),this._viewportCount=1,this._viewports=[new Yt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,n=this.matrix;yo.setFromMatrixPosition(e.matrixWorld),t.position.copy(yo),bo.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(bo),t.updateMatrixWorld(),vo.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(vo),n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(vo)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){let e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}},So=class extends xo{constructor(){super(new yi(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){let t=this.camera,n=rt*2*e.angle*this.focus,r=this.mapSize.width/this.mapSize.height,i=e.distance||t.far;(n!==t.fov||r!==t.aspect||i!==t.far)&&(t.fov=n,t.aspect=r,t.far=i,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}},Co=class extends go{constructor(e,t,n=0,r=Math.PI/3,i=0,a=2){super(e,t),this.isSpotLight=!0,this.type=`SpotLight`,this.position.copy(rr.DEFAULT_UP),this.updateMatrix(),this.target=new rr,this.distance=n,this.angle=r,this.penumbra=i,this.decay=a,this.map=null,this.shadow=new So}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}},wo=new z,To=new R,Eo=new R,Do=class extends xo{constructor(){super(new yi(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new L(4,2),this._viewportCount=6,this._viewports=[new Yt(2,1,1,1),new Yt(0,1,1,1),new Yt(3,1,1,1),new Yt(1,1,1,1),new Yt(3,0,1,1),new Yt(1,0,1,1)],this._cubeDirections=[new R(1,0,0),new R(-1,0,0),new R(0,0,1),new R(0,0,-1),new R(0,1,0),new R(0,-1,0)],this._cubeUps=[new R(0,1,0),new R(0,1,0),new R(0,1,0),new R(0,1,0),new R(0,0,1),new R(0,0,-1)]}updateMatrices(e,t=0){let n=this.camera,r=this.matrix,i=e.distance||n.far;i!==n.far&&(n.far=i,n.updateProjectionMatrix()),To.setFromMatrixPosition(e.matrixWorld),n.position.copy(To),Eo.copy(n.position),Eo.add(this._cubeDirections[t]),n.up.copy(this._cubeUps[t]),n.lookAt(Eo),n.updateMatrixWorld(),r.makeTranslation(-To.x,-To.y,-To.z),wo.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(wo)}},Oo=class extends go{constructor(e,t,n=0,r=2){super(e,t),this.isPointLight=!0,this.type=`PointLight`,this.distance=n,this.decay=r,this.shadow=new Do}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}},ko=class extends hi{constructor(e=-1,t=1,n=1,r=-1,i=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type=`OrthographicCamera`,this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=r,this.near=i,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,r,i,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2,i=n-e,a=n+e,o=r+t,s=r-t;if(this.view!==null&&this.view.enabled){let e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;i+=e*this.view.offsetX,a=i+e*this.view.width,o-=t*this.view.offsetY,s=o-t*this.view.height}this.projectionMatrix.makeOrthographic(i,a,o,s,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},Ao=class extends xo{constructor(){super(new ko(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},jo=class extends go{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type=`DirectionalLight`,this.position.copy(rr.DEFAULT_UP),this.updateMatrix(),this.target=new rr,this.shadow=new Ao}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}},Mo=class extends go{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type=`AmbientLight`}},No=class{static extractUrlBase(e){let t=e.lastIndexOf(`/`);return t===-1?`./`:e.slice(0,t+1)}static resolveURL(e,t){return typeof e!=`string`||e===``?``:(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,`$1`)),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}},Po=class extends co{constructor(e){super(e),this.isImageBitmapLoader=!0,typeof createImageBitmap>`u`&&console.warn(`THREE.ImageBitmapLoader: createImageBitmap() not supported.`),typeof fetch>`u`&&console.warn(`THREE.ImageBitmapLoader: fetch() not supported.`),this.options={premultiplyAlpha:`none`}}setOptions(e){return this.options=e,this}load(e,t,n,r){e===void 0&&(e=``),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=this,a=ao.get(e);if(a!==void 0){if(i.manager.itemStart(e),a.then){a.then(n=>{t&&t(n),i.manager.itemEnd(e)}).catch(e=>{r&&r(e)});return}return setTimeout(function(){t&&t(a),i.manager.itemEnd(e)},0),a}let o={};o.credentials=this.crossOrigin===`anonymous`?`same-origin`:`include`,o.headers=this.requestHeader;let s=fetch(e,o).then(function(e){return e.blob()}).then(function(e){return createImageBitmap(e,Object.assign(i.options,{colorSpaceConversion:`none`}))}).then(function(n){return ao.add(e,n),t&&t(n),i.manager.itemEnd(e),n}).catch(function(t){r&&r(t),ao.remove(e),i.manager.itemError(e),i.manager.itemEnd(e)});ao.add(e,s),i.manager.itemStart(e)}},Fo=class extends yi{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},Io=class{constructor(e,t,n){this.binding=e,this.valueSize=n;let r,i,a;switch(t){case`quaternion`:r=this._slerp,i=this._slerpAdditive,a=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(n*6),this._workIndex=5;break;case`string`:case`bool`:r=this._select,i=this._select,a=this._setAdditiveIdentityOther,this.buffer=Array(n*5);break;default:r=this._lerp,i=this._lerpAdditive,a=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(n*5)}this._mixBufferRegion=r,this._mixBufferRegionAdditive=i,this._setIdentity=a,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){let n=this.buffer,r=this.valueSize,i=e*r+r,a=this.cumulativeWeight;if(a===0){for(let e=0;e!==r;++e)n[i+e]=n[e];a=t}else{a+=t;let e=t/a;this._mixBufferRegion(n,i,0,e,r)}this.cumulativeWeight=a}accumulateAdditive(e){let t=this.buffer,n=this.valueSize,r=n*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,r,0,e,n),this.cumulativeWeightAdditive+=e}apply(e){let t=this.valueSize,n=this.buffer,r=e*t+t,i=this.cumulativeWeight,a=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,i<1){let e=t*this._origIndex;this._mixBufferRegion(n,r,e,1-i,t)}a>0&&this._mixBufferRegionAdditive(n,r,this._addIndex*t,1,t);for(let e=t,i=t+t;e!==i;++e)if(n[e]!==n[e+t]){o.setValue(n,r);break}}saveOriginalState(){let e=this.binding,t=this.buffer,n=this.valueSize,r=n*this._origIndex;e.getValue(t,r);for(let e=n,i=r;e!==i;++e)t[e]=t[r+e%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){let e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n<t;n++)this.buffer[n]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){let e=this._origIndex*this.valueSize,t=this._addIndex*this.valueSize;for(let n=0;n<this.valueSize;n++)this.buffer[t+n]=this.buffer[e+n]}_select(e,t,n,r,i){if(r>=.5)for(let r=0;r!==i;++r)e[t+r]=e[n+r]}_slerp(e,t,n,r){en.slerpFlat(e,t,e,t,e,n,r)}_slerpAdditive(e,t,n,r,i){let a=this._workIndex*i;en.multiplyQuaternionsFlat(e,a,e,t,e,n),en.slerpFlat(e,t,e,t,e,a,r)}_lerp(e,t,n,r,i){let a=1-r;for(let o=0;o!==i;++o){let i=t+o;e[i]=e[i]*a+e[n+o]*r}}_lerpAdditive(e,t,n,r,i){for(let a=0;a!==i;++a){let i=t+a;e[i]=e[i]+e[n+a]*r}}},Lo=`\\[\\]\\.:\\/`,Ro=RegExp(`[`+Lo+`]`,`g`),zo=`[^`+Lo+`]`,Bo=`[^`+Lo.replace(`\\.`,``)+`]`,Vo=`((?:WC+[\\/:])*)`.replace(`WC`,zo),Ho=`(WCOD+)?`.replace(`WCOD`,Bo),Uo=`(?:\\.(WC+)(?:\\[(.+)\\])?)?`.replace(`WC`,zo),Wo=`\\.(WC+)(?:\\[(.+)\\])?`.replace(`WC`,zo),Go=RegExp(`^`+Vo+Ho+Uo+Wo+`$`),Ko=[`material`,`materials`,`bones`,`map`],qo=class{constructor(e,t,n){let r=n||Jo.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,i=n.length;r!==i;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},Jo=class e{constructor(t,n,r){this.path=n,this.parsedPath=r||e.parseTrackName(n),this.node=e.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,n,r){return t&&t.isAnimationObjectGroup?new e.Composite(t,n,r):new e(t,n,r)}static sanitizeNodeName(e){return e.replace(/\s/g,`_`).replace(Ro,``)}static parseTrackName(e){let t=Go.exec(e);if(t===null)throw Error(`PropertyBinding: Cannot parse trackName: `+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(`.`);if(r!==void 0&&r!==-1){let e=n.nodeName.substring(r+1);Ko.indexOf(e)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=e)}if(n.propertyName===null||n.propertyName.length===0)throw Error(`PropertyBinding: can not parse propertyName from trackName: `+e);return n}static findNode(e,t){if(t===void 0||t===``||t===`.`||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(e){for(let r=0;r<e.length;r++){let i=e[r];if(i.name===t||i.uuid===t)return i;let a=n(i.children);if(a)return a}return null},r=n(e.children);if(r)return r}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)e[t++]=n[r]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let t=this.node,n=this.parsedPath,r=n.objectName,i=n.propertyName,a=n.propertyIndex;if(t||(t=e.findNode(this.rootNode,n.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t){console.warn(`THREE.PropertyBinding: No target node found for track: `+this.path+`.`);return}if(r){let e=n.objectIndex;switch(r){case`materials`:if(!t.material){console.error(`THREE.PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.materials){console.error(`THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.`,this);return}t=t.material.materials;break;case`bones`:if(!t.skeleton){console.error(`THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.`,this);return}t=t.skeleton.bones;for(let n=0;n<t.length;n++)if(t[n].name===e){e=n;break}break;case`map`:if(`map`in t){t=t.map;break}if(!t.material){console.error(`THREE.PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.map){console.error(`THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.`,this);return}t=t.material.map;break;default:if(t[r]===void 0){console.error(`THREE.PropertyBinding: Can not bind to objectName of node undefined.`,this);return}t=t[r]}if(e!==void 0){if(t[e]===void 0){console.error(`THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.`,this,t);return}t=t[e]}}let o=t[i];if(o===void 0){let e=n.nodeName;console.error(`THREE.PropertyBinding: Trying to update property for track: `+e+`.`+i+` but it wasn't found.`,t);return}let s=this.Versioning.None;this.targetObject=t,t.isMaterial===!0?s=this.Versioning.NeedsUpdate:t.isObject3D===!0&&(s=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(a!==void 0){if(i===`morphTargetInfluences`){if(!t.geometry){console.error(`THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.`,this);return}if(!t.geometry.morphAttributes){console.error(`THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.`,this);return}t.morphTargetDictionary[a]!==void 0&&(a=t.morphTargetDictionary[a])}c=this.BindingType.ArrayElement,this.resolvedProperty=o,this.propertyIndex=a}else o.fromArray!==void 0&&o.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(c=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=i;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][s]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};Jo.Composite=qo,Jo.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Jo.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},Jo.prototype.GetterByBindingType=[Jo.prototype._getValue_direct,Jo.prototype._getValue_array,Jo.prototype._getValue_arrayElement,Jo.prototype._getValue_toArray],Jo.prototype.SetterByBindingTypeAndVersioning=[[Jo.prototype._setValue_direct,Jo.prototype._setValue_direct_setNeedsUpdate,Jo.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Jo.prototype._setValue_array,Jo.prototype._setValue_array_setNeedsUpdate,Jo.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Jo.prototype._setValue_arrayElement,Jo.prototype._setValue_arrayElement_setNeedsUpdate,Jo.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Jo.prototype._setValue_fromArray,Jo.prototype._setValue_fromArray_setNeedsUpdate,Jo.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];var Yo=class{constructor(e,t,n=null,r=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=r;let i=t.tracks,a=i.length,o=Array(a),s={endingStart:ze,endingEnd:ze};for(let e=0;e!==a;++e){let t=i[e].createInterpolant(null);o[e]=t,t.settings=s}this._interpolantSettings=s,this._interpolants=o,this._propertyBindings=Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=Pe,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,n=!1){if(e.fadeOut(t),this.fadeIn(t),n===!0){let n=this._clip.duration,r=e._clip.duration,i=r/n,a=n/r;e.warp(1,i,t),this.warp(a,1,t)}return this}crossFadeTo(e,t,n=!1){return e.crossFadeFrom(this,t,n)}stopFading(){let e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,n){let r=this._mixer,i=r.time,a=this.timeScale,o=this._timeScaleInterpolant;o===null&&(o=r._lendControlInterpolant(),this._timeScaleInterpolant=o);let s=o.parameterPositions,c=o.sampleValues;return s[0]=i,s[1]=i+n,c[0]=e/a,c[1]=t/a,this}stopWarping(){let e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,r){if(!this.enabled){this._updateWeight(e);return}let i=this._startTime;if(i!==null){let r=(e-i)*n;r<0||n===0?t=0:(this._startTime=null,t=n*r)}t*=this._updateTimeScale(e);let a=this._updateTime(t),o=this._updateWeight(e);if(o>0){let e=this._interpolants,t=this._propertyBindings;switch(this.blendMode){case Ue:for(let n=0,r=e.length;n!==r;++n)e[n].evaluate(a),t[n].accumulateAdditive(o);break;case He:default:for(let n=0,i=e.length;n!==i;++n)e[n].evaluate(a),t[n].accumulate(r,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let n=this._weightInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(this.stopFading(),r===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;let n=this._timeScaleInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,n=this.loop,r=this.time+e,i=this._loopCount,a=n===Fe;if(e===0)return i===-1?r:a&&(i&1)==1?t-r:r;if(n===2200){i===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));handle_stop:{if(r>=t)r=t;else if(r<0)r=0;else{this.time=r;break handle_stop}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=r,this._mixer.dispatchEvent({type:`finished`,action:this,direction:e<0?-1:1})}}else{if(i===-1&&(e>=0?(i=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),r>=t||r<0){let n=Math.floor(r/t);r-=t*n,i+=Math.abs(n);let o=this.repetitions-i;if(o<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,r=e>0?t:0,this.time=r,this._mixer.dispatchEvent({type:`finished`,action:this,direction:e>0?1:-1});else{if(o===1){let t=e<0;this._setEndings(t,!t,a)}else this._setEndings(!1,!1,a);this._loopCount=i,this.time=r,this._mixer.dispatchEvent({type:`loop`,action:this,loopDelta:n})}}else this.time=r;if(a&&(i&1)==1)return t-r}return r}_setEndings(e,t,n){let r=this._interpolantSettings;n?(r.endingStart=Be,r.endingEnd=Be):(e?r.endingStart=this.zeroSlopeAtStart?Be:ze:r.endingStart=Ve,t?r.endingEnd=this.zeroSlopeAtEnd?Be:ze:r.endingEnd=Ve)}_scheduleFading(e,t,n){let r=this._mixer,i=r.time,a=this._weightInterpolant;a===null&&(a=r._lendControlInterpolant(),this._weightInterpolant=a);let o=a.parameterPositions,s=a.sampleValues;return o[0]=i,s[0]=t,o[1]=i+e,s[1]=n,this}},Xo=new Float32Array(1),Zo=class extends $e{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){let n=e._localRoot||this._root,r=e._clip.tracks,i=r.length,a=e._propertyBindings,o=e._interpolants,s=n.uuid,c=this._bindingsByRootAndName,l=c[s];l===void 0&&(l={},c[s]=l);for(let e=0;e!==i;++e){let i=r[e],c=i.name,u=l[c];if(u!==void 0)++u.referenceCount,a[e]=u;else{if(u=a[e],u!==void 0){u._cacheIndex===null&&(++u.referenceCount,this._addInactiveBinding(u,s,c));continue}let r=t&&t._propertyBindings[e].binding.parsedPath;u=new Io(Jo.create(n,c,r),i.ValueTypeName,i.getValueSize()),++u.referenceCount,this._addInactiveBinding(u,s,c),a[e]=u}o[e].resultBuffer=u.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let t=(e._localRoot||this._root).uuid,n=e._clip.uuid,r=this._actionsByClip[n];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,n,t)}let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];n.useCount++===0&&(this._lendBinding(n),n.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];--n.useCount===0&&(n.restoreOriginalState(),this._takeBackBinding(n))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){let t=e._cacheIndex;return t!==null&&t<this._nActiveActions}_addInactiveAction(e,t,n){let r=this._actions,i=this._actionsByClip,a=i[t];if(a===void 0)a={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,i[t]=a;else{let t=a.knownActions;e._byClipCacheIndex=t.length,t.push(e)}e._cacheIndex=r.length,r.push(e),a.actionByRoot[n]=e}_removeInactiveAction(e){let t=this._actions,n=t[t.length-1],r=e._cacheIndex;n._cacheIndex=r,t[r]=n,t.pop(),e._cacheIndex=null;let i=e._clip.uuid,a=this._actionsByClip,o=a[i],s=o.knownActions,c=s[s.length-1],l=e._byClipCacheIndex;c._byClipCacheIndex=l,s[l]=c,s.pop(),e._byClipCacheIndex=null;let u=o.actionByRoot,d=(e._localRoot||this._root).uuid;delete u[d],s.length===0&&delete a[i],this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];--n.referenceCount===0&&this._removeInactiveBinding(n)}}_lendAction(e){let t=this._actions,n=e._cacheIndex,r=this._nActiveActions++,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_takeBackAction(e){let t=this._actions,n=e._cacheIndex,r=--this._nActiveActions,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_addInactiveBinding(e,t,n){let r=this._bindingsByRootAndName,i=this._bindings,a=r[t];a===void 0&&(a={},r[t]=a),a[n]=e,e._cacheIndex=i.length,i.push(e)}_removeInactiveBinding(e){let t=this._bindings,n=e.binding,r=n.rootNode.uuid,i=n.path,a=this._bindingsByRootAndName,o=a[r],s=t[t.length-1],c=e._cacheIndex;s._cacheIndex=c,t[c]=s,t.pop(),delete o[i],Object.keys(o).length===0&&delete a[r]}_lendBinding(e){let t=this._bindings,n=e._cacheIndex,r=this._nActiveBindings++,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_takeBackBinding(e){let t=this._bindings,n=e._cacheIndex,r=--this._nActiveBindings,i=t[r];e._cacheIndex=r,t[r]=e,i._cacheIndex=n,t[n]=i}_lendControlInterpolant(){let e=this._controlInterpolants,t=this._nActiveControlInterpolants++,n=e[t];return n===void 0&&(n=new Ka(new Float32Array(2),new Float32Array(2),1,Xo),n.__cacheIndex=t,e[t]=n),n}_takeBackControlInterpolant(e){let t=this._controlInterpolants,n=e.__cacheIndex,r=--this._nActiveControlInterpolants,i=t[r];e.__cacheIndex=r,t[r]=e,i.__cacheIndex=n,t[n]=i}clipAction(e,t,n){let r=t||this._root,i=r.uuid,a=typeof e==`string`?no.findByName(r,e):e,o=a===null?e:a.uuid,s=this._actionsByClip[o],c=null;if(n===void 0&&(n=a===null?He:a.blendMode),s!==void 0){let e=s.actionByRoot[i];if(e!==void 0&&e.blendMode===n)return e;c=s.knownActions[0],a===null&&(a=c._clip)}if(a===null)return null;let l=new Yo(this,a,t,n);return this._bindAction(l,c),this._addInactiveAction(l,o,i),l}existingAction(e,t){let n=t||this._root,r=n.uuid,i=typeof e==`string`?no.findByName(n,e):e,a=i?i.uuid:e,o=this._actionsByClip[a];return o===void 0?null:o.actionByRoot[r]||null}stopAllAction(){let e=this._actions,t=this._nActiveActions;for(let n=t-1;n>=0;--n)e[n].stop();return this}update(e){e*=this.timeScale;let t=this._actions,n=this._nActiveActions,r=this.time+=e,i=Math.sign(e),a=this._accuIndex^=1;for(let o=0;o!==n;++o)t[o]._update(r,e,i,a);let o=this._bindings,s=this._nActiveBindings;for(let e=0;e!==s;++e)o[e].apply(a);return this}setTime(e){this.time=0;for(let e=0;e<this._actions.length;e++)this._actions[e].time=0;return this.update(e)}getRoot(){return this._root}uncacheClip(e){let t=this._actions,n=e.uuid,r=this._actionsByClip,i=r[n];if(i!==void 0){let e=i.knownActions;for(let n=0,r=e.length;n!==r;++n){let r=e[n];this._deactivateAction(r);let i=r._cacheIndex,a=t[t.length-1];r._cacheIndex=null,r._byClipCacheIndex=null,a._cacheIndex=i,t[i]=a,t.pop(),this._removeInactiveBindingsForAction(r)}delete r[n]}}uncacheRoot(e){let t=e.uuid,n=this._actionsByClip;for(let e in n){let r=n[e].actionByRoot[t];r!==void 0&&(this._deactivateAction(r),this._removeInactiveAction(r))}let r=this._bindingsByRootAndName[t];if(r!==void 0)for(let e in r){let t=r[e];t.restoreOriginalState(),this._removeInactiveBinding(t)}}uncacheAction(e,t){let n=this.existingAction(e,t);n!==null&&(this._deactivateAction(n),this._removeInactiveAction(n))}},Qo=class{constructor(e=1,t=0,n=0){this.radius=e,this.phi=t,this.theta=n}set(e,t,n){return this.radius=e,this.phi=t,this.theta=n,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){let e=1e-6;return this.phi=I(this.phi,e,Math.PI-e),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+t*t+n*n),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,n),this.phi=Math.acos(I(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}},$o=new R,es=new z,ts=new z,ns=class extends xa{constructor(e){let t=rs(e),n=new Gr,r=[],i=[],a=new B(0,0,1),o=new B(0,1,0);for(let e=0;e<t.length;e++){let n=t[e];n.parent&&n.parent.isBone&&(r.push(0,0,0),r.push(0,0,0),i.push(a.r,a.g,a.b),i.push(o.r,o.g,o.b))}n.setAttribute(`position`,new Lr(r,3)),n.setAttribute(`color`,new Lr(i,3));let s=new la({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});super(n,s),this.isSkeletonHelper=!0,this.type=`SkeletonHelper`,this.root=e,this.bones=t,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1}updateMatrixWorld(e){let t=this.bones,n=this.geometry,r=n.getAttribute(`position`);ts.copy(this.root.matrixWorld).invert();for(let e=0,n=0;e<t.length;e++){let i=t[e];i.parent&&i.parent.isBone&&(es.multiplyMatrices(ts,i.matrixWorld),$o.setFromMatrixPosition(es),r.setXYZ(n,$o.x,$o.y,$o.z),es.multiplyMatrices(ts,i.parent.matrixWorld),$o.setFromMatrixPosition(es),r.setXYZ(n+1,$o.x,$o.y,$o.z),n+=2)}n.getAttribute(`position`).needsUpdate=!0,super.updateMatrixWorld(e)}dispose(){this.geometry.dispose(),this.material.dispose()}};function rs(e){let t=[];e.isBone===!0&&t.push(e);for(let n=0;n<e.children.length;n++)t.push(...rs(e.children[n]));return t}var is=class extends xa{constructor(e=10,t=10,n=4473924,r=8947848){n=new B(n),r=new B(r);let i=t/2,a=e/t,o=e/2,s=[],c=[];for(let e=0,l=0,u=-o;e<=t;e++,u+=a){s.push(-o,0,u,o,0,u),s.push(u,0,-o,u,0,o);let t=e===i?n:r;t.toArray(c,l),l+=3,t.toArray(c,l),l+=3,t.toArray(c,l),l+=3,t.toArray(c,l),l+=3}let l=new Gr;l.setAttribute(`position`,new Lr(s,3)),l.setAttribute(`color`,new Lr(c,3));let u=new la({vertexColors:!0,toneMapped:!1});super(l,u),this.type=`GridHelper`}dispose(){this.geometry.dispose(),this.material.dispose()}},as=class extends xa{constructor(e=1){let t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],n=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],r=new Gr;r.setAttribute(`position`,new Lr(t,3)),r.setAttribute(`color`,new Lr(n,3));let i=new la({vertexColors:!0,toneMapped:!1});super(r,i),this.type=`AxesHelper`}setColors(e,t,n){let r=new B,i=this.geometry.attributes.color.array;return r.set(e),r.toArray(i,0),r.toArray(i,3),r.set(t),r.toArray(i,6),r.toArray(i,9),r.set(n),r.toArray(i,12),r.toArray(i,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}},os=class extends $e{constructor(e,t=null){super(),this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){if(e===void 0){console.warn(`THREE.Controls: connect() now requires an element.`);return}this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}};function ss(e,t,n,r){let i=cs(r);switch(n){case D:return e*t;case ne:return e*t/i.components*i.byteLength;case re:return e*t/i.components*i.byteLength;case A:return e*t*2/i.components*i.byteLength;case ie:return e*t*2/i.components*i.byteLength;case O:return e*t*3/i.components*i.byteLength;case k:return e*t*4/i.components*i.byteLength;case ae:return e*t*4/i.components*i.byteLength;case oe:case se:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case ce:case le:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case de:case pe:return Math.max(e,16)*Math.max(t,8)/4;case ue:case fe:return Math.max(e,8)*Math.max(t,8)/2;case me:case he:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case ge:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case _e:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case ve:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case ye:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case be:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case j:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case xe:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case Se:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case Ce:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case M:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case we:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case N:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case P:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case Te:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case Ee:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case F:case De:case Oe:return Math.ceil(e/4)*Math.ceil(t/4)*16;case ke:case Ae:return Math.ceil(e/4)*Math.ceil(t/4)*8;case je:case Me:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function cs(e){switch(e){case h:case g:return{byteLength:1,components:1};case v:case _:case S:return{byteLength:2,components:1};case C:case w:return{byteLength:2,components:4};case b:case y:case x:return{byteLength:4,components:1};case E:return{byteLength:4,components:3}}throw Error(`Unknown texture type ${e}.`)}typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`register`,{detail:{revision:`176`}})),typeof window<`u`&&(window.__THREE__?console.warn(`WARNING: Multiple instances of Three.js being imported.`):window.__THREE__=`176`);function ls(){let e=null,t=!1,n=null,r=null;function i(t,a){n(t,a),r=e.requestAnimationFrame(i)}return{start:function(){t!==!0&&n!==null&&(r=e.requestAnimationFrame(i),t=!0)},stop:function(){e.cancelAnimationFrame(r),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function us(e){let t=new WeakMap;function n(t,n){let r=t.array,i=t.usage,a=r.byteLength,o=e.createBuffer();e.bindBuffer(n,o),e.bufferData(n,r,i),t.onUploadCallback();let s;if(r instanceof Float32Array)s=e.FLOAT;else if(r instanceof Uint16Array)s=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(r instanceof Int16Array)s=e.SHORT;else if(r instanceof Uint32Array)s=e.UNSIGNED_INT;else if(r instanceof Int32Array)s=e.INT;else if(r instanceof Int8Array)s=e.BYTE;else if(r instanceof Uint8Array)s=e.UNSIGNED_BYTE;else if(r instanceof Uint8ClampedArray)s=e.UNSIGNED_BYTE;else throw Error(`THREE.WebGLAttributes: Unsupported buffer data format: `+r);return{buffer:o,type:s,bytesPerElement:r.BYTES_PER_ELEMENT,version:t.version,size:a}}function r(t,n,r){let i=n.array,a=n.updateRanges;if(e.bindBuffer(r,t),a.length===0)e.bufferSubData(r,0,i);else{a.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<a.length;e++){let n=a[t],r=a[e];r.start<=n.start+n.count+1?n.count=Math.max(n.count,r.start+r.count-n.start):(++t,a[t]=r)}a.length=t+1;for(let t=0,n=a.length;t<n;t++){let n=a[t];e.bufferSubData(r,n.start*i.BYTES_PER_ELEMENT,i,n.start,n.count)}n.clearUpdateRanges()}n.onUploadCallback()}function i(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)}function a(n){n.isInterleavedBufferAttribute&&(n=n.data);let r=t.get(n);r&&(e.deleteBuffer(r.buffer),t.delete(n))}function o(e,i){if(e.isInterleavedBufferAttribute&&(e=e.data),e.isGLBufferAttribute){let n=t.get(e);(!n||n.version<e.version)&&t.set(e,{buffer:e.buffer,type:e.type,bytesPerElement:e.elementSize,version:e.version});return}let a=t.get(e);if(a===void 0)t.set(e,n(e,i));else if(a.version<e.version){if(a.size!==e.array.byteLength)throw Error(`THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.`);r(a.buffer,e,i),a.version=e.version}}return{get:i,remove:a,update:o}}var V={alphahash_fragment:`#ifdef USE_ALPHAHASH
+ if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
+#endif`,alphahash_pars_fragment:`#ifdef USE_ALPHAHASH
+ const float ALPHA_HASH_SCALE = 0.05;
+ float hash2D( vec2 value ) {
+ return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
+ }
+ float hash3D( vec3 value ) {
+ return hash2D( vec2( hash2D( value.xy ), value.z ) );
+ }
+ float getAlphaHashThreshold( vec3 position ) {
+ float maxDeriv = max(
+ length( dFdx( position.xyz ) ),
+ length( dFdy( position.xyz ) )
+ );
+ float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
+ vec2 pixScales = vec2(
+ exp2( floor( log2( pixScale ) ) ),
+ exp2( ceil( log2( pixScale ) ) )
+ );
+ vec2 alpha = vec2(
+ hash3D( floor( pixScales.x * position.xyz ) ),
+ hash3D( floor( pixScales.y * position.xyz ) )
+ );
+ float lerpFactor = fract( log2( pixScale ) );
+ float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
+ float a = min( lerpFactor, 1.0 - lerpFactor );
+ vec3 cases = vec3(
+ x * x / ( 2.0 * a * ( 1.0 - a ) ),
+ ( x - 0.5 * a ) / ( 1.0 - a ),
+ 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
+ );
+ float threshold = ( x < ( 1.0 - a ) )
+ ? ( ( x < a ) ? cases.x : cases.y )
+ : cases.z;
+ return clamp( threshold , 1.0e-6, 1.0 );
+ }
+#endif`,alphamap_fragment:`#ifdef USE_ALPHAMAP
+ diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
+#endif`,alphamap_pars_fragment:`#ifdef USE_ALPHAMAP
+ uniform sampler2D alphaMap;
+#endif`,alphatest_fragment:`#ifdef USE_ALPHATEST
+ #ifdef ALPHA_TO_COVERAGE
+ diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
+ if ( diffuseColor.a == 0.0 ) discard;
+ #else
+ if ( diffuseColor.a < alphaTest ) discard;
+ #endif
+#endif`,alphatest_pars_fragment:`#ifdef USE_ALPHATEST
+ uniform float alphaTest;
+#endif`,aomap_fragment:`#ifdef USE_AOMAP
+ float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
+ reflectedLight.indirectDiffuse *= ambientOcclusion;
+ #if defined( USE_CLEARCOAT )
+ clearcoatSpecularIndirect *= ambientOcclusion;
+ #endif
+ #if defined( USE_SHEEN )
+ sheenSpecularIndirect *= ambientOcclusion;
+ #endif
+ #if defined( USE_ENVMAP ) && defined( STANDARD )
+ float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
+ reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
+ #endif
+#endif`,aomap_pars_fragment:`#ifdef USE_AOMAP
+ uniform sampler2D aoMap;
+ uniform float aoMapIntensity;
+#endif`,batching_pars_vertex:`#ifdef USE_BATCHING
+ #if ! defined( GL_ANGLE_multi_draw )
+ #define gl_DrawID _gl_DrawID
+ uniform int _gl_DrawID;
+ #endif
+ uniform highp sampler2D batchingTexture;
+ uniform highp usampler2D batchingIdTexture;
+ mat4 getBatchingMatrix( const in float i ) {
+ int size = textureSize( batchingTexture, 0 ).x;
+ int j = int( i ) * 4;
+ int x = j % size;
+ int y = j / size;
+ vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
+ vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
+ vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
+ vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
+ return mat4( v1, v2, v3, v4 );
+ }
+ float getIndirectIndex( const in int i ) {
+ int size = textureSize( batchingIdTexture, 0 ).x;
+ int x = i % size;
+ int y = i / size;
+ return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );
+ }
+#endif
+#ifdef USE_BATCHING_COLOR
+ uniform sampler2D batchingColorTexture;
+ vec3 getBatchingColor( const in float i ) {
+ int size = textureSize( batchingColorTexture, 0 ).x;
+ int j = int( i );
+ int x = j % size;
+ int y = j / size;
+ return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;
+ }
+#endif`,batching_vertex:`#ifdef USE_BATCHING
+ mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
+#endif`,begin_vertex:`vec3 transformed = vec3( position );
+#ifdef USE_ALPHAHASH
+ vPosition = vec3( position );
+#endif`,beginnormal_vertex:`vec3 objectNormal = vec3( normal );
+#ifdef USE_TANGENT
+ vec3 objectTangent = vec3( tangent.xyz );
+#endif`,bsdfs:`float G_BlinnPhong_Implicit( ) {
+ return 0.25;
+}
+float D_BlinnPhong( const in float shininess, const in float dotNH ) {
+ return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
+}
+vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
+ vec3 halfDir = normalize( lightDir + viewDir );
+ float dotNH = saturate( dot( normal, halfDir ) );
+ float dotVH = saturate( dot( viewDir, halfDir ) );
+ vec3 F = F_Schlick( specularColor, 1.0, dotVH );
+ float G = G_BlinnPhong_Implicit( );
+ float D = D_BlinnPhong( shininess, dotNH );
+ return F * ( G * D );
+} // validated`,iridescence_fragment:`#ifdef USE_IRIDESCENCE
+ const mat3 XYZ_TO_REC709 = mat3(
+ 3.2404542, -0.9692660, 0.0556434,
+ -1.5371385, 1.8760108, -0.2040259,
+ -0.4985314, 0.0415560, 1.0572252
+ );
+ vec3 Fresnel0ToIor( vec3 fresnel0 ) {
+ vec3 sqrtF0 = sqrt( fresnel0 );
+ return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
+ }
+ vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
+ return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
+ }
+ float IorToFresnel0( float transmittedIor, float incidentIor ) {
+ return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
+ }
+ vec3 evalSensitivity( float OPD, vec3 shift ) {
+ float phase = 2.0 * PI * OPD * 1.0e-9;
+ vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
+ vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
+ vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
+ vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
+ xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );
+ xyz /= 1.0685e-7;
+ vec3 rgb = XYZ_TO_REC709 * xyz;
+ return rgb;
+ }
+ vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
+ vec3 I;
+ float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
+ float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
+ float cosTheta2Sq = 1.0 - sinTheta2Sq;
+ if ( cosTheta2Sq < 0.0 ) {
+ return vec3( 1.0 );
+ }
+ float cosTheta2 = sqrt( cosTheta2Sq );
+ float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
+ float R12 = F_Schlick( R0, 1.0, cosTheta1 );
+ float T121 = 1.0 - R12;
+ float phi12 = 0.0;
+ if ( iridescenceIOR < outsideIOR ) phi12 = PI;
+ float phi21 = PI - phi12;
+ vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
+ vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
+ vec3 phi23 = vec3( 0.0 );
+ if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
+ if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
+ if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
+ float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
+ vec3 phi = vec3( phi21 ) + phi23;
+ vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
+ vec3 r123 = sqrt( R123 );
+ vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
+ vec3 C0 = R12 + Rs;
+ I = C0;
+ vec3 Cm = Rs - T121;
+ for ( int m = 1; m <= 2; ++ m ) {
+ Cm *= r123;
+ vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
+ I += Cm * Sm;
+ }
+ return max( I, vec3( 0.0 ) );
+ }
+#endif`,bumpmap_pars_fragment:`#ifdef USE_BUMPMAP
+ uniform sampler2D bumpMap;
+ uniform float bumpScale;
+ vec2 dHdxy_fwd() {
+ vec2 dSTdx = dFdx( vBumpMapUv );
+ vec2 dSTdy = dFdy( vBumpMapUv );
+ float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
+ float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
+ float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
+ return vec2( dBx, dBy );
+ }
+ vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
+ vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
+ vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
+ vec3 vN = surf_norm;
+ vec3 R1 = cross( vSigmaY, vN );
+ vec3 R2 = cross( vN, vSigmaX );
+ float fDet = dot( vSigmaX, R1 ) * faceDirection;
+ vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
+ return normalize( abs( fDet ) * surf_norm - vGrad );
+ }
+#endif`,clipping_planes_fragment:`#if NUM_CLIPPING_PLANES > 0
+ vec4 plane;
+ #ifdef ALPHA_TO_COVERAGE
+ float distanceToPlane, distanceGradient;
+ float clipOpacity = 1.0;
+ #pragma unroll_loop_start
+ for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
+ plane = clippingPlanes[ i ];
+ distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
+ distanceGradient = fwidth( distanceToPlane ) / 2.0;
+ clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
+ if ( clipOpacity == 0.0 ) discard;
+ }
+ #pragma unroll_loop_end
+ #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
+ float unionClipOpacity = 1.0;
+ #pragma unroll_loop_start
+ for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
+ plane = clippingPlanes[ i ];
+ distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
+ distanceGradient = fwidth( distanceToPlane ) / 2.0;
+ unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
+ }
+ #pragma unroll_loop_end
+ clipOpacity *= 1.0 - unionClipOpacity;
+ #endif
+ diffuseColor.a *= clipOpacity;
+ if ( diffuseColor.a == 0.0 ) discard;
+ #else
+ #pragma unroll_loop_start
+ for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
+ plane = clippingPlanes[ i ];
+ if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
+ }
+ #pragma unroll_loop_end
+ #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
+ bool clipped = true;
+ #pragma unroll_loop_start
+ for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
+ plane = clippingPlanes[ i ];
+ clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
+ }
+ #pragma unroll_loop_end
+ if ( clipped ) discard;
+ #endif
+ #endif
+#endif`,clipping_planes_pars_fragment:`#if NUM_CLIPPING_PLANES > 0
+ varying vec3 vClipPosition;
+ uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
+#endif`,clipping_planes_pars_vertex:`#if NUM_CLIPPING_PLANES > 0
+ varying vec3 vClipPosition;
+#endif`,clipping_planes_vertex:`#if NUM_CLIPPING_PLANES > 0
+ vClipPosition = - mvPosition.xyz;
+#endif`,color_fragment:`#if defined( USE_COLOR_ALPHA )
+ diffuseColor *= vColor;
+#elif defined( USE_COLOR )
+ diffuseColor.rgb *= vColor;
+#endif`,color_pars_fragment:`#if defined( USE_COLOR_ALPHA )
+ varying vec4 vColor;
+#elif defined( USE_COLOR )
+ varying vec3 vColor;
+#endif`,color_pars_vertex:`#if defined( USE_COLOR_ALPHA )
+ varying vec4 vColor;
+#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
+ varying vec3 vColor;
+#endif`,color_vertex:`#if defined( USE_COLOR_ALPHA )
+ vColor = vec4( 1.0 );
+#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
+ vColor = vec3( 1.0 );
+#endif
+#ifdef USE_COLOR
+ vColor *= color;
+#endif
+#ifdef USE_INSTANCING_COLOR
+ vColor.xyz *= instanceColor.xyz;
+#endif
+#ifdef USE_BATCHING_COLOR
+ vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );
+ vColor.xyz *= batchingColor.xyz;
+#endif`,common:`#define PI 3.141592653589793
+#define PI2 6.283185307179586
+#define PI_HALF 1.5707963267948966
+#define RECIPROCAL_PI 0.3183098861837907
+#define RECIPROCAL_PI2 0.15915494309189535
+#define EPSILON 1e-6
+#ifndef saturate
+#define saturate( a ) clamp( a, 0.0, 1.0 )
+#endif
+#define whiteComplement( a ) ( 1.0 - saturate( a ) )
+float pow2( const in float x ) { return x*x; }
+vec3 pow2( const in vec3 x ) { return x*x; }
+float pow3( const in float x ) { return x*x*x; }
+float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
+float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
+float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
+highp float rand( const in vec2 uv ) {
+ const highp float a = 12.9898, b = 78.233, c = 43758.5453;
+ highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
+ return fract( sin( sn ) * c );
+}
+#ifdef HIGH_PRECISION
+ float precisionSafeLength( vec3 v ) { return length( v ); }
+#else
+ float precisionSafeLength( vec3 v ) {
+ float maxComponent = max3( abs( v ) );
+ return length( v / maxComponent ) * maxComponent;
+ }
+#endif
+struct IncidentLight {
+ vec3 color;
+ vec3 direction;
+ bool visible;
+};
+struct ReflectedLight {
+ vec3 directDiffuse;
+ vec3 directSpecular;
+ vec3 indirectDiffuse;
+ vec3 indirectSpecular;
+};
+#ifdef USE_ALPHAHASH
+ varying vec3 vPosition;
+#endif
+vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
+ return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
+}
+vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
+ return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
+}
+mat3 transposeMat3( const in mat3 m ) {
+ mat3 tmp;
+ tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );
+ tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );
+ tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );
+ return tmp;
+}
+bool isPerspectiveMatrix( mat4 m ) {
+ return m[ 2 ][ 3 ] == - 1.0;
+}
+vec2 equirectUv( in vec3 dir ) {
+ float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
+ float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
+ return vec2( u, v );
+}
+vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
+ return RECIPROCAL_PI * diffuseColor;
+}
+vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
+ float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
+ return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
+}
+float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
+ float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
+ return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
+} // validated`,cube_uv_reflection_fragment:`#ifdef ENVMAP_TYPE_CUBE_UV
+ #define cubeUV_minMipLevel 4.0
+ #define cubeUV_minTileSize 16.0
+ float getFace( vec3 direction ) {
+ vec3 absDirection = abs( direction );
+ float face = - 1.0;
+ if ( absDirection.x > absDirection.z ) {
+ if ( absDirection.x > absDirection.y )
+ face = direction.x > 0.0 ? 0.0 : 3.0;
+ else
+ face = direction.y > 0.0 ? 1.0 : 4.0;
+ } else {
+ if ( absDirection.z > absDirection.y )
+ face = direction.z > 0.0 ? 2.0 : 5.0;
+ else
+ face = direction.y > 0.0 ? 1.0 : 4.0;
+ }
+ return face;
+ }
+ vec2 getUV( vec3 direction, float face ) {
+ vec2 uv;
+ if ( face == 0.0 ) {
+ uv = vec2( direction.z, direction.y ) / abs( direction.x );
+ } else if ( face == 1.0 ) {
+ uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
+ } else if ( face == 2.0 ) {
+ uv = vec2( - direction.x, direction.y ) / abs( direction.z );
+ } else if ( face == 3.0 ) {
+ uv = vec2( - direction.z, direction.y ) / abs( direction.x );
+ } else if ( face == 4.0 ) {
+ uv = vec2( - direction.x, direction.z ) / abs( direction.y );
+ } else {
+ uv = vec2( direction.x, direction.y ) / abs( direction.z );
+ }
+ return 0.5 * ( uv + 1.0 );
+ }
+ vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
+ float face = getFace( direction );
+ float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
+ mipInt = max( mipInt, cubeUV_minMipLevel );
+ float faceSize = exp2( mipInt );
+ highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
+ if ( face > 2.0 ) {
+ uv.y += faceSize;
+ face -= 3.0;
+ }
+ uv.x += face * faceSize;
+ uv.x += filterInt * 3.0 * cubeUV_minTileSize;
+ uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
+ uv.x *= CUBEUV_TEXEL_WIDTH;
+ uv.y *= CUBEUV_TEXEL_HEIGHT;
+ #ifdef texture2DGradEXT
+ return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
+ #else
+ return texture2D( envMap, uv ).rgb;
+ #endif
+ }
+ #define cubeUV_r0 1.0
+ #define cubeUV_m0 - 2.0
+ #define cubeUV_r1 0.8
+ #define cubeUV_m1 - 1.0
+ #define cubeUV_r4 0.4
+ #define cubeUV_m4 2.0
+ #define cubeUV_r5 0.305
+ #define cubeUV_m5 3.0
+ #define cubeUV_r6 0.21
+ #define cubeUV_m6 4.0
+ float roughnessToMip( float roughness ) {
+ float mip = 0.0;
+ if ( roughness >= cubeUV_r1 ) {
+ mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
+ } else if ( roughness >= cubeUV_r4 ) {
+ mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
+ } else if ( roughness >= cubeUV_r5 ) {
+ mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
+ } else if ( roughness >= cubeUV_r6 ) {
+ mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
+ } else {
+ mip = - 2.0 * log2( 1.16 * roughness ); }
+ return mip;
+ }
+ vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
+ float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
+ float mipF = fract( mip );
+ float mipInt = floor( mip );
+ vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
+ if ( mipF == 0.0 ) {
+ return vec4( color0, 1.0 );
+ } else {
+ vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
+ return vec4( mix( color0, color1, mipF ), 1.0 );
+ }
+ }
+#endif`,defaultnormal_vertex:`vec3 transformedNormal = objectNormal;
+#ifdef USE_TANGENT
+ vec3 transformedTangent = objectTangent;
+#endif
+#ifdef USE_BATCHING
+ mat3 bm = mat3( batchingMatrix );
+ transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
+ transformedNormal = bm * transformedNormal;
+ #ifdef USE_TANGENT
+ transformedTangent = bm * transformedTangent;
+ #endif
+#endif
+#ifdef USE_INSTANCING
+ mat3 im = mat3( instanceMatrix );
+ transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
+ transformedNormal = im * transformedNormal;
+ #ifdef USE_TANGENT
+ transformedTangent = im * transformedTangent;
+ #endif
+#endif
+transformedNormal = normalMatrix * transformedNormal;
+#ifdef FLIP_SIDED
+ transformedNormal = - transformedNormal;
+#endif
+#ifdef USE_TANGENT
+ transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
+ #ifdef FLIP_SIDED
+ transformedTangent = - transformedTangent;
+ #endif
+#endif`,displacementmap_pars_vertex:`#ifdef USE_DISPLACEMENTMAP
+ uniform sampler2D displacementMap;
+ uniform float displacementScale;
+ uniform float displacementBias;
+#endif`,displacementmap_vertex:`#ifdef USE_DISPLACEMENTMAP
+ transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
+#endif`,emissivemap_fragment:`#ifdef USE_EMISSIVEMAP
+ vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
+ #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
+ emissiveColor = sRGBTransferEOTF( emissiveColor );
+ #endif
+ totalEmissiveRadiance *= emissiveColor.rgb;
+#endif`,emissivemap_pars_fragment:`#ifdef USE_EMISSIVEMAP
+ uniform sampler2D emissiveMap;
+#endif`,colorspace_fragment:`gl_FragColor = linearToOutputTexel( gl_FragColor );`,colorspace_pars_fragment:`vec4 LinearTransferOETF( in vec4 value ) {
+ return value;
+}
+vec4 sRGBTransferEOTF( in vec4 value ) {
+ return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
+}
+vec4 sRGBTransferOETF( in vec4 value ) {
+ return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );
+}`,envmap_fragment:`#ifdef USE_ENVMAP
+ #ifdef ENV_WORLDPOS
+ vec3 cameraToFrag;
+ if ( isOrthographic ) {
+ cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
+ } else {
+ cameraToFrag = normalize( vWorldPosition - cameraPosition );
+ }
+ vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
+ #ifdef ENVMAP_MODE_REFLECTION
+ vec3 reflectVec = reflect( cameraToFrag, worldNormal );
+ #else
+ vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
+ #endif
+ #else
+ vec3 reflectVec = vReflect;
+ #endif
+ #ifdef ENVMAP_TYPE_CUBE
+ vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
+ #else
+ vec4 envColor = vec4( 0.0 );
+ #endif
+ #ifdef ENVMAP_BLENDING_MULTIPLY
+ outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
+ #elif defined( ENVMAP_BLENDING_MIX )
+ outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
+ #elif defined( ENVMAP_BLENDING_ADD )
+ outgoingLight += envColor.xyz * specularStrength * reflectivity;
+ #endif
+#endif`,envmap_common_pars_fragment:`#ifdef USE_ENVMAP
+ uniform float envMapIntensity;
+ uniform float flipEnvMap;
+ uniform mat3 envMapRotation;
+ #ifdef ENVMAP_TYPE_CUBE
+ uniform samplerCube envMap;
+ #else
+ uniform sampler2D envMap;
+ #endif
+
+#endif`,envmap_pars_fragment:`#ifdef USE_ENVMAP
+ uniform float reflectivity;
+ #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
+ #define ENV_WORLDPOS
+ #endif
+ #ifdef ENV_WORLDPOS
+ varying vec3 vWorldPosition;
+ uniform float refractionRatio;
+ #else
+ varying vec3 vReflect;
+ #endif
+#endif`,envmap_pars_vertex:`#ifdef USE_ENVMAP
+ #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
+ #define ENV_WORLDPOS
+ #endif
+ #ifdef ENV_WORLDPOS
+
+ varying vec3 vWorldPosition;
+ #else
+ varying vec3 vReflect;
+ uniform float refractionRatio;
+ #endif
+#endif`,envmap_physical_pars_fragment:`#ifdef USE_ENVMAP
+ vec3 getIBLIrradiance( const in vec3 normal ) {
+ #ifdef ENVMAP_TYPE_CUBE_UV
+ vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
+ vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );
+ return PI * envMapColor.rgb * envMapIntensity;
+ #else
+ return vec3( 0.0 );
+ #endif
+ }
+ vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
+ #ifdef ENVMAP_TYPE_CUBE_UV
+ vec3 reflectVec = reflect( - viewDir, normal );
+ reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );
+ reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
+ vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
+ return envMapColor.rgb * envMapIntensity;
+ #else
+ return vec3( 0.0 );
+ #endif
+ }
+ #ifdef USE_ANISOTROPY
+ vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
+ #ifdef ENVMAP_TYPE_CUBE_UV
+ vec3 bentNormal = cross( bitangent, viewDir );
+ bentNormal = normalize( cross( bentNormal, bitangent ) );
+ bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
+ return getIBLRadiance( viewDir, bentNormal, roughness );
+ #else
+ return vec3( 0.0 );
+ #endif
+ }
+ #endif
+#endif`,envmap_vertex:`#ifdef USE_ENVMAP
+ #ifdef ENV_WORLDPOS
+ vWorldPosition = worldPosition.xyz;
+ #else
+ vec3 cameraToVertex;
+ if ( isOrthographic ) {
+ cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
+ } else {
+ cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
+ }
+ vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
+ #ifdef ENVMAP_MODE_REFLECTION
+ vReflect = reflect( cameraToVertex, worldNormal );
+ #else
+ vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
+ #endif
+ #endif
+#endif`,fog_vertex:`#ifdef USE_FOG
+ vFogDepth = - mvPosition.z;
+#endif`,fog_pars_vertex:`#ifdef USE_FOG
+ varying float vFogDepth;
+#endif`,fog_fragment:`#ifdef USE_FOG
+ #ifdef FOG_EXP2
+ float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
+ #else
+ float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
+ #endif
+ gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
+#endif`,fog_pars_fragment:`#ifdef USE_FOG
+ uniform vec3 fogColor;
+ varying float vFogDepth;
+ #ifdef FOG_EXP2
+ uniform float fogDensity;
+ #else
+ uniform float fogNear;
+ uniform float fogFar;
+ #endif
+#endif`,gradientmap_pars_fragment:`#ifdef USE_GRADIENTMAP
+ uniform sampler2D gradientMap;
+#endif
+vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
+ float dotNL = dot( normal, lightDirection );
+ vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
+ #ifdef USE_GRADIENTMAP
+ return vec3( texture2D( gradientMap, coord ).r );
+ #else
+ vec2 fw = fwidth( coord ) * 0.5;
+ return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
+ #endif
+}`,lightmap_pars_fragment:`#ifdef USE_LIGHTMAP
+ uniform sampler2D lightMap;
+ uniform float lightMapIntensity;
+#endif`,lights_lambert_fragment:`LambertMaterial material;
+material.diffuseColor = diffuseColor.rgb;
+material.specularStrength = specularStrength;`,lights_lambert_pars_fragment:`varying vec3 vViewPosition;
+struct LambertMaterial {
+ vec3 diffuseColor;
+ float specularStrength;
+};
+void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
+ float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
+ vec3 irradiance = dotNL * directLight.color;
+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
+}
+void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
+}
+#define RE_Direct RE_Direct_Lambert
+#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,lights_pars_begin:`uniform bool receiveShadow;
+uniform vec3 ambientLightColor;
+#if defined( USE_LIGHT_PROBES )
+ uniform vec3 lightProbe[ 9 ];
+#endif
+vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
+ float x = normal.x, y = normal.y, z = normal.z;
+ vec3 result = shCoefficients[ 0 ] * 0.886227;
+ result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
+ result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
+ result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
+ result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
+ result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
+ result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
+ result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
+ result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
+ return result;
+}
+vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
+ vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
+ vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
+ return irradiance;
+}
+vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
+ vec3 irradiance = ambientLightColor;
+ return irradiance;
+}
+float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
+ float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
+ if ( cutoffDistance > 0.0 ) {
+ distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
+ }
+ return distanceFalloff;
+}
+float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
+ return smoothstep( coneCosine, penumbraCosine, angleCosine );
+}
+#if NUM_DIR_LIGHTS > 0
+ struct DirectionalLight {
+ vec3 direction;
+ vec3 color;
+ };
+ uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
+ void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
+ light.color = directionalLight.color;
+ light.direction = directionalLight.direction;
+ light.visible = true;
+ }
+#endif
+#if NUM_POINT_LIGHTS > 0
+ struct PointLight {
+ vec3 position;
+ vec3 color;
+ float distance;
+ float decay;
+ };
+ uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
+ void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
+ vec3 lVector = pointLight.position - geometryPosition;
+ light.direction = normalize( lVector );
+ float lightDistance = length( lVector );
+ light.color = pointLight.color;
+ light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
+ light.visible = ( light.color != vec3( 0.0 ) );
+ }
+#endif
+#if NUM_SPOT_LIGHTS > 0
+ struct SpotLight {
+ vec3 position;
+ vec3 direction;
+ vec3 color;
+ float distance;
+ float decay;
+ float coneCos;
+ float penumbraCos;
+ };
+ uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
+ void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
+ vec3 lVector = spotLight.position - geometryPosition;
+ light.direction = normalize( lVector );
+ float angleCos = dot( light.direction, spotLight.direction );
+ float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
+ if ( spotAttenuation > 0.0 ) {
+ float lightDistance = length( lVector );
+ light.color = spotLight.color * spotAttenuation;
+ light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
+ light.visible = ( light.color != vec3( 0.0 ) );
+ } else {
+ light.color = vec3( 0.0 );
+ light.visible = false;
+ }
+ }
+#endif
+#if NUM_RECT_AREA_LIGHTS > 0
+ struct RectAreaLight {
+ vec3 color;
+ vec3 position;
+ vec3 halfWidth;
+ vec3 halfHeight;
+ };
+ uniform sampler2D ltc_1; uniform sampler2D ltc_2;
+ uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
+#endif
+#if NUM_HEMI_LIGHTS > 0
+ struct HemisphereLight {
+ vec3 direction;
+ vec3 skyColor;
+ vec3 groundColor;
+ };
+ uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
+ vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
+ float dotNL = dot( normal, hemiLight.direction );
+ float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
+ vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
+ return irradiance;
+ }
+#endif`,lights_toon_fragment:`ToonMaterial material;
+material.diffuseColor = diffuseColor.rgb;`,lights_toon_pars_fragment:`varying vec3 vViewPosition;
+struct ToonMaterial {
+ vec3 diffuseColor;
+};
+void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
+ vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
+}
+void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
+}
+#define RE_Direct RE_Direct_Toon
+#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,lights_phong_fragment:`BlinnPhongMaterial material;
+material.diffuseColor = diffuseColor.rgb;
+material.specularColor = specular;
+material.specularShininess = shininess;
+material.specularStrength = specularStrength;`,lights_phong_pars_fragment:`varying vec3 vViewPosition;
+struct BlinnPhongMaterial {
+ vec3 diffuseColor;
+ vec3 specularColor;
+ float specularShininess;
+ float specularStrength;
+};
+void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
+ float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
+ vec3 irradiance = dotNL * directLight.color;
+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
+ reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
+}
+void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
+}
+#define RE_Direct RE_Direct_BlinnPhong
+#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,lights_physical_fragment:`PhysicalMaterial material;
+material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
+vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
+float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
+material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
+material.roughness = min( material.roughness, 1.0 );
+#ifdef IOR
+ material.ior = ior;
+ #ifdef USE_SPECULAR
+ float specularIntensityFactor = specularIntensity;
+ vec3 specularColorFactor = specularColor;
+ #ifdef USE_SPECULAR_COLORMAP
+ specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
+ #endif
+ #ifdef USE_SPECULAR_INTENSITYMAP
+ specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
+ #endif
+ material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
+ #else
+ float specularIntensityFactor = 1.0;
+ vec3 specularColorFactor = vec3( 1.0 );
+ material.specularF90 = 1.0;
+ #endif
+ material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
+#else
+ material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
+ material.specularF90 = 1.0;
+#endif
+#ifdef USE_CLEARCOAT
+ material.clearcoat = clearcoat;
+ material.clearcoatRoughness = clearcoatRoughness;
+ material.clearcoatF0 = vec3( 0.04 );
+ material.clearcoatF90 = 1.0;
+ #ifdef USE_CLEARCOATMAP
+ material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
+ #endif
+ #ifdef USE_CLEARCOAT_ROUGHNESSMAP
+ material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
+ #endif
+ material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
+ material.clearcoatRoughness += geometryRoughness;
+ material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
+#endif
+#ifdef USE_DISPERSION
+ material.dispersion = dispersion;
+#endif
+#ifdef USE_IRIDESCENCE
+ material.iridescence = iridescence;
+ material.iridescenceIOR = iridescenceIOR;
+ #ifdef USE_IRIDESCENCEMAP
+ material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
+ #endif
+ #ifdef USE_IRIDESCENCE_THICKNESSMAP
+ material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
+ #else
+ material.iridescenceThickness = iridescenceThicknessMaximum;
+ #endif
+#endif
+#ifdef USE_SHEEN
+ material.sheenColor = sheenColor;
+ #ifdef USE_SHEEN_COLORMAP
+ material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
+ #endif
+ material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
+ #ifdef USE_SHEEN_ROUGHNESSMAP
+ material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
+ #endif
+#endif
+#ifdef USE_ANISOTROPY
+ #ifdef USE_ANISOTROPYMAP
+ mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
+ vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
+ vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
+ #else
+ vec2 anisotropyV = anisotropyVector;
+ #endif
+ material.anisotropy = length( anisotropyV );
+ if( material.anisotropy == 0.0 ) {
+ anisotropyV = vec2( 1.0, 0.0 );
+ } else {
+ anisotropyV /= material.anisotropy;
+ material.anisotropy = saturate( material.anisotropy );
+ }
+ material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
+ material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
+ material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
+#endif`,lights_physical_pars_fragment:`struct PhysicalMaterial {
+ vec3 diffuseColor;
+ float roughness;
+ vec3 specularColor;
+ float specularF90;
+ float dispersion;
+ #ifdef USE_CLEARCOAT
+ float clearcoat;
+ float clearcoatRoughness;
+ vec3 clearcoatF0;
+ float clearcoatF90;
+ #endif
+ #ifdef USE_IRIDESCENCE
+ float iridescence;
+ float iridescenceIOR;
+ float iridescenceThickness;
+ vec3 iridescenceFresnel;
+ vec3 iridescenceF0;
+ #endif
+ #ifdef USE_SHEEN
+ vec3 sheenColor;
+ float sheenRoughness;
+ #endif
+ #ifdef IOR
+ float ior;
+ #endif
+ #ifdef USE_TRANSMISSION
+ float transmission;
+ float transmissionAlpha;
+ float thickness;
+ float attenuationDistance;
+ vec3 attenuationColor;
+ #endif
+ #ifdef USE_ANISOTROPY
+ float anisotropy;
+ float alphaT;
+ vec3 anisotropyT;
+ vec3 anisotropyB;
+ #endif
+};
+vec3 clearcoatSpecularDirect = vec3( 0.0 );
+vec3 clearcoatSpecularIndirect = vec3( 0.0 );
+vec3 sheenSpecularDirect = vec3( 0.0 );
+vec3 sheenSpecularIndirect = vec3(0.0 );
+vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
+ float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
+ float x2 = x * x;
+ float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
+ return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
+}
+float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
+ float a2 = pow2( alpha );
+ float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
+ float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
+ return 0.5 / max( gv + gl, EPSILON );
+}
+float D_GGX( const in float alpha, const in float dotNH ) {
+ float a2 = pow2( alpha );
+ float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
+ return RECIPROCAL_PI * a2 / pow2( denom );
+}
+#ifdef USE_ANISOTROPY
+ float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {
+ float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
+ float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
+ float v = 0.5 / ( gv + gl );
+ return saturate(v);
+ }
+ float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
+ float a2 = alphaT * alphaB;
+ highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
+ highp float v2 = dot( v, v );
+ float w2 = a2 / v2;
+ return RECIPROCAL_PI * a2 * pow2 ( w2 );
+ }
+#endif
+#ifdef USE_CLEARCOAT
+ vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
+ vec3 f0 = material.clearcoatF0;
+ float f90 = material.clearcoatF90;
+ float roughness = material.clearcoatRoughness;
+ float alpha = pow2( roughness );
+ vec3 halfDir = normalize( lightDir + viewDir );
+ float dotNL = saturate( dot( normal, lightDir ) );
+ float dotNV = saturate( dot( normal, viewDir ) );
+ float dotNH = saturate( dot( normal, halfDir ) );
+ float dotVH = saturate( dot( viewDir, halfDir ) );
+ vec3 F = F_Schlick( f0, f90, dotVH );
+ float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
+ float D = D_GGX( alpha, dotNH );
+ return F * ( V * D );
+ }
+#endif
+vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
+ vec3 f0 = material.specularColor;
+ float f90 = material.specularF90;
+ float roughness = material.roughness;
+ float alpha = pow2( roughness );
+ vec3 halfDir = normalize( lightDir + viewDir );
+ float dotNL = saturate( dot( normal, lightDir ) );
+ float dotNV = saturate( dot( normal, viewDir ) );
+ float dotNH = saturate( dot( normal, halfDir ) );
+ float dotVH = saturate( dot( viewDir, halfDir ) );
+ vec3 F = F_Schlick( f0, f90, dotVH );
+ #ifdef USE_IRIDESCENCE
+ F = mix( F, material.iridescenceFresnel, material.iridescence );
+ #endif
+ #ifdef USE_ANISOTROPY
+ float dotTL = dot( material.anisotropyT, lightDir );
+ float dotTV = dot( material.anisotropyT, viewDir );
+ float dotTH = dot( material.anisotropyT, halfDir );
+ float dotBL = dot( material.anisotropyB, lightDir );
+ float dotBV = dot( material.anisotropyB, viewDir );
+ float dotBH = dot( material.anisotropyB, halfDir );
+ float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
+ float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
+ #else
+ float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
+ float D = D_GGX( alpha, dotNH );
+ #endif
+ return F * ( V * D );
+}
+vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
+ const float LUT_SIZE = 64.0;
+ const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
+ const float LUT_BIAS = 0.5 / LUT_SIZE;
+ float dotNV = saturate( dot( N, V ) );
+ vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
+ uv = uv * LUT_SCALE + LUT_BIAS;
+ return uv;
+}
+float LTC_ClippedSphereFormFactor( const in vec3 f ) {
+ float l = length( f );
+ return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
+}
+vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
+ float x = dot( v1, v2 );
+ float y = abs( x );
+ float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
+ float b = 3.4175940 + ( 4.1616724 + y ) * y;
+ float v = a / b;
+ float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
+ return cross( v1, v2 ) * theta_sintheta;
+}
+vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
+ vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
+ vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
+ vec3 lightNormal = cross( v1, v2 );
+ if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
+ vec3 T1, T2;
+ T1 = normalize( V - N * dot( V, N ) );
+ T2 = - cross( N, T1 );
+ mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );
+ vec3 coords[ 4 ];
+ coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
+ coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
+ coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
+ coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
+ coords[ 0 ] = normalize( coords[ 0 ] );
+ coords[ 1 ] = normalize( coords[ 1 ] );
+ coords[ 2 ] = normalize( coords[ 2 ] );
+ coords[ 3 ] = normalize( coords[ 3 ] );
+ vec3 vectorFormFactor = vec3( 0.0 );
+ vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
+ vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
+ vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
+ vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
+ float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
+ return vec3( result );
+}
+#if defined( USE_SHEEN )
+float D_Charlie( float roughness, float dotNH ) {
+ float alpha = pow2( roughness );
+ float invAlpha = 1.0 / alpha;
+ float cos2h = dotNH * dotNH;
+ float sin2h = max( 1.0 - cos2h, 0.0078125 );
+ return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
+}
+float V_Neubelt( float dotNV, float dotNL ) {
+ return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
+}
+vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
+ vec3 halfDir = normalize( lightDir + viewDir );
+ float dotNL = saturate( dot( normal, lightDir ) );
+ float dotNV = saturate( dot( normal, viewDir ) );
+ float dotNH = saturate( dot( normal, halfDir ) );
+ float D = D_Charlie( sheenRoughness, dotNH );
+ float V = V_Neubelt( dotNV, dotNL );
+ return sheenColor * ( D * V );
+}
+#endif
+float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
+ float dotNV = saturate( dot( normal, viewDir ) );
+ float r2 = roughness * roughness;
+ float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
+ float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
+ float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
+ return saturate( DG * RECIPROCAL_PI );
+}
+vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
+ float dotNV = saturate( dot( normal, viewDir ) );
+ const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
+ const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
+ vec4 r = roughness * c0 + c1;
+ float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;
+ vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;
+ return fab;
+}
+vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
+ vec2 fab = DFGApprox( normal, viewDir, roughness );
+ return specularColor * fab.x + specularF90 * fab.y;
+}
+#ifdef USE_IRIDESCENCE
+void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
+#else
+void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
+#endif
+ vec2 fab = DFGApprox( normal, viewDir, roughness );
+ #ifdef USE_IRIDESCENCE
+ vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
+ #else
+ vec3 Fr = specularColor;
+ #endif
+ vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
+ float Ess = fab.x + fab.y;
+ float Ems = 1.0 - Ess;
+ vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
+ singleScatter += FssEss;
+ multiScatter += Fms * Ems;
+}
+#if NUM_RECT_AREA_LIGHTS > 0
+ void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
+ vec3 normal = geometryNormal;
+ vec3 viewDir = geometryViewDir;
+ vec3 position = geometryPosition;
+ vec3 lightPos = rectAreaLight.position;
+ vec3 halfWidth = rectAreaLight.halfWidth;
+ vec3 halfHeight = rectAreaLight.halfHeight;
+ vec3 lightColor = rectAreaLight.color;
+ float roughness = material.roughness;
+ vec3 rectCoords[ 4 ];
+ rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
+ rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
+ rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
+ vec2 uv = LTC_Uv( normal, viewDir, roughness );
+ vec4 t1 = texture2D( ltc_1, uv );
+ vec4 t2 = texture2D( ltc_2, uv );
+ mat3 mInv = mat3(
+ vec3( t1.x, 0, t1.y ),
+ vec3( 0, 1, 0 ),
+ vec3( t1.z, 0, t1.w )
+ );
+ vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
+ reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
+ reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
+ }
+#endif
+void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
+ float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
+ vec3 irradiance = dotNL * directLight.color;
+ #ifdef USE_CLEARCOAT
+ float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
+ vec3 ccIrradiance = dotNLcc * directLight.color;
+ clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
+ #endif
+ #ifdef USE_SHEEN
+ sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
+ #endif
+ reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );
+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
+}
+void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
+}
+void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {
+ #ifdef USE_CLEARCOAT
+ clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
+ #endif
+ #ifdef USE_SHEEN
+ sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
+ #endif
+ vec3 singleScattering = vec3( 0.0 );
+ vec3 multiScattering = vec3( 0.0 );
+ vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
+ #ifdef USE_IRIDESCENCE
+ computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
+ #else
+ computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
+ #endif
+ vec3 totalScattering = singleScattering + multiScattering;
+ vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
+ reflectedLight.indirectSpecular += radiance * singleScattering;
+ reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
+ reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
+}
+#define RE_Direct RE_Direct_Physical
+#define RE_Direct_RectArea RE_Direct_RectArea_Physical
+#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical
+#define RE_IndirectSpecular RE_IndirectSpecular_Physical
+float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
+ return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
+}`,lights_fragment_begin:`
+vec3 geometryPosition = - vViewPosition;
+vec3 geometryNormal = normal;
+vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
+vec3 geometryClearcoatNormal = vec3( 0.0 );
+#ifdef USE_CLEARCOAT
+ geometryClearcoatNormal = clearcoatNormal;
+#endif
+#ifdef USE_IRIDESCENCE
+ float dotNVi = saturate( dot( normal, geometryViewDir ) );
+ if ( material.iridescenceThickness == 0.0 ) {
+ material.iridescence = 0.0;
+ } else {
+ material.iridescence = saturate( material.iridescence );
+ }
+ if ( material.iridescence > 0.0 ) {
+ material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
+ material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
+ }
+#endif
+IncidentLight directLight;
+#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
+ PointLight pointLight;
+ #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
+ PointLightShadow pointLightShadow;
+ #endif
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
+ pointLight = pointLights[ i ];
+ getPointLightInfo( pointLight, geometryPosition, directLight );
+ #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
+ pointLightShadow = pointLightShadows[ i ];
+ directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
+ #endif
+ RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
+ }
+ #pragma unroll_loop_end
+#endif
+#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
+ SpotLight spotLight;
+ vec4 spotColor;
+ vec3 spotLightCoord;
+ bool inSpotLightMap;
+ #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
+ SpotLightShadow spotLightShadow;
+ #endif
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
+ spotLight = spotLights[ i ];
+ getSpotLightInfo( spotLight, geometryPosition, directLight );
+ #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
+ #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
+ #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
+ #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
+ #else
+ #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
+ #endif
+ #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
+ spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
+ inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
+ spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
+ directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
+ #endif
+ #undef SPOT_LIGHT_MAP_INDEX
+ #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
+ spotLightShadow = spotLightShadows[ i ];
+ directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
+ #endif
+ RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
+ }
+ #pragma unroll_loop_end
+#endif
+#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
+ DirectionalLight directionalLight;
+ #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
+ DirectionalLightShadow directionalLightShadow;
+ #endif
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
+ directionalLight = directionalLights[ i ];
+ getDirectionalLightInfo( directionalLight, directLight );
+ #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
+ directionalLightShadow = directionalLightShadows[ i ];
+ directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
+ #endif
+ RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
+ }
+ #pragma unroll_loop_end
+#endif
+#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
+ RectAreaLight rectAreaLight;
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
+ rectAreaLight = rectAreaLights[ i ];
+ RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
+ }
+ #pragma unroll_loop_end
+#endif
+#if defined( RE_IndirectDiffuse )
+ vec3 iblIrradiance = vec3( 0.0 );
+ vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
+ #if defined( USE_LIGHT_PROBES )
+ irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
+ #endif
+ #if ( NUM_HEMI_LIGHTS > 0 )
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
+ irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
+ }
+ #pragma unroll_loop_end
+ #endif
+#endif
+#if defined( RE_IndirectSpecular )
+ vec3 radiance = vec3( 0.0 );
+ vec3 clearcoatRadiance = vec3( 0.0 );
+#endif`,lights_fragment_maps:`#if defined( RE_IndirectDiffuse )
+ #ifdef USE_LIGHTMAP
+ vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
+ vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
+ irradiance += lightMapIrradiance;
+ #endif
+ #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
+ iblIrradiance += getIBLIrradiance( geometryNormal );
+ #endif
+#endif
+#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
+ #ifdef USE_ANISOTROPY
+ radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
+ #else
+ radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
+ #endif
+ #ifdef USE_CLEARCOAT
+ clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
+ #endif
+#endif`,lights_fragment_end:`#if defined( RE_IndirectDiffuse )
+ RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
+#endif
+#if defined( RE_IndirectSpecular )
+ RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
+#endif`,logdepthbuf_fragment:`#if defined( USE_LOGDEPTHBUF )
+ gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
+#endif`,logdepthbuf_pars_fragment:`#if defined( USE_LOGDEPTHBUF )
+ uniform float logDepthBufFC;
+ varying float vFragDepth;
+ varying float vIsPerspective;
+#endif`,logdepthbuf_pars_vertex:`#ifdef USE_LOGDEPTHBUF
+ varying float vFragDepth;
+ varying float vIsPerspective;
+#endif`,logdepthbuf_vertex:`#ifdef USE_LOGDEPTHBUF
+ vFragDepth = 1.0 + gl_Position.w;
+ vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
+#endif`,map_fragment:`#ifdef USE_MAP
+ vec4 sampledDiffuseColor = texture2D( map, vMapUv );
+ #ifdef DECODE_VIDEO_TEXTURE
+ sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
+ #endif
+ diffuseColor *= sampledDiffuseColor;
+#endif`,map_pars_fragment:`#ifdef USE_MAP
+ uniform sampler2D map;
+#endif`,map_particle_fragment:`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
+ #if defined( USE_POINTS_UV )
+ vec2 uv = vUv;
+ #else
+ vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
+ #endif
+#endif
+#ifdef USE_MAP
+ diffuseColor *= texture2D( map, uv );
+#endif
+#ifdef USE_ALPHAMAP
+ diffuseColor.a *= texture2D( alphaMap, uv ).g;
+#endif`,map_particle_pars_fragment:`#if defined( USE_POINTS_UV )
+ varying vec2 vUv;
+#else
+ #if defined( USE_MAP ) || defined( USE_ALPHAMAP )
+ uniform mat3 uvTransform;
+ #endif
+#endif
+#ifdef USE_MAP
+ uniform sampler2D map;
+#endif
+#ifdef USE_ALPHAMAP
+ uniform sampler2D alphaMap;
+#endif`,metalnessmap_fragment:`float metalnessFactor = metalness;
+#ifdef USE_METALNESSMAP
+ vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
+ metalnessFactor *= texelMetalness.b;
+#endif`,metalnessmap_pars_fragment:`#ifdef USE_METALNESSMAP
+ uniform sampler2D metalnessMap;
+#endif`,morphinstance_vertex:`#ifdef USE_INSTANCING_MORPH
+ float morphTargetInfluences[ MORPHTARGETS_COUNT ];
+ float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
+ for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
+ morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
+ }
+#endif`,morphcolor_vertex:`#if defined( USE_MORPHCOLORS )
+ vColor *= morphTargetBaseInfluence;
+ for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
+ #if defined( USE_COLOR_ALPHA )
+ if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
+ #elif defined( USE_COLOR )
+ if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
+ #endif
+ }
+#endif`,morphnormal_vertex:`#ifdef USE_MORPHNORMALS
+ objectNormal *= morphTargetBaseInfluence;
+ for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
+ if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
+ }
+#endif`,morphtarget_pars_vertex:`#ifdef USE_MORPHTARGETS
+ #ifndef USE_INSTANCING_MORPH
+ uniform float morphTargetBaseInfluence;
+ uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
+ #endif
+ uniform sampler2DArray morphTargetsTexture;
+ uniform ivec2 morphTargetsTextureSize;
+ vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
+ int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
+ int y = texelIndex / morphTargetsTextureSize.x;
+ int x = texelIndex - y * morphTargetsTextureSize.x;
+ ivec3 morphUV = ivec3( x, y, morphTargetIndex );
+ return texelFetch( morphTargetsTexture, morphUV, 0 );
+ }
+#endif`,morphtarget_vertex:`#ifdef USE_MORPHTARGETS
+ transformed *= morphTargetBaseInfluence;
+ for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
+ if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
+ }
+#endif`,normal_fragment_begin:`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
+#ifdef FLAT_SHADED
+ vec3 fdx = dFdx( vViewPosition );
+ vec3 fdy = dFdy( vViewPosition );
+ vec3 normal = normalize( cross( fdx, fdy ) );
+#else
+ vec3 normal = normalize( vNormal );
+ #ifdef DOUBLE_SIDED
+ normal *= faceDirection;
+ #endif
+#endif
+#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
+ #ifdef USE_TANGENT
+ mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
+ #else
+ mat3 tbn = getTangentFrame( - vViewPosition, normal,
+ #if defined( USE_NORMALMAP )
+ vNormalMapUv
+ #elif defined( USE_CLEARCOAT_NORMALMAP )
+ vClearcoatNormalMapUv
+ #else
+ vUv
+ #endif
+ );
+ #endif
+ #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
+ tbn[0] *= faceDirection;
+ tbn[1] *= faceDirection;
+ #endif
+#endif
+#ifdef USE_CLEARCOAT_NORMALMAP
+ #ifdef USE_TANGENT
+ mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
+ #else
+ mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
+ #endif
+ #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
+ tbn2[0] *= faceDirection;
+ tbn2[1] *= faceDirection;
+ #endif
+#endif
+vec3 nonPerturbedNormal = normal;`,normal_fragment_maps:`#ifdef USE_NORMALMAP_OBJECTSPACE
+ normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
+ #ifdef FLIP_SIDED
+ normal = - normal;
+ #endif
+ #ifdef DOUBLE_SIDED
+ normal = normal * faceDirection;
+ #endif
+ normal = normalize( normalMatrix * normal );
+#elif defined( USE_NORMALMAP_TANGENTSPACE )
+ vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
+ mapN.xy *= normalScale;
+ normal = normalize( tbn * mapN );
+#elif defined( USE_BUMPMAP )
+ normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
+#endif`,normal_pars_fragment:`#ifndef FLAT_SHADED
+ varying vec3 vNormal;
+ #ifdef USE_TANGENT
+ varying vec3 vTangent;
+ varying vec3 vBitangent;
+ #endif
+#endif`,normal_pars_vertex:`#ifndef FLAT_SHADED
+ varying vec3 vNormal;
+ #ifdef USE_TANGENT
+ varying vec3 vTangent;
+ varying vec3 vBitangent;
+ #endif
+#endif`,normal_vertex:`#ifndef FLAT_SHADED
+ vNormal = normalize( transformedNormal );
+ #ifdef USE_TANGENT
+ vTangent = normalize( transformedTangent );
+ vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
+ #endif
+#endif`,normalmap_pars_fragment:`#ifdef USE_NORMALMAP
+ uniform sampler2D normalMap;
+ uniform vec2 normalScale;
+#endif
+#ifdef USE_NORMALMAP_OBJECTSPACE
+ uniform mat3 normalMatrix;
+#endif
+#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
+ mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
+ vec3 q0 = dFdx( eye_pos.xyz );
+ vec3 q1 = dFdy( eye_pos.xyz );
+ vec2 st0 = dFdx( uv.st );
+ vec2 st1 = dFdy( uv.st );
+ vec3 N = surf_norm;
+ vec3 q1perp = cross( q1, N );
+ vec3 q0perp = cross( N, q0 );
+ vec3 T = q1perp * st0.x + q0perp * st1.x;
+ vec3 B = q1perp * st0.y + q0perp * st1.y;
+ float det = max( dot( T, T ), dot( B, B ) );
+ float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
+ return mat3( T * scale, B * scale, N );
+ }
+#endif`,clearcoat_normal_fragment_begin:`#ifdef USE_CLEARCOAT
+ vec3 clearcoatNormal = nonPerturbedNormal;
+#endif`,clearcoat_normal_fragment_maps:`#ifdef USE_CLEARCOAT_NORMALMAP
+ vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
+ clearcoatMapN.xy *= clearcoatNormalScale;
+ clearcoatNormal = normalize( tbn2 * clearcoatMapN );
+#endif`,clearcoat_pars_fragment:`#ifdef USE_CLEARCOATMAP
+ uniform sampler2D clearcoatMap;
+#endif
+#ifdef USE_CLEARCOAT_NORMALMAP
+ uniform sampler2D clearcoatNormalMap;
+ uniform vec2 clearcoatNormalScale;
+#endif
+#ifdef USE_CLEARCOAT_ROUGHNESSMAP
+ uniform sampler2D clearcoatRoughnessMap;
+#endif`,iridescence_pars_fragment:`#ifdef USE_IRIDESCENCEMAP
+ uniform sampler2D iridescenceMap;
+#endif
+#ifdef USE_IRIDESCENCE_THICKNESSMAP
+ uniform sampler2D iridescenceThicknessMap;
+#endif`,opaque_fragment:`#ifdef OPAQUE
+diffuseColor.a = 1.0;
+#endif
+#ifdef USE_TRANSMISSION
+diffuseColor.a *= material.transmissionAlpha;
+#endif
+gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,packing:`vec3 packNormalToRGB( const in vec3 normal ) {
+ return normalize( normal ) * 0.5 + 0.5;
+}
+vec3 unpackRGBToNormal( const in vec3 rgb ) {
+ return 2.0 * rgb.xyz - 1.0;
+}
+const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;
+const float Inv255 = 1. / 255.;
+const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );
+const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );
+const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );
+const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );
+vec4 packDepthToRGBA( const in float v ) {
+ if( v <= 0.0 )
+ return vec4( 0., 0., 0., 0. );
+ if( v >= 1.0 )
+ return vec4( 1., 1., 1., 1. );
+ float vuf;
+ float af = modf( v * PackFactors.a, vuf );
+ float bf = modf( vuf * ShiftRight8, vuf );
+ float gf = modf( vuf * ShiftRight8, vuf );
+ return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );
+}
+vec3 packDepthToRGB( const in float v ) {
+ if( v <= 0.0 )
+ return vec3( 0., 0., 0. );
+ if( v >= 1.0 )
+ return vec3( 1., 1., 1. );
+ float vuf;
+ float bf = modf( v * PackFactors.b, vuf );
+ float gf = modf( vuf * ShiftRight8, vuf );
+ return vec3( vuf * Inv255, gf * PackUpscale, bf );
+}
+vec2 packDepthToRG( const in float v ) {
+ if( v <= 0.0 )
+ return vec2( 0., 0. );
+ if( v >= 1.0 )
+ return vec2( 1., 1. );
+ float vuf;
+ float gf = modf( v * 256., vuf );
+ return vec2( vuf * Inv255, gf );
+}
+float unpackRGBAToDepth( const in vec4 v ) {
+ return dot( v, UnpackFactors4 );
+}
+float unpackRGBToDepth( const in vec3 v ) {
+ return dot( v, UnpackFactors3 );
+}
+float unpackRGToDepth( const in vec2 v ) {
+ return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;
+}
+vec4 pack2HalfToRGBA( const in vec2 v ) {
+ vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
+ return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
+}
+vec2 unpackRGBATo2Half( const in vec4 v ) {
+ return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
+}
+float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
+ return ( viewZ + near ) / ( near - far );
+}
+float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
+ return depth * ( near - far ) - near;
+}
+float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
+ return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
+}
+float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
+ return ( near * far ) / ( ( far - near ) * depth - far );
+}`,premultiplied_alpha_fragment:`#ifdef PREMULTIPLIED_ALPHA
+ gl_FragColor.rgb *= gl_FragColor.a;
+#endif`,project_vertex:`vec4 mvPosition = vec4( transformed, 1.0 );
+#ifdef USE_BATCHING
+ mvPosition = batchingMatrix * mvPosition;
+#endif
+#ifdef USE_INSTANCING
+ mvPosition = instanceMatrix * mvPosition;
+#endif
+mvPosition = modelViewMatrix * mvPosition;
+gl_Position = projectionMatrix * mvPosition;`,dithering_fragment:`#ifdef DITHERING
+ gl_FragColor.rgb = dithering( gl_FragColor.rgb );
+#endif`,dithering_pars_fragment:`#ifdef DITHERING
+ vec3 dithering( vec3 color ) {
+ float grid_position = rand( gl_FragCoord.xy );
+ vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
+ dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
+ return color + dither_shift_RGB;
+ }
+#endif`,roughnessmap_fragment:`float roughnessFactor = roughness;
+#ifdef USE_ROUGHNESSMAP
+ vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
+ roughnessFactor *= texelRoughness.g;
+#endif`,roughnessmap_pars_fragment:`#ifdef USE_ROUGHNESSMAP
+ uniform sampler2D roughnessMap;
+#endif`,shadowmap_pars_fragment:`#if NUM_SPOT_LIGHT_COORDS > 0
+ varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
+#endif
+#if NUM_SPOT_LIGHT_MAPS > 0
+ uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
+#endif
+#ifdef USE_SHADOWMAP
+ #if NUM_DIR_LIGHT_SHADOWS > 0
+ uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
+ varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
+ struct DirectionalLightShadow {
+ float shadowIntensity;
+ float shadowBias;
+ float shadowNormalBias;
+ float shadowRadius;
+ vec2 shadowMapSize;
+ };
+ uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
+ #endif
+ #if NUM_SPOT_LIGHT_SHADOWS > 0
+ uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
+ struct SpotLightShadow {
+ float shadowIntensity;
+ float shadowBias;
+ float shadowNormalBias;
+ float shadowRadius;
+ vec2 shadowMapSize;
+ };
+ uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
+ #endif
+ #if NUM_POINT_LIGHT_SHADOWS > 0
+ uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
+ varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
+ struct PointLightShadow {
+ float shadowIntensity;
+ float shadowBias;
+ float shadowNormalBias;
+ float shadowRadius;
+ vec2 shadowMapSize;
+ float shadowCameraNear;
+ float shadowCameraFar;
+ };
+ uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
+ #endif
+ float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
+ return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );
+ }
+ vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
+ return unpackRGBATo2Half( texture2D( shadow, uv ) );
+ }
+ float VSMShadow (sampler2D shadow, vec2 uv, float compare ){
+ float occlusion = 1.0;
+ vec2 distribution = texture2DDistribution( shadow, uv );
+ float hard_shadow = step( compare , distribution.x );
+ if (hard_shadow != 1.0 ) {
+ float distance = compare - distribution.x ;
+ float variance = max( 0.00000, distribution.y * distribution.y );
+ float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );
+ }
+ return occlusion;
+ }
+ float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
+ float shadow = 1.0;
+ shadowCoord.xyz /= shadowCoord.w;
+ shadowCoord.z += shadowBias;
+ bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
+ bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
+ if ( frustumTest ) {
+ #if defined( SHADOWMAP_TYPE_PCF )
+ vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
+ float dx0 = - texelSize.x * shadowRadius;
+ float dy0 = - texelSize.y * shadowRadius;
+ float dx1 = + texelSize.x * shadowRadius;
+ float dy1 = + texelSize.y * shadowRadius;
+ float dx2 = dx0 / 2.0;
+ float dy2 = dy0 / 2.0;
+ float dx3 = dx1 / 2.0;
+ float dy3 = dy1 / 2.0;
+ shadow = (
+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
+ ) * ( 1.0 / 17.0 );
+ #elif defined( SHADOWMAP_TYPE_PCF_SOFT )
+ vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
+ float dx = texelSize.x;
+ float dy = texelSize.y;
+ vec2 uv = shadowCoord.xy;
+ vec2 f = fract( uv * shadowMapSize + 0.5 );
+ uv -= f * texelSize;
+ shadow = (
+ texture2DCompare( shadowMap, uv, shadowCoord.z ) +
+ texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
+ texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
+ mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
+ texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
+ f.x ) +
+ mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
+ texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
+ f.x ) +
+ mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
+ texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
+ f.y ) +
+ mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
+ texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
+ f.y ) +
+ mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
+ texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
+ f.x ),
+ mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
+ texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
+ f.x ),
+ f.y )
+ ) * ( 1.0 / 9.0 );
+ #elif defined( SHADOWMAP_TYPE_VSM )
+ shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
+ #else
+ shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
+ #endif
+ }
+ return mix( 1.0, shadow, shadowIntensity );
+ }
+ vec2 cubeToUV( vec3 v, float texelSizeY ) {
+ vec3 absV = abs( v );
+ float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
+ absV *= scaleToCube;
+ v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
+ vec2 planar = v.xy;
+ float almostATexel = 1.5 * texelSizeY;
+ float almostOne = 1.0 - almostATexel;
+ if ( absV.z >= almostOne ) {
+ if ( v.z > 0.0 )
+ planar.x = 4.0 - v.x;
+ } else if ( absV.x >= almostOne ) {
+ float signX = sign( v.x );
+ planar.x = v.z * signX + 2.0 * signX;
+ } else if ( absV.y >= almostOne ) {
+ float signY = sign( v.y );
+ planar.x = v.x + 2.0 * signY + 2.0;
+ planar.y = v.z * signY - 2.0;
+ }
+ return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
+ }
+ float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
+ float shadow = 1.0;
+ vec3 lightToPosition = shadowCoord.xyz;
+
+ float lightToPositionLength = length( lightToPosition );
+ if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {
+ float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias;
+ vec3 bd3D = normalize( lightToPosition );
+ vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
+ #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
+ vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
+ shadow = (
+ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
+ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
+ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
+ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
+ texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
+ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
+ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
+ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
+ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
+ ) * ( 1.0 / 9.0 );
+ #else
+ shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
+ #endif
+ }
+ return mix( 1.0, shadow, shadowIntensity );
+ }
+#endif`,shadowmap_pars_vertex:`#if NUM_SPOT_LIGHT_COORDS > 0
+ uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
+ varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
+#endif
+#ifdef USE_SHADOWMAP
+ #if NUM_DIR_LIGHT_SHADOWS > 0
+ uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
+ varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
+ struct DirectionalLightShadow {
+ float shadowIntensity;
+ float shadowBias;
+ float shadowNormalBias;
+ float shadowRadius;
+ vec2 shadowMapSize;
+ };
+ uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
+ #endif
+ #if NUM_SPOT_LIGHT_SHADOWS > 0
+ struct SpotLightShadow {
+ float shadowIntensity;
+ float shadowBias;
+ float shadowNormalBias;
+ float shadowRadius;
+ vec2 shadowMapSize;
+ };
+ uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
+ #endif
+ #if NUM_POINT_LIGHT_SHADOWS > 0
+ uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
+ varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
+ struct PointLightShadow {
+ float shadowIntensity;
+ float shadowBias;
+ float shadowNormalBias;
+ float shadowRadius;
+ vec2 shadowMapSize;
+ float shadowCameraNear;
+ float shadowCameraFar;
+ };
+ uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
+ #endif
+#endif`,shadowmap_vertex:`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
+ vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
+ vec4 shadowWorldPosition;
+#endif
+#if defined( USE_SHADOWMAP )
+ #if NUM_DIR_LIGHT_SHADOWS > 0
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
+ shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
+ vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
+ }
+ #pragma unroll_loop_end
+ #endif
+ #if NUM_POINT_LIGHT_SHADOWS > 0
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
+ shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
+ vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
+ }
+ #pragma unroll_loop_end
+ #endif
+#endif
+#if NUM_SPOT_LIGHT_COORDS > 0
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
+ shadowWorldPosition = worldPosition;
+ #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
+ shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
+ #endif
+ vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
+ }
+ #pragma unroll_loop_end
+#endif`,shadowmask_pars_fragment:`float getShadowMask() {
+ float shadow = 1.0;
+ #ifdef USE_SHADOWMAP
+ #if NUM_DIR_LIGHT_SHADOWS > 0
+ DirectionalLightShadow directionalLight;
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
+ directionalLight = directionalLightShadows[ i ];
+ shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
+ }
+ #pragma unroll_loop_end
+ #endif
+ #if NUM_SPOT_LIGHT_SHADOWS > 0
+ SpotLightShadow spotLight;
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
+ spotLight = spotLightShadows[ i ];
+ shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
+ }
+ #pragma unroll_loop_end
+ #endif
+ #if NUM_POINT_LIGHT_SHADOWS > 0
+ PointLightShadow pointLight;
+ #pragma unroll_loop_start
+ for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
+ pointLight = pointLightShadows[ i ];
+ shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
+ }
+ #pragma unroll_loop_end
+ #endif
+ #endif
+ return shadow;
+}`,skinbase_vertex:`#ifdef USE_SKINNING
+ mat4 boneMatX = getBoneMatrix( skinIndex.x );
+ mat4 boneMatY = getBoneMatrix( skinIndex.y );
+ mat4 boneMatZ = getBoneMatrix( skinIndex.z );
+ mat4 boneMatW = getBoneMatrix( skinIndex.w );
+#endif`,skinning_pars_vertex:`#ifdef USE_SKINNING
+ uniform mat4 bindMatrix;
+ uniform mat4 bindMatrixInverse;
+ uniform highp sampler2D boneTexture;
+ mat4 getBoneMatrix( const in float i ) {
+ int size = textureSize( boneTexture, 0 ).x;
+ int j = int( i ) * 4;
+ int x = j % size;
+ int y = j / size;
+ vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
+ vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
+ vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
+ vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
+ return mat4( v1, v2, v3, v4 );
+ }
+#endif`,skinning_vertex:`#ifdef USE_SKINNING
+ vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
+ vec4 skinned = vec4( 0.0 );
+ skinned += boneMatX * skinVertex * skinWeight.x;
+ skinned += boneMatY * skinVertex * skinWeight.y;
+ skinned += boneMatZ * skinVertex * skinWeight.z;
+ skinned += boneMatW * skinVertex * skinWeight.w;
+ transformed = ( bindMatrixInverse * skinned ).xyz;
+#endif`,skinnormal_vertex:`#ifdef USE_SKINNING
+ mat4 skinMatrix = mat4( 0.0 );
+ skinMatrix += skinWeight.x * boneMatX;
+ skinMatrix += skinWeight.y * boneMatY;
+ skinMatrix += skinWeight.z * boneMatZ;
+ skinMatrix += skinWeight.w * boneMatW;
+ skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
+ objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
+ #ifdef USE_TANGENT
+ objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
+ #endif
+#endif`,specularmap_fragment:`float specularStrength;
+#ifdef USE_SPECULARMAP
+ vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
+ specularStrength = texelSpecular.r;
+#else
+ specularStrength = 1.0;
+#endif`,specularmap_pars_fragment:`#ifdef USE_SPECULARMAP
+ uniform sampler2D specularMap;
+#endif`,tonemapping_fragment:`#if defined( TONE_MAPPING )
+ gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
+#endif`,tonemapping_pars_fragment:`#ifndef saturate
+#define saturate( a ) clamp( a, 0.0, 1.0 )
+#endif
+uniform float toneMappingExposure;
+vec3 LinearToneMapping( vec3 color ) {
+ return saturate( toneMappingExposure * color );
+}
+vec3 ReinhardToneMapping( vec3 color ) {
+ color *= toneMappingExposure;
+ return saturate( color / ( vec3( 1.0 ) + color ) );
+}
+vec3 CineonToneMapping( vec3 color ) {
+ color *= toneMappingExposure;
+ color = max( vec3( 0.0 ), color - 0.004 );
+ return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
+}
+vec3 RRTAndODTFit( vec3 v ) {
+ vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
+ vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
+ return a / b;
+}
+vec3 ACESFilmicToneMapping( vec3 color ) {
+ const mat3 ACESInputMat = mat3(
+ vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),
+ vec3( 0.04823, 0.01566, 0.83777 )
+ );
+ const mat3 ACESOutputMat = mat3(
+ vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),
+ vec3( -0.07367, -0.00605, 1.07602 )
+ );
+ color *= toneMappingExposure / 0.6;
+ color = ACESInputMat * color;
+ color = RRTAndODTFit( color );
+ color = ACESOutputMat * color;
+ return saturate( color );
+}
+const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(
+ vec3( 1.6605, - 0.1246, - 0.0182 ),
+ vec3( - 0.5876, 1.1329, - 0.1006 ),
+ vec3( - 0.0728, - 0.0083, 1.1187 )
+);
+const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(
+ vec3( 0.6274, 0.0691, 0.0164 ),
+ vec3( 0.3293, 0.9195, 0.0880 ),
+ vec3( 0.0433, 0.0113, 0.8956 )
+);
+vec3 agxDefaultContrastApprox( vec3 x ) {
+ vec3 x2 = x * x;
+ vec3 x4 = x2 * x2;
+ return + 15.5 * x4 * x2
+ - 40.14 * x4 * x
+ + 31.96 * x4
+ - 6.868 * x2 * x
+ + 0.4298 * x2
+ + 0.1191 * x
+ - 0.00232;
+}
+vec3 AgXToneMapping( vec3 color ) {
+ const mat3 AgXInsetMatrix = mat3(
+ vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),
+ vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),
+ vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )
+ );
+ const mat3 AgXOutsetMatrix = mat3(
+ vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),
+ vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),
+ vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )
+ );
+ const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069;
+ color *= toneMappingExposure;
+ color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
+ color = AgXInsetMatrix * color;
+ color = max( color, 1e-10 ); color = log2( color );
+ color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );
+ color = clamp( color, 0.0, 1.0 );
+ color = agxDefaultContrastApprox( color );
+ color = AgXOutsetMatrix * color;
+ color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );
+ color = LINEAR_REC2020_TO_LINEAR_SRGB * color;
+ color = clamp( color, 0.0, 1.0 );
+ return color;
+}
+vec3 NeutralToneMapping( vec3 color ) {
+ const float StartCompression = 0.8 - 0.04;
+ const float Desaturation = 0.15;
+ color *= toneMappingExposure;
+ float x = min( color.r, min( color.g, color.b ) );
+ float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
+ color -= offset;
+ float peak = max( color.r, max( color.g, color.b ) );
+ if ( peak < StartCompression ) return color;
+ float d = 1. - StartCompression;
+ float newPeak = 1. - d * d / ( peak + d - StartCompression );
+ color *= newPeak / peak;
+ float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
+ return mix( color, vec3( newPeak ), g );
+}
+vec3 CustomToneMapping( vec3 color ) { return color; }`,transmission_fragment:`#ifdef USE_TRANSMISSION
+ material.transmission = transmission;
+ material.transmissionAlpha = 1.0;
+ material.thickness = thickness;
+ material.attenuationDistance = attenuationDistance;
+ material.attenuationColor = attenuationColor;
+ #ifdef USE_TRANSMISSIONMAP
+ material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
+ #endif
+ #ifdef USE_THICKNESSMAP
+ material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
+ #endif
+ vec3 pos = vWorldPosition;
+ vec3 v = normalize( cameraPosition - pos );
+ vec3 n = inverseTransformDirection( normal, viewMatrix );
+ vec4 transmitted = getIBLVolumeRefraction(
+ n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
+ pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,
+ material.attenuationColor, material.attenuationDistance );
+ material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
+ totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
+#endif`,transmission_pars_fragment:`#ifdef USE_TRANSMISSION
+ uniform float transmission;
+ uniform float thickness;
+ uniform float attenuationDistance;
+ uniform vec3 attenuationColor;
+ #ifdef USE_TRANSMISSIONMAP
+ uniform sampler2D transmissionMap;
+ #endif
+ #ifdef USE_THICKNESSMAP
+ uniform sampler2D thicknessMap;
+ #endif
+ uniform vec2 transmissionSamplerSize;
+ uniform sampler2D transmissionSamplerMap;
+ uniform mat4 modelMatrix;
+ uniform mat4 projectionMatrix;
+ varying vec3 vWorldPosition;
+ float w0( float a ) {
+ return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
+ }
+ float w1( float a ) {
+ return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );
+ }
+ float w2( float a ){
+ return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
+ }
+ float w3( float a ) {
+ return ( 1.0 / 6.0 ) * ( a * a * a );
+ }
+ float g0( float a ) {
+ return w0( a ) + w1( a );
+ }
+ float g1( float a ) {
+ return w2( a ) + w3( a );
+ }
+ float h0( float a ) {
+ return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
+ }
+ float h1( float a ) {
+ return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
+ }
+ vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
+ uv = uv * texelSize.zw + 0.5;
+ vec2 iuv = floor( uv );
+ vec2 fuv = fract( uv );
+ float g0x = g0( fuv.x );
+ float g1x = g1( fuv.x );
+ float h0x = h0( fuv.x );
+ float h1x = h1( fuv.x );
+ float h0y = h0( fuv.y );
+ float h1y = h1( fuv.y );
+ vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
+ vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
+ vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
+ vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
+ return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
+ g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
+ }
+ vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
+ vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
+ vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
+ vec2 fLodSizeInv = 1.0 / fLodSize;
+ vec2 cLodSizeInv = 1.0 / cLodSize;
+ vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
+ vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
+ return mix( fSample, cSample, fract( lod ) );
+ }
+ vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
+ vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
+ vec3 modelScale;
+ modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
+ modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
+ modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
+ return normalize( refractionVector ) * thickness * modelScale;
+ }
+ float applyIorToRoughness( const in float roughness, const in float ior ) {
+ return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
+ }
+ vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
+ float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
+ return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
+ }
+ vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
+ if ( isinf( attenuationDistance ) ) {
+ return vec3( 1.0 );
+ } else {
+ vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
+ vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;
+ }
+ }
+ vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
+ const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
+ const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,
+ const in vec3 attenuationColor, const in float attenuationDistance ) {
+ vec4 transmittedLight;
+ vec3 transmittance;
+ #ifdef USE_DISPERSION
+ float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;
+ vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );
+ for ( int i = 0; i < 3; i ++ ) {
+ vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );
+ vec3 refractedRayExit = position + transmissionRay;
+ vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
+ vec2 refractionCoords = ndcPos.xy / ndcPos.w;
+ refractionCoords += 1.0;
+ refractionCoords /= 2.0;
+ vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );
+ transmittedLight[ i ] = transmissionSample[ i ];
+ transmittedLight.a += transmissionSample.a;
+ transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];
+ }
+ transmittedLight.a /= 3.0;
+ #else
+ vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
+ vec3 refractedRayExit = position + transmissionRay;
+ vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
+ vec2 refractionCoords = ndcPos.xy / ndcPos.w;
+ refractionCoords += 1.0;
+ refractionCoords /= 2.0;
+ transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
+ transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
+ #endif
+ vec3 attenuatedColor = transmittance * transmittedLight.rgb;
+ vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
+ float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
+ return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
+ }
+#endif`,uv_pars_fragment:`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
+ varying vec2 vUv;
+#endif
+#ifdef USE_MAP
+ varying vec2 vMapUv;
+#endif
+#ifdef USE_ALPHAMAP
+ varying vec2 vAlphaMapUv;
+#endif
+#ifdef USE_LIGHTMAP
+ varying vec2 vLightMapUv;
+#endif
+#ifdef USE_AOMAP
+ varying vec2 vAoMapUv;
+#endif
+#ifdef USE_BUMPMAP
+ varying vec2 vBumpMapUv;
+#endif
+#ifdef USE_NORMALMAP
+ varying vec2 vNormalMapUv;
+#endif
+#ifdef USE_EMISSIVEMAP
+ varying vec2 vEmissiveMapUv;
+#endif
+#ifdef USE_METALNESSMAP
+ varying vec2 vMetalnessMapUv;
+#endif
+#ifdef USE_ROUGHNESSMAP
+ varying vec2 vRoughnessMapUv;
+#endif
+#ifdef USE_ANISOTROPYMAP
+ varying vec2 vAnisotropyMapUv;
+#endif
+#ifdef USE_CLEARCOATMAP
+ varying vec2 vClearcoatMapUv;
+#endif
+#ifdef USE_CLEARCOAT_NORMALMAP
+ varying vec2 vClearcoatNormalMapUv;
+#endif
+#ifdef USE_CLEARCOAT_ROUGHNESSMAP
+ varying vec2 vClearcoatRoughnessMapUv;
+#endif
+#ifdef USE_IRIDESCENCEMAP
+ varying vec2 vIridescenceMapUv;
+#endif
+#ifdef USE_IRIDESCENCE_THICKNESSMAP
+ varying vec2 vIridescenceThicknessMapUv;
+#endif
+#ifdef USE_SHEEN_COLORMAP
+ varying vec2 vSheenColorMapUv;
+#endif
+#ifdef USE_SHEEN_ROUGHNESSMAP
+ varying vec2 vSheenRoughnessMapUv;
+#endif
+#ifdef USE_SPECULARMAP
+ varying vec2 vSpecularMapUv;
+#endif
+#ifdef USE_SPECULAR_COLORMAP
+ varying vec2 vSpecularColorMapUv;
+#endif
+#ifdef USE_SPECULAR_INTENSITYMAP
+ varying vec2 vSpecularIntensityMapUv;
+#endif
+#ifdef USE_TRANSMISSIONMAP
+ uniform mat3 transmissionMapTransform;
+ varying vec2 vTransmissionMapUv;
+#endif
+#ifdef USE_THICKNESSMAP
+ uniform mat3 thicknessMapTransform;
+ varying vec2 vThicknessMapUv;
+#endif`,uv_pars_vertex:`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
+ varying vec2 vUv;
+#endif
+#ifdef USE_MAP
+ uniform mat3 mapTransform;
+ varying vec2 vMapUv;
+#endif
+#ifdef USE_ALPHAMAP
+ uniform mat3 alphaMapTransform;
+ varying vec2 vAlphaMapUv;
+#endif
+#ifdef USE_LIGHTMAP
+ uniform mat3 lightMapTransform;
+ varying vec2 vLightMapUv;
+#endif
+#ifdef USE_AOMAP
+ uniform mat3 aoMapTransform;
+ varying vec2 vAoMapUv;
+#endif
+#ifdef USE_BUMPMAP
+ uniform mat3 bumpMapTransform;
+ varying vec2 vBumpMapUv;
+#endif
+#ifdef USE_NORMALMAP
+ uniform mat3 normalMapTransform;
+ varying vec2 vNormalMapUv;
+#endif
+#ifdef USE_DISPLACEMENTMAP
+ uniform mat3 displacementMapTransform;
+ varying vec2 vDisplacementMapUv;
+#endif
+#ifdef USE_EMISSIVEMAP
+ uniform mat3 emissiveMapTransform;
+ varying vec2 vEmissiveMapUv;
+#endif
+#ifdef USE_METALNESSMAP
+ uniform mat3 metalnessMapTransform;
+ varying vec2 vMetalnessMapUv;
+#endif
+#ifdef USE_ROUGHNESSMAP
+ uniform mat3 roughnessMapTransform;
+ varying vec2 vRoughnessMapUv;
+#endif
+#ifdef USE_ANISOTROPYMAP
+ uniform mat3 anisotropyMapTransform;
+ varying vec2 vAnisotropyMapUv;
+#endif
+#ifdef USE_CLEARCOATMAP
+ uniform mat3 clearcoatMapTransform;
+ varying vec2 vClearcoatMapUv;
+#endif
+#ifdef USE_CLEARCOAT_NORMALMAP
+ uniform mat3 clearcoatNormalMapTransform;
+ varying vec2 vClearcoatNormalMapUv;
+#endif
+#ifdef USE_CLEARCOAT_ROUGHNESSMAP
+ uniform mat3 clearcoatRoughnessMapTransform;
+ varying vec2 vClearcoatRoughnessMapUv;
+#endif
+#ifdef USE_SHEEN_COLORMAP
+ uniform mat3 sheenColorMapTransform;
+ varying vec2 vSheenColorMapUv;
+#endif
+#ifdef USE_SHEEN_ROUGHNESSMAP
+ uniform mat3 sheenRoughnessMapTransform;
+ varying vec2 vSheenRoughnessMapUv;
+#endif
+#ifdef USE_IRIDESCENCEMAP
+ uniform mat3 iridescenceMapTransform;
+ varying vec2 vIridescenceMapUv;
+#endif
+#ifdef USE_IRIDESCENCE_THICKNESSMAP
+ uniform mat3 iridescenceThicknessMapTransform;
+ varying vec2 vIridescenceThicknessMapUv;
+#endif
+#ifdef USE_SPECULARMAP
+ uniform mat3 specularMapTransform;
+ varying vec2 vSpecularMapUv;
+#endif
+#ifdef USE_SPECULAR_COLORMAP
+ uniform mat3 specularColorMapTransform;
+ varying vec2 vSpecularColorMapUv;
+#endif
+#ifdef USE_SPECULAR_INTENSITYMAP
+ uniform mat3 specularIntensityMapTransform;
+ varying vec2 vSpecularIntensityMapUv;
+#endif
+#ifdef USE_TRANSMISSIONMAP
+ uniform mat3 transmissionMapTransform;
+ varying vec2 vTransmissionMapUv;
+#endif
+#ifdef USE_THICKNESSMAP
+ uniform mat3 thicknessMapTransform;
+ varying vec2 vThicknessMapUv;
+#endif`,uv_vertex:`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
+ vUv = vec3( uv, 1 ).xy;
+#endif
+#ifdef USE_MAP
+ vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_ALPHAMAP
+ vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_LIGHTMAP
+ vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_AOMAP
+ vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_BUMPMAP
+ vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_NORMALMAP
+ vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_DISPLACEMENTMAP
+ vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_EMISSIVEMAP
+ vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_METALNESSMAP
+ vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_ROUGHNESSMAP
+ vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_ANISOTROPYMAP
+ vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_CLEARCOATMAP
+ vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_CLEARCOAT_NORMALMAP
+ vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_CLEARCOAT_ROUGHNESSMAP
+ vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_IRIDESCENCEMAP
+ vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_IRIDESCENCE_THICKNESSMAP
+ vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_SHEEN_COLORMAP
+ vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_SHEEN_ROUGHNESSMAP
+ vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_SPECULARMAP
+ vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_SPECULAR_COLORMAP
+ vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_SPECULAR_INTENSITYMAP
+ vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_TRANSMISSIONMAP
+ vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
+#endif
+#ifdef USE_THICKNESSMAP
+ vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
+#endif`,worldpos_vertex:`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
+ vec4 worldPosition = vec4( transformed, 1.0 );
+ #ifdef USE_BATCHING
+ worldPosition = batchingMatrix * worldPosition;
+ #endif
+ #ifdef USE_INSTANCING
+ worldPosition = instanceMatrix * worldPosition;
+ #endif
+ worldPosition = modelMatrix * worldPosition;
+#endif`,background_vert:`varying vec2 vUv;
+uniform mat3 uvTransform;
+void main() {
+ vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
+ gl_Position = vec4( position.xy, 1.0, 1.0 );
+}`,background_frag:`uniform sampler2D t2D;
+uniform float backgroundIntensity;
+varying vec2 vUv;
+void main() {
+ vec4 texColor = texture2D( t2D, vUv );
+ #ifdef DECODE_VIDEO_TEXTURE
+ texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
+ #endif
+ texColor.rgb *= backgroundIntensity;
+ gl_FragColor = texColor;
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+}`,backgroundCube_vert:`varying vec3 vWorldDirection;
+#include <common>
+void main() {
+ vWorldDirection = transformDirection( position, modelMatrix );
+ #include <begin_vertex>
+ #include <project_vertex>
+ gl_Position.z = gl_Position.w;
+}`,backgroundCube_frag:`#ifdef ENVMAP_TYPE_CUBE
+ uniform samplerCube envMap;
+#elif defined( ENVMAP_TYPE_CUBE_UV )
+ uniform sampler2D envMap;
+#endif
+uniform float flipEnvMap;
+uniform float backgroundBlurriness;
+uniform float backgroundIntensity;
+uniform mat3 backgroundRotation;
+varying vec3 vWorldDirection;
+#include <cube_uv_reflection_fragment>
+void main() {
+ #ifdef ENVMAP_TYPE_CUBE
+ vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
+ #elif defined( ENVMAP_TYPE_CUBE_UV )
+ vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );
+ #else
+ vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
+ #endif
+ texColor.rgb *= backgroundIntensity;
+ gl_FragColor = texColor;
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+}`,cube_vert:`varying vec3 vWorldDirection;
+#include <common>
+void main() {
+ vWorldDirection = transformDirection( position, modelMatrix );
+ #include <begin_vertex>
+ #include <project_vertex>
+ gl_Position.z = gl_Position.w;
+}`,cube_frag:`uniform samplerCube tCube;
+uniform float tFlip;
+uniform float opacity;
+varying vec3 vWorldDirection;
+void main() {
+ vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
+ gl_FragColor = texColor;
+ gl_FragColor.a *= opacity;
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+}`,depth_vert:`#include <common>
+#include <batching_pars_vertex>
+#include <uv_pars_vertex>
+#include <displacementmap_pars_vertex>
+#include <morphtarget_pars_vertex>
+#include <skinning_pars_vertex>
+#include <logdepthbuf_pars_vertex>
+#include <clipping_planes_pars_vertex>
+varying vec2 vHighPrecisionZW;
+void main() {
+ #include <uv_vertex>
+ #include <batching_vertex>
+ #include <skinbase_vertex>
+ #include <morphinstance_vertex>
+ #ifdef USE_DISPLACEMENTMAP
+ #include <beginnormal_vertex>
+ #include <morphnormal_vertex>
+ #include <skinnormal_vertex>
+ #endif
+ #include <begin_vertex>
+ #include <morphtarget_vertex>
+ #include <skinning_vertex>
+ #include <displacementmap_vertex>
+ #include <project_vertex>
+ #include <logdepthbuf_vertex>
+ #include <clipping_planes_vertex>
+ vHighPrecisionZW = gl_Position.zw;
+}`,depth_frag:`#if DEPTH_PACKING == 3200
+ uniform float opacity;
+#endif
+#include <common>
+#include <packing>
+#include <uv_pars_fragment>
+#include <map_pars_fragment>
+#include <alphamap_pars_fragment>
+#include <alphatest_pars_fragment>
+#include <alphahash_pars_fragment>
+#include <logdepthbuf_pars_fragment>
+#include <clipping_planes_pars_fragment>
+varying vec2 vHighPrecisionZW;
+void main() {
+ vec4 diffuseColor = vec4( 1.0 );
+ #include <clipping_planes_fragment>
+ #if DEPTH_PACKING == 3200
+ diffuseColor.a = opacity;
+ #endif
+ #include <map_fragment>
+ #include <alphamap_fragment>
+ #include <alphatest_fragment>
+ #include <alphahash_fragment>
+ #include <logdepthbuf_fragment>
+ float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;
+ #if DEPTH_PACKING == 3200
+ gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
+ #elif DEPTH_PACKING == 3201
+ gl_FragColor = packDepthToRGBA( fragCoordZ );
+ #elif DEPTH_PACKING == 3202
+ gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );
+ #elif DEPTH_PACKING == 3203
+ gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );
+ #endif
+}`,distanceRGBA_vert:`#define DISTANCE
+varying vec3 vWorldPosition;
+#include <common>
+#include <batching_pars_vertex>
+#include <uv_pars_vertex>
+#include <displacementmap_pars_vertex>
+#include <morphtarget_pars_vertex>
+#include <skinning_pars_vertex>
+#include <clipping_planes_pars_vertex>
+void main() {
+ #include <uv_vertex>
+ #include <batching_vertex>
+ #include <skinbase_vertex>
+ #include <morphinstance_vertex>
+ #ifdef USE_DISPLACEMENTMAP
+ #include <beginnormal_vertex>
+ #include <morphnormal_vertex>
+ #include <skinnormal_vertex>
+ #endif
+ #include <begin_vertex>
+ #include <morphtarget_vertex>
+ #include <skinning_vertex>
+ #include <displacementmap_vertex>
+ #include <project_vertex>
+ #include <worldpos_vertex>
+ #include <clipping_planes_vertex>
+ vWorldPosition = worldPosition.xyz;
+}`,distanceRGBA_frag:`#define DISTANCE
+uniform vec3 referencePosition;
+uniform float nearDistance;
+uniform float farDistance;
+varying vec3 vWorldPosition;
+#include <common>
+#include <packing>
+#include <uv_pars_fragment>
+#include <map_pars_fragment>
+#include <alphamap_pars_fragment>
+#include <alphatest_pars_fragment>
+#include <alphahash_pars_fragment>
+#include <clipping_planes_pars_fragment>
+void main () {
+ vec4 diffuseColor = vec4( 1.0 );
+ #include <clipping_planes_fragment>
+ #include <map_fragment>
+ #include <alphamap_fragment>
+ #include <alphatest_fragment>
+ #include <alphahash_fragment>
+ float dist = length( vWorldPosition - referencePosition );
+ dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
+ dist = saturate( dist );
+ gl_FragColor = packDepthToRGBA( dist );
+}`,equirect_vert:`varying vec3 vWorldDirection;
+#include <common>
+void main() {
+ vWorldDirection = transformDirection( position, modelMatrix );
+ #include <begin_vertex>
+ #include <project_vertex>
+}`,equirect_frag:`uniform sampler2D tEquirect;
+varying vec3 vWorldDirection;
+#include <common>
+void main() {
+ vec3 direction = normalize( vWorldDirection );
+ vec2 sampleUV = equirectUv( direction );
+ gl_FragColor = texture2D( tEquirect, sampleUV );
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+}`,linedashed_vert:`uniform float scale;
+attribute float lineDistance;
+varying float vLineDistance;
+#include <common>
+#include <uv_pars_vertex>
+#include <color_pars_vertex>
+#include <fog_pars_vertex>
+#include <morphtarget_pars_vertex>
+#include <logdepthbuf_pars_vertex>
+#include <clipping_planes_pars_vertex>
+void main() {
+ vLineDistance = scale * lineDistance;
+ #include <uv_vertex>
+ #include <color_vertex>
+ #include <morphinstance_vertex>
+ #include <morphcolor_vertex>
+ #include <begin_vertex>
+ #include <morphtarget_vertex>
+ #include <project_vertex>
+ #include <logdepthbuf_vertex>
+ #include <clipping_planes_vertex>
+ #include <fog_vertex>
+}`,linedashed_frag:`uniform vec3 diffuse;
+uniform float opacity;
+uniform float dashSize;
+uniform float totalSize;
+varying float vLineDistance;
+#include <common>
+#include <color_pars_fragment>
+#include <uv_pars_fragment>
+#include <map_pars_fragment>
+#include <fog_pars_fragment>
+#include <logdepthbuf_pars_fragment>
+#include <clipping_planes_pars_fragment>
+void main() {
+ vec4 diffuseColor = vec4( diffuse, opacity );
+ #include <clipping_planes_fragment>
+ if ( mod( vLineDistance, totalSize ) > dashSize ) {
+ discard;
+ }
+ vec3 outgoingLight = vec3( 0.0 );
+ #include <logdepthbuf_fragment>
+ #include <map_fragment>
+ #include <color_fragment>
+ outgoingLight = diffuseColor.rgb;
+ #include <opaque_fragment>
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+ #include <fog_fragment>
+ #include <premultiplied_alpha_fragment>
+}`,meshbasic_vert:`#include <common>
+#include <batching_pars_vertex>
+#include <uv_pars_vertex>
+#include <envmap_pars_vertex>
+#include <color_pars_vertex>
+#include <fog_pars_vertex>
+#include <morphtarget_pars_vertex>
+#include <skinning_pars_vertex>
+#include <logdepthbuf_pars_vertex>
+#include <clipping_planes_pars_vertex>
+void main() {
+ #include <uv_vertex>
+ #include <color_vertex>
+ #include <morphinstance_vertex>
+ #include <morphcolor_vertex>
+ #include <batching_vertex>
+ #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
+ #include <beginnormal_vertex>
+ #include <morphnormal_vertex>
+ #include <skinbase_vertex>
+ #include <skinnormal_vertex>
+ #include <defaultnormal_vertex>
+ #endif
+ #include <begin_vertex>
+ #include <morphtarget_vertex>
+ #include <skinning_vertex>
+ #include <project_vertex>
+ #include <logdepthbuf_vertex>
+ #include <clipping_planes_vertex>
+ #include <worldpos_vertex>
+ #include <envmap_vertex>
+ #include <fog_vertex>
+}`,meshbasic_frag:`uniform vec3 diffuse;
+uniform float opacity;
+#ifndef FLAT_SHADED
+ varying vec3 vNormal;
+#endif
+#include <common>
+#include <dithering_pars_fragment>
+#include <color_pars_fragment>
+#include <uv_pars_fragment>
+#include <map_pars_fragment>
+#include <alphamap_pars_fragment>
+#include <alphatest_pars_fragment>
+#include <alphahash_pars_fragment>
+#include <aomap_pars_fragment>
+#include <lightmap_pars_fragment>
+#include <envmap_common_pars_fragment>
+#include <envmap_pars_fragment>
+#include <fog_pars_fragment>
+#include <specularmap_pars_fragment>
+#include <logdepthbuf_pars_fragment>
+#include <clipping_planes_pars_fragment>
+void main() {
+ vec4 diffuseColor = vec4( diffuse, opacity );
+ #include <clipping_planes_fragment>
+ #include <logdepthbuf_fragment>
+ #include <map_fragment>
+ #include <color_fragment>
+ #include <alphamap_fragment>
+ #include <alphatest_fragment>
+ #include <alphahash_fragment>
+ #include <specularmap_fragment>
+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
+ #ifdef USE_LIGHTMAP
+ vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
+ reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
+ #else
+ reflectedLight.indirectDiffuse += vec3( 1.0 );
+ #endif
+ #include <aomap_fragment>
+ reflectedLight.indirectDiffuse *= diffuseColor.rgb;
+ vec3 outgoingLight = reflectedLight.indirectDiffuse;
+ #include <envmap_fragment>
+ #include <opaque_fragment>
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+ #include <fog_fragment>
+ #include <premultiplied_alpha_fragment>
+ #include <dithering_fragment>
+}`,meshlambert_vert:`#define LAMBERT
+varying vec3 vViewPosition;
+#include <common>
+#include <batching_pars_vertex>
+#include <uv_pars_vertex>
+#include <displacementmap_pars_vertex>
+#include <envmap_pars_vertex>
+#include <color_pars_vertex>
+#include <fog_pars_vertex>
+#include <normal_pars_vertex>
+#include <morphtarget_pars_vertex>
+#include <skinning_pars_vertex>
+#include <shadowmap_pars_vertex>
+#include <logdepthbuf_pars_vertex>
+#include <clipping_planes_pars_vertex>
+void main() {
+ #include <uv_vertex>
+ #include <color_vertex>
+ #include <morphinstance_vertex>
+ #include <morphcolor_vertex>
+ #include <batching_vertex>
+ #include <beginnormal_vertex>
+ #include <morphnormal_vertex>
+ #include <skinbase_vertex>
+ #include <skinnormal_vertex>
+ #include <defaultnormal_vertex>
+ #include <normal_vertex>
+ #include <begin_vertex>
+ #include <morphtarget_vertex>
+ #include <skinning_vertex>
+ #include <displacementmap_vertex>
+ #include <project_vertex>
+ #include <logdepthbuf_vertex>
+ #include <clipping_planes_vertex>
+ vViewPosition = - mvPosition.xyz;
+ #include <worldpos_vertex>
+ #include <envmap_vertex>
+ #include <shadowmap_vertex>
+ #include <fog_vertex>
+}`,meshlambert_frag:`#define LAMBERT
+uniform vec3 diffuse;
+uniform vec3 emissive;
+uniform float opacity;
+#include <common>
+#include <packing>
+#include <dithering_pars_fragment>
+#include <color_pars_fragment>
+#include <uv_pars_fragment>
+#include <map_pars_fragment>
+#include <alphamap_pars_fragment>
+#include <alphatest_pars_fragment>
+#include <alphahash_pars_fragment>
+#include <aomap_pars_fragment>
+#include <lightmap_pars_fragment>
+#include <emissivemap_pars_fragment>
+#include <envmap_common_pars_fragment>
+#include <envmap_pars_fragment>
+#include <fog_pars_fragment>
+#include <bsdfs>
+#include <lights_pars_begin>
+#include <normal_pars_fragment>
+#include <lights_lambert_pars_fragment>
+#include <shadowmap_pars_fragment>
+#include <bumpmap_pars_fragment>
+#include <normalmap_pars_fragment>
+#include <specularmap_pars_fragment>
+#include <logdepthbuf_pars_fragment>
+#include <clipping_planes_pars_fragment>
+void main() {
+ vec4 diffuseColor = vec4( diffuse, opacity );
+ #include <clipping_planes_fragment>
+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
+ vec3 totalEmissiveRadiance = emissive;
+ #include <logdepthbuf_fragment>
+ #include <map_fragment>
+ #include <color_fragment>
+ #include <alphamap_fragment>
+ #include <alphatest_fragment>
+ #include <alphahash_fragment>
+ #include <specularmap_fragment>
+ #include <normal_fragment_begin>
+ #include <normal_fragment_maps>
+ #include <emissivemap_fragment>
+ #include <lights_lambert_fragment>
+ #include <lights_fragment_begin>
+ #include <lights_fragment_maps>
+ #include <lights_fragment_end>
+ #include <aomap_fragment>
+ vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
+ #include <envmap_fragment>
+ #include <opaque_fragment>
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+ #include <fog_fragment>
+ #include <premultiplied_alpha_fragment>
+ #include <dithering_fragment>
+}`,meshmatcap_vert:`#define MATCAP
+varying vec3 vViewPosition;
+#include <common>
+#include <batching_pars_vertex>
+#include <uv_pars_vertex>
+#include <color_pars_vertex>
+#include <displacementmap_pars_vertex>
+#include <fog_pars_vertex>
+#include <normal_pars_vertex>
+#include <morphtarget_pars_vertex>
+#include <skinning_pars_vertex>
+#include <logdepthbuf_pars_vertex>
+#include <clipping_planes_pars_vertex>
+void main() {
+ #include <uv_vertex>
+ #include <color_vertex>
+ #include <morphinstance_vertex>
+ #include <morphcolor_vertex>
+ #include <batching_vertex>
+ #include <beginnormal_vertex>
+ #include <morphnormal_vertex>
+ #include <skinbase_vertex>
+ #include <skinnormal_vertex>
+ #include <defaultnormal_vertex>
+ #include <normal_vertex>
+ #include <begin_vertex>
+ #include <morphtarget_vertex>
+ #include <skinning_vertex>
+ #include <displacementmap_vertex>
+ #include <project_vertex>
+ #include <logdepthbuf_vertex>
+ #include <clipping_planes_vertex>
+ #include <fog_vertex>
+ vViewPosition = - mvPosition.xyz;
+}`,meshmatcap_frag:`#define MATCAP
+uniform vec3 diffuse;
+uniform float opacity;
+uniform sampler2D matcap;
+varying vec3 vViewPosition;
+#include <common>
+#include <dithering_pars_fragment>
+#include <color_pars_fragment>
+#include <uv_pars_fragment>
+#include <map_pars_fragment>
+#include <alphamap_pars_fragment>
+#include <alphatest_pars_fragment>
+#include <alphahash_pars_fragment>
+#include <fog_pars_fragment>
+#include <normal_pars_fragment>
+#include <bumpmap_pars_fragment>
+#include <normalmap_pars_fragment>
+#include <logdepthbuf_pars_fragment>
+#include <clipping_planes_pars_fragment>
+void main() {
+ vec4 diffuseColor = vec4( diffuse, opacity );
+ #include <clipping_planes_fragment>
+ #include <logdepthbuf_fragment>
+ #include <map_fragment>
+ #include <color_fragment>
+ #include <alphamap_fragment>
+ #include <alphatest_fragment>
+ #include <alphahash_fragment>
+ #include <normal_fragment_begin>
+ #include <normal_fragment_maps>
+ vec3 viewDir = normalize( vViewPosition );
+ vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
+ vec3 y = cross( viewDir, x );
+ vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
+ #ifdef USE_MATCAP
+ vec4 matcapColor = texture2D( matcap, uv );
+ #else
+ vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
+ #endif
+ vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
+ #include <opaque_fragment>
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+ #include <fog_fragment>
+ #include <premultiplied_alpha_fragment>
+ #include <dithering_fragment>
+}`,meshnormal_vert:`#define NORMAL
+#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
+ varying vec3 vViewPosition;
+#endif
+#include <common>
+#include <batching_pars_vertex>
+#include <uv_pars_vertex>
+#include <displacementmap_pars_vertex>
+#include <normal_pars_vertex>
+#include <morphtarget_pars_vertex>
+#include <skinning_pars_vertex>
+#include <logdepthbuf_pars_vertex>
+#include <clipping_planes_pars_vertex>
+void main() {
+ #include <uv_vertex>
+ #include <batching_vertex>
+ #include <beginnormal_vertex>
+ #include <morphinstance_vertex>
+ #include <morphnormal_vertex>
+ #include <skinbase_vertex>
+ #include <skinnormal_vertex>
+ #include <defaultnormal_vertex>
+ #include <normal_vertex>
+ #include <begin_vertex>
+ #include <morphtarget_vertex>
+ #include <skinning_vertex>
+ #include <displacementmap_vertex>
+ #include <project_vertex>
+ #include <logdepthbuf_vertex>
+ #include <clipping_planes_vertex>
+#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
+ vViewPosition = - mvPosition.xyz;
+#endif
+}`,meshnormal_frag:`#define NORMAL
+uniform float opacity;
+#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
+ varying vec3 vViewPosition;
+#endif
+#include <packing>
+#include <uv_pars_fragment>
+#include <normal_pars_fragment>
+#include <bumpmap_pars_fragment>
+#include <normalmap_pars_fragment>
+#include <logdepthbuf_pars_fragment>
+#include <clipping_planes_pars_fragment>
+void main() {
+ vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );
+ #include <clipping_planes_fragment>
+ #include <logdepthbuf_fragment>
+ #include <normal_fragment_begin>
+ #include <normal_fragment_maps>
+ gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );
+ #ifdef OPAQUE
+ gl_FragColor.a = 1.0;
+ #endif
+}`,meshphong_vert:`#define PHONG
+varying vec3 vViewPosition;
+#include <common>
+#include <batching_pars_vertex>
+#include <uv_pars_vertex>
+#include <displacementmap_pars_vertex>
+#include <envmap_pars_vertex>
+#include <color_pars_vertex>
+#include <fog_pars_vertex>
+#include <normal_pars_vertex>
+#include <morphtarget_pars_vertex>
+#include <skinning_pars_vertex>
+#include <shadowmap_pars_vertex>
+#include <logdepthbuf_pars_vertex>
+#include <clipping_planes_pars_vertex>
+void main() {
+ #include <uv_vertex>
+ #include <color_vertex>
+ #include <morphcolor_vertex>
+ #include <batching_vertex>
+ #include <beginnormal_vertex>
+ #include <morphinstance_vertex>
+ #include <morphnormal_vertex>
+ #include <skinbase_vertex>
+ #include <skinnormal_vertex>
+ #include <defaultnormal_vertex>
+ #include <normal_vertex>
+ #include <begin_vertex>
+ #include <morphtarget_vertex>
+ #include <skinning_vertex>
+ #include <displacementmap_vertex>
+ #include <project_vertex>
+ #include <logdepthbuf_vertex>
+ #include <clipping_planes_vertex>
+ vViewPosition = - mvPosition.xyz;
+ #include <worldpos_vertex>
+ #include <envmap_vertex>
+ #include <shadowmap_vertex>
+ #include <fog_vertex>
+}`,meshphong_frag:`#define PHONG
+uniform vec3 diffuse;
+uniform vec3 emissive;
+uniform vec3 specular;
+uniform float shininess;
+uniform float opacity;
+#include <common>
+#include <packing>
+#include <dithering_pars_fragment>
+#include <color_pars_fragment>
+#include <uv_pars_fragment>
+#include <map_pars_fragment>
+#include <alphamap_pars_fragment>
+#include <alphatest_pars_fragment>
+#include <alphahash_pars_fragment>
+#include <aomap_pars_fragment>
+#include <lightmap_pars_fragment>
+#include <emissivemap_pars_fragment>
+#include <envmap_common_pars_fragment>
+#include <envmap_pars_fragment>
+#include <fog_pars_fragment>
+#include <bsdfs>
+#include <lights_pars_begin>
+#include <normal_pars_fragment>
+#include <lights_phong_pars_fragment>
+#include <shadowmap_pars_fragment>
+#include <bumpmap_pars_fragment>
+#include <normalmap_pars_fragment>
+#include <specularmap_pars_fragment>
+#include <logdepthbuf_pars_fragment>
+#include <clipping_planes_pars_fragment>
+void main() {
+ vec4 diffuseColor = vec4( diffuse, opacity );
+ #include <clipping_planes_fragment>
+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
+ vec3 totalEmissiveRadiance = emissive;
+ #include <logdepthbuf_fragment>
+ #include <map_fragment>
+ #include <color_fragment>
+ #include <alphamap_fragment>
+ #include <alphatest_fragment>
+ #include <alphahash_fragment>
+ #include <specularmap_fragment>
+ #include <normal_fragment_begin>
+ #include <normal_fragment_maps>
+ #include <emissivemap_fragment>
+ #include <lights_phong_fragment>
+ #include <lights_fragment_begin>
+ #include <lights_fragment_maps>
+ #include <lights_fragment_end>
+ #include <aomap_fragment>
+ vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
+ #include <envmap_fragment>
+ #include <opaque_fragment>
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+ #include <fog_fragment>
+ #include <premultiplied_alpha_fragment>
+ #include <dithering_fragment>
+}`,meshphysical_vert:`#define STANDARD
+varying vec3 vViewPosition;
+#ifdef USE_TRANSMISSION
+ varying vec3 vWorldPosition;
+#endif
+#include <common>
+#include <batching_pars_vertex>
+#include <uv_pars_vertex>
+#include <displacementmap_pars_vertex>
+#include <color_pars_vertex>
+#include <fog_pars_vertex>
+#include <normal_pars_vertex>
+#include <morphtarget_pars_vertex>
+#include <skinning_pars_vertex>
+#include <shadowmap_pars_vertex>
+#include <logdepthbuf_pars_vertex>
+#include <clipping_planes_pars_vertex>
+void main() {
+ #include <uv_vertex>
+ #include <color_vertex>
+ #include <morphinstance_vertex>
+ #include <morphcolor_vertex>
+ #include <batching_vertex>
+ #include <beginnormal_vertex>
+ #include <morphnormal_vertex>
+ #include <skinbase_vertex>
+ #include <skinnormal_vertex>
+ #include <defaultnormal_vertex>
+ #include <normal_vertex>
+ #include <begin_vertex>
+ #include <morphtarget_vertex>
+ #include <skinning_vertex>
+ #include <displacementmap_vertex>
+ #include <project_vertex>
+ #include <logdepthbuf_vertex>
+ #include <clipping_planes_vertex>
+ vViewPosition = - mvPosition.xyz;
+ #include <worldpos_vertex>
+ #include <shadowmap_vertex>
+ #include <fog_vertex>
+#ifdef USE_TRANSMISSION
+ vWorldPosition = worldPosition.xyz;
+#endif
+}`,meshphysical_frag:`#define STANDARD
+#ifdef PHYSICAL
+ #define IOR
+ #define USE_SPECULAR
+#endif
+uniform vec3 diffuse;
+uniform vec3 emissive;
+uniform float roughness;
+uniform float metalness;
+uniform float opacity;
+#ifdef IOR
+ uniform float ior;
+#endif
+#ifdef USE_SPECULAR
+ uniform float specularIntensity;
+ uniform vec3 specularColor;
+ #ifdef USE_SPECULAR_COLORMAP
+ uniform sampler2D specularColorMap;
+ #endif
+ #ifdef USE_SPECULAR_INTENSITYMAP
+ uniform sampler2D specularIntensityMap;
+ #endif
+#endif
+#ifdef USE_CLEARCOAT
+ uniform float clearcoat;
+ uniform float clearcoatRoughness;
+#endif
+#ifdef USE_DISPERSION
+ uniform float dispersion;
+#endif
+#ifdef USE_IRIDESCENCE
+ uniform float iridescence;
+ uniform float iridescenceIOR;
+ uniform float iridescenceThicknessMinimum;
+ uniform float iridescenceThicknessMaximum;
+#endif
+#ifdef USE_SHEEN
+ uniform vec3 sheenColor;
+ uniform float sheenRoughness;
+ #ifdef USE_SHEEN_COLORMAP
+ uniform sampler2D sheenColorMap;
+ #endif
+ #ifdef USE_SHEEN_ROUGHNESSMAP
+ uniform sampler2D sheenRoughnessMap;
+ #endif
+#endif
+#ifdef USE_ANISOTROPY
+ uniform vec2 anisotropyVector;
+ #ifdef USE_ANISOTROPYMAP
+ uniform sampler2D anisotropyMap;
+ #endif
+#endif
+varying vec3 vViewPosition;
+#include <common>
+#include <packing>
+#include <dithering_pars_fragment>
+#include <color_pars_fragment>
+#include <uv_pars_fragment>
+#include <map_pars_fragment>
+#include <alphamap_pars_fragment>
+#include <alphatest_pars_fragment>
+#include <alphahash_pars_fragment>
+#include <aomap_pars_fragment>
+#include <lightmap_pars_fragment>
+#include <emissivemap_pars_fragment>
+#include <iridescence_fragment>
+#include <cube_uv_reflection_fragment>
+#include <envmap_common_pars_fragment>
+#include <envmap_physical_pars_fragment>
+#include <fog_pars_fragment>
+#include <lights_pars_begin>
+#include <normal_pars_fragment>
+#include <lights_physical_pars_fragment>
+#include <transmission_pars_fragment>
+#include <shadowmap_pars_fragment>
+#include <bumpmap_pars_fragment>
+#include <normalmap_pars_fragment>
+#include <clearcoat_pars_fragment>
+#include <iridescence_pars_fragment>
+#include <roughnessmap_pars_fragment>
+#include <metalnessmap_pars_fragment>
+#include <logdepthbuf_pars_fragment>
+#include <clipping_planes_pars_fragment>
+void main() {
+ vec4 diffuseColor = vec4( diffuse, opacity );
+ #include <clipping_planes_fragment>
+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
+ vec3 totalEmissiveRadiance = emissive;
+ #include <logdepthbuf_fragment>
+ #include <map_fragment>
+ #include <color_fragment>
+ #include <alphamap_fragment>
+ #include <alphatest_fragment>
+ #include <alphahash_fragment>
+ #include <roughnessmap_fragment>
+ #include <metalnessmap_fragment>
+ #include <normal_fragment_begin>
+ #include <normal_fragment_maps>
+ #include <clearcoat_normal_fragment_begin>
+ #include <clearcoat_normal_fragment_maps>
+ #include <emissivemap_fragment>
+ #include <lights_physical_fragment>
+ #include <lights_fragment_begin>
+ #include <lights_fragment_maps>
+ #include <lights_fragment_end>
+ #include <aomap_fragment>
+ vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
+ vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
+ #include <transmission_fragment>
+ vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
+ #ifdef USE_SHEEN
+ float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
+ outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
+ #endif
+ #ifdef USE_CLEARCOAT
+ float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
+ vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
+ outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
+ #endif
+ #include <opaque_fragment>
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+ #include <fog_fragment>
+ #include <premultiplied_alpha_fragment>
+ #include <dithering_fragment>
+}`,meshtoon_vert:`#define TOON
+varying vec3 vViewPosition;
+#include <common>
+#include <batching_pars_vertex>
+#include <uv_pars_vertex>
+#include <displacementmap_pars_vertex>
+#include <color_pars_vertex>
+#include <fog_pars_vertex>
+#include <normal_pars_vertex>
+#include <morphtarget_pars_vertex>
+#include <skinning_pars_vertex>
+#include <shadowmap_pars_vertex>
+#include <logdepthbuf_pars_vertex>
+#include <clipping_planes_pars_vertex>
+void main() {
+ #include <uv_vertex>
+ #include <color_vertex>
+ #include <morphinstance_vertex>
+ #include <morphcolor_vertex>
+ #include <batching_vertex>
+ #include <beginnormal_vertex>
+ #include <morphnormal_vertex>
+ #include <skinbase_vertex>
+ #include <skinnormal_vertex>
+ #include <defaultnormal_vertex>
+ #include <normal_vertex>
+ #include <begin_vertex>
+ #include <morphtarget_vertex>
+ #include <skinning_vertex>
+ #include <displacementmap_vertex>
+ #include <project_vertex>
+ #include <logdepthbuf_vertex>
+ #include <clipping_planes_vertex>
+ vViewPosition = - mvPosition.xyz;
+ #include <worldpos_vertex>
+ #include <shadowmap_vertex>
+ #include <fog_vertex>
+}`,meshtoon_frag:`#define TOON
+uniform vec3 diffuse;
+uniform vec3 emissive;
+uniform float opacity;
+#include <common>
+#include <packing>
+#include <dithering_pars_fragment>
+#include <color_pars_fragment>
+#include <uv_pars_fragment>
+#include <map_pars_fragment>
+#include <alphamap_pars_fragment>
+#include <alphatest_pars_fragment>
+#include <alphahash_pars_fragment>
+#include <aomap_pars_fragment>
+#include <lightmap_pars_fragment>
+#include <emissivemap_pars_fragment>
+#include <gradientmap_pars_fragment>
+#include <fog_pars_fragment>
+#include <bsdfs>
+#include <lights_pars_begin>
+#include <normal_pars_fragment>
+#include <lights_toon_pars_fragment>
+#include <shadowmap_pars_fragment>
+#include <bumpmap_pars_fragment>
+#include <normalmap_pars_fragment>
+#include <logdepthbuf_pars_fragment>
+#include <clipping_planes_pars_fragment>
+void main() {
+ vec4 diffuseColor = vec4( diffuse, opacity );
+ #include <clipping_planes_fragment>
+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
+ vec3 totalEmissiveRadiance = emissive;
+ #include <logdepthbuf_fragment>
+ #include <map_fragment>
+ #include <color_fragment>
+ #include <alphamap_fragment>
+ #include <alphatest_fragment>
+ #include <alphahash_fragment>
+ #include <normal_fragment_begin>
+ #include <normal_fragment_maps>
+ #include <emissivemap_fragment>
+ #include <lights_toon_fragment>
+ #include <lights_fragment_begin>
+ #include <lights_fragment_maps>
+ #include <lights_fragment_end>
+ #include <aomap_fragment>
+ vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
+ #include <opaque_fragment>
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+ #include <fog_fragment>
+ #include <premultiplied_alpha_fragment>
+ #include <dithering_fragment>
+}`,points_vert:`uniform float size;
+uniform float scale;
+#include <common>
+#include <color_pars_vertex>
+#include <fog_pars_vertex>
+#include <morphtarget_pars_vertex>
+#include <logdepthbuf_pars_vertex>
+#include <clipping_planes_pars_vertex>
+#ifdef USE_POINTS_UV
+ varying vec2 vUv;
+ uniform mat3 uvTransform;
+#endif
+void main() {
+ #ifdef USE_POINTS_UV
+ vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
+ #endif
+ #include <color_vertex>
+ #include <morphinstance_vertex>
+ #include <morphcolor_vertex>
+ #include <begin_vertex>
+ #include <morphtarget_vertex>
+ #include <project_vertex>
+ gl_PointSize = size;
+ #ifdef USE_SIZEATTENUATION
+ bool isPerspective = isPerspectiveMatrix( projectionMatrix );
+ if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
+ #endif
+ #include <logdepthbuf_vertex>
+ #include <clipping_planes_vertex>
+ #include <worldpos_vertex>
+ #include <fog_vertex>
+}`,points_frag:`uniform vec3 diffuse;
+uniform float opacity;
+#include <common>
+#include <color_pars_fragment>
+#include <map_particle_pars_fragment>
+#include <alphatest_pars_fragment>
+#include <alphahash_pars_fragment>
+#include <fog_pars_fragment>
+#include <logdepthbuf_pars_fragment>
+#include <clipping_planes_pars_fragment>
+void main() {
+ vec4 diffuseColor = vec4( diffuse, opacity );
+ #include <clipping_planes_fragment>
+ vec3 outgoingLight = vec3( 0.0 );
+ #include <logdepthbuf_fragment>
+ #include <map_particle_fragment>
+ #include <color_fragment>
+ #include <alphatest_fragment>
+ #include <alphahash_fragment>
+ outgoingLight = diffuseColor.rgb;
+ #include <opaque_fragment>
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+ #include <fog_fragment>
+ #include <premultiplied_alpha_fragment>
+}`,shadow_vert:`#include <common>
+#include <batching_pars_vertex>
+#include <fog_pars_vertex>
+#include <morphtarget_pars_vertex>
+#include <skinning_pars_vertex>
+#include <logdepthbuf_pars_vertex>
+#include <shadowmap_pars_vertex>
+void main() {
+ #include <batching_vertex>
+ #include <beginnormal_vertex>
+ #include <morphinstance_vertex>
+ #include <morphnormal_vertex>
+ #include <skinbase_vertex>
+ #include <skinnormal_vertex>
+ #include <defaultnormal_vertex>
+ #include <begin_vertex>
+ #include <morphtarget_vertex>
+ #include <skinning_vertex>
+ #include <project_vertex>
+ #include <logdepthbuf_vertex>
+ #include <worldpos_vertex>
+ #include <shadowmap_vertex>
+ #include <fog_vertex>
+}`,shadow_frag:`uniform vec3 color;
+uniform float opacity;
+#include <common>
+#include <packing>
+#include <fog_pars_fragment>
+#include <bsdfs>
+#include <lights_pars_begin>
+#include <logdepthbuf_pars_fragment>
+#include <shadowmap_pars_fragment>
+#include <shadowmask_pars_fragment>
+void main() {
+ #include <logdepthbuf_fragment>
+ gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+ #include <fog_fragment>
+}`,sprite_vert:`uniform float rotation;
+uniform vec2 center;
+#include <common>
+#include <uv_pars_vertex>
+#include <fog_pars_vertex>
+#include <logdepthbuf_pars_vertex>
+#include <clipping_planes_pars_vertex>
+void main() {
+ #include <uv_vertex>
+ vec4 mvPosition = modelViewMatrix[ 3 ];
+ vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );
+ #ifndef USE_SIZEATTENUATION
+ bool isPerspective = isPerspectiveMatrix( projectionMatrix );
+ if ( isPerspective ) scale *= - mvPosition.z;
+ #endif
+ vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
+ vec2 rotatedPosition;
+ rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
+ rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
+ mvPosition.xy += rotatedPosition;
+ gl_Position = projectionMatrix * mvPosition;
+ #include <logdepthbuf_vertex>
+ #include <clipping_planes_vertex>
+ #include <fog_vertex>
+}`,sprite_frag:`uniform vec3 diffuse;
+uniform float opacity;
+#include <common>
+#include <uv_pars_fragment>
+#include <map_pars_fragment>
+#include <alphamap_pars_fragment>
+#include <alphatest_pars_fragment>
+#include <alphahash_pars_fragment>
+#include <fog_pars_fragment>
+#include <logdepthbuf_pars_fragment>
+#include <clipping_planes_pars_fragment>
+void main() {
+ vec4 diffuseColor = vec4( diffuse, opacity );
+ #include <clipping_planes_fragment>
+ vec3 outgoingLight = vec3( 0.0 );
+ #include <logdepthbuf_fragment>
+ #include <map_fragment>
+ #include <alphamap_fragment>
+ #include <alphatest_fragment>
+ #include <alphahash_fragment>
+ outgoingLight = diffuseColor.rgb;
+ #include <opaque_fragment>
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+ #include <fog_fragment>
+}`},H={common:{diffuse:{value:new B(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Et},alphaMap:{value:null},alphaMapTransform:{value:new Et},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Et}},envmap:{envMap:{value:null},envMapRotation:{value:new Et},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Et}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Et}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Et},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Et},normalScale:{value:new L(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Et},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Et}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Et}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Et}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new B(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new B(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Et},alphaTest:{value:0},uvTransform:{value:new Et}},sprite:{diffuse:{value:new B(16777215)},opacity:{value:1},center:{value:new L(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Et},alphaMap:{value:null},alphaMapTransform:{value:new Et},alphaTest:{value:0}}},ds={basic:{uniforms:ci([H.common,H.specularmap,H.envmap,H.aomap,H.lightmap,H.fog]),vertexShader:V.meshbasic_vert,fragmentShader:V.meshbasic_frag},lambert:{uniforms:ci([H.common,H.specularmap,H.envmap,H.aomap,H.lightmap,H.emissivemap,H.bumpmap,H.normalmap,H.displacementmap,H.fog,H.lights,{emissive:{value:new B(0)}}]),vertexShader:V.meshlambert_vert,fragmentShader:V.meshlambert_frag},phong:{uniforms:ci([H.common,H.specularmap,H.envmap,H.aomap,H.lightmap,H.emissivemap,H.bumpmap,H.normalmap,H.displacementmap,H.fog,H.lights,{emissive:{value:new B(0)},specular:{value:new B(1118481)},shininess:{value:30}}]),vertexShader:V.meshphong_vert,fragmentShader:V.meshphong_frag},standard:{uniforms:ci([H.common,H.envmap,H.aomap,H.lightmap,H.emissivemap,H.bumpmap,H.normalmap,H.displacementmap,H.roughnessmap,H.metalnessmap,H.fog,H.lights,{emissive:{value:new B(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:V.meshphysical_vert,fragmentShader:V.meshphysical_frag},toon:{uniforms:ci([H.common,H.aomap,H.lightmap,H.emissivemap,H.bumpmap,H.normalmap,H.displacementmap,H.gradientmap,H.fog,H.lights,{emissive:{value:new B(0)}}]),vertexShader:V.meshtoon_vert,fragmentShader:V.meshtoon_frag},matcap:{uniforms:ci([H.common,H.bumpmap,H.normalmap,H.displacementmap,H.fog,{matcap:{value:null}}]),vertexShader:V.meshmatcap_vert,fragmentShader:V.meshmatcap_frag},points:{uniforms:ci([H.points,H.fog]),vertexShader:V.points_vert,fragmentShader:V.points_frag},dashed:{uniforms:ci([H.common,H.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:V.linedashed_vert,fragmentShader:V.linedashed_frag},depth:{uniforms:ci([H.common,H.displacementmap]),vertexShader:V.depth_vert,fragmentShader:V.depth_frag},normal:{uniforms:ci([H.common,H.bumpmap,H.normalmap,H.displacementmap,{opacity:{value:1}}]),vertexShader:V.meshnormal_vert,fragmentShader:V.meshnormal_frag},sprite:{uniforms:ci([H.sprite,H.fog]),vertexShader:V.sprite_vert,fragmentShader:V.sprite_frag},background:{uniforms:{uvTransform:{value:new Et},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:V.background_vert,fragmentShader:V.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Et}},vertexShader:V.backgroundCube_vert,fragmentShader:V.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:V.cube_vert,fragmentShader:V.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:V.equirect_vert,fragmentShader:V.equirect_frag},distanceRGBA:{uniforms:ci([H.common,H.displacementmap,{referencePosition:{value:new R},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:V.distanceRGBA_vert,fragmentShader:V.distanceRGBA_frag},shadow:{uniforms:ci([H.lights,H.fog,{color:{value:new B(0)},opacity:{value:1}}]),vertexShader:V.shadow_vert,fragmentShader:V.shadow_frag}};ds.physical={uniforms:ci([ds.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Et},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Et},clearcoatNormalScale:{value:new L(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Et},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Et},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Et},sheen:{value:0},sheenColor:{value:new B(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Et},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Et},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Et},transmissionSamplerSize:{value:new L},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Et},attenuationDistance:{value:0},attenuationColor:{value:new B(0)},specularColor:{value:new B(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Et},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Et},anisotropyVector:{value:new L},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Et}}]),vertexShader:V.meshphysical_vert,fragmentShader:V.meshphysical_frag};var fs={r:0,b:0,g:0},ps=new Bn,ms=new z;function hs(e,t,n,r,i,a,o){let s=new B(0),c=a===!0?0:1,l,u,d=null,f=0,p=null;function m(e){let r=e.isScene===!0?e.background:null;return r&&r.isTexture&&(r=(e.backgroundBlurriness>0?n:t).get(r)),r}function h(t){let n=!1,i=m(t);i===null?_(s,c):i&&i.isColor&&(_(i,1),n=!0);let a=e.xr.getEnvironmentBlendMode();a===`additive`?r.buffers.color.setClear(0,0,0,1,o):a===`alpha-blend`&&r.buffers.color.setClear(0,0,0,0,o),(e.autoClear||n)&&(r.buffers.depth.setTest(!0),r.buffers.depth.setMask(!0),r.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))}function g(t,n){let r=m(n);r&&(r.isCubeTexture||r.mapping===306)?(u===void 0&&(u=new ri(new oi(1,1,1),new mi({name:`BackgroundCubeMaterial`,uniforms:si(ds.backgroundCube.uniforms),vertexShader:ds.backgroundCube.vertexShader,fragmentShader:ds.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),u.geometry.deleteAttribute(`normal`),u.geometry.deleteAttribute(`uv`),u.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(u.material,`envMap`,{get:function(){return this.uniforms.envMap.value}}),i.update(u)),ps.copy(n.backgroundRotation),ps.x*=-1,ps.y*=-1,ps.z*=-1,r.isCubeTexture&&r.isRenderTargetTexture===!1&&(ps.y*=-1,ps.z*=-1),u.material.uniforms.envMap.value=r,u.material.uniforms.flipEnvMap.value=r.isCubeTexture&&r.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(ms.makeRotationFromEuler(ps)),u.material.toneMapped=zt.getTransfer(r.colorSpace)!==Ye,(d!==r||f!==r.version||p!==e.toneMapping)&&(u.material.needsUpdate=!0,d=r,f=r.version,p=e.toneMapping),u.layers.enableAll(),t.unshift(u,u.geometry,u.material,0,0,null)):r&&r.isTexture&&(l===void 0&&(l=new ri(new Pa(2,2),new mi({name:`BackgroundMaterial`,uniforms:si(ds.background.uniforms),vertexShader:ds.background.vertexShader,fragmentShader:ds.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute(`normal`),Object.defineProperty(l.material,`map`,{get:function(){return this.uniforms.t2D.value}}),i.update(l)),l.material.uniforms.t2D.value=r,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.toneMapped=zt.getTransfer(r.colorSpace)!==Ye,r.matrixAutoUpdate===!0&&r.updateMatrix(),l.material.uniforms.uvTransform.value.copy(r.matrix),(d!==r||f!==r.version||p!==e.toneMapping)&&(l.material.needsUpdate=!0,d=r,f=r.version,p=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null))}function _(t,n){t.getRGB(fs,ui(e)),r.buffers.color.setClear(fs.r,fs.g,fs.b,n,o)}function v(){u!==void 0&&(u.geometry.dispose(),u.material.dispose(),u=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return s},setClearColor:function(e,t=1){s.set(e),c=t,_(s,c)},getClearAlpha:function(){return c},setClearAlpha:function(e){c=e,_(s,c)},render:h,addToRenderList:g,dispose:v}}function gs(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},i=f(null),a=i,o=!1;function s(n,r,i,s,c){let u=!1,f=d(s,i,r);a!==f&&(a=f,l(a.object)),u=p(n,s,i,c),u&&m(n,s,i,c),c!==null&&t.update(c,e.ELEMENT_ARRAY_BUFFER),(u||o)&&(o=!1,b(n,r,i,s),c!==null&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(c).buffer))}function c(){return e.createVertexArray()}function l(t){return e.bindVertexArray(t)}function u(t){return e.deleteVertexArray(t)}function d(e,t,n){let i=n.wireframe===!0,a=r[e.id];a===void 0&&(a={},r[e.id]=a);let o=a[t.id];o===void 0&&(o={},a[t.id]=o);let s=o[i];return s===void 0&&(s=f(c()),o[i]=s),s}function f(e){let t=[],r=[],i=[];for(let e=0;e<n;e++)t[e]=0,r[e]=0,i[e]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:r,attributeDivisors:i,object:e,attributes:{},index:null}}function p(e,t,n,r){let i=a.attributes,o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=i[t],r=o[t];if(r===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(r=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(r=e.instanceColor)),n===void 0||n.attribute!==r||r&&n.data!==r.data)return!0;s++}return a.attributesNum!==s||a.index!==r}function m(e,t,n,r){let i={},o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=o[t];n===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(n=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(n=e.instanceColor));let r={};r.attribute=n,n&&n.data&&(r.data=n.data),i[t]=r,s++}a.attributes=i,a.attributesNum=s,a.index=r}function h(){let e=a.newAttributes;for(let t=0,n=e.length;t<n;t++)e[t]=0}function g(e){_(e,0)}function _(t,n){let r=a.newAttributes,i=a.enabledAttributes,o=a.attributeDivisors;r[t]=1,i[t]===0&&(e.enableVertexAttribArray(t),i[t]=1),o[t]!==n&&(e.vertexAttribDivisor(t,n),o[t]=n)}function v(){let t=a.newAttributes,n=a.enabledAttributes;for(let r=0,i=n.length;r<i;r++)n[r]!==t[r]&&(e.disableVertexAttribArray(r),n[r]=0)}function y(t,n,r,i,a,o,s){s===!0?e.vertexAttribIPointer(t,n,r,a,o):e.vertexAttribPointer(t,n,r,i,a,o)}function b(n,r,i,a){h();let o=a.attributes,s=i.getAttributes(),c=r.defaultAttributeValues;for(let r in s){let i=s[r];if(i.location>=0){let s=o[r];if(s===void 0&&(r===`instanceMatrix`&&n.instanceMatrix&&(s=n.instanceMatrix),r===`instanceColor`&&n.instanceColor&&(s=n.instanceColor)),s!==void 0){let r=s.normalized,o=s.itemSize,c=t.get(s);if(c===void 0)continue;let l=c.buffer,u=c.type,d=c.bytesPerElement,f=u===e.INT||u===e.UNSIGNED_INT||s.gpuType===1013;if(s.isInterleavedBufferAttribute){let t=s.data,c=t.stride,p=s.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e<i.locationSize;e++)_(i.location+e,t.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,c*d,(p+o/i.locationSize*e)*d,f)}else{if(s.isInstancedBufferAttribute){for(let e=0;e<i.locationSize;e++)_(i.location+e,s.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=s.meshPerAttribute*s.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,o*d,o/i.locationSize*e*d,f)}}else if(c!==void 0){let t=c[r];if(t!==void 0)switch(t.length){case 2:e.vertexAttrib2fv(i.location,t);break;case 3:e.vertexAttrib3fv(i.location,t);break;case 4:e.vertexAttrib4fv(i.location,t);break;default:e.vertexAttrib1fv(i.location,t)}}}}v()}function x(){w();for(let e in r){let t=r[e];for(let e in t){let n=t[e];for(let e in n)u(n[e].object),delete n[e];delete t[e]}delete r[e]}}function S(e){if(r[e.id]===void 0)return;let t=r[e.id];for(let e in t){let n=t[e];for(let e in n)u(n[e].object),delete n[e];delete t[e]}delete r[e.id]}function C(e){for(let t in r){let n=r[t];if(n[e.id]===void 0)continue;let i=n[e.id];for(let e in i)u(i[e].object),delete i[e];delete n[e.id]}}function w(){T(),o=!0,a!==i&&(a=i,l(a.object))}function T(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:s,reset:w,resetDefaultState:T,dispose:x,releaseStatesOfGeometry:S,releaseStatesOfProgram:C,initAttributes:h,enableAttribute:g,disableUnusedAttributes:v}}function _s(e,t,n){let r;function i(e){r=e}function a(t,i){e.drawArrays(r,t,i),n.update(i,r,1)}function o(t,i,a){a!==0&&(e.drawArraysInstanced(r,t,i,a),n.update(i,r,a))}function s(e,i,a){if(a===0)return;t.get(`WEBGL_multi_draw`).multiDrawArraysWEBGL(r,e,0,i,0,a);let o=0;for(let e=0;e<a;e++)o+=i[e];n.update(o,r,1)}function c(e,i,a,s){if(a===0)return;let c=t.get(`WEBGL_multi_draw`);if(c===null)for(let t=0;t<e.length;t++)o(e[t],i[t],s[t]);else{c.multiDrawArraysInstancedWEBGL(r,e,0,i,0,s,0,a);let t=0;for(let e=0;e<a;e++)t+=i[e]*s[e];n.update(t,r,1)}}this.setMode=i,this.render=a,this.renderInstances=o,this.renderMultiDraw=s,this.renderMultiDrawInstances=c}function vs(e,t,n,r){let i;function a(){if(i!==void 0)return i;if(t.has(`EXT_texture_filter_anisotropic`)===!0){let n=t.get(`EXT_texture_filter_anisotropic`);i=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function o(t){return!(t!==1023&&r.convert(t)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT))}function s(n){let i=n===1016&&(t.has(`EXT_color_buffer_half_float`)||t.has(`EXT_color_buffer_float`));return!(n!==1009&&r.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==1015&&!i)}function c(t){if(t===`highp`){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return`highp`;t=`mediump`}return t===`mediump`&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?`mediump`:`lowp`}let l=n.precision===void 0?`highp`:n.precision,u=c(l);u!==l&&(console.warn(`THREE.WebGLRenderer:`,l,`not supported, using`,u,`instead.`),l=u);let d=n.logarithmicDepthBuffer===!0,f=n.reverseDepthBuffer===!0&&t.has(`EXT_clip_control`),p=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),m=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_TEXTURE_SIZE),g=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),_=e.getParameter(e.MAX_VERTEX_ATTRIBS),v=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),y=e.getParameter(e.MAX_VARYING_VECTORS),b=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),x=m>0,S=e.getParameter(e.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:s,precision:l,logarithmicDepthBuffer:d,reverseDepthBuffer:f,maxTextures:p,maxVertexTextures:m,maxTextureSize:h,maxCubemapSize:g,maxAttributes:_,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,vertexTextures:x,maxSamples:S}}function ys(e){let t=this,n=null,r=0,i=!1,a=!1,o=new aa,s=new Et,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){let n=e.length!==0||t||r!==0||i;return i=t,r=e.length,n},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(e,t){n=u(e,t,0)},this.setState=function(t,o,s){let d=t.clippingPlanes,f=t.clipIntersection,p=t.clipShadows,m=e.get(t);if(!i||d===null||d.length===0||a&&!p)a?u(null):l();else{let e=a?0:r,t=e*4,i=m.clippingState||null;c.value=i,i=u(d,o,t,s);for(let e=0;e!==t;++e)i[e]=n[e];m.clippingState=i,this.numIntersection=f?this.numPlanes:0,this.numPlanes+=e}};function l(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),t.numPlanes=r,t.numIntersection=0}function u(e,n,r,i){let a=e===null?0:e.length,l=null;if(a!==0){if(l=c.value,i!==!0||l===null){let t=r+a*4,i=n.matrixWorldInverse;s.getNormalMatrix(i),(l===null||l.length<t)&&(l=new Float32Array(t));for(let t=0,n=r;t!==a;++t,n+=4)o.copy(e[t]).applyMatrix4(i,s),o.normal.toArray(l,n),l[n+3]=o.constant}c.value=l,c.needsUpdate=!0}return t.numPlanes=a,t.numIntersection=0,l}}function bs(e){let t=new WeakMap;function n(e,t){return t===303?e.mapping=301:t===304&&(e.mapping=302),e}function r(r){if(r&&r.isTexture){let a=r.mapping;if(a===303||a===304)if(t.has(r)){let e=t.get(r).texture;return n(e,r.mapping)}else{let a=r.image;if(a&&a.height>0){let o=new wi(a.height);return o.fromEquirectangularTexture(e,r),t.set(r,o),r.addEventListener(`dispose`,i),n(o.texture,r.mapping)}else return null}}return r}function i(e){let n=e.target;n.removeEventListener(`dispose`,i);let r=t.get(n);r!==void 0&&(t.delete(n),r.dispose())}function a(){t=new WeakMap}return{get:r,dispose:a}}var xs=4,Ss=[.125,.215,.35,.446,.526,.582],Cs=20,ws=new ko,Ts=new B,Es=null,Ds=0,Os=0,ks=!1,As=(1+Math.sqrt(5))/2,js=1/As,Ms=[new R(-As,js,0),new R(As,js,0),new R(-js,0,As),new R(js,0,As),new R(0,As,-js),new R(0,As,js),new R(-1,1,-1),new R(1,1,-1),new R(-1,1,1),new R(1,1,1)],Ns=new R,Ps=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,n=.1,r=100,i={}){let{size:a=256,position:o=Ns}=i;Es=this._renderer.getRenderTarget(),Ds=this._renderer.getActiveCubeFace(),Os=this._renderer.getActiveMipmapLevel(),ks=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,n,r,s,o),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Bs(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=zs(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=2**this._lodMax}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(Es,Ds,Os),this._renderer.xr.enabled=ks,e.scissorTest=!1,Ls(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===301||e.mapping===302?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),Es=this._renderer.getRenderTarget(),Ds=this._renderer.getActiveCubeFace(),Os=this._renderer.getActiveMipmapLevel(),ks=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){let e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:f,minFilter:f,generateMipmaps:!1,type:S,format:k,colorSpace:qe,depthBuffer:!1},r=Is(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Is(e,t,n);let{_lodMax:r}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=Fs(r)),this._blurMaterial=Rs(r,e,t)}return r}_compileMaterial(e){let t=new ri(this._lodPlanes[0],e);this._renderer.compile(t,ws)}_sceneToCubeUV(e,t,n,r,i){let a=new yi(90,1,t,n),o=[1,-1,1,1,1,1],s=[1,1,1,-1,-1,-1],c=this._renderer,l=c.autoClear,u=c.toneMapping;c.getClearColor(Ts),c.toneMapping=0,c.autoClear=!1;let d=new Tr({name:`PMREM.Background`,side:1,depthWrite:!1,depthTest:!1}),f=new ri(new oi,d),p=!1,m=e.background;m?m.isColor&&(d.color.copy(m),e.background=null,p=!0):(d.color.copy(Ts),p=!0);for(let t=0;t<6;t++){let n=t%3;n===0?(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x+s[t],i.y,i.z)):n===1?(a.up.set(0,0,o[t]),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y+s[t],i.z)):(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y,i.z+s[t]));let l=this._cubeSize;Ls(r,n*l,t>2?l:0,l,l),c.setRenderTarget(r),p&&c.render(f,a),c.render(e,a)}f.geometry.dispose(),f.material.dispose(),c.toneMapping=u,c.autoClear=l,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,r=e.mapping===301||e.mapping===302;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=Bs()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=zs());let i=r?this._cubemapMaterial:this._equirectMaterial,a=new ri(this._lodPlanes[0],i),o=i.uniforms;o.envMap.value=e;let s=this._cubeSize;Ls(t,0,0,3*s,2*s),n.setRenderTarget(t),n.render(a,ws)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let r=this._lodPlanes.length;for(let t=1;t<r;t++){let n=Math.sqrt(this._sigmas[t]*this._sigmas[t]-this._sigmas[t-1]*this._sigmas[t-1]),i=Ms[(r-t-1)%Ms.length];this._blur(e,t-1,t,n,i)}t.autoClear=n}_blur(e,t,n,r,i){let a=this._pingPongRenderTarget;this._halfBlur(e,a,t,n,r,`latitudinal`,i),this._halfBlur(a,e,n,n,r,`longitudinal`,i)}_halfBlur(e,t,n,r,i,a,o){let s=this._renderer,c=this._blurMaterial;a!==`latitudinal`&&a!==`longitudinal`&&console.error(`blur direction must be either latitudinal or longitudinal!`);let l=new ri(this._lodPlanes[r],c),u=c.uniforms,d=this._sizeLods[n]-1,f=isFinite(i)?Math.PI/(2*d):2*Math.PI/(2*Cs-1),p=i/f,m=isFinite(i)?1+Math.floor(3*p):Cs;m>Cs&&console.warn(`sigmaRadians, ${i}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Cs}`);let h=[],g=0;for(let e=0;e<Cs;++e){let t=e/p,n=Math.exp(-t*t/2);h.push(n),e===0?g+=n:e<m&&(g+=2*n)}for(let e=0;e<h.length;e++)h[e]=h[e]/g;u.envMap.value=e.texture,u.samples.value=m,u.weights.value=h,u.latitudinal.value=a===`latitudinal`,o&&(u.poleAxis.value=o);let{_lodMax:_}=this;u.dTheta.value=f,u.mipInt.value=_-n;let v=this._sizeLods[r];Ls(t,3*v*(r>_-xs?r-_+xs:0),4*(this._cubeSize-v),3*v,2*v),s.setRenderTarget(t),s.render(l,ws)}};function Fs(e){let t=[],n=[],r=[],i=e,a=e-xs+1+Ss.length;for(let o=0;o<a;o++){let a=2**i;n.push(a);let s=1/a;o>e-xs?s=Ss[o-e+xs-1]:o===0&&(s=0),r.push(s);let c=1/(a-2),l=-c,u=1+c,d=[l,l,u,l,u,u,l,l,u,u,l,u],f=new Float32Array(108),p=new Float32Array(72),m=new Float32Array(36);for(let e=0;e<6;e++){let t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];f.set(r,18*e),p.set(d,12*e);let i=[e,e,e,e,e,e];m.set(i,6*e)}let h=new Gr;h.setAttribute(`position`,new Pr(f,3)),h.setAttribute(`uv`,new Pr(p,2)),h.setAttribute(`faceIndex`,new Pr(m,1)),t.push(h),i>xs&&i--}return{lodPlanes:t,sizeLods:n,sigmas:r}}function Is(e,t,n){let r=new Zt(e,t,n);return r.texture.mapping=306,r.texture.name=`PMREM.cubeUv`,r.scissorTest=!0,r}function Ls(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function Rs(e,t,n){let r=new Float32Array(Cs),i=new R(0,1,0);return new mi({name:`SphericalGaussianBlur`,defines:{n:Cs,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:Vs(),fragmentShader:`
+
+ precision mediump float;
+ precision mediump int;
+
+ varying vec3 vOutputDirection;
+
+ uniform sampler2D envMap;
+ uniform int samples;
+ uniform float weights[ n ];
+ uniform bool latitudinal;
+ uniform float dTheta;
+ uniform float mipInt;
+ uniform vec3 poleAxis;
+
+ #define ENVMAP_TYPE_CUBE_UV
+ #include <cube_uv_reflection_fragment>
+
+ vec3 getSample( float theta, vec3 axis ) {
+
+ float cosTheta = cos( theta );
+ // Rodrigues' axis-angle rotation
+ vec3 sampleDirection = vOutputDirection * cosTheta
+ + cross( axis, vOutputDirection ) * sin( theta )
+ + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
+
+ return bilinearCubeUV( envMap, sampleDirection, mipInt );
+
+ }
+
+ void main() {
+
+ vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
+
+ if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
+
+ axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
+
+ }
+
+ axis = normalize( axis );
+
+ gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
+ gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
+
+ for ( int i = 1; i < n; i++ ) {
+
+ if ( i >= samples ) {
+
+ break;
+
+ }
+
+ float theta = dTheta * float( i );
+ gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
+ gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
+
+ }
+
+ }
+ `,blending:0,depthTest:!1,depthWrite:!1})}function zs(){return new mi({name:`EquirectangularToCubeUV`,uniforms:{envMap:{value:null}},vertexShader:Vs(),fragmentShader:`
+
+ precision mediump float;
+ precision mediump int;
+
+ varying vec3 vOutputDirection;
+
+ uniform sampler2D envMap;
+
+ #include <common>
+
+ void main() {
+
+ vec3 outputDirection = normalize( vOutputDirection );
+ vec2 uv = equirectUv( outputDirection );
+
+ gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
+
+ }
+ `,blending:0,depthTest:!1,depthWrite:!1})}function Bs(){return new mi({name:`CubemapToCubeUV`,uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Vs(),fragmentShader:`
+
+ precision mediump float;
+ precision mediump int;
+
+ uniform float flipEnvMap;
+
+ varying vec3 vOutputDirection;
+
+ uniform samplerCube envMap;
+
+ void main() {
+
+ gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
+
+ }
+ `,blending:0,depthTest:!1,depthWrite:!1})}function Vs(){return`
+
+ precision mediump float;
+ precision mediump int;
+
+ attribute float faceIndex;
+
+ varying vec3 vOutputDirection;
+
+ // RH coordinate system; PMREM face-indexing convention
+ vec3 getDirection( vec2 uv, float face ) {
+
+ uv = 2.0 * uv - 1.0;
+
+ vec3 direction = vec3( uv, 1.0 );
+
+ if ( face == 0.0 ) {
+
+ direction = direction.zyx; // ( 1, v, u ) pos x
+
+ } else if ( face == 1.0 ) {
+
+ direction = direction.xzy;
+ direction.xz *= -1.0; // ( -u, 1, -v ) pos y
+
+ } else if ( face == 2.0 ) {
+
+ direction.x *= -1.0; // ( -u, v, 1 ) pos z
+
+ } else if ( face == 3.0 ) {
+
+ direction = direction.zyx;
+ direction.xz *= -1.0; // ( -1, v, -u ) neg x
+
+ } else if ( face == 4.0 ) {
+
+ direction = direction.xzy;
+ direction.xy *= -1.0; // ( -u, -1, v ) neg y
+
+ } else if ( face == 5.0 ) {
+
+ direction.z *= -1.0; // ( u, v, -1 ) neg z
+
+ }
+
+ return direction;
+
+ }
+
+ void main() {
+
+ vOutputDirection = getDirection( uv, faceIndex );
+ gl_Position = vec4( position, 1.0 );
+
+ }
+ `}function Hs(e){let t=new WeakMap,n=null;function r(r){if(r&&r.isTexture){let o=r.mapping,s=o===303||o===304,c=o===301||o===302;if(s||c){let o=t.get(r),l=o===void 0?0:o.texture.pmremVersion;if(r.isRenderTargetTexture&&r.pmremVersion!==l)return n===null&&(n=new Ps(e)),o=s?n.fromEquirectangular(r,o):n.fromCubemap(r,o),o.texture.pmremVersion=r.pmremVersion,t.set(r,o),o.texture;if(o!==void 0)return o.texture;{let l=r.image;return s&&l&&l.height>0||c&&l&&i(l)?(n===null&&(n=new Ps(e)),o=s?n.fromEquirectangular(r):n.fromCubemap(r),o.texture.pmremVersion=r.pmremVersion,t.set(r,o),r.addEventListener(`dispose`,a),o.texture):null}}}return r}function i(e){let t=0;for(let n=0;n<6;n++)e[n]!==void 0&&t++;return t===6}function a(e){let n=e.target;n.removeEventListener(`dispose`,a);let r=t.get(n);r!==void 0&&(t.delete(n),r.dispose())}function o(){t=new WeakMap,n!==null&&(n.dispose(),n=null)}return{get:r,dispose:o}}function Us(e){let t={};function n(n){if(t[n]!==void 0)return t[n];let r;switch(n){case`WEBGL_depth_texture`:r=e.getExtension(`WEBGL_depth_texture`)||e.getExtension(`MOZ_WEBGL_depth_texture`)||e.getExtension(`WEBKIT_WEBGL_depth_texture`);break;case`EXT_texture_filter_anisotropic`:r=e.getExtension(`EXT_texture_filter_anisotropic`)||e.getExtension(`MOZ_EXT_texture_filter_anisotropic`)||e.getExtension(`WEBKIT_EXT_texture_filter_anisotropic`);break;case`WEBGL_compressed_texture_s3tc`:r=e.getExtension(`WEBGL_compressed_texture_s3tc`)||e.getExtension(`MOZ_WEBGL_compressed_texture_s3tc`)||e.getExtension(`WEBKIT_WEBGL_compressed_texture_s3tc`);break;case`WEBGL_compressed_texture_pvrtc`:r=e.getExtension(`WEBGL_compressed_texture_pvrtc`)||e.getExtension(`WEBKIT_WEBGL_compressed_texture_pvrtc`);break;default:r=e.getExtension(n)}return t[n]=r,r}return{has:function(e){return n(e)!==null},init:function(){n(`EXT_color_buffer_float`),n(`WEBGL_clip_cull_distance`),n(`OES_texture_float_linear`),n(`EXT_color_buffer_half_float`),n(`WEBGL_multisampled_render_to_texture`),n(`WEBGL_render_shared_exponent`)},get:function(e){let t=n(e);return t===null&&Mt(`THREE.WebGLRenderer: `+e+` extension not supported.`),t}}}function Ws(e,t,n,r){let i={},a=new WeakMap;function o(e){let s=e.target;s.index!==null&&t.remove(s.index);for(let e in s.attributes)t.remove(s.attributes[e]);s.removeEventListener(`dispose`,o),delete i[s.id];let c=a.get(s);c&&(t.remove(c),a.delete(s)),r.releaseStatesOfGeometry(s),s.isInstancedBufferGeometry===!0&&delete s._maxInstanceCount,n.memory.geometries--}function s(e,t){return i[t.id]===!0?t:(t.addEventListener(`dispose`,o),i[t.id]=!0,n.memory.geometries++,t)}function c(n){let r=n.attributes;for(let n in r)t.update(r[n],e.ARRAY_BUFFER)}function l(e){let n=[],r=e.index,i=e.attributes.position,o=0;if(r!==null){let e=r.array;o=r.version;for(let t=0,r=e.length;t<r;t+=3){let r=e[t+0],i=e[t+1],a=e[t+2];n.push(r,i,i,a,a,r)}}else if(i!==void 0){let e=i.array;o=i.version;for(let t=0,r=e.length/3-1;t<r;t+=3){let e=t+0,r=t+1,i=t+2;n.push(e,r,r,i,i,e)}}else return;let s=new(Ot(n)?Ir:Fr)(n,1);s.version=o;let c=a.get(e);c&&t.remove(c),a.set(e,s)}function u(e){let t=a.get(e);if(t){let n=e.index;n!==null&&t.version<n.version&&l(e)}else l(e);return a.get(e)}return{get:s,update:c,getWireframeAttribute:u}}function Gs(e,t,n){let r;function i(e){r=e}let a,o;function s(e){a=e.type,o=e.bytesPerElement}function c(t,i){e.drawElements(r,i,a,t*o),n.update(i,r,1)}function l(t,i,s){s!==0&&(e.drawElementsInstanced(r,i,a,t*o,s),n.update(i,r,s))}function u(e,i,o){if(o===0)return;t.get(`WEBGL_multi_draw`).multiDrawElementsWEBGL(r,i,0,a,e,0,o);let s=0;for(let e=0;e<o;e++)s+=i[e];n.update(s,r,1)}function d(e,i,s,c){if(s===0)return;let u=t.get(`WEBGL_multi_draw`);if(u===null)for(let t=0;t<e.length;t++)l(e[t]/o,i[t],c[t]);else{u.multiDrawElementsInstancedWEBGL(r,i,0,a,e,0,c,0,s);let t=0;for(let e=0;e<s;e++)t+=i[e]*c[e];n.update(t,r,1)}}this.setMode=i,this.setIndex=s,this.render=c,this.renderInstances=l,this.renderMultiDraw=u,this.renderMultiDrawInstances=d}function Ks(e){let t={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function r(t,r,i){switch(n.calls++,r){case e.TRIANGLES:n.triangles+=t/3*i;break;case e.LINES:n.lines+=t/2*i;break;case e.LINE_STRIP:n.lines+=i*(t-1);break;case e.LINE_LOOP:n.lines+=i*t;break;case e.POINTS:n.points+=i*t;break;default:console.error(`THREE.WebGLInfo: Unknown draw mode:`,r);break}}function i(){n.calls=0,n.triangles=0,n.points=0,n.lines=0}return{memory:t,render:n,programs:null,autoReset:!0,reset:i,update:r}}function qs(e,t,n){let r=new WeakMap,i=new Yt;function a(a,o,s){let c=a.morphTargetInfluences,l=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,u=l===void 0?0:l.length,d=r.get(o);if(d===void 0||d.count!==u){d!==void 0&&d.texture.dispose();let e=o.morphAttributes.position!==void 0,n=o.morphAttributes.normal!==void 0,a=o.morphAttributes.color!==void 0,s=o.morphAttributes.position||[],c=o.morphAttributes.normal||[],l=o.morphAttributes.color||[],p=0;e===!0&&(p=1),n===!0&&(p=2),a===!0&&(p=3);let m=o.attributes.position.count*p,h=1;m>t.maxTextureSize&&(h=Math.ceil(m/t.maxTextureSize),m=t.maxTextureSize);let g=new Float32Array(m*h*4*u),_=new Qt(g,m,h,u);_.type=x,_.needsUpdate=!0;let v=p*4;for(let t=0;t<u;t++){let r=s[t],o=c[t],u=l[t],d=m*h*4*t;for(let t=0;t<r.count;t++){let s=t*v;e===!0&&(i.fromBufferAttribute(r,t),g[d+s+0]=i.x,g[d+s+1]=i.y,g[d+s+2]=i.z,g[d+s+3]=0),n===!0&&(i.fromBufferAttribute(o,t),g[d+s+4]=i.x,g[d+s+5]=i.y,g[d+s+6]=i.z,g[d+s+7]=0),a===!0&&(i.fromBufferAttribute(u,t),g[d+s+8]=i.x,g[d+s+9]=i.y,g[d+s+10]=i.z,g[d+s+11]=u.itemSize===4?i.w:1)}}d={count:u,texture:_,size:new L(m,h)},r.set(o,d);function f(){_.dispose(),r.delete(o),o.removeEventListener(`dispose`,f)}o.addEventListener(`dispose`,f)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)s.getUniforms().setValue(e,`morphTexture`,a.morphTexture,n);else{let t=0;for(let e=0;e<c.length;e++)t+=c[e];let n=o.morphTargetsRelative?1:1-t;s.getUniforms().setValue(e,`morphTargetBaseInfluence`,n),s.getUniforms().setValue(e,`morphTargetInfluences`,c)}s.getUniforms().setValue(e,`morphTargetsTexture`,d.texture,n),s.getUniforms().setValue(e,`morphTargetsTextureSize`,d.size)}return{update:a}}function Js(e,t,n,r){let i=new WeakMap;function a(a){let o=r.render.frame,c=a.geometry,l=t.get(a,c);if(i.get(l)!==o&&(t.update(l),i.set(l,o)),a.isInstancedMesh&&(a.hasEventListener(`dispose`,s)===!1&&a.addEventListener(`dispose`,s),i.get(a)!==o&&(n.update(a.instanceMatrix,e.ARRAY_BUFFER),a.instanceColor!==null&&n.update(a.instanceColor,e.ARRAY_BUFFER),i.set(a,o))),a.isSkinnedMesh){let e=a.skeleton;i.get(e)!==o&&(e.update(),i.set(e,o))}return l}function o(){i=new WeakMap}function s(e){let t=e.target;t.removeEventListener(`dispose`,s),n.remove(t.instanceMatrix),t.instanceColor!==null&&n.remove(t.instanceColor)}return{update:a,dispose:o}}var Ys=new Jt,Xs=new Na(1,1),Zs=new Qt,Qs=new $t,$s=new Ci,ec=[],tc=[],nc=new Float32Array(16),rc=new Float32Array(9),ic=new Float32Array(4);function ac(e,t,n){let r=e[0];if(r<=0||r>0)return e;let i=t*n,a=ec[i];if(a===void 0&&(a=new Float32Array(i),ec[i]=a),t!==0){r.toArray(a,0);for(let r=1,i=0;r!==t;++r)i+=n,e[r].toArray(a,i)}return a}function oc(e,t){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n<r;n++)if(e[n]!==t[n])return!1;return!0}function sc(e,t){for(let n=0,r=t.length;n<r;n++)e[n]=t[n]}function cc(e,t){let n=tc[t];n===void 0&&(n=new Int32Array(t),tc[t]=n);for(let r=0;r!==t;++r)n[r]=e.allocateTextureUnit();return n}function lc(e,t){let n=this.cache;n[0]!==t&&(e.uniform1f(this.addr,t),n[0]=t)}function uc(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2f(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(oc(n,t))return;e.uniform2fv(this.addr,t),sc(n,t)}}function dc(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3f(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else if(t.r!==void 0)(n[0]!==t.r||n[1]!==t.g||n[2]!==t.b)&&(e.uniform3f(this.addr,t.r,t.g,t.b),n[0]=t.r,n[1]=t.g,n[2]=t.b);else{if(oc(n,t))return;e.uniform3fv(this.addr,t),sc(n,t)}}function fc(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4f(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(oc(n,t))return;e.uniform4fv(this.addr,t),sc(n,t)}}function pc(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(oc(n,t))return;e.uniformMatrix2fv(this.addr,!1,t),sc(n,t)}else{if(oc(n,r))return;ic.set(r),e.uniformMatrix2fv(this.addr,!1,ic),sc(n,r)}}function mc(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(oc(n,t))return;e.uniformMatrix3fv(this.addr,!1,t),sc(n,t)}else{if(oc(n,r))return;rc.set(r),e.uniformMatrix3fv(this.addr,!1,rc),sc(n,r)}}function hc(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(oc(n,t))return;e.uniformMatrix4fv(this.addr,!1,t),sc(n,t)}else{if(oc(n,r))return;nc.set(r),e.uniformMatrix4fv(this.addr,!1,nc),sc(n,r)}}function gc(e,t){let n=this.cache;n[0]!==t&&(e.uniform1i(this.addr,t),n[0]=t)}function _c(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2i(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(oc(n,t))return;e.uniform2iv(this.addr,t),sc(n,t)}}function vc(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3i(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(oc(n,t))return;e.uniform3iv(this.addr,t),sc(n,t)}}function yc(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4i(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(oc(n,t))return;e.uniform4iv(this.addr,t),sc(n,t)}}function bc(e,t){let n=this.cache;n[0]!==t&&(e.uniform1ui(this.addr,t),n[0]=t)}function xc(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2ui(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(oc(n,t))return;e.uniform2uiv(this.addr,t),sc(n,t)}}function Sc(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3ui(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(oc(n,t))return;e.uniform3uiv(this.addr,t),sc(n,t)}}function Cc(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4ui(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(oc(n,t))return;e.uniform4uiv(this.addr,t),sc(n,t)}}function wc(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i);let a;this.type===e.SAMPLER_2D_SHADOW?(Xs.compareFunction=515,a=Xs):a=Ys,n.setTexture2D(t||a,i)}function Tc(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTexture3D(t||Qs,i)}function Ec(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTextureCube(t||$s,i)}function Dc(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTexture2DArray(t||Zs,i)}function Oc(e){switch(e){case 5126:return lc;case 35664:return uc;case 35665:return dc;case 35666:return fc;case 35674:return pc;case 35675:return mc;case 35676:return hc;case 5124:case 35670:return gc;case 35667:case 35671:return _c;case 35668:case 35672:return vc;case 35669:case 35673:return yc;case 5125:return bc;case 36294:return xc;case 36295:return Sc;case 36296:return Cc;case 35678:case 36198:case 36298:case 36306:case 35682:return wc;case 35679:case 36299:case 36307:return Tc;case 35680:case 36300:case 36308:case 36293:return Ec;case 36289:case 36303:case 36311:case 36292:return Dc}}function kc(e,t){e.uniform1fv(this.addr,t)}function Ac(e,t){let n=ac(t,this.size,2);e.uniform2fv(this.addr,n)}function jc(e,t){let n=ac(t,this.size,3);e.uniform3fv(this.addr,n)}function Mc(e,t){let n=ac(t,this.size,4);e.uniform4fv(this.addr,n)}function Nc(e,t){let n=ac(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,n)}function Pc(e,t){let n=ac(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,n)}function Fc(e,t){let n=ac(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,n)}function Ic(e,t){e.uniform1iv(this.addr,t)}function Lc(e,t){e.uniform2iv(this.addr,t)}function Rc(e,t){e.uniform3iv(this.addr,t)}function zc(e,t){e.uniform4iv(this.addr,t)}function Bc(e,t){e.uniform1uiv(this.addr,t)}function Vc(e,t){e.uniform2uiv(this.addr,t)}function Hc(e,t){e.uniform3uiv(this.addr,t)}function Uc(e,t){e.uniform4uiv(this.addr,t)}function Wc(e,t,n){let r=this.cache,i=t.length,a=cc(n,i);oc(r,a)||(e.uniform1iv(this.addr,a),sc(r,a));for(let e=0;e!==i;++e)n.setTexture2D(t[e]||Ys,a[e])}function Gc(e,t,n){let r=this.cache,i=t.length,a=cc(n,i);oc(r,a)||(e.uniform1iv(this.addr,a),sc(r,a));for(let e=0;e!==i;++e)n.setTexture3D(t[e]||Qs,a[e])}function Kc(e,t,n){let r=this.cache,i=t.length,a=cc(n,i);oc(r,a)||(e.uniform1iv(this.addr,a),sc(r,a));for(let e=0;e!==i;++e)n.setTextureCube(t[e]||$s,a[e])}function qc(e,t,n){let r=this.cache,i=t.length,a=cc(n,i);oc(r,a)||(e.uniform1iv(this.addr,a),sc(r,a));for(let e=0;e!==i;++e)n.setTexture2DArray(t[e]||Zs,a[e])}function Jc(e){switch(e){case 5126:return kc;case 35664:return Ac;case 35665:return jc;case 35666:return Mc;case 35674:return Nc;case 35675:return Pc;case 35676:return Fc;case 5124:case 35670:return Ic;case 35667:case 35671:return Lc;case 35668:case 35672:return Rc;case 35669:case 35673:return zc;case 5125:return Bc;case 36294:return Vc;case 36295:return Hc;case 36296:return Uc;case 35678:case 36198:case 36298:case 36306:case 35682:return Wc;case 35679:case 36299:case 36307:return Gc;case 35680:case 36300:case 36308:case 36293:return Kc;case 36289:case 36303:case 36311:case 36292:return qc}}var Yc=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=Oc(t.type)}},Xc=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=Jc(t.type)}},Zc=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){let r=this.seq;for(let i=0,a=r.length;i!==a;++i){let a=r[i];a.setValue(e,t[a.id],n)}}},Qc=/(\w+)(\])?(\[|\.)?/g;function $c(e,t){e.seq.push(t),e.map[t.id]=t}function el(e,t,n){let r=e.name,i=r.length;for(Qc.lastIndex=0;;){let a=Qc.exec(r),o=Qc.lastIndex,s=a[1],c=a[2]===`]`,l=a[3];if(c&&(s|=0),l===void 0||l===`[`&&o+2===i){$c(n,l===void 0?new Yc(s,e,t):new Xc(s,e,t));break}else{let e=n.map[s];e===void 0&&(e=new Zc(s),$c(n,e)),n=e}}}var tl=class{constructor(e,t){this.seq=[],this.map={};let n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let r=0;r<n;++r){let n=e.getActiveUniform(t,r);el(n,e.getUniformLocation(t,n.name),this)}}setValue(e,t,n,r){let i=this.map[t];i!==void 0&&i.setValue(e,n,r)}setOptional(e,t,n){let r=t[n];r!==void 0&&this.setValue(e,n,r)}static upload(e,t,n,r){for(let i=0,a=t.length;i!==a;++i){let a=t[i],o=n[a.id];o.needsUpdate!==!1&&a.setValue(e,o.value,r)}}static seqWithValue(e,t){let n=[];for(let r=0,i=e.length;r!==i;++r){let i=e[r];i.id in t&&n.push(i)}return n}};function nl(e,t,n){let r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),r}var rl=37297,il=0;function al(e,t){let n=e.split(`
+`),r=[],i=Math.max(t-6,0),a=Math.min(t+6,n.length);for(let e=i;e<a;e++){let i=e+1;r.push(`${i===t?`>`:` `} ${i}: ${n[e]}`)}return r.join(`
+`)}var ol=new Et;function sl(e){zt._getMatrix(ol,zt.workingColorSpace,e);let t=`mat3( ${ol.elements.map(e=>e.toFixed(4))} )`;switch(zt.getTransfer(e)){case Je:return[t,`LinearTransferOETF`];case Ye:return[t,`sRGBTransferOETF`];default:return console.warn(`THREE.WebGLProgram: Unsupported color space: `,e),[t,`LinearTransferOETF`]}}function cl(e,t,n){let r=e.getShaderParameter(t,e.COMPILE_STATUS),i=e.getShaderInfoLog(t).trim();if(r&&i===``)return``;let a=/ERROR: 0:(\d+)/.exec(i);if(a){let r=parseInt(a[1]);return n.toUpperCase()+`
+
+`+i+`
+
+`+al(e.getShaderSource(t),r)}else return i}function ll(e,t){let n=sl(t);return[`vec4 ${e}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,`}`].join(`
+`)}function ul(e,t){let n;switch(t){case 1:n=`Linear`;break;case 2:n=`Reinhard`;break;case 3:n=`Cineon`;break;case 4:n=`ACESFilmic`;break;case 6:n=`AgX`;break;case 7:n=`Neutral`;break;case 5:n=`Custom`;break;default:console.warn(`THREE.WebGLProgram: Unsupported toneMapping:`,t),n=`Linear`}return`vec3 `+e+`( vec3 color ) { return `+n+`ToneMapping( color ); }`}var dl=new R;function fl(){return zt.getLuminanceCoefficients(dl),[`float luminance( const in vec3 rgb ) {`,` const vec3 weights = vec3( ${dl.x.toFixed(4)}, ${dl.y.toFixed(4)}, ${dl.z.toFixed(4)} );`,` return dot( weights, rgb );`,`}`].join(`
+`)}function pl(e){return[e.extensionClipCullDistance?`#extension GL_ANGLE_clip_cull_distance : require`:``,e.extensionMultiDraw?`#extension GL_ANGLE_multi_draw : require`:``].filter(gl).join(`
+`)}function ml(e){let t=[];for(let n in e){let r=e[n];r!==!1&&t.push(`#define `+n+` `+r)}return t.join(`
+`)}function hl(e,t){let n={},r=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let i=0;i<r;i++){let r=e.getActiveAttrib(t,i),a=r.name,o=1;r.type===e.FLOAT_MAT2&&(o=2),r.type===e.FLOAT_MAT3&&(o=3),r.type===e.FLOAT_MAT4&&(o=4),n[a]={type:r.type,location:e.getAttribLocation(t,a),locationSize:o}}return n}function gl(e){return e!==``}function _l(e,t){let n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function vl(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}var yl=/^[ \t]*#include +<([\w\d./]+)>/gm;function bl(e){return e.replace(yl,Sl)}var xl=new Map;function Sl(e,t){let n=V[t];if(n===void 0){let e=xl.get(t);if(e!==void 0)n=V[e],console.warn(`THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.`,t,e);else throw Error(`Can not resolve #include <`+t+`>`)}return bl(n)}var Cl=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function wl(e){return e.replace(Cl,Tl)}function Tl(e,t,n,r){let i=``;for(let e=parseInt(t);e<parseInt(n);e++)i+=r.replace(/\[\s*i\s*\]/g,`[ `+e+` ]`).replace(/UNROLLED_LOOP_INDEX/g,e);return i}function El(e){let t=`precision ${e.precision} float;
+ precision ${e.precision} int;
+ precision ${e.precision} sampler2D;
+ precision ${e.precision} samplerCube;
+ precision ${e.precision} sampler3D;
+ precision ${e.precision} sampler2DArray;
+ precision ${e.precision} sampler2DShadow;
+ precision ${e.precision} samplerCubeShadow;
+ precision ${e.precision} sampler2DArrayShadow;
+ precision ${e.precision} isampler2D;
+ precision ${e.precision} isampler3D;
+ precision ${e.precision} isamplerCube;
+ precision ${e.precision} isampler2DArray;
+ precision ${e.precision} usampler2D;
+ precision ${e.precision} usampler3D;
+ precision ${e.precision} usamplerCube;
+ precision ${e.precision} usampler2DArray;
+ `;return e.precision===`highp`?t+=`
+#define HIGH_PRECISION`:e.precision===`mediump`?t+=`
+#define MEDIUM_PRECISION`:e.precision===`lowp`&&(t+=`
+#define LOW_PRECISION`),t}function Dl(e){let t=`SHADOWMAP_TYPE_BASIC`;return e.shadowMapType===1?t=`SHADOWMAP_TYPE_PCF`:e.shadowMapType===2?t=`SHADOWMAP_TYPE_PCF_SOFT`:e.shadowMapType===3&&(t=`SHADOWMAP_TYPE_VSM`),t}function Ol(e){let t=`ENVMAP_TYPE_CUBE`;if(e.envMap)switch(e.envMapMode){case 301:case 302:t=`ENVMAP_TYPE_CUBE`;break;case 306:t=`ENVMAP_TYPE_CUBE_UV`;break}return t}function kl(e){let t=`ENVMAP_MODE_REFLECTION`;if(e.envMap)switch(e.envMapMode){case 302:t=`ENVMAP_MODE_REFRACTION`;break}return t}function Al(e){let t=`ENVMAP_BLENDING_NONE`;if(e.envMap)switch(e.combine){case 0:t=`ENVMAP_BLENDING_MULTIPLY`;break;case 1:t=`ENVMAP_BLENDING_MIX`;break;case 2:t=`ENVMAP_BLENDING_ADD`;break}return t}function jl(e){let t=e.envMapCubeUVHeight;if(t===null)return null;let n=Math.log2(t)-2,r=1/t;return{texelWidth:1/(3*Math.max(2**n,112)),texelHeight:r,maxMip:n}}function Ml(e,t,n,r){let i=e.getContext(),a=n.defines,o=n.vertexShader,s=n.fragmentShader,c=Dl(n),l=Ol(n),u=kl(n),d=Al(n),f=jl(n),p=pl(n),m=ml(a),h=i.createProgram(),g,_,v=n.glslVersion?`#version `+n.glslVersion+`
+`:``;n.isRawShaderMaterial?(g=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(gl).join(`
+`),g.length>0&&(g+=`
+`),_=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(gl).join(`
+`),_.length>0&&(_+=`
+`)):(g=[El(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.extensionClipCullDistance?`#define USE_CLIP_DISTANCE`:``,n.batching?`#define USE_BATCHING`:``,n.batchingColor?`#define USE_BATCHING_COLOR`:``,n.instancing?`#define USE_INSTANCING`:``,n.instancingColor?`#define USE_INSTANCING_COLOR`:``,n.instancingMorph?`#define USE_INSTANCING_MORPH`:``,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.map?`#define USE_MAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+u:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.displacementMap?`#define USE_DISPLACEMENTMAP`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.mapUv?`#define MAP_UV `+n.mapUv:``,n.alphaMapUv?`#define ALPHAMAP_UV `+n.alphaMapUv:``,n.lightMapUv?`#define LIGHTMAP_UV `+n.lightMapUv:``,n.aoMapUv?`#define AOMAP_UV `+n.aoMapUv:``,n.emissiveMapUv?`#define EMISSIVEMAP_UV `+n.emissiveMapUv:``,n.bumpMapUv?`#define BUMPMAP_UV `+n.bumpMapUv:``,n.normalMapUv?`#define NORMALMAP_UV `+n.normalMapUv:``,n.displacementMapUv?`#define DISPLACEMENTMAP_UV `+n.displacementMapUv:``,n.metalnessMapUv?`#define METALNESSMAP_UV `+n.metalnessMapUv:``,n.roughnessMapUv?`#define ROUGHNESSMAP_UV `+n.roughnessMapUv:``,n.anisotropyMapUv?`#define ANISOTROPYMAP_UV `+n.anisotropyMapUv:``,n.clearcoatMapUv?`#define CLEARCOATMAP_UV `+n.clearcoatMapUv:``,n.clearcoatNormalMapUv?`#define CLEARCOAT_NORMALMAP_UV `+n.clearcoatNormalMapUv:``,n.clearcoatRoughnessMapUv?`#define CLEARCOAT_ROUGHNESSMAP_UV `+n.clearcoatRoughnessMapUv:``,n.iridescenceMapUv?`#define IRIDESCENCEMAP_UV `+n.iridescenceMapUv:``,n.iridescenceThicknessMapUv?`#define IRIDESCENCE_THICKNESSMAP_UV `+n.iridescenceThicknessMapUv:``,n.sheenColorMapUv?`#define SHEEN_COLORMAP_UV `+n.sheenColorMapUv:``,n.sheenRoughnessMapUv?`#define SHEEN_ROUGHNESSMAP_UV `+n.sheenRoughnessMapUv:``,n.specularMapUv?`#define SPECULARMAP_UV `+n.specularMapUv:``,n.specularColorMapUv?`#define SPECULAR_COLORMAP_UV `+n.specularColorMapUv:``,n.specularIntensityMapUv?`#define SPECULAR_INTENSITYMAP_UV `+n.specularIntensityMapUv:``,n.transmissionMapUv?`#define TRANSMISSIONMAP_UV `+n.transmissionMapUv:``,n.thicknessMapUv?`#define THICKNESSMAP_UV `+n.thicknessMapUv:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexColors?`#define USE_COLOR`:``,n.vertexAlphas?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.flatShading?`#define FLAT_SHADED`:``,n.skinning?`#define USE_SKINNING`:``,n.morphTargets?`#define USE_MORPHTARGETS`:``,n.morphNormals&&n.flatShading===!1?`#define USE_MORPHNORMALS`:``,n.morphColors?`#define USE_MORPHCOLORS`:``,n.morphTargetsCount>0?`#define MORPHTARGETS_TEXTURE_STRIDE `+n.morphTextureStride:``,n.morphTargetsCount>0?`#define MORPHTARGETS_COUNT `+n.morphTargetsCount:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.sizeAttenuation?`#define USE_SIZEATTENUATION`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.logarithmicDepthBuffer?`#define USE_LOGDEPTHBUF`:``,n.reverseDepthBuffer?`#define USE_REVERSEDEPTHBUF`:``,`uniform mat4 modelMatrix;`,`uniform mat4 modelViewMatrix;`,`uniform mat4 projectionMatrix;`,`uniform mat4 viewMatrix;`,`uniform mat3 normalMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,`#ifdef USE_INSTANCING`,` attribute mat4 instanceMatrix;`,`#endif`,`#ifdef USE_INSTANCING_COLOR`,` attribute vec3 instanceColor;`,`#endif`,`#ifdef USE_INSTANCING_MORPH`,` uniform sampler2D morphTexture;`,`#endif`,`attribute vec3 position;`,`attribute vec3 normal;`,`attribute vec2 uv;`,`#ifdef USE_UV1`,` attribute vec2 uv1;`,`#endif`,`#ifdef USE_UV2`,` attribute vec2 uv2;`,`#endif`,`#ifdef USE_UV3`,` attribute vec2 uv3;`,`#endif`,`#ifdef USE_TANGENT`,` attribute vec4 tangent;`,`#endif`,`#if defined( USE_COLOR_ALPHA )`,` attribute vec4 color;`,`#elif defined( USE_COLOR )`,` attribute vec3 color;`,`#endif`,`#ifdef USE_SKINNING`,` attribute vec4 skinIndex;`,` attribute vec4 skinWeight;`,`#endif`,`
+`].filter(gl).join(`
+`),_=[El(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.alphaToCoverage?`#define ALPHA_TO_COVERAGE`:``,n.map?`#define USE_MAP`:``,n.matcap?`#define USE_MATCAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+l:``,n.envMap?`#define `+u:``,n.envMap?`#define `+d:``,f?`#define CUBEUV_TEXEL_WIDTH `+f.texelWidth:``,f?`#define CUBEUV_TEXEL_HEIGHT `+f.texelHeight:``,f?`#define CUBEUV_MAX_MIP `+f.maxMip+`.0`:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoat?`#define USE_CLEARCOAT`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.dispersion?`#define USE_DISPERSION`:``,n.iridescence?`#define USE_IRIDESCENCE`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaTest?`#define USE_ALPHATEST`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.sheen?`#define USE_SHEEN`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexColors||n.instancingColor||n.batchingColor?`#define USE_COLOR`:``,n.vertexAlphas?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.gradientMap?`#define USE_GRADIENTMAP`:``,n.flatShading?`#define FLAT_SHADED`:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.premultipliedAlpha?`#define PREMULTIPLIED_ALPHA`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.decodeVideoTexture?`#define DECODE_VIDEO_TEXTURE`:``,n.decodeVideoTextureEmissive?`#define DECODE_VIDEO_TEXTURE_EMISSIVE`:``,n.logarithmicDepthBuffer?`#define USE_LOGDEPTHBUF`:``,n.reverseDepthBuffer?`#define USE_REVERSEDEPTHBUF`:``,`uniform mat4 viewMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,n.toneMapping===0?``:`#define TONE_MAPPING`,n.toneMapping===0?``:V.tonemapping_pars_fragment,n.toneMapping===0?``:ul(`toneMapping`,n.toneMapping),n.dithering?`#define DITHERING`:``,n.opaque?`#define OPAQUE`:``,V.colorspace_pars_fragment,ll(`linearToOutputTexel`,n.outputColorSpace),fl(),n.useDepthPacking?`#define DEPTH_PACKING `+n.depthPacking:``,`
+`].filter(gl).join(`
+`)),o=bl(o),o=_l(o,n),o=vl(o,n),s=bl(s),s=_l(s,n),s=vl(s,n),o=wl(o),s=wl(s),n.isRawShaderMaterial!==!0&&(v=`#version 300 es
+`,g=[p,`#define attribute in`,`#define varying out`,`#define texture2D texture`].join(`
+`)+`
+`+g,_=[`#define varying in`,n.glslVersion===`300 es`?``:`layout(location = 0) out highp vec4 pc_fragColor;`,n.glslVersion===`300 es`?``:`#define gl_FragColor pc_fragColor`,`#define gl_FragDepthEXT gl_FragDepth`,`#define texture2D texture`,`#define textureCube texture`,`#define texture2DProj textureProj`,`#define texture2DLodEXT textureLod`,`#define texture2DProjLodEXT textureProjLod`,`#define textureCubeLodEXT textureLod`,`#define texture2DGradEXT textureGrad`,`#define texture2DProjGradEXT textureProjGrad`,`#define textureCubeGradEXT textureGrad`].join(`
+`)+`
+`+_);let y=v+g+o,b=v+_+s,x=nl(i,i.VERTEX_SHADER,y),S=nl(i,i.FRAGMENT_SHADER,b);i.attachShader(h,x),i.attachShader(h,S),n.index0AttributeName===void 0?n.morphTargets===!0&&i.bindAttribLocation(h,0,`position`):i.bindAttribLocation(h,0,n.index0AttributeName),i.linkProgram(h);function C(t){if(e.debug.checkShaderErrors){let n=i.getProgramInfoLog(h).trim(),r=i.getShaderInfoLog(x).trim(),a=i.getShaderInfoLog(S).trim(),o=!0,s=!0;if(i.getProgramParameter(h,i.LINK_STATUS)===!1)if(o=!1,typeof e.debug.onShaderError==`function`)e.debug.onShaderError(i,h,x,S);else{let e=cl(i,x,`vertex`),r=cl(i,S,`fragment`);console.error(`THREE.WebGLProgram: Shader Error `+i.getError()+` - VALIDATE_STATUS `+i.getProgramParameter(h,i.VALIDATE_STATUS)+`
+
+Material Name: `+t.name+`
+Material Type: `+t.type+`
+
+Program Info Log: `+n+`
+`+e+`
+`+r)}else n===``?(r===``||a===``)&&(s=!1):console.warn(`THREE.WebGLProgram: Program Info Log:`,n);s&&(t.diagnostics={runnable:o,programLog:n,vertexShader:{log:r,prefix:g},fragmentShader:{log:a,prefix:_}})}i.deleteShader(x),i.deleteShader(S),w=new tl(i,h),T=hl(i,h)}let w;this.getUniforms=function(){return w===void 0&&C(this),w};let T;this.getAttributes=function(){return T===void 0&&C(this),T};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=i.getProgramParameter(h,rl)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(h),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=il++,this.cacheKey=t,this.usedTimes=1,this.program=h,this.vertexShader=x,this.fragmentShader=S,this}var Nl=0,Pl=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,n=e.fragmentShader,r=this._getShaderStage(t),i=this._getShaderStage(n),a=this._getShaderCacheForMaterial(e);return a.has(r)===!1&&(a.add(r),r.usedTimes++),a.has(i)===!1&&(a.add(i),i.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let e of t)e.usedTimes--,e.usedTimes===0&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new Fl(e),t.set(e,n)),n}},Fl=class{constructor(e){this.id=Nl++,this.code=e,this.usedTimes=0}};function Il(e,t,n,r,i,a,o){let s=new Vn,c=new Pl,l=new Set,u=[],d=i.logarithmicDepthBuffer,f=i.vertexTextures,p=i.precision,m={MeshDepthMaterial:`depth`,MeshDistanceMaterial:`distanceRGBA`,MeshNormalMaterial:`normal`,MeshBasicMaterial:`basic`,MeshLambertMaterial:`lambert`,MeshPhongMaterial:`phong`,MeshToonMaterial:`toon`,MeshStandardMaterial:`physical`,MeshPhysicalMaterial:`physical`,MeshMatcapMaterial:`matcap`,LineBasicMaterial:`basic`,LineDashedMaterial:`dashed`,PointsMaterial:`points`,ShadowMaterial:`shadow`,SpriteMaterial:`sprite`};function h(e){return l.add(e),e===0?`uv`:`uv${e}`}function g(a,s,u,g,_){let v=g.fog,y=_.geometry,b=a.isMeshStandardMaterial?g.environment:null,x=(a.isMeshStandardMaterial?n:t).get(a.envMap||b),S=x&&x.mapping===306?x.image.height:null,C=m[a.type];a.precision!==null&&(p=i.getMaxPrecision(a.precision),p!==a.precision&&console.warn(`THREE.WebGLProgram.getParameters:`,a.precision,`not supported, using`,p,`instead.`));let w=y.morphAttributes.position||y.morphAttributes.normal||y.morphAttributes.color,T=w===void 0?0:w.length,E=0;y.morphAttributes.position!==void 0&&(E=1),y.morphAttributes.normal!==void 0&&(E=2),y.morphAttributes.color!==void 0&&(E=3);let D,O,k,ee;if(C){let e=ds[C];D=e.vertexShader,O=e.fragmentShader}else D=a.vertexShader,O=a.fragmentShader,c.update(a),k=c.getVertexShaderID(a),ee=c.getFragmentShaderID(a);let te=e.getRenderTarget(),ne=e.state.buffers.depth.getReversed(),re=_.isInstancedMesh===!0,A=_.isBatchedMesh===!0,ie=!!a.map,ae=!!a.matcap,oe=!!x,se=!!a.aoMap,ce=!!a.lightMap,le=!!a.bumpMap,ue=!!a.normalMap,de=!!a.displacementMap,fe=!!a.emissiveMap,pe=!!a.metalnessMap,me=!!a.roughnessMap,he=a.anisotropy>0,ge=a.clearcoat>0,_e=a.dispersion>0,ve=a.iridescence>0,ye=a.sheen>0,be=a.transmission>0,j=he&&!!a.anisotropyMap,xe=ge&&!!a.clearcoatMap,Se=ge&&!!a.clearcoatNormalMap,Ce=ge&&!!a.clearcoatRoughnessMap,M=ve&&!!a.iridescenceMap,we=ve&&!!a.iridescenceThicknessMap,N=ye&&!!a.sheenColorMap,P=ye&&!!a.sheenRoughnessMap,Te=!!a.specularMap,Ee=!!a.specularColorMap,F=!!a.specularIntensityMap,De=be&&!!a.transmissionMap,Oe=be&&!!a.thicknessMap,ke=!!a.gradientMap,Ae=!!a.alphaMap,je=a.alphaTest>0,Me=!!a.alphaHash,Ne=!!a.extensions,Pe=0;a.toneMapped&&(te===null||te.isXRRenderTarget===!0)&&(Pe=e.toneMapping);let Fe={shaderID:C,shaderType:a.type,shaderName:a.name,vertexShader:D,fragmentShader:O,defines:a.defines,customVertexShaderID:k,customFragmentShaderID:ee,isRawShaderMaterial:a.isRawShaderMaterial===!0,glslVersion:a.glslVersion,precision:p,batching:A,batchingColor:A&&_._colorsTexture!==null,instancing:re,instancingColor:re&&_.instanceColor!==null,instancingMorph:re&&_.morphTexture!==null,supportsVertexTextures:f,outputColorSpace:te===null?e.outputColorSpace:te.isXRRenderTarget===!0?te.texture.colorSpace:qe,alphaToCoverage:!!a.alphaToCoverage,map:ie,matcap:ae,envMap:oe,envMapMode:oe&&x.mapping,envMapCubeUVHeight:S,aoMap:se,lightMap:ce,bumpMap:le,normalMap:ue,displacementMap:f&&de,emissiveMap:fe,normalMapObjectSpace:ue&&a.normalMapType===1,normalMapTangentSpace:ue&&a.normalMapType===0,metalnessMap:pe,roughnessMap:me,anisotropy:he,anisotropyMap:j,clearcoat:ge,clearcoatMap:xe,clearcoatNormalMap:Se,clearcoatRoughnessMap:Ce,dispersion:_e,iridescence:ve,iridescenceMap:M,iridescenceThicknessMap:we,sheen:ye,sheenColorMap:N,sheenRoughnessMap:P,specularMap:Te,specularColorMap:Ee,specularIntensityMap:F,transmission:be,transmissionMap:De,thicknessMap:Oe,gradientMap:ke,opaque:a.transparent===!1&&a.blending===1&&a.alphaToCoverage===!1,alphaMap:Ae,alphaTest:je,alphaHash:Me,combine:a.combine,mapUv:ie&&h(a.map.channel),aoMapUv:se&&h(a.aoMap.channel),lightMapUv:ce&&h(a.lightMap.channel),bumpMapUv:le&&h(a.bumpMap.channel),normalMapUv:ue&&h(a.normalMap.channel),displacementMapUv:de&&h(a.displacementMap.channel),emissiveMapUv:fe&&h(a.emissiveMap.channel),metalnessMapUv:pe&&h(a.metalnessMap.channel),roughnessMapUv:me&&h(a.roughnessMap.channel),anisotropyMapUv:j&&h(a.anisotropyMap.channel),clearcoatMapUv:xe&&h(a.clearcoatMap.channel),clearcoatNormalMapUv:Se&&h(a.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ce&&h(a.clearcoatRoughnessMap.channel),iridescenceMapUv:M&&h(a.iridescenceMap.channel),iridescenceThicknessMapUv:we&&h(a.iridescenceThicknessMap.channel),sheenColorMapUv:N&&h(a.sheenColorMap.channel),sheenRoughnessMapUv:P&&h(a.sheenRoughnessMap.channel),specularMapUv:Te&&h(a.specularMap.channel),specularColorMapUv:Ee&&h(a.specularColorMap.channel),specularIntensityMapUv:F&&h(a.specularIntensityMap.channel),transmissionMapUv:De&&h(a.transmissionMap.channel),thicknessMapUv:Oe&&h(a.thicknessMap.channel),alphaMapUv:Ae&&h(a.alphaMap.channel),vertexTangents:!!y.attributes.tangent&&(ue||he),vertexColors:a.vertexColors,vertexAlphas:a.vertexColors===!0&&!!y.attributes.color&&y.attributes.color.itemSize===4,pointsUvs:_.isPoints===!0&&!!y.attributes.uv&&(ie||Ae),fog:!!v,useFog:a.fog===!0,fogExp2:!!v&&v.isFogExp2,flatShading:a.flatShading===!0,sizeAttenuation:a.sizeAttenuation===!0,logarithmicDepthBuffer:d,reverseDepthBuffer:ne,skinning:_.isSkinnedMesh===!0,morphTargets:y.morphAttributes.position!==void 0,morphNormals:y.morphAttributes.normal!==void 0,morphColors:y.morphAttributes.color!==void 0,morphTargetsCount:T,morphTextureStride:E,numDirLights:s.directional.length,numPointLights:s.point.length,numSpotLights:s.spot.length,numSpotLightMaps:s.spotLightMap.length,numRectAreaLights:s.rectArea.length,numHemiLights:s.hemi.length,numDirLightShadows:s.directionalShadowMap.length,numPointLightShadows:s.pointShadowMap.length,numSpotLightShadows:s.spotShadowMap.length,numSpotLightShadowsWithMaps:s.numSpotLightShadowsWithMaps,numLightProbes:s.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:a.dithering,shadowMapEnabled:e.shadowMap.enabled&&u.length>0,shadowMapType:e.shadowMap.type,toneMapping:Pe,decodeVideoTexture:ie&&a.map.isVideoTexture===!0&&zt.getTransfer(a.map.colorSpace)===`srgb`,decodeVideoTextureEmissive:fe&&a.emissiveMap.isVideoTexture===!0&&zt.getTransfer(a.emissiveMap.colorSpace)===`srgb`,premultipliedAlpha:a.premultipliedAlpha,doubleSided:a.side===2,flipSided:a.side===1,useDepthPacking:a.depthPacking>=0,depthPacking:a.depthPacking||0,index0AttributeName:a.index0AttributeName,extensionClipCullDistance:Ne&&a.extensions.clipCullDistance===!0&&r.has(`WEBGL_clip_cull_distance`),extensionMultiDraw:(Ne&&a.extensions.multiDraw===!0||A)&&r.has(`WEBGL_multi_draw`),rendererExtensionParallelShaderCompile:r.has(`KHR_parallel_shader_compile`),customProgramCacheKey:a.customProgramCacheKey()};return Fe.vertexUv1s=l.has(1),Fe.vertexUv2s=l.has(2),Fe.vertexUv3s=l.has(3),l.clear(),Fe}function _(t){let n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),t.defines!==void 0)for(let e in t.defines)n.push(e),n.push(t.defines[e]);return t.isRawShaderMaterial===!1&&(v(n,t),y(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()}function v(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}function y(e,t){s.disableAll(),t.supportsVertexTextures&&s.enable(0),t.instancing&&s.enable(1),t.instancingColor&&s.enable(2),t.instancingMorph&&s.enable(3),t.matcap&&s.enable(4),t.envMap&&s.enable(5),t.normalMapObjectSpace&&s.enable(6),t.normalMapTangentSpace&&s.enable(7),t.clearcoat&&s.enable(8),t.iridescence&&s.enable(9),t.alphaTest&&s.enable(10),t.vertexColors&&s.enable(11),t.vertexAlphas&&s.enable(12),t.vertexUv1s&&s.enable(13),t.vertexUv2s&&s.enable(14),t.vertexUv3s&&s.enable(15),t.vertexTangents&&s.enable(16),t.anisotropy&&s.enable(17),t.alphaHash&&s.enable(18),t.batching&&s.enable(19),t.dispersion&&s.enable(20),t.batchingColor&&s.enable(21),e.push(s.mask),s.disableAll(),t.fog&&s.enable(0),t.useFog&&s.enable(1),t.flatShading&&s.enable(2),t.logarithmicDepthBuffer&&s.enable(3),t.reverseDepthBuffer&&s.enable(4),t.skinning&&s.enable(5),t.morphTargets&&s.enable(6),t.morphNormals&&s.enable(7),t.morphColors&&s.enable(8),t.premultipliedAlpha&&s.enable(9),t.shadowMapEnabled&&s.enable(10),t.doubleSided&&s.enable(11),t.flipSided&&s.enable(12),t.useDepthPacking&&s.enable(13),t.dithering&&s.enable(14),t.transmission&&s.enable(15),t.sheen&&s.enable(16),t.opaque&&s.enable(17),t.pointsUvs&&s.enable(18),t.decodeVideoTexture&&s.enable(19),t.decodeVideoTextureEmissive&&s.enable(20),t.alphaToCoverage&&s.enable(21),e.push(s.mask)}function b(e){let t=m[e.type],n;if(t){let e=ds[t];n=di.clone(e.uniforms)}else n=e.uniforms;return n}function x(t,n){let r;for(let e=0,t=u.length;e<t;e++){let t=u[e];if(t.cacheKey===n){r=t,++r.usedTimes;break}}return r===void 0&&(r=new Ml(e,n,t,a),u.push(r)),r}function S(e){if(--e.usedTimes===0){let t=u.indexOf(e);u[t]=u[u.length-1],u.pop(),e.destroy()}}function C(e){c.remove(e)}function w(){c.dispose()}return{getParameters:g,getProgramCacheKey:_,getUniforms:b,acquireProgram:x,releaseProgram:S,releaseShaderCache:C,programs:u,dispose:w}}function Ll(){let e=new WeakMap;function t(t){return e.has(t)}function n(t){let n=e.get(t);return n===void 0&&(n={},e.set(t,n)),n}function r(t){e.delete(t)}function i(t,n,r){e.get(t)[n]=r}function a(){e=new WeakMap}return{has:t,get:n,remove:r,update:i,dispose:a}}function Rl(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.material.id===t.material.id?e.z===t.z?e.id-t.id:e.z-t.z:e.material.id-t.material.id:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function zl(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:t.z-e.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function Bl(){let e=[],t=0,n=[],r=[],i=[];function a(){t=0,n.length=0,r.length=0,i.length=0}function o(n,r,i,a,o,s){let c=e[t];return c===void 0?(c={id:n.id,object:n,geometry:r,material:i,groupOrder:a,renderOrder:n.renderOrder,z:o,group:s},e[t]=c):(c.id=n.id,c.object=n,c.geometry=r,c.material=i,c.groupOrder=a,c.renderOrder=n.renderOrder,c.z=o,c.group=s),t++,c}function s(e,t,a,s,c,l){let u=o(e,t,a,s,c,l);a.transmission>0?r.push(u):a.transparent===!0?i.push(u):n.push(u)}function c(e,t,a,s,c,l){let u=o(e,t,a,s,c,l);a.transmission>0?r.unshift(u):a.transparent===!0?i.unshift(u):n.unshift(u)}function l(e,t){n.length>1&&n.sort(e||Rl),r.length>1&&r.sort(t||zl),i.length>1&&i.sort(t||zl)}function u(){for(let n=t,r=e.length;n<r;n++){let t=e[n];if(t.id===null)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}}return{opaque:n,transmissive:r,transparent:i,init:a,push:s,unshift:c,finish:u,sort:l}}function Vl(){let e=new WeakMap;function t(t,n){let r=e.get(t),i;return r===void 0?(i=new Bl,e.set(t,[i])):n>=r.length?(i=new Bl,r.push(i)):i=r[n],i}function n(){e=new WeakMap}return{get:t,dispose:n}}function Hl(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={direction:new R,color:new B};break;case`SpotLight`:n={position:new R,direction:new R,color:new B,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case`PointLight`:n={position:new R,color:new B,distance:0,decay:0};break;case`HemisphereLight`:n={direction:new R,skyColor:new B,groundColor:new B};break;case`RectAreaLight`:n={color:new B,position:new R,halfWidth:new R,halfHeight:new R};break}return e[t.id]=n,n}}}function Ul(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new L};break;case`SpotLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new L};break;case`PointLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new L,shadowCameraNear:1,shadowCameraFar:1e3};break}return e[t.id]=n,n}}}var Wl=0;function Gl(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+ +!!t.map-!!e.map}function Kl(e){let t=new Hl,n=Ul(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)r.probe.push(new R);let i=new R,a=new z,o=new z;function s(i){let a=0,o=0,s=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0;i.sort(Gl);for(let e=0,y=i.length;e<y;e++){let y=i[e],b=y.color,x=y.intensity,S=y.distance,C=y.shadow&&y.shadow.map?y.shadow.map.texture:null;if(y.isAmbientLight)a+=b.r*x,o+=b.g*x,s+=b.b*x;else if(y.isLightProbe){for(let e=0;e<9;e++)r.probe[e].addScaledVector(y.sh.coefficients[e],x);v++}else if(y.isDirectionalLight){let e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),y.castShadow){let e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,r.directionalShadow[c]=t,r.directionalShadowMap[c]=C,r.directionalShadowMatrix[c]=y.shadow.matrix,p++}r.directional[c]=e,c++}else if(y.isSpotLight){let e=t.get(y);e.position.setFromMatrixPosition(y.matrixWorld),e.color.copy(b).multiplyScalar(x),e.distance=S,e.coneCos=Math.cos(y.angle),e.penumbraCos=Math.cos(y.angle*(1-y.penumbra)),e.decay=y.decay,r.spot[u]=e;let i=y.shadow;if(y.map&&(r.spotLightMap[g]=y.map,g++,i.updateMatrices(y),y.castShadow&&_++),r.spotLightMatrix[u]=i.matrix,y.castShadow){let e=n.get(y);e.shadowIntensity=i.intensity,e.shadowBias=i.bias,e.shadowNormalBias=i.normalBias,e.shadowRadius=i.radius,e.shadowMapSize=i.mapSize,r.spotShadow[u]=e,r.spotShadowMap[u]=C,h++}u++}else if(y.isRectAreaLight){let e=t.get(y);e.color.copy(b).multiplyScalar(x),e.halfWidth.set(y.width*.5,0,0),e.halfHeight.set(0,y.height*.5,0),r.rectArea[d]=e,d++}else if(y.isPointLight){let e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),e.distance=y.distance,e.decay=y.decay,y.castShadow){let e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,r.pointShadow[l]=t,r.pointShadowMap[l]=C,r.pointShadowMatrix[l]=y.shadow.matrix,m++}r.point[l]=e,l++}else if(y.isHemisphereLight){let e=t.get(y);e.skyColor.copy(y.color).multiplyScalar(x),e.groundColor.copy(y.groundColor).multiplyScalar(x),r.hemi[f]=e,f++}}d>0&&(e.has(`OES_texture_float_linear`)===!0?(r.rectAreaLTC1=H.LTC_FLOAT_1,r.rectAreaLTC2=H.LTC_FLOAT_2):(r.rectAreaLTC1=H.LTC_HALF_1,r.rectAreaLTC2=H.LTC_HALF_2)),r.ambient[0]=a,r.ambient[1]=o,r.ambient[2]=s;let y=r.hash;(y.directionalLength!==c||y.pointLength!==l||y.spotLength!==u||y.rectAreaLength!==d||y.hemiLength!==f||y.numDirectionalShadows!==p||y.numPointShadows!==m||y.numSpotShadows!==h||y.numSpotMaps!==g||y.numLightProbes!==v)&&(r.directional.length=c,r.spot.length=u,r.rectArea.length=d,r.point.length=l,r.hemi.length=f,r.directionalShadow.length=p,r.directionalShadowMap.length=p,r.pointShadow.length=m,r.pointShadowMap.length=m,r.spotShadow.length=h,r.spotShadowMap.length=h,r.directionalShadowMatrix.length=p,r.pointShadowMatrix.length=m,r.spotLightMatrix.length=h+g-_,r.spotLightMap.length=g,r.numSpotLightShadowsWithMaps=_,r.numLightProbes=v,y.directionalLength=c,y.pointLength=l,y.spotLength=u,y.rectAreaLength=d,y.hemiLength=f,y.numDirectionalShadows=p,y.numPointShadows=m,y.numSpotShadows=h,y.numSpotMaps=g,y.numLightProbes=v,r.version=Wl++)}function c(e,t){let n=0,s=0,c=0,l=0,u=0,d=t.matrixWorldInverse;for(let t=0,f=e.length;t<f;t++){let f=e[t];if(f.isDirectionalLight){let e=r.directional[n];e.direction.setFromMatrixPosition(f.matrixWorld),i.setFromMatrixPosition(f.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(d),n++}else if(f.isSpotLight){let e=r.spot[c];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),e.direction.setFromMatrixPosition(f.matrixWorld),i.setFromMatrixPosition(f.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(d),c++}else if(f.isRectAreaLight){let e=r.rectArea[l];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),o.identity(),a.copy(f.matrixWorld),a.premultiply(d),o.extractRotation(a),e.halfWidth.set(f.width*.5,0,0),e.halfHeight.set(0,f.height*.5,0),e.halfWidth.applyMatrix4(o),e.halfHeight.applyMatrix4(o),l++}else if(f.isPointLight){let e=r.point[s];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),s++}else if(f.isHemisphereLight){let e=r.hemi[u];e.direction.setFromMatrixPosition(f.matrixWorld),e.direction.transformDirection(d),u++}}}return{setup:s,setupView:c,state:r}}function ql(e){let t=new Kl(e),n=[],r=[];function i(e){l.camera=e,n.length=0,r.length=0}function a(e){n.push(e)}function o(e){r.push(e)}function s(){t.setup(n)}function c(e){t.setupView(n,e)}let l={lightsArray:n,shadowsArray:r,camera:null,lights:t,transmissionRenderTarget:{}};return{init:i,state:l,setupLights:s,setupLightsView:c,pushLight:a,pushShadow:o}}function Jl(e){let t=new WeakMap;function n(n,r=0){let i=t.get(n),a;return i===void 0?(a=new ql(e),t.set(n,[a])):r>=i.length?(a=new ql(e),i.push(a)):a=i[r],a}function r(){t=new WeakMap}return{get:n,dispose:r}}var Yl=`void main() {
+ gl_Position = vec4( position, 1.0 );
+}`,Xl=`uniform sampler2D shadow_pass;
+uniform vec2 resolution;
+uniform float radius;
+#include <packing>
+void main() {
+ const float samples = float( VSM_SAMPLES );
+ float mean = 0.0;
+ float squared_mean = 0.0;
+ float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
+ float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
+ for ( float i = 0.0; i < samples; i ++ ) {
+ float uvOffset = uvStart + i * uvStride;
+ #ifdef HORIZONTAL_PASS
+ vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );
+ mean += distribution.x;
+ squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
+ #else
+ float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );
+ mean += depth;
+ squared_mean += depth * depth;
+ #endif
+ }
+ mean = mean / samples;
+ squared_mean = squared_mean / samples;
+ float std_dev = sqrt( squared_mean - mean * mean );
+ gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
+}`;function Zl(e,t,n){let r=new ca,i=new L,a=new L,o=new Yt,s=new La({depthPacking:Ge}),c=new Ra,u={},d=n.maxTextureSize,f={0:1,1:0,2:2},p=new mi({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new L},radius:{value:4}},vertexShader:Yl,fragmentShader:Xl}),m=p.clone();m.defines.HORIZONTAL_PASS=1;let h=new Gr;h.setAttribute(`position`,new Pr(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let g=new ri(h,p),_=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let v=this.type;this.render=function(t,n,s){if(_.enabled===!1||_.autoUpdate===!1&&_.needsUpdate===!1||t.length===0)return;let c=e.getRenderTarget(),u=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.state;p.setBlending(0),p.buffers.color.setClear(1,1,1,1),p.buffers.depth.setTest(!0),p.setScissorTest(!1);let m=v!==3&&this.type===3,h=v===3&&this.type!==3;for(let c=0,u=t.length;c<u;c++){let u=t[c],f=u.shadow;if(f===void 0){console.warn(`THREE.WebGLShadowMap:`,u,`has no shadow.`);continue}if(f.autoUpdate===!1&&f.needsUpdate===!1)continue;i.copy(f.mapSize);let g=f.getFrameExtents();if(i.multiply(g),a.copy(f.mapSize),(i.x>d||i.y>d)&&(i.x>d&&(a.x=Math.floor(d/g.x),i.x=a.x*g.x,f.mapSize.x=a.x),i.y>d&&(a.y=Math.floor(d/g.y),i.y=a.y*g.y,f.mapSize.y=a.y)),f.map===null||m===!0||h===!0){let e=this.type===3?{}:{minFilter:l,magFilter:l};f.map!==null&&f.map.dispose(),f.map=new Zt(i.x,i.y,e),f.map.texture.name=u.name+`.shadowMap`,f.camera.updateProjectionMatrix()}e.setRenderTarget(f.map),e.clear();let _=f.getViewportCount();for(let e=0;e<_;e++){let t=f.getViewport(e);o.set(a.x*t.x,a.y*t.y,a.x*t.z,a.y*t.w),p.viewport(o),f.updateMatrices(u,e),r=f.getFrustum(),x(n,s,f.camera,u,this.type)}f.isPointLightShadow!==!0&&this.type===3&&y(f,s),f.needsUpdate=!1}v=this.type,_.needsUpdate=!1,e.setRenderTarget(c,u,f)};function y(n,r){let a=t.update(g);p.defines.VSM_SAMPLES!==n.blurSamples&&(p.defines.VSM_SAMPLES=n.blurSamples,m.defines.VSM_SAMPLES=n.blurSamples,p.needsUpdate=!0,m.needsUpdate=!0),n.mapPass===null&&(n.mapPass=new Zt(i.x,i.y)),p.uniforms.shadow_pass.value=n.map.texture,p.uniforms.resolution.value=n.mapSize,p.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(r,null,a,p,g,null),m.uniforms.shadow_pass.value=n.mapPass.texture,m.uniforms.resolution.value=n.mapSize,m.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(r,null,a,m,g,null)}function b(t,n,r,i){let a=null,o=r.isPointLight===!0?t.customDistanceMaterial:t.customDepthMaterial;if(o!==void 0)a=o;else if(a=r.isPointLight===!0?c:s,e.localClippingEnabled&&n.clipShadows===!0&&Array.isArray(n.clippingPlanes)&&n.clippingPlanes.length!==0||n.displacementMap&&n.displacementScale!==0||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||n.alphaToCoverage===!0){let e=a.uuid,t=n.uuid,r=u[e];r===void 0&&(r={},u[e]=r);let i=r[t];i===void 0&&(i=a.clone(),r[t]=i,n.addEventListener(`dispose`,S)),a=i}if(a.visible=n.visible,a.wireframe=n.wireframe,i===3?a.side=n.shadowSide===null?n.side:n.shadowSide:a.side=n.shadowSide===null?f[n.side]:n.shadowSide,a.alphaMap=n.alphaMap,a.alphaTest=n.alphaToCoverage===!0?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,r.isPointLight===!0&&a.isMeshDistanceMaterial===!0){let t=e.properties.get(a);t.light=r}return a}function x(n,i,a,o,s){if(n.visible===!1)return;if(n.layers.test(i.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&s===3)&&(!n.frustumCulled||r.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,n.matrixWorld);let r=t.update(n),c=n.material;if(Array.isArray(c)){let t=r.groups;for(let l=0,u=t.length;l<u;l++){let u=t[l],d=c[u.materialIndex];if(d&&d.visible){let t=b(n,d,o,s);n.onBeforeShadow(e,n,i,a,r,t,u),e.renderBufferDirect(a,null,r,t,n,u),n.onAfterShadow(e,n,i,a,r,t,u)}}}else if(c.visible){let t=b(n,c,o,s);n.onBeforeShadow(e,n,i,a,r,t,null),e.renderBufferDirect(a,null,r,t,n,null),n.onAfterShadow(e,n,i,a,r,t,null)}}let c=n.children;for(let e=0,t=c.length;e<t;e++)x(c[e],i,a,o,s)}function S(e){e.target.removeEventListener(`dispose`,S);for(let t in u){let n=u[t],r=e.target.uuid;r in n&&(n[r].dispose(),delete n[r])}}}var Ql={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3};function $l(e,t){function n(){let t=!1,n=new Yt,r=null,i=new Yt(0,0,0,0);return{setMask:function(n){r!==n&&!t&&(e.colorMask(n,n,n,n),r=n)},setLocked:function(e){t=e},setClear:function(t,r,a,o,s){s===!0&&(t*=o,r*=o,a*=o),n.set(t,r,a,o),i.equals(n)===!1&&(e.clearColor(t,r,a,o),i.copy(n))},reset:function(){t=!1,r=null,i.set(-1,0,0,0)}}}function r(){let n=!1,r=!1,i=null,a=null,o=null;return{setReversed:function(e){if(r!==e){let n=t.get(`EXT_clip_control`);e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),r=e;let i=o;o=null,this.setClear(i)}},getReversed:function(){return r},setTest:function(t){t?fe(e.DEPTH_TEST):pe(e.DEPTH_TEST)},setMask:function(t){i!==t&&!n&&(e.depthMask(t),i=t)},setFunc:function(t){if(r&&(t=Ql[t]),a!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}a=t}},setLocked:function(e){n=e},setClear:function(t){o!==t&&(r&&(t=1-t),e.clearDepth(t),o=t)},reset:function(){n=!1,i=null,a=null,o=null,r=!1}}}function i(){let t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null;return{setTest:function(n){t||(n?fe(e.STENCIL_TEST):pe(e.STENCIL_TEST))},setMask:function(r){n!==r&&!t&&(e.stencilMask(r),n=r)},setFunc:function(t,n,o){(r!==t||i!==n||a!==o)&&(e.stencilFunc(t,n,o),r=t,i=n,a=o)},setOp:function(t,n,r){(o!==t||s!==n||c!==r)&&(e.stencilOp(t,n,r),o=t,s=n,c=r)},setLocked:function(e){t=e},setClear:function(t){l!==t&&(e.clearStencil(t),l=t)},reset:function(){t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null}}}let a=new n,o=new r,s=new i,c=new WeakMap,l=new WeakMap,u={},d={},f=new WeakMap,p=[],m=null,h=!1,g=null,_=null,v=null,y=null,b=null,x=null,S=null,C=new B(0,0,0),w=0,T=!1,E=null,D=null,O=null,k=null,ee=null,te=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),ne=!1,re=0,A=e.getParameter(e.VERSION);A.indexOf(`WebGL`)===-1?A.indexOf(`OpenGL ES`)!==-1&&(re=parseFloat(/^OpenGL ES (\d)/.exec(A)[1]),ne=re>=2):(re=parseFloat(/^WebGL (\d)/.exec(A)[1]),ne=re>=1);let ie=null,ae={},oe=e.getParameter(e.SCISSOR_BOX),se=e.getParameter(e.VIEWPORT),ce=new Yt().fromArray(oe),le=new Yt().fromArray(se);function ue(t,n,r,i){let a=new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;o<r;o++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(n,0,e.RGBA,1,1,i,0,e.RGBA,e.UNSIGNED_BYTE,a):e.texImage2D(n+o,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,a);return o}let de={};de[e.TEXTURE_2D]=ue(e.TEXTURE_2D,e.TEXTURE_2D,1),de[e.TEXTURE_CUBE_MAP]=ue(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),de[e.TEXTURE_2D_ARRAY]=ue(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),de[e.TEXTURE_3D]=ue(e.TEXTURE_3D,e.TEXTURE_3D,1,1),a.setClear(0,0,0,1),o.setClear(1),s.setClear(0),fe(e.DEPTH_TEST),o.setFunc(3),j(!1),xe(1),fe(e.CULL_FACE),ye(0);function fe(t){u[t]!==!0&&(e.enable(t),u[t]=!0)}function pe(t){u[t]!==!1&&(e.disable(t),u[t]=!1)}function me(t,n){return d[t]===n?!1:(e.bindFramebuffer(t,n),d[t]=n,t===e.DRAW_FRAMEBUFFER&&(d[e.FRAMEBUFFER]=n),t===e.FRAMEBUFFER&&(d[e.DRAW_FRAMEBUFFER]=n),!0)}function he(t,n){let r=p,i=!1;if(t){r=f.get(n),r===void 0&&(r=[],f.set(n,r));let a=t.textures;if(r.length!==a.length||r[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=a.length;t<n;t++)r[t]=e.COLOR_ATTACHMENT0+t;r.length=a.length,i=!0}}else r[0]!==e.BACK&&(r[0]=e.BACK,i=!0);i&&e.drawBuffers(r)}function ge(t){return m===t?!1:(e.useProgram(t),m=t,!0)}let _e={100:e.FUNC_ADD,101:e.FUNC_SUBTRACT,102:e.FUNC_REVERSE_SUBTRACT};_e[103]=e.MIN,_e[104]=e.MAX;let ve={200:e.ZERO,201:e.ONE,202:e.SRC_COLOR,204:e.SRC_ALPHA,210:e.SRC_ALPHA_SATURATE,208:e.DST_COLOR,206:e.DST_ALPHA,203:e.ONE_MINUS_SRC_COLOR,205:e.ONE_MINUS_SRC_ALPHA,209:e.ONE_MINUS_DST_COLOR,207:e.ONE_MINUS_DST_ALPHA,211:e.CONSTANT_COLOR,212:e.ONE_MINUS_CONSTANT_COLOR,213:e.CONSTANT_ALPHA,214:e.ONE_MINUS_CONSTANT_ALPHA};function ye(t,n,r,i,a,o,s,c,l,u){if(t===0){h===!0&&(pe(e.BLEND),h=!1);return}if(h===!1&&(fe(e.BLEND),h=!0),t!==5){if(t!==g||u!==T){if((_!==100||b!==100)&&(e.blendEquation(e.FUNC_ADD),_=100,b=100),u)switch(t){case 1:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.ONE,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFuncSeparate(e.ZERO,e.SRC_COLOR,e.ZERO,e.SRC_ALPHA);break;default:console.error(`THREE.WebGLState: Invalid blending: `,t);break}else switch(t){case 1:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.SRC_ALPHA,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFunc(e.ZERO,e.SRC_COLOR);break;default:console.error(`THREE.WebGLState: Invalid blending: `,t);break}v=null,y=null,x=null,S=null,C.set(0,0,0),w=0,g=t,T=u}return}a||=n,o||=r,s||=i,(n!==_||a!==b)&&(e.blendEquationSeparate(_e[n],_e[a]),_=n,b=a),(r!==v||i!==y||o!==x||s!==S)&&(e.blendFuncSeparate(ve[r],ve[i],ve[o],ve[s]),v=r,y=i,x=o,S=s),(c.equals(C)===!1||l!==w)&&(e.blendColor(c.r,c.g,c.b,l),C.copy(c),w=l),g=t,T=!1}function be(t,n){t.side===2?pe(e.CULL_FACE):fe(e.CULL_FACE);let r=t.side===1;n&&(r=!r),j(r),t.blending===1&&t.transparent===!1?ye(0):ye(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),o.setFunc(t.depthFunc),o.setTest(t.depthTest),o.setMask(t.depthWrite),a.setMask(t.colorWrite);let i=t.stencilWrite;s.setTest(i),i&&(s.setMask(t.stencilWriteMask),s.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),s.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),Ce(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),t.alphaToCoverage===!0?fe(e.SAMPLE_ALPHA_TO_COVERAGE):pe(e.SAMPLE_ALPHA_TO_COVERAGE)}function j(t){E!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),E=t)}function xe(t){t===0?pe(e.CULL_FACE):(fe(e.CULL_FACE),t!==D&&(t===1?e.cullFace(e.BACK):t===2?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))),D=t}function Se(t){t!==O&&(ne&&e.lineWidth(t),O=t)}function Ce(t,n,r){t?(fe(e.POLYGON_OFFSET_FILL),(k!==n||ee!==r)&&(e.polygonOffset(n,r),k=n,ee=r)):pe(e.POLYGON_OFFSET_FILL)}function M(t){t?fe(e.SCISSOR_TEST):pe(e.SCISSOR_TEST)}function we(t){t===void 0&&(t=e.TEXTURE0+te-1),ie!==t&&(e.activeTexture(t),ie=t)}function N(t,n,r){r===void 0&&(r=ie===null?e.TEXTURE0+te-1:ie);let i=ae[r];i===void 0&&(i={type:void 0,texture:void 0},ae[r]=i),(i.type!==t||i.texture!==n)&&(ie!==r&&(e.activeTexture(r),ie=r),e.bindTexture(t,n||de[t]),i.type=t,i.texture=n)}function P(){let t=ae[ie];t!==void 0&&t.type!==void 0&&(e.bindTexture(t.type,null),t.type=void 0,t.texture=void 0)}function Te(){try{e.compressedTexImage2D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Ee(){try{e.compressedTexImage3D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function F(){try{e.texSubImage2D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function De(){try{e.texSubImage3D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Oe(){try{e.compressedTexSubImage2D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function ke(){try{e.compressedTexSubImage3D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Ae(){try{e.texStorage2D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function je(){try{e.texStorage3D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Me(){try{e.texImage2D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Ne(){try{e.texImage3D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Pe(t){ce.equals(t)===!1&&(e.scissor(t.x,t.y,t.z,t.w),ce.copy(t))}function Fe(t){le.equals(t)===!1&&(e.viewport(t.x,t.y,t.z,t.w),le.copy(t))}function Ie(t,n){let r=l.get(n);r===void 0&&(r=new WeakMap,l.set(n,r));let i=r.get(t);i===void 0&&(i=e.getUniformBlockIndex(n,t.name),r.set(t,i))}function Le(t,n){let r=l.get(n).get(t);c.get(n)!==r&&(e.uniformBlockBinding(n,r,t.__bindingPointIndex),c.set(n,r))}function Re(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),o.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),u={},ie=null,ae={},d={},f=new WeakMap,p=[],m=null,h=!1,g=null,_=null,v=null,y=null,b=null,x=null,S=null,C=new B(0,0,0),w=0,T=!1,E=null,D=null,O=null,k=null,ee=null,ce.set(0,0,e.canvas.width,e.canvas.height),le.set(0,0,e.canvas.width,e.canvas.height),a.reset(),o.reset(),s.reset()}return{buffers:{color:a,depth:o,stencil:s},enable:fe,disable:pe,bindFramebuffer:me,drawBuffers:he,useProgram:ge,setBlending:ye,setMaterial:be,setFlipSided:j,setCullFace:xe,setLineWidth:Se,setPolygonOffset:Ce,setScissorTest:M,activeTexture:we,bindTexture:N,unbindTexture:P,compressedTexImage2D:Te,compressedTexImage3D:Ee,texImage2D:Me,texImage3D:Ne,updateUBOMapping:Ie,uniformBlockBinding:Le,texStorage2D:Ae,texStorage3D:je,texSubImage2D:F,texSubImage3D:De,compressedTexSubImage2D:Oe,compressedTexSubImage3D:ke,scissor:Pe,viewport:Fe,reset:Re}}function eu(e,t,n,r,i,a,h){let g=t.has(`WEBGL_multisampled_render_to_texture`)?t.get(`WEBGL_multisampled_render_to_texture`):null,_=typeof navigator>`u`?!1:/OculusBrowser/g.test(navigator.userAgent),v=new L,y=new WeakMap,b,x=new WeakMap,S=!1;try{S=typeof OffscreenCanvas<`u`&&new OffscreenCanvas(1,1).getContext(`2d`)!==null}catch{}function C(e,t){return S?new OffscreenCanvas(e,t):kt(`canvas`)}function w(e,t,n){let r=1,i=Ae(e);if((i.width>n||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1)if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof VideoFrame<`u`&&e instanceof VideoFrame){let n=Math.floor(r*i.width),a=Math.floor(r*i.height);b===void 0&&(b=C(n,a));let o=t?C(n,a):b;return o.width=n,o.height=a,o.getContext(`2d`).drawImage(e,0,0,n,a),console.warn(`THREE.WebGLRenderer: Texture has been resized from (`+i.width+`x`+i.height+`) to (`+n+`x`+a+`).`),o}else return`data`in e&&console.warn(`THREE.WebGLRenderer: Image in DataTexture is too big (`+i.width+`x`+i.height+`).`),e;return e}function T(e){return e.generateMipmaps}function E(t){e.generateMipmap(t)}function D(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function O(n,r,i,a,o=!1){if(n!==null){if(e[n]!==void 0)return e[n];console.warn(`THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '`+n+`'`)}let s=r;if(r===e.RED&&(i===e.FLOAT&&(s=e.R32F),i===e.HALF_FLOAT&&(s=e.R16F),i===e.UNSIGNED_BYTE&&(s=e.R8)),r===e.RED_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.R8UI),i===e.UNSIGNED_SHORT&&(s=e.R16UI),i===e.UNSIGNED_INT&&(s=e.R32UI),i===e.BYTE&&(s=e.R8I),i===e.SHORT&&(s=e.R16I),i===e.INT&&(s=e.R32I)),r===e.RG&&(i===e.FLOAT&&(s=e.RG32F),i===e.HALF_FLOAT&&(s=e.RG16F),i===e.UNSIGNED_BYTE&&(s=e.RG8)),r===e.RG_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.RG8UI),i===e.UNSIGNED_SHORT&&(s=e.RG16UI),i===e.UNSIGNED_INT&&(s=e.RG32UI),i===e.BYTE&&(s=e.RG8I),i===e.SHORT&&(s=e.RG16I),i===e.INT&&(s=e.RG32I)),r===e.RGB_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.RGB8UI),i===e.UNSIGNED_SHORT&&(s=e.RGB16UI),i===e.UNSIGNED_INT&&(s=e.RGB32UI),i===e.BYTE&&(s=e.RGB8I),i===e.SHORT&&(s=e.RGB16I),i===e.INT&&(s=e.RGB32I)),r===e.RGBA_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.RGBA8UI),i===e.UNSIGNED_SHORT&&(s=e.RGBA16UI),i===e.UNSIGNED_INT&&(s=e.RGBA32UI),i===e.BYTE&&(s=e.RGBA8I),i===e.SHORT&&(s=e.RGBA16I),i===e.INT&&(s=e.RGBA32I)),r===e.RGB&&i===e.UNSIGNED_INT_5_9_9_9_REV&&(s=e.RGB9_E5),r===e.RGBA){let t=o?Je:zt.getTransfer(a);i===e.FLOAT&&(s=e.RGBA32F),i===e.HALF_FLOAT&&(s=e.RGBA16F),i===e.UNSIGNED_BYTE&&(s=t===`srgb`?e.SRGB8_ALPHA8:e.RGBA8),i===e.UNSIGNED_SHORT_4_4_4_4&&(s=e.RGBA4),i===e.UNSIGNED_SHORT_5_5_5_1&&(s=e.RGB5_A1)}return(s===e.R16F||s===e.R32F||s===e.RG16F||s===e.RG32F||s===e.RGBA16F||s===e.RGBA32F)&&t.get(`EXT_color_buffer_float`),s}function k(t,n){let r;return t?n===null||n===1014||n===1020?r=e.DEPTH24_STENCIL8:n===1015?r=e.DEPTH32F_STENCIL8:n===1012&&(r=e.DEPTH24_STENCIL8,console.warn(`DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.`)):n===null||n===1014||n===1020?r=e.DEPTH_COMPONENT24:n===1015?r=e.DEPTH_COMPONENT32F:n===1012&&(r=e.DEPTH_COMPONENT16),r}function ee(e,t){return T(e)===!0||e.isFramebufferTexture&&e.minFilter!==1003&&e.minFilter!==1006?Math.log2(Math.max(t.width,t.height))+1:e.mipmaps!==void 0&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function ne(e){let t=e.target;t.removeEventListener(`dispose`,ne),A(t),t.isVideoTexture&&y.delete(t)}function re(e){let t=e.target;t.removeEventListener(`dispose`,re),ae(t)}function A(e){let t=r.get(e);if(t.__webglInit===void 0)return;let n=e.source,i=x.get(n);if(i){let r=i[t.__cacheKey];r.usedTimes--,r.usedTimes===0&&ie(e),Object.keys(i).length===0&&x.delete(n)}r.remove(e)}function ie(t){let n=r.get(t);e.deleteTexture(n.__webglTexture);let i=t.source,a=x.get(i);delete a[n.__cacheKey],h.memory.textures--}function ae(t){let n=r.get(t);if(t.depthTexture&&(t.depthTexture.dispose(),r.remove(t.depthTexture)),t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let r=0;r<n.__webglFramebuffer[t].length;r++)e.deleteFramebuffer(n.__webglFramebuffer[t][r]);else e.deleteFramebuffer(n.__webglFramebuffer[t]);n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[t])}else{if(Array.isArray(n.__webglFramebuffer))for(let t=0;t<n.__webglFramebuffer.length;t++)e.deleteFramebuffer(n.__webglFramebuffer[t]);else e.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&e.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let t=0;t<n.__webglColorRenderbuffer.length;t++)n.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(n.__webglColorRenderbuffer[t]);n.__webglDepthRenderbuffer&&e.deleteRenderbuffer(n.__webglDepthRenderbuffer)}let i=t.textures;for(let t=0,n=i.length;t<n;t++){let n=r.get(i[t]);n.__webglTexture&&(e.deleteTexture(n.__webglTexture),h.memory.textures--),r.remove(i[t])}r.remove(t)}let oe=0;function se(){oe=0}function ce(){let e=oe;return e>=i.maxTextures&&console.warn(`THREE.WebGLTextures: Trying to use `+e+` texture units while this GPU supports only `+i.maxTextures),oe+=1,e}function le(e){let t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}function ue(t,i){let a=r.get(t);if(t.isVideoTexture&&Oe(t),t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){let e=t.image;if(e===null)console.warn(`THREE.WebGLRenderer: Texture marked for update but no image data found.`);else if(e.complete===!1)console.warn(`THREE.WebGLRenderer: Texture marked for update but image is incomplete`);else{ye(a,t,i);return}}n.bindTexture(e.TEXTURE_2D,a.__webglTexture,e.TEXTURE0+i)}function de(t,i){let a=r.get(t);if(t.version>0&&a.__version!==t.version){ye(a,t,i);return}n.bindTexture(e.TEXTURE_2D_ARRAY,a.__webglTexture,e.TEXTURE0+i)}function fe(t,i){let a=r.get(t);if(t.version>0&&a.__version!==t.version){ye(a,t,i);return}n.bindTexture(e.TEXTURE_3D,a.__webglTexture,e.TEXTURE0+i)}function pe(t,i){let a=r.get(t);if(t.version>0&&a.__version!==t.version){be(a,t,i);return}n.bindTexture(e.TEXTURE_CUBE_MAP,a.__webglTexture,e.TEXTURE0+i)}let me={[o]:e.REPEAT,[s]:e.CLAMP_TO_EDGE,[c]:e.MIRRORED_REPEAT},he={[l]:e.NEAREST,[u]:e.NEAREST_MIPMAP_NEAREST,[d]:e.NEAREST_MIPMAP_LINEAR,[f]:e.LINEAR,[p]:e.LINEAR_MIPMAP_NEAREST,[m]:e.LINEAR_MIPMAP_LINEAR},ge={512:e.NEVER,519:e.ALWAYS,513:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL};function _e(n,a){if(a.type===1015&&t.has(`OES_texture_float_linear`)===!1&&(a.magFilter===1006||a.magFilter===1007||a.magFilter===1005||a.magFilter===1008||a.minFilter===1006||a.minFilter===1007||a.minFilter===1005||a.minFilter===1008)&&console.warn(`THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.`),e.texParameteri(n,e.TEXTURE_WRAP_S,me[a.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,me[a.wrapT]),(n===e.TEXTURE_3D||n===e.TEXTURE_2D_ARRAY)&&e.texParameteri(n,e.TEXTURE_WRAP_R,me[a.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,he[a.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,he[a.minFilter]),a.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,ge[a.compareFunction])),t.has(`EXT_texture_filter_anisotropic`)===!0){if(a.magFilter===1003||a.minFilter!==1005&&a.minFilter!==1008||a.type===1015&&t.has(`OES_texture_float_linear`)===!1)return;if(a.anisotropy>1||r.get(a).__currentAnisotropy){let o=t.get(`EXT_texture_filter_anisotropic`);e.texParameterf(n,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(a.anisotropy,i.getMaxAnisotropy())),r.get(a).__currentAnisotropy=a.anisotropy}}}function ve(t,n){let r=!1;t.__webglInit===void 0&&(t.__webglInit=!0,n.addEventListener(`dispose`,ne));let i=n.source,a=x.get(i);a===void 0&&(a={},x.set(i,a));let o=le(n);if(o!==t.__cacheKey){a[o]===void 0&&(a[o]={texture:e.createTexture(),usedTimes:0},h.memory.textures++,r=!0),a[o].usedTimes++;let i=a[t.__cacheKey];i!==void 0&&(a[t.__cacheKey].usedTimes--,i.usedTimes===0&&ie(n)),t.__cacheKey=o,t.__webglTexture=a[o].texture}return r}function ye(t,o,s){let c=e.TEXTURE_2D;(o.isDataArrayTexture||o.isCompressedArrayTexture)&&(c=e.TEXTURE_2D_ARRAY),o.isData3DTexture&&(c=e.TEXTURE_3D);let l=ve(t,o),u=o.source;n.bindTexture(c,t.__webglTexture,e.TEXTURE0+s);let d=r.get(u);if(u.version!==d.__version||l===!0){n.activeTexture(e.TEXTURE0+s);let t=zt.getPrimaries(zt.workingColorSpace),r=o.colorSpace===``?null:zt.getPrimaries(o.colorSpace),f=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,f);let p=w(o.image,!1,i.maxTextureSize);p=ke(o,p);let m=a.convert(o.format,o.colorSpace),h=a.convert(o.type),g=O(o.internalFormat,m,h,o.colorSpace,o.isVideoTexture);_e(c,o);let _,v=o.mipmaps,y=o.isVideoTexture!==!0,b=d.__version===void 0||l===!0,x=u.dataReady,S=ee(o,p);if(o.isDepthTexture)g=k(o.format===te,o.type),b&&(y?n.texStorage2D(e.TEXTURE_2D,1,g,p.width,p.height):n.texImage2D(e.TEXTURE_2D,0,g,p.width,p.height,0,m,h,null));else if(o.isDataTexture)if(v.length>0){y&&b&&n.texStorage2D(e.TEXTURE_2D,S,g,v[0].width,v[0].height);for(let t=0,r=v.length;t<r;t++)_=v[t],y?x&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,_.width,_.height,m,h,_.data):n.texImage2D(e.TEXTURE_2D,t,g,_.width,_.height,0,m,h,_.data);o.generateMipmaps=!1}else y?(b&&n.texStorage2D(e.TEXTURE_2D,S,g,p.width,p.height),x&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,p.width,p.height,m,h,p.data)):n.texImage2D(e.TEXTURE_2D,0,g,p.width,p.height,0,m,h,p.data);else if(o.isCompressedTexture)if(o.isCompressedArrayTexture){y&&b&&n.texStorage3D(e.TEXTURE_2D_ARRAY,S,g,v[0].width,v[0].height,p.depth);for(let t=0,r=v.length;t<r;t++)if(_=v[t],o.format!==1023)if(m!==null)if(y){if(x)if(o.layerUpdates.size>0){let r=ss(_.width,_.height,o.format,o.type);for(let i of o.layerUpdates){let a=_.data.subarray(i*r/_.data.BYTES_PER_ELEMENT,(i+1)*r/_.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,i,_.width,_.height,1,m,a)}o.clearLayerUpdates()}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,_.width,_.height,p.depth,m,_.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,t,g,_.width,_.height,p.depth,0,_.data,0,0);else console.warn(`THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`);else y?x&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,_.width,_.height,p.depth,m,h,_.data):n.texImage3D(e.TEXTURE_2D_ARRAY,t,g,_.width,_.height,p.depth,0,m,h,_.data)}else{y&&b&&n.texStorage2D(e.TEXTURE_2D,S,g,v[0].width,v[0].height);for(let t=0,r=v.length;t<r;t++)_=v[t],o.format===1023?y?x&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,_.width,_.height,m,h,_.data):n.texImage2D(e.TEXTURE_2D,t,g,_.width,_.height,0,m,h,_.data):m===null?console.warn(`THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`):y?x&&n.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,_.width,_.height,m,_.data):n.compressedTexImage2D(e.TEXTURE_2D,t,g,_.width,_.height,0,_.data)}else if(o.isDataArrayTexture)if(y){if(b&&n.texStorage3D(e.TEXTURE_2D_ARRAY,S,g,p.width,p.height,p.depth),x)if(o.layerUpdates.size>0){let t=ss(p.width,p.height,o.format,o.type);for(let r of o.layerUpdates){let i=p.data.subarray(r*t/p.data.BYTES_PER_ELEMENT,(r+1)*t/p.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,r,p.width,p.height,1,m,h,i)}o.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,p.width,p.height,p.depth,m,h,p.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,g,p.width,p.height,p.depth,0,m,h,p.data);else if(o.isData3DTexture)y?(b&&n.texStorage3D(e.TEXTURE_3D,S,g,p.width,p.height,p.depth),x&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,p.width,p.height,p.depth,m,h,p.data)):n.texImage3D(e.TEXTURE_3D,0,g,p.width,p.height,p.depth,0,m,h,p.data);else if(o.isFramebufferTexture){if(b)if(y)n.texStorage2D(e.TEXTURE_2D,S,g,p.width,p.height);else{let t=p.width,r=p.height;for(let i=0;i<S;i++)n.texImage2D(e.TEXTURE_2D,i,g,t,r,0,m,h,null),t>>=1,r>>=1}}else if(v.length>0){if(y&&b){let t=Ae(v[0]);n.texStorage2D(e.TEXTURE_2D,S,g,t.width,t.height)}for(let t=0,r=v.length;t<r;t++)_=v[t],y?x&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,m,h,_):n.texImage2D(e.TEXTURE_2D,t,g,m,h,_);o.generateMipmaps=!1}else if(y){if(b){let t=Ae(p);n.texStorage2D(e.TEXTURE_2D,S,g,t.width,t.height)}x&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,m,h,p)}else n.texImage2D(e.TEXTURE_2D,0,g,m,h,p);T(o)&&E(c),d.__version=u.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function be(t,o,s){if(o.image.length!==6)return;let c=ve(t,o),l=o.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+s);let u=r.get(l);if(l.version!==u.__version||c===!0){n.activeTexture(e.TEXTURE0+s);let t=zt.getPrimaries(zt.workingColorSpace),r=o.colorSpace===``?null:zt.getPrimaries(o.colorSpace),d=o.colorSpace===``||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,o.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,o.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,o.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let f=o.isCompressedTexture||o.image[0].isCompressedTexture,p=o.image[0]&&o.image[0].isDataTexture,m=[];for(let e=0;e<6;e++)!f&&!p?m[e]=w(o.image[e],!0,i.maxCubemapSize):m[e]=p?o.image[e].image:o.image[e],m[e]=ke(o,m[e]);let h=m[0],g=a.convert(o.format,o.colorSpace),_=a.convert(o.type),v=O(o.internalFormat,g,_,o.colorSpace),y=o.isVideoTexture!==!0,b=u.__version===void 0||c===!0,x=l.dataReady,S=ee(o,h);_e(e.TEXTURE_CUBE_MAP,o);let C;if(f){y&&b&&n.texStorage2D(e.TEXTURE_CUBE_MAP,S,v,h.width,h.height);for(let t=0;t<6;t++){C=m[t].mipmaps;for(let r=0;r<C.length;r++){let i=C[r];o.format===1023?y?x&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,g,_,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,v,i.width,i.height,0,g,_,i.data):g===null?console.warn(`THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()`):y?x&&n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,g,i.data):n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,v,i.width,i.height,0,i.data)}}}else{if(C=o.mipmaps,y&&b){C.length>0&&S++;let t=Ae(m[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,S,v,t.width,t.height)}for(let t=0;t<6;t++)if(p){y?x&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,m[t].width,m[t].height,g,_,m[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,v,m[t].width,m[t].height,0,g,_,m[t].data);for(let r=0;r<C.length;r++){let i=C[r].image[t].image;y?x&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,i.width,i.height,g,_,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,v,i.width,i.height,0,g,_,i.data)}}else{y?x&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,g,_,m[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,v,g,_,m[t]);for(let r=0;r<C.length;r++){let i=C[r];y?x&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,g,_,i.image[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,v,g,_,i.image[t])}}}T(o)&&E(e.TEXTURE_CUBE_MAP),u.__version=l.version,o.onUpdate&&o.onUpdate(o)}t.__version=o.version}function j(t,i,o,s,c,l){let u=a.convert(o.format,o.colorSpace),d=a.convert(o.type),f=O(o.internalFormat,u,d,o.colorSpace),p=r.get(i),m=r.get(o);if(m.__renderTarget=i,!p.__hasExternalTextures){let t=Math.max(1,i.width>>l),r=Math.max(1,i.height>>l);c===e.TEXTURE_3D||c===e.TEXTURE_2D_ARRAY?n.texImage3D(c,l,f,t,r,i.depth,0,u,d,null):n.texImage2D(c,l,f,t,r,0,u,d,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),De(i)?g.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,s,c,m.__webglTexture,0,F(i)):(c===e.TEXTURE_2D||c>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&c<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,s,c,m.__webglTexture,l),n.bindFramebuffer(e.FRAMEBUFFER,null)}function xe(t,n,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){let i=n.depthTexture,a=i&&i.isDepthTexture?i.type:null,o=k(n.stencilBuffer,a),s=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,c=F(n);De(n)?g.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,c,o,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,c,o,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,o,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,s,e.RENDERBUFFER,t)}else{let t=n.textures;for(let i=0;i<t.length;i++){let o=t[i],s=a.convert(o.format,o.colorSpace),c=a.convert(o.type),l=O(o.internalFormat,s,c,o.colorSpace),u=F(n);r&&De(n)===!1?e.renderbufferStorageMultisample(e.RENDERBUFFER,u,l,n.width,n.height):De(n)?g.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,u,l,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,l,n.width,n.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function Se(t,i){if(i&&i.isWebGLCubeRenderTarget)throw Error(`Depth Texture with cube render targets is not supported`);if(n.bindFramebuffer(e.FRAMEBUFFER,t),!(i.depthTexture&&i.depthTexture.isDepthTexture))throw Error(`renderTarget.depthTexture must be an instance of THREE.DepthTexture`);let a=r.get(i.depthTexture);a.__renderTarget=i,(!a.__webglTexture||i.depthTexture.image.width!==i.width||i.depthTexture.image.height!==i.height)&&(i.depthTexture.image.width=i.width,i.depthTexture.image.height=i.height,i.depthTexture.needsUpdate=!0),ue(i.depthTexture,0);let o=a.__webglTexture,s=F(i);if(i.depthTexture.format===1026)De(i)?g.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,o,0,s):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,o,0);else if(i.depthTexture.format===1027)De(i)?g.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,o,0,s):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,o,0);else throw Error(`Unknown depthTexture format`)}function Ce(t){let i=r.get(t),a=t.isWebGLCubeRenderTarget===!0;if(i.__boundDepthTexture!==t.depthTexture){let e=t.depthTexture;if(i.__depthDisposeCallback&&i.__depthDisposeCallback(),e){let t=()=>{delete i.__boundDepthTexture,delete i.__depthDisposeCallback,e.removeEventListener(`dispose`,t)};e.addEventListener(`dispose`,t),i.__depthDisposeCallback=t}i.__boundDepthTexture=e}if(t.depthTexture&&!i.__autoAllocateDepthBuffer){if(a)throw Error(`target.depthTexture not supported in Cube render targets`);let e=t.texture.mipmaps;e&&e.length>0?Se(i.__webglFramebuffer[0],t):Se(i.__webglFramebuffer,t)}else if(a){i.__webglDepthbuffer=[];for(let r=0;r<6;r++)if(n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[r]),i.__webglDepthbuffer[r]===void 0)i.__webglDepthbuffer[r]=e.createRenderbuffer(),xe(i.__webglDepthbuffer[r],t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,a=i.__webglDepthbuffer[r];e.bindRenderbuffer(e.RENDERBUFFER,a),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,a)}}else{let r=t.texture.mipmaps;if(r&&r.length>0?n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer),i.__webglDepthbuffer===void 0)i.__webglDepthbuffer=e.createRenderbuffer(),xe(i.__webglDepthbuffer,t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,r=i.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,r)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}function M(t,n,i){let a=r.get(t);n!==void 0&&j(a.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),i!==void 0&&Ce(t)}function we(t){let i=t.texture,o=r.get(t),s=r.get(i);t.addEventListener(`dispose`,re);let c=t.textures,l=t.isWebGLCubeRenderTarget===!0,u=c.length>1;if(u||(s.__webglTexture===void 0&&(s.__webglTexture=e.createTexture()),s.__version=i.version,h.memory.textures++),l){o.__webglFramebuffer=[];for(let t=0;t<6;t++)if(i.mipmaps&&i.mipmaps.length>0){o.__webglFramebuffer[t]=[];for(let n=0;n<i.mipmaps.length;n++)o.__webglFramebuffer[t][n]=e.createFramebuffer()}else o.__webglFramebuffer[t]=e.createFramebuffer()}else{if(i.mipmaps&&i.mipmaps.length>0){o.__webglFramebuffer=[];for(let t=0;t<i.mipmaps.length;t++)o.__webglFramebuffer[t]=e.createFramebuffer()}else o.__webglFramebuffer=e.createFramebuffer();if(u)for(let t=0,n=c.length;t<n;t++){let n=r.get(c[t]);n.__webglTexture===void 0&&(n.__webglTexture=e.createTexture(),h.memory.textures++)}if(t.samples>0&&De(t)===!1){o.__webglMultisampledFramebuffer=e.createFramebuffer(),o.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let n=0;n<c.length;n++){let r=c[n];o.__webglColorRenderbuffer[n]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,o.__webglColorRenderbuffer[n]);let i=a.convert(r.format,r.colorSpace),s=a.convert(r.type),l=O(r.internalFormat,i,s,r.colorSpace,t.isXRRenderTarget===!0),u=F(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,u,l,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+n,e.RENDERBUFFER,o.__webglColorRenderbuffer[n])}e.bindRenderbuffer(e.RENDERBUFFER,null),t.depthBuffer&&(o.__webglDepthRenderbuffer=e.createRenderbuffer(),xe(o.__webglDepthRenderbuffer,t,!0)),n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(l){n.bindTexture(e.TEXTURE_CUBE_MAP,s.__webglTexture),_e(e.TEXTURE_CUBE_MAP,i);for(let n=0;n<6;n++)if(i.mipmaps&&i.mipmaps.length>0)for(let r=0;r<i.mipmaps.length;r++)j(o.__webglFramebuffer[n][r],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,r);else j(o.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0);T(i)&&E(e.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(u){for(let i=0,a=c.length;i<a;i++){let a=c[i],s=r.get(a);n.bindTexture(e.TEXTURE_2D,s.__webglTexture),_e(e.TEXTURE_2D,a),j(o.__webglFramebuffer,t,a,e.COLOR_ATTACHMENT0+i,e.TEXTURE_2D,0),T(a)&&E(e.TEXTURE_2D)}n.unbindTexture()}else{let r=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(r=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(r,s.__webglTexture),_e(r,i),i.mipmaps&&i.mipmaps.length>0)for(let n=0;n<i.mipmaps.length;n++)j(o.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,r,n);else j(o.__webglFramebuffer,t,i,e.COLOR_ATTACHMENT0,r,0);T(i)&&E(r),n.unbindTexture()}t.depthBuffer&&Ce(t)}function N(e){let t=e.textures;for(let i=0,a=t.length;i<a;i++){let a=t[i];if(T(a)){let t=D(e),i=r.get(a).__webglTexture;n.bindTexture(t,i),E(t),n.unbindTexture()}}}let P=[],Te=[];function Ee(t){if(t.samples>0){if(De(t)===!1){let i=t.textures,a=t.width,o=t.height,s=e.COLOR_BUFFER_BIT,c=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,l=r.get(t),u=i.length>1;if(u)for(let t=0;t<i.length;t++)n.bindFramebuffer(e.FRAMEBUFFER,l.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,l.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,l.__webglMultisampledFramebuffer);let d=t.texture.mipmaps;d&&d.length>0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,l.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,l.__webglFramebuffer);for(let n=0;n<i.length;n++){if(t.resolveDepthBuffer&&(t.depthBuffer&&(s|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&t.resolveStencilBuffer&&(s|=e.STENCIL_BUFFER_BIT)),u){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,l.__webglColorRenderbuffer[n]);let t=r.get(i[n]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,a,o,0,0,a,o,s,e.NEAREST),_===!0&&(P.length=0,Te.length=0,P.push(e.COLOR_ATTACHMENT0+n),t.depthBuffer&&t.resolveDepthBuffer===!1&&(P.push(c),Te.push(c),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,Te)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,P))}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),u)for(let t=0;t<i.length;t++){n.bindFramebuffer(e.FRAMEBUFFER,l.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,l.__webglColorRenderbuffer[t]);let a=r.get(i[t]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,l.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,a,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,l.__webglMultisampledFramebuffer)}else if(t.depthBuffer&&t.resolveDepthBuffer===!1&&_){let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[n])}}}function F(e){return Math.min(i.maxSamples,e.samples)}function De(e){let n=r.get(e);return e.samples>0&&t.has(`WEBGL_multisampled_render_to_texture`)===!0&&n.__useRenderToTexture!==!1}function Oe(e){let t=h.render.frame;y.get(e)!==t&&(y.set(e,t),e.update())}function ke(e,t){let n=e.colorSpace,r=e.format,i=e.type;return e.isCompressedTexture===!0||e.isVideoTexture===!0||n!==`srgb-linear`&&n!==``&&(zt.getTransfer(n)===`srgb`?(r!==1023||i!==1009)&&console.warn(`THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.`):console.error(`THREE.WebGLTextures: Unsupported texture color space:`,n)),t}function Ae(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement?(v.width=e.naturalWidth||e.width,v.height=e.naturalHeight||e.height):typeof VideoFrame<`u`&&e instanceof VideoFrame?(v.width=e.displayWidth,v.height=e.displayHeight):(v.width=e.width,v.height=e.height),v}this.allocateTextureUnit=ce,this.resetTextureUnits=se,this.setTexture2D=ue,this.setTexture2DArray=de,this.setTexture3D=fe,this.setTextureCube=pe,this.rebindTextures=M,this.setupRenderTarget=we,this.updateRenderTargetMipmap=N,this.updateMultisampleRenderTarget=Ee,this.setupDepthRenderbuffer=Ce,this.setupFrameBufferTexture=j,this.useMultisampledRTT=De}function tu(e,t){function n(n,r=``){let i,a=zt.getTransfer(r);if(n===1009)return e.UNSIGNED_BYTE;if(n===1017)return e.UNSIGNED_SHORT_4_4_4_4;if(n===1018)return e.UNSIGNED_SHORT_5_5_5_1;if(n===35902)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===1010)return e.BYTE;if(n===1011)return e.SHORT;if(n===1012)return e.UNSIGNED_SHORT;if(n===1013)return e.INT;if(n===1014)return e.UNSIGNED_INT;if(n===1015)return e.FLOAT;if(n===1016)return e.HALF_FLOAT;if(n===1021)return e.ALPHA;if(n===1022)return e.RGB;if(n===1023)return e.RGBA;if(n===1026)return e.DEPTH_COMPONENT;if(n===1027)return e.DEPTH_STENCIL;if(n===1028)return e.RED;if(n===1029)return e.RED_INTEGER;if(n===1030)return e.RG;if(n===1031)return e.RG_INTEGER;if(n===1033)return e.RGBA_INTEGER;if(n===33776||n===33777||n===33778||n===33779)if(a===`srgb`)if(i=t.get(`WEBGL_compressed_texture_s3tc_srgb`),i!==null){if(n===33776)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(i=t.get(`WEBGL_compressed_texture_s3tc`),i!==null){if(n===33776)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===35840||n===35841||n===35842||n===35843)if(i=t.get(`WEBGL_compressed_texture_pvrtc`),i!==null){if(n===35840)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===35841)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===35842)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===35843)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===36196||n===37492||n===37496)if(i=t.get(`WEBGL_compressed_texture_etc`),i!==null){if(n===36196||n===37492)return a===`srgb`?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(n===37496)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(n===37808||n===37809||n===37810||n===37811||n===37812||n===37813||n===37814||n===37815||n===37816||n===37817||n===37818||n===37819||n===37820||n===37821)if(i=t.get(`WEBGL_compressed_texture_astc`),i!==null){if(n===37808)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===37809)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===37810)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===37811)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===37812)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===37813)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===37814)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===37815)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===37816)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===37817)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===37818)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===37819)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===37820)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===37821)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===36492||n===36494||n===36495)if(i=t.get(`EXT_texture_compression_bptc`),i!==null){if(n===36492)return a===`srgb`?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===36494)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===36495)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===36283||n===36284||n===36285||n===36286)if(i=t.get(`EXT_texture_compression_rgtc`),i!==null){if(n===36492)return i.COMPRESSED_RED_RGTC1_EXT;if(n===36284)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===36285)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===36286)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===1020?e.UNSIGNED_INT_24_8:e[n]===void 0?null:e[n]}return{convert:n}}var nu=`
+void main() {
+
+ gl_Position = vec4( position, 1.0 );
+
+}`,ru=`
+uniform sampler2DArray depthColor;
+uniform float depthWidth;
+uniform float depthHeight;
+
+void main() {
+
+ vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
+
+ if ( coord.x >= 1.0 ) {
+
+ gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
+
+ } else {
+
+ gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
+
+ }
+
+}`,iu=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,n){if(this.texture===null){let r=new Jt,i=e.properties.get(r);i.__webglTexture=t.texture,(t.depthNear!==n.depthNear||t.depthFar!==n.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=r}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new mi({vertexShader:nu,fragmentShader:ru,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new ri(new Pa(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},au=class extends $e{constructor(e,t){super();let n=this,r=null,i=1,a=null,o=`local-floor`,s=1,c=null,l=null,u=null,d=null,f=null,p=null,m=new iu,g=t.getContextAttributes(),_=null,v=null,y=[],x=[],S=new L,C=null,w=new yi;w.viewport=new Yt;let E=new yi;E.viewport=new Yt;let D=[w,E],O=new Fo,ne=null,re=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=y[e];return t===void 0&&(t=new Di,y[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=y[e];return t===void 0&&(t=new Di,y[e]=t),t.getGripSpace()},this.getHand=function(e){let t=y[e];return t===void 0&&(t=new Di,y[e]=t),t.getHandSpace()};function A(e){let t=x.indexOf(e.inputSource);if(t===-1)return;let n=y[t];n!==void 0&&(n.update(e.inputSource,e.frame,c||a),n.dispatchEvent({type:e.type,data:e.inputSource}))}function ie(){r.removeEventListener(`select`,A),r.removeEventListener(`selectstart`,A),r.removeEventListener(`selectend`,A),r.removeEventListener(`squeeze`,A),r.removeEventListener(`squeezestart`,A),r.removeEventListener(`squeezeend`,A),r.removeEventListener(`end`,ie),r.removeEventListener(`inputsourceschange`,ae);for(let e=0;e<y.length;e++){let t=x[e];t!==null&&(x[e]=null,y[e].disconnect(t))}ne=null,re=null,m.reset(),e.setRenderTarget(_),f=null,d=null,u=null,r=null,v=null,pe.stop(),n.isPresenting=!1,e.setPixelRatio(C),e.setSize(S.width,S.height,!1),n.dispatchEvent({type:`sessionend`})}this.setFramebufferScaleFactor=function(e){i=e,n.isPresenting===!0&&console.warn(`THREE.WebXRManager: Cannot change framebuffer scale while presenting.`)},this.setReferenceSpaceType=function(e){o=e,n.isPresenting===!0&&console.warn(`THREE.WebXRManager: Cannot change reference space type while presenting.`)},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(e){c=e},this.getBaseLayer=function(){return d===null?f:d},this.getBinding=function(){return u},this.getFrame=function(){return p},this.getSession=function(){return r},this.setSession=async function(l){if(r=l,r!==null){if(_=e.getRenderTarget(),r.addEventListener(`select`,A),r.addEventListener(`selectstart`,A),r.addEventListener(`selectend`,A),r.addEventListener(`squeeze`,A),r.addEventListener(`squeezestart`,A),r.addEventListener(`squeezeend`,A),r.addEventListener(`end`,ie),r.addEventListener(`inputsourceschange`,ae),g.xrCompatible!==!0&&await t.makeXRCompatible(),C=e.getPixelRatio(),e.getSize(S),typeof XRWebGLBinding<`u`&&`createProjectionLayer`in XRWebGLBinding.prototype){let n=null,a=null,o=null;g.depth&&(o=g.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=g.stencil?te:ee,a=g.stencil?T:b);let s={colorFormat:t.RGBA8,depthFormat:o,scaleFactor:i};u=new XRWebGLBinding(r,t),d=u.createProjectionLayer(s),r.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),v=new Zt(d.textureWidth,d.textureHeight,{format:k,type:h,depthTexture:new Na(d.textureWidth,d.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:g.stencil,colorSpace:e.outputColorSpace,samples:g.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{let n={antialias:g.antialias,alpha:!0,depth:g.depth,stencil:g.stencil,framebufferScaleFactor:i};f=new XRWebGLLayer(r,t,n),r.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),v=new Zt(f.framebufferWidth,f.framebufferHeight,{format:k,type:h,colorSpace:e.outputColorSpace,stencilBuffer:g.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}v.isXRRenderTarget=!0,this.setFoveation(s),c=null,a=await r.requestReferenceSpace(o),pe.setContext(r),pe.start(),n.isPresenting=!0,n.dispatchEvent({type:`sessionstart`})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function ae(e){for(let t=0;t<e.removed.length;t++){let n=e.removed[t],r=x.indexOf(n);r>=0&&(x[r]=null,y[r].disconnect(n))}for(let t=0;t<e.added.length;t++){let n=e.added[t],r=x.indexOf(n);if(r===-1){for(let e=0;e<y.length;e++)if(e>=x.length){x.push(n),r=e;break}else if(x[e]===null){x[e]=n,r=e;break}if(r===-1)break}let i=y[r];i&&i.connect(n)}}let oe=new R,se=new R;function ce(e,t,n){oe.setFromMatrixPosition(t.matrixWorld),se.setFromMatrixPosition(n.matrixWorld);let r=oe.distanceTo(se),i=t.projectionMatrix.elements,a=n.projectionMatrix.elements,o=i[14]/(i[10]-1),s=i[14]/(i[10]+1),c=(i[9]+1)/i[5],l=(i[9]-1)/i[5],u=(i[8]-1)/i[0],d=(a[8]+1)/a[0],f=o*u,p=o*d,m=r/(-u+d),h=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(h),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),i[10]===-1)e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{let t=o+m,n=s+m,i=f-h,a=p+(r-h),u=c*s/n*t,d=l*s/n*t;e.projectionMatrix.makePerspective(i,a,u,d,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}function le(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(r===null)return;let t=e.near,n=e.far;m.texture!==null&&(m.depthNear>0&&(t=m.depthNear),m.depthFar>0&&(n=m.depthFar)),O.near=E.near=w.near=t,O.far=E.far=w.far=n,(ne!==O.near||re!==O.far)&&(r.updateRenderState({depthNear:O.near,depthFar:O.far}),ne=O.near,re=O.far),w.layers.mask=e.layers.mask|2,E.layers.mask=e.layers.mask|4,O.layers.mask=w.layers.mask|E.layers.mask;let i=e.parent,a=O.cameras;le(O,i);for(let e=0;e<a.length;e++)le(a[e],i);a.length===2?ce(O,w,E):O.projectionMatrix.copy(w.projectionMatrix),ue(e,O,i)};function ue(e,t,n){n===null?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld)),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=rt*2*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}this.getCamera=function(){return O},this.getFoveation=function(){if(!(d===null&&f===null))return s},this.setFoveation=function(e){s=e,d!==null&&(d.fixedFoveation=e),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=e)},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(O)};let de=null;function fe(t,i){if(l=i.getViewerPose(c||a),p=i,l!==null){let t=l.views;f!==null&&(e.setRenderTargetFramebuffer(v,f.framebuffer),e.setRenderTarget(v));let n=!1;t.length!==O.cameras.length&&(O.cameras.length=0,n=!0);for(let r=0;r<t.length;r++){let i=t[r],a=null;if(f!==null)a=f.getViewport(i);else{let t=u.getViewSubImage(d,i);a=t.viewport,r===0&&(e.setRenderTargetTextures(v,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(v))}let o=D[r];o===void 0&&(o=new yi,o.layers.enable(r),o.viewport=new Yt,D[r]=o),o.matrix.fromArray(i.transform.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale),o.projectionMatrix.fromArray(i.projectionMatrix),o.projectionMatrixInverse.copy(o.projectionMatrix).invert(),o.viewport.set(a.x,a.y,a.width,a.height),r===0&&(O.matrix.copy(o.matrix),O.matrix.decompose(O.position,O.quaternion,O.scale)),n===!0&&O.cameras.push(o)}let i=r.enabledFeatures;if(i&&i.includes(`depth-sensing`)&&r.depthUsage==`gpu-optimized`&&u){let n=u.getDepthInformation(t[0]);n&&n.isValid&&n.texture&&m.init(e,n,r.renderState)}}for(let e=0;e<y.length;e++){let t=x[e],n=y[e];t!==null&&n!==void 0&&n.update(t,i,c||a)}de&&de(t,i),i.detectedPlanes&&n.dispatchEvent({type:`planesdetected`,data:i}),p=null}let pe=new ls;pe.setAnimationLoop(fe),this.setAnimationLoop=function(e){de=e},this.dispose=function(){}}},ou=new Bn,su=new z;function cu(e,t){function n(e,t){e.matrixAutoUpdate===!0&&e.updateMatrix(),t.value.copy(e.matrix)}function r(t,n){n.color.getRGB(t.fogColor.value,ui(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)}function i(e,t,n,r,i){t.isMeshBasicMaterial||t.isMeshLambertMaterial?a(e,t):t.isMeshToonMaterial?(a(e,t),d(e,t)):t.isMeshPhongMaterial?(a(e,t),u(e,t)):t.isMeshStandardMaterial?(a(e,t),f(e,t),t.isMeshPhysicalMaterial&&p(e,t,i)):t.isMeshMatcapMaterial?(a(e,t),m(e,t)):t.isMeshDepthMaterial?a(e,t):t.isMeshDistanceMaterial?(a(e,t),h(e,t)):t.isMeshNormalMaterial?a(e,t):t.isLineBasicMaterial?(o(e,t),t.isLineDashedMaterial&&s(e,t)):t.isPointsMaterial?c(e,t,n,r):t.isSpriteMaterial?l(e,t):t.isShadowMaterial?(e.color.value.copy(t.color),e.opacity.value=t.opacity):t.isShaderMaterial&&(t.uniformsNeedUpdate=!1)}function a(e,r){e.opacity.value=r.opacity,r.color&&e.diffuse.value.copy(r.color),r.emissive&&e.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(e.map.value=r.map,n(r.map,e.mapTransform)),r.alphaMap&&(e.alphaMap.value=r.alphaMap,n(r.alphaMap,e.alphaMapTransform)),r.bumpMap&&(e.bumpMap.value=r.bumpMap,n(r.bumpMap,e.bumpMapTransform),e.bumpScale.value=r.bumpScale,r.side===1&&(e.bumpScale.value*=-1)),r.normalMap&&(e.normalMap.value=r.normalMap,n(r.normalMap,e.normalMapTransform),e.normalScale.value.copy(r.normalScale),r.side===1&&e.normalScale.value.negate()),r.displacementMap&&(e.displacementMap.value=r.displacementMap,n(r.displacementMap,e.displacementMapTransform),e.displacementScale.value=r.displacementScale,e.displacementBias.value=r.displacementBias),r.emissiveMap&&(e.emissiveMap.value=r.emissiveMap,n(r.emissiveMap,e.emissiveMapTransform)),r.specularMap&&(e.specularMap.value=r.specularMap,n(r.specularMap,e.specularMapTransform)),r.alphaTest>0&&(e.alphaTest.value=r.alphaTest);let i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,ou.copy(o),ou.x*=-1,ou.y*=-1,ou.z*=-1,a.isCubeTexture&&a.isRenderTargetTexture===!1&&(ou.y*=-1,ou.z*=-1),e.envMapRotation.value.setFromMatrix4(su.makeRotationFromEuler(ou)),e.flipEnvMap.value=a.isCubeTexture&&a.isRenderTargetTexture===!1?-1:1,e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}function o(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}function s(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}function c(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=i*.5,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function l(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function u(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}function d(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}function f(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform)),e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform)),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}function p(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform))),t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===1&&e.clearcoatNormalScale.value.negate())),t.dispersion>0&&(e.dispersion.value=t.dispersion),t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform))),t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor)),t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform))),e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform)),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}function m(e,t){t.matcap&&(e.matcap.value=t.matcap)}function h(e,n){let r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function lu(e,t,n,r){let i={},a={},o=[],s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(e,t){let n=t.program;r.uniformBlockBinding(e,n)}function l(e,n){let o=i[e.id];o===void 0&&(m(e),o=u(e),i[e.id]=o,e.addEventListener(`dispose`,g));let s=n.program;r.updateUBOMapping(e,s);let c=t.render.frame;a[e.id]!==c&&(f(e),a[e.id]=c)}function u(t){let n=d();t.__bindingPointIndex=n;let r=e.createBuffer(),i=t.__size,a=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,r),e.bufferData(e.UNIFORM_BUFFER,i,a),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,r),r}function d(){for(let e=0;e<s;e++)if(o.indexOf(e)===-1)return o.push(e),e;return console.error(`THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.`),0}function f(t){let n=i[t.id],r=t.uniforms,a=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let t=0,n=r.length;t<n;t++){let n=Array.isArray(r[t])?r[t]:[r[t]];for(let r=0,i=n.length;r<i;r++){let i=n[r];if(p(i,t,r,a)===!0){let t=i.__offset,n=Array.isArray(i.value)?i.value:[i.value],r=0;for(let a=0;a<n.length;a++){let o=n[a],s=h(o);typeof o==`number`||typeof o==`boolean`?(i.__data[0]=o,e.bufferSubData(e.UNIFORM_BUFFER,t+r,i.__data)):o.isMatrix3?(i.__data[0]=o.elements[0],i.__data[1]=o.elements[1],i.__data[2]=o.elements[2],i.__data[3]=0,i.__data[4]=o.elements[3],i.__data[5]=o.elements[4],i.__data[6]=o.elements[5],i.__data[7]=0,i.__data[8]=o.elements[6],i.__data[9]=o.elements[7],i.__data[10]=o.elements[8],i.__data[11]=0):(o.toArray(i.__data,r),r+=s.storage/Float32Array.BYTES_PER_ELEMENT)}e.bufferSubData(e.UNIFORM_BUFFER,t,i.__data)}}}e.bindBuffer(e.UNIFORM_BUFFER,null)}function p(e,t,n,r){let i=e.value,a=t+`_`+n;if(r[a]===void 0)return typeof i==`number`||typeof i==`boolean`?r[a]=i:r[a]=i.clone(),!0;{let e=r[a];if(typeof i==`number`||typeof i==`boolean`){if(e!==i)return r[a]=i,!0}else if(e.equals(i)===!1)return e.copy(i),!0}return!1}function m(e){let t=e.uniforms,n=0;for(let e=0,r=t.length;e<r;e++){let r=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0,t=r.length;e<t;e++){let t=r[e],i=Array.isArray(t.value)?t.value:[t.value];for(let e=0,r=i.length;e<r;e++){let r=i[e],a=h(r),o=n%16,s=o%a.boundary,c=o+s;n+=s,c!==0&&16-c<a.storage&&(n+=16-c),t.__data=new Float32Array(a.storage/Float32Array.BYTES_PER_ELEMENT),t.__offset=n,n+=a.storage}}}let r=n%16;return r>0&&(n+=16-r),e.__size=n,e.__cache={},this}function h(e){let t={boundary:0,storage:0};return typeof e==`number`||typeof e==`boolean`?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?console.warn(`THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.`):console.warn(`THREE.WebGLRenderer: Unsupported uniform value type.`,e),t}function g(t){let n=t.target;n.removeEventListener(`dispose`,g);let r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}function _(){for(let t in i)e.deleteBuffer(i[t]);o=[],i={},a={}}return{bind:c,update:l,dispose:_}}var uu=class{constructor(e={}){let{canvas:t=At(),context:n=null,depth:r=!0,stencil:i=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:s=!0,preserveDrawingBuffer:c=!1,powerPreference:l=`default`,failIfMajorPerformanceCaveat:u=!1,reverseDepthBuffer:d=!1}=e;this.isWebGLRenderer=!0;let f;if(n!==null){if(typeof WebGLRenderingContext<`u`&&n instanceof WebGLRenderingContext)throw Error(`THREE.WebGLRenderer: WebGL 1 is not supported since r163.`);f=n.getContextAttributes().alpha}else f=a;let p=new Uint32Array(4),g=new Int32Array(4),_=null,v=null,y=[],b=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let x=this,C=!1;this._outputColorSpace=Ke;let w=0,T=0,E=null,D=-1,O=null,k=new Yt,ee=new Yt,te=null,ne=new B(0),re=0,A=t.width,ie=t.height,ae=1,oe=null,se=null,ce=new Yt(0,0,A,ie),le=new Yt(0,0,A,ie),ue=!1,de=new ca,fe=!1,pe=!1,me=new z,he=new z,ge=new R,_e=new Yt,ve={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},ye=!1;function be(){return E===null?ae:1}let j=n;function xe(e,n){return t.getContext(e,n)}try{let e={alpha:!0,depth:r,stencil:i,antialias:o,premultipliedAlpha:s,preserveDrawingBuffer:c,powerPreference:l,failIfMajorPerformanceCaveat:u};if(`setAttribute`in t&&t.setAttribute(`data-engine`,`three.js r176`),t.addEventListener(`webglcontextlost`,We,!1),t.addEventListener(`webglcontextrestored`,Ge,!1),t.addEventListener(`webglcontextcreationerror`,Je,!1),j===null){let t=`webgl2`;if(j=xe(t,e),j===null)throw xe(t)?Error(`Error creating WebGL context with your selected attributes.`):Error(`Error creating WebGL context.`)}}catch(e){throw console.error(`THREE.WebGLRenderer: `+e.message),e}let Se,Ce,M,we,N,P,Te,Ee,F,De,Oe,ke,Ae,je,Me,Ne,Pe,Fe,Ie,Le,Re,ze,Be,Ve;function He(){Se=new Us(j),Se.init(),ze=new tu(j,Se),Ce=new vs(j,Se,e,ze),M=new $l(j,Se),Ce.reverseDepthBuffer&&d&&M.buffers.depth.setReversed(!0),we=new Ks(j),N=new Ll,P=new eu(j,Se,M,N,Ce,ze,we),Te=new bs(x),Ee=new Hs(x),F=new us(j),Be=new gs(j,F),De=new Ws(j,F,we,Be),Oe=new Js(j,De,F,we),Ie=new qs(j,Ce,P),Ne=new ys(N),ke=new Il(x,Te,Ee,Se,Ce,Be,Ne),Ae=new cu(x,N),je=new Vl,Me=new Jl(Se),Fe=new hs(x,Te,Ee,M,Oe,f,s),Pe=new Zl(x,Oe,Ce),Ve=new lu(j,we,Ce,M),Le=new _s(j,Se,we),Re=new Gs(j,Se,we),we.programs=ke.programs,x.capabilities=Ce,x.extensions=Se,x.properties=N,x.renderLists=je,x.shadowMap=Pe,x.state=M,x.info=we}He();let Ue=new au(x,j);this.xr=Ue,this.getContext=function(){return j},this.getContextAttributes=function(){return j.getContextAttributes()},this.forceContextLoss=function(){let e=Se.get(`WEBGL_lose_context`);e&&e.loseContext()},this.forceContextRestore=function(){let e=Se.get(`WEBGL_lose_context`);e&&e.restoreContext()},this.getPixelRatio=function(){return ae},this.setPixelRatio=function(e){e!==void 0&&(ae=e,this.setSize(A,ie,!1))},this.getSize=function(e){return e.set(A,ie)},this.setSize=function(e,n,r=!0){if(Ue.isPresenting){console.warn(`THREE.WebGLRenderer: Can't change size while VR device is presenting.`);return}A=e,ie=n,t.width=Math.floor(e*ae),t.height=Math.floor(n*ae),r===!0&&(t.style.width=e+`px`,t.style.height=n+`px`),this.setViewport(0,0,e,n)},this.getDrawingBufferSize=function(e){return e.set(A*ae,ie*ae).floor()},this.setDrawingBufferSize=function(e,n,r){A=e,ie=n,ae=r,t.width=Math.floor(e*r),t.height=Math.floor(n*r),this.setViewport(0,0,e,n)},this.getCurrentViewport=function(e){return e.copy(k)},this.getViewport=function(e){return e.copy(ce)},this.setViewport=function(e,t,n,r){e.isVector4?ce.set(e.x,e.y,e.z,e.w):ce.set(e,t,n,r),M.viewport(k.copy(ce).multiplyScalar(ae).round())},this.getScissor=function(e){return e.copy(le)},this.setScissor=function(e,t,n,r){e.isVector4?le.set(e.x,e.y,e.z,e.w):le.set(e,t,n,r),M.scissor(ee.copy(le).multiplyScalar(ae).round())},this.getScissorTest=function(){return ue},this.setScissorTest=function(e){M.setScissorTest(ue=e)},this.setOpaqueSort=function(e){oe=e},this.setTransparentSort=function(e){se=e},this.getClearColor=function(e){return e.copy(Fe.getClearColor())},this.setClearColor=function(){Fe.setClearColor(...arguments)},this.getClearAlpha=function(){return Fe.getClearAlpha()},this.setClearAlpha=function(){Fe.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let r=0;if(e){let e=!1;if(E!==null){let t=E.texture.format;e=t===1033||t===1031||t===1029}if(e){let e=E.texture.type,t=e===1009||e===1014||e===1012||e===1020||e===1017||e===1018,n=Fe.getClearColor(),r=Fe.getClearAlpha(),i=n.r,a=n.g,o=n.b;t?(p[0]=i,p[1]=a,p[2]=o,p[3]=r,j.clearBufferuiv(j.COLOR,0,p)):(g[0]=i,g[1]=a,g[2]=o,g[3]=r,j.clearBufferiv(j.COLOR,0,g))}else r|=j.COLOR_BUFFER_BIT}t&&(r|=j.DEPTH_BUFFER_BIT),n&&(r|=j.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),j.clear(r)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener(`webglcontextlost`,We,!1),t.removeEventListener(`webglcontextrestored`,Ge,!1),t.removeEventListener(`webglcontextcreationerror`,Je,!1),Fe.dispose(),je.dispose(),Me.dispose(),N.dispose(),Te.dispose(),Ee.dispose(),Oe.dispose(),Be.dispose(),Ve.dispose(),ke.dispose(),Ue.dispose(),Ue.removeEventListener(`sessionstart`,tt),Ue.removeEventListener(`sessionend`,nt),rt.stop()};function We(e){e.preventDefault(),console.log(`THREE.WebGLRenderer: Context Lost.`),C=!0}function Ge(){console.log(`THREE.WebGLRenderer: Context Restored.`),C=!1;let e=we.autoReset,t=Pe.enabled,n=Pe.autoUpdate,r=Pe.needsUpdate,i=Pe.type;He(),we.autoReset=e,Pe.enabled=t,Pe.autoUpdate=n,Pe.needsUpdate=r,Pe.type=i}function Je(e){console.error(`THREE.WebGLRenderer: A WebGL context could not be created. Reason: `,e.statusMessage)}function Ye(e){let t=e.target;t.removeEventListener(`dispose`,Ye),Xe(t)}function Xe(e){Ze(e),N.remove(e)}function Ze(e){let t=N.get(e).programs;t!==void 0&&(t.forEach(function(e){ke.releaseProgram(e)}),e.isShaderMaterial&&ke.releaseShaderCache(e))}this.renderBufferDirect=function(e,t,n,r,i,a){t===null&&(t=ve);let o=i.isMesh&&i.matrixWorld.determinant()<0,s=dt(e,t,n,r,i);M.setMaterial(r,o);let c=n.index,l=1;if(r.wireframe===!0){if(c=De.getWireframeAttribute(n),c===void 0)return;l=2}let u=n.drawRange,d=n.attributes.position,f=u.start*l,p=(u.start+u.count)*l;a!==null&&(f=Math.max(f,a.start*l),p=Math.min(p,(a.start+a.count)*l)),c===null?d!=null&&(f=Math.max(f,0),p=Math.min(p,d.count)):(f=Math.max(f,0),p=Math.min(p,c.count));let m=p-f;if(m<0||m===1/0)return;Be.setup(i,r,s,n,c);let h,g=Le;if(c!==null&&(h=F.get(c),g=Re,g.setIndex(h)),i.isMesh)r.wireframe===!0?(M.setLineWidth(r.wireframeLinewidth*be()),g.setMode(j.LINES)):g.setMode(j.TRIANGLES);else if(i.isLine){let e=r.linewidth;e===void 0&&(e=1),M.setLineWidth(e*be()),i.isLineSegments?g.setMode(j.LINES):i.isLineLoop?g.setMode(j.LINE_LOOP):g.setMode(j.LINE_STRIP)}else i.isPoints?g.setMode(j.POINTS):i.isSprite&&g.setMode(j.TRIANGLES);if(i.isBatchedMesh)if(i._multiDrawInstances!==null)Mt(`THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.`),g.renderMultiDrawInstances(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount,i._multiDrawInstances);else if(Se.get(`WEBGL_multi_draw`))g.renderMultiDraw(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount);else{let e=i._multiDrawStarts,t=i._multiDrawCounts,n=i._multiDrawCount,a=c?F.get(c).bytesPerElement:1,o=N.get(r).currentProgram.getUniforms();for(let r=0;r<n;r++)o.setValue(j,`_gl_DrawID`,r),g.render(e[r]/a,t[r])}else if(i.isInstancedMesh)g.renderInstances(f,m,i.count);else if(n.isInstancedBufferGeometry){let e=n._maxInstanceCount===void 0?1/0:n._maxInstanceCount,t=Math.min(n.instanceCount,e);g.renderInstances(f,m,t)}else g.render(f,m)};function Qe(e,t,n){e.transparent===!0&&e.side===2&&e.forceSinglePass===!1?(e.side=1,e.needsUpdate=!0,ct(e,t,n),e.side=0,e.needsUpdate=!0,ct(e,t,n),e.side=2):ct(e,t,n)}this.compile=function(e,t,n=null){n===null&&(n=e),v=Me.get(n),v.init(t),b.push(v),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(v.pushLight(e),e.castShadow&&v.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(v.pushLight(e),e.castShadow&&v.pushShadow(e))}),v.setupLights();let r=new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;let t=e.material;if(t)if(Array.isArray(t))for(let i=0;i<t.length;i++){let a=t[i];Qe(a,n,e),r.add(a)}else Qe(t,n,e),r.add(t)}),v=b.pop(),r},this.compileAsync=function(e,t,n=null){let r=this.compile(e,t,n);return new Promise(t=>{function n(){if(r.forEach(function(e){N.get(e).currentProgram.isReady()&&r.delete(e)}),r.size===0){t(e);return}setTimeout(n,10)}Se.get(`KHR_parallel_shader_compile`)===null?setTimeout(n,10):n()})};let $e=null;function et(e){$e&&$e(e)}function tt(){rt.stop()}function nt(){rt.start()}let rt=new ls;rt.setAnimationLoop(et),typeof self<`u`&&rt.setContext(self),this.setAnimationLoop=function(e){$e=e,Ue.setAnimationLoop(e),e===null?rt.stop():rt.start()},Ue.addEventListener(`sessionstart`,tt),Ue.addEventListener(`sessionend`,nt),this.render=function(e,t){if(t!==void 0&&t.isCamera!==!0){console.error(`THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.`);return}if(C===!0)return;if(e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),Ue.enabled===!0&&Ue.isPresenting===!0&&(Ue.cameraAutoUpdate===!0&&Ue.updateCamera(t),t=Ue.getCamera()),e.isScene===!0&&e.onBeforeRender(x,e,t,E),v=Me.get(e,b.length),v.init(t),b.push(v),he.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),de.setFromProjectionMatrix(he),pe=this.localClippingEnabled,fe=Ne.init(this.clippingPlanes,pe),_=je.get(e,y.length),_.init(),y.push(_),Ue.enabled===!0&&Ue.isPresenting===!0){let e=x.xr.getDepthSensingMesh();e!==null&&it(e,t,-1/0,x.sortObjects)}it(e,t,0,x.sortObjects),_.finish(),x.sortObjects===!0&&_.sort(oe,se),ye=Ue.enabled===!1||Ue.isPresenting===!1||Ue.hasDepthSensing()===!1,ye&&Fe.addToRenderList(_,e),this.info.render.frame++,fe===!0&&Ne.beginShadows();let n=v.state.shadowsArray;Pe.render(n,e,t),fe===!0&&Ne.endShadows(),this.info.autoReset===!0&&this.info.reset();let r=_.opaque,i=_.transmissive;if(v.setupLights(),t.isArrayCamera){let n=t.cameras;if(i.length>0)for(let t=0,a=n.length;t<a;t++){let a=n[t];at(r,i,e,a)}ye&&Fe.render(e);for(let t=0,r=n.length;t<r;t++){let r=n[t];I(_,e,r,r.viewport)}}else i.length>0&&at(r,i,e,t),ye&&Fe.render(e),I(_,e,t);E!==null&&T===0&&(P.updateMultisampleRenderTarget(E),P.updateRenderTargetMipmap(E)),e.isScene===!0&&e.onAfterRender(x,e,t),Be.resetDefaultState(),D=-1,O=null,b.pop(),b.length>0?(v=b[b.length-1],fe===!0&&Ne.setGlobalState(x.clippingPlanes,v.state.camera)):v=null,y.pop(),_=y.length>0?y[y.length-1]:null};function it(e,t,n,r){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder;else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLight)v.pushLight(e),e.castShadow&&v.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||de.intersectsSprite(e)){r&&_e.setFromMatrixPosition(e.matrixWorld).applyMatrix4(he);let t=Oe.update(e),i=e.material;i.visible&&_.push(e,t,i,n,_e.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||de.intersectsObject(e))){let t=Oe.update(e),i=e.material;if(r&&(e.boundingSphere===void 0?(t.boundingSphere===null&&t.computeBoundingSphere(),_e.copy(t.boundingSphere.center)):(e.boundingSphere===null&&e.computeBoundingSphere(),_e.copy(e.boundingSphere.center)),_e.applyMatrix4(e.matrixWorld).applyMatrix4(he)),Array.isArray(i)){let r=t.groups;for(let a=0,o=r.length;a<o;a++){let o=r[a],s=i[o.materialIndex];s&&s.visible&&_.push(e,t,s,n,_e.z,o)}}else i.visible&&_.push(e,t,i,n,_e.z,null)}}let i=e.children;for(let e=0,a=i.length;e<a;e++)it(i[e],t,n,r)}function I(e,t,n,r){let i=e.opaque,a=e.transmissive,o=e.transparent;v.setupLightsView(n),fe===!0&&Ne.setGlobalState(x.clippingPlanes,n),r&&M.viewport(k.copy(r)),i.length>0&&ot(i,t,n),a.length>0&&ot(a,t,n),o.length>0&&ot(o,t,n),M.buffers.depth.setTest(!0),M.buffers.depth.setMask(!0),M.buffers.color.setMask(!0),M.setPolygonOffset(!1)}function at(e,t,n,r){if((n.isScene===!0?n.overrideMaterial:null)!==null)return;v.state.transmissionRenderTarget[r.id]===void 0&&(v.state.transmissionRenderTarget[r.id]=new Zt(1,1,{generateMipmaps:!0,type:Se.has(`EXT_color_buffer_half_float`)||Se.has(`EXT_color_buffer_float`)?S:h,minFilter:m,samples:4,stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:zt.workingColorSpace}));let a=v.state.transmissionRenderTarget[r.id],o=r.viewport||k;a.setSize(o.z*x.transmissionResolutionScale,o.w*x.transmissionResolutionScale);let s=x.getRenderTarget();x.setRenderTarget(a),x.getClearColor(ne),re=x.getClearAlpha(),re<1&&x.setClearColor(16777215,.5),x.clear(),ye&&Fe.render(n);let c=x.toneMapping;x.toneMapping=0;let l=r.viewport;if(r.viewport!==void 0&&(r.viewport=void 0),v.setupLightsView(r),fe===!0&&Ne.setGlobalState(x.clippingPlanes,r),ot(e,n,r),P.updateMultisampleRenderTarget(a),P.updateRenderTargetMipmap(a),Se.has(`WEBGL_multisampled_render_to_texture`)===!1){let e=!1;for(let i=0,a=t.length;i<a;i++){let a=t[i],o=a.object,s=a.geometry,c=a.material,l=a.group;if(c.side===2&&o.layers.test(r.layers)){let t=c.side;c.side=1,c.needsUpdate=!0,st(o,n,r,s,c,l),c.side=t,c.needsUpdate=!0,e=!0}}e===!0&&(P.updateMultisampleRenderTarget(a),P.updateRenderTargetMipmap(a))}x.setRenderTarget(s),x.setClearColor(ne,re),l!==void 0&&(r.viewport=l),x.toneMapping=c}function ot(e,t,n){let r=t.isScene===!0?t.overrideMaterial:null;for(let i=0,a=e.length;i<a;i++){let a=e[i],o=a.object,s=a.geometry,c=a.group,l=a.material;l.allowOverride===!0&&r!==null&&(l=r),o.layers.test(n.layers)&&st(o,t,n,s,l,c)}}function st(e,t,n,r,i,a){e.onBeforeRender(x,t,n,r,i,a),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),i.onBeforeRender(x,t,n,r,e,a),i.transparent===!0&&i.side===2&&i.forceSinglePass===!1?(i.side=1,i.needsUpdate=!0,x.renderBufferDirect(n,t,r,i,e,a),i.side=0,i.needsUpdate=!0,x.renderBufferDirect(n,t,r,i,e,a),i.side=2):x.renderBufferDirect(n,t,r,i,e,a),e.onAfterRender(x,t,n,r,i,a)}function ct(e,t,n){t.isScene!==!0&&(t=ve);let r=N.get(e),i=v.state.lights,a=v.state.shadowsArray,o=i.state.version,s=ke.getParameters(e,i.state,a,t,n),c=ke.getProgramCacheKey(s),l=r.programs;r.environment=e.isMeshStandardMaterial?t.environment:null,r.fog=t.fog,r.envMap=(e.isMeshStandardMaterial?Ee:Te).get(e.envMap||r.environment),r.envMapRotation=r.environment!==null&&e.envMap===null?t.environmentRotation:e.envMapRotation,l===void 0&&(e.addEventListener(`dispose`,Ye),l=new Map,r.programs=l);let u=l.get(c);if(u!==void 0){if(r.currentProgram===u&&r.lightsStateVersion===o)return ut(e,s),u}else s.uniforms=ke.getUniforms(e),e.onBeforeCompile(s,x),u=ke.acquireProgram(s,c),l.set(c,u),r.uniforms=s.uniforms;let d=r.uniforms;return(!e.isShaderMaterial&&!e.isRawShaderMaterial||e.clipping===!0)&&(d.clippingPlanes=Ne.uniform),ut(e,s),r.needsLights=pt(e),r.lightsStateVersion=o,r.needsLights&&(d.ambientLightColor.value=i.state.ambient,d.lightProbe.value=i.state.probe,d.directionalLights.value=i.state.directional,d.directionalLightShadows.value=i.state.directionalShadow,d.spotLights.value=i.state.spot,d.spotLightShadows.value=i.state.spotShadow,d.rectAreaLights.value=i.state.rectArea,d.ltc_1.value=i.state.rectAreaLTC1,d.ltc_2.value=i.state.rectAreaLTC2,d.pointLights.value=i.state.point,d.pointLightShadows.value=i.state.pointShadow,d.hemisphereLights.value=i.state.hemi,d.directionalShadowMap.value=i.state.directionalShadowMap,d.directionalShadowMatrix.value=i.state.directionalShadowMatrix,d.spotShadowMap.value=i.state.spotShadowMap,d.spotLightMatrix.value=i.state.spotLightMatrix,d.spotLightMap.value=i.state.spotLightMap,d.pointShadowMap.value=i.state.pointShadowMap,d.pointShadowMatrix.value=i.state.pointShadowMatrix),r.currentProgram=u,r.uniformsList=null,u}function lt(e){if(e.uniformsList===null){let t=e.currentProgram.getUniforms();e.uniformsList=tl.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function ut(e,t){let n=N.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}function dt(e,t,n,r,i){t.isScene!==!0&&(t=ve),P.resetTextureUnits();let a=t.fog,o=r.isMeshStandardMaterial?t.environment:null,s=E===null?x.outputColorSpace:E.isXRRenderTarget===!0?E.texture.colorSpace:qe,c=(r.isMeshStandardMaterial?Ee:Te).get(r.envMap||o),l=r.vertexColors===!0&&!!n.attributes.color&&n.attributes.color.itemSize===4,u=!!n.attributes.tangent&&(!!r.normalMap||r.anisotropy>0),d=!!n.morphAttributes.position,f=!!n.morphAttributes.normal,p=!!n.morphAttributes.color,m=0;r.toneMapped&&(E===null||E.isXRRenderTarget===!0)&&(m=x.toneMapping);let h=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,g=h===void 0?0:h.length,_=N.get(r),y=v.state.lights;if(fe===!0&&(pe===!0||e!==O)){let t=e===O&&r.id===D;Ne.setState(r,e,t)}let b=!1;r.version===_.__version?_.needsLights&&_.lightsStateVersion!==y.state.version?b=!0:_.outputColorSpace===s?i.isBatchedMesh&&_.batching===!1||!i.isBatchedMesh&&_.batching===!0||i.isBatchedMesh&&_.batchingColor===!0&&i.colorTexture===null||i.isBatchedMesh&&_.batchingColor===!1&&i.colorTexture!==null||i.isInstancedMesh&&_.instancing===!1||!i.isInstancedMesh&&_.instancing===!0||i.isSkinnedMesh&&_.skinning===!1||!i.isSkinnedMesh&&_.skinning===!0||i.isInstancedMesh&&_.instancingColor===!0&&i.instanceColor===null||i.isInstancedMesh&&_.instancingColor===!1&&i.instanceColor!==null||i.isInstancedMesh&&_.instancingMorph===!0&&i.morphTexture===null||i.isInstancedMesh&&_.instancingMorph===!1&&i.morphTexture!==null?b=!0:_.envMap===c?r.fog===!0&&_.fog!==a||_.numClippingPlanes!==void 0&&(_.numClippingPlanes!==Ne.numPlanes||_.numIntersection!==Ne.numIntersection)?b=!0:_.vertexAlphas===l&&_.vertexTangents===u&&_.morphTargets===d&&_.morphNormals===f&&_.morphColors===p&&_.toneMapping===m?_.morphTargetsCount!==g&&(b=!0):b=!0:b=!0:b=!0:(b=!0,_.__version=r.version);let S=_.currentProgram;b===!0&&(S=ct(r,t,i));let C=!1,w=!1,T=!1,k=S.getUniforms(),ee=_.uniforms;if(M.useProgram(S.program)&&(C=!0,w=!0,T=!0),r.id!==D&&(D=r.id,w=!0),C||O!==e){M.buffers.depth.getReversed()?(me.copy(e.projectionMatrix),Pt(me),Ft(me),k.setValue(j,`projectionMatrix`,me)):k.setValue(j,`projectionMatrix`,e.projectionMatrix),k.setValue(j,`viewMatrix`,e.matrixWorldInverse);let t=k.map.cameraPosition;t!==void 0&&t.setValue(j,ge.setFromMatrixPosition(e.matrixWorld)),Ce.logarithmicDepthBuffer&&k.setValue(j,`logDepthBufFC`,2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&k.setValue(j,`isOrthographic`,e.isOrthographicCamera===!0),O!==e&&(O=e,w=!0,T=!0)}if(i.isSkinnedMesh){k.setOptional(j,i,`bindMatrix`),k.setOptional(j,i,`bindMatrixInverse`);let e=i.skeleton;e&&(e.boneTexture===null&&e.computeBoneTexture(),k.setValue(j,`boneTexture`,e.boneTexture,P))}i.isBatchedMesh&&(k.setOptional(j,i,`batchingTexture`),k.setValue(j,`batchingTexture`,i._matricesTexture,P),k.setOptional(j,i,`batchingIdTexture`),k.setValue(j,`batchingIdTexture`,i._indirectTexture,P),k.setOptional(j,i,`batchingColorTexture`),i._colorsTexture!==null&&k.setValue(j,`batchingColorTexture`,i._colorsTexture,P));let te=n.morphAttributes;if((te.position!==void 0||te.normal!==void 0||te.color!==void 0)&&Ie.update(i,n,S),(w||_.receiveShadow!==i.receiveShadow)&&(_.receiveShadow=i.receiveShadow,k.setValue(j,`receiveShadow`,i.receiveShadow)),r.isMeshGouraudMaterial&&r.envMap!==null&&(ee.envMap.value=c,ee.flipEnvMap.value=c.isCubeTexture&&c.isRenderTargetTexture===!1?-1:1),r.isMeshStandardMaterial&&r.envMap===null&&t.environment!==null&&(ee.envMapIntensity.value=t.environmentIntensity),w&&(k.setValue(j,`toneMappingExposure`,x.toneMappingExposure),_.needsLights&&ft(ee,T),a&&r.fog===!0&&Ae.refreshFogUniforms(ee,a),Ae.refreshMaterialUniforms(ee,r,ae,ie,v.state.transmissionRenderTarget[e.id]),tl.upload(j,lt(_),ee,P)),r.isShaderMaterial&&r.uniformsNeedUpdate===!0&&(tl.upload(j,lt(_),ee,P),r.uniformsNeedUpdate=!1),r.isSpriteMaterial&&k.setValue(j,`center`,i.center),k.setValue(j,`modelViewMatrix`,i.modelViewMatrix),k.setValue(j,`normalMatrix`,i.normalMatrix),k.setValue(j,`modelMatrix`,i.matrixWorld),r.isShaderMaterial||r.isRawShaderMaterial){let e=r.uniformsGroups;for(let t=0,n=e.length;t<n;t++){let n=e[t];Ve.update(n,S),Ve.bind(n,S)}}return S}function ft(e,t){e.ambientLightColor.needsUpdate=t,e.lightProbe.needsUpdate=t,e.directionalLights.needsUpdate=t,e.directionalLightShadows.needsUpdate=t,e.pointLights.needsUpdate=t,e.pointLightShadows.needsUpdate=t,e.spotLights.needsUpdate=t,e.spotLightShadows.needsUpdate=t,e.rectAreaLights.needsUpdate=t,e.hemisphereLights.needsUpdate=t}function pt(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&e.lights===!0}this.getActiveCubeFace=function(){return w},this.getActiveMipmapLevel=function(){return T},this.getRenderTarget=function(){return E},this.setRenderTargetTextures=function(e,t,n){let r=N.get(e);r.__autoAllocateDepthBuffer=e.resolveDepthBuffer===!1,r.__autoAllocateDepthBuffer===!1&&(r.__useRenderToTexture=!1),N.get(e.texture).__webglTexture=t,N.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){let n=N.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=t===void 0};let mt=j.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){E=e,w=t,T=n;let r=!0,i=null,a=!1,o=!1;if(e){let s=N.get(e);if(s.__useDefaultFramebuffer!==void 0)M.bindFramebuffer(j.FRAMEBUFFER,null),r=!1;else if(s.__webglFramebuffer===void 0)P.setupRenderTarget(e);else if(s.__hasExternalTextures)P.rebindTextures(e,N.get(e.texture).__webglTexture,N.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){let t=e.depthTexture;if(s.__boundDepthTexture!==t){if(t!==null&&N.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw Error(`WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.`);P.setupDepthRenderbuffer(e)}}let c=e.texture;(c.isData3DTexture||c.isDataArrayTexture||c.isCompressedArrayTexture)&&(o=!0);let l=N.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(i=Array.isArray(l[t])?l[t][n]:l[t],a=!0):i=e.samples>0&&P.useMultisampledRTT(e)===!1?N.get(e).__webglMultisampledFramebuffer:Array.isArray(l)?l[n]:l,k.copy(e.viewport),ee.copy(e.scissor),te=e.scissorTest}else k.copy(ce).multiplyScalar(ae).floor(),ee.copy(le).multiplyScalar(ae).floor(),te=ue;if(n!==0&&(i=mt),M.bindFramebuffer(j.FRAMEBUFFER,i)&&r&&M.drawBuffers(e,i),M.viewport(k),M.scissor(ee),M.setScissorTest(te),a){let r=N.get(e.texture);j.framebufferTexture2D(j.FRAMEBUFFER,j.COLOR_ATTACHMENT0,j.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(o){let r=N.get(e.texture),i=t;j.framebufferTextureLayer(j.FRAMEBUFFER,j.COLOR_ATTACHMENT0,r.__webglTexture,n,i)}else if(e!==null&&n!==0){let t=N.get(e.texture);j.framebufferTexture2D(j.FRAMEBUFFER,j.COLOR_ATTACHMENT0,j.TEXTURE_2D,t.__webglTexture,n)}D=-1},this.readRenderTargetPixels=function(e,t,n,r,i,a,o){if(!(e&&e.isWebGLRenderTarget)){console.error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);return}let s=N.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(s=s[o]),s){M.bindFramebuffer(j.FRAMEBUFFER,s);try{let o=e.texture,s=o.format,c=o.type;if(!Ce.textureFormatReadable(s)){console.error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.`);return}if(!Ce.textureTypeReadable(c)){console.error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.`);return}t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&j.readPixels(t,n,r,i,ze.convert(s),ze.convert(c),a)}finally{let e=E===null?null:N.get(E).__webglFramebuffer;M.bindFramebuffer(j.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o){if(!(e&&e.isWebGLRenderTarget))throw Error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);let s=N.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(s=s[o]),s)if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){M.bindFramebuffer(j.FRAMEBUFFER,s);let o=e.texture,c=o.format,l=o.type;if(!Ce.textureFormatReadable(c))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.`);if(!Ce.textureTypeReadable(l))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.`);let u=j.createBuffer();j.bindBuffer(j.PIXEL_PACK_BUFFER,u),j.bufferData(j.PIXEL_PACK_BUFFER,a.byteLength,j.STREAM_READ),j.readPixels(t,n,r,i,ze.convert(c),ze.convert(l),0);let d=E===null?null:N.get(E).__webglFramebuffer;M.bindFramebuffer(j.FRAMEBUFFER,d);let f=j.fenceSync(j.SYNC_GPU_COMMANDS_COMPLETE,0);return j.flush(),await Nt(j,f,4),j.bindBuffer(j.PIXEL_PACK_BUFFER,u),j.getBufferSubData(j.PIXEL_PACK_BUFFER,0,a),j.deleteBuffer(u),j.deleteSync(f),a}else throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.`)},this.copyFramebufferToTexture=function(e,t=null,n=0){let r=2**-n,i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=t===null?0:t.x,s=t===null?0:t.y;P.setTexture2D(e,0),j.copyTexSubImage2D(j.TEXTURE_2D,n,0,0,o,s,i,a),M.unbindTexture()};let ht=j.createFramebuffer(),gt=j.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=null){a===null&&(i===0?a=0:(Mt(`WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.`),a=i,i=0));let o,s,c,l,u,d,f,p,m,h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)o=n.max.x-n.min.x,s=n.max.y-n.min.y,c=n.isBox3?n.max.z-n.min.z:1,l=n.min.x,u=n.min.y,d=n.isBox3?n.min.z:0;else{let t=2**-i;o=Math.floor(h.width*t),s=Math.floor(h.height*t),c=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,l=0,u=0,d=0}r===null?(f=0,p=0,m=0):(f=r.x,p=r.y,m=r.z);let g=ze.convert(t.format),_=ze.convert(t.type),v;t.isData3DTexture?(P.setTexture3D(t,0),v=j.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(P.setTexture2DArray(t,0),v=j.TEXTURE_2D_ARRAY):(P.setTexture2D(t,0),v=j.TEXTURE_2D),j.pixelStorei(j.UNPACK_FLIP_Y_WEBGL,t.flipY),j.pixelStorei(j.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),j.pixelStorei(j.UNPACK_ALIGNMENT,t.unpackAlignment);let y=j.getParameter(j.UNPACK_ROW_LENGTH),b=j.getParameter(j.UNPACK_IMAGE_HEIGHT),x=j.getParameter(j.UNPACK_SKIP_PIXELS),S=j.getParameter(j.UNPACK_SKIP_ROWS),C=j.getParameter(j.UNPACK_SKIP_IMAGES);j.pixelStorei(j.UNPACK_ROW_LENGTH,h.width),j.pixelStorei(j.UNPACK_IMAGE_HEIGHT,h.height),j.pixelStorei(j.UNPACK_SKIP_PIXELS,l),j.pixelStorei(j.UNPACK_SKIP_ROWS,u),j.pixelStorei(j.UNPACK_SKIP_IMAGES,d);let w=e.isDataArrayTexture||e.isData3DTexture,T=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){let n=N.get(e),r=N.get(t),h=N.get(n.__renderTarget),g=N.get(r.__renderTarget);M.bindFramebuffer(j.READ_FRAMEBUFFER,h.__webglFramebuffer),M.bindFramebuffer(j.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n<c;n++)w&&(j.framebufferTextureLayer(j.READ_FRAMEBUFFER,j.COLOR_ATTACHMENT0,N.get(e).__webglTexture,i,d+n),j.framebufferTextureLayer(j.DRAW_FRAMEBUFFER,j.COLOR_ATTACHMENT0,N.get(t).__webglTexture,a,m+n)),j.blitFramebuffer(l,u,o,s,f,p,o,s,j.DEPTH_BUFFER_BIT,j.NEAREST);M.bindFramebuffer(j.READ_FRAMEBUFFER,null),M.bindFramebuffer(j.DRAW_FRAMEBUFFER,null)}else if(i!==0||e.isRenderTargetTexture||N.has(e)){let n=N.get(e),r=N.get(t);M.bindFramebuffer(j.READ_FRAMEBUFFER,ht),M.bindFramebuffer(j.DRAW_FRAMEBUFFER,gt);for(let e=0;e<c;e++)w?j.framebufferTextureLayer(j.READ_FRAMEBUFFER,j.COLOR_ATTACHMENT0,n.__webglTexture,i,d+e):j.framebufferTexture2D(j.READ_FRAMEBUFFER,j.COLOR_ATTACHMENT0,j.TEXTURE_2D,n.__webglTexture,i),T?j.framebufferTextureLayer(j.DRAW_FRAMEBUFFER,j.COLOR_ATTACHMENT0,r.__webglTexture,a,m+e):j.framebufferTexture2D(j.DRAW_FRAMEBUFFER,j.COLOR_ATTACHMENT0,j.TEXTURE_2D,r.__webglTexture,a),i===0?T?j.copyTexSubImage3D(v,a,f,p,m+e,l,u,o,s):j.copyTexSubImage2D(v,a,f,p,l,u,o,s):j.blitFramebuffer(l,u,o,s,f,p,o,s,j.COLOR_BUFFER_BIT,j.NEAREST);M.bindFramebuffer(j.READ_FRAMEBUFFER,null),M.bindFramebuffer(j.DRAW_FRAMEBUFFER,null)}else T?e.isDataTexture||e.isData3DTexture?j.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h.data):t.isCompressedArrayTexture?j.compressedTexSubImage3D(v,a,f,p,m,o,s,c,g,h.data):j.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h):e.isDataTexture?j.texSubImage2D(j.TEXTURE_2D,a,f,p,o,s,g,_,h.data):e.isCompressedTexture?j.compressedTexSubImage2D(j.TEXTURE_2D,a,f,p,h.width,h.height,g,h.data):j.texSubImage2D(j.TEXTURE_2D,a,f,p,o,s,g,_,h);j.pixelStorei(j.UNPACK_ROW_LENGTH,y),j.pixelStorei(j.UNPACK_IMAGE_HEIGHT,b),j.pixelStorei(j.UNPACK_SKIP_PIXELS,x),j.pixelStorei(j.UNPACK_SKIP_ROWS,S),j.pixelStorei(j.UNPACK_SKIP_IMAGES,C),a===0&&t.generateMipmaps&&j.generateMipmap(v),M.unbindTexture()},this.copyTextureToTexture3D=function(e,t,n=null,r=null,i=0){return Mt(`WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.`),this.copyTextureToTexture(e,t,n,r,i)},this.initRenderTarget=function(e){N.get(e).__webglFramebuffer===void 0&&P.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?P.setTextureCube(e,0):e.isData3DTexture?P.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?P.setTexture2DArray(e,0):P.setTexture2D(e,0),M.unbindTexture()},this.resetState=function(){w=0,T=0,E=null,M.reset(),Be.reset()},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}get coordinateSystem(){return Qe}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=zt._getDrawingBufferColorSpace(e),t.unpackColorSpace=zt._getUnpackColorSpace()}},du=function(){var e=0,t=document.createElement(`div`);t.style.cssText=`position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000`,t.addEventListener(`click`,function(n){n.preventDefault(),r(++e%t.children.length)},!1);function n(e){return t.appendChild(e.dom),e}function r(n){for(var r=0;r<t.children.length;r++)t.children[r].style.display=r===n?`block`:`none`;e=n}var i=(performance||Date).now(),a=i,o=0,s=n(new du.Panel(`FPS`,`#0ff`,`#002`)),c=n(new du.Panel(`MS`,`#0f0`,`#020`));if(self.performance&&self.performance.memory)var l=n(new du.Panel(`MB`,`#f08`,`#201`));return r(0),{REVISION:16,dom:t,addPanel:n,showPanel:r,begin:function(){i=(performance||Date).now()},end:function(){o++;var e=(performance||Date).now();if(c.update(e-i,200),e>=a+1e3&&(s.update(o*1e3/(e-a),100),a=e,o=0,l)){var t=performance.memory;l.update(t.usedJSHeapSize/1048576,t.jsHeapSizeLimit/1048576)}return e},update:function(){i=this.end()},domElement:t,setMode:r}};du.Panel=function(e,t,n){var r=1/0,i=0,a=Math.round,o=a(window.devicePixelRatio||1),s=80*o,c=48*o,l=3*o,u=2*o,d=3*o,f=15*o,p=74*o,m=30*o,h=document.createElement(`canvas`);h.width=s,h.height=c,h.style.cssText=`width:80px;height:48px`;var g=h.getContext(`2d`);return g.font=`bold `+9*o+`px Helvetica,Arial,sans-serif`,g.textBaseline=`top`,g.fillStyle=n,g.fillRect(0,0,s,c),g.fillStyle=t,g.fillText(e,l,u),g.fillRect(d,f,p,m),g.fillStyle=n,g.globalAlpha=.9,g.fillRect(d,f,p,m),{dom:h,update:function(c,_){r=Math.min(r,c),i=Math.max(i,c),g.fillStyle=n,g.globalAlpha=1,g.fillRect(0,0,s,f),g.fillStyle=t,g.fillText(a(c)+` `+e+` (`+a(r)+`-`+a(i)+`)`,l,u),g.drawImage(h,d+o,f,p-o,m,d,f,p-o,m),g.fillRect(d+p-o,f,o,m),g.fillStyle=n,g.globalAlpha=.9,g.fillRect(d+p-o,f,o,a((1-c/_)*m))}}};function fu(e,t){if(t===0)return console.warn(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.`),e;if(t===2||t===1){let n=e.getIndex();if(n===null){let t=[],r=e.getAttribute(`position`);if(r!==void 0){for(let e=0;e<r.count;e++)t.push(e);e.setIndex(t),n=e.getIndex()}else return console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.`),e}let r=n.count-2,i=[];if(t===2)for(let e=1;e<=r;e++)i.push(n.getX(0)),i.push(n.getX(e)),i.push(n.getX(e+1));else for(let e=0;e<r;e++)e%2==0?(i.push(n.getX(e)),i.push(n.getX(e+1)),i.push(n.getX(e+2))):(i.push(n.getX(e+2)),i.push(n.getX(e+1)),i.push(n.getX(e)));i.length/3!==r&&console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.`);let a=e.clone();return a.setIndex(i),a.clearGroups(),a}else return console.error(`THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:`,t),e}var pu=class extends co{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(e){return new yu(e)}),this.register(function(e){return new bu(e)}),this.register(function(e){return new ku(e)}),this.register(function(e){return new Au(e)}),this.register(function(e){return new ju(e)}),this.register(function(e){return new Su(e)}),this.register(function(e){return new Cu(e)}),this.register(function(e){return new wu(e)}),this.register(function(e){return new Tu(e)}),this.register(function(e){return new vu(e)}),this.register(function(e){return new Eu(e)}),this.register(function(e){return new xu(e)}),this.register(function(e){return new Ou(e)}),this.register(function(e){return new Du(e)}),this.register(function(e){return new gu(e)}),this.register(function(e){return new Mu(e)}),this.register(function(e){return new Nu(e)})}load(e,t,n,r){let i=this,a;if(this.resourcePath!==``)a=this.resourcePath;else if(this.path!==``){let t=No.extractUrlBase(e);a=No.resolveURL(t,this.path)}else a=No.extractUrlBase(e);this.manager.itemStart(e);let o=function(t){r?r(t):console.error(t),i.manager.itemError(e),i.manager.itemEnd(e)},s=new fo(this.manager);s.setPath(this.path),s.setResponseType(`arraybuffer`),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(n){try{i.parse(n,a,function(n){t(n),i.manager.itemEnd(e)},o)}catch(e){o(e)}},n,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,r){let i,a={},o={},s=new TextDecoder;if(typeof e==`string`)i=JSON.parse(e);else if(e instanceof ArrayBuffer)if(s.decode(new Uint8Array(e,0,4))===Pu){try{a[hu.KHR_BINARY_GLTF]=new Lu(e)}catch(e){r&&r(e);return}i=JSON.parse(a[hu.KHR_BINARY_GLTF].content)}else i=JSON.parse(s.decode(e));else i=e;if(i.asset===void 0||i.asset.version[0]<2){r&&r(Error(`THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.`));return}let c=new ld(i,{path:t||this.resourcePath||``,crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let e=0;e<this.pluginCallbacks.length;e++){let t=this.pluginCallbacks[e](c);t.name||console.error(`THREE.GLTFLoader: Invalid plugin found: missing name`),o[t.name]=t,a[t.name]=!0}if(i.extensionsUsed)for(let e=0;e<i.extensionsUsed.length;++e){let t=i.extensionsUsed[e],n=i.extensionsRequired||[];switch(t){case hu.KHR_MATERIALS_UNLIT:a[t]=new _u;break;case hu.KHR_DRACO_MESH_COMPRESSION:a[t]=new Ru(i,this.dracoLoader);break;case hu.KHR_TEXTURE_TRANSFORM:a[t]=new zu;break;case hu.KHR_MESH_QUANTIZATION:a[t]=new Bu;break;default:n.indexOf(t)>=0&&o[t]===void 0&&console.warn(`THREE.GLTFLoader: Unknown extension "`+t+`".`)}}c.setExtensions(a),c.setPlugins(o),c.parse(n,r)}parseAsync(e,t){let n=this;return new Promise(function(r,i){n.parse(e,t,r,i)})}};function mu(){let e={};return{get:function(t){return e[t]},add:function(t,n){e[t]=n},remove:function(t){delete e[t]},removeAll:function(){e={}}}}var hu={KHR_BINARY_GLTF:`KHR_binary_glTF`,KHR_DRACO_MESH_COMPRESSION:`KHR_draco_mesh_compression`,KHR_LIGHTS_PUNCTUAL:`KHR_lights_punctual`,KHR_MATERIALS_CLEARCOAT:`KHR_materials_clearcoat`,KHR_MATERIALS_DISPERSION:`KHR_materials_dispersion`,KHR_MATERIALS_IOR:`KHR_materials_ior`,KHR_MATERIALS_SHEEN:`KHR_materials_sheen`,KHR_MATERIALS_SPECULAR:`KHR_materials_specular`,KHR_MATERIALS_TRANSMISSION:`KHR_materials_transmission`,KHR_MATERIALS_IRIDESCENCE:`KHR_materials_iridescence`,KHR_MATERIALS_ANISOTROPY:`KHR_materials_anisotropy`,KHR_MATERIALS_UNLIT:`KHR_materials_unlit`,KHR_MATERIALS_VOLUME:`KHR_materials_volume`,KHR_TEXTURE_BASISU:`KHR_texture_basisu`,KHR_TEXTURE_TRANSFORM:`KHR_texture_transform`,KHR_MESH_QUANTIZATION:`KHR_mesh_quantization`,KHR_MATERIALS_EMISSIVE_STRENGTH:`KHR_materials_emissive_strength`,EXT_MATERIALS_BUMP:`EXT_materials_bump`,EXT_TEXTURE_WEBP:`EXT_texture_webp`,EXT_TEXTURE_AVIF:`EXT_texture_avif`,EXT_MESHOPT_COMPRESSION:`EXT_meshopt_compression`,EXT_MESH_GPU_INSTANCING:`EXT_mesh_gpu_instancing`},gu=class{constructor(e){this.parser=e,this.name=hu.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,r=t.length;n<r;n++){let r=t[n];r.extensions&&r.extensions[this.name]&&r.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,r.extensions[this.name].light)}}_loadLight(e){let t=this.parser,n=`light:`+e,r=t.cache.get(n);if(r)return r;let i=t.json,a=((i.extensions&&i.extensions[this.name]||{}).lights||[])[e],o,s=new B(16777215);a.color!==void 0&&s.setRGB(a.color[0],a.color[1],a.color[2],qe);let c=a.range===void 0?0:a.range;switch(a.type){case`directional`:o=new jo(s),o.target.position.set(0,0,-1),o.add(o.target);break;case`point`:o=new Oo(s),o.distance=c;break;case`spot`:o=new Co(s),o.distance=c,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle===void 0?0:a.spot.innerConeAngle,a.spot.outerConeAngle=a.spot.outerConeAngle===void 0?Math.PI/4:a.spot.outerConeAngle,o.angle=a.spot.outerConeAngle,o.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,o.target.position.set(0,0,-1),o.add(o.target);break;default:throw Error(`THREE.GLTFLoader: Unexpected light type: `+a.type)}return o.position.set(0,0,0),td(o,a),a.intensity!==void 0&&(o.intensity=a.intensity),o.name=t.createUniqueName(a.name||`light_`+e),r=Promise.resolve(o),t.cache.add(n,r),r}getDependency(e,t){if(e===`light`)return this._loadLight(t)}createNodeAttachment(e){let t=this,n=this.parser,r=n.json.nodes[e],i=(r.extensions&&r.extensions[this.name]||{}).light;return i===void 0?null:this._loadLight(i).then(function(e){return n._getNodeRef(t.cache,i,e)})}},_u=class{constructor(){this.name=hu.KHR_MATERIALS_UNLIT}getMaterialType(){return Tr}extendParams(e,t,n){let r=[];e.color=new B(1,1,1),e.opacity=1;let i=t.pbrMetallicRoughness;if(i){if(Array.isArray(i.baseColorFactor)){let t=i.baseColorFactor;e.color.setRGB(t[0],t[1],t[2],qe),e.opacity=t[3]}i.baseColorTexture!==void 0&&r.push(n.assignTexture(e,`map`,i.baseColorTexture,Ke))}return Promise.all(r)}},vu=class{constructor(e){this.parser=e,this.name=hu.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();let r=n.extensions[this.name].emissiveStrength;return r!==void 0&&(t.emissiveIntensity=r),Promise.resolve()}},yu=class{constructor(e){this.parser=e,this.name=hu.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:Ia}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];if(a.clearcoatFactor!==void 0&&(t.clearcoat=a.clearcoatFactor),a.clearcoatTexture!==void 0&&i.push(n.assignTexture(t,`clearcoatMap`,a.clearcoatTexture)),a.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=a.clearcoatRoughnessFactor),a.clearcoatRoughnessTexture!==void 0&&i.push(n.assignTexture(t,`clearcoatRoughnessMap`,a.clearcoatRoughnessTexture)),a.clearcoatNormalTexture!==void 0&&(i.push(n.assignTexture(t,`clearcoatNormalMap`,a.clearcoatNormalTexture)),a.clearcoatNormalTexture.scale!==void 0)){let e=a.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new L(e,e)}return Promise.all(i)}},bu=class{constructor(e){this.parser=e,this.name=hu.KHR_MATERIALS_DISPERSION}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:Ia}extendMaterialParams(e,t){let n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();let r=n.extensions[this.name];return t.dispersion=r.dispersion===void 0?0:r.dispersion,Promise.resolve()}},xu=class{constructor(e){this.parser=e,this.name=hu.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:Ia}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];return a.iridescenceFactor!==void 0&&(t.iridescence=a.iridescenceFactor),a.iridescenceTexture!==void 0&&i.push(n.assignTexture(t,`iridescenceMap`,a.iridescenceTexture)),a.iridescenceIor!==void 0&&(t.iridescenceIOR=a.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),a.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=a.iridescenceThicknessMinimum),a.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=a.iridescenceThicknessMaximum),a.iridescenceThicknessTexture!==void 0&&i.push(n.assignTexture(t,`iridescenceThicknessMap`,a.iridescenceThicknessTexture)),Promise.all(i)}},Su=class{constructor(e){this.parser=e,this.name=hu.KHR_MATERIALS_SHEEN}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:Ia}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[];t.sheenColor=new B(0,0,0),t.sheenRoughness=0,t.sheen=1;let a=r.extensions[this.name];if(a.sheenColorFactor!==void 0){let e=a.sheenColorFactor;t.sheenColor.setRGB(e[0],e[1],e[2],qe)}return a.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=a.sheenRoughnessFactor),a.sheenColorTexture!==void 0&&i.push(n.assignTexture(t,`sheenColorMap`,a.sheenColorTexture,Ke)),a.sheenRoughnessTexture!==void 0&&i.push(n.assignTexture(t,`sheenRoughnessMap`,a.sheenRoughnessTexture)),Promise.all(i)}},Cu=class{constructor(e){this.parser=e,this.name=hu.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:Ia}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];return a.transmissionFactor!==void 0&&(t.transmission=a.transmissionFactor),a.transmissionTexture!==void 0&&i.push(n.assignTexture(t,`transmissionMap`,a.transmissionTexture)),Promise.all(i)}},wu=class{constructor(e){this.parser=e,this.name=hu.KHR_MATERIALS_VOLUME}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:Ia}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];t.thickness=a.thicknessFactor===void 0?0:a.thicknessFactor,a.thicknessTexture!==void 0&&i.push(n.assignTexture(t,`thicknessMap`,a.thicknessTexture)),t.attenuationDistance=a.attenuationDistance||1/0;let o=a.attenuationColor||[1,1,1];return t.attenuationColor=new B().setRGB(o[0],o[1],o[2],qe),Promise.all(i)}},Tu=class{constructor(e){this.parser=e,this.name=hu.KHR_MATERIALS_IOR}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:Ia}extendMaterialParams(e,t){let n=this.parser.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();let r=n.extensions[this.name];return t.ior=r.ior===void 0?1.5:r.ior,Promise.resolve()}},Eu=class{constructor(e){this.parser=e,this.name=hu.KHR_MATERIALS_SPECULAR}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:Ia}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];t.specularIntensity=a.specularFactor===void 0?1:a.specularFactor,a.specularTexture!==void 0&&i.push(n.assignTexture(t,`specularIntensityMap`,a.specularTexture));let o=a.specularColorFactor||[1,1,1];return t.specularColor=new B().setRGB(o[0],o[1],o[2],qe),a.specularColorTexture!==void 0&&i.push(n.assignTexture(t,`specularColorMap`,a.specularColorTexture,Ke)),Promise.all(i)}},Du=class{constructor(e){this.parser=e,this.name=hu.EXT_MATERIALS_BUMP}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:Ia}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];return t.bumpScale=a.bumpFactor===void 0?1:a.bumpFactor,a.bumpTexture!==void 0&&i.push(n.assignTexture(t,`bumpMap`,a.bumpTexture)),Promise.all(i)}},Ou=class{constructor(e){this.parser=e,this.name=hu.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:Ia}extendMaterialParams(e,t){let n=this.parser,r=n.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=[],a=r.extensions[this.name];return a.anisotropyStrength!==void 0&&(t.anisotropy=a.anisotropyStrength),a.anisotropyRotation!==void 0&&(t.anisotropyRotation=a.anisotropyRotation),a.anisotropyTexture!==void 0&&i.push(n.assignTexture(t,`anisotropyMap`,a.anisotropyTexture)),Promise.all(i)}},ku=class{constructor(e){this.parser=e,this.name=hu.KHR_TEXTURE_BASISU}loadTexture(e){let t=this.parser,n=t.json,r=n.textures[e];if(!r.extensions||!r.extensions[this.name])return null;let i=r.extensions[this.name],a=t.options.ktx2Loader;if(!a){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw Error(`THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures`);return null}return t.loadTextureImage(e,i.source,a)}},Au=class{constructor(e){this.parser=e,this.name=hu.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},ju=class{constructor(e){this.parser=e,this.name=hu.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,n=this.parser,r=n.json,i=r.textures[e];if(!i.extensions||!i.extensions[t])return null;let a=i.extensions[t],o=r.images[a.source],s=n.textureLoader;if(o.uri){let e=n.options.manager.getHandler(o.uri);e!==null&&(s=e)}return n.loadTextureImage(e,a.source,s)}},Mu=class{constructor(e){this.name=hu.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){let t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){let e=n.extensions[this.name],r=this.parser.getDependency(`buffer`,e.buffer),i=this.parser.options.meshoptDecoder;if(!i||!i.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw Error(`THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files`);return null}return r.then(function(t){let n=e.byteOffset||0,r=e.byteLength||0,a=e.count,o=e.byteStride,s=new Uint8Array(t,n,r);return i.decodeGltfBufferAsync?i.decodeGltfBufferAsync(a,o,s,e.mode,e.filter).then(function(e){return e.buffer}):i.ready.then(function(){let t=new ArrayBuffer(a*o);return i.decodeGltfBuffer(new Uint8Array(t),a,o,s,e.mode,e.filter),t})})}else return null}},Nu=class{constructor(e){this.name=hu.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;let r=t.meshes[n.mesh];for(let e of r.primitives)if(e.mode!==Wu.TRIANGLES&&e.mode!==Wu.TRIANGLE_STRIP&&e.mode!==Wu.TRIANGLE_FAN&&e.mode!==void 0)return null;let i=n.extensions[this.name].attributes,a=[],o={};for(let e in i)a.push(this.parser.getDependency(`accessor`,i[e]).then(t=>(o[e]=t,o[e])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(e=>{let t=e.pop(),n=t.isGroup?t.children:[t],r=e[0].count,i=[];for(let e of n){let t=new z,n=new R,a=new en,s=new R(1,1,1),c=new ta(e.geometry,e.material,r);for(let e=0;e<r;e++)o.TRANSLATION&&n.fromBufferAttribute(o.TRANSLATION,e),o.ROTATION&&a.fromBufferAttribute(o.ROTATION,e),o.SCALE&&s.fromBufferAttribute(o.SCALE,e),c.setMatrixAt(e,t.compose(n,a,s));for(let t in o)if(t===`_COLOR_0`){let e=o[t];c.instanceColor=new qi(e.array,e.itemSize,e.normalized)}else t!==`TRANSLATION`&&t!==`ROTATION`&&t!==`SCALE`&&e.geometry.setAttribute(t,o[t]);rr.prototype.copy.call(c,e),this.parser.assignFinalMaterial(c),i.push(c)}return t.isGroup?(t.clear(),t.add(...i),t):i[0]}))}},Pu=`glTF`,Fu=12,Iu={JSON:1313821514,BIN:5130562},Lu=class{constructor(e){this.name=hu.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,Fu),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Pu)throw Error(`THREE.GLTFLoader: Unsupported glTF-Binary header.`);if(this.header.version<2)throw Error(`THREE.GLTFLoader: Legacy binary file detected.`);let r=this.header.length-Fu,i=new DataView(e,Fu),a=0;for(;a<r;){let t=i.getUint32(a,!0);a+=4;let r=i.getUint32(a,!0);if(a+=4,r===Iu.JSON){let r=new Uint8Array(e,Fu+a,t);this.content=n.decode(r)}else if(r===Iu.BIN){let n=Fu+a;this.body=e.slice(n,n+t)}a+=t}if(this.content===null)throw Error(`THREE.GLTFLoader: JSON content not found.`)}},Ru=class{constructor(e,t){if(!t)throw Error(`THREE.GLTFLoader: No DRACOLoader instance provided.`);this.name=hu.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){let n=this.json,r=this.dracoLoader,i=e.extensions[this.name].bufferView,a=e.extensions[this.name].attributes,o={},s={},c={};for(let e in a){let t=Yu[e]||e.toLowerCase();o[t]=a[e]}for(let t in e.attributes){let r=Yu[t]||t.toLowerCase();if(a[t]!==void 0){let i=n.accessors[e.attributes[t]];c[r]=Gu[i.componentType].name,s[r]=i.normalized===!0}}return t.getDependency(`bufferView`,i).then(function(e){return new Promise(function(t,n){r.decodeDracoFile(e,function(e){for(let t in e.attributes){let n=e.attributes[t],r=s[t];r!==void 0&&(n.normalized=r)}t(e)},o,c,qe,n)})})}},zu=class{constructor(){this.name=hu.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0?e:(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0,e)}},Bu=class{constructor(){this.name=hu.KHR_MESH_QUANTIZATION}},Vu=class extends Wa{constructor(e,t,n,r){super(e,t,n,r)}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r*3+r;for(let e=0;e!==r;e++)t[e]=n[i+e];return t}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=o*2,c=o*3,l=r-t,u=(n-t)/l,d=u*u,f=d*u,p=e*c,m=p-c,h=-2*f+3*d,g=f-d,_=1-h,v=g-d+u;for(let e=0;e!==o;e++){let t=a[m+e+o],n=a[m+e+s]*l,r=a[p+e+o],c=a[p+e]*l;i[e]=_*t+v*n+h*r+g*c}return i}},Hu=new en,Uu=class extends Vu{interpolate_(e,t,n,r){let i=super.interpolate_(e,t,n,r);return Hu.fromArray(i).normalize().toArray(i),i}},Wu={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},Gu={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Ku={9728:l,9729:f,9984:u,9985:p,9986:d,9987:m},qu={33071:s,33648:c,10497:o},Ju={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Yu={POSITION:`position`,NORMAL:`normal`,TANGENT:`tangent`,TEXCOORD_0:`uv`,TEXCOORD_1:`uv1`,TEXCOORD_2:`uv2`,TEXCOORD_3:`uv3`,COLOR_0:`color`,WEIGHTS_0:`skinWeight`,JOINTS_0:`skinIndex`},Xu={scale:`scale`,translation:`position`,rotation:`quaternion`,weights:`morphTargetInfluences`},Zu={CUBICSPLINE:void 0,LINEAR:Le,STEP:Ie},Qu={OPAQUE:`OPAQUE`,MASK:`MASK`,BLEND:`BLEND`};function $u(e){return e.DefaultMaterial===void 0&&(e.DefaultMaterial=new Fa({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:0})),e.DefaultMaterial}function ed(e,t,n){for(let r in n.extensions)e[r]===void 0&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[r]=n.extensions[r])}function td(e,t){t.extras!==void 0&&(typeof t.extras==`object`?Object.assign(e.userData,t.extras):console.warn(`THREE.GLTFLoader: Ignoring primitive type .extras, `+t.extras))}function nd(e,t,n){let r=!1,i=!1,a=!1;for(let e=0,n=t.length;e<n;e++){let n=t[e];if(n.POSITION!==void 0&&(r=!0),n.NORMAL!==void 0&&(i=!0),n.COLOR_0!==void 0&&(a=!0),r&&i&&a)break}if(!r&&!i&&!a)return Promise.resolve(e);let o=[],s=[],c=[];for(let l=0,u=t.length;l<u;l++){let u=t[l];if(r){let t=u.POSITION===void 0?e.attributes.position:n.getDependency(`accessor`,u.POSITION);o.push(t)}if(i){let t=u.NORMAL===void 0?e.attributes.normal:n.getDependency(`accessor`,u.NORMAL);s.push(t)}if(a){let t=u.COLOR_0===void 0?e.attributes.color:n.getDependency(`accessor`,u.COLOR_0);c.push(t)}}return Promise.all([Promise.all(o),Promise.all(s),Promise.all(c)]).then(function(t){let n=t[0],o=t[1],s=t[2];return r&&(e.morphAttributes.position=n),i&&(e.morphAttributes.normal=o),a&&(e.morphAttributes.color=s),e.morphTargetsRelative=!0,e})}function rd(e,t){if(e.updateMorphTargets(),t.weights!==void 0)for(let n=0,r=t.weights.length;n<r;n++)e.morphTargetInfluences[n]=t.weights[n];if(t.extras&&Array.isArray(t.extras.targetNames)){let n=t.extras.targetNames;if(e.morphTargetInfluences.length===n.length){e.morphTargetDictionary={};for(let t=0,r=n.length;t<r;t++)e.morphTargetDictionary[n[t]]=t}else console.warn(`THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.`)}}function id(e){let t,n=e.extensions&&e.extensions[hu.KHR_DRACO_MESH_COMPRESSION];if(t=n?`draco:`+n.bufferView+`:`+n.indices+`:`+ad(n.attributes):e.indices+`:`+ad(e.attributes)+`:`+e.mode,e.targets!==void 0)for(let n=0,r=e.targets.length;n<r;n++)t+=`:`+ad(e.targets[n]);return t}function ad(e){let t=``,n=Object.keys(e).sort();for(let r=0,i=n.length;r<i;r++)t+=n[r]+`:`+e[n[r]]+`;`;return t}function od(e){switch(e){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw Error(`THREE.GLTFLoader: Unsupported normalized accessor component type.`)}}function sd(e){return e.search(/\.jpe?g($|\?)/i)>0||e.search(/^data\:image\/jpeg/)===0?`image/jpeg`:e.search(/\.webp($|\?)/i)>0||e.search(/^data\:image\/webp/)===0?`image/webp`:e.search(/\.ktx2($|\?)/i)>0||e.search(/^data\:image\/ktx2/)===0?`image/ktx2`:`image/png`}var cd=new z,ld=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new mu,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,r=-1,i=!1,a=-1;if(typeof navigator<`u`){let e=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(e)===!0;let t=e.match(/Version\/(\d+)/);r=n&&t?parseInt(t[1],10):-1,i=e.indexOf(`Firefox`)>-1,a=i?e.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>`u`||n&&r<17||i&&a<98?this.textureLoader=new ho(this.options.manager):this.textureLoader=new Po(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new fo(this.options.manager),this.fileLoader.setResponseType(`arraybuffer`),this.options.crossOrigin===`use-credentials`&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let n=this,r=this.json,i=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(e){return e._markDefs&&e._markDefs()}),Promise.all(this._invokeAll(function(e){return e.beforeRoot&&e.beforeRoot()})).then(function(){return Promise.all([n.getDependencies(`scene`),n.getDependencies(`animation`),n.getDependencies(`camera`)])}).then(function(t){let a={scene:t[0][r.scene||0],scenes:t[0],animations:t[1],cameras:t[2],asset:r.asset,parser:n,userData:{}};return ed(i,a,r),td(a,r),Promise.all(n._invokeAll(function(e){return e.afterRoot&&e.afterRoot(a)})).then(function(){for(let e of a.scenes)e.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let n=0,r=t.length;n<r;n++){let r=t[n].joints;for(let t=0,n=r.length;t<n;t++)e[r[t]].isBone=!0}for(let t=0,r=e.length;t<r;t++){let r=e[t];r.mesh!==void 0&&(this._addNodeRef(this.meshCache,r.mesh),r.skin!==void 0&&(n[r.mesh].isSkinnedMesh=!0)),r.camera!==void 0&&this._addNodeRef(this.cameraCache,r.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;let r=n.clone(),i=(e,t)=>{let n=this.associations.get(e);n!=null&&this.associations.set(t,n);for(let[n,r]of e.children.entries())i(r,t.children[n])};return i(n,r),r.name+=`_instance_`+ e.uses[t]++,r}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){let r=e(t[n]);if(r)return r}return null}_invokeAll(e){let t=Object.values(this.plugins);t.unshift(this);let n=[];for(let r=0;r<t.length;r++){let i=e(t[r]);i&&n.push(i)}return n}getDependency(e,t){let n=e+`:`+t,r=this.cache.get(n);if(!r){switch(e){case`scene`:r=this.loadScene(t);break;case`node`:r=this._invokeOne(function(e){return e.loadNode&&e.loadNode(t)});break;case`mesh`:r=this._invokeOne(function(e){return e.loadMesh&&e.loadMesh(t)});break;case`accessor`:r=this.loadAccessor(t);break;case`bufferView`:r=this._invokeOne(function(e){return e.loadBufferView&&e.loadBufferView(t)});break;case`buffer`:r=this.loadBuffer(t);break;case`material`:r=this._invokeOne(function(e){return e.loadMaterial&&e.loadMaterial(t)});break;case`texture`:r=this._invokeOne(function(e){return e.loadTexture&&e.loadTexture(t)});break;case`skin`:r=this.loadSkin(t);break;case`animation`:r=this._invokeOne(function(e){return e.loadAnimation&&e.loadAnimation(t)});break;case`camera`:r=this.loadCamera(t);break;default:if(r=this._invokeOne(function(n){return n!=this&&n.getDependency&&n.getDependency(e,t)}),!r)throw Error(`Unknown type: `+e);break}this.cache.add(n,r)}return r}getDependencies(e){let t=this.cache.get(e);if(!t){let n=this,r=this.json[e+(e===`mesh`?`es`:`s`)]||[];t=Promise.all(r.map(function(t,r){return n.getDependency(e,r)})),this.cache.add(e,t)}return t}loadBuffer(e){let t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!==`arraybuffer`)throw Error(`THREE.GLTFLoader: `+t.type+` buffer type is not supported.`);if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[hu.KHR_BINARY_GLTF].body);let r=this.options;return new Promise(function(e,i){n.load(No.resolveURL(t.uri,r.path),e,void 0,function(){i(Error(`THREE.GLTFLoader: Failed to load buffer "`+t.uri+`".`))})})}loadBufferView(e){let t=this.json.bufferViews[e];return this.getDependency(`buffer`,t.buffer).then(function(e){let n=t.byteLength||0,r=t.byteOffset||0;return e.slice(r,r+n)})}loadAccessor(e){let t=this,n=this.json,r=this.json.accessors[e];if(r.bufferView===void 0&&r.sparse===void 0){let e=Ju[r.type],t=Gu[r.componentType],n=r.normalized===!0,i=new t(r.count*e);return Promise.resolve(new Pr(i,e,n))}let i=[];return r.bufferView===void 0?i.push(null):i.push(this.getDependency(`bufferView`,r.bufferView)),r.sparse!==void 0&&(i.push(this.getDependency(`bufferView`,r.sparse.indices.bufferView)),i.push(this.getDependency(`bufferView`,r.sparse.values.bufferView))),Promise.all(i).then(function(e){let i=e[0],a=Ju[r.type],o=Gu[r.componentType],s=o.BYTES_PER_ELEMENT,c=s*a,l=r.byteOffset||0,u=r.bufferView===void 0?void 0:n.bufferViews[r.bufferView].byteStride,d=r.normalized===!0,f,p;if(u&&u!==c){let e=Math.floor(l/u),n=`InterleavedBuffer:`+r.bufferView+`:`+r.componentType+`:`+e+`:`+r.count,c=t.cache.get(n);c||(f=new o(i,e*u,r.count*u/s),c=new ki(f,u/s),t.cache.add(n,c)),p=new ji(c,a,l%u/s,d)}else f=i===null?new o(r.count*a):new o(i,l,r.count*a),p=new Pr(f,a,d);if(r.sparse!==void 0){let t=Ju.SCALAR,n=Gu[r.sparse.indices.componentType],s=r.sparse.indices.byteOffset||0,c=r.sparse.values.byteOffset||0,l=new n(e[1],s,r.sparse.count*t),u=new o(e[2],c,r.sparse.count*a);i!==null&&(p=new Pr(p.array.slice(),p.itemSize,p.normalized)),p.normalized=!1;for(let e=0,t=l.length;e<t;e++){let t=l[e];if(p.setX(t,u[e*a]),a>=2&&p.setY(t,u[e*a+1]),a>=3&&p.setZ(t,u[e*a+2]),a>=4&&p.setW(t,u[e*a+3]),a>=5)throw Error(`THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.`)}p.normalized=d}return p})}loadTexture(e){let t=this.json,n=this.options,r=t.textures[e].source,i=t.images[r],a=this.textureLoader;if(i.uri){let e=n.manager.getHandler(i.uri);e!==null&&(a=e)}return this.loadTextureImage(e,r,a)}loadTextureImage(e,t,n){let r=this,i=this.json,a=i.textures[e],o=i.images[t],s=(o.uri||o.bufferView)+`:`+a.sampler;if(this.textureCache[s])return this.textureCache[s];let c=this.loadImageSource(t,n).then(function(t){t.flipY=!1,t.name=a.name||o.name||``,t.name===``&&typeof o.uri==`string`&&o.uri.startsWith(`data:image/`)===!1&&(t.name=o.uri);let n=(i.samplers||{})[a.sampler]||{};return t.magFilter=Ku[n.magFilter]||1006,t.minFilter=Ku[n.minFilter]||1008,t.wrapS=qu[n.wrapS]||1e3,t.wrapT=qu[n.wrapT]||1e3,t.generateMipmaps=!t.isCompressedTexture&&t.minFilter!==1003&&t.minFilter!==1006,r.associations.set(t,{textures:e}),t}).catch(function(){return null});return this.textureCache[s]=c,c}loadImageSource(e,t){let n=this,r=this.json,i=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(e=>e.clone());let a=r.images[e],o=self.URL||self.webkitURL,s=a.uri||``,c=!1;if(a.bufferView!==void 0)s=n.getDependency(`bufferView`,a.bufferView).then(function(e){c=!0;let t=new Blob([e],{type:a.mimeType});return s=o.createObjectURL(t),s});else if(a.uri===void 0)throw Error(`THREE.GLTFLoader: Image `+e+` is missing URI and bufferView`);let l=Promise.resolve(s).then(function(e){return new Promise(function(n,r){let a=n;t.isImageBitmapLoader===!0&&(a=function(e){let t=new Jt(e);t.needsUpdate=!0,n(t)}),t.load(No.resolveURL(e,i.path),a,void 0,r)})}).then(function(e){return c===!0&&o.revokeObjectURL(s),td(e,a),e.userData.mimeType=a.mimeType||sd(a.uri),e}).catch(function(e){throw console.error(`THREE.GLTFLoader: Couldn't load texture`,s),e});return this.sourceCache[e]=l,l}assignTexture(e,t,n,r){let i=this;return this.getDependency(`texture`,n.index).then(function(a){if(!a)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(a=a.clone(),a.channel=n.texCoord),i.extensions[hu.KHR_TEXTURE_TRANSFORM]){let e=n.extensions===void 0?void 0:n.extensions[hu.KHR_TEXTURE_TRANSFORM];if(e){let t=i.associations.get(a);a=i.extensions[hu.KHR_TEXTURE_TRANSFORM].extendTexture(a,e),i.associations.set(a,t)}}return r!==void 0&&(a.colorSpace=r),e[t]=a,a})}assignFinalMaterial(e){let t=e.geometry,n=e.material,r=t.attributes.tangent===void 0,i=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){let e=`PointsMaterial:`+n.uuid,t=this.cache.get(e);t||(t=new Ca,wr.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,t.sizeAttenuation=!1,this.cache.add(e,t)),n=t}else if(e.isLine){let e=`LineBasicMaterial:`+n.uuid,t=this.cache.get(e);t||(t=new la,wr.prototype.copy.call(t,n),t.color.copy(n.color),t.map=n.map,this.cache.add(e,t)),n=t}if(r||i||a){let e=`ClonedMaterial:`+n.uuid+`:`;r&&(e+=`derivative-tangents:`),i&&(e+=`vertex-colors:`),a&&(e+=`flat-shading:`);let t=this.cache.get(e);t||(t=n.clone(),i&&(t.vertexColors=!0),a&&(t.flatShading=!0),r&&(t.normalScale&&(t.normalScale.y*=-1),t.clearcoatNormalScale&&(t.clearcoatNormalScale.y*=-1)),this.cache.add(e,t),this.associations.set(t,this.associations.get(n))),n=t}e.material=n}getMaterialType(){return Fa}loadMaterial(e){let t=this,n=this.json,r=this.extensions,i=n.materials[e],a,o={},s=i.extensions||{},c=[];if(s[hu.KHR_MATERIALS_UNLIT]){let e=r[hu.KHR_MATERIALS_UNLIT];a=e.getMaterialType(),c.push(e.extendParams(o,i,t))}else{let n=i.pbrMetallicRoughness||{};if(o.color=new B(1,1,1),o.opacity=1,Array.isArray(n.baseColorFactor)){let e=n.baseColorFactor;o.color.setRGB(e[0],e[1],e[2],qe),o.opacity=e[3]}n.baseColorTexture!==void 0&&c.push(t.assignTexture(o,`map`,n.baseColorTexture,Ke)),o.metalness=n.metallicFactor===void 0?1:n.metallicFactor,o.roughness=n.roughnessFactor===void 0?1:n.roughnessFactor,n.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,`metalnessMap`,n.metallicRoughnessTexture)),c.push(t.assignTexture(o,`roughnessMap`,n.metallicRoughnessTexture))),a=this._invokeOne(function(t){return t.getMaterialType&&t.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,o)})))}i.doubleSided===!0&&(o.side=2);let l=i.alphaMode||Qu.OPAQUE;if(l===Qu.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,l===Qu.MASK&&(o.alphaTest=i.alphaCutoff===void 0?.5:i.alphaCutoff)),i.normalTexture!==void 0&&a!==Tr&&(c.push(t.assignTexture(o,`normalMap`,i.normalTexture)),o.normalScale=new L(1,1),i.normalTexture.scale!==void 0)){let e=i.normalTexture.scale;o.normalScale.set(e,e)}if(i.occlusionTexture!==void 0&&a!==Tr&&(c.push(t.assignTexture(o,`aoMap`,i.occlusionTexture)),i.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=i.occlusionTexture.strength)),i.emissiveFactor!==void 0&&a!==Tr){let e=i.emissiveFactor;o.emissive=new B().setRGB(e[0],e[1],e[2],qe)}return i.emissiveTexture!==void 0&&a!==Tr&&c.push(t.assignTexture(o,`emissiveMap`,i.emissiveTexture,Ke)),Promise.all(c).then(function(){let n=new a(o);return i.name&&(n.name=i.name),td(n,i),t.associations.set(n,{materials:e}),i.extensions&&ed(r,n,i),n})}createUniqueName(e){let t=Jo.sanitizeNodeName(e||``);return t in this.nodeNamesUsed?t+`_`+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,n=this.extensions,r=this.primitiveCache;function i(e){return n[hu.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(e,t).then(function(n){return dd(n,e,t)})}let a=[];for(let n=0,o=e.length;n<o;n++){let o=e[n],s=id(o),c=r[s];if(c)a.push(c.promise);else{let e;e=o.extensions&&o.extensions[hu.KHR_DRACO_MESH_COMPRESSION]?i(o):dd(new Gr,o,t),r[s]={primitive:o,promise:e},a.push(e)}}return Promise.all(a)}loadMesh(e){let t=this,n=this.json,r=this.extensions,i=n.meshes[e],a=i.primitives,o=[];for(let e=0,t=a.length;e<t;e++){let t=a[e].material===void 0?$u(this.cache):this.getDependency(`material`,a[e].material);o.push(t)}return o.push(t.loadGeometries(a)),Promise.all(o).then(function(n){let o=n.slice(0,n.length-1),s=n[n.length-1],c=[];for(let n=0,l=s.length;n<l;n++){let l=s[n],u=a[n],d,f=o[n];if(u.mode===Wu.TRIANGLES||u.mode===Wu.TRIANGLE_STRIP||u.mode===Wu.TRIANGLE_FAN||u.mode===void 0)d=i.isSkinnedMesh===!0?new Vi(l,f):new ri(l,f),d.isSkinnedMesh===!0&&d.normalizeSkinWeights(),u.mode===Wu.TRIANGLE_STRIP?d.geometry=fu(d.geometry,1):u.mode===Wu.TRIANGLE_FAN&&(d.geometry=fu(d.geometry,2));else if(u.mode===Wu.LINES)d=new xa(l,f);else if(u.mode===Wu.LINE_STRIP)d=new _a(l,f);else if(u.mode===Wu.LINE_LOOP)d=new Sa(l,f);else if(u.mode===Wu.POINTS)d=new Oa(l,f);else throw Error(`THREE.GLTFLoader: Primitive mode unsupported: `+u.mode);Object.keys(d.geometry.morphAttributes).length>0&&rd(d,i),d.name=t.createUniqueName(i.name||`mesh_`+e),td(d,i),u.extensions&&ed(r,d,u),t.assignFinalMaterial(d),c.push(d)}for(let n=0,r=c.length;n<r;n++)t.associations.set(c[n],{meshes:e,primitives:n});if(c.length===1)return i.extensions&&ed(r,c[0],i),c[0];let l=new Ti;i.extensions&&ed(r,l,i),t.associations.set(l,{meshes:e});for(let e=0,t=c.length;e<t;e++)l.add(c[e]);return l})}loadCamera(e){let t,n=this.json.cameras[e],r=n[n.type];if(!r){console.warn(`THREE.GLTFLoader: Missing camera parameters.`);return}return n.type===`perspective`?t=new yi(Tt.radToDeg(r.yfov),r.aspectRatio||1,r.znear||1,r.zfar||2e6):n.type===`orthographic`&&(t=new ko(-r.xmag,r.xmag,r.ymag,-r.ymag,r.znear,r.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),td(t,n),Promise.resolve(t)}loadSkin(e){let t=this.json.skins[e],n=[];for(let e=0,r=t.joints.length;e<r;e++)n.push(this._loadNodeShallow(t.joints[e]));return t.inverseBindMatrices===void 0?n.push(null):n.push(this.getDependency(`accessor`,t.inverseBindMatrices)),Promise.all(n).then(function(e){let n=e.pop(),r=e,i=[],a=[];for(let e=0,o=r.length;e<o;e++){let o=r[e];if(o){i.push(o);let t=new z;n!==null&&t.fromArray(n.array,e*16),a.push(t)}else console.warn(`THREE.GLTFLoader: Joint "%s" could not be found.`,t.joints[e])}return new Ki(i,a)})}loadAnimation(e){let t=this.json,n=this,r=t.animations[e],i=r.name?r.name:`animation_`+e,a=[],o=[],s=[],c=[],l=[];for(let e=0,t=r.channels.length;e<t;e++){let t=r.channels[e],n=r.samplers[t.sampler],i=t.target,u=i.node,d=r.parameters===void 0?n.input:r.parameters[n.input],f=r.parameters===void 0?n.output:r.parameters[n.output];i.node!==void 0&&(a.push(this.getDependency(`node`,u)),o.push(this.getDependency(`accessor`,d)),s.push(this.getDependency(`accessor`,f)),c.push(n),l.push(i))}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(s),Promise.all(c),Promise.all(l)]).then(function(e){let t=e[0],r=e[1],a=e[2],o=e[3],s=e[4],c=[];for(let e=0,i=t.length;e<i;e++){let i=t[e],l=r[e],u=a[e],d=o[e],f=s[e];if(i===void 0)continue;i.updateMatrix&&i.updateMatrix();let p=n._createAnimationTracks(i,l,u,d,f);if(p)for(let e=0;e<p.length;e++)c.push(p[e])}return new no(i,void 0,c)})}createNodeMesh(e){let t=this.json,n=this,r=t.nodes[e];return r.mesh===void 0?null:n.getDependency(`mesh`,r.mesh).then(function(e){let t=n._getNodeRef(n.meshCache,r.mesh,e);return r.weights!==void 0&&t.traverse(function(e){if(e.isMesh)for(let t=0,n=r.weights.length;t<n;t++)e.morphTargetInfluences[t]=r.weights[t]}),t})}loadNode(e){let t=this.json,n=this,r=t.nodes[e],i=n._loadNodeShallow(e),a=[],o=r.children||[];for(let e=0,t=o.length;e<t;e++)a.push(n.getDependency(`node`,o[e]));let s=r.skin===void 0?Promise.resolve(null):n.getDependency(`skin`,r.skin);return Promise.all([i,Promise.all(a),s]).then(function(e){let t=e[0],n=e[1],r=e[2];r!==null&&t.traverse(function(e){e.isSkinnedMesh&&e.bind(r,cd)});for(let e=0,r=n.length;e<r;e++)t.add(n[e]);return t})}_loadNodeShallow(e){let t=this.json,n=this.extensions,r=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let i=t.nodes[e],a=i.name?r.createUniqueName(i.name):``,o=[],s=r._invokeOne(function(t){return t.createNodeMesh&&t.createNodeMesh(e)});return s&&o.push(s),i.camera!==void 0&&o.push(r.getDependency(`camera`,i.camera).then(function(e){return r._getNodeRef(r.cameraCache,i.camera,e)})),r._invokeAll(function(t){return t.createNodeAttachment&&t.createNodeAttachment(e)}).forEach(function(e){o.push(e)}),this.nodeCache[e]=Promise.all(o).then(function(t){let o;if(o=i.isBone===!0?new Hi:t.length>1?new Ti:t.length===1?t[0]:new rr,o!==t[0])for(let e=0,n=t.length;e<n;e++)o.add(t[e]);if(i.name&&(o.userData.name=i.name,o.name=a),td(o,i),i.extensions&&ed(n,o,i),i.matrix!==void 0){let e=new z;e.fromArray(i.matrix),o.applyMatrix4(e)}else i.translation!==void 0&&o.position.fromArray(i.translation),i.rotation!==void 0&&o.quaternion.fromArray(i.rotation),i.scale!==void 0&&o.scale.fromArray(i.scale);return r.associations.has(o)||r.associations.set(o,{}),r.associations.get(o).nodes=e,o}),this.nodeCache[e]}loadScene(e){let t=this.extensions,n=this.json.scenes[e],r=this,i=new Ti;n.name&&(i.name=r.createUniqueName(n.name)),td(i,n),n.extensions&&ed(t,i,n);let a=n.nodes||[],o=[];for(let e=0,t=a.length;e<t;e++)o.push(r.getDependency(`node`,a[e]));return Promise.all(o).then(function(e){for(let t=0,n=e.length;t<n;t++)i.add(e[t]);return r.associations=(e=>{let t=new Map;for(let[e,n]of r.associations)(e instanceof wr||e instanceof Jt)&&t.set(e,n);return e.traverse(e=>{let n=r.associations.get(e);n!=null&&t.set(e,n)}),t})(i),i})}_createAnimationTracks(e,t,n,r,i){let a=[],o=e.name?e.name:e.uuid,s=[];Xu[i.path]===Xu.weights?e.traverse(function(e){e.morphTargetInfluences&&s.push(e.name?e.name:e.uuid)}):s.push(o);let c;switch(Xu[i.path]){case Xu.weights:c=Za;break;case Xu.rotation:c=$a;break;case Xu.translation:case Xu.scale:c=to;break;default:switch(n.itemSize){case 1:c=Za;break;default:c=to;break}break}let l=r.interpolation===void 0?Le:Zu[r.interpolation],u=this._getArrayFromAccessor(n);for(let e=0,n=s.length;e<n;e++){let n=new c(s[e]+`.`+Xu[i.path],t.array,u,l);r.interpolation===`CUBICSPLINE`&&this._createCubicSplineTrackInterpolant(n),a.push(n)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let e=od(t.constructor),n=new Float32Array(t.length);for(let r=0,i=t.length;r<i;r++)n[r]=t[r]*e;t=n}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(e){return new(this instanceof $a?Uu:Vu)(this.times,this.values,this.getValueSize()/3,e)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}};function ud(e,t,n){let r=t.attributes,i=new rn;if(r.POSITION!==void 0){let e=n.json.accessors[r.POSITION],t=e.min,a=e.max;if(t!==void 0&&a!==void 0){if(i.set(new R(t[0],t[1],t[2]),new R(a[0],a[1],a[2])),e.normalized){let t=od(Gu[e.componentType]);i.min.multiplyScalar(t),i.max.multiplyScalar(t)}}else{console.warn(`THREE.GLTFLoader: Missing min/max properties for accessor POSITION.`);return}}else return;let a=t.targets;if(a!==void 0){let e=new R,t=new R;for(let r=0,i=a.length;r<i;r++){let i=a[r];if(i.POSITION!==void 0){let r=n.json.accessors[i.POSITION],a=r.min,o=r.max;if(a!==void 0&&o!==void 0){if(t.setX(Math.max(Math.abs(a[0]),Math.abs(o[0]))),t.setY(Math.max(Math.abs(a[1]),Math.abs(o[1]))),t.setZ(Math.max(Math.abs(a[2]),Math.abs(o[2]))),r.normalized){let e=od(Gu[r.componentType]);t.multiplyScalar(e)}e.max(t)}else console.warn(`THREE.GLTFLoader: Missing min/max properties for accessor POSITION.`)}}i.expandByVector(e)}e.boundingBox=i;let o=new Sn;i.getCenter(o.center),o.radius=i.min.distanceTo(i.max)/2,e.boundingSphere=o}function dd(e,t,n){let r=t.attributes,i=[];function a(t,r){return n.getDependency(`accessor`,t).then(function(t){e.setAttribute(r,t)})}for(let t in r){let n=Yu[t]||t.toLowerCase();n in e.attributes||i.push(a(r[t],n))}if(t.indices!==void 0&&!e.index){let r=n.getDependency(`accessor`,t.indices).then(function(t){e.setIndex(t)});i.push(r)}return zt.workingColorSpace!==`srgb-linear`&&`COLOR_0`in r&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${zt.workingColorSpace}" not supported.`),td(e,t),ud(e,t,n),Promise.all(i).then(function(){return t.targets===void 0?e:nd(e,t.targets,n)})}var fd=(function(){"use strict";var e=`b9H79Tebbbe8Fv9Gbb9Gvuuuuueu9Giuuub9Geueu9Giuuueuikqbeeedddillviebeoweuec:q;iekr;leDo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbeY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVbdE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbiL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtblK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949Wbol79IV9Rbrq:P8Yqdbk;3sezu8Jjjjjbcj;eb9Rgv8Kjjjjbc9:hodnadcefal0mbcuhoaiRbbc:Ge9hmbavaialfgrad9Radz1jjjbhwcj;abad9UhoaicefhldnadTmbaoc;WFbGgocjdaocjd6EhDcbhqinaqae9pmeaDaeaq9RaqaDfae6Egkcsfgocl4cifcd4hxdndndndnaoc9WGgmTmbcbhPcehsawcjdfhzalhHinaraH9Rax6midnaraHaxfgl9RcK6mbczhoinawcj;cbfaogifgoc9WfhOdndndndndnaHaic9WfgAco4fRbbaAci4coG4ciGPlbedibkaO9cb83ibaOcwf9cb83ibxikaOalRblalRbbgAco4gCaCciSgCE86bbaocGfalclfaCfgORbbaAcl4ciGgCaCciSgCE86bbaocVfaOaCfgORbbaAcd4ciGgCaCciSgCE86bbaoc7faOaCfgORbbaAciGgAaAciSgAE86bbaoctfaOaAfgARbbalRbegOco4gCaCciSgCE86bbaoc91faAaCfgARbbaOcl4ciGgCaCciSgCE86bbaoc4faAaCfgARbbaOcd4ciGgCaCciSgCE86bbaoc93faAaCfgARbbaOciGgOaOciSgOE86bbaoc94faAaOfgARbbalRbdgOco4gCaCciSgCE86bbaoc95faAaCfgARbbaOcl4ciGgCaCciSgCE86bbaoc96faAaCfgARbbaOcd4ciGgCaCciSgCE86bbaoc97faAaCfgARbbaOciGgOaOciSgOE86bbaoc98faAaOfgORbbalRbiglco4gAaAciSgAE86bbaoc99faOaAfgORbbalcl4ciGgAaAciSgAE86bbaoc9:faOaAfgORbbalcd4ciGgAaAciSgAE86bbaocufaOaAfgoRbbalciGglalciSglE86bbaoalfhlxdkaOalRbwalRbbgAcl4gCaCcsSgCE86bbaocGfalcwfaCfgORbbaAcsGgAaAcsSgAE86bbaocVfaOaAfgORbbalRbegAcl4gCaCcsSgCE86bbaoc7faOaCfgORbbaAcsGgAaAcsSgAE86bbaoctfaOaAfgORbbalRbdgAcl4gCaCcsSgCE86bbaoc91faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc4faOaAfgORbbalRbigAcl4gCaCcsSgCE86bbaoc93faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc94faOaAfgORbbalRblgAcl4gCaCcsSgCE86bbaoc95faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc96faOaAfgORbbalRbvgAcl4gCaCcsSgCE86bbaoc97faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc98faOaAfgORbbalRbogAcl4gCaCcsSgCE86bbaoc99faOaCfgORbbaAcsGgAaAcsSgAE86bbaoc9:faOaAfgORbbalRbrglcl4gAaAcsSgAE86bbaocufaOaAfgoRbbalcsGglalcsSglE86bbaoalfhlxekaOal8Pbb83bbaOcwfalcwf8Pbb83bbalczfhlkdnaiam9pmbaiczfhoaral9RcL0mekkaiam6mialTmidnakTmbawaPfRbbhOcbhoazhiinaiawcj;cbfaofRbbgAce4cbaAceG9R7aOfgO86bbaiadfhiaocefgoak9hmbkkazcefhzaPcefgPad6hsalhHaPad9hmexvkkcbhlasceGmdxikalaxad2fhCdnakTmbcbhHcehsawcjdfhminaral9Rax6mialTmdalaxfhlawaHfRbbhOcbhoamhiinaiawcj;cbfaofRbbgAce4cbaAceG9R7aOfgO86bbaiadfhiaocefgoak9hmbkamcefhmaHcefgHad6hsaHad9hmbkaChlxikcbhocehsinaral9Rax6mdalTmealaxfhlaocefgoad6hsadao9hmbkaChlxdkcbhlasceGTmekc9:hoxikabaqad2fawcjdfakad2z1jjjb8Aawawcjdfakcufad2fadz1jjjb8Aakaqfhqalmbkc9:hoxekcbc99aral9Radcaadca0ESEhokavcj;ebf8Kjjjjbaok;yzeHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecjez:jjjjb8AavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhodnaeTmbcmcsaDceSEhkcbhxcbhmcbhDcbhicbhlindnaoaq9nmbc9:hoxikdndnawRbbgrc;Ve0mbavc;abfalarcl4cu7fcsGcitfgPydlhsaPydbhzdnarcsGgPak9pmbavaiarcu7fcsGcdtfydbaxaPEhraPThPdndnadcd9hmbabaDcetfgHaz87ebaHcdfas87ebaHclfar87ebxekabaDcdtfgHazBdbaHclfasBdbaHcwfarBdbkaxaPfhxavc;abfalcitfgHarBdbaHasBdlavaicdtfarBdbavc;abfalcefcsGglcitfgHazBdbaHarBdlaiaPfhialcefhlxdkdndnaPcsSmbamaPfaPc987fcefhmxekaocefhrao8SbbgPcFeGhHdndnaPcu9mmbarhoxekaocvfhoaHcFbGhHcrhPdninar8SbbgOcFbGaPtaHVhHaOcu9kmearcefhraPcrfgPc8J9hmbxdkkarcefhokaHce4cbaHceG9R7amfhmkdndnadcd9hmbabaDcetfgraz87ebarcdfas87ebarclfam87ebxekabaDcdtfgrazBdbarclfasBdbarcwfamBdbkavc;abfalcitfgramBdbarasBdlavaicdtfamBdbavc;abfalcefcsGglcitfgrazBdbaramBdlaicefhialcefhlxekdnarcpe0mbaxcefgOavaiaqarcsGfRbbgPcl49RcsGcdtfydbaPcz6gHEhravaiaP9RcsGcdtfydbaOaHfgsaPcsGgOEhPaOThOdndnadcd9hmbabaDcetfgzax87ebazcdfar87ebazclfaP87ebxekabaDcdtfgzaxBdbazclfarBdbazcwfaPBdbkavaicdtfaxBdbavc;abfalcitfgzarBdbazaxBdlavaicefgicsGcdtfarBdbavc;abfalcefcsGcitfgzaPBdbazarBdlavaiaHfcsGgicdtfaPBdbavc;abfalcdfcsGglcitfgraxBdbaraPBdlalcefhlaiaOfhiasaOfhxxekaxcbaoRbbgzEgAarc;:eSgrfhsazcsGhCazcl4hXdndnazcs0mbascefhOxekashOavaiaX9RcsGcdtfydbhskdndnaCmbaOcefhxxekaOhxavaiaz9RcsGcdtfydbhOkdndnarTmbaocefhrxekaocdfhrao8SbegHcFeGhPdnaHcu9kmbaocofhAaPcFbGhPcrhodninar8SbbgHcFbGaotaPVhPaHcu9kmearcefhraocrfgoc8J9hmbkaAhrxekarcefhrkaPce4cbaPceG9R7amfgmhAkdndnaXcsSmbarhPxekarcefhPar8SbbgocFeGhHdnaocu9kmbarcvfhsaHcFbGhHcrhodninaP8SbbgrcFbGaotaHVhHarcu9kmeaPcefhPaocrfgoc8J9hmbkashPxekaPcefhPkaHce4cbaHceG9R7amfgmhskdndnaCcsSmbaPhoxekaPcefhoaP8SbbgrcFeGhHdnarcu9kmbaPcvfhOaHcFbGhHcrhrdninao8SbbgPcFbGartaHVhHaPcu9kmeaocefhoarcrfgrc8J9hmbkaOhoxekaocefhokaHce4cbaHceG9R7amfgmhOkdndnadcd9hmbabaDcetfgraA87ebarcdfas87ebarclfaO87ebxekabaDcdtfgraABdbarclfasBdbarcwfaOBdbkavc;abfalcitfgrasBdbaraABdlavaicdtfaABdbavc;abfalcefcsGcitfgraOBdbarasBdlavaicefgicsGcdtfasBdbavc;abfalcdfcsGcitfgraABdbaraOBdlavaiazcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhialcifhlkawcefhwalcsGhlaicsGhiaDcifgDae6mbkkcbc99aoaqSEhokavc;aef8Kjjjjbaok:llevu8Jjjjjbcz9Rhvc9:hodnaecvfal0mbcuhoaiRbbc;:eGc;qe9hmbav9cb83iwaicefhraialfc98fhwdnaeTmbdnadcdSmbcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcdtfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfglBdbaoalBdbaDcefgDae9hmbxdkkcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcetfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfgl87ebaoalBdbaDcefgDae9hmbkkcbc99arawSEhokaok:Lvoeue99dud99eud99dndnadcl9hmbaeTmeindndnabcdfgd8Sbb:Yab8Sbbgi:Ygl:l:tabcefgv8Sbbgo:Ygr:l:tgwJbb;:9cawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai86bbdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad86bbdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad86bbabclfhbaecufgembxdkkaeTmbindndnabclfgd8Ueb:Yab8Uebgi:Ygl:l:tabcdfgv8Uebgo:Ygr:l:tgwJb;:FSawawNJbbbbawawJbbbb9GgDEgq:mgkaqaicb9iEalMgwawNakaqaocb9iEarMgqaqNMM:r:vglNJbbbZJbbb:;aDEMgr:lJbbb9p9DTmbar:Ohixekcjjjj94hikadai87ebdndnaqalNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:Ohdxekcjjjj94hdkavad87ebdndnawalNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohdxekcjjjj94hdkabad87ebabcwfhbaecufgembkkk;siliui99iue99dnaeTmbcbhiabhlindndnJ;Zl81Zalcof8UebgvciV:Y:vgoal8Ueb:YNgrJb;:FSNJbbbZJbbb:;arJbbbb9GEMgw:lJbbb9p9DTmbaw:OhDxekcjjjj94hDkalclf8Uebhqalcdf8UebhkabavcefciGaiVcetfaD87ebdndnaoak:YNgwJb;:FSNJbbbZJbbb:;awJbbbb9GEMgx:lJbbb9p9DTmbax:Ohkxekcjjjj94hkkabavcdfciGaiVcetfak87ebdndnaoaq:YNgoJb;:FSNJbbbZJbbb:;aoJbbbb9GEMgx:lJbbb9p9DTmbax:Ohqxekcjjjj94hqkabavcufciGaiVcetfaq87ebdndnJbbjZararN:tawawN:taoaoN:tgrJbbbbarJbbbb9GE:rJb;:FSNJbbbZMgr:lJbbb9p9DTmbar:Ohqxekcjjjj94hqkabavciGaiVcetfaq87ebalcwfhlaiclfhiaecufgembkkk9mbdnadcd4ae2geTmbinababydbgdcwtcw91:Yadce91cjjj;8ifcjjj98G::NUdbabclfhbaecufgembkkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;LeeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiclfaeclfydbBdbaicwfaecwfydbBdbaicxfaecxfydbBdbaiczfhiaeczfheadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk;aeedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdbaicxfalBdbaicwfalBdbaiclfalBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabkkkebcjwklz9Kbb`,t=`b9H79TebbbeKl9Gbb9Gvuuuuueu9Giuuub9Geueuikqbbebeedddilve9Weeeviebeoweuec:q;Aekr;leDo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9F9KW9J9V9KW9wWVtW949c919M9MWVbdY9TW79O9V9Wt9F9KW9J9V9KW69U9KW949c919M9MWVblE9TW79O9V9Wt9F9KW9J9V9KW69U9KW949tWG91W9U9JWbvL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9p9JtboK9TW79O9V9Wt9F9KW9J9V9KWS9P2tWV9r919HtbrL9TW79O9V9Wt9F9KW9J9V9KWS9P2tWVT949Wbwl79IV9RbDq;t9tqlbzik9:evu8Jjjjjbcz9Rhbcbheincbhdcbhiinabcwfadfaicjuaead4ceGglE86bbaialfhiadcefgdcw9hmbkaec:q:yjjbfai86bbaecitc:q1jjbfab8Piw83ibaecefgecjd9hmbkk;h8JlHud97euo978Jjjjjbcj;kb9Rgv8Kjjjjbc9:hodnadcefal0mbcuhoaiRbbc:Ge9hmbavaialfgrad9Rad;8qbbcj;abad9UhoaicefhldnadTmbaoc;WFbGgocjdaocjd6EhwcbhDinaDae9pmeawaeaD9RaDawfae6Egqcsfgoc9WGgkci2hxakcethmaocl4cifcd4hPabaDad2fhscbhzdnincehHalhOcbhAdninaraO9RaP6miavcj;cbfaAak2fhCaOaPfhlcbhidnakc;ab6mbaral9Rc;Gb6mbcbhoinaCaofhidndndndndnaOaoco4fRbbgXciGPlbedibkaipxbbbbbbbbbbbbbbbbpklbxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklbalczfhlkdndndndndnaXcd4ciGPlbedibkaipxbbbbbbbbbbbbbbbbpklzxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklzalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklzalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklzalczfhlkdndndndndnaXcl4ciGPlbedibkaipxbbbbbbbbbbbbbbbbpklaxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklaalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklaalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaialpbbbpklaalczfhlkdndndndndnaXco4Plbedibkaipxbbbbbbbbbbbbbbbbpkl8WxikaialpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibaXc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spkl8WalclfaYpQbfaXc:q:yjjbfRbbfhlxdkaialpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibaXc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgXcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spkl8WalcwfaYpQbfaXc:q:yjjbfRbbfhlxekaialpbbbpkl8Walczfhlkaoc;abfhiaocjefak0meaihoaral9Rc;Fb0mbkkdndnaiak9pmbaici4hoinaral9RcK6mdaCaifhXdndndndndnaOaico4fRbbaocoG4ciGPlbedibkaXpxbbbbbbbbbbbbbbbbpklbxikaXalpbblalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLgQcdp:meaQpmbzeHdOiAlCvXoQrLpxiiiiiiiiiiiiiiiip9ogLpxiiiiiiiiiiiiiiiip8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalclfaYpQbfaKc:q:yjjbfRbbfhlxdkaXalpbbwalpbbbgQclp:meaQpmbzeHdOiAlCvXoQrLpxssssssssssssssssp9ogLpxssssssssssssssssp8JgQp5b9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibaKc:q:yjjbfpbbbgYaYpmbbbbbbbbbbbbbbbbaQp5e9cjF;8;4;W;G;ab9:9cU1:NgKcitc:q1jjbfpbibp9UpmbedilvorzHOACXQLpPaLaQp9spklbalcwfaYpQbfaKc:q:yjjbfRbbfhlxekaXalpbbbpklbalczfhlkaocdfhoaiczfgiak6mbkkalTmbaAci6hHalhOaAcefgohAaoclSmdxekkcbhlaHceGmdkdnakTmbavcjdfazfhiavazfpbdbhYcbhXinaiavcj;cbfaXfgopblbgLcep9TaLpxeeeeeeeeeeeeeeeegQp9op9Hp9rgLaoakfpblbg8Acep9Ta8AaQp9op9Hp9rg8ApmbzeHdOiAlCvXoQrLgEaoamfpblbg3cep9Ta3aQp9op9Hp9rg3aoaxfpblbg5cep9Ta5aQp9op9Hp9rg5pmbzeHdOiAlCvXoQrLg8EpmbezHdiOAlvCXorQLgQaQpmbedibedibedibediaYp9UgYp9AdbbaiadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfgoaYaEa8EpmwDKYqk8AExm35Ps8E8FgQaQpmbedibedibedibedip9UgYp9AdbbaoadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfgoaYaLa8ApmwKDYq8AkEx3m5P8Es8FgLa3a5pmwKDYq8AkEx3m5P8Es8Fg8ApmbezHdiOAlvCXorQLgQaQpmbedibedibedibedip9UgYp9AdbbaoadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfgoaYaLa8ApmwDKYqk8AExm35Ps8E8FgQaQpmbedibedibedibedip9UgYp9AdbbaoadfgoaYaQaQpmlvorlvorlvorlvorp9UgYp9AdbbaoadfgoaYaQaQpmwDqkwDqkwDqkwDqkp9UgYp9AdbbaoadfgoaYaQaQpmxmPsxmPsxmPsxmPsp9UgYp9AdbbaoadfhiaXczfgXak6mbkkazclfgzad6mbkasavcjdfaqad2;8qbbavavcjdfaqcufad2fad;8qbbaqaDfhDc9:hoalmexikkc9:hoxekcbc99aral9Radcaadca0ESEhokavcj;kbf8Kjjjjbaokwbz:bjjjbk;uzeHu8Jjjjjbc;ae9Rgv8Kjjjjbc9:hodnaeci9UgrcHfal0mbcuhoaiRbbgwc;WeGc;Ge9hmbawcsGgDce0mbavc;abfcFecje;8kbavcUf9cu83ibavc8Wf9cu83ibavcyf9cu83ibavcaf9cu83ibavcKf9cu83ibavczf9cu83ibav9cu83iwav9cu83ibaialfc9WfhqaicefgwarfhodnaeTmbcmcsaDceSEhkcbhxcbhmcbhDcbhicbhlindnaoaq9nmbc9:hoxikdndnawRbbgrc;Ve0mbavc;abfalarcl4cu7fcsGcitfgPydlhsaPydbhzdnarcsGgPak9pmbavaiarcu7fcsGcdtfydbaxaPEhraPThPdndnadcd9hmbabaDcetfgHaz87ebaHcdfas87ebaHclfar87ebxekabaDcdtfgHazBdbaHclfasBdbaHcwfarBdbkaxaPfhxavc;abfalcitfgHarBdbaHasBdlavaicdtfarBdbavc;abfalcefcsGglcitfgHazBdbaHarBdlaiaPfhialcefhlxdkdndnaPcsSmbamaPfaPc987fcefhmxekaocefhrao8SbbgPcFeGhHdndnaPcu9mmbarhoxekaocvfhoaHcFbGhHcrhPdninar8SbbgOcFbGaPtaHVhHaOcu9kmearcefhraPcrfgPc8J9hmbxdkkarcefhokaHce4cbaHceG9R7amfhmkdndnadcd9hmbabaDcetfgraz87ebarcdfas87ebarclfam87ebxekabaDcdtfgrazBdbarclfasBdbarcwfamBdbkavc;abfalcitfgramBdbarasBdlavaicdtfamBdbavc;abfalcefcsGglcitfgrazBdbaramBdlaicefhialcefhlxekdnarcpe0mbaxcefgOavaiaqarcsGfRbbgPcl49RcsGcdtfydbaPcz6gHEhravaiaP9RcsGcdtfydbaOaHfgsaPcsGgOEhPaOThOdndnadcd9hmbabaDcetfgzax87ebazcdfar87ebazclfaP87ebxekabaDcdtfgzaxBdbazclfarBdbazcwfaPBdbkavaicdtfaxBdbavc;abfalcitfgzarBdbazaxBdlavaicefgicsGcdtfarBdbavc;abfalcefcsGcitfgzaPBdbazarBdlavaiaHfcsGgicdtfaPBdbavc;abfalcdfcsGglcitfgraxBdbaraPBdlalcefhlaiaOfhiasaOfhxxekaxcbaoRbbgzEgAarc;:eSgrfhsazcsGhCazcl4hXdndnazcs0mbascefhOxekashOavaiaX9RcsGcdtfydbhskdndnaCmbaOcefhxxekaOhxavaiaz9RcsGcdtfydbhOkdndnarTmbaocefhrxekaocdfhrao8SbegHcFeGhPdnaHcu9kmbaocofhAaPcFbGhPcrhodninar8SbbgHcFbGaotaPVhPaHcu9kmearcefhraocrfgoc8J9hmbkaAhrxekarcefhrkaPce4cbaPceG9R7amfgmhAkdndnaXcsSmbarhPxekarcefhPar8SbbgocFeGhHdnaocu9kmbarcvfhsaHcFbGhHcrhodninaP8SbbgrcFbGaotaHVhHarcu9kmeaPcefhPaocrfgoc8J9hmbkashPxekaPcefhPkaHce4cbaHceG9R7amfgmhskdndnaCcsSmbaPhoxekaPcefhoaP8SbbgrcFeGhHdnarcu9kmbaPcvfhOaHcFbGhHcrhrdninao8SbbgPcFbGartaHVhHaPcu9kmeaocefhoarcrfgrc8J9hmbkaOhoxekaocefhokaHce4cbaHceG9R7amfgmhOkdndnadcd9hmbabaDcetfgraA87ebarcdfas87ebarclfaO87ebxekabaDcdtfgraABdbarclfasBdbarcwfaOBdbkavc;abfalcitfgrasBdbaraABdlavaicdtfaABdbavc;abfalcefcsGcitfgraOBdbarasBdlavaicefgicsGcdtfasBdbavc;abfalcdfcsGcitfgraABdbaraOBdlavaiazcz6aXcsSVfgicsGcdtfaOBdbaiaCTaCcsSVfhialcifhlkawcefhwalcsGhlaicsGhiaDcifgDae6mbkkcbc99aoaqSEhokavc;aef8Kjjjjbaok:llevu8Jjjjjbcz9Rhvc9:hodnaecvfal0mbcuhoaiRbbc;:eGc;qe9hmbav9cb83iwaicefhraialfc98fhwdnaeTmbdnadcdSmbcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcdtfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfglBdbaoalBdbaDcefgDae9hmbxdkkcbhDindnaraw6mbc9:skarcefhoar8SbbglcFeGhidndnalcu9mmbaohrxekarcvfhraicFbGhicrhldninao8SbbgdcFbGaltaiVhiadcu9kmeaocefhoalcrfglc8J9hmbxdkkaocefhrkabaDcetfaicd4cbaice4ceG9R7avcwfaiceGcdtVgoydbfgl87ebaoalBdbaDcefgDae9hmbkkcbc99arawSEhokaok:EPliuo97eue978Jjjjjbca9Rhidndnadcl9hmbdnaec98GglTmbcbhvabhdinadadpbbbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpkbbadczfhdavclfgval6mbkkalae9pmeaiaeciGgvcdtgdVcbczad9R;8kbaiabalcdtfglad;8qbbdnavTmbaiaipblbgocKp:RecKp:Sep;6egraocwp:RecKp:Sep;6earp;Geaoczp:RecKp:Sep;6egwp;Gep;Kep;LegDpxbbbbbbbbbbbbbbbbp:2egqarpxbbbjbbbjbbbjbbbjgkp9op9rp;Kegrpxbb;:9cbb;:9cbb;:9cbb;:9cararp;MeaDaDp;Meawaqawakp9op9rp;Kegrarp;Mep;Kep;Kep;Jep;Negwp;Mepxbbn0bbn0bbn0bbn0gqp;KepxFbbbFbbbFbbbFbbbp9oaopxbbbFbbbFbbbFbbbFp9op9qarawp;Meaqp;Kecwp:RepxbFbbbFbbbFbbbFbbp9op9qaDawp;Meaqp;Keczp:RepxbbFbbbFbbbFbbbFbp9op9qpklbkalaiad;8qbbskdnaec98GgxTmbcbhvabhdinadczfglalpbbbgopxbbbbbbFFbbbbbbFFgkp9oadpbbbgDaopmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eaDaopmbediwDqkzHOAKY8AEgoczp:Sep;6egrp;Geaoczp:Reczp:Sep;6egwp;Gep;Kep;Legopxb;:FSb;:FSb;:FSb;:FSawaopxbbbbbbbbbbbbbbbbp:2egqawpxbbbjbbbjbbbjbbbjgmp9op9rp;Kegwawp;Meaoaop;Mearaqaramp9op9rp;Kegoaop;Mep;Kep;Kep;Jep;Negrp;Mepxbbn0bbn0bbn0bbn0gqp;Keczp:Reawarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9op9qgwaoarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogopmwDKYqk8AExm35Ps8E8Fp9qpkbbadaDakp9oawaopmbezHdiOAlvCXorQLp9qpkbbadcafhdavclfgvax6mbkkaxae9pmbaiaeciGgvcitgdfcbcaad9R;8kbaiabaxcitfglad;8qbbdnavTmbaiaipblzgopxbbbbbbFFbbbbbbFFgkp9oaipblbgDaopmlvorxmPsCXQL358E8FpxFubbFubbFubbFubbp9op;6eaDaopmbediwDqkzHOAKY8AEgoczp:Sep;6egrp;Geaoczp:Reczp:Sep;6egwp;Gep;Kep;Legopxb;:FSb;:FSb;:FSb;:FSawaopxbbbbbbbbbbbbbbbbp:2egqawpxbbbjbbbjbbbjbbbjgmp9op9rp;Kegwawp;Meaoaop;Mearaqaramp9op9rp;Kegoaop;Mep;Kep;Kep;Jep;Negrp;Mepxbbn0bbn0bbn0bbn0gqp;Keczp:Reawarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9op9qgwaoarp;Meaqp;KepxFFbbFFbbFFbbFFbbp9ogopmwDKYqk8AExm35Ps8E8Fp9qpklzaiaDakp9oawaopmbezHdiOAlvCXorQLp9qpklbkalaiad;8qbbkk;4wllue97euv978Jjjjjbc8W9Rhidnaec98GglTmbcbhvabhoinaiaopbbbgraoczfgwpbbbgDpmlvorxmPsCXQL358E8Fgqczp:Segkclp:RepklbaopxbbjZbbjZbbjZbbjZpx;Zl81Z;Zl81Z;Zl81Z;Zl81Zakpxibbbibbbibbbibbbp9qp;6ep;NegkaraDpmbediwDqkzHOAKY8AEgrczp:Reczp:Sep;6ep;MegDaDp;Meakarczp:Sep;6ep;Megxaxp;Meakaqczp:Reczp:Sep;6ep;Megqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jepxb;:FSb;:FSb;:FSb;:FSgkp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbgmp9oaxakp;Mearp;Keczp:Rep9qgxaqakp;Mearp;Keczp:ReaDakp;Mearp;Keamp9op9qgkpmbezHdiOAlvCXorQLgrp5baipblbpEb:T:j83ibaocwfarp5eaipblbpEe:T:j83ibawaxakpmwDKYqk8AExm35Ps8E8Fgkp5baipblbpEd:T:j83ibaocKfakp5eaipblbpEi:T:j83ibaocafhoavclfgval6mbkkdnalae9pmbaiaeciGgvcitgofcbcaao9R;8kbaiabalcitfgwao;8qbbdnavTmbaiaipblbgraipblzgDpmlvorxmPsCXQL358E8Fgqczp:Segkclp:RepklaaipxbbjZbbjZbbjZbbjZpx;Zl81Z;Zl81Z;Zl81Z;Zl81Zakpxibbbibbbibbbibbbp9qp;6ep;NegkaraDpmbediwDqkzHOAKY8AEgrczp:Reczp:Sep;6ep;MegDaDp;Meakarczp:Sep;6ep;Megxaxp;Meakaqczp:Reczp:Sep;6ep;Megqaqp;Mep;Kep;Kep;Lepxbbbbbbbbbbbbbbbbp:4ep;Jepxb;:FSb;:FSb;:FSb;:FSgkp;Mepxbbn0bbn0bbn0bbn0grp;KepxFFbbFFbbFFbbFFbbgmp9oaxakp;Mearp;Keczp:Rep9qgxaqakp;Mearp;Keczp:ReaDakp;Mearp;Keamp9op9qgkpmbezHdiOAlvCXorQLgrp5baipblapEb:T:j83ibaiarp5eaipblapEe:T:j83iwaiaxakpmwDKYqk8AExm35Ps8E8Fgkp5baipblapEd:T:j83izaiakp5eaipblapEi:T:j83iKkawaiao;8qbbkk:Pddiue978Jjjjjbc;ab9Rhidnadcd4ae2glc98GgvTmbcbhdabheinaeaepbbbgocwp:Recwp:Sep;6eaocep:SepxbbjZbbjZbbjZbbjZp:UepxbbjFbbjFbbjFbbjFp9op;Mepkbbaeczfheadclfgdav6mbkkdnaval9pmbaialciGgdcdtgeVcbc;abae9R;8kbaiabavcdtfgvae;8qbbdnadTmbaiaipblbgocwp:Recwp:Sep;6eaocep:SepxbbjZbbjZbbjZbbjZp:UepxbbjFbbjFbbjFbbjFp9op;Mepklbkavaiae;8qbbkk9teiucbcbydj1jjbgeabcifc98GfgbBdj1jjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikkkebcjwklz9Tbb`,n=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]),r=new Uint8Array([32,0,65,2,1,106,34,33,3,128,11,4,13,64,6,253,10,7,15,116,127,5,8,12,40,16,19,54,20,9,27,255,113,17,42,67,24,23,146,148,18,14,22,45,70,69,56,114,101,21,25,63,75,136,108,28,118,29,73,115]);if(typeof WebAssembly!=`object`)return{supported:!1};var i=WebAssembly.validate(n)?t:e,a,o=WebAssembly.instantiate(s(i),{}).then(function(e){a=e.instance,a.exports.__wasm_call_ctors()});function s(e){for(var t=new Uint8Array(e.length),n=0;n<e.length;++n){var i=e.charCodeAt(n);t[n]=i>96?i-97:i>64?i-39:i+4}for(var a=0,n=0;n<e.length;++n)t[a++]=t[n]<60?r[t[n]]:(t[n]-60)*64+t[++n];return t.buffer.slice(0,a)}function c(e,t,n,r,i,o){var s=a.exports.sbrk,c=n+3&-4,l=s(c*r),u=s(i.length),d=new Uint8Array(a.exports.memory.buffer);d.set(i,u);var f=e(l,n,r,u,i.length);if(f==0&&o&&o(l,c,r),t.set(d.subarray(l,l+n*r)),s(l-s(0)),f!=0)throw Error(`Malformed buffer data: `+f)}var l={NONE:``,OCTAHEDRAL:`meshopt_decodeFilterOct`,QUATERNION:`meshopt_decodeFilterQuat`,EXPONENTIAL:`meshopt_decodeFilterExp`},u={ATTRIBUTES:`meshopt_decodeVertexBuffer`,TRIANGLES:`meshopt_decodeIndexBuffer`,INDICES:`meshopt_decodeIndexSequence`},d=[],f=0;function p(e){var t={object:new Worker(e),pending:0,requests:{}};return t.object.onmessage=function(e){var n=e.data;t.pending-=n.count,t.requests[n.id][n.action](n.value),delete t.requests[n.id]},t}function m(e){for(var t=`var instance; var ready = WebAssembly.instantiate(new Uint8Array([`+new Uint8Array(s(i))+`]), {}).then(function(result) { instance = result.instance; instance.exports.__wasm_call_ctors(); });self.onmessage = workerProcess;`+c.toString()+g.toString(),n=new Blob([t],{type:`text/javascript`}),r=URL.createObjectURL(n),a=0;a<e;++a)d[a]=p(r);URL.revokeObjectURL(r)}function h(e,t,n,r,i){for(var a=d[0],o=1;o<d.length;++o)d[o].pending<a.pending&&(a=d[o]);return new Promise(function(o,s){var c=new Uint8Array(n),l=f++;a.pending+=e,a.requests[l]={resolve:o,reject:s},a.object.postMessage({id:l,count:e,size:t,source:c,mode:r,filter:i},[c.buffer])})}function g(e){o.then(function(){var t=e.data;try{var n=new Uint8Array(t.count*t.size);c(a.exports[t.mode],n,t.count,t.size,t.source,a.exports[t.filter]),self.postMessage({id:t.id,count:t.count,action:`resolve`,value:n},[n.buffer])}catch(e){self.postMessage({id:t.id,count:t.count,action:`reject`,value:e})}})}return{ready:o,supported:!0,useWorkers:function(e){m(e)},decodeVertexBuffer:function(e,t,n,r,i){c(a.exports.meshopt_decodeVertexBuffer,e,t,n,r,a.exports[l[i]])},decodeIndexBuffer:function(e,t,n,r){c(a.exports.meshopt_decodeIndexBuffer,e,t,n,r)},decodeIndexSequence:function(e,t,n,r){c(a.exports.meshopt_decodeIndexSequence,e,t,n,r)},decodeGltfBuffer:function(e,t,n,r,i,o){c(a.exports[u[i]],e,t,n,r,a.exports[l[o]])},decodeGltfBufferAsync:function(e,t,n,r,i){return d.length>0?h(e,t,n,u[r],l[i]):o.then(function(){var o=new Uint8Array(e*t);return c(a.exports[u[r]],o,e,t,n,a.exports[l[i]]),o})}}})(),pd={type:`change`},md={type:`start`},hd={type:`end`},gd=new An,_d=new aa,vd=Math.cos(70*Tt.DEG2RAD),yd=new R,bd=2*Math.PI,xd={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Sd=1e-6,Cd=class extends os{constructor(e,t=null){super(e,t),this.state=xd.NONE,this.target=new R,this.cursor=new R,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:`ArrowLeft`,UP:`ArrowUp`,RIGHT:`ArrowRight`,BOTTOM:`ArrowDown`},this.mouseButtons={LEFT:r.ROTATE,MIDDLE:r.DOLLY,RIGHT:r.PAN},this.touches={ONE:i.ROTATE,TWO:i.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new R,this._lastQuaternion=new en,this._lastTargetPosition=new R,this._quat=new en().setFromUnitVectors(e.up,new R(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new Qo,this._sphericalDelta=new Qo,this._scale=1,this._panOffset=new R,this._rotateStart=new L,this._rotateEnd=new L,this._rotateDelta=new L,this._panStart=new L,this._panEnd=new L,this._panDelta=new L,this._dollyStart=new L,this._dollyEnd=new L,this._dollyDelta=new L,this._dollyDirection=new R,this._mouse=new L,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Td.bind(this),this._onPointerDown=wd.bind(this),this._onPointerUp=Ed.bind(this),this._onContextMenu=Nd.bind(this),this._onMouseWheel=kd.bind(this),this._onKeyDown=Ad.bind(this),this._onTouchStart=jd.bind(this),this._onTouchMove=Md.bind(this),this._onMouseDown=Dd.bind(this),this._onMouseMove=Od.bind(this),this._interceptControlDown=Pd.bind(this),this._interceptControlUp=Fd.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}connect(e){super.connect(e),this.domElement.addEventListener(`pointerdown`,this._onPointerDown),this.domElement.addEventListener(`pointercancel`,this._onPointerUp),this.domElement.addEventListener(`contextmenu`,this._onContextMenu),this.domElement.addEventListener(`wheel`,this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener(`keydown`,this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction=`none`}disconnect(){this.domElement.removeEventListener(`pointerdown`,this._onPointerDown),this.domElement.removeEventListener(`pointermove`,this._onPointerMove),this.domElement.removeEventListener(`pointerup`,this._onPointerUp),this.domElement.removeEventListener(`pointercancel`,this._onPointerUp),this.domElement.removeEventListener(`wheel`,this._onMouseWheel),this.domElement.removeEventListener(`contextmenu`,this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener(`keydown`,this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction=`auto`}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener(`keydown`,this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener(`keydown`,this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(pd),this.update(),this.state=xd.NONE}update(e=null){let t=this.object.position;yd.copy(t).sub(this.target),yd.applyQuaternion(this._quat),this._spherical.setFromVector3(yd),this.autoRotate&&this.state===xd.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,r=this.maxAzimuthAngle;isFinite(n)&&isFinite(r)&&(n<-Math.PI?n+=bd:n>Math.PI&&(n-=bd),r<-Math.PI?r+=bd:r>Math.PI&&(r-=bd),n<=r?this._spherical.theta=Math.max(n,Math.min(r,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+r)/2?Math.max(n,this._spherical.theta):Math.min(r,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let i=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{let e=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),i=e!=this._spherical.radius}if(yd.setFromSpherical(this._spherical),yd.applyQuaternion(this._quatInverse),t.copy(this.target).add(yd),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let e=null;if(this.object.isPerspectiveCamera){let t=yd.length();e=this._clampDistance(t*this._scale);let n=t-e;this.object.position.addScaledVector(this._dollyDirection,n),this.object.updateMatrixWorld(),i=!!n}else if(this.object.isOrthographicCamera){let t=new R(this._mouse.x,this._mouse.y,0);t.unproject(this.object);let n=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),i=n!==this.object.zoom;let r=new R(this._mouse.x,this._mouse.y,0);r.unproject(this.object),this.object.position.sub(r).add(t),this.object.updateMatrixWorld(),e=yd.length()}else console.warn(`WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.`),this.zoomToCursor=!1;e!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(e).add(this.object.position):(gd.origin.copy(this.object.position),gd.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(gd.direction))<vd?this.object.lookAt(this.target):(_d.setFromNormalAndCoplanarPoint(this.object.up,this.target),gd.intersectPlane(_d,this.target))))}else if(this.object.isOrthographicCamera){let e=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),e!==this.object.zoom&&(this.object.updateProjectionMatrix(),i=!0)}return this._scale=1,this._performCursorZoom=!1,i||this._lastPosition.distanceToSquared(this.object.position)>Sd||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Sd||this._lastTargetPosition.distanceToSquared(this.target)>Sd?(this.dispatchEvent(pd),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e===null?bd/60/60*this.autoRotateSpeed:bd/60*this.autoRotateSpeed*e}_getZoomScale(e){let t=Math.abs(e*.01);return .95**(this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){yd.setFromMatrixColumn(t,0),yd.multiplyScalar(-e),this._panOffset.add(yd)}_panUp(e,t){this.screenSpacePanning===!0?yd.setFromMatrixColumn(t,1):(yd.setFromMatrixColumn(t,0),yd.crossVectors(this.object.up,yd)),yd.multiplyScalar(e),this._panOffset.add(yd)}_pan(e,t){let n=this.domElement;if(this.object.isPerspectiveCamera){let r=this.object.position;yd.copy(r).sub(this.target);let i=yd.length();i*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*i/n.clientHeight,this.object.matrix),this._panUp(2*t*i/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn(`WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.`),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn(`WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.`),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn(`WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.`),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;let n=this.domElement.getBoundingClientRect(),r=e-n.left,i=t-n.top,a=n.width,o=n.height;this._mouse.x=r/a*2-1,this._mouse.y=-(i/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(bd*this._rotateDelta.x/t.clientHeight),this._rotateUp(bd*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(bd*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-bd*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(bd*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-bd*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._rotateStart.set(n,r)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._panStart.set(n,r)}}_handleTouchStartDolly(e){let t=this._getSecondPointerPosition(e),n=e.pageX-t.x,r=e.pageY-t.y,i=Math.sqrt(n*n+r*r);this._dollyStart.set(0,i)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._rotateEnd.set(n,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(bd*this._rotateDelta.x/t.clientHeight),this._rotateUp(bd*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._panEnd.set(n,r)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){let t=this._getSecondPointerPosition(e),n=e.pageX-t.x,r=e.pageY-t.y,i=Math.sqrt(n*n+r*r);this._dollyEnd.set(0,i),this._dollyDelta.set(0,(this._dollyEnd.y/this._dollyStart.y)**+this.zoomSpeed),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);let a=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.5;this._updateZoomParameters(a,o)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new L,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){let t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){let t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}};function wd(e){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.addEventListener(`pointermove`,this._onPointerMove),this.domElement.addEventListener(`pointerup`,this._onPointerUp)),!this._isTrackingPointer(e)&&(this._addPointer(e),e.pointerType===`touch`?this._onTouchStart(e):this._onMouseDown(e)))}function Td(e){this.enabled!==!1&&(e.pointerType===`touch`?this._onTouchMove(e):this._onMouseMove(e))}function Ed(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.removeEventListener(`pointermove`,this._onPointerMove),this.domElement.removeEventListener(`pointerup`,this._onPointerUp),this.dispatchEvent(hd),this.state=xd.NONE;break;case 1:let t=this._pointers[0],n=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:n.x,pageY:n.y});break}}function Dd(e){let t;switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case r.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(e),this.state=xd.DOLLY;break;case r.ROTATE:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=xd.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=xd.ROTATE}break;case r.PAN:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=xd.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=xd.PAN}break;default:this.state=xd.NONE}this.state!==xd.NONE&&this.dispatchEvent(md)}function Od(e){switch(this.state){case xd.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(e);break;case xd.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(e);break;case xd.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(e);break}}function kd(e){this.enabled===!1||this.enableZoom===!1||this.state!==xd.NONE||(e.preventDefault(),this.dispatchEvent(md),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(hd))}function Ad(e){this.enabled!==!1&&this._handleKeyDown(e)}function jd(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case i.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(e),this.state=xd.TOUCH_ROTATE;break;case i.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(e),this.state=xd.TOUCH_PAN;break;default:this.state=xd.NONE}break;case 2:switch(this.touches.TWO){case i.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(e),this.state=xd.TOUCH_DOLLY_PAN;break;case i.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(e),this.state=xd.TOUCH_DOLLY_ROTATE;break;default:this.state=xd.NONE}break;default:this.state=xd.NONE}this.state!==xd.NONE&&this.dispatchEvent(md)}function Md(e){switch(this._trackPointer(e),this.state){case xd.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(e),this.update();break;case xd.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(e),this.update();break;case xd.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(e),this.update();break;case xd.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=xd.NONE}}function Nd(e){this.enabled!==!1&&e.preventDefault()}function Pd(e){e.key===`Control`&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener(`keyup`,this._interceptControlUp,{passive:!0,capture:!0}))}function Fd(e){e.key===`Control`&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener(`keyup`,this._interceptControlUp,{passive:!0,capture:!0}))}var Id=class extends Oi{constructor(){super();let e=new oi;e.deleteAttribute(`uv`);let t=new Fa({side:1}),n=new Fa,r=new Oo(16777215,900,28,2);r.position.set(.418,16.199,.3),this.add(r);let i=new ri(e,t);i.position.set(-.757,13.219,.717),i.scale.set(31.713,28.305,28.591),this.add(i);let a=new ta(e,n,6),o=new rr;o.position.set(-10.906,2.009,1.846),o.rotation.set(0,-.195,0),o.scale.set(2.328,7.905,4.651),o.updateMatrix(),a.setMatrixAt(0,o.matrix),o.position.set(-5.607,-.754,-.758),o.rotation.set(0,.994,0),o.scale.set(1.97,1.534,3.955),o.updateMatrix(),a.setMatrixAt(1,o.matrix),o.position.set(6.167,.857,7.803),o.rotation.set(0,.561,0),o.scale.set(3.927,6.285,3.687),o.updateMatrix(),a.setMatrixAt(2,o.matrix),o.position.set(-2.017,.018,6.124),o.rotation.set(0,.333,0),o.scale.set(2.002,4.566,2.064),o.updateMatrix(),a.setMatrixAt(3,o.matrix),o.position.set(2.291,-.756,-2.621),o.rotation.set(0,-.286,0),o.scale.set(1.546,1.552,1.496),o.updateMatrix(),a.setMatrixAt(4,o.matrix),o.position.set(-2.193,-.369,-5.547),o.rotation.set(0,.516,0),o.scale.set(3.875,3.487,2.986),o.updateMatrix(),a.setMatrixAt(5,o.matrix),this.add(a);let s=new ri(e,Ld(50));s.position.set(-16.116,14.37,8.208),s.scale.set(.1,2.428,2.739),this.add(s);let c=new ri(e,Ld(50));c.position.set(-16.109,18.021,-8.207),c.scale.set(.1,2.425,2.751),this.add(c);let l=new ri(e,Ld(17));l.position.set(14.904,12.198,-1.832),l.scale.set(.15,4.265,6.331),this.add(l);let u=new ri(e,Ld(43));u.position.set(-.462,8.89,14.52),u.scale.set(4.38,5.441,.088),this.add(u);let d=new ri(e,Ld(20));d.position.set(3.235,11.486,-12.541),d.scale.set(2.5,2,.1),this.add(d);let f=new ri(e,Ld(100));f.position.set(0,20,0),f.scale.set(1,.1,1),this.add(f)}dispose(){let e=new Set;this.traverse(t=>{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(let t of e)t.dispose()}};function Ld(e){let t=new Tr;return t.color.setScalar(e),t}function Rd(e){if(e&&!(typeof window>`u`)){var t=document.createElement(`style`);return t.setAttribute(`type`,`text/css`),t.innerHTML=e,document.head.appendChild(t),e}}function zd(e,t){var n=e.__state.conversionName.toString(),r=Math.round(e.r),i=Math.round(e.g),a=Math.round(e.b),o=e.a,s=Math.round(e.h),c=e.s.toFixed(1),l=e.v.toFixed(1);if(t||n===`THREE_CHAR_HEX`||n===`SIX_CHAR_HEX`){for(var u=e.hex.toString(16);u.length<6;)u=`0`+u;return`#`+u}else if(n===`CSS_RGB`)return`rgb(`+r+`,`+i+`,`+a+`)`;else if(n===`CSS_RGBA`)return`rgba(`+r+`,`+i+`,`+a+`,`+o+`)`;else if(n===`HEX`)return`0x`+e.hex.toString(16);else if(n===`RGB_ARRAY`)return`[`+r+`,`+i+`,`+a+`]`;else if(n===`RGBA_ARRAY`)return`[`+r+`,`+i+`,`+a+`,`+o+`]`;else if(n===`RGB_OBJ`)return`{r:`+r+`,g:`+i+`,b:`+a+`}`;else if(n===`RGBA_OBJ`)return`{r:`+r+`,g:`+i+`,b:`+a+`,a:`+o+`}`;else if(n===`HSV_OBJ`)return`{h:`+s+`,s:`+c+`,v:`+l+`}`;else if(n===`HSVA_OBJ`)return`{h:`+s+`,s:`+c+`,v:`+l+`,a:`+o+`}`;return`unknown format`}var Bd=Array.prototype.forEach,Vd=Array.prototype.slice,U={BREAK:{},extend:function(e){return this.each(Vd.call(arguments,1),function(t){(this.isObject(t)?Object.keys(t):[]).forEach(function(n){this.isUndefined(t[n])||(e[n]=t[n])}.bind(this))},this),e},defaults:function(e){return this.each(Vd.call(arguments,1),function(t){(this.isObject(t)?Object.keys(t):[]).forEach(function(n){this.isUndefined(e[n])&&(e[n]=t[n])}.bind(this))},this),e},compose:function(){var e=Vd.call(arguments);return function(){for(var t=Vd.call(arguments),n=e.length-1;n>=0;n--)t=[e[n].apply(this,t)];return t[0]}},each:function(e,t,n){if(e){if(Bd&&e.forEach&&e.forEach===Bd)e.forEach(t,n);else if(e.length===e.length+0){var r=void 0,i=void 0;for(r=0,i=e.length;r<i;r++)if(r in e&&t.call(n,e[r],r)===this.BREAK)return}else for(var a in e)if(t.call(n,e[a],a)===this.BREAK)return}},defer:function(e){setTimeout(e,0)},debounce:function(e,t,n){var r=void 0;return function(){var i=this,a=arguments;function o(){r=null,n||e.apply(i,a)}var s=n||!r;clearTimeout(r),r=setTimeout(o,t),s&&e.apply(i,a)}},toArray:function(e){return e.toArray?e.toArray():Vd.call(e)},isUndefined:function(e){return e===void 0},isNull:function(e){return e===null},isNaN:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(e){return isNaN(e)}),isArray:Array.isArray||function(e){return e.constructor===Array},isObject:function(e){return e===Object(e)},isNumber:function(e){return e===e+0},isString:function(e){return e===e+``},isBoolean:function(e){return e===!1||e===!0},isFunction:function(e){return e instanceof Function}},Hd=[{litmus:U.isString,conversions:{THREE_CHAR_HEX:{read:function(e){var t=e.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);return t===null?!1:{space:`HEX`,hex:parseInt(`0x`+t[1].toString()+t[1].toString()+t[2].toString()+t[2].toString()+t[3].toString()+t[3].toString(),0)}},write:zd},SIX_CHAR_HEX:{read:function(e){var t=e.match(/^#([A-F0-9]{6})$/i);return t===null?!1:{space:`HEX`,hex:parseInt(`0x`+t[1].toString(),0)}},write:zd},CSS_RGB:{read:function(e){var t=e.match(/^rgb\(\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*\)/);return t===null?!1:{space:`RGB`,r:parseFloat(t[1]),g:parseFloat(t[2]),b:parseFloat(t[3])}},write:zd},CSS_RGBA:{read:function(e){var t=e.match(/^rgba\(\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*,\s*(\S+)\s*\)/);return t===null?!1:{space:`RGB`,r:parseFloat(t[1]),g:parseFloat(t[2]),b:parseFloat(t[3]),a:parseFloat(t[4])}},write:zd}}},{litmus:U.isNumber,conversions:{HEX:{read:function(e){return{space:`HEX`,hex:e,conversionName:`HEX`}},write:function(e){return e.hex}}}},{litmus:U.isArray,conversions:{RGB_ARRAY:{read:function(e){return e.length===3?{space:`RGB`,r:e[0],g:e[1],b:e[2]}:!1},write:function(e){return[e.r,e.g,e.b]}},RGBA_ARRAY:{read:function(e){return e.length===4?{space:`RGB`,r:e[0],g:e[1],b:e[2],a:e[3]}:!1},write:function(e){return[e.r,e.g,e.b,e.a]}}}},{litmus:U.isObject,conversions:{RGBA_OBJ:{read:function(e){return U.isNumber(e.r)&&U.isNumber(e.g)&&U.isNumber(e.b)&&U.isNumber(e.a)?{space:`RGB`,r:e.r,g:e.g,b:e.b,a:e.a}:!1},write:function(e){return{r:e.r,g:e.g,b:e.b,a:e.a}}},RGB_OBJ:{read:function(e){return U.isNumber(e.r)&&U.isNumber(e.g)&&U.isNumber(e.b)?{space:`RGB`,r:e.r,g:e.g,b:e.b}:!1},write:function(e){return{r:e.r,g:e.g,b:e.b}}},HSVA_OBJ:{read:function(e){return U.isNumber(e.h)&&U.isNumber(e.s)&&U.isNumber(e.v)&&U.isNumber(e.a)?{space:`HSV`,h:e.h,s:e.s,v:e.v,a:e.a}:!1},write:function(e){return{h:e.h,s:e.s,v:e.v,a:e.a}}},HSV_OBJ:{read:function(e){return U.isNumber(e.h)&&U.isNumber(e.s)&&U.isNumber(e.v)?{space:`HSV`,h:e.h,s:e.s,v:e.v}:!1},write:function(e){return{h:e.h,s:e.s,v:e.v}}}}}],Ud=void 0,Wd=void 0,Gd=function(){Wd=!1;var e=arguments.length>1?U.toArray(arguments):arguments[0];return U.each(Hd,function(t){if(t.litmus(e))return U.each(t.conversions,function(t,n){if(Ud=t.read(e),Wd===!1&&Ud!==!1)return Wd=Ud,Ud.conversionName=n,Ud.conversion=t,U.BREAK}),U.BREAK}),Wd},Kd=void 0,qd={hsv_to_rgb:function(e,t,n){var r=Math.floor(e/60)%6,i=e/60-Math.floor(e/60),a=n*(1-t),o=n*(1-i*t),s=n*(1-(1-i)*t),c=[[n,s,a],[o,n,a],[a,n,s],[a,o,n],[s,a,n],[n,a,o]][r];return{r:c[0]*255,g:c[1]*255,b:c[2]*255}},rgb_to_hsv:function(e,t,n){var r=Math.min(e,t,n),i=Math.max(e,t,n),a=i-r,o=void 0,s=void 0;if(i!==0)s=a/i;else return{h:NaN,s:0,v:0};return o=e===i?(t-n)/a:t===i?2+(n-e)/a:4+(e-t)/a,o/=6,o<0&&(o+=1),{h:o*360,s,v:i/255}},rgb_to_hex:function(e,t,n){var r=this.hex_with_component(0,2,e);return r=this.hex_with_component(r,1,t),r=this.hex_with_component(r,0,n),r},component_from_hex:function(e,t){return e>>t*8&255},hex_with_component:function(e,t,n){return n<<(Kd=t*8)|e&~(255<<Kd)}},Jd=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},Yd=function(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)},Xd=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),Zd=function e(t,n,r){t===null&&(t=Function.prototype);var i=Object.getOwnPropertyDescriptor(t,n);if(i===void 0){var a=Object.getPrototypeOf(t);return a===null?void 0:e(a,n,r)}else if(`value`in i)return i.value;else{var o=i.get;return o===void 0?void 0:o.call(r)}},Qd=function(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Super expression must either be null or a function, not `+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},$d=function(e,t){if(!e)throw ReferenceError(`this hasn't been initialised - super() hasn't been called`);return t&&(typeof t==`object`||typeof t==`function`)?t:e},ef=function(){function e(){if(Yd(this,e),this.__state=Gd.apply(this,arguments),this.__state===!1)throw Error(`Failed to interpret color arguments`);this.__state.a=this.__state.a||1}return Xd(e,[{key:`toString`,value:function(){return zd(this)}},{key:`toHexString`,value:function(){return zd(this,!0)}},{key:`toOriginal`,value:function(){return this.__state.conversion.write(this)}}]),e}();function tf(e,t,n){Object.defineProperty(e,t,{get:function(){return this.__state.space===`RGB`||ef.recalculateRGB(this,t,n),this.__state[t]},set:function(e){this.__state.space!==`RGB`&&(ef.recalculateRGB(this,t,n),this.__state.space=`RGB`),this.__state[t]=e}})}function nf(e,t){Object.defineProperty(e,t,{get:function(){return this.__state.space===`HSV`||ef.recalculateHSV(this),this.__state[t]},set:function(e){this.__state.space!==`HSV`&&(ef.recalculateHSV(this),this.__state.space=`HSV`),this.__state[t]=e}})}ef.recalculateRGB=function(e,t,n){if(e.__state.space===`HEX`)e.__state[t]=qd.component_from_hex(e.__state.hex,n);else if(e.__state.space===`HSV`)U.extend(e.__state,qd.hsv_to_rgb(e.__state.h,e.__state.s,e.__state.v));else throw Error(`Corrupted color state`)},ef.recalculateHSV=function(e){var t=qd.rgb_to_hsv(e.r,e.g,e.b);U.extend(e.__state,{s:t.s,v:t.v}),U.isNaN(t.h)?U.isUndefined(e.__state.h)&&(e.__state.h=0):e.__state.h=t.h},ef.COMPONENTS=[`r`,`g`,`b`,`h`,`s`,`v`,`hex`,`a`],tf(ef.prototype,`r`,2),tf(ef.prototype,`g`,1),tf(ef.prototype,`b`,0),nf(ef.prototype,`h`),nf(ef.prototype,`s`),nf(ef.prototype,`v`),Object.defineProperty(ef.prototype,`a`,{get:function(){return this.__state.a},set:function(e){this.__state.a=e}}),Object.defineProperty(ef.prototype,`hex`,{get:function(){return this.__state.space!==`HEX`&&(this.__state.hex=qd.rgb_to_hex(this.r,this.g,this.b),this.__state.space=`HEX`),this.__state.hex},set:function(e){this.__state.space=`HEX`,this.__state.hex=e}});var rf=function(){function e(t,n){Yd(this,e),this.initialValue=t[n],this.domElement=document.createElement(`div`),this.object=t,this.property=n,this.__onChange=void 0,this.__onFinishChange=void 0}return Xd(e,[{key:`onChange`,value:function(e){return this.__onChange=e,this}},{key:`onFinishChange`,value:function(e){return this.__onFinishChange=e,this}},{key:`setValue`,value:function(e){return this.object[this.property]=e,this.__onChange&&this.__onChange.call(this,e),this.updateDisplay(),this}},{key:`getValue`,value:function(){return this.object[this.property]}},{key:`updateDisplay`,value:function(){return this}},{key:`isModified`,value:function(){return this.initialValue!==this.getValue()}}]),e}(),af={HTMLEvents:[`change`],MouseEvents:[`click`,`mousemove`,`mousedown`,`mouseup`,`mouseover`],KeyboardEvents:[`keydown`]},of={};U.each(af,function(e,t){U.each(e,function(e){of[e]=t})});var sf=/(\d+(\.\d+)?)px/;function cf(e){if(e===`0`||U.isUndefined(e))return 0;var t=e.match(sf);return U.isNull(t)?0:parseFloat(t[1])}var W={makeSelectable:function(e,t){e===void 0||e.style===void 0||(e.onselectstart=t?function(){return!1}:function(){},e.style.MozUserSelect=t?`auto`:`none`,e.style.KhtmlUserSelect=t?`auto`:`none`,e.unselectable=t?`on`:`off`)},makeFullscreen:function(e,t,n){var r=n,i=t;U.isUndefined(i)&&(i=!0),U.isUndefined(r)&&(r=!0),e.style.position=`absolute`,i&&(e.style.left=0,e.style.right=0),r&&(e.style.top=0,e.style.bottom=0)},fakeEvent:function(e,t,n,r){var i=n||{},a=of[t];if(!a)throw Error(`Event type `+t+` not supported.`);var o=document.createEvent(a);switch(a){case`MouseEvents`:var s=i.x||i.clientX||0,c=i.y||i.clientY||0;o.initMouseEvent(t,i.bubbles||!1,i.cancelable||!0,window,i.clickCount||1,0,0,s,c,!1,!1,!1,!1,0,null);break;case`KeyboardEvents`:var l=o.initKeyboardEvent||o.initKeyEvent;U.defaults(i,{cancelable:!0,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,keyCode:void 0,charCode:void 0}),l(t,i.bubbles||!1,i.cancelable,window,i.ctrlKey,i.altKey,i.shiftKey,i.metaKey,i.keyCode,i.charCode);break;default:o.initEvent(t,i.bubbles||!1,i.cancelable||!0);break}U.defaults(o,r),e.dispatchEvent(o)},bind:function(e,t,n,r){var i=r||!1;return e.addEventListener?e.addEventListener(t,n,i):e.attachEvent&&e.attachEvent(`on`+t,n),W},unbind:function(e,t,n,r){var i=r||!1;return e.removeEventListener?e.removeEventListener(t,n,i):e.detachEvent&&e.detachEvent(`on`+t,n),W},addClass:function(e,t){if(e.className===void 0)e.className=t;else if(e.className!==t){var n=e.className.split(/ +/);n.indexOf(t)===-1&&(n.push(t),e.className=n.join(` `).replace(/^\s+/,``).replace(/\s+$/,``))}return W},removeClass:function(e,t){if(t)if(e.className===t)e.removeAttribute(`class`);else{var n=e.className.split(/ +/),r=n.indexOf(t);r!==-1&&(n.splice(r,1),e.className=n.join(` `))}else e.className=void 0;return W},hasClass:function(e,t){return RegExp(`(?:^|\\s+)`+t+`(?:\\s+|$)`).test(e.className)||!1},getWidth:function(e){var t=getComputedStyle(e);return cf(t[`border-left-width`])+cf(t[`border-right-width`])+cf(t[`padding-left`])+cf(t[`padding-right`])+cf(t.width)},getHeight:function(e){var t=getComputedStyle(e);return cf(t[`border-top-width`])+cf(t[`border-bottom-width`])+cf(t[`padding-top`])+cf(t[`padding-bottom`])+cf(t.height)},getOffset:function(e){var t=e,n={left:0,top:0};if(t.offsetParent)do n.left+=t.offsetLeft,n.top+=t.offsetTop,t=t.offsetParent;while(t);return n},isActive:function(e){return e===document.activeElement&&(e.type||e.href)}},lf=function(e){Qd(t,e);function t(e,n){Yd(this,t);var r=$d(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n)),i=r;r.__prev=r.getValue(),r.__checkbox=document.createElement(`input`),r.__checkbox.setAttribute(`type`,`checkbox`);function a(){i.setValue(!i.__prev)}return W.bind(r.__checkbox,`change`,a,!1),r.domElement.appendChild(r.__checkbox),r.updateDisplay(),r}return Xd(t,[{key:`setValue`,value:function(e){var n=Zd(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),`setValue`,this).call(this,e);return this.__onFinishChange&&this.__onFinishChange.call(this,this.getValue()),this.__prev=this.getValue(),n}},{key:`updateDisplay`,value:function(){return this.getValue()===!0?(this.__checkbox.setAttribute(`checked`,`checked`),this.__checkbox.checked=!0,this.__prev=!0):(this.__checkbox.checked=!1,this.__prev=!1),Zd(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),`updateDisplay`,this).call(this)}}]),t}(rf),uf=function(e){Qd(t,e);function t(e,n,r){Yd(this,t);var i=$d(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n)),a=r,o=i;if(i.__select=document.createElement(`select`),U.isArray(a)){var s={};U.each(a,function(e){s[e]=e}),a=s}return U.each(a,function(e,t){var n=document.createElement(`option`);n.innerHTML=t,n.setAttribute(`value`,e),o.__select.appendChild(n)}),i.updateDisplay(),W.bind(i.__select,`change`,function(){var e=this.options[this.selectedIndex].value;o.setValue(e)}),i.domElement.appendChild(i.__select),i}return Xd(t,[{key:`setValue`,value:function(e){var n=Zd(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),`setValue`,this).call(this,e);return this.__onFinishChange&&this.__onFinishChange.call(this,this.getValue()),n}},{key:`updateDisplay`,value:function(){return W.isActive(this.__select)?this:(this.__select.value=this.getValue(),Zd(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),`updateDisplay`,this).call(this))}}]),t}(rf),df=function(e){Qd(t,e);function t(e,n){Yd(this,t);var r=$d(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n)),i=r;function a(){i.setValue(i.__input.value)}function o(){i.__onFinishChange&&i.__onFinishChange.call(i,i.getValue())}return r.__input=document.createElement(`input`),r.__input.setAttribute(`type`,`text`),W.bind(r.__input,`keyup`,a),W.bind(r.__input,`change`,a),W.bind(r.__input,`blur`,o),W.bind(r.__input,`keydown`,function(e){e.keyCode===13&&this.blur()}),r.updateDisplay(),r.domElement.appendChild(r.__input),r}return Xd(t,[{key:`updateDisplay`,value:function(){return W.isActive(this.__input)||(this.__input.value=this.getValue()),Zd(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),`updateDisplay`,this).call(this)}}]),t}(rf);function ff(e){var t=e.toString();return t.indexOf(`.`)>-1?t.length-t.indexOf(`.`)-1:0}var pf=function(e){Qd(t,e);function t(e,n,r){Yd(this,t);var i=$d(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n)),a=r||{};return i.__min=a.min,i.__max=a.max,i.__step=a.step,U.isUndefined(i.__step)?i.initialValue===0?i.__impliedStep=1:i.__impliedStep=10**Math.floor(Math.log(Math.abs(i.initialValue))/Math.LN10)/10:i.__impliedStep=i.__step,i.__precision=ff(i.__impliedStep),i}return Xd(t,[{key:`setValue`,value:function(e){var n=e;return this.__min!==void 0&&n<this.__min?n=this.__min:this.__max!==void 0&&n>this.__max&&(n=this.__max),this.__step!==void 0&&n%this.__step!==0&&(n=Math.round(n/this.__step)*this.__step),Zd(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),`setValue`,this).call(this,n)}},{key:`min`,value:function(e){return this.__min=e,this}},{key:`max`,value:function(e){return this.__max=e,this}},{key:`step`,value:function(e){return this.__step=e,this.__impliedStep=e,this.__precision=ff(e),this}}]),t}(rf);function mf(e,t){var n=10**t;return Math.round(e*n)/n}var hf=function(e){Qd(t,e);function t(e,n,r){Yd(this,t);var i=$d(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n,r));i.__truncationSuspended=!1;var a=i,o=void 0;function s(){var e=parseFloat(a.__input.value);U.isNaN(e)||a.setValue(e)}function c(){a.__onFinishChange&&a.__onFinishChange.call(a,a.getValue())}function l(){c()}function u(e){var t=o-e.clientY;a.setValue(a.getValue()+t*a.__impliedStep),o=e.clientY}function d(){W.unbind(window,`mousemove`,u),W.unbind(window,`mouseup`,d),c()}function f(e){W.bind(window,`mousemove`,u),W.bind(window,`mouseup`,d),o=e.clientY}return i.__input=document.createElement(`input`),i.__input.setAttribute(`type`,`text`),W.bind(i.__input,`change`,s),W.bind(i.__input,`blur`,l),W.bind(i.__input,`mousedown`,f),W.bind(i.__input,`keydown`,function(e){e.keyCode===13&&(a.__truncationSuspended=!0,this.blur(),a.__truncationSuspended=!1,c())}),i.updateDisplay(),i.domElement.appendChild(i.__input),i}return Xd(t,[{key:`updateDisplay`,value:function(){return this.__input.value=this.__truncationSuspended?this.getValue():mf(this.getValue(),this.__precision),Zd(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),`updateDisplay`,this).call(this)}}]),t}(pf);function gf(e,t,n,r,i){return r+(i-r)*((e-t)/(n-t))}var _f=function(e){Qd(t,e);function t(e,n,r,i,a){Yd(this,t);var o=$d(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n,{min:r,max:i,step:a})),s=o;o.__background=document.createElement(`div`),o.__foreground=document.createElement(`div`),W.bind(o.__background,`mousedown`,c),W.bind(o.__background,`touchstart`,d),W.addClass(o.__background,`slider`),W.addClass(o.__foreground,`slider-fg`);function c(e){document.activeElement.blur(),W.bind(window,`mousemove`,l),W.bind(window,`mouseup`,u),l(e)}function l(e){e.preventDefault();var t=s.__background.getBoundingClientRect();return s.setValue(gf(e.clientX,t.left,t.right,s.__min,s.__max)),!1}function u(){W.unbind(window,`mousemove`,l),W.unbind(window,`mouseup`,u),s.__onFinishChange&&s.__onFinishChange.call(s,s.getValue())}function d(e){e.touches.length===1&&(W.bind(window,`touchmove`,f),W.bind(window,`touchend`,p),f(e))}function f(e){var t=e.touches[0].clientX,n=s.__background.getBoundingClientRect();s.setValue(gf(t,n.left,n.right,s.__min,s.__max))}function p(){W.unbind(window,`touchmove`,f),W.unbind(window,`touchend`,p),s.__onFinishChange&&s.__onFinishChange.call(s,s.getValue())}return o.updateDisplay(),o.__background.appendChild(o.__foreground),o.domElement.appendChild(o.__background),o}return Xd(t,[{key:`updateDisplay`,value:function(){var e=(this.getValue()-this.__min)/(this.__max-this.__min);return this.__foreground.style.width=e*100+`%`,Zd(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),`updateDisplay`,this).call(this)}}]),t}(pf),vf=function(e){Qd(t,e);function t(e,n,r){Yd(this,t);var i=$d(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n)),a=i;return i.__button=document.createElement(`div`),i.__button.innerHTML=r===void 0?`Fire`:r,W.bind(i.__button,`click`,function(e){return e.preventDefault(),a.fire(),!1}),W.addClass(i.__button,`button`),i.domElement.appendChild(i.__button),i}return Xd(t,[{key:`fire`,value:function(){this.__onChange&&this.__onChange.call(this),this.getValue().call(this.object),this.__onFinishChange&&this.__onFinishChange.call(this,this.getValue())}}]),t}(rf),yf=function(e){Qd(t,e);function t(e,n){Yd(this,t);var r=$d(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));r.__color=new ef(r.getValue()),r.__temp=new ef(0);var i=r;r.domElement=document.createElement(`div`),W.makeSelectable(r.domElement,!1),r.__selector=document.createElement(`div`),r.__selector.className=`selector`,r.__saturation_field=document.createElement(`div`),r.__saturation_field.className=`saturation-field`,r.__field_knob=document.createElement(`div`),r.__field_knob.className=`field-knob`,r.__field_knob_border=`2px solid `,r.__hue_knob=document.createElement(`div`),r.__hue_knob.className=`hue-knob`,r.__hue_field=document.createElement(`div`),r.__hue_field.className=`hue-field`,r.__input=document.createElement(`input`),r.__input.type=`text`,r.__input_textShadow=`0 1px 1px `,W.bind(r.__input,`keydown`,function(e){e.keyCode===13&&u.call(this)}),W.bind(r.__input,`blur`,u),W.bind(r.__selector,`mousedown`,function(){W.addClass(this,`drag`).bind(window,`mouseup`,function(){W.removeClass(i.__selector,`drag`)})}),W.bind(r.__selector,`touchstart`,function(){W.addClass(this,`drag`).bind(window,`touchend`,function(){W.removeClass(i.__selector,`drag`)})});var a=document.createElement(`div`);U.extend(r.__selector.style,{width:`122px`,height:`102px`,padding:`3px`,backgroundColor:`#222`,boxShadow:`0px 1px 3px rgba(0,0,0,0.3)`}),U.extend(r.__field_knob.style,{position:`absolute`,width:`12px`,height:`12px`,border:r.__field_knob_border+(r.__color.v<.5?`#fff`:`#000`),boxShadow:`0px 1px 3px rgba(0,0,0,0.5)`,borderRadius:`12px`,zIndex:1}),U.extend(r.__hue_knob.style,{position:`absolute`,width:`15px`,height:`2px`,borderRight:`4px solid #fff`,zIndex:1}),U.extend(r.__saturation_field.style,{width:`100px`,height:`100px`,border:`1px solid #555`,marginRight:`3px`,display:`inline-block`,cursor:`pointer`}),U.extend(a.style,{width:`100%`,height:`100%`,background:`none`}),xf(a,`top`,`rgba(0,0,0,0)`,`#000`),U.extend(r.__hue_field.style,{width:`15px`,height:`100px`,border:`1px solid #555`,cursor:`ns-resize`,position:`absolute`,top:`3px`,right:`3px`}),Sf(r.__hue_field),U.extend(r.__input.style,{outline:`none`,textAlign:`center`,color:`#fff`,border:0,fontWeight:`bold`,textShadow:r.__input_textShadow+`rgba(0,0,0,0.7)`}),W.bind(r.__saturation_field,`mousedown`,o),W.bind(r.__saturation_field,`touchstart`,o),W.bind(r.__field_knob,`mousedown`,o),W.bind(r.__field_knob,`touchstart`,o),W.bind(r.__hue_field,`mousedown`,s),W.bind(r.__hue_field,`touchstart`,s);function o(e){f(e),W.bind(window,`mousemove`,f),W.bind(window,`touchmove`,f),W.bind(window,`mouseup`,c),W.bind(window,`touchend`,c)}function s(e){p(e),W.bind(window,`mousemove`,p),W.bind(window,`touchmove`,p),W.bind(window,`mouseup`,l),W.bind(window,`touchend`,l)}function c(){W.unbind(window,`mousemove`,f),W.unbind(window,`touchmove`,f),W.unbind(window,`mouseup`,c),W.unbind(window,`touchend`,c),d()}function l(){W.unbind(window,`mousemove`,p),W.unbind(window,`touchmove`,p),W.unbind(window,`mouseup`,l),W.unbind(window,`touchend`,l),d()}function u(){var e=Gd(this.value);e===!1?this.value=i.__color.toString():(i.__color.__state=e,i.setValue(i.__color.toOriginal()))}function d(){i.__onFinishChange&&i.__onFinishChange.call(i,i.__color.toOriginal())}r.__saturation_field.appendChild(a),r.__selector.appendChild(r.__field_knob),r.__selector.appendChild(r.__saturation_field),r.__selector.appendChild(r.__hue_field),r.__hue_field.appendChild(r.__hue_knob),r.domElement.appendChild(r.__input),r.domElement.appendChild(r.__selector),r.updateDisplay();function f(e){e.type.indexOf(`touch`)===-1&&e.preventDefault();var t=i.__saturation_field.getBoundingClientRect(),n=e.touches&&e.touches[0]||e,r=n.clientX,a=n.clientY,o=(r-t.left)/(t.right-t.left),s=1-(a-t.top)/(t.bottom-t.top);return s>1?s=1:s<0&&(s=0),o>1?o=1:o<0&&(o=0),i.__color.v=s,i.__color.s=o,i.setValue(i.__color.toOriginal()),!1}function p(e){e.type.indexOf(`touch`)===-1&&e.preventDefault();var t=i.__hue_field.getBoundingClientRect(),n=1-((e.touches&&e.touches[0]||e).clientY-t.top)/(t.bottom-t.top);return n>1?n=1:n<0&&(n=0),i.__color.h=n*360,i.setValue(i.__color.toOriginal()),!1}return r}return Xd(t,[{key:`updateDisplay`,value:function(){var e=Gd(this.getValue());if(e!==!1){var t=!1;U.each(ef.COMPONENTS,function(n){if(!U.isUndefined(e[n])&&!U.isUndefined(this.__color.__state[n])&&e[n]!==this.__color.__state[n])return t=!0,{}},this),t&&U.extend(this.__color.__state,e)}U.extend(this.__temp.__state,this.__color.__state),this.__temp.a=1;var n=this.__color.v<.5||this.__color.s>.5?255:0,r=255-n;U.extend(this.__field_knob.style,{marginLeft:100*this.__color.s-7+`px`,marginTop:100*(1-this.__color.v)-7+`px`,backgroundColor:this.__temp.toHexString(),border:this.__field_knob_border+`rgb(`+n+`,`+n+`,`+n+`)`}),this.__hue_knob.style.marginTop=(1-this.__color.h/360)*100+`px`,this.__temp.s=1,this.__temp.v=1,xf(this.__saturation_field,`left`,`#fff`,this.__temp.toHexString()),this.__input.value=this.__color.toString(),U.extend(this.__input.style,{backgroundColor:this.__color.toHexString(),color:`rgb(`+n+`,`+n+`,`+n+`)`,textShadow:this.__input_textShadow+`rgba(`+r+`,`+r+`,`+r+`,.7)`})}}]),t}(rf),bf=[`-moz-`,`-o-`,`-webkit-`,`-ms-`,``];function xf(e,t,n,r){e.style.background=``,U.each(bf,function(i){e.style.cssText+=`background: `+i+`linear-gradient(`+t+`, `+n+` 0%, `+r+` 100%); `})}function Sf(e){e.style.background=``,e.style.cssText+=`background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);`,e.style.cssText+=`background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);`,e.style.cssText+=`background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);`,e.style.cssText+=`background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);`,e.style.cssText+=`background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);`}var Cf={load:function(e,t){var n=t||document,r=n.createElement(`link`);r.type=`text/css`,r.rel=`stylesheet`,r.href=e,n.getElementsByTagName(`head`)[0].appendChild(r)},inject:function(e,t){var n=t||document,r=document.createElement(`style`);r.type=`text/css`,r.innerHTML=e;var i=n.getElementsByTagName(`head`)[0];try{i.appendChild(r)}catch{}}},wf=`<div id="dg-save" class="dg dialogue">
+
+ Here's the new load parameter for your <code>GUI</code>'s constructor:
+
+ <textarea id="dg-new-constructor"></textarea>
+
+ <div id="dg-save-locally">
+
+ <input id="dg-local-storage" type="checkbox"/> Automatically save
+ values to <code>localStorage</code> on exit.
+
+ <div id="dg-local-explain">The values saved to <code>localStorage</code> will
+ override those passed to <code>dat.GUI</code>'s constructor. This makes it
+ easier to work incrementally, but <code>localStorage</code> is fragile,
+ and your friends may not see the same values you do.
+
+ </div>
+
+ </div>
+
+</div>`,Tf=function(e,t){var n=e[t];return U.isArray(arguments[2])||U.isObject(arguments[2])?new uf(e,t,arguments[2]):U.isNumber(n)?U.isNumber(arguments[2])&&U.isNumber(arguments[3])?U.isNumber(arguments[4])?new _f(e,t,arguments[2],arguments[3],arguments[4]):new _f(e,t,arguments[2],arguments[3]):U.isNumber(arguments[4])?new hf(e,t,{min:arguments[2],max:arguments[3],step:arguments[4]}):new hf(e,t,{min:arguments[2],max:arguments[3]}):U.isString(n)?new df(e,t):U.isFunction(n)?new vf(e,t,``):U.isBoolean(n)?new lf(e,t):null};function Ef(e){setTimeout(e,1e3/60)}var Df=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||Ef,Of=function(){function e(){Yd(this,e),this.backgroundElement=document.createElement(`div`),U.extend(this.backgroundElement.style,{backgroundColor:`rgba(0,0,0,0.8)`,top:0,left:0,display:`none`,zIndex:`1000`,opacity:0,WebkitTransition:`opacity 0.2s linear`,transition:`opacity 0.2s linear`}),W.makeFullscreen(this.backgroundElement),this.backgroundElement.style.position=`fixed`,this.domElement=document.createElement(`div`),U.extend(this.domElement.style,{position:`fixed`,display:`none`,zIndex:`1001`,opacity:0,WebkitTransition:`-webkit-transform 0.2s ease-out, opacity 0.2s linear`,transition:`transform 0.2s ease-out, opacity 0.2s linear`}),document.body.appendChild(this.backgroundElement),document.body.appendChild(this.domElement);var t=this;W.bind(this.backgroundElement,`click`,function(){t.hide()})}return Xd(e,[{key:`show`,value:function(){var e=this;this.backgroundElement.style.display=`block`,this.domElement.style.display=`block`,this.domElement.style.opacity=0,this.domElement.style.webkitTransform=`scale(1.1)`,this.layout(),U.defer(function(){e.backgroundElement.style.opacity=1,e.domElement.style.opacity=1,e.domElement.style.webkitTransform=`scale(1)`})}},{key:`hide`,value:function(){var e=this,t=function t(){e.domElement.style.display=`none`,e.backgroundElement.style.display=`none`,W.unbind(e.domElement,`webkitTransitionEnd`,t),W.unbind(e.domElement,`transitionend`,t),W.unbind(e.domElement,`oTransitionEnd`,t)};W.bind(this.domElement,`webkitTransitionEnd`,t),W.bind(this.domElement,`transitionend`,t),W.bind(this.domElement,`oTransitionEnd`,t),this.backgroundElement.style.opacity=0,this.domElement.style.opacity=0,this.domElement.style.webkitTransform=`scale(1.1)`}},{key:`layout`,value:function(){this.domElement.style.left=window.innerWidth/2-W.getWidth(this.domElement)/2+`px`,this.domElement.style.top=window.innerHeight/2-W.getHeight(this.domElement)/2+`px`}}]),e}(),kf=Rd(`.dg ul{list-style:none;margin:0;padding:0;width:100%;clear:both}.dg.ac{position:fixed;top:0;left:0;right:0;height:0;z-index:0}.dg:not(.ac) .main{overflow:hidden}.dg.main{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear}.dg.main.taller-than-window{overflow-y:auto}.dg.main.taller-than-window .close-button{opacity:1;margin-top:-1px;border-top:1px solid #2c2c2c}.dg.main ul.closed .close-button{opacity:1 !important}.dg.main:hover .close-button,.dg.main .close-button.drag{opacity:1}.dg.main .close-button{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear;border:0;line-height:19px;height:20px;cursor:pointer;text-align:center;background-color:#000}.dg.main .close-button.close-top{position:relative}.dg.main .close-button.close-bottom{position:absolute}.dg.main .close-button:hover{background-color:#111}.dg.a{float:right;margin-right:15px;overflow-y:visible}.dg.a.has-save>ul.close-top{margin-top:0}.dg.a.has-save>ul.close-bottom{margin-top:27px}.dg.a.has-save>ul.closed{margin-top:0}.dg.a .save-row{top:0;z-index:1002}.dg.a .save-row.close-top{position:relative}.dg.a .save-row.close-bottom{position:fixed}.dg li{-webkit-transition:height .1s ease-out;-o-transition:height .1s ease-out;-moz-transition:height .1s ease-out;transition:height .1s ease-out;-webkit-transition:overflow .1s linear;-o-transition:overflow .1s linear;-moz-transition:overflow .1s linear;transition:overflow .1s linear}.dg li:not(.folder){cursor:auto;height:27px;line-height:27px;padding:0 4px 0 5px}.dg li.folder{padding:0;border-left:4px solid rgba(0,0,0,0)}.dg li.title{cursor:pointer;margin-left:-4px}.dg .closed li:not(.title),.dg .closed ul li,.dg .closed ul li>*{height:0;overflow:hidden;border:0}.dg .cr{clear:both;padding-left:3px;height:27px;overflow:hidden}.dg .property-name{cursor:default;float:left;clear:left;width:40%;overflow:hidden;text-overflow:ellipsis}.dg .cr.function .property-name{width:100%}.dg .c{float:left;width:60%;position:relative}.dg .c input[type=text]{border:0;margin-top:4px;padding:3px;width:100%;float:right}.dg .has-slider input[type=text]{width:30%;margin-left:0}.dg .slider{float:left;width:66%;margin-left:-5px;margin-right:0;height:19px;margin-top:4px}.dg .slider-fg{height:100%}.dg .c input[type=checkbox]{margin-top:7px}.dg .c select{margin-top:5px}.dg .cr.function,.dg .cr.function .property-name,.dg .cr.function *,.dg .cr.boolean,.dg .cr.boolean *{cursor:pointer}.dg .cr.color{overflow:visible}.dg .selector{display:none;position:absolute;margin-left:-9px;margin-top:23px;z-index:10}.dg .c:hover .selector,.dg .selector.drag{display:block}.dg li.save-row{padding:0}.dg li.save-row .button{display:inline-block;padding:0px 6px}.dg.dialogue{background-color:#222;width:460px;padding:15px;font-size:13px;line-height:15px}#dg-new-constructor{padding:10px;color:#222;font-family:Monaco, monospace;font-size:10px;border:0;resize:none;box-shadow:inset 1px 1px 1px #888;word-wrap:break-word;margin:12px 0;display:block;width:440px;overflow-y:scroll;height:100px;position:relative}#dg-local-explain{display:none;font-size:11px;line-height:17px;border-radius:3px;background-color:#333;padding:8px;margin-top:10px}#dg-local-explain code{font-size:10px}#dat-gui-save-locally{display:none}.dg{color:#eee;font:11px 'Lucida Grande', sans-serif;text-shadow:0 -1px 0 #111}.dg.main::-webkit-scrollbar{width:5px;background:#1a1a1a}.dg.main::-webkit-scrollbar-corner{height:0;display:none}.dg.main::-webkit-scrollbar-thumb{border-radius:5px;background:#676767}.dg li:not(.folder){background:#1a1a1a;border-bottom:1px solid #2c2c2c}.dg li.save-row{line-height:25px;background:#dad5cb;border:0}.dg li.save-row select{margin-left:5px;width:108px}.dg li.save-row .button{margin-left:5px;margin-top:1px;border-radius:2px;font-size:9px;line-height:7px;padding:4px 4px 5px 4px;background:#c5bdad;color:#fff;text-shadow:0 1px 0 #b0a58f;box-shadow:0 -1px 0 #b0a58f;cursor:pointer}.dg li.save-row .button.gears{background:#c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;height:7px;width:8px}.dg li.save-row .button:hover{background-color:#bab19e;box-shadow:0 -1px 0 #b0a58f}.dg li.folder{border-bottom:0}.dg li.title{padding-left:16px;background:#000 url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.2)}.dg .closed li.title{background-image:url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==)}.dg .cr.boolean{border-left:3px solid #806787}.dg .cr.color{border-left:3px solid}.dg .cr.function{border-left:3px solid #e61d5f}.dg .cr.number{border-left:3px solid #2FA1D6}.dg .cr.number input[type=text]{color:#2FA1D6}.dg .cr.string{border-left:3px solid #1ed36f}.dg .cr.string input[type=text]{color:#1ed36f}.dg .cr.function:hover,.dg .cr.boolean:hover{background:#111}.dg .c input[type=text]{background:#303030;outline:none}.dg .c input[type=text]:hover{background:#3c3c3c}.dg .c input[type=text]:focus{background:#494949;color:#fff}.dg .c .slider{background:#303030;cursor:ew-resize}.dg .c .slider-fg{background:#2FA1D6;max-width:100%}.dg .c .slider:hover{background:#3c3c3c}.dg .c .slider:hover .slider-fg{background:#44abda}
+`);Cf.inject(kf);var Af=`dg`,jf=72,Mf=20,Nf=`Default`,Pf=function(){try{return!!window.localStorage}catch{return!1}}(),Ff=void 0,If=!0,Lf=void 0,Rf=!1,zf=[],Bf=function e(t){var n=this,r=t||{};this.domElement=document.createElement(`div`),this.__ul=document.createElement(`ul`),this.domElement.appendChild(this.__ul),W.addClass(this.domElement,Af),this.__folders={},this.__controllers=[],this.__rememberedObjects=[],this.__rememberedObjectIndecesToControllers=[],this.__listening=[],r=U.defaults(r,{closeOnTop:!1,autoPlace:!0,width:e.DEFAULT_WIDTH}),r=U.defaults(r,{resizable:r.autoPlace,hideable:r.autoPlace}),U.isUndefined(r.load)?r.load={preset:Nf}:r.preset&&(r.load.preset=r.preset),U.isUndefined(r.parent)&&r.hideable&&zf.push(this),r.resizable=U.isUndefined(r.parent)&&r.resizable,r.autoPlace&&U.isUndefined(r.scrollable)&&(r.scrollable=!0);var i=Pf&&localStorage.getItem(qf(this,`isLocal`))===`true`,a=void 0,o=void 0;if(Object.defineProperties(this,{parent:{get:function(){return r.parent}},scrollable:{get:function(){return r.scrollable}},autoPlace:{get:function(){return r.autoPlace}},closeOnTop:{get:function(){return r.closeOnTop}},preset:{get:function(){return n.parent?n.getRoot().preset:r.load.preset},set:function(e){n.parent?n.getRoot().preset=e:r.load.preset=e,ep(this),n.revert()}},width:{get:function(){return r.width},set:function(e){r.width=e,Qf(n,e)}},name:{get:function(){return r.name},set:function(e){r.name=e,o&&(o.innerHTML=r.name)}},closed:{get:function(){return r.closed},set:function(t){r.closed=t,r.closed?W.addClass(n.__ul,e.CLASS_CLOSED):W.removeClass(n.__ul,e.CLASS_CLOSED),this.onResize(),n.__closeButton&&(n.__closeButton.innerHTML=t?e.TEXT_OPEN:e.TEXT_CLOSED)}},load:{get:function(){return r.load}},useLocalStorage:{get:function(){return i},set:function(e){Pf&&(i=e,e?W.bind(window,`unload`,a):W.unbind(window,`unload`,a),localStorage.setItem(qf(n,`isLocal`),e))}}}),U.isUndefined(r.parent)){if(this.closed=r.closed||!1,W.addClass(this.domElement,e.CLASS_MAIN),W.makeSelectable(this.domElement,!1),Pf&&i){n.useLocalStorage=!0;var s=localStorage.getItem(qf(this,`gui`));s&&(r.load=JSON.parse(s))}this.__closeButton=document.createElement(`div`),this.__closeButton.innerHTML=e.TEXT_CLOSED,W.addClass(this.__closeButton,e.CLASS_CLOSE_BUTTON),r.closeOnTop?(W.addClass(this.__closeButton,e.CLASS_CLOSE_TOP),this.domElement.insertBefore(this.__closeButton,this.domElement.childNodes[0])):(W.addClass(this.__closeButton,e.CLASS_CLOSE_BOTTOM),this.domElement.appendChild(this.__closeButton)),W.bind(this.__closeButton,`click`,function(){n.closed=!n.closed})}else{r.closed===void 0&&(r.closed=!0);var c=document.createTextNode(r.name);W.addClass(c,`controller-name`),o=Vf(n,c),W.addClass(this.__ul,e.CLASS_CLOSED),W.addClass(o,`title`),W.bind(o,`click`,function(e){return e.preventDefault(),n.closed=!n.closed,!1}),r.closed||(this.closed=!1)}r.autoPlace&&(U.isUndefined(r.parent)&&(If&&=(Lf=document.createElement(`div`),W.addClass(Lf,Af),W.addClass(Lf,e.CLASS_AUTO_PLACE_CONTAINER),document.body.appendChild(Lf),!1),Lf.appendChild(this.domElement),W.addClass(this.domElement,e.CLASS_AUTO_PLACE)),this.parent||Qf(n,r.width)),this.__resizeHandler=function(){n.onResizeDebounced()},W.bind(window,`resize`,this.__resizeHandler),W.bind(this.__ul,`webkitTransitionEnd`,this.__resizeHandler),W.bind(this.__ul,`transitionend`,this.__resizeHandler),W.bind(this.__ul,`oTransitionEnd`,this.__resizeHandler),this.onResize(),r.resizable&&Zf(this),a=function(){Pf&&localStorage.getItem(qf(n,`isLocal`))===`true`&&localStorage.setItem(qf(n,`gui`),JSON.stringify(n.getSaveObject()))},this.saveToLocalStorageIfPossible=a;function l(){var e=n.getRoot();e.width+=1,U.defer(function(){--e.width})}r.parent||l()};Bf.toggleHide=function(){Rf=!Rf,U.each(zf,function(e){e.domElement.style.display=Rf?`none`:``})},Bf.CLASS_AUTO_PLACE=`a`,Bf.CLASS_AUTO_PLACE_CONTAINER=`ac`,Bf.CLASS_MAIN=`main`,Bf.CLASS_CONTROLLER_ROW=`cr`,Bf.CLASS_TOO_TALL=`taller-than-window`,Bf.CLASS_CLOSED=`closed`,Bf.CLASS_CLOSE_BUTTON=`close-button`,Bf.CLASS_CLOSE_TOP=`close-top`,Bf.CLASS_CLOSE_BOTTOM=`close-bottom`,Bf.CLASS_DRAG=`drag`,Bf.DEFAULT_WIDTH=245,Bf.TEXT_CLOSED=`Close Controls`,Bf.TEXT_OPEN=`Open Controls`,Bf._keydownHandler=function(e){document.activeElement.type!==`text`&&(e.which===jf||e.keyCode===jf)&&Bf.toggleHide()},W.bind(window,`keydown`,Bf._keydownHandler,!1),U.extend(Bf.prototype,{add:function(e,t){return Kf(this,e,t,{factoryArgs:Array.prototype.slice.call(arguments,2)})},addColor:function(e,t){return Kf(this,e,t,{color:!0})},remove:function(e){this.__ul.removeChild(e.__li),this.__controllers.splice(this.__controllers.indexOf(e),1);var t=this;U.defer(function(){t.onResize()})},destroy:function(){if(this.parent)throw Error(`Only the root GUI should be removed with .destroy(). For subfolders, use gui.removeFolder(folder) instead.`);this.autoPlace&&Lf.removeChild(this.domElement);var e=this;U.each(this.__folders,function(t){e.removeFolder(t)}),W.unbind(window,`keydown`,Bf._keydownHandler,!1),Hf(this)},addFolder:function(e){if(this.__folders[e]!==void 0)throw Error(`You already have a folder in this GUI by the name "`+e+`"`);var t={name:e,parent:this};t.autoPlace=this.autoPlace,this.load&&this.load.folders&&this.load.folders[e]&&(t.closed=this.load.folders[e].closed,t.load=this.load.folders[e]);var n=new Bf(t);this.__folders[e]=n;var r=Vf(this,n.domElement);return W.addClass(r,`folder`),n},removeFolder:function(e){this.__ul.removeChild(e.domElement.parentElement),delete this.__folders[e.name],this.load&&this.load.folders&&this.load.folders[e.name]&&delete this.load.folders[e.name],Hf(e);var t=this;U.each(e.__folders,function(t){e.removeFolder(t)}),U.defer(function(){t.onResize()})},open:function(){this.closed=!1},close:function(){this.closed=!0},hide:function(){this.domElement.style.display=`none`},show:function(){this.domElement.style.display=``},onResize:function(){var e=this.getRoot();if(e.scrollable){var t=W.getOffset(e.__ul).top,n=0;U.each(e.__ul.childNodes,function(t){e.autoPlace&&t===e.__save_row||(n+=W.getHeight(t))}),window.innerHeight-t-Mf<n?(W.addClass(e.domElement,Bf.CLASS_TOO_TALL),e.__ul.style.height=window.innerHeight-t-Mf+`px`):(W.removeClass(e.domElement,Bf.CLASS_TOO_TALL),e.__ul.style.height=`auto`)}e.__resize_handle&&U.defer(function(){e.__resize_handle.style.height=e.__ul.offsetHeight+`px`}),e.__closeButton&&(e.__closeButton.style.width=e.width+`px`)},onResizeDebounced:U.debounce(function(){this.onResize()},50),remember:function(){if(U.isUndefined(Ff)&&(Ff=new Of,Ff.domElement.innerHTML=wf),this.parent)throw Error(`You can only call remember on a top level GUI.`);var e=this;U.each(Array.prototype.slice.call(arguments),function(t){e.__rememberedObjects.length===0&&Xf(e),e.__rememberedObjects.indexOf(t)===-1&&e.__rememberedObjects.push(t)}),this.autoPlace&&Qf(this,this.width)},getRoot:function(){for(var e=this;e.parent;)e=e.parent;return e},getSaveObject:function(){var e=this.load;return e.closed=this.closed,this.__rememberedObjects.length>0&&(e.preset=this.preset,e.remembered||={},e.remembered[this.preset]=$f(this)),e.folders={},U.each(this.__folders,function(t,n){e.folders[n]=t.getSaveObject()}),e},save:function(){this.load.remembered||(this.load.remembered={}),this.load.remembered[this.preset]=$f(this),Uf(this,!1),this.saveToLocalStorageIfPossible()},saveAs:function(e){this.load.remembered||(this.load.remembered={},this.load.remembered[Nf]=$f(this,!0)),this.load.remembered[e]=$f(this),this.preset=e,Jf(this,e,!0),this.saveToLocalStorageIfPossible()},revert:function(e){U.each(this.__controllers,function(t){this.getRoot().load.remembered?Gf(e||this.getRoot(),t):t.setValue(t.initialValue),t.__onFinishChange&&t.__onFinishChange.call(t,t.getValue())},this),U.each(this.__folders,function(e){e.revert(e)}),e||Uf(this.getRoot(),!1)},listen:function(e){var t=this.__listening.length===0;this.__listening.push(e),t&&tp(this.__listening)},updateDisplay:function(){U.each(this.__controllers,function(e){e.updateDisplay()}),U.each(this.__folders,function(e){e.updateDisplay()})}});function Vf(e,t,n){var r=document.createElement(`li`);return t&&r.appendChild(t),n?e.__ul.insertBefore(r,n):e.__ul.appendChild(r),e.onResize(),r}function Hf(e){W.unbind(window,`resize`,e.__resizeHandler),e.saveToLocalStorageIfPossible&&W.unbind(window,`unload`,e.saveToLocalStorageIfPossible)}function Uf(e,t){var n=e.__preset_select[e.__preset_select.selectedIndex];t?n.innerHTML=n.value+`*`:n.innerHTML=n.value}function Wf(e,t,n){if(n.__li=t,n.__gui=e,U.extend(n,{options:function(t){if(arguments.length>1){var r=n.__li.nextElementSibling;return n.remove(),Kf(e,n.object,n.property,{before:r,factoryArgs:[U.toArray(arguments)]})}if(U.isArray(t)||U.isObject(t)){var i=n.__li.nextElementSibling;return n.remove(),Kf(e,n.object,n.property,{before:i,factoryArgs:[t]})}},name:function(e){return n.__li.firstElementChild.firstElementChild.innerHTML=e,n},listen:function(){return n.__gui.listen(n),n},remove:function(){return n.__gui.remove(n),n}}),n instanceof _f){var r=new hf(n.object,n.property,{min:n.__min,max:n.__max,step:n.__step});U.each([`updateDisplay`,`onChange`,`onFinishChange`,`step`,`min`,`max`],function(e){var t=n[e],i=r[e];n[e]=r[e]=function(){var e=Array.prototype.slice.call(arguments);return i.apply(r,e),t.apply(n,e)}}),W.addClass(t,`has-slider`),n.domElement.insertBefore(r.domElement,n.domElement.firstElementChild)}else if(n instanceof hf){var i=function(t){if(U.isNumber(n.__min)&&U.isNumber(n.__max)){var r=n.__li.firstElementChild.firstElementChild.innerHTML,i=n.__gui.__listening.indexOf(n)>-1;n.remove();var a=Kf(e,n.object,n.property,{before:n.__li.nextElementSibling,factoryArgs:[n.__min,n.__max,n.__step]});return a.name(r),i&&a.listen(),a}return t};n.min=U.compose(i,n.min),n.max=U.compose(i,n.max)}else n instanceof lf?(W.bind(t,`click`,function(){W.fakeEvent(n.__checkbox,`click`)}),W.bind(n.__checkbox,`click`,function(e){e.stopPropagation()})):n instanceof vf?(W.bind(t,`click`,function(){W.fakeEvent(n.__button,`click`)}),W.bind(t,`mouseover`,function(){W.addClass(n.__button,`hover`)}),W.bind(t,`mouseout`,function(){W.removeClass(n.__button,`hover`)})):n instanceof yf&&(W.addClass(t,`color`),n.updateDisplay=U.compose(function(e){return t.style.borderLeftColor=n.__color.toString(),e},n.updateDisplay),n.updateDisplay());n.setValue=U.compose(function(t){return e.getRoot().__preset_select&&n.isModified()&&Uf(e.getRoot(),!0),t},n.setValue)}function Gf(e,t){var n=e.getRoot(),r=n.__rememberedObjects.indexOf(t.object);if(r!==-1){var i=n.__rememberedObjectIndecesToControllers[r];if(i===void 0&&(i={},n.__rememberedObjectIndecesToControllers[r]=i),i[t.property]=t,n.load&&n.load.remembered){var a=n.load.remembered,o=void 0;if(a[e.preset])o=a[e.preset];else if(a[Nf])o=a[Nf];else return;if(o[r]&&o[r][t.property]!==void 0){var s=o[r][t.property];t.initialValue=s,t.setValue(s)}}}}function Kf(e,t,n,r){if(t[n]===void 0)throw Error(`Object "`+t+`" has no property "`+n+`"`);var i=void 0;if(r.color)i=new yf(t,n);else{var a=[t,n].concat(r.factoryArgs);i=Tf.apply(e,a)}r.before instanceof rf&&(r.before=r.before.__li),Gf(e,i),W.addClass(i.domElement,`c`);var o=document.createElement(`span`);W.addClass(o,`property-name`),o.innerHTML=i.property;var s=document.createElement(`div`);s.appendChild(o),s.appendChild(i.domElement);var c=Vf(e,s,r.before);return W.addClass(c,Bf.CLASS_CONTROLLER_ROW),i instanceof yf?W.addClass(c,`color`):W.addClass(c,Jd(i.getValue())),Wf(e,c,i),e.__controllers.push(i),i}function qf(e,t){return document.location.href+`.`+t}function Jf(e,t,n){var r=document.createElement(`option`);r.innerHTML=t,r.value=t,e.__preset_select.appendChild(r),n&&(e.__preset_select.selectedIndex=e.__preset_select.length-1)}function Yf(e,t){t.style.display=e.useLocalStorage?`block`:`none`}function Xf(e){var t=e.__save_row=document.createElement(`li`);W.addClass(e.domElement,`has-save`),e.__ul.insertBefore(t,e.__ul.firstChild),W.addClass(t,`save-row`);var n=document.createElement(`span`);n.innerHTML=`&nbsp;`,W.addClass(n,`button gears`);var r=document.createElement(`span`);r.innerHTML=`Save`,W.addClass(r,`button`),W.addClass(r,`save`);var i=document.createElement(`span`);i.innerHTML=`New`,W.addClass(i,`button`),W.addClass(i,`save-as`);var a=document.createElement(`span`);a.innerHTML=`Revert`,W.addClass(a,`button`),W.addClass(a,`revert`);var o=e.__preset_select=document.createElement(`select`);if(e.load&&e.load.remembered?U.each(e.load.remembered,function(t,n){Jf(e,n,n===e.preset)}):Jf(e,Nf,!1),W.bind(o,`change`,function(){for(var t=0;t<e.__preset_select.length;t++)e.__preset_select[t].innerHTML=e.__preset_select[t].value;e.preset=this.value}),t.appendChild(o),t.appendChild(n),t.appendChild(r),t.appendChild(i),t.appendChild(a),Pf){var s=document.getElementById(`dg-local-explain`),c=document.getElementById(`dg-local-storage`),l=document.getElementById(`dg-save-locally`);l.style.display=`block`,localStorage.getItem(qf(e,`isLocal`))===`true`&&c.setAttribute(`checked`,`checked`),Yf(e,s),W.bind(c,`change`,function(){e.useLocalStorage=!e.useLocalStorage,Yf(e,s)})}var u=document.getElementById(`dg-new-constructor`);W.bind(u,`keydown`,function(e){e.metaKey&&(e.which===67||e.keyCode===67)&&Ff.hide()}),W.bind(n,`click`,function(){u.innerHTML=JSON.stringify(e.getSaveObject(),void 0,2),Ff.show(),u.focus(),u.select()}),W.bind(r,`click`,function(){e.save()}),W.bind(i,`click`,function(){var t=prompt(`Enter a new preset name.`);t&&e.saveAs(t)}),W.bind(a,`click`,function(){e.revert()})}function Zf(e){var t=void 0;e.__resize_handle=document.createElement(`div`),U.extend(e.__resize_handle.style,{width:`6px`,marginLeft:`-3px`,height:`200px`,cursor:`ew-resize`,position:`absolute`});function n(n){return n.preventDefault(),e.width+=t-n.clientX,e.onResize(),t=n.clientX,!1}function r(){W.removeClass(e.__closeButton,Bf.CLASS_DRAG),W.unbind(window,`mousemove`,n),W.unbind(window,`mouseup`,r)}function i(i){return i.preventDefault(),t=i.clientX,W.addClass(e.__closeButton,Bf.CLASS_DRAG),W.bind(window,`mousemove`,n),W.bind(window,`mouseup`,r),!1}W.bind(e.__resize_handle,`mousedown`,i),W.bind(e.__closeButton,`mousedown`,i),e.domElement.insertBefore(e.__resize_handle,e.domElement.firstElementChild)}function Qf(e,t){e.domElement.style.width=t+`px`,e.__save_row&&e.autoPlace&&(e.__save_row.style.width=t+`px`),e.__closeButton&&(e.__closeButton.style.width=t+`px`)}function $f(e,t){var n={};return U.each(e.__rememberedObjects,function(r,i){var a={},o=e.__rememberedObjectIndecesToControllers[i];U.each(o,function(e,n){a[n]=t?e.initialValue:e.getValue()}),n[i]=a}),n}function ep(e){for(var t=0;t<e.__preset_select.length;t++)e.__preset_select[t].value===e.preset&&(e.__preset_select.selectedIndex=t)}function tp(e){e.length!==0&&Df.call(window,function(){tp(e)}),U.each(e,function(e){e.updateDisplay()})}var np=Bf,rp=[{id:``,name:`None`,path:null},{id:`neutral`,name:`Neutral`,path:null},{id:`venice-sunset`,name:`Venice Sunset`,path:`https://storage.googleapis.com/donmccurdy-static/venice_sunset_1k.exr`,format:`.exr`},{id:`footprint-court`,name:`Footprint Court (HDR Labs)`,path:`https://storage.googleapis.com/donmccurdy-static/footprint_court_2k.exr`,format:`.exr`}],ip=`BN.BN.BN.BN.BN.BN.BN.BN.BN.S.B.S.WS.B.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.B.B.B.S.WS.ON.ON.ET.ET.ET.ON.ON.ON.ON.ON.ES.CS.ES.CS.CS.EN.EN.EN.EN.EN.EN.EN.EN.EN.EN.CS.ON.ON.ON.ON.ON.ON.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.ON.ON.ON.ON.ON.ON.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.ON.ON.ON.ON.BN.BN.BN.BN.BN.BN.B.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.BN.CS.ON.ET.ET.ET.ET.ON.ON.ON.ON.L.ON.ON.BN.ON.ON.ET.ET.EN.EN.ON.L.ON.ON.ON.EN.L.ON.ON.ON.ON.ON.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.ON.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.L.ON.L.L.L.L.L.L.L.L`.split(`.`),ap=[[697,698,`ON`],[706,719,`ON`],[722,735,`ON`],[741,749,`ON`],[751,767,`ON`],[768,879,`NSM`],[884,885,`ON`],[894,894,`ON`],[900,901,`ON`],[903,903,`ON`],[1014,1014,`ON`],[1155,1161,`NSM`],[1418,1418,`ON`],[1421,1422,`ON`],[1423,1423,`ET`],[1424,1424,`R`],[1425,1469,`NSM`],[1470,1470,`R`],[1471,1471,`NSM`],[1472,1472,`R`],[1473,1474,`NSM`],[1475,1475,`R`],[1476,1477,`NSM`],[1478,1478,`R`],[1479,1479,`NSM`],[1480,1535,`R`],[1536,1541,`AN`],[1542,1543,`ON`],[1544,1544,`AL`],[1545,1546,`ET`],[1547,1547,`AL`],[1548,1548,`CS`],[1549,1549,`AL`],[1550,1551,`ON`],[1552,1562,`NSM`],[1563,1610,`AL`],[1611,1631,`NSM`],[1632,1641,`AN`],[1642,1642,`ET`],[1643,1644,`AN`],[1645,1647,`AL`],[1648,1648,`NSM`],[1649,1749,`AL`],[1750,1756,`NSM`],[1757,1757,`AN`],[1758,1758,`ON`],[1759,1764,`NSM`],[1765,1766,`AL`],[1767,1768,`NSM`],[1769,1769,`ON`],[1770,1773,`NSM`],[1774,1775,`AL`],[1776,1785,`EN`],[1786,1808,`AL`],[1809,1809,`NSM`],[1810,1839,`AL`],[1840,1866,`NSM`],[1867,1957,`AL`],[1958,1968,`NSM`],[1969,1983,`AL`],[1984,2026,`R`],[2027,2035,`NSM`],[2036,2037,`R`],[2038,2041,`ON`],[2042,2044,`R`],[2045,2045,`NSM`],[2046,2069,`R`],[2070,2073,`NSM`],[2074,2074,`R`],[2075,2083,`NSM`],[2084,2084,`R`],[2085,2087,`NSM`],[2088,2088,`R`],[2089,2093,`NSM`],[2094,2136,`R`],[2137,2139,`NSM`],[2140,2143,`R`],[2144,2191,`AL`],[2192,2193,`AN`],[2194,2198,`AL`],[2199,2207,`NSM`],[2208,2249,`AL`],[2250,2273,`NSM`],[2274,2274,`AN`],[2275,2306,`NSM`],[2362,2362,`NSM`],[2364,2364,`NSM`],[2369,2376,`NSM`],[2381,2381,`NSM`],[2385,2391,`NSM`],[2402,2403,`NSM`],[2433,2433,`NSM`],[2492,2492,`NSM`],[2497,2500,`NSM`],[2509,2509,`NSM`],[2530,2531,`NSM`],[2546,2547,`ET`],[2555,2555,`ET`],[2558,2558,`NSM`],[2561,2562,`NSM`],[2620,2620,`NSM`],[2625,2626,`NSM`],[2631,2632,`NSM`],[2635,2637,`NSM`],[2641,2641,`NSM`],[2672,2673,`NSM`],[2677,2677,`NSM`],[2689,2690,`NSM`],[2748,2748,`NSM`],[2753,2757,`NSM`],[2759,2760,`NSM`],[2765,2765,`NSM`],[2786,2787,`NSM`],[2801,2801,`ET`],[2810,2815,`NSM`],[2817,2817,`NSM`],[2876,2876,`NSM`],[2879,2879,`NSM`],[2881,2884,`NSM`],[2893,2893,`NSM`],[2901,2902,`NSM`],[2914,2915,`NSM`],[2946,2946,`NSM`],[3008,3008,`NSM`],[3021,3021,`NSM`],[3059,3064,`ON`],[3065,3065,`ET`],[3066,3066,`ON`],[3072,3072,`NSM`],[3076,3076,`NSM`],[3132,3132,`NSM`],[3134,3136,`NSM`],[3142,3144,`NSM`],[3146,3149,`NSM`],[3157,3158,`NSM`],[3170,3171,`NSM`],[3192,3198,`ON`],[3201,3201,`NSM`],[3260,3260,`NSM`],[3276,3277,`NSM`],[3298,3299,`NSM`],[3328,3329,`NSM`],[3387,3388,`NSM`],[3393,3396,`NSM`],[3405,3405,`NSM`],[3426,3427,`NSM`],[3457,3457,`NSM`],[3530,3530,`NSM`],[3538,3540,`NSM`],[3542,3542,`NSM`],[3633,3633,`NSM`],[3636,3642,`NSM`],[3647,3647,`ET`],[3655,3662,`NSM`],[3761,3761,`NSM`],[3764,3772,`NSM`],[3784,3790,`NSM`],[3864,3865,`NSM`],[3893,3893,`NSM`],[3895,3895,`NSM`],[3897,3897,`NSM`],[3898,3901,`ON`],[3953,3966,`NSM`],[3968,3972,`NSM`],[3974,3975,`NSM`],[3981,3991,`NSM`],[3993,4028,`NSM`],[4038,4038,`NSM`],[4141,4144,`NSM`],[4146,4151,`NSM`],[4153,4154,`NSM`],[4157,4158,`NSM`],[4184,4185,`NSM`],[4190,4192,`NSM`],[4209,4212,`NSM`],[4226,4226,`NSM`],[4229,4230,`NSM`],[4237,4237,`NSM`],[4253,4253,`NSM`],[4957,4959,`NSM`],[5008,5017,`ON`],[5120,5120,`ON`],[5760,5760,`WS`],[5787,5788,`ON`],[5906,5908,`NSM`],[5938,5939,`NSM`],[5970,5971,`NSM`],[6002,6003,`NSM`],[6068,6069,`NSM`],[6071,6077,`NSM`],[6086,6086,`NSM`],[6089,6099,`NSM`],[6107,6107,`ET`],[6109,6109,`NSM`],[6128,6137,`ON`],[6144,6154,`ON`],[6155,6157,`NSM`],[6158,6158,`BN`],[6159,6159,`NSM`],[6277,6278,`NSM`],[6313,6313,`NSM`],[6432,6434,`NSM`],[6439,6440,`NSM`],[6450,6450,`NSM`],[6457,6459,`NSM`],[6464,6464,`ON`],[6468,6469,`ON`],[6622,6655,`ON`],[6679,6680,`NSM`],[6683,6683,`NSM`],[6742,6742,`NSM`],[6744,6750,`NSM`],[6752,6752,`NSM`],[6754,6754,`NSM`],[6757,6764,`NSM`],[6771,6780,`NSM`],[6783,6783,`NSM`],[6832,6877,`NSM`],[6880,6891,`NSM`],[6912,6915,`NSM`],[6964,6964,`NSM`],[6966,6970,`NSM`],[6972,6972,`NSM`],[6978,6978,`NSM`],[7019,7027,`NSM`],[7040,7041,`NSM`],[7074,7077,`NSM`],[7080,7081,`NSM`],[7083,7085,`NSM`],[7142,7142,`NSM`],[7144,7145,`NSM`],[7149,7149,`NSM`],[7151,7153,`NSM`],[7212,7219,`NSM`],[7222,7223,`NSM`],[7376,7378,`NSM`],[7380,7392,`NSM`],[7394,7400,`NSM`],[7405,7405,`NSM`],[7412,7412,`NSM`],[7416,7417,`NSM`],[7616,7679,`NSM`],[8125,8125,`ON`],[8127,8129,`ON`],[8141,8143,`ON`],[8157,8159,`ON`],[8173,8175,`ON`],[8189,8190,`ON`],[8192,8202,`WS`],[8203,8205,`BN`],[8207,8207,`R`],[8208,8231,`ON`],[8232,8232,`WS`],[8233,8233,`B`],[8234,8238,`BN`],[8239,8239,`CS`],[8240,8244,`ET`],[8245,8259,`ON`],[8260,8260,`CS`],[8261,8286,`ON`],[8287,8287,`WS`],[8288,8303,`BN`],[8304,8304,`EN`],[8308,8313,`EN`],[8314,8315,`ES`],[8316,8318,`ON`],[8320,8329,`EN`],[8330,8331,`ES`],[8332,8334,`ON`],[8352,8399,`ET`],[8400,8432,`NSM`],[8448,8449,`ON`],[8451,8454,`ON`],[8456,8457,`ON`],[8468,8468,`ON`],[8470,8472,`ON`],[8478,8483,`ON`],[8485,8485,`ON`],[8487,8487,`ON`],[8489,8489,`ON`],[8494,8494,`ET`],[8506,8507,`ON`],[8512,8516,`ON`],[8522,8525,`ON`],[8528,8543,`ON`],[8585,8587,`ON`],[8592,8721,`ON`],[8722,8722,`ES`],[8723,8723,`ET`],[8724,9013,`ON`],[9083,9108,`ON`],[9110,9257,`ON`],[9280,9290,`ON`],[9312,9351,`ON`],[9352,9371,`EN`],[9450,9899,`ON`],[9901,10239,`ON`],[10496,11123,`ON`],[11126,11263,`ON`],[11493,11498,`ON`],[11503,11505,`NSM`],[11513,11519,`ON`],[11647,11647,`NSM`],[11744,11775,`NSM`],[11776,11869,`ON`],[11904,11929,`ON`],[11931,12019,`ON`],[12032,12245,`ON`],[12272,12287,`ON`],[12288,12288,`WS`],[12289,12292,`ON`],[12296,12320,`ON`],[12330,12333,`NSM`],[12336,12336,`ON`],[12342,12343,`ON`],[12349,12351,`ON`],[12441,12442,`NSM`],[12443,12444,`ON`],[12448,12448,`ON`],[12539,12539,`ON`],[12736,12773,`ON`],[12783,12783,`ON`],[12829,12830,`ON`],[12880,12895,`ON`],[12924,12926,`ON`],[12977,12991,`ON`],[13004,13007,`ON`],[13175,13178,`ON`],[13278,13279,`ON`],[13311,13311,`ON`],[19904,19967,`ON`],[42128,42182,`ON`],[42509,42511,`ON`],[42607,42610,`NSM`],[42611,42611,`ON`],[42612,42621,`NSM`],[42622,42623,`ON`],[42654,42655,`NSM`],[42736,42737,`NSM`],[42752,42785,`ON`],[42888,42888,`ON`],[43010,43010,`NSM`],[43014,43014,`NSM`],[43019,43019,`NSM`],[43045,43046,`NSM`],[43048,43051,`ON`],[43052,43052,`NSM`],[43064,43065,`ET`],[43124,43127,`ON`],[43204,43205,`NSM`],[43232,43249,`NSM`],[43263,43263,`NSM`],[43302,43309,`NSM`],[43335,43345,`NSM`],[43392,43394,`NSM`],[43443,43443,`NSM`],[43446,43449,`NSM`],[43452,43453,`NSM`],[43493,43493,`NSM`],[43561,43566,`NSM`],[43569,43570,`NSM`],[43573,43574,`NSM`],[43587,43587,`NSM`],[43596,43596,`NSM`],[43644,43644,`NSM`],[43696,43696,`NSM`],[43698,43700,`NSM`],[43703,43704,`NSM`],[43710,43711,`NSM`],[43713,43713,`NSM`],[43756,43757,`NSM`],[43766,43766,`NSM`],[43882,43883,`ON`],[44005,44005,`NSM`],[44008,44008,`NSM`],[44013,44013,`NSM`],[64285,64285,`R`],[64286,64286,`NSM`],[64287,64296,`R`],[64297,64297,`ES`],[64298,64335,`R`],[64336,64450,`AL`],[64451,64466,`ON`],[64467,64829,`AL`],[64830,64847,`ON`],[64848,64911,`AL`],[64912,64913,`ON`],[64914,64967,`AL`],[64968,64975,`ON`],[64976,65007,`BN`],[65008,65020,`AL`],[65021,65023,`ON`],[65024,65039,`NSM`],[65040,65049,`ON`],[65056,65071,`NSM`],[65072,65103,`ON`],[65104,65104,`CS`],[65105,65105,`ON`],[65106,65106,`CS`],[65108,65108,`ON`],[65109,65109,`CS`],[65110,65118,`ON`],[65119,65119,`ET`],[65120,65121,`ON`],[65122,65123,`ES`],[65124,65126,`ON`],[65128,65128,`ON`],[65129,65130,`ET`],[65131,65131,`ON`],[65136,65278,`AL`],[65279,65279,`BN`],[65281,65282,`ON`],[65283,65285,`ET`],[65286,65290,`ON`],[65291,65291,`ES`],[65292,65292,`CS`],[65293,65293,`ES`],[65294,65295,`CS`],[65296,65305,`EN`],[65306,65306,`CS`],[65307,65312,`ON`],[65339,65344,`ON`],[65371,65381,`ON`],[65504,65505,`ET`],[65506,65508,`ON`],[65509,65510,`ET`],[65512,65518,`ON`],[65520,65528,`BN`],[65529,65533,`ON`],[65534,65535,`BN`],[65793,65793,`ON`],[65856,65932,`ON`],[65936,65948,`ON`],[65952,65952,`ON`],[66045,66045,`NSM`],[66272,66272,`NSM`],[66273,66299,`EN`],[66422,66426,`NSM`],[67584,67870,`R`],[67871,67871,`ON`],[67872,68096,`R`],[68097,68099,`NSM`],[68100,68100,`R`],[68101,68102,`NSM`],[68103,68107,`R`],[68108,68111,`NSM`],[68112,68151,`R`],[68152,68154,`NSM`],[68155,68158,`R`],[68159,68159,`NSM`],[68160,68324,`R`],[68325,68326,`NSM`],[68327,68408,`R`],[68409,68415,`ON`],[68416,68863,`R`],[68864,68899,`AL`],[68900,68903,`NSM`],[68904,68911,`AL`],[68912,68921,`AN`],[68922,68927,`AL`],[68928,68937,`AN`],[68938,68968,`R`],[68969,68973,`NSM`],[68974,68974,`ON`],[68975,69215,`R`],[69216,69246,`AN`],[69247,69290,`R`],[69291,69292,`NSM`],[69293,69311,`R`],[69312,69327,`AL`],[69328,69336,`ON`],[69337,69369,`AL`],[69370,69375,`NSM`],[69376,69423,`R`],[69424,69445,`AL`],[69446,69456,`NSM`],[69457,69487,`AL`],[69488,69505,`R`],[69506,69509,`NSM`],[69510,69631,`R`],[69633,69633,`NSM`],[69688,69702,`NSM`],[69714,69733,`ON`],[69744,69744,`NSM`],[69747,69748,`NSM`],[69759,69761,`NSM`],[69811,69814,`NSM`],[69817,69818,`NSM`],[69826,69826,`NSM`],[69888,69890,`NSM`],[69927,69931,`NSM`],[69933,69940,`NSM`],[70003,70003,`NSM`],[70016,70017,`NSM`],[70070,70078,`NSM`],[70089,70092,`NSM`],[70095,70095,`NSM`],[70191,70193,`NSM`],[70196,70196,`NSM`],[70198,70199,`NSM`],[70206,70206,`NSM`],[70209,70209,`NSM`],[70367,70367,`NSM`],[70371,70378,`NSM`],[70400,70401,`NSM`],[70459,70460,`NSM`],[70464,70464,`NSM`],[70502,70508,`NSM`],[70512,70516,`NSM`],[70587,70592,`NSM`],[70606,70606,`NSM`],[70608,70608,`NSM`],[70610,70610,`NSM`],[70625,70626,`NSM`],[70712,70719,`NSM`],[70722,70724,`NSM`],[70726,70726,`NSM`],[70750,70750,`NSM`],[70835,70840,`NSM`],[70842,70842,`NSM`],[70847,70848,`NSM`],[70850,70851,`NSM`],[71090,71093,`NSM`],[71100,71101,`NSM`],[71103,71104,`NSM`],[71132,71133,`NSM`],[71219,71226,`NSM`],[71229,71229,`NSM`],[71231,71232,`NSM`],[71264,71276,`ON`],[71339,71339,`NSM`],[71341,71341,`NSM`],[71344,71349,`NSM`],[71351,71351,`NSM`],[71453,71453,`NSM`],[71455,71455,`NSM`],[71458,71461,`NSM`],[71463,71467,`NSM`],[71727,71735,`NSM`],[71737,71738,`NSM`],[71995,71996,`NSM`],[71998,71998,`NSM`],[72003,72003,`NSM`],[72148,72151,`NSM`],[72154,72155,`NSM`],[72160,72160,`NSM`],[72193,72198,`NSM`],[72201,72202,`NSM`],[72243,72248,`NSM`],[72251,72254,`NSM`],[72263,72263,`NSM`],[72273,72278,`NSM`],[72281,72283,`NSM`],[72330,72342,`NSM`],[72344,72345,`NSM`],[72544,72544,`NSM`],[72546,72548,`NSM`],[72550,72550,`NSM`],[72752,72758,`NSM`],[72760,72765,`NSM`],[72850,72871,`NSM`],[72874,72880,`NSM`],[72882,72883,`NSM`],[72885,72886,`NSM`],[73009,73014,`NSM`],[73018,73018,`NSM`],[73020,73021,`NSM`],[73023,73029,`NSM`],[73031,73031,`NSM`],[73104,73105,`NSM`],[73109,73109,`NSM`],[73111,73111,`NSM`],[73459,73460,`NSM`],[73472,73473,`NSM`],[73526,73530,`NSM`],[73536,73536,`NSM`],[73538,73538,`NSM`],[73562,73562,`NSM`],[73685,73692,`ON`],[73693,73696,`ET`],[73697,73713,`ON`],[78912,78912,`NSM`],[78919,78933,`NSM`],[90398,90409,`NSM`],[90413,90415,`NSM`],[92912,92916,`NSM`],[92976,92982,`NSM`],[94031,94031,`NSM`],[94095,94098,`NSM`],[94178,94178,`ON`],[94180,94180,`NSM`],[113821,113822,`NSM`],[113824,113827,`BN`],[117760,117973,`ON`],[118e3,118009,`EN`],[118010,118012,`ON`],[118016,118451,`ON`],[118458,118480,`ON`],[118496,118512,`ON`],[118528,118573,`NSM`],[118576,118598,`NSM`],[119143,119145,`NSM`],[119155,119162,`BN`],[119163,119170,`NSM`],[119173,119179,`NSM`],[119210,119213,`NSM`],[119273,119274,`ON`],[119296,119361,`ON`],[119362,119364,`NSM`],[119365,119365,`ON`],[119552,119638,`ON`],[120513,120513,`ON`],[120539,120539,`ON`],[120571,120571,`ON`],[120597,120597,`ON`],[120629,120629,`ON`],[120655,120655,`ON`],[120687,120687,`ON`],[120713,120713,`ON`],[120745,120745,`ON`],[120771,120771,`ON`],[120782,120831,`EN`],[121344,121398,`NSM`],[121403,121452,`NSM`],[121461,121461,`NSM`],[121476,121476,`NSM`],[121499,121503,`NSM`],[121505,121519,`NSM`],[122880,122886,`NSM`],[122888,122904,`NSM`],[122907,122913,`NSM`],[122915,122916,`NSM`],[122918,122922,`NSM`],[123023,123023,`NSM`],[123184,123190,`NSM`],[123566,123566,`NSM`],[123628,123631,`NSM`],[123647,123647,`ET`],[124140,124143,`NSM`],[124398,124399,`NSM`],[124643,124643,`NSM`],[124646,124646,`NSM`],[124654,124655,`NSM`],[124661,124661,`NSM`],[124928,125135,`R`],[125136,125142,`NSM`],[125143,125251,`R`],[125252,125258,`NSM`],[125259,126063,`R`],[126064,126143,`AL`],[126144,126207,`R`],[126208,126287,`AL`],[126288,126463,`R`],[126464,126703,`AL`],[126704,126705,`ON`],[126706,126719,`AL`],[126720,126975,`R`],[126976,127019,`ON`],[127024,127123,`ON`],[127136,127150,`ON`],[127153,127167,`ON`],[127169,127183,`ON`],[127185,127221,`ON`],[127232,127242,`EN`],[127243,127247,`ON`],[127279,127279,`ON`],[127338,127343,`ON`],[127405,127405,`ON`],[127584,127589,`ON`],[127744,128728,`ON`],[128732,128748,`ON`],[128752,128764,`ON`],[128768,128985,`ON`],[128992,129003,`ON`],[129008,129008,`ON`],[129024,129035,`ON`],[129040,129095,`ON`],[129104,129113,`ON`],[129120,129159,`ON`],[129168,129197,`ON`],[129200,129211,`ON`],[129216,129217,`ON`],[129232,129240,`ON`],[129280,129623,`ON`],[129632,129645,`ON`],[129648,129660,`ON`],[129664,129674,`ON`],[129678,129734,`ON`],[129736,129736,`ON`],[129741,129756,`ON`],[129759,129770,`ON`],[129775,129784,`ON`],[129792,129938,`ON`],[129940,130031,`ON`],[130032,130041,`EN`],[130042,130042,`ON`],[131070,131071,`BN`],[196606,196607,`BN`],[262142,262143,`BN`],[327678,327679,`BN`],[393214,393215,`BN`],[458750,458751,`BN`],[524286,524287,`BN`],[589822,589823,`BN`],[655358,655359,`BN`],[720894,720895,`BN`],[786430,786431,`BN`],[851966,851967,`BN`],[917502,917759,`BN`],[917760,917999,`NSM`],[918e3,921599,`BN`],[983038,983039,`BN`],[1048574,1048575,`BN`],[1114110,1114111,`BN`]];function op(e){if(e<=255)return ip[e];let t=0,n=ap.length-1;for(;t<=n;){let r=t+n>>1,i=ap[r];if(e<i[0]){n=r-1;continue}if(e>i[1]){t=r+1;continue}return i[2]}return`L`}function sp(e){let t=e.length;if(t===0)return null;let n=Array(t),r=!1;for(let i=0;i<t;){let a=e.charCodeAt(i),o=a,s=1;if(a>=55296&&a<=56319&&i+1<t){let t=e.charCodeAt(i+1);t>=56320&&t<=57343&&(o=(a-55296<<10)+(t-56320)+65536,s=2)}let c=op(o);(c===`R`||c===`AL`||c===`AN`)&&(r=!0);for(let e=0;e<s;e++)n[i+e]=c;i+=s}if(!r)return null;let i=0;for(let e=0;e<t;e++){let t=n[e];if(t===`L`){i=0;break}if(t===`R`||t===`AL`){i=1;break}}let a=new Int8Array(t);for(let e=0;e<t;e++)a[e]=i;let o=i&1?`R`:`L`,s=o,c=s;for(let e=0;e<t;e++)n[e]===`NSM`?n[e]=c:c=n[e];c=s;for(let e=0;e<t;e++){let t=n[e];t===`EN`?n[e]=c===`AL`?`AN`:`EN`:(t===`R`||t===`L`||t===`AL`)&&(c=t)}for(let e=0;e<t;e++)n[e]===`AL`&&(n[e]=`R`);for(let e=1;e<t-1;e++)n[e]===`ES`&&n[e-1]===`EN`&&n[e+1]===`EN`&&(n[e]=`EN`),n[e]===`CS`&&(n[e-1]===`EN`||n[e-1]===`AN`)&&n[e+1]===n[e-1]&&(n[e]=n[e-1]);for(let e=0;e<t;e++){if(n[e]!==`EN`)continue;let r;for(r=e-1;r>=0&&n[r]===`ET`;r--)n[r]=`EN`;for(r=e+1;r<t&&n[r]===`ET`;r++)n[r]=`EN`}for(let e=0;e<t;e++){let t=n[e];(t===`WS`||t===`ES`||t===`ET`||t===`CS`)&&(n[e]=`ON`)}c=s;for(let e=0;e<t;e++){let t=n[e];t===`EN`?n[e]=c===`L`?`L`:`EN`:(t===`R`||t===`L`)&&(c=t)}for(let e=0;e<t;e++){if(n[e]!==`ON`)continue;let r=e+1;for(;r<t&&n[r]===`ON`;)r++;let i=e>0?n[e-1]:s,a=r<t?n[r]:s,o=i===`L`?`L`:`R`;if(o===(a===`L`?`L`:`R`))for(let t=e;t<r;t++)n[t]=o;e=r-1}for(let e=0;e<t;e++)n[e]===`ON`&&(n[e]=o);for(let e=0;e<t;e++){let t=n[e];a[e]&1?(t===`L`||t===`AN`||t===`EN`)&&a[e]++:t===`R`?a[e]++:(t===`AN`||t===`EN`)&&(a[e]+=2)}return a}function cp(e,t){let n=sp(e);if(n===null)return null;let r=new Int8Array(t.length);for(let e=0;e<t.length;e++)r[e]=n[t[e]];return r}var lp=/[ \t\n\r\f]+/g,up=/[\t\n\r\f]| {2,}|^ | $/;function dp(e){let t=e??`normal`;return t===`pre-wrap`?{mode:t,preserveOrdinarySpaces:!0,preserveHardBreaks:!0}:{mode:t,preserveOrdinarySpaces:!1,preserveHardBreaks:!1}}function fp(e){if(!up.test(e))return e;let t=e.replace(lp,` `);return t.charCodeAt(0)===32&&(t=t.slice(1)),t.length>0&&t.charCodeAt(t.length-1)===32&&(t=t.slice(0,-1)),t}function pp(e){return/[\r\f]/.test(e)?e.replace(/\r\n/g,`
+`).replace(/[\r\f]/g,`
+`):e.replace(/\r\n/g,`
+`)}var mp=null,hp;function gp(){return mp===null&&(mp=new Intl.Segmenter(hp,{granularity:`word`})),mp}var _p=/\p{Script=Arabic}/u,vp=/\p{M}/u,yp=/\p{Nd}/u;function bp(e){return _p.test(e)}function xp(e){return e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=183984&&e<=191471||e>=191472&&e<=192093||e>=194560&&e<=195103||e>=196608&&e<=201551||e>=201552&&e<=205743||e>=205744&&e<=210041||e>=63744&&e<=64255||e>=12288&&e<=12351||e>=12352&&e<=12447||e>=12448&&e<=12543||e>=44032&&e<=55215||e>=65280&&e<=65519}function Sp(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(!(n<12288)){if(n>=55296&&n<=56319&&t+1<e.length){let r=e.charCodeAt(t+1);if(r>=56320&&r<=57343){if(xp((n-55296<<10)+(r-56320)+65536))return!0;t++;continue}}if(xp(n))return!0}}return!1}function Cp(e){let t=Bp(e);return t!==null&&(Op.has(t)||jp.has(t))}var wp=new Set([`\xA0`,` `,`⁠`,``]);function Tp(e){return Sp(e)}function Ep(e){let t=Bp(e);return t!==null&&wp.has(t)}function Dp(e){return!Cp(e)&&!Ep(e)}var Op=new Set(`,...!.:.;.?.、.。.・.).〕.〉.》.」.』.】.〗.〙.〛.ー.々.〻.ゝ.ゞ.ヽ.ヾ`.split(`.`)),kp=new Set([`"`,`(`,`[`,`{`,`“`,`‘`,`«`,`‹`,`(`,`〔`,`〈`,`《`,`「`,`『`,`【`,`〖`,`〘`,`〚`]),Ap=new Set([`'`,`’`]),jp=new Set(`.(,(!(?(:(;(،(؛(؟(।(॥(၊(။(၌(၍(၏()(](}(%("(”(’(»(›(…`.split(`(`)),Mp=new Set([`:`,`.`,`،`,`؛`]),Np=new Set([`၏`]),Pp=new Set([`”`,`’`,`»`,`›`,`」`,`』`,`】`,`》`,`〉`,`〕`,`)`]);function Fp(e){if(Rp(e))return!0;let t=!1;for(let n of e){if(jp.has(n)){t=!0;continue}if(!(t&&vp.test(n)))return!1}return t}function Ip(e){for(let t of e)if(!Op.has(t)&&!jp.has(t))return!1;return e.length>0}function Lp(e){if(Rp(e))return!0;for(let t of e)if(!kp.has(t)&&!Ap.has(t)&&!vp.test(t))return!1;return e.length>0}function Rp(e){let t=!1;for(let n of e)if(!(n===`\\`||vp.test(n))){if(kp.has(n)||jp.has(n)||Ap.has(n)){t=!0;continue}return!1}return t}function zp(e,t){let n=t-1;if(n<=0)return Math.max(n,0);let r=e.charCodeAt(n);if(r<56320||r>57343)return n;let i=n-1;if(i<0)return n;let a=e.charCodeAt(i);return a>=55296&&a<=56319?i:n}function Bp(e){if(e.length===0)return null;let t=zp(e,e.length);return e.slice(t)}function Vp(e){let t=Array.from(e),n=t.length;for(;n>0;){let e=t[n-1];if(vp.test(e)){n--;continue}if(kp.has(e)||Ap.has(e)){n--;continue}break}return n<=0||n===t.length?null:{head:t.slice(0,n).join(``),tail:t.slice(n).join(``)}}function Hp(e,t,n){return n===`text`&&!t&&e.length===1&&e!==`-`&&e!==`—`?e:null}function Up(e,t,n,r){let i=t[r],a=e[r];if(i==null)return a;let o=n[r];if(a.length===o)return a;let s=i.repeat(o);return e[r]=s,s}function Wp(e,t){return e&&t!==null&&Mp.has(t)}function Gp(e){let t=Bp(e);return t!==null&&Np.has(t)}function Kp(e){if(e.length<2||e[0]!==` `)return null;let t=e.slice(1);return/^\p{M}+$/u.test(t)?{space:` `,marks:t}:null}function qp(e){let t=e.length;for(;t>0;){let n=zp(e,t),r=e.slice(n,t);if(Pp.has(r))return!0;if(!jp.has(r))return!1;t=n}return!1}function Jp(e,t){if(t.preserveOrdinarySpaces||t.preserveHardBreaks){if(e===` `)return`preserved-space`;if(e===` `)return`tab`;if(t.preserveHardBreaks&&e===`
+`)return`hard-break`}return e===` `?`space`:e===`\xA0`||e===` `||e===`⁠`||e===``?`glue`:e===`​`?`zero-width-break`:e===`­`?`soft-hyphen`:`text`}var Yp=/[\x20\t\n\xA0\xAD\u200B\u202F\u2060\uFEFF]/;function Xp(e){return e.length===1?e[0]:e.join(``)}function Zp(e,t){let n=[];for(let t=e.length-1;t>=0;t--)n.push(e[t]);return n.push(t),Xp(n)}function Qp(e,t,n,r){if(!Yp.test(e))return[{text:e,isWordLike:t,kind:`text`,start:n}];let i=[],a=null,o=[],s=n,c=!1,l=0;for(let u of e){let e=Jp(u,r),d=e===`text`&&t;if(a!==null&&e===a&&d===c){o.push(u),l+=u.length;continue}a!==null&&i.push({text:Xp(o),isWordLike:c,kind:a,start:s}),a=e,o=[u],s=n+l,c=d,l+=u.length}return a!==null&&i.push({text:Xp(o),isWordLike:c,kind:a,start:s}),i}function $p(e){return e===`space`||e===`preserved-space`||e===`zero-width-break`||e===`hard-break`}var em=/^[A-Za-z][A-Za-z0-9+.-]*:$/;function tm(e,t){let n=e.texts[t];return n.startsWith(`www.`)?!0:em.test(n)&&t+1<e.len&&e.kinds[t+1]===`text`&&e.texts[t+1]===`//`}function nm(e){return e.includes(`?`)&&(e.includes(`://`)||e.startsWith(`www.`))}function rm(e){let t=e.texts.slice(),n=e.isWordLike.slice(),r=e.kinds.slice(),i=e.starts.slice();for(let i=0;i<e.len;i++){if(r[i]!==`text`||!tm(e,i))continue;let a=[t[i]],o=i+1;for(;o<e.len&&!$p(r[o]);){a.push(t[o]),n[i]=!0;let e=t[o].includes(`?`);if(r[o]=`text`,t[o]=``,o++,e)break}t[i]=Xp(a)}let a=0;for(let e=0;e<t.length;e++){let o=t[e];o.length!==0&&(a!==e&&(t[a]=o,n[a]=n[e],r[a]=r[e],i[a]=i[e]),a++)}return t.length=a,n.length=a,r.length=a,i.length=a,{len:a,texts:t,isWordLike:n,kinds:r,starts:i}}function im(e){let t=[],n=[],r=[],i=[];for(let a=0;a<e.len;a++){let o=e.texts[a];if(t.push(o),n.push(e.isWordLike[a]),r.push(e.kinds[a]),i.push(e.starts[a]),!nm(o))continue;let s=a+1;if(s>=e.len||$p(e.kinds[s]))continue;let c=[],l=e.starts[s],u=s;for(;u<e.len&&!$p(e.kinds[u]);)c.push(e.texts[u]),u++;c.length>0&&(t.push(Xp(c)),n.push(!0),r.push(`text`),i.push(l),a=u-1)}return{len:t.length,texts:t,isWordLike:n,kinds:r,starts:i}}var am=new Set([`:`,`-`,`/`,`×`,`,`,`.`,`+`,`–`,`—`]),om=/^[A-Za-z0-9_]+[,:;]*$/,sm=/[,:;]+$/;function cm(e){for(let t of e)if(yp.test(t))return!0;return!1}function lm(e){if(e.length===0)return!1;for(let t of e)if(!(yp.test(t)||am.has(t)))return!1;return!0}function um(e){let t=[],n=[],r=[],i=[];for(let a=0;a<e.len;a++){let o=e.texts[a],s=e.kinds[a];if(s===`text`&&lm(o)&&cm(o)){let s=[o],c=a+1;for(;c<e.len&&e.kinds[c]===`text`&&lm(e.texts[c]);)s.push(e.texts[c]),c++;t.push(Xp(s)),n.push(!0),r.push(`text`),i.push(e.starts[a]),a=c-1;continue}t.push(o),n.push(e.isWordLike[a]),r.push(s),i.push(e.starts[a])}return{len:t.length,texts:t,isWordLike:n,kinds:r,starts:i}}function dm(e){let t=[],n=[],r=[],i=[];for(let a=0;a<e.len;a++){let o=e.texts[a],s=e.kinds[a],c=e.isWordLike[a];if(s===`text`&&c&&om.test(o)){let s=[o],c=sm.test(o),l=a+1;for(;c&&l<e.len&&e.kinds[l]===`text`&&e.isWordLike[l]&&om.test(e.texts[l]);){let t=e.texts[l];s.push(t),c=sm.test(t),l++}t.push(Xp(s)),n.push(!0),r.push(`text`),i.push(e.starts[a]),a=l-1;continue}t.push(o),n.push(c),r.push(s),i.push(e.starts[a])}return{len:t.length,texts:t,isWordLike:n,kinds:r,starts:i}}function fm(e){let t=[],n=[],r=[],i=[];for(let a=0;a<e.len;a++){let o=e.texts[a];if(e.kinds[a]===`text`&&o.includes(`-`)){let s=o.split(`-`),c=s.length>1;for(let e=0;e<s.length;e++){let t=s[e];if(!c)break;(t.length===0||!cm(t)||!lm(t))&&(c=!1)}if(c){let o=0;for(let c=0;c<s.length;c++){let l=s[c],u=c<s.length-1?`${l}-`:l;t.push(u),n.push(!0),r.push(`text`),i.push(e.starts[a]+o),o+=u.length}continue}}t.push(o),n.push(e.isWordLike[a]),r.push(e.kinds[a]),i.push(e.starts[a])}return{len:t.length,texts:t,isWordLike:n,kinds:r,starts:i}}function pm(e){let t=[],n=[],r=[],i=[],a=0;for(;a<e.len;){let o=[e.texts[a]],s=e.isWordLike[a],c=e.kinds[a],l=e.starts[a];if(c===`glue`){let u=[o[0]],d=l;for(a++;a<e.len&&e.kinds[a]===`glue`;)u.push(e.texts[a]),a++;let f=Xp(u);if(a<e.len&&e.kinds[a]===`text`)o[0]=f,o.push(e.texts[a]),s=e.isWordLike[a],c=`text`,l=d,a++;else{t.push(f),n.push(!1),r.push(`glue`),i.push(d);continue}}else a++;if(c===`text`)for(;a<e.len&&e.kinds[a]===`glue`;){let t=[];for(;a<e.len&&e.kinds[a]===`glue`;)t.push(e.texts[a]),a++;let n=Xp(t);if(a<e.len&&e.kinds[a]===`text`){o.push(n,e.texts[a]),s||=e.isWordLike[a],a++;continue}o.push(n)}t.push(Xp(o)),n.push(s),r.push(c),i.push(l)}return{len:t.length,texts:t,isWordLike:n,kinds:r,starts:i}}function mm(e){let t=e.texts.slice(),n=e.isWordLike.slice(),r=e.kinds.slice(),i=e.starts.slice();for(let e=0;e<t.length-1;e++){if(r[e]!==`text`||r[e+1]!==`text`||!Sp(t[e])||!Sp(t[e+1]))continue;let n=Vp(t[e]);n!==null&&(t[e]=n.head,t[e+1]=n.tail+t[e+1],i[e+1]=i[e]+n.head.length)}return{len:t.length,texts:t,isWordLike:n,kinds:r,starts:i}}function hm(e,t,n){let r=gp(),i=0,a=[],o=[],s=[],c=[],l=[],u=[],d=[],f=[],p=[],m=[],h=[],g=[];for(let v of r.segment(e))for(let e of Qp(v.segment,v.isWordLike??!1,v.index,n)){let n=e.kind===`text`,r=Hp(e.text,e.isWordLike,e.kind),v=Sp(e.text),y=bp(e.text),b=Bp(e.text),x=qp(e.text),S=Gp(e.text),C=i-1;function _(){u[C]!==null&&(o[C]=[Up(a,u,d,C)],u[C]=null),o[C].push(e.text),s[C]=s[C]||e.isWordLike,f[C]=f[C]||v,p[C]=p[C]||y,m[C]=x,h[C]=S,g[C]=Wp(p[C],b)}t.carryCJKAfterClosingQuote&&n&&i>0&&c[C]===`text`&&v&&f[C]&&m[C]||n&&i>0&&c[C]===`text`&&Ip(e.text)&&f[C]||n&&i>0&&c[C]===`text`&&h[C]?_():n&&i>0&&c[C]===`text`&&e.isWordLike&&y&&g[C]?(_(),s[C]=!0):r!==null&&i>0&&c[C]===`text`&&u[C]===r?d[C]=(d[C]??1)+1:n&&!e.isWordLike&&i>0&&c[C]===`text`&&(Fp(e.text)||e.text===`-`&&s[C])?_():(a[i]=e.text,o[i]=[e.text],s[i]=e.isWordLike,c[i]=e.kind,l[i]=e.start,u[i]=r,d[i]=r===null?0:1,f[i]=v,p[i]=y,m[i]=x,h[i]=S,g[i]=Wp(y,b),i++)}for(let e=0;e<i;e++){if(u[e]!==null){a[e]=Up(a,u,d,e);continue}a[e]=Xp(o[e])}for(let e=1;e<i;e++)c[e]===`text`&&!s[e]&&Rp(a[e])&&c[e-1]===`text`&&(a[e-1]+=a[e],s[e-1]=s[e-1]||s[e],a[e]=``);let v=Array.from({length:i},()=>null),y=-1;for(let e=i-1;e>=0;e--){let t=a[e];if(t.length!==0){if(c[e]===`text`&&!s[e]&&Lp(t)&&y>=0&&c[y]===`text`){let n=v[y]??[];n.push(t),v[y]=n,l[y]=l[e],a[e]=``;continue}y=e}}for(let e=0;e<i;e++){let t=v[e];t!=null&&(a[e]=Zp(t,a[e]))}let b=0;for(let e=0;e<i;e++){let t=a[e];t.length!==0&&(b!==e&&(a[b]=t,s[b]=s[e],c[b]=c[e],l[b]=l[e]),b++)}a.length=b,s.length=b,c.length=b,l.length=b;let x=mm(dm(fm(um(im(rm(pm({len:b,texts:a,isWordLike:s,kinds:c,starts:l})))))));for(let e=0;e<x.len-1;e++){let t=Kp(x.texts[e]);t!==null&&(x.kinds[e]!==`space`&&x.kinds[e]!==`preserved-space`||x.kinds[e+1]!==`text`||!bp(x.texts[e+1])||(x.texts[e]=t.space,x.isWordLike[e]=!1,x.kinds[e]=x.kinds[e]===`preserved-space`?`preserved-space`:`space`,x.texts[e+1]=t.marks+x.texts[e+1],x.starts[e+1]=x.starts[e]+t.space.length))}return x}function gm(e,t){if(e.len===0)return[];if(!t.preserveHardBreaks)return[{startSegmentIndex:0,endSegmentIndex:e.len,consumedEndSegmentIndex:e.len}];let n=[],r=0;for(let t=0;t<e.len;t++)e.kinds[t]===`hard-break`&&(n.push({startSegmentIndex:r,endSegmentIndex:t,consumedEndSegmentIndex:t+1}),r=t+1);return r<e.len&&n.push({startSegmentIndex:r,endSegmentIndex:e.len,consumedEndSegmentIndex:e.len}),n}function _m(e){if(e.len<=1)return e;let t=[],n=[],r=[],i=[],a=null,o=!1,s=0,c=!1,l=!1;function u(){a!==null&&(t.push(Xp(a)),n.push(o),r.push(`text`),i.push(s),a=null)}for(let d=0;d<e.len;d++){let f=e.texts[d],p=e.kinds[d],m=e.isWordLike[d],h=e.starts[d];if(p===`text`){let e=Tp(f),t=Dp(f);if(a!==null&&c&&l){a.push(f),o||=m,c||=e,l=t;continue}u(),a=[f],o=m,s=h,c=e,l=t;continue}u(),t.push(f),n.push(m),r.push(p),i.push(h)}return u(),{len:t.length,texts:t,isWordLike:n,kinds:r,starts:i}}function vm(e,t,n=`normal`,r=`normal`){let i=dp(n),a=i.mode===`pre-wrap`?pp(e):fp(e);if(a.length===0)return{normalized:a,chunks:[],len:0,texts:[],isWordLike:[],kinds:[],starts:[]};let o=r===`keep-all`?_m(hm(a,t,i)):hm(a,t,i);return{normalized:a,chunks:gm(o,i),...o}}var ym=null,bm=new Map,xm=null,Sm=96,Cm=/\p{Emoji_Presentation}/u,wm=/[\p{Emoji_Presentation}\p{Extended_Pictographic}\p{Regional_Indicator}\uFE0F\u20E3]/u,Tm=null,Em=new Map;function Dm(){if(ym!==null)return ym;if(typeof OffscreenCanvas<`u`)return ym=new OffscreenCanvas(1,1).getContext(`2d`),ym;if(typeof document<`u`)return ym=document.createElement(`canvas`).getContext(`2d`),ym;throw Error(`Text measurement requires OffscreenCanvas or a DOM canvas context.`)}function Om(e){let t=bm.get(e);return t||(t=new Map,bm.set(e,t)),t}function km(e,t){let n=t.get(e);return n===void 0&&(n={width:Dm().measureText(e).width,containsCJK:Sp(e)},t.set(e,n)),n}function Am(){if(xm!==null)return xm;if(typeof navigator>`u`)return xm={lineFitEpsilon:.005,carryCJKAfterClosingQuote:!1,preferPrefixWidthsForBreakableRuns:!1,preferEarlySoftHyphenBreak:!1},xm;let e=navigator.userAgent,t=navigator.vendor===`Apple Computer, Inc.`&&e.includes(`Safari/`)&&!e.includes(`Chrome/`)&&!e.includes(`Chromium/`)&&!e.includes(`CriOS/`)&&!e.includes(`FxiOS/`)&&!e.includes(`EdgiOS/`),n=e.includes(`Chrome/`)||e.includes(`Chromium/`)||e.includes(`CriOS/`)||e.includes(`Edg/`);return xm={lineFitEpsilon:t?1/64:.005,carryCJKAfterClosingQuote:n,preferPrefixWidthsForBreakableRuns:t,preferEarlySoftHyphenBreak:t},xm}function jm(e){let t=e.match(/(\d+(?:\.\d+)?)\s*px/);return t?parseFloat(t[1]):16}function Mm(){return Tm===null&&(Tm=new Intl.Segmenter(void 0,{granularity:`grapheme`})),Tm}function Nm(e){return Cm.test(e)||e.includes(`️`)}function Pm(e){return wm.test(e)}function Fm(e,t){let n=Em.get(e);if(n!==void 0)return n;let r=Dm();r.font=e;let i=r.measureText(`😀`).width;if(n=0,i>t+.5&&typeof document<`u`&&document.body!==null){let t=document.createElement(`span`);t.style.font=e,t.style.display=`inline-block`,t.style.visibility=`hidden`,t.style.position=`absolute`,t.textContent=`😀`,document.body.appendChild(t);let r=t.getBoundingClientRect().width;document.body.removeChild(t),i-r>.5&&(n=i-r)}return Em.set(e,n),n}function Im(e){let t=0,n=Mm();for(let r of n.segment(e))Nm(r.segment)&&t++;return t}function Lm(e,t){return t.emojiCount===void 0&&(t.emojiCount=Im(e)),t.emojiCount}function Rm(e,t,n){return n===0?t.width:t.width-Lm(e,t)*n}function zm(e,t,n,r,i){if(t.breakableFitAdvances!==void 0)return t.breakableFitAdvances;let a=Mm(),o=[];for(let t of a.segment(e))o.push(t.segment);if(o.length<=1)return t.breakableFitAdvances=null,t.breakableFitAdvances;if(i===`sum-graphemes`){let e=[];for(let t of o){let i=km(t,n);e.push(Rm(t,i,r))}return t.breakableFitAdvances=e,t.breakableFitAdvances}if(i===`pair-context`||o.length>Sm){let e=[],i=null,a=0;for(let t of o){let o=Rm(t,km(t,n),r);if(i===null)e.push(o);else{let o=i+t,s=km(o,n);e.push(Rm(o,s,r)-a)}i=t,a=o}return t.breakableFitAdvances=e,t.breakableFitAdvances}let s=[],c=``,l=0;for(let e of o){c+=e;let t=km(c,n),i=Rm(c,t,r);s.push(i-l),l=i}return t.breakableFitAdvances=s,t.breakableFitAdvances}function Bm(e,t){let n=Dm();n.font=e;let r=Om(e),i=jm(e);return{cache:r,fontSize:i,emojiCorrection:t?Fm(e,i):0}}function Vm(e,t){for(;t<e.widths.length;){let n=e.kinds[t];if(n!==`space`&&n!==`zero-width-break`&&n!==`soft-hyphen`)break;t++}return t}function Hm(e,t){if(t<=0)return 0;let n=e%t;return Math.abs(n)<=1e-6?t:t-n}function Um(e,t,n,r,i){let a=0,o=t;for(;a<e.length;){let t=o+e[a];if((a+1<e.length?t+i:t)>n+r)break;o=t,a++}return{fitCount:a,fittedWidth:o}}function Wm(e,t){let n=0,r=e.chunks.length;for(;n<r;){let i=Math.floor((n+r)/2);t<e.chunks[i].consumedEndSegmentIndex?r=i:n=i+1}return n<e.chunks.length?n:-1}function Gm(e,t,n){let r=n.segmentIndex;if(n.graphemeIndex>0)return t;let i=e.chunks[t];if(i.startSegmentIndex===i.endSegmentIndex&&r===i.startSegmentIndex)return n.segmentIndex=r,n.graphemeIndex=0,t;for(r<i.startSegmentIndex&&(r=i.startSegmentIndex);r<i.endSegmentIndex;){let i=e.kinds[r];if(i!==`space`&&i!==`zero-width-break`&&i!==`soft-hyphen`)return n.segmentIndex=r,n.graphemeIndex=0,t;r++}return i.consumedEndSegmentIndex>=e.widths.length?-1:(n.segmentIndex=i.consumedEndSegmentIndex,n.graphemeIndex=0,t+1)}function Km(e,t){if(t.segmentIndex>=e.widths.length)return-1;let n=Wm(e,t.segmentIndex);return n<0?-1:Gm(e,n,t)}function qm(e,t,n){if(n.segmentIndex>=e.widths.length)return-1;let r=t;for(;r<e.chunks.length&&n.segmentIndex>=e.chunks[r].consumedEndSegmentIndex;)r++;return r>=e.chunks.length?-1:Gm(e,r,n)}function Jm(e,t){return e.simpleLineWalkFastPath?Ym(e,t):Xm(e,t)}function Ym(e,t,n){let{widths:r,kinds:i,breakableFitAdvances:a}=e;if(r.length===0)return 0;let o=t+Am().lineFitEpsilon,s=0,c=0,l=!1,u=0,d=0,f=0,p=0,m=-1,h=0;function g(){m=-1,h=0}function _(e=f,t=p,r=c){s++,n?.({startSegmentIndex:u,startGraphemeIndex:d,endSegmentIndex:e,endGraphemeIndex:t,width:r}),c=0,l=!1,g()}function v(e,t){l=!0,u=e,d=0,f=e+1,p=0,c=t}function y(e,t,n){l=!0,u=e,d=t,f=e,p=t+1,c=n}function b(e,t){if(!l){v(e,t);return}c+=t,f=e+1,p=0}function x(e,t){let n=a[e];for(let r=t;r<n.length;r++){let t=n[r];l?c+t>o?(_(),y(e,r,t)):(c+=t,f=e,p=r+1):y(e,r,t)}l&&f===e&&p===n.length&&(f=e+1,p=0)}let S=0;for(;S<r.length&&!(!l&&(S=Vm(e,S),S>=r.length));){let e=r[S],n=i[S],s=n===`space`||n===`preserved-space`||n===`tab`||n===`zero-width-break`||n===`soft-hyphen`;if(!l){e>t&&a[S]!==null?x(S,0):v(S,e),s&&(m=S+1,h=c-e),S++;continue}if(c+e>o){if(s){b(S,e),_(S+1,0,c-e),S++;continue}if(m>=0){if(f>m||f===m&&p>0){_();continue}_(m,0,h);continue}if(e>t&&a[S]!==null){_(),x(S,0),S++;continue}_();continue}b(S,e),s&&(m=S+1,h=c-e),S++}return l&&_(),s}function Xm(e,t,n){if(e.simpleLineWalkFastPath)return Ym(e,t,n);let{widths:r,lineEndFitAdvances:i,lineEndPaintAdvances:a,kinds:o,breakableFitAdvances:s,discretionaryHyphenWidth:c,tabStopAdvance:l,chunks:u}=e;if(r.length===0||u.length===0)return 0;let d=Am(),f=d.lineFitEpsilon,p=t+f,m=0,h=0,g=!1,_=0,v=0,y=0,b=0,x=-1,S=0,C=0,w=null;function T(){x=-1,S=0,C=0,w=null}function E(e=y,t=b,r=h){m++,n?.({startSegmentIndex:_,startGraphemeIndex:v,endSegmentIndex:e,endGraphemeIndex:t,width:r}),h=0,g=!1,T()}function D(e,t){g=!0,_=e,v=0,y=e+1,b=0,h=t}function O(e,t,n){g=!0,_=e,v=t,y=e,b=t+1,h=n}function k(e,t){if(!g){D(e,t);return}h+=t,y=e+1,b=0}function ee(e,t,n,r){if(!t)return;let o=e===`tab`?0:i[n],s=e===`tab`?r:a[n];x=n+1,S=h-r+o,C=h-r+s,w=e}function te(e,t){let n=s[e];for(let r=t;r<n.length;r++){let t=n[r];g?h+t>p?(E(),O(e,r,t)):(h+=t,y=e,b=r+1):O(e,r,t)}g&&y===e&&b===n.length&&(y=e+1,b=0)}function ne(e){if(w!==`soft-hyphen`)return!1;let n=s[e];if(n==null)return!1;let{fitCount:r,fittedWidth:i}=Um(n,h,t,f,c);return r===0?!1:(h=i,y=e,b=r,T(),r===n.length?(y=e+1,b=0,!0):(E(e,r,i+c),te(e,r),!0))}function re(e){m++,n?.({startSegmentIndex:e.startSegmentIndex,startGraphemeIndex:0,endSegmentIndex:e.consumedEndSegmentIndex,endGraphemeIndex:0,width:0}),T()}for(let e=0;e<u.length;e++){let n=u[e];if(n.startSegmentIndex===n.endSegmentIndex){re(n);continue}g=!1,h=0,_=n.startSegmentIndex,v=0,y=n.startSegmentIndex,b=0,T();let f=n.startSegmentIndex;for(;f<n.endSegmentIndex;){let e=o[f],n=e===`space`||e===`preserved-space`||e===`tab`||e===`zero-width-break`||e===`soft-hyphen`,u=e===`tab`?Hm(h,l):r[f];if(e===`soft-hyphen`){g&&(y=f+1,b=0,x=f+1,S=h+c,C=h+c,w=e),f++;continue}if(!g){u>t&&s[f]!==null?te(f,0):D(f,u),ee(e,n,f,u),f++;continue}if(h+u>p){let r=h+(e===`tab`?0:i[f]),o=h+(e===`tab`?u:a[f]);if(w===`soft-hyphen`&&d.preferEarlySoftHyphenBreak&&S<=p){E(x,0,C);continue}if(w===`soft-hyphen`&&ne(f)){f++;continue}if(n&&r<=p){k(f,u),E(f+1,0,o),f++;continue}if(x>=0&&S<=p){if(y>x||y===x&&b>0){E();continue}let e=x;E(e,0,C),f=e;continue}if(u>t&&s[f]!==null){E(),te(f,0),f++;continue}E();continue}k(f,u),ee(e,n,f,u),f++}if(g){let e=x===n.consumedEndSegmentIndex?C:h;E(n.consumedEndSegmentIndex,0,e)}}return m}function Zm(e,t,n,r){let i=e.chunks[n];if(i.startSegmentIndex===i.endSegmentIndex)return t.segmentIndex=i.consumedEndSegmentIndex,t.graphemeIndex=0,0;let{widths:a,lineEndFitAdvances:o,lineEndPaintAdvances:s,kinds:c,breakableFitAdvances:l,discretionaryHyphenWidth:u,tabStopAdvance:d}=e,f=Am(),p=f.lineFitEpsilon,m=r+p,h=0,g=!1,_=t.segmentIndex,v=t.graphemeIndex,y=-1,b=0,x=0,S=null;function C(){y=-1,b=0,x=0,S=null}function w(e=_,n=v,r=h){return g?(t.segmentIndex=e,t.graphemeIndex=n,r):null}function T(e,t){g=!0,_=e+1,v=0,h=t}function E(e,t,n){g=!0,_=e,v=t+1,h=n}function D(e,t){if(!g){T(e,t);return}h+=t,_=e+1,v=0}function O(e,t,n,r){if(!t)return;let i=e===`tab`?0:o[n],a=e===`tab`?r:s[n];y=n+1,b=h-r+i,x=h-r+a,S=e}function k(e,t){let n=l[e];for(let r=t;r<n.length;r++){let t=n[r];if(!g)E(e,r,t);else{if(h+t>m)return w();h+=t,_=e,v=r+1}}return g&&_===e&&v===n.length&&(_=e+1,v=0),null}function ee(e){if(S!==`soft-hyphen`||y<0)return null;let t=l[e]??null;if(t!==null){let{fitCount:n,fittedWidth:i}=Um(t,h,r,p,u);if(n===t.length)return h=i,_=e+1,v=0,C(),null;if(n>0)return w(e,n,i+u)}return b<=m?w(y,0,x):null}for(let e=t.segmentIndex;e<i.endSegmentIndex;e++){let n=c[e],i=n===`space`||n===`preserved-space`||n===`tab`||n===`zero-width-break`||n===`soft-hyphen`,p=e===t.segmentIndex?t.graphemeIndex:0,C=n===`tab`?Hm(h,d):a[e];if(n===`soft-hyphen`&&p===0){g&&(_=e+1,v=0,y=e+1,b=h+u,x=h+u,S=n);continue}if(!g){if(p>0){let t=k(e,p);if(t!==null)return t}else if(C>r&&l[e]!==null){let t=k(e,0);if(t!==null)return t}else T(e,C);O(n,i,e,C);continue}if(h+C>m){let t=h+(n===`tab`?0:o[e]),a=h+(n===`tab`?C:s[e]);if(S===`soft-hyphen`&&f.preferEarlySoftHyphenBreak&&b<=m)return w(y,0,x);let c=ee(e);if(c!==null)return c;if(i&&t<=m)return D(e,C),w(e+1,0,a);if(y>=0&&b<=m)return _>y||_===y&&v>0?w():w(y,0,x);if(C>r&&l[e]!==null){let t=w();if(t!==null)return t;let n=k(e,0);if(n!==null)return n}return w()}D(e,C),O(n,i,e,C)}return y===i.consumedEndSegmentIndex&&v===0?w(i.consumedEndSegmentIndex,0,x):w(i.consumedEndSegmentIndex,0,h)}function Qm(e,t,n){let{widths:r,kinds:i,breakableFitAdvances:a}=e,o=n+Am().lineFitEpsilon,s=0,c=!1,l=t.segmentIndex,u=t.graphemeIndex,d=-1,f=0;for(let e=t.segmentIndex;e<r.length;e++){let p=r[e],m=i[e],h=m===`space`||m===`preserved-space`||m===`tab`||m===`zero-width-break`||m===`soft-hyphen`,g=e===t.segmentIndex?t.graphemeIndex:0,_=a[e];if(!c){if(g>0||p>n&&_!==null){let n=_,r=n[g];c=!0,s=r,l=e,u=g+1;for(let r=g+1;r<n.length;r++){let i=n[r];if(s+i>o)return t.segmentIndex=l,t.graphemeIndex=u,s;s+=i,l=e,u=r+1}l===e&&u===n.length&&(l=e+1,u=0)}else c=!0,s=p,l=e+1,u=0;h&&(d=e+1,f=s-p);continue}if(s+p>o)return h?(t.segmentIndex=e+1,t.graphemeIndex=0,s):d>=0?l>d||l===d&&u>0?(t.segmentIndex=l,t.graphemeIndex=u,s):(t.segmentIndex=d,t.graphemeIndex=0,f):(t.segmentIndex=l,t.graphemeIndex=u,s);s+=p,l=e+1,u=0,h&&(d=e+1,f=s-p)}return c?(t.segmentIndex=l,t.graphemeIndex=u,s):null}function $m(e,t,n){let r={segmentIndex:t.segmentIndex,graphemeIndex:t.graphemeIndex},i=Km(e,r);if(i<0)return null;let a=r.segmentIndex,o=r.graphemeIndex,s=e.simpleLineWalkFastPath?Qm(e,r,n):Zm(e,r,i,n);return s===null?null:{startSegmentIndex:a,startGraphemeIndex:o,endSegmentIndex:r.segmentIndex,endGraphemeIndex:r.graphemeIndex,width:s}}function eh(e,t,n){let r=Km(e,t);return r<0?null:e.simpleLineWalkFastPath?Qm(e,t,n):Zm(e,t,r,n)}function th(e,t){if(e.widths.length===0)return{lineCount:0,maxLineWidth:0};let n={segmentIndex:0,graphemeIndex:0},r=0,i=0;if(!e.simpleLineWalkFastPath){let a=Km(e,n);for(;a>=0;){let o=Zm(e,n,a,t);if(o===null)return{lineCount:r,maxLineWidth:i};r++,o>i&&(i=o),a=qm(e,a,n)}return{lineCount:r,maxLineWidth:i}}for(;;){let a=eh(e,n,t);if(a===null)return{lineCount:r,maxLineWidth:i};r++,a>i&&(i=a)}}var nh=null,rh=new WeakMap;function ih(){return nh===null&&(nh=new Intl.Segmenter(void 0,{granularity:`grapheme`})),nh}function ah(e){return e?{widths:[],lineEndFitAdvances:[],lineEndPaintAdvances:[],kinds:[],simpleLineWalkFastPath:!0,segLevels:null,breakableFitAdvances:[],discretionaryHyphenWidth:0,tabStopAdvance:0,chunks:[],segments:[]}:{widths:[],lineEndFitAdvances:[],lineEndPaintAdvances:[],kinds:[],simpleLineWalkFastPath:!0,segLevels:null,breakableFitAdvances:[],discretionaryHyphenWidth:0,tabStopAdvance:0,chunks:[]}}function oh(e,t){let n=[],r=[],i=0,a=!1,o=!1,s=!1;function c(){r.length!==0&&(n.push({text:r.length===1?r[0]:r.join(``),start:i}),r=[],a=!1,o=!1,s=!1)}function l(e,t,n){r=[e],i=t,a=n,o=qp(e),s=kp.has(e)}function u(e,t){r.push(e),a||=t;let n=qp(e);e.length===1&&jp.has(e)?o||=n:o=n,s=!1}for(let n of ih().segment(e)){let e=n.segment,i=Sp(e);if(r.length===0){l(e,n.index,i);continue}if(s||Op.has(e)||jp.has(e)||t.carryCJKAfterClosingQuote&&i&&o){u(e,i);continue}if(!a&&!i){u(e,i);continue}c(),l(e,n.index,i)}return c(),n}function sh(e){if(e.length<=1)return e;let t=[],n=[e[0].text],r=e[0].start,i=Sp(e[0].text),a=Dp(e[0].text);function o(){t.push({text:n.length===1?n[0]:n.join(``),start:r})}for(let t=1;t<e.length;t++){let s=e[t],c=Sp(s.text),l=Dp(s.text);if(i&&a){n.push(s.text),i||=c,a=l;continue}o(),n=[s.text],r=s.start,i=c,a=l}return o(),t}function ch(e,t,n,r){let i=Am(),{cache:a,emojiCorrection:o}=Bm(t,Pm(e.normalized)),s=Rm(`-`,km(`-`,a),o),c=Rm(` `,km(` `,a),o)*8;if(e.len===0)return ah(n);let l=[],u=[],d=[],f=[],p=e.chunks.length<=1,m=n?[]:null,h=[],g=n?[]:null,_=Array.from({length:e.len});function v(e,t,n,r,i,a,o){i!==`text`&&i!==`space`&&i!==`zero-width-break`&&(p=!1),l.push(t),u.push(n),d.push(r),f.push(i),m?.push(a),h.push(o),g!==null&&g.push(e)}function y(e,t,n,r,s){let c=km(e,a),l=Rm(e,c,o),u=t===`space`||t===`preserved-space`||t===`zero-width-break`?0:l,d=t===`space`||t===`zero-width-break`?0:l;if(s&&r&&e.length>1){let r=`sum-graphemes`;lm(e)?r=`pair-context`:i.preferPrefixWidthsForBreakableRuns&&(r=`segment-prefixes`),v(e,l,u,d,t,n,zm(e,c,a,o,r));return}v(e,l,u,d,t,n,null)}for(let t=0;t<e.len;t++){_[t]=l.length;let n=e.texts[t],o=e.isWordLike[t],c=e.kinds[t],u=e.starts[t];if(c===`soft-hyphen`){v(n,0,s,s,c,u,null);continue}if(c===`hard-break`){v(n,0,0,0,c,u,null);continue}if(c===`tab`){v(n,0,0,0,c,u,null);continue}let d=km(n,a);if(c===`text`&&d.containsCJK){let e=oh(n,i),t=r===`keep-all`?sh(e):e;for(let e=0;e<t.length;e++){let n=t[e];y(n.text,`text`,u+n.start,o,r===`keep-all`||!Sp(n.text))}continue}y(n,c,u,o,!0)}let b=lh(e.chunks,_,l.length),x=m===null?null:cp(e.normalized,m);return g===null?{widths:l,lineEndFitAdvances:u,lineEndPaintAdvances:d,kinds:f,simpleLineWalkFastPath:p,segLevels:x,breakableFitAdvances:h,discretionaryHyphenWidth:s,tabStopAdvance:c,chunks:b}:{widths:l,lineEndFitAdvances:u,lineEndPaintAdvances:d,kinds:f,simpleLineWalkFastPath:p,segLevels:x,breakableFitAdvances:h,discretionaryHyphenWidth:s,tabStopAdvance:c,chunks:b,segments:g}}function lh(e,t,n){let r=[];for(let i=0;i<e.length;i++){let a=e[i],o=a.startSegmentIndex<t.length?t[a.startSegmentIndex]:n,s=a.endSegmentIndex<t.length?t[a.endSegmentIndex]:n,c=a.consumedEndSegmentIndex<t.length?t[a.consumedEndSegmentIndex]:n;r.push({startSegmentIndex:o,endSegmentIndex:s,consumedEndSegmentIndex:c})}return r}function uh(e,t,n,r){let i=r?.wordBreak??`normal`;return ch(vm(e,Am(),r?.whiteSpace,i),t,n,i)}function dh(e,t,n){return uh(e,t,!1,n)}function fh(e,t,n){return uh(e,t,!0,n)}function ph(e){return e}function mh(e,t,n){let r=Jm(ph(e),t);return{lineCount:r,height:r*n}}function hh(e,t,n){let r=n.get(e);if(r!==void 0)return r;r=[];let i=ih();for(let n of i.segment(t[e]))r.push(n.segment);return n.set(e,r),r}function gh(e){let t=rh.get(e);return t===void 0?(t=new Map,rh.set(e,t),t):t}function _h(e,t,n,r){return r>0&&e[r-1]===`soft-hyphen`&&!(t===r&&n>0)}function vh(e,t,n,r,i,a,o){let s=``,c=_h(t,r,i,a);for(let o=r;o<a;o++)t[o]===`soft-hyphen`||t[o]===`hard-break`||(o===r&&i>0?s+=hh(o,e,n).slice(i).join(``):s+=e[o]);return o>0?(c&&(s+=`-`),s+=hh(a,e,n).slice(r===a?i:0,o).join(``)):c&&(s+=`-`),s}function yh(e,t,n,r,i,a,o){return{text:vh(e.segments,e.kinds,t,r,i,a,o),width:n,start:{segmentIndex:r,graphemeIndex:i},end:{segmentIndex:a,graphemeIndex:o}}}function bh(e,t,n){return yh(e,t,n.width,n.startSegmentIndex,n.startGraphemeIndex,n.endSegmentIndex,n.endGraphemeIndex)}function xh(e){return{width:e.width,start:{segmentIndex:e.startSegmentIndex,graphemeIndex:e.startGraphemeIndex},end:{segmentIndex:e.endSegmentIndex,graphemeIndex:e.endGraphemeIndex}}}function Sh(e,t){return yh(e,gh(e),t.width,t.start.segmentIndex,t.start.graphemeIndex,t.end.segmentIndex,t.end.graphemeIndex)}function Ch(e,t,n){return e.widths.length===0?0:Xm(ph(e),t,e=>{n(xh(e))})}function wh(e,t){return th(ph(e),t)}function Th(e){let t=0;return Ch(e,1/0,e=>{e.width>t&&(t=e.width)}),t}function Eh(e,t,n){let r=[];if(e.widths.length===0)return{lineCount:0,height:0,lines:r};let i=gh(e),a=Xm(ph(e),t,t=>{r.push(bh(e,i,t))});return{lineCount:a,height:a*n,lines:r}}var Dh=/[ \t\n\f\r]+/,Oh=/^[ \t\n\f\r]+/,kh=/[ \t\n\f\r]+$/,Ah={segmentIndex:0,graphemeIndex:0},jh={itemIndex:0,segmentIndex:0,graphemeIndex:0};function Mh(e){return e}function Nh(e){return{segmentIndex:e.segmentIndex,graphemeIndex:e.graphemeIndex}}function Ph(e){return e.segmentIndex===0&&e.graphemeIndex===0}function Fh(e,t){let n=t.get(e);if(n!==void 0)return n;let r=Th(fh(`A A`,e)),i=Th(fh(`AA`,e)),a=Math.max(0,r-i);return t.set(e,a),a}function Ih(e){let t=$m(e,Ah,1/0);return t===null?null:{endGraphemeIndex:t.endGraphemeIndex,endSegmentIndex:t.endSegmentIndex,width:t.width}}function Lh(e,t){return e===0&&t>0}function Rh(e){let t=[],n=Array.from({length:e.length}),r=new Map,i=0;for(let a=0;a<e.length;a++){let o=e[a],s=Oh.test(o.text),c=kh.test(o.text),l=o.text.replace(Oh,``).replace(kh,``);if(l.length===0){Dh.test(o.text)&&i===0&&(i=Fh(o.font,r));continue}let u=i>0?i:s?Fh(o.font,r):0,d=fh(l,o.font),f=Ih(d);if(f===null){i=c?Fh(o.font,r):0;continue}let p={break:o.break??`normal`,endGraphemeIndex:f.endGraphemeIndex,endSegmentIndex:f.endSegmentIndex,extraWidth:o.extraWidth??0,gapBefore:u,naturalWidth:f.width,prepared:d,sourceItemIndex:a};t.push(p),n[a]=p,i=c?Fh(o.font,r):0}return{items:t,itemsBySourceItemIndex:n}}function zh(e,t,n,r){if(e.items.length===0||n.itemIndex>=e.items.length)return null;let i=Math.max(1,t),a=0,o=i,s=n.itemIndex,c={segmentIndex:n.segmentIndex,graphemeIndex:n.graphemeIndex};lineLoop:for(;s<e.items.length;){let t=e.items[s];if(!Ph(c)&&c.segmentIndex===t.endSegmentIndex&&c.graphemeIndex===t.endGraphemeIndex){s++,c.segmentIndex=0,c.graphemeIndex=0;continue}let n=a===0?0:t.gapBefore,l=Ph(c);if(t.break===`never`){if(!l){s++,c.segmentIndex=0,c.graphemeIndex=0;continue}let e=t.naturalWidth+t.extraWidth,u=n+e;if(a>0&&u>o)break lineLoop;r?.(t,n,e,Nh(Ah),{segmentIndex:t.endSegmentIndex,graphemeIndex:t.endGraphemeIndex}),a+=u,o=Math.max(0,i-a),s++,c.segmentIndex=0,c.graphemeIndex=0;continue}let u=n+t.extraWidth;if(a>0&&u>=o)break lineLoop;if(l){let e=u+t.naturalWidth;if(e<=o){r?.(t,n,t.naturalWidth+t.extraWidth,Nh(Ah),{segmentIndex:t.endSegmentIndex,graphemeIndex:t.endGraphemeIndex}),a+=e,o=Math.max(0,i-a),s++,c.segmentIndex=0,c.graphemeIndex=0;continue}}let d=Math.max(1,o-u),f=$m(t.prepared,c,d);if(f===null){s++,c.segmentIndex=0,c.graphemeIndex=0;continue}if(c.segmentIndex===f.endSegmentIndex&&c.graphemeIndex===f.endGraphemeIndex){s++,c.segmentIndex=0,c.graphemeIndex=0;continue}if(a>0&&l&&n>0&&Lh(f.endSegmentIndex,f.endGraphemeIndex)){let e=$m(t.prepared,Ah,Math.max(1,i-t.extraWidth));if(e!==null&&(e.endSegmentIndex>f.endSegmentIndex||e.endSegmentIndex===f.endSegmentIndex&&e.endGraphemeIndex>f.endGraphemeIndex))break lineLoop}if(r?.(t,n,f.width+t.extraWidth,Nh(c),{segmentIndex:f.endSegmentIndex,graphemeIndex:f.endGraphemeIndex}),a+=n+f.width+t.extraWidth,o=Math.max(0,i-a),f.endSegmentIndex===t.endSegmentIndex&&f.endGraphemeIndex===t.endGraphemeIndex){s++,c.segmentIndex=0,c.graphemeIndex=0;continue}c.segmentIndex=f.endSegmentIndex,c.graphemeIndex=f.endGraphemeIndex;break}return a===0?null:(n.itemIndex=s,n.segmentIndex=c.segmentIndex,n.graphemeIndex=c.graphemeIndex,a)}function Bh(e,t,n=jh){let r=Mh(e),i={itemIndex:n.itemIndex,segmentIndex:n.segmentIndex,graphemeIndex:n.graphemeIndex},a=[],o=zh(r,t,i,(e,t,n,r,i)=>{a.push({itemIndex:e.sourceItemIndex,gapBefore:t,occupiedWidth:n,start:r,end:i})});return o===null?null:{fragments:a,width:o,end:i}}function Vh(e,t){return Sh(e.prepared,{width:t.occupiedWidth-e.extraWidth,start:t.start,end:t.end}).text}function Hh(e,t){let n=Mh(e);return{fragments:t.fragments.map(e=>{let t=n.itemsBySourceItemIndex[e.itemIndex];if(t===void 0)throw Error(`Missing rich-text inline item for fragment`);return{...e,text:Vh(t,e)}}),width:t.width,end:t.end}}function Uh(e,t,n){let r=0,i=jh;for(;;){let a=Bh(e,t,i);if(a===null)return r;n(a),r++,i=a.end}}var Wh=`500 14px Inter, sans-serif`,Gh=`600 10px Inter, sans-serif`,Kh=`300 13px Inter, sans-serif`,qh=`600 10px Inter, sans-serif`,Jh=`300 12px Inter, sans-serif`,Yh=18,Xh=16,Zh=16,Qh=6,$h=12,eg=Math.min(window.devicePixelRatio||1,2),tg=`rgba(0, 0, 0, 0.75)`,ng=`rgba(255, 255, 255, 0.08)`,rg=`rgba(255, 255, 255, 0.9)`,ig=`rgba(255, 255, 255, 0.30)`,ag=`rgba(255, 255, 255, 0.85)`,og=`rgba(255, 255, 255, 0.08)`,sg=`rgba(255, 255, 255, 0.45)`,cg=`rgba(255, 255, 255, 0.08)`,lg=`rgba(255, 255, 255, 0.7)`;function ug(e){let t=0,n=0,r=0,i=new Set,a=new Set,o=new Set,s=!1,c=!1;return e.traverse(e=>{if(e.isMesh||e.isPoints||e.isLine){r++;let l=e.geometry;l&&(l.index?n+=l.index.count/3:l.attributes.position&&(n+=l.attributes.position.count/3),l.attributes.position&&(t+=l.attributes.position.count)),e.skeleton&&(s=!0),e.morphTargetInfluences&&e.morphTargetInfluences.length>0&&(c=!0),(Array.isArray(e.material)?e.material:[e.material]).forEach(e=>{if(e){i.add(e.uuid),o.add(e.type.replace(`Material`,``));for(let t in e)e[t]&&e[t].isTexture&&a.add(e[t].uuid)}})}}),{vertices:t,triangles:Math.floor(n),meshes:r,materials:i.size,textures:a.size,materialTypes:Array.from(o),hasSkinning:s,hasMorphs:c}}function dg(e){return e>=1e6?(e/1e6).toFixed(1)+`M`:e>=1e3?(e/1e3).toFixed(1)+`K`:e.toString()}function fg(e,t){let n=[];return e.hasSkinning&&n.push(`skinned`),e.hasMorphs&&n.push(`morph targets`),t&&t.length>0&&n.push(`${t.length} animation${t.length>1?`s`:``}`),e.materialTypes.length>0&&n.push(e.materialTypes.join(`, `)),n.length>0?n.join(` · `):``}function pg(e,t,n){let r=ug(t),i=fg(r,n),a=[{label:`MESHES`,value:dg(r.meshes)},{label:`VERTICES`,value:dg(r.vertices)},{label:`TRIANGLES`,value:dg(r.triangles)},{label:`MATERIALS`,value:dg(r.materials)},{label:`TEXTURES`,value:dg(r.textures)}];n&&n.length>0&&a.push({label:`ANIMATIONS`,value:n.length.toString()});let o=[];r.materialTypes.forEach(e=>o.push(e)),r.hasSkinning&&o.push(`Skinned`),r.hasMorphs&&o.push(`Morph`),n&&n.length>0&&o.push(`Animated`);let s=mh(dh(`Model Info`,Wh),200,Yh+2),c=a.map(e=>{let t=Rh([{text:e.label+` `,font:Gh},{text:e.value,font:Kh}]),n=wh(dh(e.label,Gh),200),r=wh(dh(e.value,Kh),200);return{...e,labelWidth:n.maxLineWidth,valueWidth:r.maxLineWidth,richPrepared:t}}),l=o.map(e=>({text:e,width:wh(dh(e,qh),300).maxLineWidth+$h})),u=[],d=0;if(i){let e=Eh(fh(i,Jh),200-Zh,Yh);u=e.lines,d=e.height}let f=Math.max(s.width+Zh*2,...c.map(e=>e.labelWidth+e.valueWidth+Zh*3)),p=Math.max(f,180),m=0;if(l.length>0){let e=0,t=1;l.forEach(n=>{e>0&&e+n.width>p-Zh*2&&(t++,e=0),e+=n.width+6}),m=t*(Xh+6)+Qh}let h=Zh+s.height+Qh+Qh+c.length*(Yh+Qh)+m+(d>0?Qh+d:0)+Zh,g=document.createElement(`canvas`);g.width=p*eg,g.height=h*eg,g.style.width=p+`px`,g.style.height=h+`px`;let _=g.getContext(`2d`);_.scale(eg,eg),_.fillStyle=tg,mg(_,0,0,p,h,10),_.fill(),_.strokeStyle=ng,_.lineWidth=1,mg(_,.5,.5,p-1,h-1,10),_.stroke();let v=Zh;if(_.font=Wh,_.fillStyle=rg,_.textBaseline=`top`,_.fillText(`Model Info`,Zh,v),v+=s.height+Qh,_.strokeStyle=og,_.beginPath(),_.moveTo(Zh,v),_.lineTo(p-Zh,v),_.stroke(),v+=Qh,c.forEach(e=>{_.font=Gh,_.fillStyle=ig,_.textAlign=`left`,_.fillText(e.label,Zh,v),_.font=Kh,_.fillStyle=ag,_.textAlign=`right`,_.fillText(e.value,p-Zh,v),_.textAlign=`left`,v+=Yh+Qh}),l.length>0){let e=Zh;l.forEach(t=>{e>Zh&&e+t.width>p-Zh&&(e=Zh,v+=Xh+6),_.fillStyle=cg,mg(_,e,v,t.width,Xh,4),_.fill(),_.font=qh,_.fillStyle=lg,_.textBaseline=`top`,_.fillText(t.text,e+$h/2,v+3),e+=t.width+6}),v+=Xh+Qh+4}u.length>0&&(_.strokeStyle=og,_.beginPath(),_.moveTo(Zh,v),_.lineTo(p-Zh,v),_.stroke(),v+=Qh,_.font=Jh,_.fillStyle=sg,_.textBaseline=`top`,u.forEach(e=>{_.fillText(e.text,Zh,v),v+=Yh}));let y=document.createElement(`div`);return y.classList.add(`model-info`),y.appendChild(g),e.appendChild(y),{el:y,canvas:g,remove(){y.remove()}}}function mg(e,t,n,r,i,a){e.beginPath(),e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.quadraticCurveTo(t+r,n,t+r,n+a),e.lineTo(t+r,n+i-a),e.quadraticCurveTo(t+r,n+i,t+r-a,n+i),e.lineTo(t+a,n+i),e.quadraticCurveTo(t,n+i,t,n+i-a),e.lineTo(t,n+a),e.quadraticCurveTo(t,n,t+a,n),e.closePath()}var hg=`500 11px Inter, sans-serif`,gg=`300 10px Inter, sans-serif`,_g=10,vg=6,yg=14,bg=Math.min(window.devicePixelRatio||1,2),xg=8;function Sg(e){let t=[];return e.traverse(e=>{if(t.length>=xg||!e.isMesh||!e.name||e.name.startsWith(`_`))return;let n=e.geometry,r=Array.isArray(e.material)?e.material[0]:e.material,i=n&&n.attributes.position?n.attributes.position.count:0,a=r?r.type.replace(`Material`,``):``,o=[{text:e.name,font:hg}];i>0&&o.push({text:` `+wg(i)+` verts`,font:gg}),a&&o.push({text:` `+a,font:gg});let s=Rh(o),c=0,l=0;Uh(s,300,e=>{let t=Hh(s,e);c=Math.max(c,t.width),l++});let u=c+_g*2,d=l*yg+vg*2;n&&n.computeBoundingBox();let f=n?n.boundingBox:null,p=new R;f?(f.getCenter(p),p.applyMatrix4(e.matrixWorld)):e.getWorldPosition(p),t.push({name:e.name,items:o,prepared:s,labelWidth:u,labelHeight:d,position:p,vertCount:i,matType:a})}),t}function Cg(e){let{labelWidth:t,labelHeight:n,items:r,prepared:i}=e,a=document.createElement(`canvas`);a.width=t*bg,a.height=n*bg,a.style.width=t+`px`,a.style.height=n+`px`;let o=a.getContext(`2d`);o.scale(bg,bg),o.fillStyle=`rgba(0, 0, 0, 0.8)`,Tg(o,0,0,t,n,6),o.fill(),o.strokeStyle=`rgba(255, 255, 255, 0.1)`,o.lineWidth=1,Tg(o,.5,.5,t-1,n-1,6),o.stroke(),o.textBaseline=`top`;let s=vg;return Uh(i,t-_g*2,e=>{let t=Hh(i,e),n=_g;t.fragments.forEach(e=>{n+=e.gapBefore,o.font=r[e.itemIndex].font,o.fillStyle=e.itemIndex===0?`rgba(255, 255, 255, 0.9)`:`rgba(255, 255, 255, 0.45)`,o.fillText(e.text,n,s),n+=e.occupiedWidth}),s+=yg}),a}function wg(e){return e>=1e6?(e/1e6).toFixed(1)+`M`:e>=1e3?(e/1e3).toFixed(1)+`K`:e.toString()}function Tg(e,t,n,r,i,a){e.beginPath(),e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.quadraticCurveTo(t+r,n,t+r,n+a),e.lineTo(t+r,n+i-a),e.quadraticCurveTo(t+r,n+i,t+r-a,n+i),e.lineTo(t+a,n+i),e.quadraticCurveTo(t,n+i,t,n+i-a),e.lineTo(t,n+a),e.quadraticCurveTo(t,n,t+a,n),e.closePath()}var Eg=new WeakMap,Dg=class extends co{constructor(e){super(e),this.decoderPath=``,this.decoderConfig={},this.decoderBinary=null,this.decoderPending=null,this.workerLimit=4,this.workerPool=[],this.workerNextTaskID=1,this.workerSourceURL=``,this.defaultAttributeIDs={position:`POSITION`,normal:`NORMAL`,color:`COLOR`,uv:`TEX_COORD`},this.defaultAttributeTypes={position:`Float32Array`,normal:`Float32Array`,color:`Float32Array`,uv:`Float32Array`}}setDecoderPath(e){return this.decoderPath=e,this}setDecoderConfig(e){return this.decoderConfig=e,this}setWorkerLimit(e){return this.workerLimit=e,this}load(e,t,n,r){let i=new fo(this.manager);i.setPath(this.path),i.setResponseType(`arraybuffer`),i.setRequestHeader(this.requestHeader),i.setWithCredentials(this.withCredentials),i.load(e,e=>{this.parse(e,t,r)},n,r)}parse(e,t,n=()=>{}){this.decodeDracoFile(e,t,null,null,Ke,n).catch(n)}decodeDracoFile(e,t,n,r,i=qe,a=()=>{}){let o={attributeIDs:n||this.defaultAttributeIDs,attributeTypes:r||this.defaultAttributeTypes,useUniqueIDs:!!n,vertexColorSpace:i};return this.decodeGeometry(e,o).then(t).catch(a)}decodeGeometry(e,t){let n=JSON.stringify(t);if(Eg.has(e)){let t=Eg.get(e);if(t.key===n)return t.promise;if(e.byteLength===0)throw Error(`THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred.`)}let r,i=this.workerNextTaskID++,a=e.byteLength,o=this._getWorker(i,a).then(n=>(r=n,new Promise((n,a)=>{r._callbacks[i]={resolve:n,reject:a},r.postMessage({type:`decode`,id:i,taskConfig:t,buffer:e},[e])}))).then(e=>this._createGeometry(e.geometry));return o.catch(()=>!0).then(()=>{r&&i&&this._releaseTask(r,i)}),Eg.set(e,{key:n,promise:o}),o}_createGeometry(e){let t=new Gr;e.index&&t.setIndex(new Pr(e.index.array,1));for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n],i=r.name,a=r.array,o=r.itemSize,s=new Pr(a,o);i===`color`&&(this._assignVertexColorSpace(s,r.vertexColorSpace),s.normalized=!(a instanceof Float32Array)),t.setAttribute(i,s)}return t}_assignVertexColorSpace(e,t){if(t!==`srgb`)return;let n=new B;for(let t=0,r=e.count;t<r;t++)n.fromBufferAttribute(e,t),zt.toWorkingColorSpace(n,Ke),e.setXYZ(t,n.r,n.g,n.b)}_loadLibrary(e,t){let n=new fo(this.manager);return n.setPath(this.decoderPath),n.setResponseType(t),n.setWithCredentials(this.withCredentials),new Promise((t,r)=>{n.load(e,t,void 0,r)})}preload(){return this._initDecoder(),this}_initDecoder(){if(this.decoderPending)return this.decoderPending;let e=typeof WebAssembly!=`object`||this.decoderConfig.type===`js`,t=[];return e?t.push(this._loadLibrary(`draco_decoder.js`,`text`)):(t.push(this._loadLibrary(`draco_wasm_wrapper.js`,`text`)),t.push(this._loadLibrary(`draco_decoder.wasm`,`arraybuffer`))),this.decoderPending=Promise.all(t).then(t=>{let n=t[0];e||(this.decoderConfig.wasmBinary=t[1]);let r=Og.toString(),i=[`/* draco decoder */`,n,``,`/* worker */`,r.substring(r.indexOf(`{`)+1,r.lastIndexOf(`}`))].join(`
+`);this.workerSourceURL=URL.createObjectURL(new Blob([i]))}),this.decoderPending}_getWorker(e,t){return this._initDecoder().then(()=>{if(this.workerPool.length<this.workerLimit){let e=new Worker(this.workerSourceURL);e._callbacks={},e._taskCosts={},e._taskLoad=0,e.postMessage({type:`init`,decoderConfig:this.decoderConfig}),e.onmessage=function(t){let n=t.data;switch(n.type){case`decode`:e._callbacks[n.id].resolve(n);break;case`error`:e._callbacks[n.id].reject(n);break;default:console.error(`THREE.DRACOLoader: Unexpected message, "`+n.type+`"`)}},this.workerPool.push(e)}else this.workerPool.sort(function(e,t){return e._taskLoad>t._taskLoad?-1:1});let n=this.workerPool[this.workerPool.length-1];return n._taskCosts[e]=t,n._taskLoad+=t,n})}_releaseTask(e,t){e._taskLoad-=e._taskCosts[t],delete e._callbacks[t],delete e._taskCosts[t]}debug(){console.log(`Task load: `,this.workerPool.map(e=>e._taskLoad))}dispose(){for(let e=0;e<this.workerPool.length;++e)this.workerPool[e].terminate();return this.workerPool.length=0,this.workerSourceURL!==``&&URL.revokeObjectURL(this.workerSourceURL),this}};function Og(){let e,t;onmessage=function(r){let i=r.data;switch(i.type){case`init`:e=i.decoderConfig,t=new Promise(function(t){e.onModuleLoaded=function(e){t({draco:e})},DracoDecoderModule(e)});break;case`decode`:let r=i.buffer,a=i.taskConfig;t.then(e=>{let t=e.draco,o=new t.Decoder;try{let e=n(t,o,new Int8Array(r),a),s=e.attributes.map(e=>e.array.buffer);e.index&&s.push(e.index.array.buffer),self.postMessage({type:`decode`,id:i.id,geometry:e},s)}catch(e){console.error(e),self.postMessage({type:`error`,id:i.id,error:e.message})}finally{t.destroy(o)}});break}};function n(e,t,n,a){let o=a.attributeIDs,s=a.attributeTypes,c,l,u=t.GetEncodedGeometryType(n);if(u===e.TRIANGULAR_MESH)c=new e.Mesh,l=t.DecodeArrayToMesh(n,n.byteLength,c);else if(u===e.POINT_CLOUD)c=new e.PointCloud,l=t.DecodeArrayToPointCloud(n,n.byteLength,c);else throw Error(`THREE.DRACOLoader: Unexpected geometry type.`);if(!l.ok()||c.ptr===0)throw Error(`THREE.DRACOLoader: Decoding failed: `+l.error_msg());let d={index:null,attributes:[]};for(let n in o){let r=self[s[n]],l,u;if(a.useUniqueIDs)u=o[n],l=t.GetAttributeByUniqueId(c,u);else{if(u=t.GetAttributeId(c,e[o[n]]),u===-1)continue;l=t.GetAttribute(c,u)}let f=i(e,t,c,n,r,l);n===`color`&&(f.vertexColorSpace=a.vertexColorSpace),d.attributes.push(f)}return u===e.TRIANGULAR_MESH&&(d.index=r(e,t,c)),e.destroy(c),d}function r(e,t,n){let r=n.num_faces()*3,i=r*4,a=e._malloc(i);t.GetTrianglesUInt32Array(n,i,a);let o=new Uint32Array(e.HEAPF32.buffer,a,r).slice();return e._free(a),{array:o,itemSize:1}}function i(e,t,n,r,i,o){let s=o.num_components(),c=n.num_points()*s,l=c*i.BYTES_PER_ELEMENT,u=a(e,i),d=e._malloc(l);t.GetAttributeDataArrayForAllPoints(n,o,u,l,d);let f=new i(e.HEAPF32.buffer,d,c).slice();return e._free(d),{name:r,array:f,itemSize:s}}function a(e,t){switch(t){case Float32Array:return e.DT_FLOAT32;case Int8Array:return e.DT_INT8;case Int16Array:return e.DT_INT16;case Int32Array:return e.DT_INT32;case Uint8Array:return e.DT_UINT8;case Uint16Array:return e.DT_UINT16;case Uint32Array:return e.DT_UINT32}}}var kg=class{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0,this.workerCreator=null}_initWorker(e){if(!this.workers[e]){let t=this.workerCreator();t.addEventListener(`message`,this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){let n=this.workersResolve[e];if(n&&n(t),this.queue.length){let{resolve:t,msg:n,transfer:r}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(n,r)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise(n=>{let r=this._getIdleWorker();r===-1?this.queue.push({resolve:n,msg:e,transfer:t}):(this._initWorker(r),this.workerStatus|=1<<r,this.workersResolve[r]=n,this.workers[r].postMessage(e,t))})}dispose(){this.workers.forEach(e=>e.terminate()),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}},Ag=1000066e3,jg=class{constructor(){this.vkFormat=0,this.typeSize=1,this.pixelWidth=0,this.pixelHeight=0,this.pixelDepth=0,this.layerCount=0,this.faceCount=1,this.supercompressionScheme=0,this.levels=[],this.dataFormatDescriptor=[{vendorId:0,descriptorType:0,descriptorBlockSize:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],this.keyValue={},this.globalData=null}},Mg=class{constructor(e,t,n,r){this._dataView=void 0,this._littleEndian=void 0,this._offset=void 0,this._dataView=new DataView(e.buffer,e.byteOffset+t,n),this._littleEndian=r,this._offset=0}_nextUint8(){let e=this._dataView.getUint8(this._offset);return this._offset+=1,e}_nextUint16(){let e=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,e}_nextUint32(){let e=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint64(){let e=this._dataView.getUint32(this._offset,this._littleEndian)+2**32*this._dataView.getUint32(this._offset+4,this._littleEndian);return this._offset+=8,e}_nextInt32(){let e=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,e}_nextUint8Array(e){let t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._offset,e);return this._offset+=e,t}_skip(e){return this._offset+=e,this}_scan(e,t){t===void 0&&(t=0);let n=this._offset,r=0;for(;this._dataView.getUint8(this._offset)!==t&&r<e;)r++,this._offset++;return r<e&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+n,r)}};new Uint8Array([0]);var Ng=[171,75,84,88,32,50,48,187,13,10,26,10];function Pg(e){return new TextDecoder().decode(e)}function Fg(e){let t=new Uint8Array(e.buffer,e.byteOffset,Ng.length);if(t[0]!==Ng[0]||t[1]!==Ng[1]||t[2]!==Ng[2]||t[3]!==Ng[3]||t[4]!==Ng[4]||t[5]!==Ng[5]||t[6]!==Ng[6]||t[7]!==Ng[7]||t[8]!==Ng[8]||t[9]!==Ng[9]||t[10]!==Ng[10]||t[11]!==Ng[11])throw Error(`Missing KTX 2.0 identifier.`);let n=new jg,r=17*Uint32Array.BYTES_PER_ELEMENT,i=new Mg(e,Ng.length,r,!0);n.vkFormat=i._nextUint32(),n.typeSize=i._nextUint32(),n.pixelWidth=i._nextUint32(),n.pixelHeight=i._nextUint32(),n.pixelDepth=i._nextUint32(),n.layerCount=i._nextUint32(),n.faceCount=i._nextUint32();let a=i._nextUint32();n.supercompressionScheme=i._nextUint32();let o=i._nextUint32(),s=i._nextUint32(),c=i._nextUint32(),l=i._nextUint32(),u=i._nextUint64(),d=i._nextUint64(),f=new Mg(e,Ng.length+r,3*a*8,!0);for(let t=0;t<a;t++)n.levels.push({levelData:new Uint8Array(e.buffer,e.byteOffset+f._nextUint64(),f._nextUint64()),uncompressedByteLength:f._nextUint64()});let p=new Mg(e,o,s,!0),m={vendorId:p._skip(4)._nextUint16(),descriptorType:p._nextUint16(),versionNumber:p._nextUint16(),descriptorBlockSize:p._nextUint16(),colorModel:p._nextUint8(),colorPrimaries:p._nextUint8(),transferFunction:p._nextUint8(),flags:p._nextUint8(),texelBlockDimension:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],bytesPlane:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],samples:[]},h=(m.descriptorBlockSize/4-6)/4;for(let e=0;e<h;e++){let t={bitOffset:p._nextUint16(),bitLength:p._nextUint8(),channelType:p._nextUint8(),samplePosition:[p._nextUint8(),p._nextUint8(),p._nextUint8(),p._nextUint8()],sampleLower:-1/0,sampleUpper:1/0};64&t.channelType?(t.sampleLower=p._nextInt32(),t.sampleUpper=p._nextInt32()):(t.sampleLower=p._nextUint32(),t.sampleUpper=p._nextUint32()),m.samples[e]=t}n.dataFormatDescriptor.length=0,n.dataFormatDescriptor.push(m);let g=new Mg(e,c,l,!0);for(;g._offset<l;){let e=g._nextUint32(),t=g._scan(e),r=Pg(t);if(n.keyValue[r]=g._nextUint8Array(e-t.byteLength-1),r.match(/^ktx/i)){let e=Pg(n.keyValue[r]);n.keyValue[r]=e.substring(0,e.lastIndexOf(`\0`))}g._skip(e%4?4-e%4:0)}if(d<=0)return n;let _=new Mg(e,u,d,!0),v=_._nextUint16(),y=_._nextUint16(),b=_._nextUint32(),x=_._nextUint32(),S=_._nextUint32(),C=_._nextUint32(),w=[];for(let e=0;e<a;e++)w.push({imageFlags:_._nextUint32(),rgbSliceByteOffset:_._nextUint32(),rgbSliceByteLength:_._nextUint32(),alphaSliceByteOffset:_._nextUint32(),alphaSliceByteLength:_._nextUint32()});let T=u+_._offset,E=T+b,D=E+x,O=D+S;return n.globalData={endpointCount:v,selectorCount:y,imageDescs:w,endpointsData:new Uint8Array(e.buffer,e.byteOffset+T,b),selectorsData:new Uint8Array(e.buffer,e.byteOffset+E,x),tablesData:new Uint8Array(e.buffer,e.byteOffset+D,S),extendedData:new Uint8Array(e.buffer,e.byteOffset+O,C)},n}var Ig,Lg,Rg,zg={env:{emscripten_notify_memory_growth:function(e){Rg=new Uint8Array(Lg.exports.memory.buffer)}}},Bg=class{init(){return Ig||(Ig=typeof fetch<`u`?fetch(`data:application/wasm;base64,`+Vg).then(e=>e.arrayBuffer()).then(e=>WebAssembly.instantiate(e,zg)).then(this._init):WebAssembly.instantiate(Buffer.from(Vg,`base64`),zg).then(this._init),Ig)}_init(e){Lg=e.instance,zg.env.emscripten_notify_memory_growth(0)}decode(e,t=0){if(!Lg)throw Error(`ZSTDDecoder: Await .init() before decoding.`);let n=e.byteLength,r=Lg.exports.malloc(n);Rg.set(e,r),t||=Number(Lg.exports.ZSTD_findDecompressedSize(r,n));let i=Lg.exports.malloc(t),a=Lg.exports.ZSTD_decompress(i,t,r,n),o=Rg.slice(i,i+a);return Lg.exports.free(r),Lg.exports.free(i),o}},Vg=`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IAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQh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ASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigC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C0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdB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IAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/IwBBMGsiBCQAIABB/wFqIgVBfWohBgJAIAMvAQIEQCAEQRhqIAEgAhAGIgIQAw0BIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahASOgAAIAMgBEEIaiAEQRhqEBI6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0FIAEgBEEQaiAEQRhqEBI6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBSABIARBCGogBEEYahASOgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEjoAACABIAJqIABrIQIMAwsgAyAEQRBqIARBGGoQEjoAAiADIARBCGogBEEYahASOgADIANBBGohAwwAAAsACyAEQRhqIAEgAhAGIgIQAw0AIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahAROgAAIAMgBEEIaiAEQRhqEBE6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0EIAEgBEEQaiAEQRhqEBE6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBCABIARBCGogBEEYahAROgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEToAACABIAJqIABrIQIMAgsgAyAEQRBqIARBGGoQEToAAiADIARBCGogBEEYahAROgADIANBBGohAwwAAAsACyAEQTBqJAAgAgtpAQF/An8CQAJAIAJBB00NACABKAAAQbfIwuF+Rw0AIAAgASgABDYCmOIBQWIgAEEQaiABIAIQPiIDEAMNAhogAEKBgICAEDcDiOEBIAAgASADaiACIANrECoMAQsgACABIAIQKgtBAAsLrQMBBn8jAEGAAWsiAyQAQWIhCAJAIAJBCUkNACAAQZjQAGogAUEIaiIEIAJBeGogAEGY0AAQMyIFEAMiBg0AIANBHzYCfCADIANB/ABqIANB+ABqIAQgBCAFaiAGGyIEIAEgAmoiAiAEaxAVIgUQAw0AIAMoAnwiBkEfSw0AIAMoAngiB0EJTw0AIABBiCBqIAMgBkGAC0GADCAHEBggA0E0NgJ8IAMgA0H8AGogA0H4AGogBCAFaiIEIAIgBGsQFSIFEAMNACADKAJ8IgZBNEsNACADKAJ4IgdBCk8NACAAQZAwaiADIAZBgA1B4A4gBxAYIANBIzYCfCADIANB/ABqIANB+ABqIAQgBWoiBCACIARrEBUiBRADDQAgAygCfCIGQSNLDQAgAygCeCIHQQpPDQAgACADIAZBwBBB0BEgBxAYIAQgBWoiBEEMaiIFIAJLDQAgAiAFayEFQQAhAgNAIAJBA0cEQCAEKAAAIgZBf2ogBU8NAiAAIAJBAnRqQZzQAWogBjYCACACQQFqIQIgBEEEaiEEDAELCyAEIAFrIQgLIANBgAFqJAAgCAtGAQN/IABBCGohAyAAKAIEIQJBACEAA0AgACACdkUEQCABIAMgAEEDdGotAAJBFktqIQEgAEEBaiEADAELCyABQQggAmt0C4YDAQV/Qbh/IQcCQCADRQ0AIAItAAAiBEUEQCABQQA2AgBBAUG4fyADQQFGGw8LAn8gAkEBaiIFIARBGHRBGHUiBkF/Sg0AGiAGQX9GBEAgA0EDSA0CIAUvAABBgP4BaiEEIAJBA2oMAQsgA0ECSA0BIAItAAEgBEEIdHJBgIB+aiEEIAJBAmoLIQUgASAENgIAIAVBAWoiASACIANqIgNLDQBBbCEHIABBEGogACAFLQAAIgVBBnZBI0EJIAEgAyABa0HAEEHQEUHwEiAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBmCBqIABBCGogBUEEdkEDcUEfQQggASABIAZqIAgbIgEgAyABa0GAC0GADEGAFyAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBoDBqIABBBGogBUECdkEDcUE0QQkgASABIAZqIAgbIgEgAyABa0GADUHgDkGQGSAAKAKM4QEgACgCnOIBIAQQHyIAEAMNACAAIAFqIAJrIQcLIAcLrQMBCn8jAEGABGsiCCQAAn9BUiACQf8BSw0AGkFUIANBDEsNABogAkEBaiELIABBBGohCUGAgAQgA0F/anRBEHUhCkEAIQJBASEEQQEgA3QiB0F/aiIMIQUDQCACIAtGRQRAAkAgASACQQF0Ig1qLwEAIgZB//8DRgRAIAkgBUECdGogAjoAAiAFQX9qIQVBASEGDAELIARBACAKIAZBEHRBEHVKGyEECyAIIA1qIAY7AQAgAkEBaiECDAELCyAAIAQ7AQIgACADOwEAIAdBA3YgB0EBdmpBA2ohBkEAIQRBACECA0AgBCALRkUEQCABIARBAXRqLgEAIQpBACEAA0AgACAKTkUEQCAJIAJBAnRqIAQ6AAIDQCACIAZqIAxxIgIgBUsNAAsgAEEBaiEADAELCyAEQQFqIQQMAQsLQX8gAg0AGkEAIQIDfyACIAdGBH9BAAUgCCAJIAJBAnRqIgAtAAJBAXRqIgEgAS8BACIBQQFqOwEAIAAgAyABEBRrIgU6AAMgACABIAVB/wFxdCAHazsBACACQQFqIQIMAQsLCyEFIAhBgARqJAAgBQvjBgEIf0FsIQcCQCACQQNJDQACQAJAAkACQCABLQAAIgNBA3EiCUEBaw4DAwEAAgsgACgCiOEBDQBBYg8LIAJBBUkNAkEDIQYgASgAACEFAn8CQAJAIANBAnZBA3EiCEF+aiIEQQFNBEAgBEEBaw0BDAILIAVBDnZB/wdxIQQgBUEEdkH/B3EhAyAIRQwCCyAFQRJ2IQRBBCEGIAVBBHZB//8AcSEDQQAMAQsgBUEEdkH//w9xIgNBgIAISw0DIAEtAARBCnQgBUEWdnIhBEEFIQZBAAshBSAEIAZqIgogAksNAgJAIANBgQZJDQAgACgCnOIBRQ0AQQAhAgNAIAJBg4ABSw0BIAJBQGshAgwAAAsACwJ/IAlBA0YEQCABIAZqIQEgAEHw4gFqIQIgACgCDCEGIAUEQCACIAMgASAEIAYQXwwCCyACIAMgASAEIAYQXQwBCyAAQbjQAWohAiABIAZqIQEgAEHw4gFqIQYgAEGo0ABqIQggBQRAIAggBiADIAEgBCACEF4MAQsgCCAGIAMgASAEIAIQXAsQAw0CIAAgAzYCgOIBIABBATYCiOEBIAAgAEHw4gFqNgLw4QEgCUECRgRAIAAgAEGo0ABqNgIMCyAAIANqIgBBiOMBakIANwAAIABBgOMBakIANwAAIABB+OIBakIANwAAIABB8OIBakIANwAAIAoPCwJ/AkACQAJAIANBAnZBA3FBf2oiBEECSw0AIARBAWsOAgACAQtBASEEIANBA3YMAgtBAiEEIAEvAABBBHYMAQtBAyEEIAEQIUEEdgsiAyAEaiIFQSBqIAJLBEAgBSACSw0CIABB8OIBaiABIARqIAMQCyEBIAAgAzYCgOIBIAAgATYC8OEBIAEgA2oiAEIANwAYIABCADcAECAAQgA3AAggAEIANwAAIAUPCyAAIAM2AoDiASAAIAEgBGo2AvDhASAFDwsCfwJAAkACQCADQQJ2QQNxQX9qIgRBAksNACAEQQFrDgIAAgELQQEhByADQQN2DAILQQIhByABLwAAQQR2DAELIAJBBEkgARAhIgJBj4CAAUtyDQFBAyEHIAJBBHYLIQIgAEHw4gFqIAEgB2otAAAgAkEgahAQIQEgACACNgKA4gEgACABNgLw4QEgB0EBaiEHCyAHC0sAIABC+erQ0OfJoeThADcDICAAQgA3AxggAELP1tO+0ser2UI3AxAgAELW64Lu6v2J9eAANwMIIABCADcDACAAQShqQQBBKBAQGgviAgICfwV+IABBKGoiASAAKAJIaiECAn4gACkDACIDQiBaBEAgACkDECIEQgeJIAApAwgiBUIBiXwgACkDGCIGQgyJfCAAKQMgIgdCEol8IAUQGSAEEBkgBhAZIAcQGQwBCyAAKQMYQsXP2bLx5brqJ3wLIAN8IQMDQCABQQhqIgAgAk0EQEIAIAEpAAAQCSADhUIbiUKHla+vmLbem55/fkLj3MqV/M7y9YV/fCEDIAAhAQwBCwsCQCABQQRqIgAgAksEQCABIQAMAQsgASgAAK1Ch5Wvr5i23puef34gA4VCF4lCz9bTvtLHq9lCfkL5893xmfaZqxZ8IQMLA0AgACACSQRAIAAxAABCxc/ZsvHluuonfiADhUILiUKHla+vmLbem55/fiEDIABBAWohAAwBCwsgA0IhiCADhULP1tO+0ser2UJ+IgNCHYggA4VC+fPd8Zn2masWfiIDQiCIIAOFC+8CAgJ/BH4gACAAKQMAIAKtfDcDAAJAAkAgACgCSCIDIAJqIgRBH00EQCABRQ0BIAAgA2pBKGogASACECAgACgCSCACaiEEDAELIAEgAmohAgJ/IAMEQCAAQShqIgQgA2ogAUEgIANrECAgACAAKQMIIAQpAAAQCTcDCCAAIAApAxAgACkAMBAJNwMQIAAgACkDGCAAKQA4EAk3AxggACAAKQMgIABBQGspAAAQCTcDICAAKAJIIQMgAEEANgJIIAEgA2tBIGohAQsgAUEgaiACTQsEQCACQWBqIQMgACkDICEFIAApAxghBiAAKQMQIQcgACkDCCEIA0AgCCABKQAAEAkhCCAHIAEpAAgQCSEHIAYgASkAEBAJIQYgBSABKQAYEAkhBSABQSBqIgEgA00NAAsgACAFNwMgIAAgBjcDGCAAIAc3AxAgACAINwMICyABIAJPDQEgAEEoaiABIAIgAWsiBBAgCyAAIAQ2AkgLCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQEBogAwVBun8LCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQCxogAwVBun8LC6gCAQZ/IwBBEGsiByQAIABB2OABaikDAEKAgIAQViEIQbh/IQUCQCAEQf//B0sNACAAIAMgBBBCIgUQAyIGDQAgACgCnOIBIQkgACAHQQxqIAMgAyAFaiAGGyIKIARBACAFIAYbayIGEEAiAxADBEAgAyEFDAELIAcoAgwhBCABRQRAQbp/IQUgBEEASg0BCyAGIANrIQUgAyAKaiEDAkAgCQRAIABBADYCnOIBDAELAkACQAJAIARBBUgNACAAQdjgAWopAwBCgICACFgNAAwBCyAAQQA2ApziAQwBCyAAKAIIED8hBiAAQQA2ApziASAGQRRPDQELIAAgASACIAMgBSAEIAgQOSEFDAELIAAgASACIAMgBSAEIAgQOiEFCyAHQRBqJAAgBQtnACAAQdDgAWogASACIAAoAuzhARAuIgEQAwRAIAEPC0G4fyECAkAgAQ0AIABB7OABaigCACIBBEBBYCECIAAoApjiASABRw0BC0EAIQIgAEHw4AFqKAIARQ0AIABBkOEBahBDCyACCycBAX8QVyIERQRAQUAPCyAEIAAgASACIAMgBBBLEE8hACAEEFYgAAs/AQF/AkACQAJAIAAoAqDiAUEBaiIBQQJLDQAgAUEBaw4CAAECCyAAEDBBAA8LIABBADYCoOIBCyAAKAKU4gELvAMCB38BfiMAQRBrIgkkAEG4fyEGAkAgBCgCACIIQQVBCSAAKALs4QEiBRtJDQAgAygCACIHQQFBBSAFGyAFEC8iBRADBEAgBSEGDAELIAggBUEDakkNACAAIAcgBRBJIgYQAw0AIAEgAmohCiAAQZDhAWohCyAIIAVrIQIgBSAHaiEHIAEhBQNAIAcgAiAJECwiBhADDQEgAkF9aiICIAZJBEBBuH8hBgwCCyAJKAIAIghBAksEQEFsIQYMAgsgB0EDaiEHAn8CQAJAAkAgCEEBaw4CAgABCyAAIAUgCiAFayAHIAYQSAwCCyAFIAogBWsgByAGEEcMAQsgBSAKIAVrIActAAAgCSgCCBBGCyIIEAMEQCAIIQYMAgsgACgC8OABBEAgCyAFIAgQRQsgAiAGayECIAYgB2ohByAFIAhqIQUgCSgCBEUNAAsgACkD0OABIgxCf1IEQEFsIQYgDCAFIAFrrFINAQsgACgC8OABBEBBaiEGIAJBBEkNASALEEQhDCAHKAAAIAynRw0BIAdBBGohByACQXxqIQILIAMgBzYCACAEIAI2AgAgBSABayEGCyAJQRBqJAAgBgsuACAAECsCf0EAQQAQAw0AGiABRSACRXJFBEBBYiAAIAEgAhA9EAMNARoLQQALCzcAIAEEQCAAIAAoAsTgASABKAIEIAEoAghqRzYCnOIBCyAAECtBABADIAFFckUEQCAAIAEQWwsL0QIBB38jAEEQayIGJAAgBiAENgIIIAYgAzYCDCAFBEAgBSgCBCEKIAUoAgghCQsgASEIAkACQANAIAAoAuzhARAWIQsCQANAIAQgC0kNASADKAAAQXBxQdDUtMIBRgRAIAMgBBAiIgcQAw0EIAQgB2shBCADIAdqIQMMAQsLIAYgAzYCDCAGIAQ2AggCQCAFBEAgACAFEE5BACEHQQAQA0UNAQwFCyAAIAogCRBNIgcQAw0ECyAAIAgQUCAMQQFHQQAgACAIIAIgBkEMaiAGQQhqEEwiByIDa0EAIAMQAxtBCkdyRQRAQbh/IQcMBAsgBxADDQMgAiAHayECIAcgCGohCEEBIQwgBigCDCEDIAYoAgghBAwBCwsgBiADNgIMIAYgBDYCCEG4fyEHIAQNASAIIAFrIQcMAQsgBiADNgIMIAYgBDYCCAsgBkEQaiQAIAcLRgECfyABIAAoArjgASICRwRAIAAgAjYCxOABIAAgATYCuOABIAAoArzgASEDIAAgATYCvOABIAAgASADIAJrajYCwOABCwutAgIEfwF+IwBBQGoiBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEE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`,Hg=`display-p3`,Ug=`display-p3-linear`,Wg=new WeakMap,Gg=0,Kg,qg=class e extends co{constructor(e){super(e),this.transcoderPath=``,this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new kg,this.workerSourceURL=``,this.workerConfig=null,typeof MSC_TRANSCODER<`u`&&console.warn(`THREE.KTX2Loader: Please update to latest "basis_transcoder". "msc_basis_transcoder" is no longer supported in three.js r125+.`)}setTranscoderPath(e){return this.transcoderPath=e,this}setWorkerLimit(e){return this.workerPool.setWorkerLimit(e),this}async detectSupportAsync(e){return this.workerConfig={astcSupported:await e.hasFeatureAsync(`texture-compression-astc`),astcHDRSupported:!1,etc1Supported:await e.hasFeatureAsync(`texture-compression-etc1`),etc2Supported:await e.hasFeatureAsync(`texture-compression-etc2`),dxtSupported:await e.hasFeatureAsync(`texture-compression-bc`),bptcSupported:await e.hasFeatureAsync(`texture-compression-bptc`),pvrtcSupported:await e.hasFeatureAsync(`texture-compression-pvrtc`)},this}detectSupport(e){return e.isWebGPURenderer===!0?this.workerConfig={astcSupported:e.hasFeature(`texture-compression-astc`),astcHDRSupported:!1,etc1Supported:e.hasFeature(`texture-compression-etc1`),etc2Supported:e.hasFeature(`texture-compression-etc2`),dxtSupported:e.hasFeature(`texture-compression-bc`),bptcSupported:e.hasFeature(`texture-compression-bptc`),pvrtcSupported:e.hasFeature(`texture-compression-pvrtc`)}:this.workerConfig={astcSupported:e.extensions.has(`WEBGL_compressed_texture_astc`),astcHDRSupported:e.extensions.has(`WEBGL_compressed_texture_astc`)&&e.extensions.get(`WEBGL_compressed_texture_astc`).getSupportedProfiles().includes(`hdr`),etc1Supported:e.extensions.has(`WEBGL_compressed_texture_etc1`),etc2Supported:e.extensions.has(`WEBGL_compressed_texture_etc`),dxtSupported:e.extensions.has(`WEBGL_compressed_texture_s3tc`),bptcSupported:e.extensions.has(`EXT_texture_compression_bptc`),pvrtcSupported:e.extensions.has(`WEBGL_compressed_texture_pvrtc`)||e.extensions.has(`WEBKIT_WEBGL_compressed_texture_pvrtc`)},this}init(){if(!this.transcoderPending){let t=new fo(this.manager);t.setPath(this.transcoderPath),t.setWithCredentials(this.withCredentials);let n=t.loadAsync(`basis_transcoder.js`),r=new fo(this.manager);r.setPath(this.transcoderPath),r.setResponseType(`arraybuffer`),r.setWithCredentials(this.withCredentials);let i=r.loadAsync(`basis_transcoder.wasm`);this.transcoderPending=Promise.all([n,i]).then(([t,n])=>{let r=e.BasisWorker.toString(),i=[`/* constants */`,`let _EngineFormat = `+JSON.stringify(e.EngineFormat),`let _EngineType = `+JSON.stringify(e.EngineType),`let _TranscoderFormat = `+JSON.stringify(e.TranscoderFormat),`let _BasisFormat = `+JSON.stringify(e.BasisFormat),`/* basis_transcoder.js */`,t,`/* worker */`,r.substring(r.indexOf(`{`)+1,r.lastIndexOf(`}`))].join(`
+`);this.workerSourceURL=URL.createObjectURL(new Blob([i])),this.transcoderBinary=n,this.workerPool.setWorkerCreator(()=>{let e=new Worker(this.workerSourceURL),t=this.transcoderBinary.slice(0);return e.postMessage({type:`init`,config:this.workerConfig,transcoderBinary:t},[t]),e})}),Gg>0&&console.warn(`THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances.`),Gg++}return this.transcoderPending}load(e,t,n,r){if(this.workerConfig===null)throw Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");let i=new fo(this.manager);i.setResponseType(`arraybuffer`),i.setWithCredentials(this.withCredentials),i.load(e,e=>{this.parse(e,t,r)},n,r)}parse(e,t,n){if(this.workerConfig===null)throw Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");if(Wg.has(e))return Wg.get(e).promise.then(t).catch(n);this._createTexture(e).then(e=>t?t(e):null).catch(n)}_createTextureFrom(e,t){let{type:n,error:r,data:{faces:i,width:a,height:o,format:s,type:c,dfdFlags:l}}=e;if(n===`error`)return Promise.reject(r);let u;if(t.faceCount===6)u=new Ma(i,s,c);else{let e=i[0].mipmaps;u=t.layerCount>1?new ja(e,a,o,t.layerCount,s,c):new Aa(e,a,o,s,c)}return u.minFilter=i[0].mipmaps.length===1?f:m,u.magFilter=f,u.generateMipmaps=!1,u.needsUpdate=!0,u.colorSpace=Qg(t),u.premultiplyAlpha=!!(l&1),u}async _createTexture(e,t={}){let n=Fg(new Uint8Array(e)),r=n.vkFormat===1000066e3&&n.dataFormatDescriptor[0].colorModel===167;if(!(n.vkFormat===0||r&&!this.workerConfig.astcHDRSupported))return Zg(n);let i=t,a=this.init().then(()=>this.workerPool.postMessage({type:`transcode`,buffer:e,taskConfig:i},[e])).then(e=>this._createTextureFrom(e.data,n));return Wg.set(e,{promise:a}),a}dispose(){this.workerPool.dispose(),this.workerSourceURL&&URL.revokeObjectURL(this.workerSourceURL),Gg--}};qg.BasisFormat={ETC1S:0,UASTC:1,UASTC_HDR:2},qg.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16,BC6H:22,RGB_HALF:24,RGBA_HALF:25},qg.EngineFormat={RGBAFormat:k,RGBA_ASTC_4x4_Format:_e,RGB_BPTC_UNSIGNED_Format:Oe,RGBA_BPTC_Format:F,RGBA_ETC2_EAC_Format:ge,RGBA_PVRTC_4BPPV1_Format:fe,RGBA_S3TC_DXT5_Format:le,RGB_ETC1_Format:me,RGB_ETC2_Format:he,RGB_PVRTC_4BPPV1_Format:ue,RGBA_S3TC_DXT1_Format:se},qg.EngineType={UnsignedByteType:h,HalfFloatType:S,FloatType:x},qg.BasisWorker=function(){let e,t,n,r=_EngineFormat,i=_EngineType,a=_TranscoderFormat,o=_BasisFormat;self.addEventListener(`message`,function(n){let r=n.data;switch(r.type){case`init`:e=r.config,s(r.transcoderBinary);break;case`transcode`:t.then(()=>{try{let{faces:e,buffers:t,width:n,height:i,hasAlpha:a,format:o,type:s,dfdFlags:l}=c(r.buffer);self.postMessage({type:`transcode`,id:r.id,data:{faces:e,width:n,height:i,hasAlpha:a,format:o,type:s,dfdFlags:l}},t)}catch(e){console.error(e),self.postMessage({type:`error`,id:r.id,error:e.message})}});break}});function s(e){t=new Promise(t=>{n={wasmBinary:e,onRuntimeInitialized:t},BASIS(n)}).then(()=>{n.initializeBasis(),n.KTX2File===void 0&&console.warn(`THREE.KTX2Loader: Please update Basis Universal transcoder.`)})}function c(e){let t=new n.KTX2File(new Uint8Array(e));function r(){t.close(),t.delete()}if(!t.isValid())throw r(),Error(`THREE.KTX2Loader: Invalid or unsupported .ktx2 file`);let a;if(t.isUASTC())a=o.UASTC;else if(t.isETC1S())a=o.ETC1S;else if(t.isHDR())a=o.UASTC_HDR;else throw Error(`THREE.KTX2Loader: Unknown Basis encoding`);let s=t.getWidth(),c=t.getHeight(),l=t.getLayers()||1,u=t.getLevels(),f=t.getFaces(),m=t.getHasAlpha(),h=t.getDFDFlags(),{transcoderFormat:g,engineFormat:_,engineType:v}=d(a,s,c,m);if(!s||!c||!u)throw r(),Error(`THREE.KTX2Loader: Invalid texture`);if(!t.startTranscoding())throw r(),Error(`THREE.KTX2Loader: .startTranscoding failed`);let y=[],b=[];for(let e=0;e<f;e++){let n=[];for(let a=0;a<u;a++){let o=[],s,c;for(let n=0;n<l;n++){let l=t.getImageLevelInfo(a,n,e);e===0&&a===0&&n===0&&(l.origWidth%4!=0||l.origHeight%4!=0)&&console.warn(`THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions.`),u>1?(s=l.origWidth,c=l.origHeight):(s=l.width,c=l.height);let d=new Uint8Array(t.getImageTranscodedSizeInBytes(a,n,0,g)),f=t.transcodeImage(d,a,n,e,g,0,-1,-1);if(v===i.HalfFloatType&&(d=new Uint16Array(d.buffer,d.byteOffset,d.byteLength/Uint16Array.BYTES_PER_ELEMENT)),!f)throw r(),Error(`THREE.KTX2Loader: .transcodeImage failed.`);o.push(d)}let d=p(o);n.push({data:d,width:s,height:c}),b.push(d.buffer)}y.push({mipmaps:n,width:s,height:c,format:_,type:v})}return r(),{faces:y,buffers:b,width:s,height:c,hasAlpha:m,dfdFlags:h,format:_,type:v}}let l=[{if:`astcSupported`,basisFormat:[o.UASTC],transcoderFormat:[a.ASTC_4x4,a.ASTC_4x4],engineFormat:[r.RGBA_ASTC_4x4_Format,r.RGBA_ASTC_4x4_Format],engineType:[i.UnsignedByteType],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:`bptcSupported`,basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[a.BC7_M5,a.BC7_M5],engineFormat:[r.RGBA_BPTC_Format,r.RGBA_BPTC_Format],engineType:[i.UnsignedByteType],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:`dxtSupported`,basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[a.BC1,a.BC3],engineFormat:[r.RGBA_S3TC_DXT1_Format,r.RGBA_S3TC_DXT5_Format],engineType:[i.UnsignedByteType],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:`etc2Supported`,basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[a.ETC1,a.ETC2],engineFormat:[r.RGB_ETC2_Format,r.RGBA_ETC2_EAC_Format],engineType:[i.UnsignedByteType],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:`etc1Supported`,basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[a.ETC1],engineFormat:[r.RGB_ETC1_Format],engineType:[i.UnsignedByteType],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:`pvrtcSupported`,basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[a.PVRTC1_4_RGB,a.PVRTC1_4_RGBA],engineFormat:[r.RGB_PVRTC_4BPPV1_Format,r.RGBA_PVRTC_4BPPV1_Format],engineType:[i.UnsignedByteType],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0},{if:`bptcSupported`,basisFormat:[o.UASTC_HDR],transcoderFormat:[a.BC6H],engineFormat:[r.RGB_BPTC_UNSIGNED_Format],engineType:[i.HalfFloatType],priorityHDR:1,needsPowerOfTwo:!1},{basisFormat:[o.ETC1S,o.UASTC],transcoderFormat:[a.RGBA32,a.RGBA32],engineFormat:[r.RGBAFormat,r.RGBAFormat],engineType:[i.UnsignedByteType,i.UnsignedByteType],priorityETC1S:100,priorityUASTC:100,needsPowerOfTwo:!1},{basisFormat:[o.UASTC_HDR],transcoderFormat:[a.RGBA_HALF],engineFormat:[r.RGBAFormat],engineType:[i.HalfFloatType],priorityHDR:100,needsPowerOfTwo:!1}],u={[o.ETC1S]:l.filter(e=>e.basisFormat.includes(o.ETC1S)).sort((e,t)=>e.priorityUASTC-t.priorityUASTC),[o.UASTC]:l.filter(e=>e.basisFormat.includes(o.UASTC)).sort((e,t)=>e.priorityUASTC-t.priorityUASTC),[o.UASTC_HDR]:l.filter(e=>e.basisFormat.includes(o.UASTC_HDR)).sort((e,t)=>e.priorityHDR-t.priorityHDR)};function d(t,n,r,i){let a=u[t];for(let o=0;o<a.length;o++){let s=a[o];if(!(s.if&&!e[s.if])&&s.basisFormat.includes(t)&&!(i&&s.transcoderFormat.length<2)&&!(s.needsPowerOfTwo&&!(f(n)&&f(r))))return{transcoderFormat:s.transcoderFormat[+!!i],engineFormat:s.engineFormat[+!!i],engineType:s.engineType[0]}}throw Error(`THREE.KTX2Loader: Failed to identify transcoding target.`)}function f(e){return e<=2?!0:(e&e-1)==0&&e!==0}function p(e){if(e.length===1)return e[0];let t=0;for(let n=0;n<e.length;n++){let r=e[n];t+=r.byteLength}let n=new Uint8Array(t),r=0;for(let t=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.byteLength}return n}};var Jg=new Set([k,A,ne]),Yg={109:k,97:k,37:k,43:k,103:A,83:A,16:A,22:A,100:ne,76:ne,15:ne,9:ne,[Ag]:_e,166:j,165:j},Xg={109:x,97:S,37:h,43:h,103:x,83:S,16:h,22:h,100:x,76:S,15:h,9:h,[Ag]:S,166:h,165:h};async function Zg(e){let{vkFormat:t}=e;if(Yg[t]===void 0)throw Error(`THREE.KTX2Loader: Unsupported vkFormat.`);let n;e.supercompressionScheme===2&&(Kg||=new Promise(async e=>{let t=new Bg;await t.init(),e(t)}),n=await Kg);let r=[];for(let i=0;i<e.levels.length;i++){let a=Math.max(1,e.pixelWidth>>i),o=Math.max(1,e.pixelHeight>>i),s=e.pixelDepth?Math.max(1,e.pixelDepth>>i):0,c=e.levels[i],l;if(e.supercompressionScheme===0)l=c.levelData;else if(e.supercompressionScheme===2)l=n.decode(c.levelData,c.uncompressedByteLength);else throw Error(`THREE.KTX2Loader: Unsupported supercompressionScheme.`);let u;u=Xg[t]===1015?new Float32Array(l.buffer,l.byteOffset,l.byteLength/Float32Array.BYTES_PER_ELEMENT):Xg[t]===1016?new Uint16Array(l.buffer,l.byteOffset,l.byteLength/Uint16Array.BYTES_PER_ELEMENT):l,r.push({data:u,width:a,height:o,depth:s})}let i;if(Jg.has(Yg[t]))i=e.pixelDepth===0?new Ui(r[0].data,e.pixelWidth,e.pixelHeight):new $t(r[0].data,e.pixelWidth,e.pixelHeight,e.pixelDepth);else{if(e.pixelDepth>0)throw Error(`THREE.KTX2Loader: Unsupported pixelDepth.`);i=new Aa(r,e.pixelWidth,e.pixelHeight),i.minFilter=r.length===1?f:m,i.magFilter=f}return i.mipmaps=r,i.type=Xg[t],i.format=Yg[t],i.colorSpace=Qg(e),i.needsUpdate=!0,Promise.resolve(i)}function Qg(e){let t=e.dataFormatDescriptor[0];return t.colorPrimaries===1?t.transferFunction===2?Ke:qe:t.colorPrimaries===10?t.transferFunction===2?Hg:Ug:(t.colorPrimaries===0||console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${t.colorPrimaries}"`),``)}var $g=`[default]`,e_={ASSET_GENERATOR:`assetgenerator`},t_=new oo,n_=`https://unpkg.com/[email protected]`,r_=new Dg(t_).setDecoderPath(`${n_}/examples/jsm/libs/draco/gltf/`),i_=new qg(t_).setTranscoderPath(`${n_}/examples/jsm/libs/basis/`);function a_(e,t){let n=new Set;e.traverse(e=>{e.geometry&&(Array.isArray(e.material)?e.material:[e.material]).forEach(e=>{e&&!n.has(e.uuid)&&(n.add(e.uuid),t(e))})})}function o_(e){let{state:t,options:n}=e;if(n.preset===e_.ASSET_GENERATOR){let t=new _o;t.name=`hemi_light`,e.scene.add(t),e.lights.push(t);return}let r=new Mo(t.ambientColor,t.ambientIntensity);r.name=`ambient_light`,e.defaultCamera.add(r);let i=new jo(t.directColor,t.directIntensity);i.position.set(.5,0,.866),i.name=`main_light`,e.defaultCamera.add(i),e.lights.push(r,i)}function s_(e){e.lights.forEach(e=>e.parent.remove(e)),e.lights.length=0}var c_=Uint8Array,l_=Uint16Array,u_=Int32Array,d_=new c_([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),f_=new c_([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),p_=new c_([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),m_=function(e,t){for(var n=new l_(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new u_(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},h_=m_(d_,2),g_=h_.b,__=h_.r;g_[28]=258,__[258]=28;var v_=m_(f_,0),y_=v_.b;v_.r;for(var b_=new l_(32768),x_=0;x_<32768;++x_){var S_=(x_&43690)>>1|(x_&21845)<<1;S_=(S_&52428)>>2|(S_&13107)<<2,S_=(S_&61680)>>4|(S_&3855)<<4,b_[x_]=((S_&65280)>>8|(S_&255)<<8)>>1}for(var C_=(function(e,t,n){for(var r=e.length,i=0,a=new l_(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new l_(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new l_(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[b_[d]>>c]=l}else for(s=new l_(r),i=0;i<r;++i)e[i]&&(s[i]=b_[o[e[i]-1]++]>>15-e[i]);return s}),w_=new c_(288),x_=0;x_<144;++x_)w_[x_]=8;for(var x_=144;x_<256;++x_)w_[x_]=9;for(var x_=256;x_<280;++x_)w_[x_]=7;for(var x_=280;x_<288;++x_)w_[x_]=8;for(var T_=new c_(32),x_=0;x_<32;++x_)T_[x_]=5;var E_=C_(w_,9,1),D_=C_(T_,5,1),O_=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},k_=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},A_=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},j_=function(e){return(e+7)/8|0},M_=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new c_(e.subarray(t,n))},N_=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],P_=function(e,t,n){var r=Error(t||N_[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,P_),!n)throw r;return r},F_=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new c_(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new c_(i*3));var l=function(e){var t=n.length;if(e>t){var r=new c_(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=k_(e,d,1);var v=k_(e,d+1,3);if(d+=3,!v){var y=j_(d)+4,b=e[y-4]|e[y-3]<<8,x=y+b;if(x>i){c&&P_(0);break}s&&l(f+b),n.set(e.subarray(y,x),f),t.b=f+=b,t.p=d=x*8,t.f=u;continue}else if(v==1)p=E_,m=D_,h=9,g=5;else if(v==2){var S=k_(e,d,31)+257,C=k_(e,d+10,15)+4,w=S+k_(e,d+5,31)+1;d+=14;for(var T=new c_(w),E=new c_(19),D=0;D<C;++D)E[p_[D]]=k_(e,d+D*3,7);d+=C*3;for(var O=O_(E),k=(1<<O)-1,ee=C_(E,O,1),D=0;D<w;){var te=ee[k_(e,d,k)];d+=te&15;var y=te>>4;if(y<16)T[D++]=y;else{var ne=0,re=0;for(y==16?(re=3+k_(e,d,3),d+=2,ne=T[D-1]):y==17?(re=3+k_(e,d,7),d+=3):y==18&&(re=11+k_(e,d,127),d+=7);re--;)T[D++]=ne}}var A=T.subarray(0,S),ie=T.subarray(S);h=O_(A),g=O_(ie),p=C_(A,h,1),m=C_(ie,g,1)}else P_(1);if(d>_){c&&P_(0);break}}s&&l(f+131072);for(var ae=(1<<h)-1,oe=(1<<g)-1,se=d;;se=d){var ne=p[A_(e,d)&ae],ce=ne>>4;if(d+=ne&15,d>_){c&&P_(0);break}if(ne||P_(2),ce<256)n[f++]=ce;else if(ce==256){se=d,p=null;break}else{var le=ce-254;if(ce>264){var D=ce-257,ue=d_[D];le=k_(e,d,(1<<ue)-1)+g_[D],d+=ue}var de=m[A_(e,d)&oe],fe=de>>4;de||P_(3),d+=de&15;var ie=y_[fe];if(fe>3){var ue=f_[fe];ie+=A_(e,d)&(1<<ue)-1,d+=ue}if(d>_){c&&P_(0);break}s&&l(f+131072);var pe=f+le;if(f<ie){var me=a-ie,he=Math.min(ie,pe);for(me+f<0&&P_(3);f<he;++f)n[f]=r[me+f]}for(;f<pe;++f)n[f]=n[f-ie]}}t.l=p,t.p=se,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?M_(n,0,f):n.subarray(0,f)},I_=new c_(0),L_=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&P_(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&P_(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function R_(e,t){return F_(e.subarray(L_(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}var z_=typeof TextDecoder<`u`&&new TextDecoder;try{z_.decode(I_,{stream:!0})}catch{}var B_=class extends mo{constructor(e){super(e),this.type=S}parse(e){let t=65536,n=t>>3,r=65537,i=16384,a=i-1,o=65535,s=2.7182818**2.2;function c(e,n){let r=0;for(let i=0;i<t;++i)(i==0||e[i>>3]&1<<(i&7))&&(n[r++]=i);let i=r-1;for(;r<t;)n[r++]=0;return i}function l(e){for(let t=0;t<i;t++)e[t]={},e[t].len=0,e[t].lit=0,e[t].p=null}let u={l:0,c:0,lc:0};function d(e,t,n,r,i){for(;n<e;)t=t<<8|we(r,i),n+=8;n-=e,u.l=t>>n&(1<<e)-1,u.c=t,u.lc=n}let f=Array(59);function p(e){for(let e=0;e<=58;++e)f[e]=0;for(let t=0;t<r;++t)f[e[t]]+=1;let t=0;for(let e=58;e>0;--e){let n=t+f[e]>>1;f[e]=t,t=n}for(let t=0;t<r;++t){let n=e[t];n>0&&(e[t]=n|f[n]++<<6)}}function m(e,t,n,r,i,a){let o=t,s=0,c=0;for(;r<=i;r++){if(o.value-t.value>n)return!1;d(6,s,c,e,o);let l=u.l;if(s=u.c,c=u.lc,a[r]=l,l==63){if(o.value-t.value>n)throw Error(`Something wrong with hufUnpackEncTable`);d(8,s,c,e,o);let l=u.l+6;if(s=u.c,c=u.lc,r+l>i+1)throw Error(`Something wrong with hufUnpackEncTable`);for(;l--;)a[r++]=0;r--}else if(l>=59){let e=l-59+2;if(r+e>i+1)throw Error(`Something wrong with hufUnpackEncTable`);for(;e--;)a[r++]=0;r--}}p(a)}function h(e){return e&63}function g(e){return e>>6}function _(e,t,n,r){for(;t<=n;t++){let n=g(e[t]),i=h(e[t]);if(n>>i)throw Error(`Invalid table entry`);if(i>14){let e=r[n>>i-14];if(e.len)throw Error(`Invalid table entry`);if(e.lit++,e.p){let t=e.p;e.p=Array(e.lit);for(let n=0;n<e.lit-1;++n)e.p[n]=t[n]}else e.p=[,];e.p[e.lit-1]=t}else if(i){let e=0;for(let a=1<<14-i;a>0;a--){let a=r[(n<<14-i)+e];if(a.len||a.p)throw Error(`Invalid table entry`);a.len=i,a.lit=t,e++}}}return!0}let v={c:0,lc:0};function y(e,t,n,r){e=e<<8|we(n,r),t+=8,v.c=e,v.lc=t}let b={c:0,lc:0};function C(e,t,n,r,i,a,o,s,c){if(e==t){r<8&&(y(n,r,i,a),n=v.c,r=v.lc),r-=8;let e=n>>r;if(e=new Uint8Array([e])[0],s.value+e>c)return!1;let t=o[s.value-1];for(;e-- >0;)o[s.value++]=t}else if(s.value<c)o[s.value++]=e;else return!1;b.c=n,b.lc=r}function w(e){return e&65535}function T(e){let t=w(e);return t>32767?t-65536:t}let E={a:0,b:0};function D(e,t){let n=T(e),r=T(t),i=n+(r&1)+(r>>1),a=i,o=i-r;E.a=a,E.b=o}function O(e,t){let n=w(e),r=w(t),i=n-(r>>1)&o;E.a=r+i-32768&o,E.b=i}function ee(e,t,n,r,i,a,o){let s=o<16384,c=n>i?i:n,l=1,u,d;for(;l<=c;)l<<=1;for(l>>=1,u=l,l>>=1;l>=1;){d=0;let o=d+a*(i-u),c=a*l,f=a*u,p=r*l,m=r*u,h,g,_,v;for(;d<=o;d+=f){let i=d,a=d+r*(n-u);for(;i<=a;i+=m){let n=i+p,r=i+c,a=r+p;s?(D(e[i+t],e[r+t]),h=E.a,_=E.b,D(e[n+t],e[a+t]),g=E.a,v=E.b,D(h,g),e[i+t]=E.a,e[n+t]=E.b,D(_,v),e[r+t]=E.a,e[a+t]=E.b):(O(e[i+t],e[r+t]),h=E.a,_=E.b,O(e[n+t],e[a+t]),g=E.a,v=E.b,O(h,g),e[i+t]=E.a,e[n+t]=E.b,O(_,v),e[r+t]=E.a,e[a+t]=E.b)}if(n&l){let n=i+c;s?D(e[i+t],e[n+t]):O(e[i+t],e[n+t]),h=E.a,e[n+t]=E.b,e[i+t]=h}}if(i&l){let i=d,a=d+r*(n-u);for(;i<=a;i+=m){let n=i+p;s?D(e[i+t],e[n+t]):O(e[i+t],e[n+t]),h=E.a,e[n+t]=E.b,e[i+t]=h}}u=l,l>>=1}return d}function te(e,t,n,r,i,o,s,c,l){let u=0,d=0,f=s,p=Math.trunc(r.value+(i+7)/8);for(;r.value<p;)for(y(u,d,n,r),u=v.c,d=v.lc;d>=14;){let i=t[u>>d-14&a];if(i.len)d-=i.len,C(i.lit,o,u,d,n,r,c,l,f),u=b.c,d=b.lc;else{if(!i.p)throw Error(`hufDecode issues`);let t;for(t=0;t<i.lit;t++){let a=h(e[i.p[t]]);for(;d<a&&r.value<p;)y(u,d,n,r),u=v.c,d=v.lc;if(d>=a&&g(e[i.p[t]])==(u>>d-a&(1<<a)-1)){d-=a,C(i.p[t],o,u,d,n,r,c,l,f),u=b.c,d=b.lc;break}}if(t==i.lit)throw Error(`hufDecode issues`)}}let m=8-i&7;for(u>>=m,d-=m;d>0;){let e=t[u<<14-d&a];if(e.len)d-=e.len,C(e.lit,o,u,d,n,r,c,l,f),u=b.c,d=b.lc;else throw Error(`hufDecode issues`)}return!0}function re(e,t,n,a,o,s){let c={value:0},u=n.value,d=M(t,n),f=M(t,n);n.value+=4;let p=M(t,n);if(n.value+=4,d<0||d>=r||f<0||f>=r)throw Error(`Something wrong with HUF_ENCSIZE`);let h=Array(r),g=Array(i);if(l(g),m(e,n,a-(n.value-u),d,f,h),p>8*(a-(n.value-u)))throw Error(`Something wrong with hufUncompress`);_(h,d,f,g),te(h,g,e,n,p,f,s,o,c)}function A(e,t,n){for(let r=0;r<n;++r)t[r]=e[t[r]]}function ie(e){for(let t=1;t<e.length;t++)e[t]=e[t-1]+e[t]-128}function ae(e,t){let n=0,r=Math.floor((e.length+1)/2),i=0,a=e.length-1;for(;!(i>a||(t[i++]=e[n++],i>a));)t[i++]=e[r++]}function oe(e){let t=e.byteLength,n=[],r=0,i=new DataView(e);for(;t>0;){let e=i.getInt8(r++);if(e<0){let a=-e;t-=a+1;for(let e=0;e<a;e++)n.push(i.getUint8(r++))}else{let a=e;t-=2;let o=i.getUint8(r++);for(let e=0;e<a+1;e++)n.push(o)}}return n}function se(e,t,n,r,i,a){let o=new DataView(a.buffer),s=n[e.idx[0]].width,c=n[e.idx[0]].height,l=Math.floor(s/8),u=Math.ceil(s/8),d=Math.ceil(c/8),f=s-(u-1)*8,p=c-(d-1)*8,m={value:0},h=[,,,],g=[,,,],_=[,,,],v=[,,,],y=[,,,];for(let n=0;n<3;++n)y[n]=t[e.idx[n]],h[n]=n<1?0:h[n-1]+u*d,g[n]=new Float32Array(64),_[n]=new Uint16Array(64),v[n]=new Uint16Array(u*64);for(let t=0;t<d;++t){let a=8;t==d-1&&(a=p);let s=8;for(let e=0;e<u;++e){e==u-1&&(s=f);for(let e=0;e<3;++e)_[e].fill(0),_[e][0]=i[h[e]++],ce(m,r,_[e]),le(_[e],g[e]),ue(g[e]);de(g);for(let t=0;t<3;++t)fe(g[t],v[t],e*64)}let c=0;for(let r=0;r<3;++r){let i=n[e.idx[r]].type;for(let e=8*t;e<8*t+a;++e){c=y[r][e];for(let t=0;t<l;++t){let n=t*64+(e&7)*8;o.setUint16(c+0*i,v[r][n+0],!0),o.setUint16(c+2*i,v[r][n+1],!0),o.setUint16(c+4*i,v[r][n+2],!0),o.setUint16(c+6*i,v[r][n+3],!0),o.setUint16(c+8*i,v[r][n+4],!0),o.setUint16(c+10*i,v[r][n+5],!0),o.setUint16(c+12*i,v[r][n+6],!0),o.setUint16(c+14*i,v[r][n+7],!0),c+=16*i}}if(l!=u)for(let e=8*t;e<8*t+a;++e){let t=y[r][e]+8*l*2*i,n=l*64+(e&7)*8;for(let e=0;e<s;++e)o.setUint16(t+e*2*i,v[r][n+e],!0)}}}let b=new Uint16Array(s);o=new DataView(a.buffer);for(let t=0;t<3;++t){n[e.idx[t]].decoded=!0;let r=n[e.idx[t]].type;if(n[t].type==2)for(let e=0;e<c;++e){let n=y[t][e];for(let e=0;e<s;++e)b[e]=o.getUint16(n+e*2*r,!0);for(let e=0;e<s;++e)o.setFloat32(n+e*2*r,F(b[e]),!0)}}}function ce(e,t,n){let r,i=1;for(;i<64;)r=t[e.value],r==65280?i=64:r>>8==255?i+=r&255:(n[i]=r,i++),e.value++}function le(e,t){t[0]=F(e[0]),t[1]=F(e[1]),t[2]=F(e[5]),t[3]=F(e[6]),t[4]=F(e[14]),t[5]=F(e[15]),t[6]=F(e[27]),t[7]=F(e[28]),t[8]=F(e[2]),t[9]=F(e[4]),t[10]=F(e[7]),t[11]=F(e[13]),t[12]=F(e[16]),t[13]=F(e[26]),t[14]=F(e[29]),t[15]=F(e[42]),t[16]=F(e[3]),t[17]=F(e[8]),t[18]=F(e[12]),t[19]=F(e[17]),t[20]=F(e[25]),t[21]=F(e[30]),t[22]=F(e[41]),t[23]=F(e[43]),t[24]=F(e[9]),t[25]=F(e[11]),t[26]=F(e[18]),t[27]=F(e[24]),t[28]=F(e[31]),t[29]=F(e[40]),t[30]=F(e[44]),t[31]=F(e[53]),t[32]=F(e[10]),t[33]=F(e[19]),t[34]=F(e[23]),t[35]=F(e[32]),t[36]=F(e[39]),t[37]=F(e[45]),t[38]=F(e[52]),t[39]=F(e[54]),t[40]=F(e[20]),t[41]=F(e[22]),t[42]=F(e[33]),t[43]=F(e[38]),t[44]=F(e[46]),t[45]=F(e[51]),t[46]=F(e[55]),t[47]=F(e[60]),t[48]=F(e[21]),t[49]=F(e[34]),t[50]=F(e[37]),t[51]=F(e[47]),t[52]=F(e[50]),t[53]=F(e[56]),t[54]=F(e[59]),t[55]=F(e[61]),t[56]=F(e[35]),t[57]=F(e[36]),t[58]=F(e[48]),t[59]=F(e[49]),t[60]=F(e[57]),t[61]=F(e[58]),t[62]=F(e[62]),t[63]=F(e[63])}function ue(e){let t=.5*Math.cos(3.14159/4),n=.5*Math.cos(3.14159/16),r=.5*Math.cos(3.14159/8),i=.5*Math.cos(3*3.14159/16),a=.5*Math.cos(5*3.14159/16),o=.5*Math.cos(3*3.14159/8),s=.5*Math.cos(7*3.14159/16),c=[,,,,],l=[,,,,],u=[,,,,],d=[,,,,];for(let f=0;f<8;++f){let p=f*8;c[0]=r*e[p+2],c[1]=o*e[p+2],c[2]=r*e[p+6],c[3]=o*e[p+6],l[0]=n*e[p+1]+i*e[p+3]+a*e[p+5]+s*e[p+7],l[1]=i*e[p+1]-s*e[p+3]-n*e[p+5]-a*e[p+7],l[2]=a*e[p+1]-n*e[p+3]+s*e[p+5]+i*e[p+7],l[3]=s*e[p+1]-a*e[p+3]+i*e[p+5]-n*e[p+7],u[0]=t*(e[p+0]+e[p+4]),u[3]=t*(e[p+0]-e[p+4]),u[1]=c[0]+c[3],u[2]=c[1]-c[2],d[0]=u[0]+u[1],d[1]=u[3]+u[2],d[2]=u[3]-u[2],d[3]=u[0]-u[1],e[p+0]=d[0]+l[0],e[p+1]=d[1]+l[1],e[p+2]=d[2]+l[2],e[p+3]=d[3]+l[3],e[p+4]=d[3]-l[3],e[p+5]=d[2]-l[2],e[p+6]=d[1]-l[1],e[p+7]=d[0]-l[0]}for(let f=0;f<8;++f)c[0]=r*e[16+f],c[1]=o*e[16+f],c[2]=r*e[48+f],c[3]=o*e[48+f],l[0]=n*e[8+f]+i*e[24+f]+a*e[40+f]+s*e[56+f],l[1]=i*e[8+f]-s*e[24+f]-n*e[40+f]-a*e[56+f],l[2]=a*e[8+f]-n*e[24+f]+s*e[40+f]+i*e[56+f],l[3]=s*e[8+f]-a*e[24+f]+i*e[40+f]-n*e[56+f],u[0]=t*(e[f]+e[32+f]),u[3]=t*(e[f]-e[32+f]),u[1]=c[0]+c[3],u[2]=c[1]-c[2],d[0]=u[0]+u[1],d[1]=u[3]+u[2],d[2]=u[3]-u[2],d[3]=u[0]-u[1],e[0+f]=d[0]+l[0],e[8+f]=d[1]+l[1],e[16+f]=d[2]+l[2],e[24+f]=d[3]+l[3],e[32+f]=d[3]-l[3],e[40+f]=d[2]-l[2],e[48+f]=d[1]-l[1],e[56+f]=d[0]-l[0]}function de(e){for(let t=0;t<64;++t){let n=e[0][t],r=e[1][t],i=e[2][t];e[0][t]=n+1.5747*i,e[1][t]=n-.1873*r-.4682*i,e[2][t]=n+1.8556*r}}function fe(e,t,n){for(let r=0;r<64;++r)t[n+r]=Ar.toHalfFloat(pe(e[r]))}function pe(e){return e<=1?Math.sign(e)*Math.abs(e)**2.2:Math.sign(e)*s**(Math.abs(e)-1)}function me(e){return new DataView(e.array.buffer,e.offset.value,e.size)}function he(e){let t=e.viewer.buffer.slice(e.offset.value,e.offset.value+e.size),n=new Uint8Array(oe(t)),r=new Uint8Array(n.length);return ie(n),ae(n,r),new DataView(r.buffer)}function ge(e){let t=R_(e.array.slice(e.offset.value,e.offset.value+e.size)),n=new Uint8Array(t.length);return ie(t),ae(t,n),new DataView(n.buffer)}function _e(e){let r=e.viewer,i={value:e.offset.value},a=new Uint16Array(e.columns*e.lines*(e.inputChannels.length*e.type)),o=new Uint8Array(n),s=0,l=Array(e.inputChannels.length);for(let t=0,n=e.inputChannels.length;t<n;t++)l[t]={},l[t].start=s,l[t].end=l[t].start,l[t].nx=e.columns,l[t].ny=e.lines,l[t].size=e.type,s+=l[t].nx*l[t].ny*l[t].size;let u=De(r,i),d=De(r,i);if(d>=n)throw Error(`Something is wrong with PIZ_COMPRESSION BITMAP_SIZE`);if(u<=d)for(let e=0;e<d-u+1;e++)o[e+u]=N(r,i);let f=new Uint16Array(t),p=c(o,f),m=M(r,i);re(e.array,r,i,m,a,s);for(let t=0;t<e.inputChannels.length;++t){let e=l[t];for(let n=0;n<l[t].size;++n)ee(a,e.start+n,e.nx,e.size,e.ny,e.nx*e.size,p)}A(f,a,s);let h=0,g=new Uint8Array(a.buffer.byteLength);for(let t=0;t<e.lines;t++)for(let t=0;t<e.inputChannels.length;t++){let e=l[t],n=e.nx*e.size,r=new Uint8Array(a.buffer,e.end*2,n*2);g.set(r,h),h+=n*2,e.end+=n}return new DataView(g.buffer)}function ve(e){let t=R_(e.array.slice(e.offset.value,e.offset.value+e.size)),n=e.inputChannels.length*e.lines*e.columns*e.totalBytes,r=new ArrayBuffer(n),i=new DataView(r),a=0,o=0,s=[,,,,];for(let n=0;n<e.lines;n++)for(let n=0;n<e.inputChannels.length;n++){let r=0;switch(e.inputChannels[n].pixelType){case 1:s[0]=a,s[1]=s[0]+e.columns,a=s[1]+e.columns;for(let n=0;n<e.columns;++n){let e=t[s[0]++]<<8|t[s[1]++];r+=e,i.setUint16(o,r,!0),o+=2}break;case 2:s[0]=a,s[1]=s[0]+e.columns,s[2]=s[1]+e.columns,a=s[2]+e.columns;for(let n=0;n<e.columns;++n){let e=t[s[0]++]<<24|t[s[1]++]<<16|t[s[2]++]<<8;r+=e,i.setUint32(o,r,!0),o+=4}break}}return i}function ye(e){let t=e.viewer,n={value:e.offset.value},r=new Uint8Array(e.columns*e.lines*(e.inputChannels.length*e.type*2)),i={version:P(t,n),unknownUncompressedSize:P(t,n),unknownCompressedSize:P(t,n),acCompressedSize:P(t,n),dcCompressedSize:P(t,n),rleCompressedSize:P(t,n),rleUncompressedSize:P(t,n),rleRawSize:P(t,n),totalAcUncompressedCount:P(t,n),totalDcUncompressedCount:P(t,n),acCompression:P(t,n)};if(i.version<2)throw Error(`EXRLoader.parse: `+Xe.compression+` version `+i.version+` is unsupported`);let a=[],o=De(t,n)-2;for(;o>0;){let e=be(t.buffer,n),r=N(t,n),i=r>>2&3,s=(r>>4)-1,c=new Int8Array([s])[0],l=N(t,n);a.push({name:e,index:c,type:l,compression:i}),o-=e.length+3}let s=Xe.channels,c=Array(e.inputChannels.length);for(let t=0;t<e.inputChannels.length;++t){let n=c[t]={},r=s[t];n.name=r.name,n.compression=0,n.decoded=!1,n.type=r.pixelType,n.pLinear=r.pLinear,n.width=e.columns,n.height=e.lines}let l={idx:[,,,]};for(let t=0;t<e.inputChannels.length;++t){let e=c[t];for(let n=0;n<a.length;++n){let r=a[n];e.name==r.name&&(e.compression=r.compression,r.index>=0&&(l.idx[r.index]=t),e.offset=t)}}let u,d,f;if(i.acCompressedSize>0)switch(i.acCompression){case 0:u=new Uint16Array(i.totalAcUncompressedCount),re(e.array,t,n,i.acCompressedSize,u,i.totalAcUncompressedCount);break;case 1:let r=R_(e.array.slice(n.value,n.value+i.totalAcUncompressedCount));u=new Uint16Array(r.buffer),n.value+=i.totalAcUncompressedCount;break}if(i.dcCompressedSize>0){let t={array:e.array,offset:n,size:i.dcCompressedSize};d=new Uint16Array(ge(t).buffer),n.value+=i.dcCompressedSize}i.rleRawSize>0&&(f=oe(R_(e.array.slice(n.value,n.value+i.rleCompressedSize)).buffer),n.value+=i.rleCompressedSize);let p=0,m=Array(c.length);for(let e=0;e<m.length;++e)m[e]=[];for(let t=0;t<e.lines;++t)for(let t=0;t<c.length;++t)m[t].push(p),p+=c[t].width*e.type*2;se(l,m,c,u,d,r);for(let t=0;t<c.length;++t){let n=c[t];if(!n.decoded)switch(n.compression){case 2:let i=0,a=0;for(let o=0;o<e.lines;++o){let e=m[t][i];for(let t=0;t<n.width;++t){for(let t=0;t<2*n.type;++t)r[e++]=f[a+t*n.width*n.height];a++}i++}break;default:throw Error(`EXRLoader.parse: unsupported channel compression`)}}return new DataView(r.buffer)}function be(e,t){let n=new Uint8Array(e),r=0;for(;n[t.value+r]!=0;)r+=1;let i=new TextDecoder().decode(n.slice(t.value,t.value+r));return t.value=t.value+r+1,i}function j(e,t,n){let r=new TextDecoder().decode(new Uint8Array(e).slice(t.value,t.value+n));return t.value+=n,r}function xe(e,t){return[Ce(e,t),M(e,t)]}function Se(e,t){return[M(e,t),M(e,t)]}function Ce(e,t){let n=e.getInt32(t.value,!0);return t.value+=4,n}function M(e,t){let n=e.getUint32(t.value,!0);return t.value+=4,n}function we(e,t){let n=e[t.value];return t.value+=1,n}function N(e,t){let n=e.getUint8(t.value);return t.value+=1,n}let P=function(e,t){let n;return n=`getBigInt64`in DataView.prototype?Number(e.getBigInt64(t.value,!0)):e.getUint32(t.value+4,!0)+Number(e.getUint32(t.value,!0)<<32),t.value+=8,n};function Te(e,t){let n=e.getFloat32(t.value,!0);return t.value+=4,n}function Ee(e,t){return Ar.toHalfFloat(Te(e,t))}function F(e){let t=(e&31744)>>10,n=e&1023;return(e>>15?-1:1)*(t?t===31?n?NaN:1/0:2**(t-15)*(1+n/1024):n/1024*6103515625e-14)}function De(e,t){let n=e.getUint16(t.value,!0);return t.value+=2,n}function Oe(e,t){return F(De(e,t))}function ke(e,t,n,r){let i=n.value,a=[];for(;n.value<i+r-1;){let r=be(t,n),i=Ce(e,n),o=N(e,n);n.value+=3;let s=Ce(e,n),c=Ce(e,n);a.push({name:r,pixelType:i,pLinear:o,xSampling:s,ySampling:c})}return n.value+=1,a}function Ae(e,t){return{redX:Te(e,t),redY:Te(e,t),greenX:Te(e,t),greenY:Te(e,t),blueX:Te(e,t),blueY:Te(e,t),whiteX:Te(e,t),whiteY:Te(e,t)}}function je(e,t){return[`NO_COMPRESSION`,`RLE_COMPRESSION`,`ZIPS_COMPRESSION`,`ZIP_COMPRESSION`,`PIZ_COMPRESSION`,`PXR24_COMPRESSION`,`B44_COMPRESSION`,`B44A_COMPRESSION`,`DWAA_COMPRESSION`,`DWAB_COMPRESSION`][N(e,t)]}function Me(e,t){return{xMin:Ce(e,t),yMin:Ce(e,t),xMax:Ce(e,t),yMax:Ce(e,t)}}function Ne(e,t){return[`INCREASING_Y`,`DECREASING_Y`,`RANDOM_Y`][N(e,t)]}function Pe(e,t){return[`ENVMAP_LATLONG`,`ENVMAP_CUBE`][N(e,t)]}function Fe(e,t){let n=[`ONE_LEVEL`,`MIPMAP_LEVELS`,`RIPMAP_LEVELS`],r=[`ROUND_DOWN`,`ROUND_UP`],i=M(e,t),a=M(e,t),o=N(e,t);return{xSize:i,ySize:a,levelMode:n[o&15],roundingMode:r[o>>4]}}function Ie(e,t){return[Te(e,t),Te(e,t)]}function Le(e,t){return[Te(e,t),Te(e,t),Te(e,t)]}function Re(e,t,n,r,i){if(r===`string`||r===`stringvector`||r===`iccProfile`)return j(t,n,i);if(r===`chlist`)return ke(e,t,n,i);if(r===`chromaticities`)return Ae(e,n);if(r===`compression`)return je(e,n);if(r===`box2i`)return Me(e,n);if(r===`envmap`)return Pe(e,n);if(r===`tiledesc`)return Fe(e,n);if(r===`lineOrder`)return Ne(e,n);if(r===`float`)return Te(e,n);if(r===`v2f`)return Ie(e,n);if(r===`v3f`)return Le(e,n);if(r===`int`)return Ce(e,n);if(r===`rational`)return xe(e,n);if(r===`timecode`)return Se(e,n);if(r===`preview`)return n.value+=i,`skipped`;n.value+=i}function ze(e,t){let n=Math.log2(e);return t==`ROUND_DOWN`?Math.floor(n):Math.ceil(n)}function Be(e,t,n){let r=0;switch(e.levelMode){case`ONE_LEVEL`:r=1;break;case`MIPMAP_LEVELS`:r=ze(Math.max(t,n),e.roundingMode)+1;break;case`RIPMAP_LEVELS`:throw Error(`THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.`)}return r}function Ve(e,t,n,r){let i=Array(e);for(let a=0;a<e;a++){let e=1<<a,o=t/e|0;r==`ROUND_UP`&&o*e<t&&(o+=1),i[a]=(Math.max(o,1)+n-1)/n|0}return i}function He(){let e=this,t=e.offset,n={value:0};for(let r=0;r<e.tileCount;r++){let r=Ce(e.viewer,t),i=Ce(e.viewer,t);t.value+=8,e.size=M(e.viewer,t);let a=r*e.blockWidth,o=i*e.blockHeight;e.columns=a+e.blockWidth>e.width?e.width-a:e.blockWidth,e.lines=o+e.blockHeight>e.height?e.height-o:e.blockHeight;let s=e.columns*e.totalBytes,c=e.size<e.lines*s?e.uncompress(e):me(e);t.value+=e.size;for(let t=0;t<e.lines;t++){let r=t*e.columns*e.totalBytes;for(let i=0;i<e.inputChannels.length;i++){let s=Xe.channels[i].name,l=e.channelByteOffsets[s]*e.columns,u=e.decodeChannels[s];if(u===void 0)continue;n.value=r+l;let d=(e.height-(1+o+t))*e.outLineWidth;for(let t=0;t<e.columns;t++){let r=d+(t+a)*e.outputChannels+u;e.byteArray[r]=e.getter(c,n)}}}}}function Ue(){let e=this,t=e.offset,n={value:0};for(let r=0;r<e.height/e.blockHeight;r++){let i=Ce(e.viewer,t)-Xe.dataWindow.yMin;e.size=M(e.viewer,t),e.lines=i+e.blockHeight>e.height?e.height-i:e.blockHeight;let a=e.columns*e.totalBytes,o=e.size<e.lines*a?e.uncompress(e):me(e);t.value+=e.size;for(let t=0;t<e.blockHeight;t++){let i=r*e.blockHeight,s=t+e.scanOrder(i);if(s>=e.height)continue;let c=t*a,l=(e.height-1-s)*e.outLineWidth;for(let t=0;t<e.inputChannels.length;t++){let r=Xe.channels[t].name,i=e.channelByteOffsets[r]*e.columns,a=e.decodeChannels[r];if(a!==void 0){n.value=c+i;for(let t=0;t<e.columns;t++){let r=l+t*e.outputChannels+a;e.byteArray[r]=e.getter(o,n)}}}}}}function We(e,t,n){let r={};if(e.getUint32(0,!0)!=20000630)throw Error(`THREE.EXRLoader: Provided file doesn't appear to be in OpenEXR format.`);r.version=e.getUint8(4);let i=e.getUint8(5);r.spec={singleTile:!!(i&2),longName:!!(i&4),deepFormat:!!(i&8),multiPart:!!(i&16)},n.value=8;let a=!0;for(;a;){let i=be(t,n);if(i===``)a=!1;else{let a=be(t,n),o=Re(e,t,n,a,M(e,n));o===void 0?console.warn(`THREE.EXRLoader: Skipped unknown header attribute type \'${a}\'.`):r[i]=o}}if(i&-7)throw console.error(`THREE.EXRHeader:`,r),Error(`THREE.EXRLoader: Provided file is currently unsupported.`);return r}function Ge(e,t,n,r,i){let a={size:0,viewer:t,array:n,offset:r,width:e.dataWindow.xMax-e.dataWindow.xMin+1,height:e.dataWindow.yMax-e.dataWindow.yMin+1,inputChannels:e.channels,channelByteOffsets:{},scanOrder:null,totalBytes:null,columns:null,lines:null,type:null,uncompress:null,getter:null,format:null,colorSpace:qe};switch(e.compression){case`NO_COMPRESSION`:a.blockHeight=1,a.uncompress=me;break;case`RLE_COMPRESSION`:a.blockHeight=1,a.uncompress=he;break;case`ZIPS_COMPRESSION`:a.blockHeight=1,a.uncompress=ge;break;case`ZIP_COMPRESSION`:a.blockHeight=16,a.uncompress=ge;break;case`PIZ_COMPRESSION`:a.blockHeight=32,a.uncompress=_e;break;case`PXR24_COMPRESSION`:a.blockHeight=16,a.uncompress=ve;break;case`DWAA_COMPRESSION`:a.blockHeight=32,a.uncompress=ye;break;case`DWAB_COMPRESSION`:a.blockHeight=256,a.uncompress=ye;break;default:throw Error(`EXRLoader.parse: `+e.compression+` is unsupported`)}let o={};for(let t of e.channels)switch(t.name){case`Y`:case`R`:case`G`:case`B`:case`A`:o[t.name]=!0,a.type=t.pixelType}let s=!1;if(o.R&&o.G&&o.B)s=!o.A,a.outputChannels=4,a.decodeChannels={R:0,G:1,B:2,A:3};else if(o.Y)a.outputChannels=1,a.decodeChannels={Y:0};else throw Error(`EXRLoader.parse: file contains unsupported data channels.`);if(a.type==1)switch(i){case x:a.getter=Oe;break;case S:a.getter=De;break}else if(a.type==2)switch(i){case x:a.getter=Te;break;case S:a.getter=Ee}else throw Error(`EXRLoader.parse: unsupported pixelType `+a.type+` for `+e.compression+`.`);a.columns=a.width;let c=a.width*a.height*a.outputChannels;switch(i){case x:a.byteArray=new Float32Array(c),s&&a.byteArray.fill(1,0,c);break;case S:a.byteArray=new Uint16Array(c),s&&a.byteArray.fill(15360,0,c);break;default:console.error(`THREE.EXRLoader: unsupported type: `,i);break}let l=0;for(let t of e.channels)a.decodeChannels[t.name]!==void 0&&(a.channelByteOffsets[t.name]=l),l+=t.pixelType*2;if(a.totalBytes=l,a.outLineWidth=a.width*a.outputChannels,e.lineOrder===`INCREASING_Y`?a.scanOrder=e=>e:a.scanOrder=e=>a.height-1-e,a.outputChannels==4?(a.format=k,a.colorSpace=qe):(a.format=ne,a.colorSpace=``),e.spec.singleTile){a.blockHeight=e.tiles.ySize,a.blockWidth=e.tiles.xSize;let n=Be(e.tiles,a.width,a.height),i=Ve(n,a.width,e.tiles.xSize,e.tiles.roundingMode),o=Ve(n,a.height,e.tiles.ySize,e.tiles.roundingMode);a.tileCount=i[0]*o[0];for(let e=0;e<n;e++)for(let n=0;n<o[e];n++)for(let n=0;n<i[e];n++)P(t,r);a.decode=He.bind(a)}else{a.blockWidth=a.width;let e=Math.ceil(a.height/a.blockHeight);for(let n=0;n<e;n++)P(t,r);a.decode=Ue.bind(a)}return a}let Ke={value:0},Je=new DataView(e),Ye=new Uint8Array(e),Xe=We(Je,e,Ke),Ze=Ge(Xe,Je,Ye,Ke,this.type);return Ze.decode(),{header:Xe,width:Ze.width,height:Ze.height,data:Ze.byteArray,format:Ze.format,colorSpace:Ze.colorSpace,type:this.type}}setDataType(e){return this.type=e,this}load(e,t,n,r){function i(e,n){e.colorSpace=n.colorSpace,e.minFilter=f,e.magFilter=f,e.generateMipmaps=!1,e.flipY=!1,t&&t(e,n)}return super.load(e,i,n,r)}};function V_(e,t){let{id:n,path:r}=t;return n===`neutral`?Promise.resolve({envMap:e.neutralEnvironment}):n===``?Promise.resolve({envMap:null}):new Promise((t,n)=>{new B_().load(r,n=>{let r=e.pmremGenerator.fromEquirectangular(n).texture;n.dispose(),e._loadedEnvironment&&e._loadedEnvironment!==r&&e._loadedEnvironment.dispose(),e._loadedEnvironment=r,t({envMap:r})},void 0,n)})}function H_(e){e.renderer.render(e.scene,e.activeCamera),e.renderer.domElement.toBlob(e=>{if(!e)return;let t=new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19),n=URL.createObjectURL(e),r=document.createElement(`a`);r.download=`3d-screenshot-${t}.png`,r.href=n,r.click(),URL.revokeObjectURL(n)},`image/png`),U_(e)}function U_(e){let t=document.createElement(`div`);t.className=`screenshot-flash`,e.el.appendChild(t),t.addEventListener(`animationend`,()=>t.remove())}function W_(e,t){e.mixer&&=(e.mixer.stopAllAction(),e.mixer.uncacheRoot(e.mixer.getRoot()),null),e.clips=t,t.length&&(e.mixer=new Zo(e.content))}function G_(e){e.clips.forEach(t=>{e.mixer.clipAction(t).reset().play(),e.state.actionStates[t.name]=!0}),e.invalidate()}var K_=.35,q_=class{constructor(){this.model=null,this.mixer=null,this.clips=new Map,this.actions=new Map,this.currentName=null,this.currentAction=null,this.loader=new pu,this.onChange=null,this._animationDefs=[]}attach(e){this.detach(),this.model=e,this.mixer=new Zo(e),this.actions.clear(),this.currentAction=null,this.currentName=null;for(let[e,t]of this.clips){let n=this._retargetClip(t,e),r=this.mixer.clipAction(n);r.enabled=!0,this.actions.set(e,r)}}detach(){this.mixer&&=(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this.mixer.getRoot()),null),this.model=null,this.actions.clear(),this.currentAction=null,this.currentName=null}setAnimationDefs(e){this._animationDefs=e}getAnimationDefs(){return this._animationDefs}async loadAnimation(e,t,n={}){if(this.clips.has(e))return this.clips.get(e);let r=(await new Promise((e,n)=>{this.loader.load(t,e,void 0,n)})).animations[0];if(!r)throw Error(`No animation found in ${t}`);if(r.name=e,this.clips.set(e,r),this.model&&this.mixer){let t=this._retargetClip(r,e),i=this.mixer.clipAction(t);i.enabled=!0,i.setLoop(n.loop===!1?Ne:Pe),n.loop===!1&&(i.clampWhenFinished=!0),this.actions.set(e,i)}return r}async loadAll(){let e=this._animationDefs.map(async e=>{try{await this.loadAnimation(e.name,e.url,{loop:e.loop!==!1})}catch(t){console.warn(`[AnimationManager] Failed to load "${e.name}" from ${e.url}:`,t)}});await Promise.all(e)}play(e){let t=this.actions.get(e);if(!t){console.warn(`[AnimationManager] Animation "${e}" not loaded`);return}this.currentAction&&this.currentAction!==t&&this.currentAction.fadeOut(.01),t.reset().fadeIn(.01).play(),this.currentAction=t,this.currentName=e,this.onChange&&this.onChange(e)}crossfadeTo(e,t=K_){if(e===this.currentName)return;let n=this.actions.get(e);if(!n){console.warn(`[AnimationManager] Animation "${e}" not loaded`);return}n.reset(),n.play(),this.currentAction?this.currentAction.crossFadeTo(n,t,!0):n.fadeIn(t),this.currentAction=n,this.currentName=e,this.onChange&&this.onChange(e)}stopAll(){this.mixer&&this.mixer.stopAllAction(),this.currentAction=null,this.currentName=null,this.onChange&&this.onChange(null)}update(e){this.mixer&&this.mixer.update(e)}_retargetClip(e,t){if(!this.model)return e;let n=new Set;if(this.model.traverse(e=>{e.isBone&&n.add(e.name)}),n.size===0)return e;let r=new Set;for(let t of e.tracks){let e=t.name.split(`.`)[0];r.add(e)}let i=0;for(let e of r)n.has(e)&&i++;if(i/r.size>.5)return e;let a=this._buildBoneNameMap(n,r);return a?(e.tracks.map(e=>{let t=e.name.split(`.`),n=t[0],r=t.slice(1).join(`.`),i=a.get(n);if(!i)return null;let o=e.clone();return o.name=`${i}.${r}`,o}).filter(Boolean),e.clone().resetDuration()):e}_buildBoneNameMap(e,t){let n=new Map,r=[...e],i=[...t],a=e=>e.replace(/^mixamorig\d*[_:]?/i,``).replace(/^Armature[_/]?/i,``),o=new Map(r.map(e=>[a(e),e])),s=0;for(let e of i){let t=a(e);o.has(t)&&(n.set(e,o.get(t)),s++)}if(s/i.length>.5)return n;let c=new Map(r.map(e=>[e.toLowerCase(),e]));n.clear(),s=0;for(let e of i)c.has(e.toLowerCase())&&(n.set(e,c.get(e.toLowerCase())),s++);return s/i.length>.5?n:null}getLoadedNames(){return[...this.clips.keys()]}isLoaded(e){return this.clips.has(e)}dispose(){this.detach(),this.clips.clear(),this._animationDefs=[]}};ao.enabled=!0;var J_=class{constructor(e,t){this.el=e,this.options=t,this.lights=[],this.content=null,this.mixer=null,this.clips=[],this.gui=null,this.animationManager=new q_,this._animPanelEl=null,this.state={environment:t.preset===e_.ASSET_GENERATOR?rp.find(e=>e.id===`footprint-court`).name:rp[1].name,background:!1,playbackSpeed:1,actionStates:{},camera:$g,wireframe:!1,skeleton:!1,grid:!1,autoRotate:!1,punctualLights:!0,exposure:0,toneMapping:1,ambientIntensity:.3,ambientColor:`#FFFFFF`,directIntensity:.8*Math.PI,directColor:`#FFFFFF`,bgColor:`#000000`,transparentBg:!1,pointSize:1,showInfo:!0,showLabels:!1},this.prevTime=0,this.stats=new du,this.stats.dom.height=`48px`,[].forEach.call(this.stats.dom.children,e=>e.style.display=``),this.backgroundColor=new B(this.state.bgColor),this.scene=new Oi,this.scene.background=this.backgroundColor,this.defaultCamera=new yi(t.preset===e_.ASSET_GENERATOR?.8*180/Math.PI:60,e.clientWidth/e.clientHeight,.01,1e3),this.activeCamera=this.defaultCamera,this.scene.add(this.defaultCamera),this.renderer=window.renderer=new uu({antialias:!0,alpha:!0}),this.renderer.setClearColor(0,1),this.renderer.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.renderer.setSize(e.clientWidth,e.clientHeight),this.pmremGenerator=new Ps(this.renderer),this.pmremGenerator.compileEquirectangularShader(),this.neutralEnvironment=this.pmremGenerator.fromScene(new Id).texture,this.controls=new Cd(this.defaultCamera,this.renderer.domElement),this.controls.screenSpacePanning=!0,this._onControlsChange=()=>this.invalidate(),this.controls.addEventListener(`change`,this._onControlsChange),this.el.appendChild(this.renderer.domElement),this.cameraCtrl=null,this.cameraFolder=null,this.animFolder=null,this.animCtrls=[],this.morphFolder=null,this.morphCtrls=[],this.skeletonHelpers=[],this.gridHelper=null,this.axesHelper=null,this.modelInfo=null,this.annotationEls=[],this._tempVec=new R,this.addAxesHelper(),this.addGUI(),t.kiosk&&this.gui.close(),this.animate=this.animate.bind(this),this._rafId=null,this._visible=!0,this._tabVisible=!document.hidden,this._disposed=!1,this._loadedEnvironment=null,this._guiWrap=null,this._needsRender=!0,this._animating=!1,this._onVisibilityChange=()=>{let e=!this._tabVisible;this._tabVisible=!document.hidden,e&&this._tabVisible&&(this._needsRender=!0),this._updateRenderLoop()},document.addEventListener(`visibilitychange`,this._onVisibilityChange),typeof IntersectionObserver<`u`&&(this._intersectionObserver=new IntersectionObserver(e=>{let t=!this._visible;this._visible=e[e.length-1].isIntersecting,t&&this._visible&&(this._needsRender=!0),this._updateRenderLoop()},{threshold:0}),this._intersectionObserver.observe(this.el)),this._onResize=this.resize.bind(this),this._onKeyDown=e=>{(e.key===`p`||e.key===`P`)&&!this.isInputFocused()&&this.takeScreenshot()},this._updateRenderLoop(),window.addEventListener(`resize`,this._onResize,!1),window.addEventListener(`keydown`,this._onKeyDown)}invalidate(){this._disposed||(this._needsRender=!0,this._updateRenderLoop())}_recomputeAnimating(){let e=!1;if(this.state&&this.state.autoRotate&&(e=!0),!e&&this.mixer&&this.state){for(let t in this.state.actionStates)if(this.state.actionStates[t]){e=!0;break}}!e&&this.animationManager.currentAction&&(e=!0),this._animating=e}_updateRenderLoop(){if(this._disposed)return;let e=this._visible&&this._tabVisible;e&&(this._needsRender||this._animating)&&this._rafId===null?(this.prevTime=performance.now(),this._rafId=requestAnimationFrame(this.animate)):!e&&this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}animate(e){let t=(e-this.prevTime)/1e3;if(this.prevTime=e,this._recomputeAnimating(),this.controls.update(),this.stats.update(),this.mixer&&this.mixer.update(t),this.animationManager.update(t),this._afterAnimateHooks)for(let e=0;e<this._afterAnimateHooks.length;e++)this._afterAnimateHooks[e](t);this.render(),this._needsRender=!1,this._animating&&this._visible&&this._tabVisible&&!this._disposed?this._rafId=requestAnimationFrame(this.animate):this._rafId=null}isInputFocused(){let e=document.activeElement;return e&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.isContentEditable)}render(){this.renderer.render(this.scene,this.activeCamera),this.state.grid&&(this.axesCamera.position.copy(this.defaultCamera.position),this.axesCamera.lookAt(this.axesScene.position),this.axesRenderer.render(this.axesScene,this.axesCamera)),this.projectAnnotations()}takeScreenshot(){H_(this)}resize(){let{clientHeight:e,clientWidth:t}=this.el;this.defaultCamera.aspect=t/e,this.defaultCamera.updateProjectionMatrix(),this.renderer.setSize(t,e),this.axesCamera.aspect=this.axesDiv.clientWidth/this.axesDiv.clientHeight,this.axesCamera.updateProjectionMatrix(),this.axesRenderer.setSize(this.axesDiv.clientWidth,this.axesDiv.clientHeight),this.invalidate()}load(e,t,n){let r=No.extractUrlBase(e);return new Promise((i,a)=>{t_.setURLModifier((e,i)=>{let a=t+decodeURI(e).replace(r,``).replace(/^(\.?\/)/,``);if(n.has(a)){let e=n.get(a),t=URL.createObjectURL(e);return s.push(t),t}return(i||``)+e});let o=new pu(t_).setCrossOrigin(`anonymous`).setDRACOLoader(r_).setKTX2Loader(i_.detectSupport(this.renderer)).setMeshoptDecoder(fd),s=[];o.load(e,e=>{window.VIEWER.json=e;let t=e.scene||e.scenes[0],n=e.animations||[];if(!t)throw Error(`This model contains no scene, and cannot be viewed here. However, it may contain individual 3D resources.`);this.setContent(t,n),s.forEach(URL.revokeObjectURL),i(e)},void 0,a)})}setContent(e,t){this.clear(),e.updateMatrixWorld();let n=new rn().setFromObject(e),r=n.getSize(new R).length(),i=n.getCenter(new R);this.controls.reset(),e.position.x-=i.x,e.position.y-=i.y,e.position.z-=i.z,this.controls.maxDistance=r*10,this.defaultCamera.near=r/100,this.defaultCamera.far=r*100,this.defaultCamera.updateProjectionMatrix(),this.options.cameraPosition?(this.defaultCamera.position.fromArray(this.options.cameraPosition),this.defaultCamera.lookAt(new R)):(this.defaultCamera.position.copy(i),this.defaultCamera.position.x+=r/2,this.defaultCamera.position.y+=r/5,this.defaultCamera.position.z+=r/2,this.defaultCamera.lookAt(i)),this.setCamera($g),this.axesCamera.position.copy(this.defaultCamera.position),this.axesCamera.lookAt(this.axesScene.position),this.axesCamera.near=r/100,this.axesCamera.far=r*100,this.axesCamera.updateProjectionMatrix(),this.axesCorner.scale.set(r,r,r),this.controls.saveState(),this.scene.add(e),this.content=e,this.state.punctualLights=!0,this.content.traverse(e=>{e.isLight&&(this.state.punctualLights=!1)}),this.setClips(t),this.animationManager.attach(this.content),this._setupAnimationPanel(),this.updateLights(),this.updateGUI(),this.updateEnvironment(),this.updateDisplay(),this.updateModelInfo(e,t),this.updateAnnotations(),window.VIEWER.scene=this.content,this.printGraph(this.content),this.invalidate()}printGraph(e){console.group(` <`+e.type+`> `+e.name),e.children.forEach(e=>this.printGraph(e)),console.groupEnd()}setClips(e){W_(this,e)}playAllClips(){G_(this)}setCamera(e){e===`[default]`?(this.controls.enabled=!0,this.activeCamera=this.defaultCamera):(this.controls.enabled=!1,this.content.traverse(t=>{t.isCamera&&t.name===e&&(this.activeCamera=t)})),this.invalidate()}updateLights(){let e=this.state,t=this.lights;e.punctualLights&&!t.length?o_(this):!e.punctualLights&&t.length&&s_(this),this.renderer.toneMapping=Number(e.toneMapping),this.renderer.toneMappingExposure=2**e.exposure,t.length===2&&(t[0].intensity=e.ambientIntensity,t[0].color.set(e.ambientColor),t[1].intensity=e.directIntensity,t[1].color.set(e.directColor)),this.invalidate()}updateEnvironment(){let e=rp.filter(e=>e.name===this.state.environment)[0];V_(this,e).then(({envMap:e})=>{this._disposed||!this.scene||(this.scene.environment=e,this.scene.background=this.state.transparentBg?null:this.state.background?e:this.backgroundColor,this.invalidate())})}updateDisplay(){this.skeletonHelpers.length&&this.skeletonHelpers.forEach(e=>this.scene.remove(e)),a_(this.content,e=>{e.wireframe=this.state.wireframe,e instanceof Ca&&(e.size=this.state.pointSize)}),this.content.traverse(e=>{if(e.geometry&&e.skeleton&&this.state.skeleton){let t=new ns(e.skeleton.bones[0].parent);t.material.linewidth=3,this.scene.add(t),this.skeletonHelpers.push(t)}}),this.state.grid!==!!this.gridHelper&&(this.state.grid?(this.gridHelper=new is,this.axesHelper=new as,this.axesHelper.renderOrder=999,this.axesHelper.onBeforeRender=e=>e.clearDepth(),this.scene.add(this.gridHelper),this.scene.add(this.axesHelper)):(this.scene.remove(this.gridHelper),this.scene.remove(this.axesHelper),this.gridHelper=null,this.axesHelper=null,this.axesRenderer.clear())),this.controls.autoRotate=this.state.autoRotate,this.invalidate()}updateBackground(){this.backgroundColor.set(this.state.bgColor),this.state.transparentBg?(this.scene.background=null,this.renderer.setClearColor(0,0)):(this.scene.background=this.backgroundColor,this.renderer.setClearColor(0,1),this.updateEnvironment()),this.invalidate()}updateModelInfo(e,t){this.modelInfo&&=(this.modelInfo.remove(),null),this.state.showInfo&&e&&(this.modelInfo=pg(this.el,e,t))}updateAnnotations(){this.annotationEls.forEach(e=>e.el.remove()),this.annotationEls=[],!(!this.state.showLabels||!this.content)&&(Sg(this.content).forEach(e=>{let t=Cg(e),n=document.createElement(`div`);n.classList.add(`annotation-label`),n.appendChild(t),this.el.appendChild(n),this.annotationEls.push({el:n,position:e.position})}),this.invalidate())}projectAnnotations(){if(this.annotationEls.length===0)return;let e=this.el.clientWidth,t=this.el.clientHeight,n=e/2,r=t/2,i=this._tempVec;this.annotationEls.forEach(({el:e,position:t})=>{if(i.copy(t),i.project(this.activeCamera),i.z>1){e.style.display=`none`;return}let a=i.x*n+n,o=-(i.y*r)+r;e.style.display=``,e.style.left=a+`px`,e.style.top=o+`px`})}addAxesHelper(){this.axesDiv=document.createElement(`div`),this.el.appendChild(this.axesDiv),this.axesDiv.classList.add(`axes`);let{clientWidth:e,clientHeight:t}=this.axesDiv;this.axesScene=new Oi,this.axesCamera=new yi(50,e/t,.1,10),this.axesScene.add(this.axesCamera),this.axesRenderer=new uu({alpha:!0}),this.axesRenderer.setPixelRatio(window.devicePixelRatio),this.axesRenderer.setSize(this.axesDiv.clientWidth,this.axesDiv.clientHeight),this.axesCamera.up=this.defaultCamera.up,this.axesCorner=new as(5),this.axesScene.add(this.axesCorner),this.axesDiv.appendChild(this.axesRenderer.domElement)}addGUI(){let e=window.innerWidth<=700,t=this.gui=new np({autoPlace:!1,width:e?220:260,hideable:!0}),n=t.addFolder(`Display`);n.add(this.state,`background`).onChange(()=>this.updateEnvironment()),n.add(this.state,`autoRotate`).onChange(()=>this.updateDisplay()),n.add(this.state,`wireframe`).onChange(()=>this.updateDisplay()),n.add(this.state,`skeleton`).onChange(()=>this.updateDisplay()),n.add(this.state,`grid`).onChange(()=>this.updateDisplay()),n.add(this.controls,`screenSpacePanning`),n.add(this.state,`pointSize`,1,16).onChange(()=>this.updateDisplay()),n.add(this.state,`transparentBg`).name(`transparent bg`).onChange(()=>this.updateBackground()),n.addColor(this.state,`bgColor`).onChange(()=>this.updateBackground()),n.add({screenshot:()=>this.takeScreenshot()},`screenshot`).name(`Screenshot [P]`),n.add(this.state,`showInfo`).name(`model info`).onChange(()=>this.updateModelInfo(this.content,this.clips)),n.add(this.state,`showLabels`).name(`mesh labels`).onChange(()=>this.updateAnnotations());let r=t.addFolder(`Lighting`);r.add(this.state,`environment`,rp.map(e=>e.name)).onChange(()=>this.updateEnvironment()),[r.add(this.state,`toneMapping`,{Linear:1,"ACES Filmic":4}),r.add(this.state,`exposure`,-10,10,.01),r.add(this.state,`punctualLights`).listen(),r.add(this.state,`ambientIntensity`,0,2),r.addColor(this.state,`ambientColor`),r.add(this.state,`directIntensity`,0,4),r.addColor(this.state,`directColor`)].forEach(e=>e.onChange(()=>this.updateLights())),this.animFolder=t.addFolder(`Animation`),this.animFolder.domElement.style.display=`none`,this.animFolder.add(this.state,`playbackSpeed`,0,1).onChange(e=>{this.mixer&&(this.mixer.timeScale=e)}),this.animFolder.add({playAll:()=>this.playAllClips()},`playAll`),this.morphFolder=t.addFolder(`Morph Targets`),this.morphFolder.domElement.style.display=`none`,this.cameraFolder=t.addFolder(`Cameras`),this.cameraFolder.domElement.style.display=`none`;let i=t.addFolder(`Performance`),a=document.createElement(`li`);this.stats.dom.style.position=`static`,a.appendChild(this.stats.dom),a.classList.add(`gui-stats`),i.__ul.appendChild(a);let o=document.createElement(`div`);this.el.appendChild(o),o.classList.add(`gui-wrap`),o.appendChild(t.domElement),this._guiWrap=o,e?t.close():t.open()}updateGUI(){this.cameraFolder.domElement.style.display=`none`,this.morphCtrls.forEach(e=>e.remove()),this.morphCtrls.length=0,this.morphFolder.domElement.style.display=`none`,this.animCtrls.forEach(e=>e.remove()),this.animCtrls.length=0,this.animFolder.domElement.style.display=`none`;let e=[],t=[];if(this.content.traverse(n=>{n.geometry&&n.morphTargetInfluences&&t.push(n),n.isCamera&&(n.name=n.name||`VIEWER__camera_${e.length+1}`,e.push(n.name))}),e.length){this.cameraFolder.domElement.style.display=``,this.cameraCtrl&&this.cameraCtrl.remove();let t=[$g].concat(e);this.cameraCtrl=this.cameraFolder.add(this.state,`camera`,t),this.cameraCtrl.onChange(e=>this.setCamera(e))}if(t.length&&(this.morphFolder.domElement.style.display=``,t.forEach(e=>{if(e.morphTargetInfluences.length){let t=this.morphFolder.add({name:e.name||`Untitled`},`name`);this.morphCtrls.push(t)}for(let t=0;t<e.morphTargetInfluences.length;t++){let n=this.morphFolder.add(e.morphTargetInfluences,t,0,1,.01).listen();Object.keys(e.morphTargetDictionary).forEach(r=>{r&&e.morphTargetDictionary[r]===t&&n.name(r)}),this.morphCtrls.push(n)}})),this.clips.length){this.animFolder.domElement.style.display=``;let e=this.state.actionStates={};this.clips.forEach((t,n)=>{t.name=`${n+1}. ${t.name}`;let r;n===0?(e[t.name]=!0,r=this.mixer.clipAction(t),r.play()):e[t.name]=!1;let i=this.animFolder.add(e,t.name).listen();i.onChange(e=>{r||=this.mixer.clipAction(t),r.setEffectiveTimeScale(1),e?r.play():r.stop(),this.invalidate()}),this.animCtrls.push(i)})}}setAnimationDefs(e){this.animationManager.setAnimationDefs(e),this.content&&this._setupAnimationPanel()}_setupAnimationPanel(){this._animPanelEl&&=(this._animPanelEl.remove(),null);let e=this.animationManager.getAnimationDefs();if(e.length===0)return;let t=!1;if(this.content.traverse(e=>{e.isSkinnedMesh&&(t=!0)}),!t)return;let n=document.createElement(`div`);n.className=`anim-panel`,n.innerHTML=`<div class="anim-panel__header"><span class="anim-panel__title">Animations</span><button class="anim-panel__stop" title="Stop all">⏹</button></div><div class="anim-panel__grid"></div>`,this.el.appendChild(n),this._animPanelEl=n,this._renderAnimButtons(),this.animationManager.loadAll().then(()=>{if(this._renderAnimButtons(),!this.animationManager.currentName&&e.length>0){let t=e[0].name;this.animationManager.isLoaded(t)&&(this.animationManager.play(t),this._renderAnimButtons(),this.invalidate(),this._recomputeAnimating(),this._updateRenderLoop())}}),n.querySelector(`.anim-panel__stop`).addEventListener(`click`,()=>{this.animationManager.stopAll(),this._renderAnimButtons(),this.invalidate()}),this.animationManager.onChange=()=>{this._renderAnimButtons()}}_renderAnimButtons(){if(!this._animPanelEl)return;let e=this._animPanelEl.querySelector(`.anim-panel__grid`),t=this.animationManager.getAnimationDefs(),n=this.animationManager.currentName,r={idle:`🧍`,breathing:`🧍`,standing:`🧍`,walking:`🚶`,walk:`🚶`,running:`🏃`,run:`🏃`,waving:`👋`,wave:`👋`,dancing:`💃`,dance:`💃`,sitting:`🪑`,sit:`🪑`,jumping:`🦘`,jump:`🦘`,talking:`🗣️`,talk:`🗣️`,clapping:`👏`,clap:`👏`,punching:`👊`,punch:`👊`,kicking:`🦵`,kick:`🦵`};e.innerHTML=t.map(e=>{let t=this.animationManager.isLoaded(e.name),i=n===e.name,a=e.icon||r[e.name.toLowerCase()]||`▶`,o=e.label||e.name.charAt(0).toUpperCase()+e.name.slice(1);return`<button class="anim-btn`+(i?` anim-btn--active`:``)+(t?``:` anim-btn--loading`)+`" data-anim="`+e.name+`" title="`+o+`"`+(t?``:` disabled`)+`><span class="anim-btn__icon">`+a+`</span><span class="anim-btn__label">`+o+`</span></button>`}).join(``),e.querySelectorAll(`.anim-btn:not([disabled])`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.anim;this.animationManager.crossfadeTo(t),this.invalidate(),this._recomputeAnimating(),this._updateRenderLoop()})})}clear(){this.content&&(this.animationManager.detach(),this._animPanelEl&&=(this._animPanelEl.remove(),null),this.modelInfo&&=(this.modelInfo.remove(),null),this.annotationEls.forEach(e=>e.el.remove()),this.annotationEls=[],this.scene.remove(this.content),this.content.traverse(e=>{e.geometry&&e.geometry.dispose()}),a_(this.content,e=>{for(let t in e)t!==`envMap`&&e[t]&&e[t].isTexture&&e[t].dispose()}),this.content=null,this._disposed||this.invalidate())}dispose(){if(!this._disposed){if(this._disposed=!0,this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null),document.removeEventListener(`visibilitychange`,this._onVisibilityChange),window.removeEventListener(`resize`,this._onResize,!1),window.removeEventListener(`keydown`,this._onKeyDown),this._intersectionObserver&&=(this._intersectionObserver.disconnect(),null),this.clear(),this.mixer){this.mixer.stopAllAction();let e=this.mixer.getRoot();e&&this.mixer.uncacheRoot(e),this.mixer=null}this.clips=[],this.animationManager.dispose(),this._animPanelEl&&=(this._animPanelEl.remove(),null),this.skeletonHelpers.length&&(this.skeletonHelpers.forEach(e=>{this.scene.remove(e),e.dispose?.()}),this.skeletonHelpers.length=0),this.gridHelper&&=(this.scene.remove(this.gridHelper),this.gridHelper.geometry?.dispose(),this.gridHelper.material?.dispose(),null),this.axesHelper&&=(this.scene.remove(this.axesHelper),this.axesHelper.geometry?.dispose(),this.axesHelper.material?.dispose(),null),this.axesCorner&&=(this.axesScene?.remove(this.axesCorner),this.axesCorner.geometry?.dispose(),this.axesCorner.material?.dispose(),null),this.lights.forEach(e=>e.parent?.remove(e)),this.lights=[],this.annotationEls.length&&(this.annotationEls.forEach(e=>e.el.remove()),this.annotationEls=[]),this.modelInfo&&=(this.modelInfo.remove(),null),this.gui&&=(this.gui.destroy(),null),this._guiWrap&&=(this._guiWrap.remove(),null),this.stats?.dom&&this.stats.dom.remove(),this.controls?.dispose(),this.controls=null,this._loadedEnvironment&&=(this._loadedEnvironment.dispose(),null),this.neutralEnvironment&&=(this.neutralEnvironment.dispose(),null),this.scene&&(this.scene.environment=null,this.scene.background=null),this.pmremGenerator&&=(this.pmremGenerator.dispose(),null),this.axesRenderer&&=(this.axesRenderer.dispose(),this.axesRenderer.forceContextLoss?.(),this.axesRenderer.domElement?.remove(),null),this.axesDiv&&=(this.axesDiv.remove(),null),this.axesScene=null,this.axesCamera=null,this.renderer&&=(this.renderer.dispose(),this.renderer.forceContextLoss?.(),this.renderer.domElement?.remove(),window.renderer===this.renderer&&(window.renderer=null),null),this.scene=null,this.content=null,this.activeCamera=null,this.defaultCamera=null,this._afterAnimateHooks=null}}},Y_=class{constructor({model:e=`claude-opus-4-6`,proxyURL:t,apiKey:n,temperature:r=.7,maxTokens:i=4096,thinking:a=`auto`}={}){this.model=e,this.proxyURL=t,this.apiKey=n,this.temperature=r,this.maxTokens=i,this.thinking=a}async complete({system:e,messages:t,tools:n}){let r={model:this.model,max_tokens:this.maxTokens,temperature:this.temperature,system:e,messages:t};n&&n.length&&(r.tools=n),this.thinking===`always`&&(r.thinking={type:`enabled`,budget_tokens:2048});let i=this.proxyURL||`https://api.anthropic.com/v1/messages`,a={"content-type":`application/json`};this.apiKey&&(a[`x-api-key`]=this.apiKey,a[`anthropic-version`]=`2023-06-01`,a[`anthropic-dangerous-direct-browser-access`]=`true`);let o=await fetch(i,{method:`POST`,headers:a,body:JSON.stringify(r)});if(!o.ok){let e=await o.text();throw Error(`Anthropic ${o.status}: ${e}`)}let s=await o.json();return this._normalize(s)}_normalize(e){let t={text:``,toolCalls:[],thinking:``,stopReason:e.stop_reason};for(let n of e.content||[])n.type===`text`?t.text+=n.text:n.type===`thinking`?t.thinking+=n.thinking||``:n.type===`tool_use`&&t.toolCalls.push({id:n.id,name:n.name,input:n.input});return t}formatToolResults(e){return{role:`user`,content:e.map(e=>({type:`tool_result`,tool_use_id:e.id,content:typeof e.output==`string`?e.output:JSON.stringify(e.output),is_error:!!e.isError}))}}formatAssistantWithToolCalls(e,t){let n=[];e&&n.push({type:`text`,text:e});for(let e of t)n.push({type:`tool_use`,id:e.id,name:e.name,input:e.input});return{role:`assistant`,content:n}}},X_=class{async complete(){return{text:``,toolCalls:[],stopReason:`end_turn`}}formatToolResults(){return{role:`user`,content:[]}}formatAssistantWithToolCalls(e){return{role:`assistant`,content:e||``}}};function Z_(e={}){let t=e.provider||`anthropic`;if(t===`anthropic`)return new Y_(e);if(t===`none`)return new X_;throw Error(`Unsupported provider: ${t}. Supported: anthropic, none`)}var Q_=class{constructor({voiceId:e=`default`,rate:t=1,pitch:n=1,lang:r=`en-US`}={}){this.voiceId=e,this.rate=t,this.pitch=n,this.lang=r,this._queue=[],this._speaking=!1}async speak(e,{onStart:t,onEnd:n}={}){if(`speechSynthesis`in window)return new Promise(r=>{let i=new SpeechSynthesisUtterance(e);i.rate=this.rate,i.pitch=this.pitch,i.lang=this.lang;let a=this._pickVoice();a&&(i.voice=a),i.onstart=()=>{this._speaking=!0,t?.()},i.onend=()=>{this._speaking=!1,n?.(),r()},i.onerror=()=>{this._speaking=!1,r()},window.speechSynthesis.speak(i)})}cancel(){`speechSynthesis`in window&&window.speechSynthesis.cancel(),this._speaking=!1}get speaking(){return this._speaking}_pickVoice(){if(!(`speechSynthesis`in window))return null;let e=window.speechSynthesis.getVoices();if(this.voiceId&&this.voiceId!==`default`){let t=e.find(e=>e.name===this.voiceId||e.voiceURI===this.voiceId);if(t)return t}return e.find(e=>e.lang?.startsWith(this.lang.slice(0,2)))||null}},$_=class{constructor({language:e=`en-US`,continuous:t=!1,interimResults:n=!0}={}){this.language=e,this.continuous=t,this.interimResults=n,this._recognition=null,this._listening=!1}_ensure(){if(this._recognition)return this._recognition;let e=window.SpeechRecognition||window.webkitSpeechRecognition;if(!e)return null;let t=new e;return t.lang=this.language,t.continuous=this.continuous,t.interimResults=this.interimResults,this._recognition=t,t}async listen({onInterim:e,onFinal:t}={}){let n=this._ensure();if(!n)throw Error(`SpeechRecognition unavailable in this browser`);return new Promise((r,i)=>{let a=``;n.onresult=n=>{for(let r=n.resultIndex;r<n.results.length;r++){let i=n.results[r],o=i[0].transcript;i.isFinal?(a+=o,t?.(o)):e?.(o)}},n.onerror=e=>{this._listening=!1,i(e.error)},n.onend=()=>{this._listening=!1,r(a.trim())},this._listening=!0;try{n.start()}catch(e){this._listening=!1,i(e)}})}stop(){this._recognition&&this._listening&&this._recognition.stop()}get listening(){return this._listening}};function ev(e={}){let t=e.provider||`browser`;if(t===`none`)return null;if(t===`browser`)return new Q_(e);throw Error(`TTS provider "${t}" not implemented yet`)}function tv(e={}){let t=e.provider||`browser`;if(t===`none`)return null;if(t===`browser`)return new $_(e);throw Error(`STT provider "${t}" not implemented yet`)}var nv=[{name:`wave`,description:`Wave at the user. Use for greetings, farewells, or acknowledgments.`,input_schema:{type:`object`,properties:{duration_ms:{type:`integer`,minimum:500,maximum:5e3,default:1500}}}},{name:`lookAt`,description:`Direct the agent's gaze toward a target.`,input_schema:{type:`object`,properties:{target:{type:`string`,enum:[`user`,`camera`,`center`],description:`Where to look`}},required:[`target`]}},{name:`play_clip`,description:`Play a named animation clip from the loaded body.`,input_schema:{type:`object`,properties:{name:{type:`string`},loop:{type:`boolean`,default:!1},fade_ms:{type:`integer`,default:200}},required:[`name`]}},{name:`setExpression`,description:`Set facial expression via morph target preset.`,input_schema:{type:`object`,properties:{preset:{type:`string`,enum:[`neutral`,`happy`,`sad`,`surprised`,`confused`,`focused`]},intensity:{type:`number`,minimum:0,maximum:1,default:1}},required:[`preset`]}},{name:`speak`,description:`Say something out loud via TTS. Use this instead of plain text when voice is on.`,input_schema:{type:`object`,properties:{text:{type:`string`}},required:[`text`]}},{name:`remember`,description:`Save a durable memory about the user, a feedback rule, a project fact, or a reference.`,input_schema:{type:`object`,properties:{key:{type:`string`,description:`short snake_case filename, e.g. "user_role"`},name:{type:`string`},description:{type:`string`},type:{type:`string`,enum:[`user`,`feedback`,`project`,`reference`]},body:{type:`string`}},required:[`key`,`name`,`description`,`type`,`body`]}}],rv={async wave(e,t){let n=e.duration_ms||1500;return await t.viewer.playAnimationByHint?.(`wave`,{duration:n}),t.memory.note(`waved`,{duration_ms:n}),{ok:!0}},async lookAt(e,t){let n=e.target||`user`;return t.viewer.lookAt?.(n),{ok:!0,target:n}},async play_clip(e,t){let{name:n,loop:r=!1,fade_ms:i=200}=e;return t.viewer.playClipByName?.(n,{loop:r,fade_ms:i})?{ok:!0,name:n}:{ok:!1,error:`No clip named "${n}"`}},async setExpression(e,t){let{preset:n,intensity:r=1}=e;return t.viewer.setExpression?.(n,r),{ok:!0,preset:n}},async speak(e,t){return await t.speak(e.text),{ok:!0}},async remember(e,t){let{key:n,name:r,description:i,type:a,body:o}=e;return t.memory.write(n,{name:r,description:i,type:a,body:o}),{ok:!0,saved:n}}},iv=8,av=class extends EventTarget{constructor({manifest:e,viewer:t,memory:n,skills:r,providerConfig:i={},voiceConfig:a={}}={}){super(),this.manifest=e||{},this.viewer=t,this.memory=n,this.skills=r,this.provider=Z_({...this.manifest.brain,...i}),this.tts=ev({...this.manifest.voice?.tts,...a.tts}),this.stt=tv({...this.manifest.voice?.stt,...a.stt}),this.messages=[],this._busy=!1}get systemPrompt(){let e=[];return this.manifest.instructions&&e.push(this.manifest.instructions),this.memory&&e.push(`
+
+<memory>
+`+this.memory.contextBlock({maxTokens:this.manifest.memory?.maxTokens||8192})+`
+</memory>`),this.skills&&e.push(this.skills.systemPrompt()),e.join(``)}get tools(){let e=new Set(this.manifest.tools||nv.map(e=>e.name)),t=nv.filter(t=>e.has(t.name)),n=this.skills?this.skills.allTools():[];return[...t,...n]}async send(e,{voice:t=!1}={}){if(this._busy)throw Error(`Runtime busy — wait for current turn to finish`);this._busy=!0;try{this.memory?.note(`user_said`,{text:e}),this.messages.push({role:`user`,content:e}),this.dispatchEvent(new CustomEvent(`brain:message`,{detail:{role:`user`,content:e}}));let n=await this._loop();return t&&n.text&&this.tts&&(this.dispatchEvent(new CustomEvent(`voice:speech-start`,{detail:{text:n.text}})),await this.tts.speak(n.text),this.dispatchEvent(new CustomEvent(`voice:speech-end`,{}))),n}finally{this._busy=!1}}async _loop(){let e=0,t=``;for(;e++<iv;){let e=await this.provider.complete({system:this.systemPrompt,messages:this.messages,tools:this.tools});if(e.thinking&&this.dispatchEvent(new CustomEvent(`brain:thinking`,{detail:{content:e.thinking}})),!e.toolCalls.length){t=e.text,this.messages.push({role:`assistant`,content:e.text}),this.dispatchEvent(new CustomEvent(`brain:message`,{detail:{role:`assistant`,content:e.text}}));break}this.messages.push(this.provider.formatAssistantWithToolCalls(e.text,e.toolCalls)),e.text&&this.dispatchEvent(new CustomEvent(`brain:message`,{detail:{role:`assistant`,content:e.text}}));let n=[];for(let t of e.toolCalls){let e,r=!1;try{e=await this._dispatchTool(t)}catch(t){e={error:t.message||String(t)},r=!0}this.dispatchEvent(new CustomEvent(`skill:tool-called`,{detail:{tool:t.name,args:t.input,result:e}})),n.push({id:t.id,output:e,isError:r})}this.messages.push(this.provider.formatToolResults(n))}return{text:t}}async _dispatchTool(e){let t=this._context(),n=this.skills?.findSkillForTool(e.name);if(n)return n.invoke(e.name,e.input,t);let r=rv[e.name];if(!r)throw Error(`Unknown tool: ${e.name}`);return r(e.input,t)}_context(){return this.skills,{viewer:this.viewer,memory:this.memory,llm:{complete:(e,t)=>this.provider.complete({system:t?.system||``,messages:[{role:`user`,content:e}],tools:t?.tools})},speak:async e=>{this.tts&&(this.dispatchEvent(new CustomEvent(`voice:speech-start`,{detail:{text:e}})),await this.tts.speak(e),this.dispatchEvent(new CustomEvent(`voice:speech-end`,{})))},listen:e=>this.stt?.listen(e),fetch:(e,t)=>fetch(e,t),loadGLB:async e=>this.viewer.loadGLB?.(e),loadClip:async e=>this.viewer.loadClip?.(e),loadJSON:async e=>(await fetch(e)).json(),call:async(e,t)=>this._dispatchTool({name:e,input:t})}}async listen({onInterim:e,onFinal:t}={}){if(!this.stt)throw Error(`STT not configured`);return this.dispatchEvent(new CustomEvent(`voice:listen-start`,{})),await this.stt.listen({onInterim:t=>{this.dispatchEvent(new CustomEvent(`voice:transcript`,{detail:{text:t,final:!1}})),e?.(t)},onFinal:e=>{this.dispatchEvent(new CustomEvent(`voice:transcript`,{detail:{text:e,final:!0}})),t?.(e)}})}clearConversation(){this.messages=[]}pause(){this.tts?.cancel(),this.stt?.stop()}destroy(){this.pause(),this.messages=[]}},ov=[`https://dweb.link/ipfs/`,`https://cloudflare-ipfs.com/ipfs/`,`https://ipfs.io/ipfs/`],sv=`https://arweave.net/`;function cv(e,t=0){if(!e)return e;let n=e.match(/^ipfs:\/\/(.+)$/i);if(n)return ov[t%ov.length]+n[1];let r=e.match(/^ar:\/\/(.+)$/i);return r?sv+r[1]:e}async function lv(e){let t;for(let n=0;n<ov.length;n++){let r=cv(e,n);try{let e=await fetch(r);if(e.ok)return e}catch(e){t=e}}throw t||Error(`All IPFS gateways failed for `+e)}var uv={neutral:{},happy:{mouthSmile:1,browInnerUp:.3,cheekSquintL:.4,cheekSquintR:.4},sad:{mouthFrownL:.8,mouthFrownR:.8,browDownL:.6,browDownR:.6},surprised:{jawOpen:.5,eyeWideL:.8,eyeWideR:.8,browInnerUp:.9},confused:{browInnerUp:.5,browOuterUpL:.4,mouthPressL:.3,mouthPressR:.3},focused:{browDownL:.4,browDownR:.4,eyeSquintL:.3,eyeSquintR:.3}},dv=class{constructor(e){this.viewer=e,this._loader=new pu,this._userTarget=new R(0,1.6,2)}get scene(){return this.viewer.scene}get mixer(){return this.viewer.mixer}get clips(){return this.viewer.clips||[]}get content(){return this.viewer.content}async load(e,t=``,n=new Map){return this.viewer.load(e,t,n)}playClipByName(e,{loop:t=!1,fade_ms:n=200}={}){let r=this._findClip(e);if(!r||!this.viewer.mixer)return!1;let i=this.viewer.mixer.clipAction(r);return i.reset(),i.setLoop(t?2201:2200),i.clampWhenFinished=!t,i.fadeIn(n/1e3),i.play(),this.viewer.state.actionStates[r.name]=!0,this.viewer.invalidate(),!0}playAnimationByHint(e,t){let n=e.toLowerCase(),r=this.clips.find(e=>e.name.toLowerCase().includes(n));return r?this.playClipByName(r.name,t):!1}stopClip(e){if(!this.viewer.mixer)return;let t=e?this._findClip(e):null;if(t){let e=this.viewer.mixer.existingAction(t);e&&e.fadeOut(.2),this.viewer.state.actionStates[t.name]=!1}else{this.viewer.mixer.stopAllAction();for(let e in this.viewer.state.actionStates)this.viewer.state.actionStates[e]=!1}this.viewer.invalidate()}async play(e,t){if(typeof e==`string`)return this.playClipByName(e,t);if(!this.viewer.mixer||!e)return!1;let n=this.viewer.mixer.clipAction(e);return n.reset(),n.fadeIn(t?.blend??.2),n.play(),this.viewer.invalidate(),!0}async loadClip(e){let t=cv(e);return new Promise((e,n)=>{this._loader.load(t,t=>e(t.animations?.[0]||null),void 0,n)})}async loadGLB(e){let t=cv(e);return new Promise((e,n)=>{this._loader.load(t,e,void 0,n)})}lookAt(e){let t=this._resolveTarget(e);if(!t||!this.viewer.content)return;let n=this._findBone([`Head`,`head`,`mixamorigHead`]);n?n.lookAt(t):this.viewer.content.lookAt(t.x,this.viewer.content.position.y,t.z),this.viewer.invalidate()}_resolveTarget(e){return e instanceof R?e:e===`camera`?this.viewer.activeCamera.position.clone():e===`center`?new R(0,1,0):e===`user`?this._userTarget.clone():null}_findBone(e){if(!this.viewer.content)return null;let t=null;return this.viewer.content.traverse(n=>{t||n.isBone&&e.includes(n.name)&&(t=n)}),t}setExpression(e,t=1){let n=uv[e]||uv.neutral;this.viewer.content&&(this.viewer.content.traverse(e=>{if(!(!e.morphTargetDictionary||!e.morphTargetInfluences)){for(let t=0;t<e.morphTargetInfluences.length;t++)e.morphTargetInfluences[t]=0;for(let[r,i]of Object.entries(n)){let n=e.morphTargetDictionary[r];n!==void 0&&(e.morphTargetInfluences[n]=i*t)}}}),this.viewer.invalidate())}moveTo(e,{duration:t=600}={}){if(!this.viewer.content)return;let n=this.viewer.content.position.clone(),r=new R(e.x||0,e.y||n.y,e.z||0),i=performance.now(),a=e=>{let o=performance.now()-i,s=Math.min(o/t,1),c=s<.5?2*s*s:1-(-2*s+2)**2/2;this.viewer.content.position.lerpVectors(n,r,c),this.viewer.invalidate(),s>=1&&this._removeHook(a)};this._addHook(a)}_addHook(e){this.viewer._afterAnimateHooks||(this.viewer._afterAnimateHooks=[]),this.viewer._afterAnimateHooks.push(e),this.viewer._animating=!0,this.viewer.invalidate()}_removeHook(e){let t=this.viewer._afterAnimateHooks;if(!t)return;let n=t.indexOf(e);n>=0&&t.splice(n,1)}_findClip(e){if(!this.clips.length)return null;let t=this.clips.find(t=>t.name===e);if(t)return t;let n=e.toLowerCase();return this.clips.find(e=>e.name.toLowerCase()===n)||this.clips.find(e=>e.name.toLowerCase().includes(n))}};function fv(e,t){return/^([a-z]+:|\/)/i.test(t)?t:(e.endsWith(`/`)||(e+=`/`),e+t)}var pv=class{constructor({uri:e,manifest:t,instructions:n,tools:r,handlers:i}){this.uri=e,this.manifest=t,this.name=t.name,this.version=t.version,this.instructions=n,this.tools=r||[],this.handlers=i||{}}async invoke(e,t,n){let r=this.handlers[e];if(!r)throw Error(`Skill "${this.name}" has no handler for tool "${e}"`);return r(t,{...n,skillBaseURI:this.uri})}systemPromptFragment(){return this.instructions?`\n\n<skill name="${this.name}" version="${this.version}">\n${this.instructions}\n</skill>`:``}},mv=class{constructor({fetchFn:e=fetch.bind(globalThis),trust:t=`owned-only`,ownerAddress:n}={}){this.fetchFn=e,this.trust=t,this.ownerAddress=n?.toLowerCase(),this.skills=new Map}async install(e,{bundleBase:t}={}){let n=this._resolveBundleURI(e.uri,t);if(this.skills.has(n))return this.skills.get(n);let r=await this._fetchJSON(`${n}manifest.json`);this._enforceTrust(r);let[i,a,o]=await Promise.all([this._fetchText(`${n}SKILL.md`).catch(()=>``),this._fetchJSON(`${n}tools.json`).catch(()=>({tools:[]})),this._fetchHandlers(`${n}handlers.js`).catch(()=>null)]),s=new pv({uri:n,manifest:r,instructions:i,tools:a.tools||[],handlers:o||{}});if(r.dependencies)for(let[e,t]of Object.entries(r.dependencies))await this.install({uri:e,version:t});return this.skills.set(n,s),s}uninstall(e){for(let[t,n]of this.skills)if(n.name===e)return this.skills.delete(t),!0;return!1}all(){return Array.from(this.skills.values())}allTools(){let e=new Map;for(let t of this.skills.values())for(let n of t.tools)e.has(n.name)&&console.warn(`[skills] tool "${n.name}" overridden by skill "${t.name}"`),e.set(n.name,{...n,_skill:t.name});return Array.from(e.values())}findSkillForTool(e){for(let t of this.skills.values())if(t.tools.some(t=>t.name===e))return t;return null}systemPrompt(){return this.all().map(e=>e.systemPromptFragment()).join(``)}_resolveBundleURI(e,t){let n=e;return!/^([a-z]+:|\/)/i.test(e)&&t&&(n=fv(t,e)),n.endsWith(`/`)||(n+=`/`),(n.startsWith(`ipfs://`)||n.startsWith(`ar://`))&&(n=cv(n)),n}async _fetchJSON(e){let t=await this.fetchFn(e);if(!t.ok)throw Error(`Fetch failed: ${e} (${t.status})`);return t.json()}async _fetchText(e){let t=await this.fetchFn(e);if(!t.ok)throw Error(`Fetch failed: ${e} (${t.status})`);return t.text()}async _fetchHandlers(e){try{return await import(e)}catch(t){return console.warn(`[skills] handlers load failed: ${e}`,t),null}}_enforceTrust(e){if(this.trust!==`any`){if(this.trust===`owned-only`){let t=(e.author||``).toLowerCase();if(t&&this.ownerAddress&&t!==this.ownerAddress)throw Error(`Skill "${e.name}" author ${t} not trusted under owned-only policy`)}this.trust}}},hv=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/;function gv(e){let t=e.match(hv);if(!t)return{meta:{},body:e};let n={};for(let e of t[1].split(`
+`)){let[t,...r]=e.split(`:`);t&&(n[t.trim()]=r.join(`:`).trim())}return{meta:n,body:t[2]}}function _v(e,t){let n=[`---`];for(let[t,r]of Object.entries(e))n.push(`${t}: ${r}`);return n.push(`---`,``,t),n.join(`
+`)}var vv=class e{constructor({mode:e=`local`,namespace:t,index:n={},files:r={},timeline:i=[]}={}){this.mode=e,this.namespace=t,this.files=new Map(Object.entries(r)),this.timeline=i,this.indexText=n.text||``,this._dirty=!1}static async load({mode:t=`local`,namespace:n,manifestURI:r,fetchFn:i}){if(t===`none`)return new e({mode:`none`,namespace:n});if(t===`local`)return e._loadLocal(n);if(t===`ipfs`||t===`encrypted-ipfs`)return e._loadIPFS({mode:t,namespace:n,manifestURI:r,fetchFn:i});throw Error(`Unknown memory mode: ${t}`)}static _loadLocal(t){let n=`agent:${t}:memory`;try{let r=localStorage.getItem(n);return r?new e({mode:`local`,namespace:t,...JSON.parse(r)}):new e({mode:`local`,namespace:t})}catch{return new e({mode:`local`,namespace:t})}}static async _loadIPFS({mode:t,namespace:n,manifestURI:r,fetchFn:i}){let a=r.replace(/manifest\.json$/,``);try{let r=await i(`${a}memory/MEMORY.md`),o=r.ok?await r.text():``,s={},c=/\[([^\]]+)\]\(([^)]+\.md)\)/g,l;for(;l=c.exec(o);){let e=l[2];try{let t=await i(`${a}memory/${e}`);t.ok&&(s[e]=await t.text())}catch{}}return new e({mode:t,namespace:n,index:{text:o},files:s})}catch{return new e({mode:t,namespace:n})}}read(e){let t=e.endsWith(`.md`)?e:`${e}.md`,n=this.files.get(t);return n?gv(n):null}write(e,{name:t,description:n,type:r,body:i,decay:a}){let o=e.endsWith(`.md`)?e:`${e}.md`,s=new Date().toISOString().slice(0,10),c=this.files.get(o),l={name:t,description:n,type:r,created:c&&gv(c).meta.created||s,updated:s};a&&(l.decay=a),this.files.set(o,_v(l,i||``)),this._rebuildIndex(),this._dirty=!0,this._persist()}note(e,t){let n={ts:new Date().toISOString(),type:e,...t};this.timeline.push(n),this.timeline.length>1e3&&(this.timeline=this.timeline.slice(-1e3)),this._dirty=!0,this._persist()}async recall(e,{limit:t=5}={}){let n=e.toLowerCase(),r=[];for(let[e,t]of this.files){let{meta:i,body:a}=gv(t),o=`${i.name||``} ${i.description||``} ${a}`.toLowerCase();o.includes(n)&&r.push({file:e,meta:i,body:a,score:o.split(n).length-1})}return r.sort((e,t)=>t.score-e.score).slice(0,t)}_rebuildIndex(){let e={user:[],feedback:[],project:[],reference:[]};for(let[t,n]of this.files){let{meta:r}=gv(n),i=r.type||`user`;e[i]||(e[i]=[]),e[i].push({file:t,name:r.name||t,description:r.description||``})}let t=[`# Memory`,``],n={user:`## User`,feedback:`## Feedback`,project:`## Project`,reference:`## Reference`};for(let[r,i]of Object.entries(e))if(i.length){t.push(n[r]||`## ${r}`);for(let e of i)t.push(`- [${e.name}](${e.file}) — ${e.description}`);t.push(``)}this.indexText=t.join(`
+`)}_persist(){if(this.mode!==`local`||!this.namespace)return;let e=`agent:${this.namespace}:memory`,t={index:{text:this.indexText},files:Object.fromEntries(this.files),timeline:this.timeline.slice(-200)};try{localStorage.setItem(e,JSON.stringify(t))}catch(e){console.warn(`[memory] persist failed`,e)}}contextBlock({maxTokens:e=8192}={}){let t=e*4,n=[`# Agent Memory`,``,this.indexText],r=n.join(`
+`).length;for(let[e,i]of this.files){if(r+i.length>t)break;n.push(``,`## ${e}`,i),r+=i.length}if(this.timeline.length){let e=this.timeline.slice(-20).map(e=>JSON.stringify(e)).join(`
+`);r+e.length<t&&n.push(``,`## Recent timeline`,"```",e,"```")}return n.join(`
+`)}async export(){return{version:`memory/0.1`,index:this.indexText,files:Object.fromEntries(this.files),timeline:this.timeline}}async import(e,{strategy:t=`merge`}={}){if(t===`replace`)this.files=new Map(Object.entries(e.files||{})),this.timeline=e.timeline||[];else{for(let[t,n]of Object.entries(e.files||{}))this.files.has(t)||this.files.set(t,n);this.timeline=[...this.timeline,...e.timeline||[]].slice(-1e3)}this._rebuildIndex(),this._persist()}},yv=`6.16.0`;function bv(e,t,n){let r=t.split(`|`).map(e=>e.trim());for(let n=0;n<r.length;n++)switch(t){case`any`:return;case`bigint`:case`boolean`:case`number`:case`string`:if(typeof e===t)return}let i=Error(`invalid value for type ${t}`);throw i.code=`INVALID_ARGUMENT`,i.argument=`value.${n}`,i.value=e,i}async function xv(e){let t=Object.keys(e);return(await Promise.all(t.map(t=>Promise.resolve(e[t])))).reduce((e,n,r)=>(e[t[r]]=n,e),{})}function G(e,t,n){for(let r in t){let i=t[r],a=n?n[r]:null;a&&bv(i,a,r),Object.defineProperty(e,r,{enumerable:!0,value:i,writable:!1})}}function Sv(e,t){if(e==null)return`null`;if(t??=new Set,typeof e==`object`){if(t.has(e))return`[Circular]`;t.add(e)}if(Array.isArray(e))return`[ `+e.map(e=>Sv(e,t)).join(`, `)+` ]`;if(e instanceof Uint8Array){let t=`0123456789abcdef`,n=`0x`;for(let r=0;r<e.length;r++)n+=t[e[r]>>4],n+=t[e[r]&15];return n}if(typeof e==`object`&&typeof e.toJSON==`function`)return Sv(e.toJSON(),t);switch(typeof e){case`boolean`:case`number`:case`symbol`:return e.toString();case`bigint`:return BigInt(e).toString();case`string`:return JSON.stringify(e);case`object`:{let n=Object.keys(e);return n.sort(),`{ `+n.map(n=>`${Sv(n,t)}: ${Sv(e[n],t)}`).join(`, `)+` }`}}return`[ COULD NOT SERIALIZE ]`}function Cv(e,t){return e&&e.code===t}function wv(e){return Cv(e,`CALL_EXCEPTION`)}function Tv(e,t,n){let r=e;{let r=[];if(n){if(`message`in n||`code`in n||`name`in n)throw Error(`value will overwrite populated values: ${Sv(n)}`);for(let e in n){if(e===`shortMessage`)continue;let t=n[e];r.push(e+`=`+Sv(t))}}r.push(`code=${t}`),r.push(`version=${yv}`),r.length&&(e+=` (`+r.join(`, `)+`)`)}let i;switch(t){case`INVALID_ARGUMENT`:i=TypeError(e);break;case`NUMERIC_FAULT`:case`BUFFER_OVERRUN`:i=RangeError(e);break;default:i=Error(e)}return G(i,{code:t}),n&&Object.assign(i,n),i.shortMessage??G(i,{shortMessage:r}),i}function K(e,t,n,r){if(!e)throw Tv(t,n,r)}function q(e,t,n,r){K(e,t,`INVALID_ARGUMENT`,{argument:n,value:r})}function Ev(e,t,n){n??=``,n&&=`: `+n,K(e>=t,`missing argument`+n,`MISSING_ARGUMENT`,{count:e,expectedCount:t}),K(e<=t,`too many arguments`+n,`UNEXPECTED_ARGUMENT`,{count:e,expectedCount:t})}var Dv=[`NFD`,`NFC`,`NFKD`,`NFKC`].reduce((e,t)=>{try{if(`test`.normalize(t)!==`test`)throw Error(`bad`);if(t===`NFD`&&`é`.normalize(`NFD`)!==`é`)throw Error(`broken`);e.push(t)}catch{}return e},[]);function Ov(e){K(Dv.indexOf(e)>=0,`platform missing String.prototype.normalize`,`UNSUPPORTED_OPERATION`,{operation:`String.prototype.normalize`,info:{form:e}})}function kv(e,t,n){if(n??=``,e!==t){let e=n,t=`new`;n&&(e+=`.`,t+=` `+n),K(!1,`private constructor; use ${e}from* methods`,`UNSUPPORTED_OPERATION`,{operation:t})}}function Av(e,t,n){if(e instanceof Uint8Array)return n?new Uint8Array(e):e;if(typeof e==`string`&&e.length%2==0&&e.match(/^0x[0-9a-f]*$/i)){let t=new Uint8Array((e.length-2)/2),n=2;for(let r=0;r<t.length;r++)t[r]=parseInt(e.substring(n,n+2),16),n+=2;return t}q(!1,`invalid BytesLike value`,t||`value`,e)}function J(e,t){return Av(e,t,!1)}function jv(e,t){return Av(e,t,!0)}function Mv(e,t){return!(typeof e!=`string`||!e.match(/^0x[0-9A-Fa-f]*$/)||typeof t==`number`&&e.length!==2+2*t||t===!0&&e.length%2!=0)}function Nv(e){return Mv(e,!0)||e instanceof Uint8Array}var Pv=`0123456789abcdef`;function Y(e){let t=J(e),n=`0x`;for(let e=0;e<t.length;e++){let r=t[e];n+=Pv[(r&240)>>4]+Pv[r&15]}return n}function Fv(e){return`0x`+e.map(e=>Y(e).substring(2)).join(``)}function Iv(e){return Mv(e,!0)?(e.length-2)/2:J(e).length}function Lv(e,t,n){let r=J(e);return n!=null&&n>r.length&&K(!1,`cannot slice beyond data bounds`,`BUFFER_OVERRUN`,{buffer:r,length:r.length,offset:n}),Y(r.slice(t??0,n??r.length))}function Rv(e,t,n){let r=J(e);K(t>=r.length,`padding exceeds data length`,`BUFFER_OVERRUN`,{buffer:new Uint8Array(r),length:t,offset:t+1});let i=new Uint8Array(t);return i.fill(0),n?i.set(r,t-r.length):i.set(r,0),Y(i)}function zv(e,t){return Rv(e,t,!0)}function Bv(e,t){return Rv(e,t,!1)}var Vv=BigInt(0),Hv=BigInt(1),Uv=9007199254740991;function Wv(e,t){let n=qv(e,`value`),r=BigInt(Z(t,`width`));if(K(n>>r===Vv,`overflow`,`NUMERIC_FAULT`,{operation:`fromTwos`,fault:`overflow`,value:e}),n>>r-Hv){let e=(Hv<<r)-Hv;return-((~n&e)+Hv)}return n}function Gv(e,t){let n=X(e,`value`),r=BigInt(Z(t,`width`)),i=Hv<<r-Hv;if(n<Vv){n=-n,K(n<=i,`too low`,`NUMERIC_FAULT`,{operation:`toTwos`,fault:`overflow`,value:e});let t=(Hv<<r)-Hv;return(~n&t)+Hv}else K(n<i,`too high`,`NUMERIC_FAULT`,{operation:`toTwos`,fault:`overflow`,value:e});return n}function Kv(e,t){return qv(e,`value`)&(Hv<<BigInt(Z(t,`bits`)))-Hv}function X(e,t){switch(typeof e){case`bigint`:return e;case`number`:return q(Number.isInteger(e),`underflow`,t||`value`,e),q(e>=-Uv&&e<=Uv,`overflow`,t||`value`,e),BigInt(e);case`string`:try{if(e===``)throw Error(`empty string`);return e[0]===`-`&&e[1]!==`-`?-BigInt(e.substring(1)):BigInt(e)}catch(n){q(!1,`invalid BigNumberish string: ${n.message}`,t||`value`,e)}}q(!1,`invalid BigNumberish value`,t||`value`,e)}function qv(e,t){let n=X(e,t);return K(n>=Vv,`unsigned value cannot be negative`,`NUMERIC_FAULT`,{fault:`overflow`,operation:`getUint`,value:e}),n}var Jv=`0123456789abcdef`;function Yv(e){if(e instanceof Uint8Array){let t=`0x0`;for(let n of e)t+=Jv[n>>4],t+=Jv[n&15];return BigInt(t)}return X(e)}function Z(e,t){switch(typeof e){case`bigint`:return q(e>=-Uv&&e<=Uv,`overflow`,t||`value`,e),Number(e);case`number`:return q(Number.isInteger(e),`underflow`,t||`value`,e),q(e>=-Uv&&e<=Uv,`overflow`,t||`value`,e),e;case`string`:try{if(e===``)throw Error(`empty string`);return Z(BigInt(e),t)}catch(n){q(!1,`invalid numeric string: ${n.message}`,t||`value`,e)}}q(!1,`invalid numeric value`,t||`value`,e)}function Xv(e){return Z(Yv(e))}function Zv(e,t){let n=qv(e,`value`),r=n.toString(16);if(t==null)r.length%2&&(r=`0`+r);else{let i=Z(t,`width`);if(i===0&&n===Vv)return`0x`;for(K(i*2>=r.length,`value exceeds width (${i} bytes)`,`NUMERIC_FAULT`,{operation:`toBeHex`,fault:`overflow`,value:e});r.length<i*2;)r=`0`+r}return`0x`+r}function Qv(e,t){let n=qv(e,`value`);if(n===Vv){let e=t==null?0:Z(t,`width`);return new Uint8Array(e)}let r=n.toString(16);if(r.length%2&&(r=`0`+r),t!=null){let n=Z(t,`width`);for(;r.length<n*2;)r=`00`+r;K(n*2===r.length,`value exceeds width (${n} bytes)`,`NUMERIC_FAULT`,{operation:`toBeArray`,fault:`overflow`,value:e})}let i=new Uint8Array(r.length/2);for(let e=0;e<i.length;e++){let t=e*2;i[e]=parseInt(r.substring(t,t+2),16)}return i}function $v(e){let t=Y(Nv(e)?e:Qv(e)).substring(2);for(;t.startsWith(`0`);)t=t.substring(1);return t===``&&(t=`0`),`0x`+t}var ey=`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`,ty=BigInt(58);function ny(e){let t=J(e),n=Yv(t),r=``;for(;n;)r=ey[Number(n%ty)]+r,n/=ty;for(let e=0;e<t.length&&!t[e];e++)r=ey[0]+r;return r}function ry(e){e=atob(e);let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return J(t)}function iy(e){let t=J(e),n=``;for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return btoa(n)}var ay=class{filter;emitter;#e;constructor(e,t,n){this.#e=t,G(this,{emitter:e,filter:n})}async removeListener(){this.#e!=null&&await this.emitter.off(this.filter,this.#e)}};function oy(e,t,n,r,i){q(!1,`invalid codepoint at offset ${t}; ${e}`,`bytes`,n)}function sy(e,t,n,r,i){if(e===`BAD_PREFIX`||e===`UNEXPECTED_CONTINUE`){let e=0;for(let r=t+1;r<n.length&&n[r]>>6==2;r++)e++;return e}return e===`OVERRUN`?n.length-t-1:0}function cy(e,t,n,r,i){return e===`OVERLONG`?(q(typeof i==`number`,`invalid bad code point for replacement`,`badCodepoint`,i),r.push(i),0):(r.push(65533),sy(e,t,n,r,i))}var ly=Object.freeze({error:oy,ignore:sy,replace:cy});function uy(e,t){t??=ly.error;let n=J(e,`bytes`),r=[],i=0;for(;i<n.length;){let e=n[i++];if(!(e>>7)){r.push(e);continue}let a=null,o=null;if((e&224)==192)a=1,o=127;else if((e&240)==224)a=2,o=2047;else if((e&248)==240)a=3,o=65535;else{(e&192)==128?i+=t(`UNEXPECTED_CONTINUE`,i-1,n,r):i+=t(`BAD_PREFIX`,i-1,n,r);continue}if(i-1+a>=n.length){i+=t(`OVERRUN`,i-1,n,r);continue}let s=e&(1<<8-a-1)-1;for(let e=0;e<a;e++){let e=n[i];if((e&192)!=128){i+=t(`MISSING_CONTINUE`,i,n,r),s=null;break}s=s<<6|e&63,i++}if(s!==null){if(s>1114111){i+=t(`OUT_OF_RANGE`,i-1-a,n,r,s);continue}if(s>=55296&&s<=57343){i+=t(`UTF16_SURROGATE`,i-1-a,n,r,s);continue}if(s<=o){i+=t(`OVERLONG`,i-1-a,n,r,s);continue}r.push(s)}}return r}function dy(e,t){q(typeof e==`string`,`invalid string value`,`str`,e),t!=null&&(Ov(t),e=e.normalize(t));let n=[];for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<128)n.push(r);else if(r<2048)n.push(r>>6|192),n.push(r&63|128);else if((r&64512)==55296){t++;let i=e.charCodeAt(t);q(t<e.length&&(i&64512)==56320,`invalid surrogate pair`,`str`,e);let a=65536+((r&1023)<<10)+(i&1023);n.push(a>>18|240),n.push(a>>12&63|128),n.push(a>>6&63|128),n.push(a&63|128)}else n.push(r>>12|224),n.push(r>>6&63|128),n.push(r&63|128)}return new Uint8Array(n)}function fy(e){return e.map(e=>e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10&1023)+55296,(e&1023)+56320))).join(``)}function py(e,t){return fy(uy(e,t))}function my(e){async function t(t,n){K(n==null||!n.cancelled,`request cancelled before sending`,`CANCELLED`);let r=t.url.split(`:`)[0].toLowerCase();K(r===`http`||r===`https`,`unsupported protocol ${r}`,`UNSUPPORTED_OPERATION`,{info:{protocol:r},operation:`request`}),K(r===`https`||!t.credentials||t.allowInsecureAuthentication,`insecure authorized connections unsupported`,`UNSUPPORTED_OPERATION`,{operation:`request`});let i=null,a=new AbortController,o=setTimeout(()=>{i=Tv(`request timeout`,`TIMEOUT`),a.abort()},t.timeout);n&&n.addListener(()=>{i=Tv(`request cancelled`,`CANCELLED`),a.abort()});let s=Object.assign({},e,{method:t.method,headers:new Headers(Array.from(t)),body:t.body||void 0,signal:a.signal}),c;try{c=await fetch(t.url,s)}catch(e){throw clearTimeout(o),i||e}clearTimeout(o);let l={};c.headers.forEach((e,t)=>{l[t.toLowerCase()]=e});let u=await c.arrayBuffer(),d=u==null?null:new Uint8Array(u);return{statusCode:c.status,statusMessage:c.statusText,headers:l,body:d}}return t}var hy=12,gy=250,_y=my(),vy=RegExp(`^data:([^;:]*)?(;base64)?,(.*)$`,`i`),yy=RegExp(`^ipfs://(ipfs/)?(.*)$`,`i`),by=!1;async function xy(e,t){try{let t=e.match(vy);if(!t)throw Error(`invalid data`);return new Oy(200,`OK`,{"content-type":t[1]||`text/plain`},t[2]?ry(t[3]):Ay(t[3]))}catch{return new Oy(599,`BAD REQUEST (invalid data: URI)`,{},null,new Dy(e))}}function Sy(e){async function t(t,n){try{let n=t.match(yy);if(!n)throw Error(`invalid link`);return new Dy(`${e}${n[2]}`)}catch{return new Oy(599,`BAD REQUEST (invalid IPFS URI)`,{},null,new Dy(t))}}return t}var Cy={data:xy,ipfs:Sy(`https://gateway.ipfs.io/ipfs/`)},wy=new WeakMap,Ty=class{#e;#t;constructor(e){this.#e=[],this.#t=!1,wy.set(e,()=>{if(!this.#t){this.#t=!0;for(let e of this.#e)setTimeout(()=>{e()},0);this.#e=[]}})}addListener(e){K(!this.#t,`singal already cancelled`,`UNSUPPORTED_OPERATION`,{operation:`fetchCancelSignal.addCancelListener`}),this.#e.push(e)}get cancelled(){return this.#t}checkSignal(){K(!this.cancelled,`cancelled`,`CANCELLED`,{})}};function Ey(e){if(e==null)throw Error(`missing signal; should not happen`);return e.checkSignal(),e}var Dy=class e{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;get url(){return this.#a}set url(e){this.#a=String(e)}get body(){return this.#o==null?null:new Uint8Array(this.#o)}set body(e){if(e==null)this.#o=void 0,this.#s=void 0;else if(typeof e==`string`)this.#o=dy(e),this.#s=`text/plain`;else if(e instanceof Uint8Array)this.#o=e,this.#s=`application/octet-stream`;else if(typeof e==`object`)this.#o=dy(JSON.stringify(e)),this.#s=`application/json`;else throw Error(`invalid body`)}hasBody(){return this.#o!=null}get method(){return this.#r?this.#r:this.hasBody()?`POST`:`GET`}set method(e){e??=``,this.#r=String(e).toUpperCase()}get headers(){let e=Object.assign({},this.#n);return this.#c&&(e.authorization=`Basic ${iy(dy(this.#c))}`),this.allowGzip&&(e[`accept-encoding`]=`gzip`),e[`content-type`]==null&&this.#s&&(e[`content-type`]=this.#s),this.body&&(e[`content-length`]=String(this.body.length)),e}getHeader(e){return this.headers[e.toLowerCase()]}setHeader(e,t){this.#n[String(e).toLowerCase()]=String(t)}clearHeaders(){this.#n={}}[Symbol.iterator](){let e=this.headers,t=Object.keys(e),n=0;return{next:()=>{if(n<t.length){let r=t[n++];return{value:[r,e[r]],done:!1}}return{value:void 0,done:!0}}}}get credentials(){return this.#c||null}setCredentials(e,t){q(!e.match(/:/),`invalid basic authentication username`,`username`,`[REDACTED]`),this.#c=`${e}:${t}`}get allowGzip(){return this.#t}set allowGzip(e){this.#t=!!e}get allowInsecureAuthentication(){return!!this.#e}set allowInsecureAuthentication(e){this.#e=!!e}get timeout(){return this.#i}set timeout(e){q(e>=0,`timeout must be non-zero`,`timeout`,e),this.#i=e}get preflightFunc(){return this.#l||null}set preflightFunc(e){this.#l=e}get processFunc(){return this.#u||null}set processFunc(e){this.#u=e}get retryFunc(){return this.#d||null}set retryFunc(e){this.#d=e}get getUrlFunc(){return this.#m||_y}set getUrlFunc(e){this.#m=e}constructor(e){this.#a=String(e),this.#e=!1,this.#t=!0,this.#n={},this.#r=``,this.#i=3e5,this.#p={slotInterval:gy,maxAttempts:hy},this.#m=null}toString(){return`<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${this.#o?Y(this.#o):`null`}>`}setThrottleParams(e){e.slotInterval!=null&&(this.#p.slotInterval=e.slotInterval),e.maxAttempts!=null&&(this.#p.maxAttempts=e.maxAttempts)}async#h(e,t,n,r,i){if(e>=this.#p.maxAttempts)return i.makeServerError(`exceeded maximum retry limit`);K(ky()<=t,`timeout`,`TIMEOUT`,{operation:`request.send`,reason:`timeout`,request:r}),n>0&&await jy(n);let a=this.clone(),o=(a.url.split(`:`)[0]||``).toLowerCase();if(o in Cy){let e=await Cy[o](a.url,Ey(r.#f));if(e instanceof Oy){let t=e;if(this.processFunc){Ey(r.#f);try{t=await this.processFunc(a,t)}catch(e){(e.throttle==null||typeof e.stall!=`number`)&&t.makeServerError(`error in post-processing function`,e).assertOk()}}return t}a=e}this.preflightFunc&&(a=await this.preflightFunc(a));let s=await this.getUrlFunc(a,Ey(r.#f)),c=new Oy(s.statusCode,s.statusMessage,s.headers,s.body,r);if(c.statusCode===301||c.statusCode===302){try{let n=c.headers.location||``;return a.redirect(n).#h(e+1,t,0,r,c)}catch{}return c}else if(c.statusCode===429&&(this.retryFunc==null||await this.retryFunc(a,c,e))){let n=c.headers[`retry-after`],i=this.#p.slotInterval*Math.trunc(Math.random()*2**e);return typeof n==`string`&&n.match(/^[1-9][0-9]*$/)&&(i=parseInt(n)),a.clone().#h(e+1,t,i,r,c)}if(this.processFunc){Ey(r.#f);try{c=await this.processFunc(a,c)}catch(n){(n.throttle==null||typeof n.stall!=`number`)&&c.makeServerError(`error in post-processing function`,n).assertOk();let i=this.#p.slotInterval*Math.trunc(Math.random()*2**e);return n.stall>=0&&(i=n.stall),a.clone().#h(e+1,t,i,r,c)}}return c}send(){return K(this.#f==null,`request already sent`,`UNSUPPORTED_OPERATION`,{operation:`fetchRequest.send`}),this.#f=new Ty(this),this.#h(0,ky()+this.timeout,0,this,new Oy(0,``,{},null,this))}cancel(){K(this.#f!=null,`request has not been sent`,`UNSUPPORTED_OPERATION`,{operation:`fetchRequest.cancel`});let e=wy.get(this);if(!e)throw Error(`missing signal; should not happen`);e()}redirect(t){let n=this.url.split(`:`)[0].toLowerCase(),r=t.split(`:`)[0].toLowerCase();K(this.method===`GET`&&(n!==`https`||r!==`http`)&&t.match(/^https?:/),`unsupported redirect`,`UNSUPPORTED_OPERATION`,{operation:`redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(t)})`});let i=new e(t);return i.method=`GET`,i.allowGzip=this.allowGzip,i.timeout=this.timeout,i.#n=Object.assign({},this.#n),this.#o&&(i.#o=new Uint8Array(this.#o)),i.#s=this.#s,i}clone(){let t=new e(this.url);return t.#r=this.#r,this.#o&&(t.#o=this.#o),t.#s=this.#s,t.#n=Object.assign({},this.#n),t.#c=this.#c,this.allowGzip&&(t.allowGzip=!0),t.timeout=this.timeout,this.allowInsecureAuthentication&&(t.allowInsecureAuthentication=!0),t.#l=this.#l,t.#u=this.#u,t.#d=this.#d,t.#p=Object.assign({},this.#p),t.#m=this.#m,t}static lockConfig(){by=!0}static getGateway(e){return Cy[e.toLowerCase()]||null}static registerGateway(e,t){if(e=e.toLowerCase(),e===`http`||e===`https`)throw Error(`cannot intercept ${e}; use registerGetUrl`);if(by)throw Error(`gateways locked`);Cy[e]=t}static registerGetUrl(e){if(by)throw Error(`gateways locked`);_y=e}static createGetUrlFunc(e){return my(e)}static createDataGateway(){return xy}static createIpfsGatewayFunc(e){return Sy(e)}},Oy=class e{#e;#t;#n;#r;#i;#a;toString(){return`<FetchResponse status=${this.statusCode} body=${this.#r?Y(this.#r):`null`}>`}get statusCode(){return this.#e}get statusMessage(){return this.#t}get headers(){return Object.assign({},this.#n)}get body(){return this.#r==null?null:new Uint8Array(this.#r)}get bodyText(){try{return this.#r==null?``:py(this.#r)}catch{K(!1,`response body is not valid UTF-8 data`,`UNSUPPORTED_OPERATION`,{operation:`bodyText`,info:{response:this}})}}get bodyJson(){try{return JSON.parse(this.bodyText)}catch{K(!1,`response body is not valid JSON`,`UNSUPPORTED_OPERATION`,{operation:`bodyJson`,info:{response:this}})}}[Symbol.iterator](){let e=this.headers,t=Object.keys(e),n=0;return{next:()=>{if(n<t.length){let r=t[n++];return{value:[r,e[r]],done:!1}}return{value:void 0,done:!0}}}}constructor(e,t,n,r,i){this.#e=e,this.#t=t,this.#n=Object.keys(n).reduce((e,t)=>(e[t.toLowerCase()]=String(n[t]),e),{}),this.#r=r==null?null:new Uint8Array(r),this.#i=i||null,this.#a={message:``}}makeServerError(t,n){let r;t?r=`CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${t})`:(t=`${this.statusCode} ${this.statusMessage}`,r=`CLIENT ESCALATED SERVER ERROR (${t})`);let i=new e(599,r,this.headers,this.body,this.#i||void 0);return i.#a={message:t,error:n},i}throwThrottleError(e,t){t==null?t=-1:q(Number.isInteger(t)&&t>=0,`invalid stall timeout`,`stall`,t);let n=Error(e||`throttling requests`);throw G(n,{stall:t,throttle:!0}),n}getHeader(e){return this.headers[e.toLowerCase()]}hasBody(){return this.#r!=null}get request(){return this.#i}ok(){return this.#a.message===``&&this.statusCode>=200&&this.statusCode<300}assertOk(){if(this.ok())return;let{message:e,error:t}=this.#a;e===``&&(e=`server response ${this.statusCode} ${this.statusMessage}`);let n=null;this.request&&(n=this.request.url);let r=null;try{this.#r&&(r=py(this.#r))}catch{}K(!1,e,`SERVER_ERROR`,{request:this.request||`unknown request`,response:this,error:t,info:{requestUrl:n,responseBody:r,responseStatus:`${this.statusCode} ${this.statusMessage}`}})}};function ky(){return new Date().getTime()}function Ay(e){return dy(e.replace(/%([0-9a-f][0-9a-f])/gi,(e,t)=>String.fromCharCode(parseInt(t,16))))}function jy(e){return new Promise(t=>setTimeout(t,e))}function My(e){let t=e.toString(16);for(;t.length<2;)t=`0`+t;return`0x`+t}function Ny(e,t,n){let r=0;for(let i=0;i<n;i++)r=r*256+e[t+i];return r}function Py(e,t,n,r){let i=[];for(;n<t+1+r;){let a=Fy(e,n);i.push(a.result),n+=a.consumed,K(n<=t+1+r,`child data too short`,`BUFFER_OVERRUN`,{buffer:e,length:r,offset:t})}return{consumed:1+r,result:i}}function Fy(e,t){K(e.length!==0,`data too short`,`BUFFER_OVERRUN`,{buffer:e,length:0,offset:1});let n=t=>{K(t<=e.length,`data short segment too short`,`BUFFER_OVERRUN`,{buffer:e,length:e.length,offset:t})};if(e[t]>=248){let r=e[t]-247;n(t+1+r);let i=Ny(e,t+1,r);return n(t+1+r+i),Py(e,t,t+1+r,r+i)}else if(e[t]>=192){let r=e[t]-192;return n(t+1+r),Py(e,t,t+1,r)}else if(e[t]>=184){let r=e[t]-183;n(t+1+r);let i=Ny(e,t+1,r);n(t+1+r+i);let a=Y(e.slice(t+1+r,t+1+r+i));return{consumed:1+r+i,result:a}}else if(e[t]>=128){let r=e[t]-128;n(t+1+r);let i=Y(e.slice(t+1,t+1+r));return{consumed:1+r,result:i}}return{consumed:1,result:My(e[t])}}function Iy(e){let t=J(e,`data`),n=Fy(t,0);return q(n.consumed===t.length,`unexpected junk after rlp payload`,`data`,e),n.result}function Ly(e){let t=[];for(;e;)t.unshift(e&255),e>>=8;return t}function Ry(e){if(Array.isArray(e)){let t=[];if(e.forEach(function(e){t=t.concat(Ry(e))}),t.length<=55)return t.unshift(192+t.length),t;let n=Ly(t.length);return n.unshift(247+n.length),n.concat(t)}let t=Array.prototype.slice.call(J(e,`object`));if(t.length===1&&t[0]<=127)return t;if(t.length<=55)return t.unshift(128+t.length),t;let n=Ly(t.length);return n.unshift(183+n.length),n.concat(t)}var zy=`0123456789abcdef`;function By(e){let t=`0x`;for(let n of Ry(e))t+=zy[n>>4],t+=zy[n&15];return t}var Vy=new Uint8Array(32),Hy=[`then`],Uy={},Wy=new WeakMap;function Gy(e){return Wy.get(e)}function Ky(e,t){Wy.set(e,t)}function qy(e,t){let n=Error(`deferred error during ABI decoding triggered accessing ${e}`);throw n.error=t,n}function Jy(e,t,n){return e.indexOf(null)>=0?t.map((e,t)=>e instanceof Yy?Jy(Gy(e),e,n):e):e.reduce((e,r,i)=>{let a=t.getValue(r);return r in e||(n&&a instanceof Yy&&(a=Jy(Gy(a),a,n)),e[r]=a),e},{})}var Yy=class e extends Array{#e;constructor(...e){let t=e[0],n=e[1],r=(e[2]||[]).slice(),i=!0;t!==Uy&&(n=e,r=[],i=!1),super(n.length),n.forEach((e,t)=>{this[t]=e});let a=r.reduce((e,t)=>(typeof t==`string`&&e.set(t,(e.get(t)||0)+1),e),new Map);if(Ky(this,Object.freeze(n.map((e,t)=>{let n=r[t];return n!=null&&a.get(n)===1?n:null}))),this.#e=[],this.#e??this.#e,!i)return;Object.freeze(this);let o=new Proxy(this,{get:(e,t,n)=>{if(typeof t==`string`){if(t.match(/^[0-9]+$/)){let n=Z(t,`%index`);if(n<0||n>=this.length)throw RangeError(`out of result range`);let r=e[n];return r instanceof Error&&qy(`index ${n}`,r),r}if(Hy.indexOf(t)>=0)return Reflect.get(e,t,n);let r=e[t];if(r instanceof Function)return function(...t){return r.apply(this===n?e:this,t)};if(!(t in e))return e.getValue.apply(this===n?e:this,[t])}return Reflect.get(e,t,n)}});return Ky(o,Gy(this)),o}toArray(t){let n=[];return this.forEach((r,i)=>{r instanceof Error&&qy(`index ${i}`,r),t&&r instanceof e&&(r=r.toArray(t)),n.push(r)}),n}toObject(e){let t=Gy(this);return t.reduce((n,r,i)=>(K(r!=null,`value at index ${i} unnamed`,`UNSUPPORTED_OPERATION`,{operation:`toObject()`}),Jy(t,this,e)),{})}slice(t,n){t??=0,t<0&&(t+=this.length,t<0&&(t=0)),n??=this.length,n<0&&(n+=this.length,n<0&&(n=0)),n>this.length&&(n=this.length);let r=Gy(this),i=[],a=[];for(let e=t;e<n;e++)i.push(this[e]),a.push(r[e]);return new e(Uy,i,a)}filter(t,n){let r=Gy(this),i=[],a=[];for(let e=0;e<this.length;e++){let o=this[e];o instanceof Error&&qy(`index ${e}`,o),t.call(n,o,e,this)&&(i.push(o),a.push(r[e]))}return new e(Uy,i,a)}map(e,t){let n=[];for(let r=0;r<this.length;r++){let i=this[r];i instanceof Error&&qy(`index ${r}`,i),n.push(e.call(t,i,r,this))}return n}getValue(e){let t=Gy(this).indexOf(e);if(t===-1)return;let n=this[t];return n instanceof Error&&qy(`property ${JSON.stringify(e)}`,n.error),n}static fromItems(t,n){return new e(Uy,t,n)}};function Xy(e){let t=Qv(e);return K(t.length<=32,`value out-of-bounds`,`BUFFER_OVERRUN`,{buffer:t,length:32,offset:t.length}),t.length!==32&&(t=jv(Fv([Vy.slice(t.length%32),t]))),t}var Zy=class{name;type;localName;dynamic;constructor(e,t,n,r){G(this,{name:e,type:t,localName:n,dynamic:r},{name:`string`,type:`string`,localName:`string`,dynamic:`boolean`})}_throwError(e,t){q(!1,e,this.localName,t)}},Qy=class{#e;#t;constructor(){this.#e=[],this.#t=0}get data(){return Fv(this.#e)}get length(){return this.#t}#n(e){return this.#e.push(e),this.#t+=e.length,e.length}appendWriter(e){return this.#n(jv(e.data))}writeBytes(e){let t=jv(e),n=t.length%32;return n&&(t=jv(Fv([t,Vy.slice(n)]))),this.#n(t)}writeValue(e){return this.#n(Xy(e))}writeUpdatableValue(){let e=this.#e.length;return this.#e.push(Vy),this.#t+=32,t=>{this.#e[e]=Xy(t)}}},$y=class e{allowLoose;#e;#t;#n;#r;#i;constructor(e,t,n){G(this,{allowLoose:!!t}),this.#e=jv(e),this.#n=0,this.#r=null,this.#i=n??1024,this.#t=0}get data(){return Y(this.#e)}get dataLength(){return this.#e.length}get consumed(){return this.#t}get bytes(){return new Uint8Array(this.#e)}#a(e){if(this.#r)return this.#r.#a(e);this.#n+=e,K(this.#i<1||this.#n<=this.#i*this.dataLength,`compressed ABI data exceeds inflation ratio of ${this.#i} ( see: https:/\/github.com/ethers-io/ethers.js/issues/4537 )`,`BUFFER_OVERRUN`,{buffer:jv(this.#e),offset:this.#t,length:e,info:{bytesRead:this.#n,dataLength:this.dataLength}})}#o(e,t,n){let r=Math.ceil(t/32)*32;return this.#t+r>this.#e.length&&(this.allowLoose&&n&&this.#t+t<=this.#e.length?r=t:K(!1,`data out-of-bounds`,`BUFFER_OVERRUN`,{buffer:jv(this.#e),length:this.#e.length,offset:this.#t+r})),this.#e.slice(this.#t,this.#t+r)}subReader(t){let n=new e(this.#e.slice(this.#t+t),this.allowLoose,this.#i);return n.#r=this,n}readBytes(e,t){let n=this.#o(0,e,!!t);return this.#a(e),this.#t+=n.length,n.slice(0,e)}readValue(){return Yv(this.readBytes(32))}readIndex(){return Xv(this.readBytes(32))}};function eb(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`Wrong positive integer: ${e}`)}function tb(e,...t){if(!(e instanceof Uint8Array))throw Error(`Expected Uint8Array`);if(t.length>0&&!t.includes(e.length))throw Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function nb(e){if(typeof e!=`function`||typeof e.create!=`function`)throw Error(`Hash should be wrapped by utils.wrapConstructor`);eb(e.outputLen),eb(e.blockLen)}function rb(e,t=!0){if(e.destroyed)throw Error(`Hash instance has been destroyed`);if(t&&e.finished)throw Error(`Hash#digest() has already been called`)}function ib(e,t){tb(e);let n=t.outputLen;if(e.length<n)throw Error(`digestInto() expects output buffer of length at least ${n}`)}var ab=typeof globalThis==`object`&&`crypto`in globalThis?globalThis.crypto:void 0,ob=e=>e instanceof Uint8Array,sb=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),cb=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),lb=(e,t)=>e<<32-t|e>>>t;if(new Uint8Array(new Uint32Array([287454020]).buffer)[0]!==68)throw Error(`Non little-endian hardware is not supported`);function ub(e){if(typeof e!=`string`)throw Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function db(e){if(typeof e==`string`&&(e=ub(e)),!ob(e))throw Error(`expected Uint8Array, got ${typeof e}`);return e}function fb(...e){let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;return e.forEach(e=>{if(!ob(e))throw Error(`Uint8Array expected`);t.set(e,n),n+=e.length}),t}var pb=class{clone(){return this._cloneInto()}};({}).toString;function mb(e){let t=t=>e().update(db(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function hb(e=32){if(ab&&typeof ab.getRandomValues==`function`)return ab.getRandomValues(new Uint8Array(e));throw Error(`crypto.getRandomValues must be defined`)}var gb=class extends pb{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,nb(e);let n=db(t);if(this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`Expected instance of class which extends utils.Hash`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i),this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i),i.fill(0)}update(e){return rb(this),this.iHash.update(e),this}digestInto(e){rb(this),tb(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},_b=(e,t,n)=>new gb(e,t).update(n).digest();_b.create=(e,t)=>new gb(e,t);function vb(e,t,n,r){if(typeof e.setBigUint64==`function`)return e.setBigUint64(t,n,r);let i=BigInt(32),a=BigInt(4294967295),o=Number(n>>i&a),s=Number(n&a),c=r?4:0,l=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+l,s,r)}var yb=class extends pb{constructor(e,t,n,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=cb(this.buffer)}update(e){rb(this);let{view:t,buffer:n,blockLen:r}=this;e=db(e);let i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let t=cb(e);for(;r<=i-a;a+=r)this.process(t,a);continue}n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){rb(this),ib(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;vb(n,r-8,BigInt(this.length*8),i),this.process(n,0);let o=cb(e),s=this.outputLen;if(s%4)throw Error(`_sha2: outputLen should be aligned to 32bit`);let c=s/4,l=this.get();if(c>l.length)throw Error(`_sha2: outputLen bigger than state`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.length=r,e.pos=o,e.finished=i,e.destroyed=a,r%t&&e.buffer.set(n),e}},bb=(e,t,n)=>e&t^~e&n,xb=(e,t,n)=>e&t^e&n^t&n,Sb=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Cb=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),wb=new Uint32Array(64),Tb=class extends yb{constructor(){super(64,32,8,!1),this.A=Cb[0]|0,this.B=Cb[1]|0,this.C=Cb[2]|0,this.D=Cb[3]|0,this.E=Cb[4]|0,this.F=Cb[5]|0,this.G=Cb[6]|0,this.H=Cb[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(e,t){for(let n=0;n<16;n++,t+=4)wb[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=wb[e-15],n=wb[e-2],r=lb(t,7)^lb(t,18)^t>>>3;wb[e]=(lb(n,17)^lb(n,19)^n>>>10)+wb[e-7]+r+wb[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=lb(o,6)^lb(o,11)^lb(o,25),u=l+t+bb(o,s,c)+Sb[e]+wb[e]|0,d=(lb(n,2)^lb(n,13)^lb(n,22))+xb(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){wb.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},Eb=mb(()=>new Tb),Db=BigInt(2**32-1),Ob=BigInt(32);function kb(e,t=!1){return t?{h:Number(e&Db),l:Number(e>>Ob&Db)}:{h:Number(e>>Ob&Db)|0,l:Number(e&Db)|0}}function Ab(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){let{h:a,l:o}=kb(e[i],t);[n[i],r[i]]=[a,o]}return[n,r]}var jb=(e,t)=>BigInt(e>>>0)<<Ob|BigInt(t>>>0),Mb=(e,t,n)=>e>>>n,Nb=(e,t,n)=>e<<32-n|t>>>n,Pb=(e,t,n)=>e>>>n|t<<32-n,Fb=(e,t,n)=>e<<32-n|t>>>n,Ib=(e,t,n)=>e<<64-n|t>>>n-32,Lb=(e,t,n)=>e>>>n-32|t<<64-n,Rb=(e,t)=>t,zb=(e,t)=>e,Bb=(e,t,n)=>e<<n|t>>>32-n,Vb=(e,t,n)=>t<<n|e>>>32-n,Hb=(e,t,n)=>t<<n-32|e>>>64-n,Ub=(e,t,n)=>e<<n-32|t>>>64-n;function Wb(e,t,n,r){let i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}var Q={fromBig:kb,split:Ab,toBig:jb,shrSH:Mb,shrSL:Nb,rotrSH:Pb,rotrSL:Fb,rotrBH:Ib,rotrBL:Lb,rotr32H:Rb,rotr32L:zb,rotlSH:Bb,rotlSL:Vb,rotlBH:Hb,rotlBL:Ub,add:Wb,add3L:(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),add3H:(e,t,n,r)=>t+n+r+(e/2**32|0)|0,add4L:(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),add4H:(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,add5H:(e,t,n,r,i,a)=>t+n+r+i+a+(e/2**32|0)|0,add5L:(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0)},[Gb,Kb]=Q.split(`0x428a2f98d728ae22.0x7137449123ef65cd.0xb5c0fbcfec4d3b2f.0xe9b5dba58189dbbc.0x3956c25bf348b538.0x59f111f1b605d019.0x923f82a4af194f9b.0xab1c5ed5da6d8118.0xd807aa98a3030242.0x12835b0145706fbe.0x243185be4ee4b28c.0x550c7dc3d5ffb4e2.0x72be5d74f27b896f.0x80deb1fe3b1696b1.0x9bdc06a725c71235.0xc19bf174cf692694.0xe49b69c19ef14ad2.0xefbe4786384f25e3.0x0fc19dc68b8cd5b5.0x240ca1cc77ac9c65.0x2de92c6f592b0275.0x4a7484aa6ea6e483.0x5cb0a9dcbd41fbd4.0x76f988da831153b5.0x983e5152ee66dfab.0xa831c66d2db43210.0xb00327c898fb213f.0xbf597fc7beef0ee4.0xc6e00bf33da88fc2.0xd5a79147930aa725.0x06ca6351e003826f.0x142929670a0e6e70.0x27b70a8546d22ffc.0x2e1b21385c26c926.0x4d2c6dfc5ac42aed.0x53380d139d95b3df.0x650a73548baf63de.0x766a0abb3c77b2a8.0x81c2c92e47edaee6.0x92722c851482353b.0xa2bfe8a14cf10364.0xa81a664bbc423001.0xc24b8b70d0f89791.0xc76c51a30654be30.0xd192e819d6ef5218.0xd69906245565a910.0xf40e35855771202a.0x106aa07032bbd1b8.0x19a4c116b8d2d0c8.0x1e376c085141ab53.0x2748774cdf8eeb99.0x34b0bcb5e19b48a8.0x391c0cb3c5c95a63.0x4ed8aa4ae3418acb.0x5b9cca4f7763e373.0x682e6ff3d6b2b8a3.0x748f82ee5defb2fc.0x78a5636f43172f60.0x84c87814a1f0ab72.0x8cc702081a6439ec.0x90befffa23631e28.0xa4506cebde82bde9.0xbef9a3f7b2c67915.0xc67178f2e372532b.0xca273eceea26619c.0xd186b8c721c0c207.0xeada7dd6cde0eb1e.0xf57d4f7fee6ed178.0x06f067aa72176fba.0x0a637dc5a2c898a6.0x113f9804bef90dae.0x1b710b35131c471b.0x28db77f523047d84.0x32caab7b40c72493.0x3c9ebe0a15c9bebc.0x431d67c49c100d4c.0x4cc5d4becb3e42b6.0x597f299cfc657e2a.0x5fcb6fab3ad6faec.0x6c44198c4a475817`.split(`.`).map(e=>BigInt(e))),qb=new Uint32Array(80),Jb=new Uint32Array(80),Yb=class extends yb{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:a,Dh:o,Dl:s,Eh:c,El:l,Fh:u,Fl:d,Gh:f,Gl:p,Hh:m,Hl:h}=this;return[e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h]}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=a|0,this.Dh=o|0,this.Dl=s|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let n=0;n<16;n++,t+=4)qb[n]=e.getUint32(t),Jb[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=qb[e-15]|0,n=Jb[e-15]|0,r=Q.rotrSH(t,n,1)^Q.rotrSH(t,n,8)^Q.shrSH(t,n,7),i=Q.rotrSL(t,n,1)^Q.rotrSL(t,n,8)^Q.shrSL(t,n,7),a=qb[e-2]|0,o=Jb[e-2]|0,s=Q.rotrSH(a,o,19)^Q.rotrBH(a,o,61)^Q.shrSH(a,o,6),c=Q.rotrSL(a,o,19)^Q.rotrBL(a,o,61)^Q.shrSL(a,o,6),l=Q.add4L(i,c,Jb[e-7],Jb[e-16]);qb[e]=Q.add4H(l,r,s,qb[e-7],qb[e-16])|0,Jb[e]=l|0}let{Ah:n,Al:r,Bh:i,Bl:a,Ch:o,Cl:s,Dh:c,Dl:l,Eh:u,El:d,Fh:f,Fl:p,Gh:m,Gl:h,Hh:g,Hl:_}=this;for(let e=0;e<80;e++){let t=Q.rotrSH(u,d,14)^Q.rotrSH(u,d,18)^Q.rotrBH(u,d,41),v=Q.rotrSL(u,d,14)^Q.rotrSL(u,d,18)^Q.rotrBL(u,d,41),y=u&f^~u&m,b=d&p^~d&h,x=Q.add5L(_,v,b,Kb[e],Jb[e]),S=Q.add5H(x,g,t,y,Gb[e],qb[e]),C=x|0,w=Q.rotrSH(n,r,28)^Q.rotrBH(n,r,34)^Q.rotrBH(n,r,39),T=Q.rotrSL(n,r,28)^Q.rotrBL(n,r,34)^Q.rotrBL(n,r,39),E=n&i^n&o^i&o,D=r&a^r&s^a&s;g=m|0,_=h|0,m=f|0,h=p|0,f=u|0,p=d|0,{h:u,l:d}=Q.add(c|0,l|0,S|0,C|0),c=o|0,l=s|0,o=i|0,s=a|0,i=n|0,a=r|0;let O=Q.add3L(C,T,D);n=Q.add3H(O,S,w,E),r=O|0}({h:n,l:r}=Q.add(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:a}=Q.add(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:s}=Q.add(this.Ch|0,this.Cl|0,o|0,s|0),{h:c,l}=Q.add(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=Q.add(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:p}=Q.add(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:h}=Q.add(this.Gh|0,this.Gl|0,m|0,h|0),{h:g,l:_}=Q.add(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_)}roundClean(){qb.fill(0),Jb.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Xb=mb(()=>new Yb);function Zb(){if(typeof self<`u`)return self;if(typeof window<`u`)return window;if(typeof global<`u`)return global;throw Error(`unable to locate global object`)}var Qb=Zb();Qb.crypto||Qb.msCrypto;function $b(e){switch(e){case`sha256`:return Eb.create();case`sha512`:return Xb.create()}q(!1,`invalid hashing algorithm name`,`algorithm`,e)}var[ex,tx,nx]=[[],[],[]],rx=BigInt(0),ix=BigInt(1),ax=BigInt(2),ox=BigInt(7),sx=BigInt(256),cx=BigInt(113);for(let e=0,t=ix,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],ex.push(2*(5*r+n)),tx.push((e+1)*(e+2)/2%64);let i=rx;for(let e=0;e<7;e++)t=(t<<ix^(t>>ox)*cx)%sx,t&ax&&(i^=ix<<(ix<<BigInt(e))-ix);nx.push(i)}var[lx,ux]=Ab(nx,!0),dx=(e,t,n)=>n>32?Hb(e,t,n):Bb(e,t,n),fx=(e,t,n)=>n>32?Ub(e,t,n):Vb(e,t,n);function px(e,t=24){let n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){let r=(t+8)%10,i=(t+2)%10,a=n[i],o=n[i+1],s=dx(a,o,1)^n[r],c=fx(a,o,1)^n[r+1];for(let n=0;n<50;n+=10)e[t+n]^=s,e[t+n+1]^=c}let t=e[2],i=e[3];for(let n=0;n<24;n++){let r=tx[n],a=dx(t,i,r),o=fx(t,i,r),s=ex[n];t=e[s],i=e[s+1],e[s]=a,e[s+1]=o}for(let t=0;t<50;t+=10){for(let r=0;r<10;r++)n[r]=e[t+r];for(let r=0;r<10;r++)e[t+r]^=~n[(r+2)%10]&n[(r+4)%10]}e[0]^=lx[r],e[1]^=ux[r]}n.fill(0)}var mx=class e extends pb{constructor(e,t,n,r=!1,i=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,eb(n),0>=this.blockLen||this.blockLen>=200)throw Error(`Sha3 supports only keccak-f1600 function`);this.state=new Uint8Array(200),this.state32=sb(this.state)}keccak(){px(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){rb(this);let{blockLen:t,state:n}=this;e=db(e);let r=e.length;for(let i=0;i<r;){let a=Math.min(t-this.pos,r-i);for(let t=0;t<a;t++)n[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,t&128&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){rb(this,!1),tb(e),this.finish();let t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();let a=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+a),r),this.posOut+=a,r+=a}return e}xofInto(e){if(!this.enableXOF)throw Error(`XOF is not possible for this instance`);return this.writeInto(e)}xof(e){return eb(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ib(e,this),this.finished)throw Error(`digest() was already called`);return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(t){let{blockLen:n,suffix:r,outputLen:i,rounds:a,enableXOF:o}=this;return t||=new e(n,r,i,o,a),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=a,t.suffix=r,t.outputLen=i,t.enableXOF=o,t.destroyed=this.destroyed,t}},hx=((e,t,n)=>mb(()=>new mx(t,e,n)))(1,136,256/8),gx=!1,_x=function(e){return hx(e)},vx=_x;function yx(e){let t=J(e,`data`);return Y(vx(t))}yx._=_x,yx.lock=function(){gx=!0},yx.register=function(e){if(gx)throw TypeError(`keccak256 is locked`);vx=e},Object.freeze(yx);var bx=function(e){return $b(`sha256`).update(e).digest()},xx=function(e){return $b(`sha512`).update(e).digest()},Sx=bx,Cx=xx,wx=!1,Tx=!1;function Ex(e){let t=J(e,`data`);return Y(Sx(t))}Ex._=bx,Ex.lock=function(){wx=!0},Ex.register=function(e){if(wx)throw Error(`sha256 is locked`);Sx=e},Object.freeze(Ex);function Dx(e){let t=J(e,`data`);return Y(Cx(t))}Dx._=xx,Dx.lock=function(){Tx=!0},Dx.register=function(e){if(Tx)throw Error(`sha512 is locked`);Cx=e},Object.freeze(Ex);var Ox=n({bitGet:()=>Jx,bitLen:()=>qx,bitMask:()=>Xx,bitSet:()=>Yx,bytesToHex:()=>Px,bytesToNumberBE:()=>Rx,bytesToNumberLE:()=>zx,concatBytes:()=>Wx,createHmacDrbg:()=>$x,ensureBytes:()=>Ux,equalBytes:()=>Gx,hexToBytes:()=>Lx,hexToNumber:()=>Ix,numberToBytesBE:()=>Bx,numberToBytesLE:()=>Vx,numberToHexUnpadded:()=>Fx,numberToVarBytesBE:()=>Hx,utf8ToBytes:()=>Kx,validateObject:()=>tS}),kx=BigInt(0),Ax=BigInt(1),jx=BigInt(2),Mx=e=>e instanceof Uint8Array,Nx=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function Px(e){if(!Mx(e))throw Error(`Uint8Array expected`);let t=``;for(let n=0;n<e.length;n++)t+=Nx[e[n]];return t}function Fx(e){let t=e.toString(16);return t.length&1?`0${t}`:t}function Ix(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);return BigInt(e===``?`0`:`0x${e}`)}function Lx(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);let t=e.length;if(t%2)throw Error(`padded hex string expected, got unpadded hex of length `+t);let n=new Uint8Array(t/2);for(let t=0;t<n.length;t++){let r=t*2,i=e.slice(r,r+2),a=Number.parseInt(i,16);if(Number.isNaN(a)||a<0)throw Error(`Invalid byte sequence`);n[t]=a}return n}function Rx(e){return Ix(Px(e))}function zx(e){if(!Mx(e))throw Error(`Uint8Array expected`);return Ix(Px(Uint8Array.from(e).reverse()))}function Bx(e,t){return Lx(e.toString(16).padStart(t*2,`0`))}function Vx(e,t){return Bx(e,t).reverse()}function Hx(e){return Lx(Fx(e))}function Ux(e,t,n){let r;if(typeof t==`string`)try{r=Lx(t)}catch(n){throw Error(`${e} must be valid hex string, got "${t}". Cause: ${n}`)}else if(Mx(t))r=Uint8Array.from(t);else throw Error(`${e} must be hex string or Uint8Array`);let i=r.length;if(typeof n==`number`&&i!==n)throw Error(`${e} expected ${n} bytes, got ${i}`);return r}function Wx(...e){let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;return e.forEach(e=>{if(!Mx(e))throw Error(`Uint8Array expected`);t.set(e,n),n+=e.length}),t}function Gx(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Kx(e){if(typeof e!=`string`)throw Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function qx(e){let t;for(t=0;e>kx;e>>=Ax,t+=1);return t}function Jx(e,t){return e>>BigInt(t)&Ax}var Yx=(e,t,n)=>e|(n?Ax:kx)<<BigInt(t),Xx=e=>(jx<<BigInt(e-1))-Ax,Zx=e=>new Uint8Array(e),Qx=e=>Uint8Array.from(e);function $x(e,t,n){if(typeof e!=`number`||e<2)throw Error(`hashLen must be a number`);if(typeof t!=`number`||t<2)throw Error(`qByteLen must be a number`);if(typeof n!=`function`)throw Error(`hmacFn must be a function`);let r=Zx(e),i=Zx(e),a=0,o=()=>{r.fill(1),i.fill(0),a=0},s=(...e)=>n(i,r,...e),c=(e=Zx())=>{i=s(Qx([0]),e),r=s(),e.length!==0&&(i=s(Qx([1]),e),r=s())},l=()=>{if(a++>=1e3)throw Error(`drbg: tried 1000 values`);let e=0,n=[];for(;e<t;){r=s();let t=r.slice();n.push(t),e+=r.length}return Wx(...n)};return(e,t)=>{o(),c(e);let n;for(;!(n=t(l()));)c();return o(),n}}var eS={bigint:e=>typeof e==`bigint`,function:e=>typeof e==`function`,boolean:e=>typeof e==`boolean`,string:e=>typeof e==`string`,stringOrUint8Array:e=>typeof e==`string`||e instanceof Uint8Array,isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>typeof e==`function`&&Number.isSafeInteger(e.outputLen)};function tS(e,t,n={}){let r=(t,n,r)=>{let i=eS[n];if(typeof i!=`function`)throw Error(`Invalid validator "${n}", expected function`);let a=e[t];if(!(r&&a===void 0)&&!i(a,e))throw Error(`Invalid param ${String(t)}=${a} (${typeof a}), expected ${n}`)};for(let[e,n]of Object.entries(t))r(e,n,!1);for(let[e,t]of Object.entries(n))r(e,t,!0);return e}var nS=BigInt(0),rS=BigInt(1),iS=BigInt(2),aS=BigInt(3),oS=BigInt(4),sS=BigInt(5),cS=BigInt(8),lS=BigInt(16);function uS(e,t){let n=e%t;return n>=nS?n:t+n}function dS(e,t,n){if(n<=nS||t<nS)throw Error(`Expected power/modulo > 0`);if(n===rS)return nS;let r=rS;for(;t>nS;)t&rS&&(r=r*e%n),e=e*e%n,t>>=rS;return r}function fS(e,t,n){let r=e;for(;t-- >nS;)r*=r,r%=n;return r}function pS(e,t){if(e===nS||t<=nS)throw Error(`invert: expected positive integers, got n=${e} mod=${t}`);let n=uS(e,t),r=t,i=nS,a=rS,o=rS,s=nS;for(;n!==nS;){let e=r/n,t=r%n,c=i-o*e,l=a-s*e;r=n,n=t,i=o,a=s,o=c,s=l}if(r!==rS)throw Error(`invert: does not exist`);return uS(i,t)}function mS(e){let t=(e-rS)/iS,n,r,i;for(n=e-rS,r=0;n%iS===nS;n/=iS,r++);for(i=iS;i<e&&dS(i,t,e)!==e-rS;i++);if(r===1){let t=(e+rS)/oS;return function(e,n){let r=e.pow(n,t);if(!e.eql(e.sqr(r),n))throw Error(`Cannot find square root`);return r}}let a=(n+rS)/iS;return function(e,o){if(e.pow(o,t)===e.neg(e.ONE))throw Error(`Cannot find square root`);let s=r,c=e.pow(e.mul(e.ONE,i),n),l=e.pow(o,a),u=e.pow(o,n);for(;!e.eql(u,e.ONE);){if(e.eql(u,e.ZERO))return e.ZERO;let t=1;for(let n=e.sqr(u);t<s&&!e.eql(n,e.ONE);t++)n=e.sqr(n);let n=e.pow(c,rS<<BigInt(s-t-1));c=e.sqr(n),l=e.mul(l,n),u=e.mul(u,c),s=t}return l}}function hS(e){if(e%oS===aS){let t=(e+rS)/oS;return function(e,n){let r=e.pow(n,t);if(!e.eql(e.sqr(r),n))throw Error(`Cannot find square root`);return r}}if(e%cS===sS){let t=(e-sS)/cS;return function(e,n){let r=e.mul(n,iS),i=e.pow(r,t),a=e.mul(n,i),o=e.mul(e.mul(a,iS),i),s=e.mul(a,e.sub(o,e.ONE));if(!e.eql(e.sqr(s),n))throw Error(`Cannot find square root`);return s}}return e%lS,mS(e)}var gS=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function _S(e){return tS(e,gS.reduce((e,t)=>(e[t]=`function`,e),{ORDER:`bigint`,MASK:`bigint`,BYTES:`isSafeInteger`,BITS:`isSafeInteger`}))}function vS(e,t,n){if(n<nS)throw Error(`Expected power > 0`);if(n===nS)return e.ONE;if(n===rS)return t;let r=e.ONE,i=t;for(;n>nS;)n&rS&&(r=e.mul(r,i)),i=e.sqr(i),n>>=rS;return r}function yS(e,t){let n=Array(t.length),r=t.reduce((t,r,i)=>e.is0(r)?t:(n[i]=t,e.mul(t,r)),e.ONE),i=e.inv(r);return t.reduceRight((t,r,i)=>e.is0(r)?t:(n[i]=e.mul(t,n[i]),e.mul(t,r)),i),n}function bS(e,t){let n=t===void 0?e.toString(2).length:t;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function xS(e,t,n=!1,r={}){if(e<=nS)throw Error(`Expected Field ORDER > 0, got ${e}`);let{nBitLength:i,nByteLength:a}=bS(e,t);if(a>2048)throw Error(`Field lengths over 2048 bytes are not supported`);let o=hS(e),s=Object.freeze({ORDER:e,BITS:i,BYTES:a,MASK:Xx(i),ZERO:nS,ONE:rS,create:t=>uS(t,e),isValid:t=>{if(typeof t!=`bigint`)throw Error(`Invalid field element: expected bigint, got ${typeof t}`);return nS<=t&&t<e},is0:e=>e===nS,isOdd:e=>(e&rS)===rS,neg:t=>uS(-t,e),eql:(e,t)=>e===t,sqr:t=>uS(t*t,e),add:(t,n)=>uS(t+n,e),sub:(t,n)=>uS(t-n,e),mul:(t,n)=>uS(t*n,e),pow:(e,t)=>vS(s,e,t),div:(t,n)=>uS(t*pS(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>pS(t,e),sqrt:r.sqrt||(e=>o(s,e)),invertBatch:e=>yS(s,e),cmov:(e,t,n)=>n?t:e,toBytes:e=>n?Vx(e,a):Bx(e,a),fromBytes:e=>{if(e.length!==a)throw Error(`Fp.fromBytes: expected ${a}, got ${e.length}`);return n?zx(e):Rx(e)}});return Object.freeze(s)}function SS(e){if(typeof e!=`bigint`)throw Error(`field order must be bigint`);let t=e.toString(2).length;return Math.ceil(t/8)}function CS(e){let t=SS(e);return t+Math.ceil(t/2)}function wS(e,t,n=!1){let r=e.length,i=SS(t),a=CS(t);if(r<16||r<a||r>1024)throw Error(`expected ${a}-1024 bytes of input, got ${r}`);let o=uS(n?Rx(e):zx(e),t-rS)+rS;return n?Vx(o,i):Bx(o,i)}var TS=BigInt(0),ES=BigInt(1);function DS(e,t){let n=(e,t)=>{let n=t.negate();return e?n:t},r=e=>({windows:Math.ceil(t/e)+1,windowSize:2**(e-1)});return{constTimeNegate:n,unsafeLadder(t,n){let r=e.ZERO,i=t;for(;n>TS;)n&ES&&(r=r.add(i)),i=i.double(),n>>=ES;return r},precomputeWindow(e,t){let{windows:n,windowSize:i}=r(t),a=[],o=e,s=o;for(let e=0;e<n;e++){s=o,a.push(s);for(let e=1;e<i;e++)s=s.add(o),a.push(s);o=s.double()}return a},wNAF(t,i,a){let{windows:o,windowSize:s}=r(t),c=e.ZERO,l=e.BASE,u=BigInt(2**t-1),d=2**t,f=BigInt(t);for(let e=0;e<o;e++){let t=e*s,r=Number(a&u);a>>=f,r>s&&(r-=d,a+=ES);let o=t,p=t+Math.abs(r)-1,m=e%2!=0,h=r<0;r===0?l=l.add(n(m,i[o])):c=c.add(n(h,i[p]))}return{p:c,f:l}},wNAFCached(e,t,n,r){let i=e._WINDOW_SIZE||1,a=t.get(e);return a||(a=this.precomputeWindow(e,i),i!==1&&t.set(e,r(a))),this.wNAF(i,a,n)}}}function OS(e){return _S(e.Fp),tS(e,{n:`bigint`,h:`bigint`,Gx:`field`,Gy:`field`},{nBitLength:`isSafeInteger`,nByteLength:`isSafeInteger`}),Object.freeze({...bS(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}function kS(e){let t=OS(e);tS(t,{a:`field`,b:`field`},{allowedPrivateKeyLengths:`array`,wrapPrivateKey:`boolean`,isTorsionFree:`function`,clearCofactor:`function`,allowInfinityPoint:`boolean`,fromBytes:`function`,toBytes:`function`});let{endo:n,Fp:r,a:i}=t;if(n){if(!r.eql(i,r.ZERO))throw Error(`Endomorphism can only be defined for Koblitz curves that have a=0`);if(typeof n!=`object`||typeof n.beta!=`bigint`||typeof n.splitScalar!=`function`)throw Error(`Expected endomorphism with beta: bigint and splitScalar: function`)}return Object.freeze({...t})}var{bytesToNumberBE:AS,hexToBytes:jS}=Ox,MS={Err:class extends Error{constructor(e=``){super(e)}},_parseInt(e){let{Err:t}=MS;if(e.length<2||e[0]!==2)throw new t(`Invalid signature integer tag`);let n=e[1],r=e.subarray(2,n+2);if(!n||r.length!==n)throw new t(`Invalid signature integer: wrong length`);if(r[0]&128)throw new t(`Invalid signature integer: negative`);if(r[0]===0&&!(r[1]&128))throw new t(`Invalid signature integer: unnecessary leading zero`);return{d:AS(r),l:e.subarray(n+2)}},toSig(e){let{Err:t}=MS,n=typeof e==`string`?jS(e):e;if(!(n instanceof Uint8Array))throw Error(`ui8a expected`);let r=n.length;if(r<2||n[0]!=48)throw new t(`Invalid signature tag`);if(n[1]!==r-2)throw new t(`Invalid signature: incorrect length`);let{d:i,l:a}=MS._parseInt(n.subarray(2)),{d:o,l:s}=MS._parseInt(a);if(s.length)throw new t(`Invalid signature: left bytes after parsing`);return{r:i,s:o}},hexFromSig(e){let t=e=>Number.parseInt(e[0],16)&8?`00`+e:e,n=e=>{let t=e.toString(16);return t.length&1?`0${t}`:t},r=t(n(e.s)),i=t(n(e.r)),a=r.length/2,o=i.length/2,s=n(a),c=n(o);return`30${n(o+a+4)}02${c}${i}02${s}${r}`}},NS=BigInt(0),PS=BigInt(1),FS=BigInt(2),IS=BigInt(3),LS=BigInt(4);function RS(e){let t=kS(e),{Fp:n}=t,r=t.toBytes||((e,t,r)=>{let i=t.toAffine();return Wx(Uint8Array.from([4]),n.toBytes(i.x),n.toBytes(i.y))}),i=t.fromBytes||(e=>{let t=e.subarray(1);return{x:n.fromBytes(t.subarray(0,n.BYTES)),y:n.fromBytes(t.subarray(n.BYTES,2*n.BYTES))}});function a(e){let{a:r,b:i}=t,a=n.sqr(e),o=n.mul(a,e);return n.add(n.add(o,n.mul(e,r)),i)}if(!n.eql(n.sqr(t.Gy),a(t.Gx)))throw Error(`bad generator point: equation left != right`);function o(e){return typeof e==`bigint`&&NS<e&&e<t.n}function s(e){if(!o(e))throw Error(`Expected valid bigint: 0 < bigint < curve.n`)}function c(e){let{allowedPrivateKeyLengths:n,nByteLength:r,wrapPrivateKey:i,n:a}=t;if(n&&typeof e!=`bigint`){if(e instanceof Uint8Array&&(e=Px(e)),typeof e!=`string`||!n.includes(e.length))throw Error(`Invalid key`);e=e.padStart(r*2,`0`)}let o;try{o=typeof e==`bigint`?e:Rx(Ux(`private key`,e,r))}catch{throw Error(`private key must be ${r} bytes, hex or bigint, not ${typeof e}`)}return i&&(o=uS(o,a)),s(o),o}let l=new Map;function u(e){if(!(e instanceof d))throw Error(`ProjectivePoint expected`)}class d{constructor(e,t,r){if(this.px=e,this.py=t,this.pz=r,e==null||!n.isValid(e))throw Error(`x required`);if(t==null||!n.isValid(t))throw Error(`y required`);if(r==null||!n.isValid(r))throw Error(`z required`)}static fromAffine(e){let{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw Error(`invalid affine point`);if(e instanceof d)throw Error(`projective point not allowed`);let i=e=>n.eql(e,n.ZERO);return i(t)&&i(r)?d.ZERO:new d(t,r,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){let t=n.invertBatch(e.map(e=>e.pz));return e.map((e,n)=>e.toAffine(t[n])).map(d.fromAffine)}static fromHex(e){let t=d.fromAffine(i(Ux(`pointHex`,e)));return t.assertValidity(),t}static fromPrivateKey(e){return d.BASE.multiply(c(e))}_setWindowSize(e){this._WINDOW_SIZE=e,l.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!n.is0(this.py))return;throw Error(`bad point: ZERO`)}let{x:e,y:r}=this.toAffine();if(!n.isValid(e)||!n.isValid(r))throw Error(`bad point: x or y not FE`);let i=n.sqr(r),o=a(e);if(!n.eql(i,o))throw Error(`bad point: equation left != right`);if(!this.isTorsionFree())throw Error(`bad point: not in prime-order subgroup`)}hasEvenY(){let{y:e}=this.toAffine();if(n.isOdd)return!n.isOdd(e);throw Error(`Field doesn't support isOdd`)}equals(e){u(e);let{px:t,py:r,pz:i}=this,{px:a,py:o,pz:s}=e,c=n.eql(n.mul(t,s),n.mul(a,i)),l=n.eql(n.mul(r,s),n.mul(o,i));return c&&l}negate(){return new d(this.px,n.neg(this.py),this.pz)}double(){let{a:e,b:r}=t,i=n.mul(r,IS),{px:a,py:o,pz:s}=this,c=n.ZERO,l=n.ZERO,u=n.ZERO,f=n.mul(a,a),p=n.mul(o,o),m=n.mul(s,s),h=n.mul(a,o);return h=n.add(h,h),u=n.mul(a,s),u=n.add(u,u),c=n.mul(e,u),l=n.mul(i,m),l=n.add(c,l),c=n.sub(p,l),l=n.add(p,l),l=n.mul(c,l),c=n.mul(h,c),u=n.mul(i,u),m=n.mul(e,m),h=n.sub(f,m),h=n.mul(e,h),h=n.add(h,u),u=n.add(f,f),f=n.add(u,f),f=n.add(f,m),f=n.mul(f,h),l=n.add(l,f),m=n.mul(o,s),m=n.add(m,m),f=n.mul(m,h),c=n.sub(c,f),u=n.mul(m,p),u=n.add(u,u),u=n.add(u,u),new d(c,l,u)}add(e){u(e);let{px:r,py:i,pz:a}=this,{px:o,py:s,pz:c}=e,l=n.ZERO,f=n.ZERO,p=n.ZERO,m=t.a,h=n.mul(t.b,IS),g=n.mul(r,o),_=n.mul(i,s),v=n.mul(a,c),y=n.add(r,i),b=n.add(o,s);y=n.mul(y,b),b=n.add(g,_),y=n.sub(y,b),b=n.add(r,a);let x=n.add(o,c);return b=n.mul(b,x),x=n.add(g,v),b=n.sub(b,x),x=n.add(i,a),l=n.add(s,c),x=n.mul(x,l),l=n.add(_,v),x=n.sub(x,l),p=n.mul(m,b),l=n.mul(h,v),p=n.add(l,p),l=n.sub(_,p),p=n.add(_,p),f=n.mul(l,p),_=n.add(g,g),_=n.add(_,g),v=n.mul(m,v),b=n.mul(h,b),_=n.add(_,v),v=n.sub(g,v),v=n.mul(m,v),b=n.add(b,v),g=n.mul(_,b),f=n.add(f,g),g=n.mul(x,b),l=n.mul(y,l),l=n.sub(l,g),g=n.mul(y,_),p=n.mul(x,p),p=n.add(p,g),new d(l,f,p)}subtract(e){return this.add(e.negate())}is0(){return this.equals(d.ZERO)}wNAF(e){return p.wNAFCached(this,l,e,e=>{let t=n.invertBatch(e.map(e=>e.pz));return e.map((e,n)=>e.toAffine(t[n])).map(d.fromAffine)})}multiplyUnsafe(e){let r=d.ZERO;if(e===NS)return r;if(s(e),e===PS)return this;let{endo:i}=t;if(!i)return p.unsafeLadder(this,e);let{k1neg:a,k1:o,k2neg:c,k2:l}=i.splitScalar(e),u=r,f=r,m=this;for(;o>NS||l>NS;)o&PS&&(u=u.add(m)),l&PS&&(f=f.add(m)),m=m.double(),o>>=PS,l>>=PS;return a&&(u=u.negate()),c&&(f=f.negate()),f=new d(n.mul(f.px,i.beta),f.py,f.pz),u.add(f)}multiply(e){s(e);let r=e,i,a,{endo:o}=t;if(o){let{k1neg:e,k1:t,k2neg:s,k2:c}=o.splitScalar(r),{p:l,f:u}=this.wNAF(t),{p:f,f:m}=this.wNAF(c);l=p.constTimeNegate(e,l),f=p.constTimeNegate(s,f),f=new d(n.mul(f.px,o.beta),f.py,f.pz),i=l.add(f),a=u.add(m)}else{let{p:e,f:t}=this.wNAF(r);i=e,a=t}return d.normalizeZ([i,a])[0]}multiplyAndAddUnsafe(e,t,n){let r=d.BASE,i=(e,t)=>t===NS||t===PS||!e.equals(r)?e.multiplyUnsafe(t):e.multiply(t),a=i(this,t).add(i(e,n));return a.is0()?void 0:a}toAffine(e){let{px:t,py:r,pz:i}=this,a=this.is0();e??=a?n.ONE:n.inv(i);let o=n.mul(t,e),s=n.mul(r,e),c=n.mul(i,e);if(a)return{x:n.ZERO,y:n.ZERO};if(!n.eql(c,n.ONE))throw Error(`invZ was invalid`);return{x:o,y:s}}isTorsionFree(){let{h:e,isTorsionFree:n}=t;if(e===PS)return!0;if(n)return n(d,this);throw Error(`isTorsionFree() has not been declared for the elliptic curve`)}clearCofactor(){let{h:e,clearCofactor:n}=t;return e===PS?this:n?n(d,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return this.assertValidity(),r(d,this,e)}toHex(e=!0){return Px(this.toRawBytes(e))}}d.BASE=new d(t.Gx,t.Gy,n.ONE),d.ZERO=new d(n.ZERO,n.ONE,n.ZERO);let f=t.nBitLength,p=DS(d,t.endo?Math.ceil(f/2):f);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:a,isWithinCurveOrder:o}}function zS(e){let t=OS(e);return tS(t,{hash:`hash`,hmac:`function`,randomBytes:`function`},{bits2int:`function`,bits2int_modN:`function`,lowS:`boolean`}),Object.freeze({lowS:!0,...t})}function BS(e){let t=zS(e),{Fp:n,n:r}=t,i=n.BYTES+1,a=2*n.BYTES+1;function o(e){return NS<e&&e<n.ORDER}function s(e){return uS(e,r)}function c(e){return pS(e,r)}let{ProjectivePoint:l,normPrivateKeyToScalar:u,weierstrassEquation:d,isWithinCurveOrder:f}=RS({...t,toBytes(e,t,r){let i=t.toAffine(),a=n.toBytes(i.x),o=Wx;return r?o(Uint8Array.from([t.hasEvenY()?2:3]),a):o(Uint8Array.from([4]),a,n.toBytes(i.y))},fromBytes(e){let t=e.length,r=e[0],s=e.subarray(1);if(t===i&&(r===2||r===3)){let e=Rx(s);if(!o(e))throw Error(`Point is not on curve`);let t=d(e),i=n.sqrt(t),a=(i&PS)===PS;return(r&1)==1!==a&&(i=n.neg(i)),{x:e,y:i}}else if(t===a&&r===4)return{x:n.fromBytes(s.subarray(0,n.BYTES)),y:n.fromBytes(s.subarray(n.BYTES,2*n.BYTES))};else throw Error(`Point of length ${t} was invalid. Expected ${i} compressed bytes or ${a} uncompressed bytes`)}}),p=e=>Px(Bx(e,t.nByteLength));function m(e){return e>r>>PS}function h(e){return m(e)?s(-e):e}let g=(e,t,n)=>Rx(e.slice(t,n));class _{constructor(e,t,n){this.r=e,this.s=t,this.recovery=n,this.assertValidity()}static fromCompact(e){let n=t.nByteLength;return e=Ux(`compactSignature`,e,n*2),new _(g(e,0,n),g(e,n,2*n))}static fromDER(e){let{r:t,s:n}=MS.toSig(Ux(`DER`,e));return new _(t,n)}assertValidity(){if(!f(this.r))throw Error(`r must be 0 < r < CURVE.n`);if(!f(this.s))throw Error(`s must be 0 < s < CURVE.n`)}addRecoveryBit(e){return new _(this.r,this.s,e)}recoverPublicKey(e){let{r,s:i,recovery:a}=this,o=C(Ux(`msgHash`,e));if(a==null||![0,1,2,3].includes(a))throw Error(`recovery id invalid`);let u=a===2||a===3?r+t.n:r;if(u>=n.ORDER)throw Error(`recovery id 2 or 3 invalid`);let d=a&1?`03`:`02`,f=l.fromHex(d+p(u)),m=c(u),h=s(-o*m),g=s(i*m),_=l.BASE.multiplyAndAddUnsafe(f,h,g);if(!_)throw Error(`point at infinify`);return _.assertValidity(),_}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new _(this.r,s(-this.s),this.recovery):this}toDERRawBytes(){return Lx(this.toDERHex())}toDERHex(){return MS.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Lx(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let v={isValidPrivateKey(e){try{return u(e),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{let e=CS(t.n);return wS(t.randomBytes(e),t.n)},precompute(e=8,t=l.BASE){return t._setWindowSize(e),t.multiply(BigInt(3)),t}};function y(e,t=!0){return l.fromPrivateKey(e).toRawBytes(t)}function b(e){let t=e instanceof Uint8Array,n=typeof e==`string`,r=(t||n)&&e.length;return t?r===i||r===a:n?r===2*i||r===2*a:e instanceof l}function x(e,t,n=!0){if(b(e))throw Error(`first arg must be private key`);if(!b(t))throw Error(`second arg must be public key`);return l.fromHex(t).multiply(u(e)).toRawBytes(n)}let S=t.bits2int||function(e){let n=Rx(e),r=e.length*8-t.nBitLength;return r>0?n>>BigInt(r):n},C=t.bits2int_modN||function(e){return s(S(e))},w=Xx(t.nBitLength);function T(e){if(typeof e!=`bigint`)throw Error(`bigint expected`);if(!(NS<=e&&e<w))throw Error(`bigint expected < 2^${t.nBitLength}`);return Bx(e,t.nByteLength)}function E(e,r,i=D){if([`recovered`,`canonical`].some(e=>e in i))throw Error(`sign() legacy options not supported`);let{hash:a,randomBytes:o}=t,{lowS:d,prehash:p,extraEntropy:g}=i;d??=!0,e=Ux(`msgHash`,e),p&&(e=Ux(`prehashed msgHash`,a(e)));let v=C(e),y=u(r),b=[T(y),T(v)];if(g!=null){let e=g===!0?o(n.BYTES):g;b.push(Ux(`extraEntropy`,e))}let x=Wx(...b),w=v;function E(e){let t=S(e);if(!f(t))return;let n=c(t),r=l.BASE.multiply(t).toAffine(),i=s(r.x);if(i===NS)return;let a=s(n*s(w+i*y));if(a===NS)return;let o=(r.x===i?0:2)|Number(r.y&PS),u=a;return d&&m(a)&&(u=h(a),o^=1),new _(i,u,o)}return{seed:x,k2sig:E}}let D={lowS:t.lowS,prehash:!1},O={lowS:t.lowS,prehash:!1};function k(e,n,r=D){let{seed:i,k2sig:a}=E(e,n,r),o=t;return $x(o.hash.outputLen,o.nByteLength,o.hmac)(i,a)}l.BASE._setWindowSize(8);function ee(e,n,r,i=O){let a=e;if(n=Ux(`msgHash`,n),r=Ux(`publicKey`,r),`strict`in i)throw Error(`options.strict was renamed to lowS`);let{lowS:o,prehash:u}=i,d,f;try{if(typeof a==`string`||a instanceof Uint8Array)try{d=_.fromDER(a)}catch(e){if(!(e instanceof MS.Err))throw e;d=_.fromCompact(a)}else if(typeof a==`object`&&typeof a.r==`bigint`&&typeof a.s==`bigint`){let{r:e,s:t}=a;d=new _(e,t)}else throw Error(`PARSE`);f=l.fromHex(r)}catch(e){if(e.message===`PARSE`)throw Error(`signature must be Signature instance, Uint8Array or hex string`);return!1}if(o&&d.hasHighS())return!1;u&&(n=t.hash(n));let{r:p,s:m}=d,h=C(n),g=c(m),v=s(h*g),y=s(p*g),b=l.BASE.multiplyAndAddUnsafe(f,v,y)?.toAffine();return b?s(b.x)===p:!1}return{CURVE:t,getPublicKey:y,getSharedSecret:x,sign:k,verify:ee,ProjectivePoint:l,Signature:_,utils:v}}function VS(e,t){let n=e.ORDER,r=NS;for(let e=n-PS;e%FS===NS;e/=FS)r+=PS;let i=r,a=FS<<i-PS-PS,o=a*FS,s=(n-PS)/o,c=(s-PS)/FS,l=o-PS,u=a,d=e.pow(t,s),f=e.pow(t,(s+PS)/FS),p=(t,n)=>{let r=d,a=e.pow(n,l),o=e.sqr(a);o=e.mul(o,n);let s=e.mul(t,o);s=e.pow(s,c),s=e.mul(s,a),a=e.mul(s,n),o=e.mul(s,t);let p=e.mul(o,a);s=e.pow(p,u);let m=e.eql(s,e.ONE);a=e.mul(o,f),s=e.mul(p,r),o=e.cmov(a,o,m),p=e.cmov(s,p,m);for(let t=i;t>PS;t--){let n=t-FS;n=FS<<n-PS;let i=e.pow(p,n),s=e.eql(i,e.ONE);a=e.mul(o,r),r=e.mul(r,r),i=e.mul(p,r),o=e.cmov(a,o,s),p=e.cmov(i,p,s)}return{isValid:m,value:o}};if(e.ORDER%LS===IS){let n=(e.ORDER-IS)/LS,r=e.sqrt(e.neg(t));p=(t,i)=>{let a=e.sqr(i),o=e.mul(t,i);a=e.mul(a,o);let s=e.pow(a,n);s=e.mul(s,o);let c=e.mul(s,r),l=e.mul(e.sqr(s),i),u=e.eql(l,t);return{isValid:u,value:e.cmov(c,s,u)}}}return p}function HS(e,t){if(_S(e),!e.isValid(t.A)||!e.isValid(t.B)||!e.isValid(t.Z))throw Error(`mapToCurveSimpleSWU: invalid opts`);let n=VS(e,t.Z);if(!e.isOdd)throw Error(`Fp.isOdd is not implemented!`);return r=>{let i,a,o,s,c,l,u,d;i=e.sqr(r),i=e.mul(i,t.Z),a=e.sqr(i),a=e.add(a,i),o=e.add(a,e.ONE),o=e.mul(o,t.B),s=e.cmov(t.Z,e.neg(a),!e.eql(a,e.ZERO)),s=e.mul(s,t.A),a=e.sqr(o),l=e.sqr(s),c=e.mul(l,t.A),a=e.add(a,c),a=e.mul(a,o),l=e.mul(l,s),c=e.mul(l,t.B),a=e.add(a,c),u=e.mul(i,o);let{isValid:f,value:p}=n(a,l);d=e.mul(i,r),d=e.mul(d,p),u=e.cmov(u,o,f),d=e.cmov(d,p,f);let m=e.isOdd(r)===e.isOdd(d);return d=e.cmov(e.neg(d),d,m),u=e.div(u,s),{x:u,y:d}}}function US(e){if(e instanceof Uint8Array)return e;if(typeof e==`string`)return Kx(e);throw Error(`DST must be Uint8Array or string`)}var WS=Rx;function GS(e,t){if(e<0||e>=1<<8*t)throw Error(`bad I2OSP call: value=${e} length=${t}`);let n=Array.from({length:t}).fill(0);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return new Uint8Array(n)}function KS(e,t){let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r];return n}function qS(e){if(!(e instanceof Uint8Array))throw Error(`Uint8Array expected`)}function JS(e){if(!Number.isSafeInteger(e))throw Error(`number expected`)}function YS(e,t,n,r){qS(e),qS(t),JS(n),t.length>255&&(t=r(Wx(Kx(`H2C-OVERSIZE-DST-`),t)));let{outputLen:i,blockLen:a}=r,o=Math.ceil(n/i);if(o>255)throw Error(`Invalid xmd length`);let s=Wx(t,GS(t.length,1)),c=GS(0,a),l=GS(n,2),u=Array(o),d=r(Wx(c,e,l,GS(0,1),s));u[0]=r(Wx(d,GS(1,1),s));for(let e=1;e<=o;e++)u[e]=r(Wx(KS(d,u[e-1]),GS(e+1,1),s));return Wx(...u).slice(0,n)}function XS(e,t,n,r,i){if(qS(e),qS(t),JS(n),t.length>255){let e=Math.ceil(2*r/8);t=i.create({dkLen:e}).update(Kx(`H2C-OVERSIZE-DST-`)).update(t).digest()}if(n>65535||t.length>255)throw Error(`expand_message_xof: invalid lenInBytes`);return i.create({dkLen:n}).update(e).update(GS(n,2)).update(t).update(GS(t.length,1)).digest()}function ZS(e,t,n){tS(n,{DST:`stringOrUint8Array`,p:`bigint`,m:`isSafeInteger`,k:`isSafeInteger`,hash:`hash`});let{p:r,k:i,m:a,hash:o,expand:s,DST:c}=n;qS(e),JS(t);let l=US(c),u=r.toString(2).length,d=Math.ceil((u+i)/8),f=t*a*d,p;if(s===`xmd`)p=YS(e,l,f,o);else if(s===`xof`)p=XS(e,l,f,i,o);else if(s===`_internal_pass`)p=e;else throw Error(`expand must be "xmd" or "xof"`);let m=Array(t);for(let e=0;e<t;e++){let t=Array(a);for(let n=0;n<a;n++){let i=d*(n+e*a);t[n]=uS(WS(p.subarray(i,i+d)),r)}m[e]=t}return m}function QS(e,t){let n=t.map(e=>Array.from(e).reverse());return(t,r)=>{let[i,a,o,s]=n.map(n=>n.reduce((n,r)=>e.add(e.mul(n,t),r)));return t=e.div(i,a),r=e.mul(r,e.div(o,s)),{x:t,y:r}}}function $S(e,t,n){if(typeof t!=`function`)throw Error(`mapToCurve() must be defined`);return{hashToCurve(r,i){let a=ZS(r,2,{...n,DST:n.DST,...i}),o=e.fromAffine(t(a[0])),s=e.fromAffine(t(a[1])),c=o.add(s).clearCofactor();return c.assertValidity(),c},encodeToCurve(r,i){let a=ZS(r,1,{...n,DST:n.encodeDST,...i}),o=e.fromAffine(t(a[0])).clearCofactor();return o.assertValidity(),o}}}function eC(e){return{hash:e,hmac:(t,...n)=>_b(e,t,fb(...n)),randomBytes:hb}}function tC(e,t){let n=t=>BS({...e,...eC(t)});return Object.freeze({...n(t),create:n})}var nC=BigInt(`0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f`),rC=BigInt(`0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141`),iC=BigInt(1),aC=BigInt(2),oC=(e,t)=>(e+t/aC)/t;function sC(e){let t=nC,n=BigInt(3),r=BigInt(6),i=BigInt(11),a=BigInt(22),o=BigInt(23),s=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=fS(fS(fS(u,n,t)*u%t,n,t)*u%t,aC,t)*l%t,f=fS(d,i,t)*d%t,p=fS(f,a,t)*f%t,m=fS(p,s,t)*p%t,h=fS(fS(fS(fS(fS(fS(m,c,t)*m%t,s,t)*p%t,n,t)*u%t,o,t)*f%t,r,t)*l%t,aC,t);if(!cC.eql(cC.sqr(h),e))throw Error(`Cannot find square root`);return h}var cC=xS(nC,void 0,void 0,{sqrt:sC}),lC=tC({a:BigInt(0),b:BigInt(7),Fp:cC,n:rC,Gx:BigInt(`55066263022277343669578718895168534326250603453777594175500187360389116729240`),Gy:BigInt(`32670510020758816978083085130507043184471273380659243275938904335757337482424`),h:BigInt(1),lowS:!0,endo:{beta:BigInt(`0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee`),splitScalar:e=>{let t=rC,n=BigInt(`0x3086d221a7d46bcde86c90e49284eb15`),r=-iC*BigInt(`0xe4437ed6010e88286f547fa90abfe4c3`),i=BigInt(`0x114ca50f7a8e2f3f657c1108d9d44cfd8`),a=n,o=BigInt(`0x100000000000000000000000000000000`),s=oC(a*e,t),c=oC(-r*e,t),l=uS(e-s*n-c*i,t),u=uS(-s*r-c*a,t),d=l>o,f=u>o;if(d&&(l=t-l),f&&(u=t-u),l>o||u>o)throw Error(`splitScalar: Endomorphism failed, k=`+e);return{k1neg:d,k1:l,k2neg:f,k2:u}}}},Eb);lC.ProjectivePoint,lC.utils.randomPrivateKey;var uC=QS(cC,[[`0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7`,`0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581`,`0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262`,`0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c`],[`0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b`,`0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14`,`0x0000000000000000000000000000000000000000000000000000000000000001`],[`0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c`,`0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3`,`0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931`,`0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84`],[`0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b`,`0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573`,`0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f`,`0x0000000000000000000000000000000000000000000000000000000000000001`]].map(e=>e.map(e=>BigInt(e)))),dC=HS(cC,{A:BigInt(`0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533`),B:BigInt(`1771`),Z:cC.create(BigInt(`-11`))}),fC=$S(lC.ProjectivePoint,e=>{let{x:t,y:n}=dC(cC.create(e[0]));return uC(t,n)},{DST:`secp256k1_XMD:SHA-256_SSWU_RO_`,encodeDST:`secp256k1_XMD:SHA-256_SSWU_NU_`,p:cC.ORDER,m:1,k:128,expand:`xmd`,hash:Eb});fC.hashToCurve,fC.encodeToCurve;var pC=`0x0000000000000000000000000000000000000000`,mC=`0x0000000000000000000000000000000000000000000000000000000000000000`,hC=BigInt(0),gC=BigInt(1),_C=BigInt(2),vC=BigInt(27),yC=BigInt(28),bC=BigInt(35),xC=BigInt(`0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141`),SC=xC/_C,CC=Symbol.for(`nodejs.util.inspect.custom`),wC={};function TC(e){return zv(Qv(e),32)}var EC=class e{#e;#t;#n;#r;get r(){return this.#e}set r(e){q(Iv(e)===32,`invalid r`,`value`,e),this.#e=Y(e)}get s(){return q(parseInt(this.#t.substring(0,3))<8,`non-canonical s; use ._s`,`s`,this.#t),this.#t}set s(e){q(Iv(e)===32,`invalid s`,`value`,e),this.#t=Y(e)}get _s(){return this.#t}isValid(){return BigInt(this.#t)<=SC}get v(){return this.#n}set v(e){let t=Z(e,`value`);q(t===27||t===28,`invalid v`,`v`,e),this.#n=t}get networkV(){return this.#r}get legacyChainId(){let t=this.networkV;return t==null?null:e.getChainId(t)}get yParity(){return this.v===27?0:1}get yParityAndS(){let e=J(this.s);return this.yParity&&(e[0]|=128),Y(e)}get compactSerialized(){return Fv([this.r,this.yParityAndS])}get serialized(){return Fv([this.r,this.s,this.yParity?`0x1c`:`0x1b`])}constructor(e,t,n,r){kv(e,wC,`Signature`),this.#e=t,this.#t=n,this.#n=r,this.#r=null}getCanonical(){if(this.isValid())return this;let t=xC-BigInt(this._s),n=55-this.v,r=new e(wC,this.r,TC(t),n);return this.networkV&&(r.#r=this.networkV),r}clone(){let t=new e(wC,this.r,this._s,this.v);return this.networkV&&(t.#r=this.networkV),t}toJSON(){let e=this.networkV;return{_type:`signature`,networkV:e==null?null:e.toString(),r:this.r,s:this._s,v:this.v}}[CC](){return this.toString()}toString(){return this.isValid()?`Signature { r: ${this.r}, s: ${this._s}, v: ${this.v} }`:`Signature { r: ${this.r}, s: ${this._s}, v: ${this.v}, valid: false }`}static getChainId(e){let t=X(e,`v`);return t==vC||t==yC?hC:(q(t>=bC,`invalid EIP-155 v`,`v`,e),(t-bC)/_C)}static getChainIdV(e,t){return X(e)*_C+BigInt(35+t-27)}static getNormalizedV(e){let t=X(e);return t===hC||t===vC?27:t===gC||t===yC?28:(q(t>=bC,`invalid v`,`v`,e),t&gC?27:28)}static from(t){function n(e,n){q(e,n,`signature`,t)}if(t==null)return new e(wC,mC,mC,27);if(typeof t==`string`){let r=J(t,`signature`);if(r.length===64){let t=Y(r.slice(0,32)),n=r.slice(32,64),i=n[0]&128?28:27;return n[0]&=127,new e(wC,t,Y(n),i)}if(r.length===65)return new e(wC,Y(r.slice(0,32)),Y(r.slice(32,64)),e.getNormalizedV(r[64]));n(!1,`invalid raw signature length`)}if(t instanceof e)return t.clone();let r=t.r;n(r!=null,`missing r`);let i=TC(r),a=(function(e,t){if(e!=null)return TC(e);if(t!=null){n(Mv(t,32),`invalid yParityAndS`);let e=J(t);return e[0]&=127,Y(e)}n(!1,`missing s`)})(t.s,t.yParityAndS),{networkV:o,v:s}=(function(t,r,i){if(t!=null){let n=X(t);return{networkV:n>=bC?n:void 0,v:e.getNormalizedV(n)}}if(r!=null)return n(Mv(r,32),`invalid yParityAndS`),{v:J(r)[0]&128?28:27};if(i!=null){switch(Z(i,`sig.yParity`)){case 0:return{v:27};case 1:return{v:28}}n(!1,`invalid yParity`)}n(!1,`missing v`)})(t.v,t.yParityAndS,t.yParity),c=new e(wC,i,a,s);return o&&(c.#r=o),n(t.yParity==null||Z(t.yParity,`sig.yParity`)===c.yParity,`yParity mismatch`),n(t.yParityAndS==null||t.yParityAndS===c.yParityAndS,`yParityAndS mismatch`),c}},DC=class e{#e;constructor(e){q(Iv(e)===32,`invalid private key`,`privateKey`,`[REDACTED]`),this.#e=Y(e)}get privateKey(){return this.#e}get publicKey(){return e.computePublicKey(this.#e)}get compressedPublicKey(){return e.computePublicKey(this.#e,!0)}sign(e){q(Iv(e)===32,`invalid digest length`,`digest`,e);let t=lC.sign(jv(e),jv(this.#e),{lowS:!0});return EC.from({r:Zv(t.r,32),s:Zv(t.s,32),v:t.recovery?28:27})}computeSharedSecret(t){let n=e.computePublicKey(t);return Y(lC.getSharedSecret(jv(this.#e),J(n),!1))}static computePublicKey(e,t){let n=J(e,`key`);if(n.length===32)return Y(lC.getPublicKey(n,!!t));if(n.length===64){let e=new Uint8Array(65);e[0]=4,e.set(n,1),n=e}return Y(lC.ProjectivePoint.fromHex(n).toRawBytes(t))}static recoverPublicKey(e,t){q(Iv(e)===32,`invalid digest length`,`digest`,e);let n=EC.from(t),r=lC.Signature.fromCompact(jv(Fv([n.r,n.s])));r=r.addRecoveryBit(n.yParity);let i=r.recoverPublicKey(jv(e));return q(i!=null,`invalid signature for digest`,`signature`,t),`0x`+i.toHex(!1)}static addPoints(t,n,r){let i=lC.ProjectivePoint.fromHex(e.computePublicKey(t).substring(2)),a=lC.ProjectivePoint.fromHex(e.computePublicKey(n).substring(2));return`0x`+i.add(a).toHex(!!r)}},OC=BigInt(0),kC=BigInt(36);function AC(e){e=e.toLowerCase();let t=e.substring(2).split(``),n=new Uint8Array(40);for(let e=0;e<40;e++)n[e]=t[e].charCodeAt(0);let r=J(yx(n));for(let e=0;e<40;e+=2)r[e>>1]>>4>=8&&(t[e]=t[e].toUpperCase()),(r[e>>1]&15)>=8&&(t[e+1]=t[e+1].toUpperCase());return`0x`+t.join(``)}var jC={};for(let e=0;e<10;e++)jC[String(e)]=String(e);for(let e=0;e<26;e++)jC[String.fromCharCode(65+e)]=String(10+e);var MC=15;function NC(e){e=e.toUpperCase(),e=e.substring(4)+e.substring(0,2)+`00`;let t=e.split(``).map(e=>jC[e]).join(``);for(;t.length>=MC;){let e=t.substring(0,MC);t=parseInt(e,10)%97+t.substring(e.length)}let n=String(98-parseInt(t,10)%97);for(;n.length<2;)n=`0`+n;return n}var PC=(function(){let e={};for(let t=0;t<36;t++){let n=`0123456789abcdefghijklmnopqrstuvwxyz`[t];e[n]=BigInt(t)}return e})();function FC(e){e=e.toLowerCase();let t=OC;for(let n=0;n<e.length;n++)t=t*kC+PC[e[n]];return t}function IC(e){if(q(typeof e==`string`,`invalid address`,`address`,e),e.match(/^(0x)?[0-9a-fA-F]{40}$/)){e.startsWith(`0x`)||(e=`0x`+e);let t=AC(e);return q(!e.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||t===e,`bad address checksum`,`address`,e),t}if(e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){q(e.substring(2,4)===NC(e),`bad icap checksum`,`address`,e);let t=FC(e.substring(4)).toString(16);for(;t.length<40;)t=`0`+t;return AC(`0x`+t)}q(!1,`invalid address`,`address`,e)}function LC(e){let t=IC(e.from),n=X(e.nonce,`tx.nonce`).toString(16);return n=n===`0`?`0x`:n.length%2?`0x0`+n:`0x`+n,IC(Lv(yx(By([t,n])),12))}function RC(e){return e&&typeof e.getAddress==`function`}async function zC(e,t){let n=await t;return(n==null||n===`0x0000000000000000000000000000000000000000`)&&(K(typeof e!=`string`,`unconfigured name`,`UNCONFIGURED_NAME`,{value:e}),q(!1,`invalid AddressLike value; did not resolve to a value address`,`target`,e)),IC(n)}function BC(e,t){if(typeof e==`string`)return e.match(/^0x[0-9a-f]{40}$/i)?IC(e):(K(t!=null,`ENS resolution requires a provider`,`UNSUPPORTED_OPERATION`,{operation:`resolveName`}),zC(e,t.resolveName(e)));if(RC(e))return zC(e,e.getAddress());if(e&&typeof e.then==`function`)return zC(e,e);q(!1,`unsupported addressable value`,`target`,e)}var VC={};function $(e,t){let n=!1;return t<0&&(n=!0,t*=-1),new WC(VC,`${n?``:`u`}int${t}`,e,{signed:n,width:t})}function HC(e,t){return new WC(VC,`bytes${t||``}`,e,{size:t})}var UC=Symbol.for(`_ethers_typed`),WC=class e{type;value;#e;_typedSymbol;constructor(e,t,n,r){r??=null,kv(VC,e,`Typed`),G(this,{_typedSymbol:UC,type:t,value:n}),this.#e=r,this.format()}format(){if(this.type===`array`||this.type===`dynamicArray`)throw Error(``);return this.type===`tuple`?`tuple(${this.value.map(e=>e.format()).join(`,`)})`:this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.startsWith(`bytes`)}isString(){return this.type===`string`}get tupleName(){if(this.type!==`tuple`)throw TypeError(`not a tuple`);return this.#e}get arrayLength(){if(this.type!==`array`)throw TypeError(`not an array`);return this.#e===!0?-1:this.#e===!1?this.value.length:null}static from(t,n){return new e(VC,t,n)}static uint8(e){return $(e,8)}static uint16(e){return $(e,16)}static uint24(e){return $(e,24)}static uint32(e){return $(e,32)}static uint40(e){return $(e,40)}static uint48(e){return $(e,48)}static uint56(e){return $(e,56)}static uint64(e){return $(e,64)}static uint72(e){return $(e,72)}static uint80(e){return $(e,80)}static uint88(e){return $(e,88)}static uint96(e){return $(e,96)}static uint104(e){return $(e,104)}static uint112(e){return $(e,112)}static uint120(e){return $(e,120)}static uint128(e){return $(e,128)}static uint136(e){return $(e,136)}static uint144(e){return $(e,144)}static uint152(e){return $(e,152)}static uint160(e){return $(e,160)}static uint168(e){return $(e,168)}static uint176(e){return $(e,176)}static uint184(e){return $(e,184)}static uint192(e){return $(e,192)}static uint200(e){return $(e,200)}static uint208(e){return $(e,208)}static uint216(e){return $(e,216)}static uint224(e){return $(e,224)}static uint232(e){return $(e,232)}static uint240(e){return $(e,240)}static uint248(e){return $(e,248)}static uint256(e){return $(e,256)}static uint(e){return $(e,256)}static int8(e){return $(e,-8)}static int16(e){return $(e,-16)}static int24(e){return $(e,-24)}static int32(e){return $(e,-32)}static int40(e){return $(e,-40)}static int48(e){return $(e,-48)}static int56(e){return $(e,-56)}static int64(e){return $(e,-64)}static int72(e){return $(e,-72)}static int80(e){return $(e,-80)}static int88(e){return $(e,-88)}static int96(e){return $(e,-96)}static int104(e){return $(e,-104)}static int112(e){return $(e,-112)}static int120(e){return $(e,-120)}static int128(e){return $(e,-128)}static int136(e){return $(e,-136)}static int144(e){return $(e,-144)}static int152(e){return $(e,-152)}static int160(e){return $(e,-160)}static int168(e){return $(e,-168)}static int176(e){return $(e,-176)}static int184(e){return $(e,-184)}static int192(e){return $(e,-192)}static int200(e){return $(e,-200)}static int208(e){return $(e,-208)}static int216(e){return $(e,-216)}static int224(e){return $(e,-224)}static int232(e){return $(e,-232)}static int240(e){return $(e,-240)}static int248(e){return $(e,-248)}static int256(e){return $(e,-256)}static int(e){return $(e,-256)}static bytes1(e){return HC(e,1)}static bytes2(e){return HC(e,2)}static bytes3(e){return HC(e,3)}static bytes4(e){return HC(e,4)}static bytes5(e){return HC(e,5)}static bytes6(e){return HC(e,6)}static bytes7(e){return HC(e,7)}static bytes8(e){return HC(e,8)}static bytes9(e){return HC(e,9)}static bytes10(e){return HC(e,10)}static bytes11(e){return HC(e,11)}static bytes12(e){return HC(e,12)}static bytes13(e){return HC(e,13)}static bytes14(e){return HC(e,14)}static bytes15(e){return HC(e,15)}static bytes16(e){return HC(e,16)}static bytes17(e){return HC(e,17)}static bytes18(e){return HC(e,18)}static bytes19(e){return HC(e,19)}static bytes20(e){return HC(e,20)}static bytes21(e){return HC(e,21)}static bytes22(e){return HC(e,22)}static bytes23(e){return HC(e,23)}static bytes24(e){return HC(e,24)}static bytes25(e){return HC(e,25)}static bytes26(e){return HC(e,26)}static bytes27(e){return HC(e,27)}static bytes28(e){return HC(e,28)}static bytes29(e){return HC(e,29)}static bytes30(e){return HC(e,30)}static bytes31(e){return HC(e,31)}static bytes32(e){return HC(e,32)}static address(t){return new e(VC,`address`,t)}static bool(t){return new e(VC,`bool`,!!t)}static bytes(t){return new e(VC,`bytes`,t)}static string(t){return new e(VC,`string`,t)}static array(e,t){throw Error(`not implemented yet`)}static tuple(e,t){throw Error(`not implemented yet`)}static overrides(t){return new e(VC,`overrides`,Object.assign({},t))}static isTyped(e){return e&&typeof e==`object`&&`_typedSymbol`in e&&e._typedSymbol===UC}static dereference(t,n){if(e.isTyped(t)){if(t.type!==n)throw Error(`invalid type: expecetd ${n}, got ${t.type}`);return t.value}return t}},GC=class extends Zy{constructor(e){super(`address`,`address`,e,!1)}defaultValue(){return`0x0000000000000000000000000000000000000000`}encode(e,t){let n=WC.dereference(t,`string`);try{n=IC(n)}catch(e){return this._throwError(e.message,t)}return e.writeValue(n)}decode(e){return IC(Zv(e.readValue(),20))}},KC=class extends Zy{coder;constructor(e){super(e.name,e.type,`_`,e.dynamic),this.coder=e}defaultValue(){return this.coder.defaultValue()}encode(e,t){return this.coder.encode(e,t)}decode(e){return this.coder.decode(e)}};function qC(e,t,n){let r=[];if(Array.isArray(n))r=n;else if(n&&typeof n==`object`){let e={};r=t.map(t=>{let r=t.localName;return K(r,`cannot encode object for signature with missing names`,`INVALID_ARGUMENT`,{argument:`values`,info:{coder:t},value:n}),K(!e[r],`cannot encode object for signature with duplicate names`,`INVALID_ARGUMENT`,{argument:`values`,info:{coder:t},value:n}),e[r]=!0,n[r]})}else q(!1,`invalid tuple value`,`tuple`,n);q(t.length===r.length,`types/value length mismatch`,`tuple`,n);let i=new Qy,a=new Qy,o=[];t.forEach((e,t)=>{let n=r[t];if(e.dynamic){let t=a.length;e.encode(a,n);let r=i.writeUpdatableValue();o.push(e=>{r(e+t)})}else e.encode(i,n)}),o.forEach(e=>{e(i.length)});let s=e.appendWriter(i);return s+=e.appendWriter(a),s}function JC(e,t){let n=[],r=[],i=e.subReader(0);return t.forEach(t=>{let a=null;if(t.dynamic){let n=e.readIndex(),r=i.subReader(n);try{a=t.decode(r)}catch(e){if(Cv(e,`BUFFER_OVERRUN`))throw e;a=e,a.baseType=t.name,a.name=t.localName,a.type=t.type}}else try{a=t.decode(e)}catch(e){if(Cv(e,`BUFFER_OVERRUN`))throw e;a=e,a.baseType=t.name,a.name=t.localName,a.type=t.type}if(a==null)throw Error(`investigate`);n.push(a),r.push(t.localName||null)}),Yy.fromItems(n,r)}var YC=class extends Zy{coder;length;constructor(e,t,n){let r=e.type+`[`+(t>=0?t:``)+`]`,i=t===-1||e.dynamic;super(`array`,r,n,i),G(this,{coder:e,length:t})}defaultValue(){let e=this.coder.defaultValue(),t=[];for(let n=0;n<this.length;n++)t.push(e);return t}encode(e,t){let n=WC.dereference(t,`array`);Array.isArray(n)||this._throwError(`expected array value`,n);let r=this.length;r===-1&&(r=n.length,e.writeValue(n.length)),Ev(n.length,r,`coder array`+(this.localName?` `+this.localName:``));let i=[];for(let e=0;e<n.length;e++)i.push(this.coder);return qC(e,i,n)}decode(e){let t=this.length;t===-1&&(t=e.readIndex(),K(t*32<=e.dataLength,`insufficient data length`,`BUFFER_OVERRUN`,{buffer:e.bytes,offset:t*32,length:e.dataLength}));let n=[];for(let e=0;e<t;e++)n.push(new KC(this.coder));return JC(e,n)}},XC=class extends Zy{constructor(e){super(`bool`,`bool`,e,!1)}defaultValue(){return!1}encode(e,t){let n=WC.dereference(t,`bool`);return e.writeValue(+!!n)}decode(e){return!!e.readValue()}},ZC=class extends Zy{constructor(e,t){super(e,e,t,!0)}defaultValue(){return`0x`}encode(e,t){t=jv(t);let n=e.writeValue(t.length);return n+=e.writeBytes(t),n}decode(e){return e.readBytes(e.readIndex(),!0)}},QC=class extends ZC{constructor(e){super(`bytes`,e)}decode(e){return Y(super.decode(e))}},$C=class extends Zy{size;constructor(e,t){let n=`bytes`+String(e);super(n,n,t,!1),G(this,{size:e},{size:`number`})}defaultValue(){return`0x0000000000000000000000000000000000000000000000000000000000000000`.substring(0,2+this.size*2)}encode(e,t){let n=jv(WC.dereference(t,this.type));return n.length!==this.size&&this._throwError(`incorrect data length`,t),e.writeBytes(n)}decode(e){return Y(e.readBytes(this.size))}},ew=new Uint8Array([]),tw=class extends Zy{constructor(e){super(`null`,``,e,!1)}defaultValue(){return null}encode(e,t){return t!=null&&this._throwError(`not null`,t),e.writeBytes(ew)}decode(e){return e.readBytes(0),null}},nw=BigInt(0),rw=BigInt(1),iw=BigInt(`0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`),aw=class extends Zy{size;signed;constructor(e,t,n){let r=(t?`int`:`uint`)+e*8;super(r,r,n,!1),G(this,{size:e,signed:t},{size:`number`,signed:`boolean`})}defaultValue(){return 0}encode(e,t){let n=X(WC.dereference(t,this.type)),r=Kv(iw,256);if(this.signed){let e=Kv(r,this.size*8-1);(n>e||n<-(e+rw))&&this._throwError(`value out-of-bounds`,t),n=Gv(n,256)}else (n<nw||n>Kv(r,this.size*8))&&this._throwError(`value out-of-bounds`,t);return e.writeValue(n)}decode(e){let t=Kv(e.readValue(),this.size*8);return this.signed&&(t=Wv(t,this.size*8)),t}},ow=class extends ZC{constructor(e){super(`string`,e)}defaultValue(){return``}encode(e,t){return super.encode(e,dy(WC.dereference(t,`string`)))}decode(e){return py(super.decode(e))}},sw=class extends Zy{coders;constructor(e,t){let n=!1,r=[];e.forEach(e=>{e.dynamic&&(n=!0),r.push(e.type)});let i=`tuple(`+r.join(`,`)+`)`;super(`tuple`,i,t,n),G(this,{coders:Object.freeze(e.slice())})}defaultValue(){let e=[];this.coders.forEach(t=>{e.push(t.defaultValue())});let t=this.coders.reduce((e,t)=>{let n=t.localName;return n&&(e[n]||(e[n]=0),e[n]++),e},{});return this.coders.forEach((n,r)=>{let i=n.localName;!i||t[i]!==1||(i===`length`&&(i=`_length`),e[i]??(e[i]=e[r]))}),Object.freeze(e)}encode(e,t){let n=WC.dereference(t,`tuple`);return qC(e,this.coders,n)}decode(e){return JC(e,this.coders)}};function cw(e,t){return{address:IC(e),storageKeys:t.map((e,t)=>(q(Mv(e,32),`invalid slot`,`storageKeys[${t}]`,e),e.toLowerCase()))}}function lw(e){if(Array.isArray(e))return e.map((t,n)=>Array.isArray(t)?(q(t.length===2,`invalid slot set`,`value[${n}]`,t),cw(t[0],t[1])):(q(typeof t==`object`&&!!t,`invalid address-slot set`,`value`,e),cw(t.address,t.storageKeys)));q(typeof e==`object`&&!!e,`invalid access list`,`value`,e);let t=Object.keys(e).map(t=>{let n=e[t].reduce((e,t)=>(e[t]=!0,e),{});return cw(t,Object.keys(n).sort())});return t.sort((e,t)=>e.address.localeCompare(t.address)),t}function uw(e){return{address:IC(e.address),nonce:X(e.nonce==null?0:e.nonce),chainId:X(e.chainId==null?0:e.chainId),signature:EC.from(e.signature)}}function dw(e){let t;return t=typeof e==`string`?DC.computePublicKey(e,!1):e.publicKey,IC(yx(`0x`+t.substring(4)).substring(26))}function fw(e,t){return dw(DC.recoverPublicKey(e,t))}var pw=BigInt(0),mw=BigInt(2),hw=BigInt(27),gw=BigInt(28),_w=BigInt(35),vw=BigInt(`0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`),yw=Symbol.for(`nodejs.util.inspect.custom`),bw=4096*32,xw=128;function Sw(e){return{blobToKzgCommitment:t=>{if(`computeBlobProof`in e){if(`blobToKzgCommitment`in e&&typeof e.blobToKzgCommitment==`function`)return J(e.blobToKzgCommitment(Y(t)))}else if(`blobToKzgCommitment`in e&&typeof e.blobToKzgCommitment==`function`)return J(e.blobToKzgCommitment(t));if(`blobToKZGCommitment`in e&&typeof e.blobToKZGCommitment==`function`)return J(e.blobToKZGCommitment(Y(t)));q(!1,`unsupported KZG library`,`kzg`,e)},computeBlobKzgProof:(t,n)=>{if(`computeBlobProof`in e&&typeof e.computeBlobProof==`function`)return J(e.computeBlobProof(Y(t),Y(n)));if(`computeBlobKzgProof`in e&&typeof e.computeBlobKzgProof==`function`)return e.computeBlobKzgProof(t,n);if(`computeBlobKZGProof`in e&&typeof e.computeBlobKZGProof==`function`)return J(e.computeBlobKZGProof(Y(t),Y(n)));q(!1,`unsupported KZG library`,`kzg`,e)}}}function Cw(e,t){let n=e.toString(16);for(;n.length<2;)n=`0`+n;return n+=Ex(t).substring(4),`0x`+n}function ww(e){return e===`0x`?null:IC(e)}function Tw(e,t){try{return lw(e)}catch(n){q(!1,n.message,t,e)}}function Ew(e,t){try{if(!Array.isArray(e))throw Error(`authorizationList: invalid array`);let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(!Array.isArray(r))throw Error(`authorization[${n}]: invalid array`);if(r.length!==6)throw Error(`authorization[${n}]: wrong length`);if(!r[1])throw Error(`authorization[${n}]: null address`);t.push({address:ww(r[1]),nonce:Ow(r[2],`nonce`),chainId:Ow(r[0],`chainId`),signature:EC.from({yParity:Dw(r[3],`yParity`),r:zv(r[4],32),s:zv(r[5],32)})})}return t}catch(n){q(!1,n.message,t,e)}}function Dw(e,t){return e===`0x`?0:Z(e,t)}function Ow(e,t){if(e===`0x`)return pw;let n=X(e,t);return q(n<=vw,`value exceeds uint size`,t,n),n}function kw(e,t){let n=X(e,`value`),r=Qv(n);return q(r.length<=32,`value too large`,`tx.${t}`,n),r}function Aw(e){return lw(e).map(e=>[e.address,e.storageKeys])}function jw(e){return e.map(e=>[kw(e.chainId,`chainId`),e.address,kw(e.nonce,`nonce`),kw(e.signature.yParity,`yParity`),Qv(e.signature.r),Qv(e.signature._s)])}function Mw(e,t){q(Array.isArray(e),`invalid ${t}`,`value`,e);for(let t=0;t<e.length;t++)q(Mv(e[t],32),"invalid ${ param } hash",`value[${t}]`,e[t]);return e}function Nw(e){let t=Iy(e);q(Array.isArray(t)&&(t.length===9||t.length===6),`invalid field count for legacy transaction`,`data`,e);let n={type:0,nonce:Dw(t[0],`nonce`),gasPrice:Ow(t[1],`gasPrice`),gasLimit:Ow(t[2],`gasLimit`),to:ww(t[3]),value:Ow(t[4],`value`),data:Y(t[5]),chainId:pw};if(t.length===6)return n;let r=Ow(t[6],`v`),i=Ow(t[7],`r`),a=Ow(t[8],`s`);if(i===pw&&a===pw)n.chainId=r;else{let e=(r-_w)/mw;e<pw&&(e=pw),n.chainId=e,q(e!==pw||r===hw||r===gw,`non-canonical legacy v`,`v`,t[6]),n.signature=EC.from({r:zv(t[7],32),s:zv(t[8],32),v:r})}return n}function Pw(e,t){let n=[kw(e.nonce,`nonce`),kw(e.gasPrice||0,`gasPrice`),kw(e.gasLimit,`gasLimit`),e.to||`0x`,kw(e.value,`value`),e.data],r=pw;if(e.chainId!=pw)r=X(e.chainId,`tx.chainId`),q(!t||t.networkV==null||t.legacyChainId===r,`tx.chainId/sig.v mismatch`,`sig`,t);else if(e.signature){let t=e.signature.legacyChainId;t!=null&&(r=t)}if(!t)return r!==pw&&(n.push(Qv(r)),n.push(`0x`),n.push(`0x`)),By(n);let i=BigInt(27+t.yParity);return r===pw?BigInt(t.v)!==i&&q(!1,`tx.chainId/sig.v mismatch`,`sig`,t):i=EC.getChainIdV(r,t.v),n.push(Qv(i)),n.push(Qv(t.r)),n.push(Qv(t._s)),By(n)}function Fw(e,t){let n;try{if(n=Dw(t[0],`yParity`),n!==0&&n!==1)throw Error(`bad yParity`)}catch{q(!1,`invalid yParity`,`yParity`,t[0])}let r=zv(t[1],32),i=zv(t[2],32);e.signature=EC.from({r,s:i,yParity:n})}function Iw(e){let t=Iy(J(e).slice(1));q(Array.isArray(t)&&(t.length===9||t.length===12),`invalid field count for transaction type: 2`,`data`,Y(e));let n={type:2,chainId:Ow(t[0],`chainId`),nonce:Dw(t[1],`nonce`),maxPriorityFeePerGas:Ow(t[2],`maxPriorityFeePerGas`),maxFeePerGas:Ow(t[3],`maxFeePerGas`),gasPrice:null,gasLimit:Ow(t[4],`gasLimit`),to:ww(t[5]),value:Ow(t[6],`value`),data:Y(t[7]),accessList:Tw(t[8],`accessList`)};return t.length===9||Fw(n,t.slice(9)),n}function Lw(e,t){let n=[kw(e.chainId,`chainId`),kw(e.nonce,`nonce`),kw(e.maxPriorityFeePerGas||0,`maxPriorityFeePerGas`),kw(e.maxFeePerGas||0,`maxFeePerGas`),kw(e.gasLimit,`gasLimit`),e.to||`0x`,kw(e.value,`value`),e.data,Aw(e.accessList||[])];return t&&(n.push(kw(t.yParity,`yParity`)),n.push(Qv(t.r)),n.push(Qv(t.s))),Fv([`0x02`,By(n)])}function Rw(e){let t=Iy(J(e).slice(1));q(Array.isArray(t)&&(t.length===8||t.length===11),`invalid field count for transaction type: 1`,`data`,Y(e));let n={type:1,chainId:Ow(t[0],`chainId`),nonce:Dw(t[1],`nonce`),gasPrice:Ow(t[2],`gasPrice`),gasLimit:Ow(t[3],`gasLimit`),to:ww(t[4]),value:Ow(t[5],`value`),data:Y(t[6]),accessList:Tw(t[7],`accessList`)};return t.length===8||Fw(n,t.slice(8)),n}function zw(e,t){let n=[kw(e.chainId,`chainId`),kw(e.nonce,`nonce`),kw(e.gasPrice||0,`gasPrice`),kw(e.gasLimit,`gasLimit`),e.to||`0x`,kw(e.value,`value`),e.data,Aw(e.accessList||[])];return t&&(n.push(kw(t.yParity,`recoveryParam`)),n.push(Qv(t.r)),n.push(Qv(t.s))),Fv([`0x01`,By(n)])}function Bw(e){let t=Iy(J(e).slice(1)),n=`3`,r=null,i=null;if(t.length===4&&Array.isArray(t[0])){n=`3 (network format)`;let e=t[1],r=t[2],a=t[3];q(Array.isArray(e),`invalid network format: blobs not an array`,`fields[1]`,e),q(Array.isArray(r),`invalid network format: commitments not an array`,`fields[2]`,r),q(Array.isArray(a),`invalid network format: proofs not an array`,`fields[3]`,a),q(e.length===r.length,`invalid network format: blobs/commitments length mismatch`,`fields`,t),q(e.length===a.length,`invalid network format: blobs/proofs length mismatch`,`fields`,t),i=[];for(let n=0;n<t[1].length;n++)i.push({data:e[n],commitment:r[n],proof:a[n]});t=t[0]}else if(t.length===5&&Array.isArray(t[0])){n=`3 (EIP-7594 network format)`,r=Z(t[1]);let e=t[2],a=t[3],o=t[4];q(r===1,`unsupported EIP-7594 network format version: ${r}`,`fields[1]`,r),q(Array.isArray(e),`invalid EIP-7594 network format: blobs not an array`,`fields[2]`,e),q(Array.isArray(a),`invalid EIP-7594 network format: commitments not an array`,`fields[3]`,a),q(Array.isArray(o),`invalid EIP-7594 network format: proofs not an array`,`fields[4]`,o),q(e.length===a.length,`invalid network format: blobs/commitments length mismatch`,`fields`,t),q(e.length*xw===o.length,`invalid network format: blobs/proofs length mismatch`,`fields`,t),i=[];for(let t=0;t<e.length;t++){let n=[];for(let e=0;e<xw;e++)n.push(o[t*xw+e]);i.push({data:e[t],commitment:a[t],proof:Fv(n)})}t=t[0]}q(Array.isArray(t)&&(t.length===11||t.length===14),`invalid field count for transaction type: ${n}`,`data`,Y(e));let a={type:3,chainId:Ow(t[0],`chainId`),nonce:Dw(t[1],`nonce`),maxPriorityFeePerGas:Ow(t[2],`maxPriorityFeePerGas`),maxFeePerGas:Ow(t[3],`maxFeePerGas`),gasPrice:null,gasLimit:Ow(t[4],`gasLimit`),to:ww(t[5]),value:Ow(t[6],`value`),data:Y(t[7]),accessList:Tw(t[8],`accessList`),maxFeePerBlobGas:Ow(t[9],`maxFeePerBlobGas`),blobVersionedHashes:t[10],blobWrapperVersion:r};i&&(a.blobs=i),q(a.to!=null,`invalid address for transaction type: ${n}`,`data`,e),q(Array.isArray(a.blobVersionedHashes),`invalid blobVersionedHashes: must be an array`,`data`,e);for(let t=0;t<a.blobVersionedHashes.length;t++)q(Mv(a.blobVersionedHashes[t],32),`invalid blobVersionedHash at index ${t}: must be length 32`,`data`,e);return t.length===11||Fw(a,t.slice(11)),a}function Vw(e,t,n){let r=[kw(e.chainId,`chainId`),kw(e.nonce,`nonce`),kw(e.maxPriorityFeePerGas||0,`maxPriorityFeePerGas`),kw(e.maxFeePerGas||0,`maxFeePerGas`),kw(e.gasLimit,`gasLimit`),e.to||`0x0000000000000000000000000000000000000000`,kw(e.value,`value`),e.data,Aw(e.accessList||[]),kw(e.maxFeePerBlobGas||0,`maxFeePerBlobGas`),Mw(e.blobVersionedHashes||[],`blobVersionedHashes`)];if(t&&(r.push(kw(t.yParity,`yParity`)),r.push(Qv(t.r)),r.push(Qv(t.s)),n)){if(e.blobWrapperVersion!=null){let t=Qv(e.blobWrapperVersion),i=[];for(let{proof:e}of n){let t=J(e),n=t.length/xw;for(let e=0;e<t.length;e+=n)i.push(t.subarray(e,e+n))}return Fv([`0x03`,By([r,t,n.map(e=>e.data),n.map(e=>e.commitment),i])])}return Fv([`0x03`,By([r,n.map(e=>e.data),n.map(e=>e.commitment),n.map(e=>e.proof)])])}return Fv([`0x03`,By(r)])}function Hw(e){let t=Iy(J(e).slice(1));q(Array.isArray(t)&&(t.length===10||t.length===13),`invalid field count for transaction type: 4`,`data`,Y(e));let n={type:4,chainId:Ow(t[0],`chainId`),nonce:Dw(t[1],`nonce`),maxPriorityFeePerGas:Ow(t[2],`maxPriorityFeePerGas`),maxFeePerGas:Ow(t[3],`maxFeePerGas`),gasPrice:null,gasLimit:Ow(t[4],`gasLimit`),to:ww(t[5]),value:Ow(t[6],`value`),data:Y(t[7]),accessList:Tw(t[8],`accessList`),authorizationList:Ew(t[9],`authorizationList`)};return t.length===10||Fw(n,t.slice(10)),n}function Uw(e,t){let n=[kw(e.chainId,`chainId`),kw(e.nonce,`nonce`),kw(e.maxPriorityFeePerGas||0,`maxPriorityFeePerGas`),kw(e.maxFeePerGas||0,`maxFeePerGas`),kw(e.gasLimit,`gasLimit`),e.to||`0x`,kw(e.value,`value`),e.data,Aw(e.accessList||[]),jw(e.authorizationList||[])];return t&&(n.push(kw(t.yParity,`yParity`)),n.push(Qv(t.r)),n.push(Qv(t.s))),Fv([`0x04`,By(n)])}var Ww=class e{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;get type(){return this.#e}set type(e){switch(e){case null:this.#e=null;break;case 0:case`legacy`:this.#e=0;break;case 1:case`berlin`:case`eip-2930`:this.#e=1;break;case 2:case`london`:case`eip-1559`:this.#e=2;break;case 3:case`cancun`:case`eip-4844`:this.#e=3;break;case 4:case`pectra`:case`eip-7702`:this.#e=4;break;default:q(!1,`unsupported transaction type`,`type`,e)}}get typeName(){switch(this.type){case 0:return`legacy`;case 1:return`eip-2930`;case 2:return`eip-1559`;case 3:return`eip-4844`;case 4:return`eip-7702`}return null}get to(){let e=this.#t;return e==null&&this.type===3?pC:e}set to(e){this.#t=e==null?null:IC(e)}get nonce(){return this.#r}set nonce(e){this.#r=Z(e,`value`)}get gasLimit(){return this.#i}set gasLimit(e){this.#i=X(e)}get gasPrice(){let e=this.#a;return e==null&&(this.type===0||this.type===1)?pw:e}set gasPrice(e){this.#a=e==null?null:X(e,`gasPrice`)}get maxPriorityFeePerGas(){return this.#o??(this.type===2||this.type===3?pw:null)}set maxPriorityFeePerGas(e){this.#o=e==null?null:X(e,`maxPriorityFeePerGas`)}get maxFeePerGas(){return this.#s??(this.type===2||this.type===3?pw:null)}set maxFeePerGas(e){this.#s=e==null?null:X(e,`maxFeePerGas`)}get data(){return this.#n}set data(e){this.#n=Y(e)}get value(){return this.#c}set value(e){this.#c=X(e,`value`)}get chainId(){return this.#l}set chainId(e){this.#l=X(e)}get signature(){return this.#u||null}set signature(e){this.#u=e==null?null:EC.from(e)}isValid(){let e=this.signature;if(e&&!e.isValid())return!1;let t=this.authorizationList;if(t){for(let e of t)if(!e.signature.isValid())return!1}return!0}get accessList(){return(this.#d||null)??(this.type===1||this.type===2||this.type===3?[]:null)}set accessList(e){this.#d=e==null?null:lw(e)}get authorizationList(){let e=this.#g||null;return e==null&&this.type===4?[]:e}set authorizationList(e){this.#g=e==null?null:e.map(e=>uw(e))}get maxFeePerBlobGas(){let e=this.#f;return e==null&&this.type===3?pw:e}set maxFeePerBlobGas(e){this.#f=e==null?null:X(e,`maxFeePerBlobGas`)}get blobVersionedHashes(){let e=this.#p;return e==null&&this.type===3?[]:e}set blobVersionedHashes(e){if(e!=null){q(Array.isArray(e),`blobVersionedHashes must be an Array`,`value`,e),e=e.slice();for(let t=0;t<e.length;t++)q(Mv(e[t],32),`invalid blobVersionedHash`,`value[${t}]`,e[t])}this.#p=e}get blobs(){return this.#h==null?null:this.#h.map(e=>Object.assign({},e))}set blobs(e){if(e==null){this.#h=null;return}let t=[],n=[];for(let r=0;r<e.length;r++){let i=e[r];if(Nv(i)){K(this.#m,`adding a raw blob requires a KZG library`,`UNSUPPORTED_OPERATION`,{operation:`set blobs()`});let e=J(i);if(q(e.length<=bw,`blob is too large`,`blobs[${r}]`,i),e.length!==bw){let t=new Uint8Array(bw);t.set(e),e=t}let a=this.#m.blobToKzgCommitment(e),o=Y(this.#m.computeBlobKzgProof(e,a));t.push({data:Y(e),commitment:Y(a),proof:o}),n.push(Cw(1,a))}else{let e=Y(i.data),r=Y(i.commitment),a=Y(i.proof);t.push({data:e,commitment:r,proof:a}),n.push(Cw(1,r))}}this.#h=t,this.#p=n}get kzg(){return this.#m}set kzg(e){e==null?this.#m=null:this.#m=Sw(e)}get blobWrapperVersion(){return this.#_}set blobWrapperVersion(e){this.#_=e}constructor(){this.#e=null,this.#t=null,this.#r=0,this.#i=pw,this.#a=null,this.#o=null,this.#s=null,this.#n=`0x`,this.#c=pw,this.#l=pw,this.#u=null,this.#d=null,this.#f=null,this.#p=null,this.#m=null,this.#h=null,this.#g=null,this.#_=null}get hash(){return this.signature==null?null:yx(this.#v(!0,!1))}get unsignedHash(){return yx(this.unsignedSerialized)}get from(){return this.signature==null?null:fw(this.unsignedHash,this.signature.getCanonical())}get fromPublicKey(){return this.signature==null?null:DC.recoverPublicKey(this.unsignedHash,this.signature.getCanonical())}isSigned(){return this.signature!=null}#v(e,t){K(!e||this.signature!=null,`cannot serialize unsigned transaction; maybe you meant .unsignedSerialized`,`UNSUPPORTED_OPERATION`,{operation:`.serialized`});let n=e?this.signature:null;switch(this.inferType()){case 0:return Pw(this,n);case 1:return zw(this,n);case 2:return Lw(this,n);case 3:return Vw(this,n,t?this.blobs:null);case 4:return Uw(this,n)}K(!1,`unsupported transaction type`,`UNSUPPORTED_OPERATION`,{operation:`.serialized`})}get serialized(){return this.#v(!0,!0)}get unsignedSerialized(){return this.#v(!1,!1)}inferType(){let e=this.inferTypes();return e.indexOf(2)>=0?2:e.pop()}inferTypes(){let e=this.gasPrice!=null,t=this.maxFeePerGas!=null||this.maxPriorityFeePerGas!=null,n=this.accessList!=null,r=this.#f!=null||this.#p;this.maxFeePerGas!=null&&this.maxPriorityFeePerGas!=null&&K(this.maxFeePerGas>=this.maxPriorityFeePerGas,`priorityFee cannot be more than maxFee`,`BAD_DATA`,{value:this}),K(!t||this.type!==0&&this.type!==1,`transaction type cannot have maxFeePerGas or maxPriorityFeePerGas`,`BAD_DATA`,{value:this}),K(this.type!==0||!n,`legacy transaction cannot have accessList`,`BAD_DATA`,{value:this});let i=[];return this.type==null?this.authorizationList&&this.authorizationList.length?i.push(4):t?i.push(2):e?(i.push(1),n||i.push(0)):n?(i.push(1),i.push(2)):r&&this.to?i.push(3):(i.push(0),i.push(1),i.push(2),i.push(3)):i.push(this.type),i.sort(),i}isLegacy(){return this.type===0}isBerlin(){return this.type===1}isLondon(){return this.type===2}isCancun(){return this.type===3}clone(){return e.from(this)}toJSON(){let e=e=>e==null?null:e.toString();return{type:this.type,to:this.to,data:this.data,nonce:this.nonce,gasLimit:e(this.gasLimit),gasPrice:e(this.gasPrice),maxPriorityFeePerGas:e(this.maxPriorityFeePerGas),maxFeePerGas:e(this.maxFeePerGas),value:e(this.value),chainId:e(this.chainId),sig:this.signature?this.signature.toJSON():null,accessList:this.accessList}}[yw](){return this.toString()}toString(){let e=[],t=t=>{let n=this[t];typeof n==`string`&&(n=JSON.stringify(n)),e.push(`${t}: ${n}`)};this.type&&t(`type`),t(`to`),t(`data`),t(`nonce`),t(`gasLimit`),t(`value`),this.chainId!=null&&t(`chainId`),this.signature&&(t(`from`),e.push(`signature: ${this.signature.toString()}`));let n=this.authorizationList;if(n){let t=[];for(let e of n){let n=[];n.push(`address: ${JSON.stringify(e.address)}`),e.nonce!=null&&n.push(`nonce: ${e.nonce}`),e.chainId!=null&&n.push(`chainId: ${e.chainId}`),e.signature&&n.push(`signature: ${e.signature.toString()}`),t.push(`Authorization { ${n.join(`, `)} }`)}e.push(`authorizations: [ ${t.join(`, `)} ]`)}return`Transaction { ${e.join(`, `)} }`}static from(t){if(t==null)return new e;if(typeof t==`string`){let n=J(t);if(n[0]>=127)return e.from(Nw(n));switch(n[0]){case 1:return e.from(Rw(n));case 2:return e.from(Iw(n));case 3:return e.from(Bw(n));case 4:return e.from(Hw(n))}K(!1,`unsupported transaction type`,`UNSUPPORTED_OPERATION`,{operation:`from`})}let n=new e;return t.type!=null&&(n.type=t.type),t.to!=null&&(n.to=t.to),t.nonce!=null&&(n.nonce=t.nonce),t.gasLimit!=null&&(n.gasLimit=t.gasLimit),t.gasPrice!=null&&(n.gasPrice=t.gasPrice),t.maxPriorityFeePerGas!=null&&(n.maxPriorityFeePerGas=t.maxPriorityFeePerGas),t.maxFeePerGas!=null&&(n.maxFeePerGas=t.maxFeePerGas),t.maxFeePerBlobGas!=null&&(n.maxFeePerBlobGas=t.maxFeePerBlobGas),t.data!=null&&(n.data=t.data),t.value!=null&&(n.value=t.value),t.chainId!=null&&(n.chainId=t.chainId),t.signature!=null&&(n.signature=EC.from(t.signature)),t.accessList!=null&&(n.accessList=t.accessList),t.authorizationList!=null&&(n.authorizationList=t.authorizationList),t.blobVersionedHashes!=null&&(n.blobVersionedHashes=t.blobVersionedHashes),t.kzg!=null&&(n.kzg=t.kzg),t.blobWrapperVersion!=null&&(n.blobWrapperVersion=t.blobWrapperVersion),t.blobs!=null&&(n.blobs=t.blobs),t.hash!=null&&(q(n.isSigned(),`unsigned transaction cannot define '.hash'`,`tx`,t),q(n.hash===t.hash,`hash mismatch`,`tx`,t)),t.from!=null&&(q(n.isSigned(),`unsigned transaction cannot define '.from'`,`tx`,t),q(n.from.toLowerCase()===(t.from||``).toLowerCase(),`from mismatch`,`tx`,t)),n}};function Gw(e){return yx(dy(e))}var Kw=`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`,qw=new Map([[8217,`apostrophe`],[8260,`fraction slash`],[12539,`middle dot`]]),Jw=4;function Yw(e){let t=0;function n(){return e[t++]<<8|e[t++]}let r=n(),i=1,a=[0,1];for(let e=1;e<r;e++)a.push(i+=n());let o=n(),s=t;t+=o;let c=0,l=0;function u(){return c==0&&(l=l<<8|e[t++],c=8),l>>--c&1}let d=2**31,f=d>>>1,p=f>>1,m=d-1,h=0;for(let e=0;e<31;e++)h=h<<1|u();let g=[],_=0,v=d;for(;;){let e=Math.floor(((h-_+1)*i-1)/v),t=0,n=r;for(;n-t>1;){let r=t+n>>>1;e<a[r]?n=r:t=r}if(t==0)break;g.push(t);let o=_+Math.floor(v*a[t]/i),s=_+Math.floor(v*a[t+1]/i)-1;for(;((o^s)&f)==0;)h=h<<1&m|u(),o=o<<1&m,s=s<<1&m|1;for(;o&~s&p;)h=h&f|h<<1&m>>>1|u(),o=o<<1^f,s=(s^f)<<1|f|1;_=o,v=1+s-o}let y=r-4;return g.map(t=>{switch(t-y){case 3:return y+65792+(e[s++]<<16|e[s++]<<8|e[s++]);case 2:return y+256+(e[s++]<<8|e[s++]);case 1:return y+e[s++];default:return t-1}})}function Xw(e){let t=0;return()=>e[t++]}function Zw(e){return Xw(Yw(Qw(e)))}function Qw(e){let t=[];[...`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`].forEach((e,n)=>t[e.charCodeAt(0)]=n);let n=e.length,r=new Uint8Array(6*n>>3);for(let i=0,a=0,o=0,s=0;i<n;i++)s=s<<6|t[e.charCodeAt(i)],o+=6,o>=8&&(r[a++]=s>>(o-=8));return r}function $w(e){return e&1?~e>>1:e>>1}function eT(e,t){let n=Array(e);for(let r=0,i=0;r<e;r++)n[r]=i+=$w(t());return n}function tT(e,t=0){let n=[];for(;;){let r=e(),i=e();if(!i)break;t+=r;for(let e=0;e<i;e++)n.push(t+e);t+=i+1}return n}function nT(e){return iT(()=>{let t=tT(e);if(t.length)return t})}function rT(e){let t=[];for(;;){let n=e();if(n==0)break;t.push(oT(n,e))}for(;;){let n=e()-1;if(n<0)break;t.push(sT(n,e))}return t.flat()}function iT(e){let t=[];for(;;){let n=e(t.length);if(!n)break;t.push(n)}return t}function aT(e,t,n){let r=Array(e).fill().map(()=>[]);for(let i=0;i<t;i++)eT(e,n).forEach((e,t)=>r[t].push(e));return r}function oT(e,t){let n=1+t(),r=t(),i=iT(t);return aT(i.length,1+e,t).flatMap((e,t)=>{let[a,...o]=e;return Array(i[t]).fill().map((e,t)=>{let i=t*r;return[a+t*n,o.map(e=>e+i)]})})}function sT(e,t){return aT(1+t(),1+e,t).map(e=>[e[0],e.slice(1)])}function cT(e){let t=[],n=tT(e);return i(r([]),[]),t;function r(t){return{S:e(),B:iT(()=>{let t=tT(e).map(e=>n[e]);if(t.length)return r(t)}),Q:t}}function i({S:e,B:n},r,a){if(!(e&4&&a===r[r.length-1])){e&2&&(a=r[r.length-1]),e&1&&t.push(r);for(let e of n)for(let t of e.Q)i(e,[...r,t],a)}}}function lT(e){return e.toString(16).toUpperCase().padStart(2,`0`)}function uT(e){return`{${lT(e)}}`}function dT(e){let t=[];for(let n=0,r=e.length;n<r;){let r=e.codePointAt(n);n+=r<65536?1:2,t.push(r)}return t}function fT(e){let t=4096,n=e.length;if(n<t)return String.fromCodePoint(...e);let r=[];for(let i=0;i<n;)r.push(String.fromCodePoint(...e.slice(i,i+=t)));return r.join(``)}function pT(e,t){let n=e.length,r=n-t.length;for(let i=0;r==0&&i<n;i++)r=e[i]-t[i];return r}var mT=`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`,hT=44032,gT=4352,_T=4449,vT=4519,yT=19,bT=21,xT=28,ST=bT*xT,CT=hT+yT*ST,wT=gT+yT,TT=_T+bT,ET=vT+xT;function DT(e){return e>>24&255}function OT(e){return e&16777215}var kT,AT,jT,MT;function NT(){let e=Zw(mT);kT=new Map(nT(e).flatMap((e,t)=>e.map(e=>[e,t+1<<24]))),AT=new Set(tT(e)),jT=new Map,MT=new Map;for(let[t,n]of rT(e)){if(!AT.has(t)&&n.length==2){let[e,r]=n,i=MT.get(e);i||(i=new Map,MT.set(e,i)),i.set(r,t)}jT.set(t,n.reverse())}}function PT(e){return e>=hT&&e<CT}function FT(e,t){if(e>=gT&&e<wT&&t>=_T&&t<TT)return hT+(e-gT)*ST+(t-_T)*xT;if(PT(e)&&t>vT&&t<ET&&(e-hT)%xT==0)return e+(t-vT);{let n=MT.get(e);return n&&(n=n.get(t),n)?n:-1}}function IT(e){kT||NT();let t=[],n=[],r=!1;function i(e){let n=kT.get(e);n&&(r=!0,e|=n),t.push(e)}for(let r of e)for(;;){if(r<128)t.push(r);else if(PT(r)){let e=r-hT,t=e/ST|0,n=e%ST/xT|0,a=e%xT;i(gT+t),i(_T+n),a>0&&i(vT+a)}else{let e=jT.get(r);e?n.push(...e):i(r)}if(!n.length)break;r=n.pop()}if(r&&t.length>1){let e=DT(t[0]);for(let n=1;n<t.length;n++){let r=DT(t[n]);if(r==0||e<=r){e=r;continue}let i=n-1;for(;;){let n=t[i+1];if(t[i+1]=t[i],t[i]=n,!i||(e=DT(t[--i]),e<=r))break}e=DT(t[n])}}return t}function LT(e){let t=[],n=[],r=-1,i=0;for(let a of e){let e=DT(a),o=OT(a);if(r==-1)e==0?r=o:t.push(o);else if(i>0&&i>=e)e==0?(t.push(r,...n),n.length=0,r=o):n.push(o),i=e;else{let a=FT(r,o);a>=0?r=a:i==0&&e==0?(t.push(r),r=o):(n.push(o),i=e)}}return r>=0&&t.push(r,...n),t}function RT(e){return IT(e).map(OT)}function zT(e){return LT(IT(e))}var BT=45,VT=`.`,HT=65039,UT=1,WT=e=>Array.from(e);function GT(e,t){return e.P.has(t)||e.Q.has(t)}var KT=class extends Array{get is_emoji(){return!0}},qT,JT,YT,XT,ZT,QT,$T,eE,tE,nE,rE;function iE(){if(qT)return;let e=Zw(Kw),t=()=>tT(e),n=()=>new Set(t()),r=(e,t)=>t.forEach(t=>e.add(t));qT=new Map(rT(e)),JT=n(),YT=t(),XT=new Set(t().map(e=>YT[e])),YT=new Set(YT),ZT=n(),n();let i=nT(e),a=e(),o=()=>{let e=new Set;return t().forEach(t=>r(e,i[t])),r(e,t()),e};QT=iT(t=>{let n=iT(e).map(e=>e+96);if(n.length){let r=t>=a;n[0]-=32,n=fT(n),r&&(n=`Restricted[${n}]`);let i=o(),s=o(),c=!e();return{N:n,P:i,Q:s,M:c,R:r}}}),$T=n(),eE=new Map;let s=t().concat(WT($T)).sort((e,t)=>e-t);s.forEach((t,n)=>{let r=e(),i=s[n]=r?s[n-r]:{V:[],M:new Map};i.V.push(t),$T.has(t)||eE.set(t,i)});for(let{V:e,M:t}of new Set(eE.values())){let n=[];for(let t of e){let e=QT.filter(e=>GT(e,t)),i=n.find(({G:t})=>e.some(e=>t.has(e)));i||(i={G:new Set,V:[]},n.push(i)),i.V.push(t),r(i.G,e)}let i=n.flatMap(e=>WT(e.G));for(let{G:e,V:r}of n){let n=new Set(i.filter(t=>!e.has(t)));for(let e of r)t.set(e,n)}}tE=new Set;let c=new Set,l=e=>tE.has(e)?c.add(e):tE.add(e);for(let e of QT){for(let t of e.P)l(t);for(let t of e.Q)l(t)}for(let e of tE)!eE.has(e)&&!c.has(e)&&eE.set(e,UT);r(tE,RT(tE)),nE=cT(e).map(e=>KT.from(e)).sort(pT),rE=new Map;for(let e of nE){let t=[rE];for(let n of e){let e=t.map(e=>{let t=e.get(n);return t||(t=new Map,e.set(n,t)),t});n===HT?t.push(...e):t=e}for(let n of t)n.V=e}}function aE(e){return(fE(e)?``:`${oE(uE([e]))} `)+uT(e)}function oE(e){return`"${e}"\u200E`}function sE(e){if(e.length>=4&&e[2]==BT&&e[3]==BT)throw Error(`invalid label extension: "${fT(e.slice(0,4))}"`)}function cE(e){for(let t=e.lastIndexOf(95);t>0;)if(e[--t]!==95)throw Error(`underscore allowed only at start`)}function lE(e){let t=e[0],n=qw.get(t);if(n)throw bE(`leading ${n}`);let r=e.length,i=-1;for(let a=1;a<r;a++){t=e[a];let r=qw.get(t);if(r){if(i==a)throw bE(`${n} + ${r}`);i=a+1,n=r}}if(i==r)throw bE(`trailing ${n}`)}function uE(e,t=1/0,n=uT){let r=[];dE(e[0])&&r.push(`◌`),e.length>t&&(t>>=1,e=[...e.slice(0,t),8230,...e.slice(-t)]);let i=0,a=e.length;for(let t=0;t<a;t++){let a=e[t];fE(a)&&(r.push(fT(e.slice(i,t))),r.push(n(a)),i=t+1)}return r.push(fT(e.slice(i,a))),r.join(``)}function dE(e){return iE(),YT.has(e)}function fE(e){return iE(),ZT.has(e)}function pE(e){return _E(mE(e,zT,CE))}function mE(e,t,n){if(!e)return[];iE();let r=0;return e.split(VT).map(e=>{let i=dT(e),a={input:i,offset:r};r+=i.length+1;try{let e=a.tokens=SE(i,t,n),r=e.length,o;if(!r)throw Error(`empty label`);let s=a.output=e.flat();if(cE(s),!(a.emoji=r>1||e[0].is_emoji)&&s.every(e=>e<128))sE(s),o=`ASCII`;else{let t=e.flatMap(e=>e.is_emoji?[]:e);if(!t.length)o=`Emoji`;else{if(YT.has(s[0]))throw bE(`leading combining mark`);for(let t=1;t<r;t++){let n=e[t];if(!n.is_emoji&&YT.has(n[0]))throw bE(`emoji + combining mark: "${fT(e[t-1])} + ${uE([n[0]])}"`)}lE(s);let n=WT(new Set(t)),[i]=gE(n);xE(i,t),hE(i,n),o=i.N}}a.type=o}catch(e){a.error=e}return a})}function hE(e,t){let n,r=[];for(let e of t){let t=eE.get(e);if(t===UT)return;if(t){let r=t.M.get(e);if(n=n?n.filter(e=>r.has(e)):WT(r),!n.length)return}else r.push(e)}if(n){for(let t of n)if(r.every(e=>GT(t,e)))throw Error(`whole-script confusable: ${e.N}/${t.N}`)}}function gE(e){let t=QT;for(let n of e){let e=t.filter(e=>GT(e,n));if(!e.length)throw QT.some(e=>GT(e,n))?yE(t[0],n):vE(n);if(t=e,e.length==1)break}return t}function _E(e){return e.map(({input:t,error:n,output:r})=>{if(n){let r=n.message;throw Error(e.length==1?r:`Invalid label ${oE(uE(t,63))}: ${r}`)}return fT(r)}).join(VT)}function vE(e){return Error(`disallowed character: ${aE(e)}`)}function yE(e,t){let n=aE(t),r=QT.find(e=>e.P.has(t));return r&&(n=`${r.N} ${n}`),Error(`illegal mixture: ${e.N} + ${n}`)}function bE(e){return Error(`illegal placement: ${e}`)}function xE(e,t){for(let n of t)if(!GT(e,n))throw yE(e,n);if(e.M){let e=RT(t);for(let t=1,n=e.length;t<n;t++)if(XT.has(e[t])){let r=t+1;for(let i;r<n&&XT.has(i=e[r]);r++)for(let n=t;n<r;n++)if(e[n]==i)throw Error(`duplicate non-spacing marks: ${aE(i)}`);if(r-t>Jw)throw Error(`excessive non-spacing marks: ${oE(uE(e.slice(t-1,r)))} (${r-t}/${Jw})`);t=r}}}function SE(e,t,n){let r=[],i=[];for(e=e.slice().reverse();e.length;){let a=wE(e);if(a)i.length&&(r.push(t(i)),i=[]),r.push(n(a));else{let t=e.pop();if(tE.has(t))i.push(t);else{let e=qT.get(t);if(e)i.push(...e);else if(!JT.has(t))throw vE(t)}}}return i.length&&r.push(t(i)),r}function CE(e){return e.filter(e=>e!=HT)}function wE(e,t){let n=rE,r,i=e.length;for(;i&&(n=n.get(e[--i]),n);){let{V:a}=n;a&&(r=a,t&&t.push(...e.slice(i).reverse()),e.length=i)}return r}var TE=new Uint8Array(32);TE.fill(0);function EE(e){return q(e.length!==0,`invalid ENS name; empty component`,`comp`,e),e}function DE(e){let t=dy(OE(e)),n=[];if(e.length===0)return n;let r=0;for(let e=0;e<t.length;e++)t[e]===46&&(n.push(EE(t.slice(r,e))),r=e+1);return q(r<t.length,`invalid ENS name; empty component`,`name`,e),n.push(EE(t.slice(r))),n}function OE(e){try{if(e.length===0)throw Error(`empty label`);return pE(e)}catch(t){q(!1,`invalid ENS name (${t.message})`,`name`,e)}}function kE(e){q(typeof e==`string`,`invalid ENS name; not a string`,`name`,e),q(e.length,`invalid ENS name (empty label)`,`name`,e);let t=TE,n=DE(e);for(;n.length;)t=yx(Fv([t,yx(n.pop())]));return Y(t)}function AE(e,t){let n=t??63;return q(n<=255,`DNS encoded label cannot exceed 255`,`length`,n),Y(Fv(DE(e).map(t=>{q(t.length<=n,`label ${JSON.stringify(e)} exceeds ${n} bytes`,`name`,e);let r=new Uint8Array(t.length+1);return r.set(t,1),r[0]=r.length-1,r})))+`00`}var jE=new Uint8Array(32);jE.fill(0);var ME=BigInt(-1),NE=BigInt(0),PE=BigInt(1),FE=BigInt(`0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`);function IE(e){let t=J(e),n=t.length%32;return n?Fv([t,jE.slice(n)]):Y(t)}var LE=Zv(PE,32),RE=Zv(NE,32),zE={name:`string`,version:`string`,chainId:`uint256`,verifyingContract:`address`,salt:`bytes32`},BE=[`name`,`version`,`chainId`,`verifyingContract`,`salt`];function VE(e){return function(t){return q(typeof t==`string`,`invalid domain value for ${JSON.stringify(e)}`,`domain.${e}`,t),t}}var HE={name:VE(`name`),version:VE(`version`),chainId:function(e){let t=X(e,`domain.chainId`);return q(t>=0,`invalid chain ID`,`domain.chainId`,e),Number.isSafeInteger(t)?Number(t):$v(t)},verifyingContract:function(e){try{return IC(e).toLowerCase()}catch{}q(!1,`invalid domain value "verifyingContract"`,`domain.verifyingContract`,e)},salt:function(e){let t=J(e,`domain.salt`);return q(t.length===32,`invalid domain value "salt"`,`domain.salt`,e),Y(t)}};function UE(e){{let t=e.match(/^(u?)int(\d+)$/);if(t){let n=t[1]===``,r=parseInt(t[2]);q(r%8==0&&r!==0&&r<=256&&t[2]===String(r),`invalid numeric width`,`type`,e);let i=Kv(FE,n?r-1:r),a=n?(i+PE)*ME:NE;return function(t){let r=X(t,`value`);return q(r>=a&&r<=i,`value out-of-bounds for ${e}`,`value`,r),Zv(n?Gv(r,256):r,32)}}}{let t=e.match(/^bytes(\d+)$/);if(t){let n=parseInt(t[1]);return q(n!==0&&n<=32&&t[1]===String(n),`invalid bytes width`,`type`,e),function(t){return q(J(t).length===n,`invalid length for ${e}`,`value`,t),IE(t)}}}switch(e){case`address`:return function(e){return zv(IC(e),32)};case`bool`:return function(e){return e?LE:RE};case`bytes`:return function(e){return yx(e)};case`string`:return function(e){return Gw(e)}}return null}function WE(e,t){return`${e}(${t.map(({name:e,type:t})=>t+` `+e).join(`,`)})`}function GE(e){let t=e.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/);return t?{base:t[1],index:t[2]+t[4],array:{base:t[1],prefix:t[1]+t[2],count:t[5]?parseInt(t[5]):-1}}:{base:e}}var KE=class e{primaryType;#e;get types(){return JSON.parse(this.#e)}#t;#n;constructor(e){this.#t=new Map,this.#n=new Map;let t=new Map,n=new Map,r=new Map,i={};Object.keys(e).forEach(a=>{i[a]=e[a].map(({name:t,type:n})=>{let{base:r,index:i}=GE(n);return r===`int`&&!e.int&&(r=`int256`),r===`uint`&&!e.uint&&(r=`uint256`),{name:t,type:r+(i||``)}}),t.set(a,new Set),n.set(a,[]),r.set(a,new Set)}),this.#e=JSON.stringify(i);for(let r in i){let a=new Set;for(let o of i[r]){q(!a.has(o.name),`duplicate variable name ${JSON.stringify(o.name)} in ${JSON.stringify(r)}`,`types`,e),a.add(o.name);let i=GE(o.type).base;q(i!==r,`circular type reference to ${JSON.stringify(i)}`,`types`,e),!UE(i)&&(q(n.has(i),`unknown type ${JSON.stringify(i)}`,`types`,e),n.get(i).push(r),t.get(r).add(i))}}let a=Array.from(n.keys()).filter(e=>n.get(e).length===0);q(a.length!==0,`missing primary type`,`types`,e),q(a.length===1,`ambiguous primary types or unused types: ${a.map(e=>JSON.stringify(e)).join(`, `)}`,`types`,e),G(this,{primaryType:a[0]});function o(i,a){q(!a.has(i),`circular type reference to ${JSON.stringify(i)}`,`types`,e),a.add(i);for(let e of t.get(i))if(n.has(e)){o(e,a);for(let t of a)r.get(t).add(e)}a.delete(i)}o(this.primaryType,new Set);for(let[e,t]of r){let n=Array.from(t);n.sort(),this.#t.set(e,WE(e,i[e])+n.map(e=>WE(e,i[e])).join(``))}}getEncoder(e){let t=this.#n.get(e);return t||(t=this.#r(e),this.#n.set(e,t)),t}#r(e){{let t=UE(e);if(t)return t}let t=GE(e).array;if(t){let e=t.prefix,n=this.getEncoder(e);return r=>{q(t.count===-1||t.count===r.length,`array length mismatch; expected length ${t.count}`,`value`,r);let i=r.map(n);return this.#t.has(e)&&(i=i.map(yx)),yx(Fv(i))}}let n=this.types[e];if(n){let t=Gw(this.#t.get(e));return e=>{let r=n.map(({name:t,type:n})=>{let r=this.getEncoder(n)(e[t]);return this.#t.has(n)?yx(r):r});return r.unshift(t),Fv(r)}}q(!1,`unknown type: ${e}`,`type`,e)}encodeType(e){let t=this.#t.get(e);return q(t,`unknown type: ${JSON.stringify(e)}`,`name`,e),t}encodeData(e,t){return this.getEncoder(e)(t)}hashStruct(e,t){return yx(this.encodeData(e,t))}encode(e){return this.encodeData(this.primaryType,e)}hash(e){return this.hashStruct(this.primaryType,e)}_visit(e,t,n){if(UE(e))return n(e,t);let r=GE(e).array;if(r)return q(r.count===-1||r.count===t.length,`array length mismatch; expected length ${r.count}`,`value`,t),t.map(e=>this._visit(r.prefix,e,n));let i=this.types[e];if(i)return i.reduce((e,{name:r,type:i})=>(e[r]=this._visit(i,t[r],n),e),{});q(!1,`unknown type: ${e}`,`type`,e)}visit(e,t){return this._visit(this.primaryType,e,t)}static from(t){return new e(t)}static getPrimaryType(t){return e.from(t).primaryType}static hashStruct(t,n,r){return e.from(n).hashStruct(t,r)}static hashDomain(t){let n=[];for(let e in t){if(t[e]==null)continue;let r=zE[e];q(r,`invalid typed-data domain key: ${JSON.stringify(e)}`,`domain`,t),n.push({name:e,type:r})}return n.sort((e,t)=>BE.indexOf(e.name)-BE.indexOf(t.name)),e.hashStruct(`EIP712Domain`,{EIP712Domain:n},t)}static encode(t,n,r){return Fv([`0x1901`,e.hashDomain(t),e.from(n).hash(r)])}static hash(t,n,r){return yx(e.encode(t,n,r))}static async resolveNames(t,n,r,i){t=Object.assign({},t);for(let e in t)t[e]??delete t[e];let a={};t.verifyingContract&&!Mv(t.verifyingContract,20)&&(a[t.verifyingContract]=`0x`);let o=e.from(n);o.visit(r,(e,t)=>(e===`address`&&!Mv(t,20)&&(a[t]=`0x`),t));for(let e in a)a[e]=await i(e);return t.verifyingContract&&a[t.verifyingContract]&&(t.verifyingContract=a[t.verifyingContract]),r=o.visit(r,(e,t)=>e===`address`&&a[t]?a[t]:t),{domain:t,value:r}}static getPayload(t,n,r){e.hashDomain(t);let i={},a=[];BE.forEach(e=>{let n=t[e];n!=null&&(i[e]=HE[e](n),a.push({name:e,type:zE[e]}))});let o=e.from(n);n=o.types;let s=Object.assign({},n);return q(s.EIP712Domain==null,`types must not contain EIP712Domain type`,`types.EIP712Domain`,n),s.EIP712Domain=a,o.encode(r),{types:s,domain:i,primaryType:o.primaryType,message:o.visit(r,(e,t)=>{if(e.match(/^bytes(\d*)/))return Y(J(t));if(e.match(/^u?int/))return X(t).toString();switch(e){case`address`:return t.toLowerCase();case`bool`:return!!t;case`string`:return q(typeof t==`string`,`invalid string`,`value`,t),t}q(!1,`unsupported type`,`type`,e)})}}};function qE(e){let t=new Set;return e.forEach(e=>t.add(e)),Object.freeze(t)}var JE=qE(`external public payable override`.split(` `)),YE=`constant external internal payable private public pure view override`,XE=qE(YE.split(` `)),ZE=`constructor error event fallback function receive struct`,QE=qE(ZE.split(` `)),$E=`calldata memory storage payable indexed`,eD=qE($E.split(` `)),tD=qE([ZE,$E,`tuple returns`,YE].join(` `).split(` `)),nD={"(":`OPEN_PAREN`,")":`CLOSE_PAREN`,"[":`OPEN_BRACKET`,"]":`CLOSE_BRACKET`,",":`COMMA`,"@":`AT`},rD=RegExp(`^(\\s*)`),iD=RegExp(`^([0-9]+)`),aD=RegExp(`^([a-zA-Z$_][a-zA-Z0-9$_]*)`),oD=RegExp(`^([a-zA-Z$_][a-zA-Z0-9$_]*)$`),sD=RegExp(`^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$`),cD=class e{#e;#t;get offset(){return this.#e}get length(){return this.#t.length-this.#e}constructor(e){this.#e=0,this.#t=e.slice()}clone(){return new e(this.#t)}reset(){this.#e=0}#n(t=0,n=0){return new e(this.#t.slice(t,n).map(e=>Object.freeze(Object.assign({},e,{match:e.match-t,linkBack:e.linkBack-t,linkNext:e.linkNext-t}))))}popKeyword(e){let t=this.peek();if(t.type!==`KEYWORD`||!e.has(t.text))throw Error(`expected keyword ${t.text}`);return this.pop().text}popType(e){if(this.peek().type!==e){let t=this.peek();throw Error(`expected ${e}; got ${t.type} ${JSON.stringify(t.text)}`)}return this.pop().text}popParen(){let e=this.peek();if(e.type!==`OPEN_PAREN`)throw Error(`bad start`);let t=this.#n(this.#e+1,e.match+1);return this.#e=e.match+1,t}popParams(){let e=this.peek();if(e.type!==`OPEN_PAREN`)throw Error(`bad start`);let t=[];for(;this.#e<e.match-1;){let e=this.peek().linkNext;t.push(this.#n(this.#e+1,e)),this.#e=e}return this.#e=e.match+1,t}peek(){if(this.#e>=this.#t.length)throw Error(`out-of-bounds`);return this.#t[this.#e]}peekKeyword(e){let t=this.peekType(`KEYWORD`);return t!=null&&e.has(t)?t:null}peekType(e){if(this.length===0)return null;let t=this.peek();return t.type===e?t.text:null}pop(){let e=this.peek();return this.#e++,e}toString(){let e=[];for(let t=this.#e;t<this.#t.length;t++){let n=this.#t[t];e.push(`${n.type}:${n.text}`)}return`<TokenString ${e.join(` `)}>`}};function lD(e){let t=[],n=t=>{let n=a<e.length?JSON.stringify(e[a]):`$EOI`;throw Error(`invalid token ${n} at ${a}: ${t}`)},r=[],i=[],a=0;for(;a<e.length;){let o=e.substring(a),s=o.match(rD);s&&(a+=s[1].length,o=e.substring(a));let c={depth:r.length,linkBack:-1,linkNext:-1,match:-1,type:``,text:``,offset:a,value:-1};t.push(c);let l=nD[o[0]]||``;if(l){if(c.type=l,c.text=o[0],a++,l===`OPEN_PAREN`)r.push(t.length-1),i.push(t.length-1);else if(l==`CLOSE_PAREN`)r.length===0&&n(`no matching open bracket`),c.match=r.pop(),t[c.match].match=t.length-1,c.depth--,c.linkBack=i.pop(),t[c.linkBack].linkNext=t.length-1;else if(l===`COMMA`)c.linkBack=i.pop(),t[c.linkBack].linkNext=t.length-1,i.push(t.length-1);else if(l===`OPEN_BRACKET`)c.type=`BRACKET`;else if(l===`CLOSE_BRACKET`){let e=t.pop().text;if(t.length>0&&t[t.length-1].type===`NUMBER`){let n=t.pop().text;e=n+e,t[t.length-1].value=Z(n)}if(t.length===0||t[t.length-1].type!==`BRACKET`)throw Error(`missing opening bracket`);t[t.length-1].text+=e}continue}if(s=o.match(aD),s){if(c.text=s[1],a+=c.text.length,tD.has(c.text)){c.type=`KEYWORD`;continue}if(c.text.match(sD)){c.type=`TYPE`;continue}c.type=`ID`;continue}if(s=o.match(iD),s){c.text=s[1],c.type=`NUMBER`,a+=c.text.length;continue}throw Error(`unexpected token ${JSON.stringify(o[0])} at position ${a}`)}return new cD(t.map(e=>Object.freeze(e)))}function uD(e,t){let n=[];for(let r in t.keys())e.has(r)&&n.push(r);if(n.length>1)throw Error(`conflicting types: ${n.join(`, `)}`)}function dD(e,t){if(t.peekKeyword(QE)){let n=t.pop().text;if(n!==e)throw Error(`expected ${e}, got ${n}`)}return t.popType(`ID`)}function fD(e,t){let n=new Set;for(;;){let r=e.peekType(`KEYWORD`);if(r==null||t&&!t.has(r))break;if(e.pop(),n.has(r))throw Error(`duplicate keywords: ${JSON.stringify(r)}`);n.add(r)}return Object.freeze(n)}function pD(e){let t=fD(e,XE);return uD(t,qE(`constant payable nonpayable`.split(` `))),uD(t,qE(`pure view payable nonpayable`.split(` `))),t.has(`view`)?`view`:t.has(`pure`)?`pure`:t.has(`payable`)?`payable`:t.has(`nonpayable`)?`nonpayable`:t.has(`constant`)?`view`:`nonpayable`}function mD(e,t){return e.popParams().map(e=>OD.from(e,t))}function hD(e){if(e.peekType(`AT`)){if(e.pop(),e.peekType(`NUMBER`))return X(e.pop().text);throw Error(`invalid gas`)}return null}function gD(e){if(e.length)throw Error(`unexpected tokens at offset ${e.offset}: ${e.toString()}`)}var _D=new RegExp(/^(.*)\[([0-9]*)\]$/);function vD(e){let t=e.match(sD);if(q(t,`invalid type`,`type`,e),e===`uint`)return`uint256`;if(e===`int`)return`int256`;if(t[2]){let n=parseInt(t[2]);q(n!==0&&n<=32,`invalid bytes length`,`type`,e)}else if(t[3]){let n=parseInt(t[3]);q(n!==0&&n<=256&&n%8==0,`invalid numeric width`,`type`,e)}return e}var yD={},bD=Symbol.for(`_ethers_internal`),xD=`_ParamTypeInternal`,SD=`_ErrorInternal`,CD=`_EventInternal`,wD=`_ConstructorInternal`,TD=`_FallbackInternal`,ED=`_FunctionInternal`,DD=`_StructInternal`,OD=class e{name;type;baseType;indexed;components;arrayLength;arrayChildren;constructor(e,t,n,r,i,a,o,s){if(kv(e,yD,`ParamType`),Object.defineProperty(this,bD,{value:xD}),a&&=Object.freeze(a.slice()),r===`array`){if(o==null||s==null)throw Error(``)}else if(o!=null||s!=null)throw Error(``);if(r===`tuple`){if(a==null)throw Error(``)}else if(a!=null)throw Error(``);G(this,{name:t,type:n,baseType:r,indexed:i,components:a,arrayLength:o,arrayChildren:s})}format(e){if(e??=`sighash`,e===`json`){let t=this.name||``;if(this.isArray()){let e=JSON.parse(this.arrayChildren.format(`json`));return e.name=t,e.type+=`[${this.arrayLength<0?``:String(this.arrayLength)}]`,JSON.stringify(e)}let n={type:this.baseType===`tuple`?`tuple`:this.type,name:t};return typeof this.indexed==`boolean`&&(n.indexed=this.indexed),this.isTuple()&&(n.components=this.components.map(t=>JSON.parse(t.format(e)))),JSON.stringify(n)}let t=``;return this.isArray()?(t+=this.arrayChildren.format(e),t+=`[${this.arrayLength<0?``:String(this.arrayLength)}]`):this.isTuple()?t+=`(`+this.components.map(t=>t.format(e)).join(e===`full`?`, `:`,`)+`)`:t+=this.type,e!==`sighash`&&(this.indexed===!0&&(t+=` indexed`),e===`full`&&this.name&&(t+=` `+this.name)),t}isArray(){return this.baseType===`array`}isTuple(){return this.baseType===`tuple`}isIndexable(){return this.indexed!=null}walk(e,t){if(this.isArray()){if(!Array.isArray(e))throw Error(`invalid array value`);if(this.arrayLength!==-1&&e.length!==this.arrayLength)throw Error(`array is wrong length`);let n=this;return e.map(e=>n.arrayChildren.walk(e,t))}if(this.isTuple()){if(!Array.isArray(e))throw Error(`invalid tuple value`);if(e.length!==this.components.length)throw Error(`array is wrong length`);let n=this;return e.map((e,r)=>n.components[r].walk(e,t))}return t(this.type,e)}#e(e,t,n,r){if(this.isArray()){if(!Array.isArray(t))throw Error(`invalid array value`);if(this.arrayLength!==-1&&t.length!==this.arrayLength)throw Error(`array is wrong length`);let i=this.arrayChildren,a=t.slice();a.forEach((t,r)=>{i.#e(e,t,n,e=>{a[r]=e})}),r(a);return}if(this.isTuple()){let i=this.components,a;if(Array.isArray(t))a=t.slice();else{if(typeof t!=`object`||!t)throw Error(`invalid tuple value`);a=i.map(e=>{if(!e.name)throw Error(`cannot use object value with unnamed components`);if(!(e.name in t))throw Error(`missing value for component ${e.name}`);return t[e.name]})}if(a.length!==this.components.length)throw Error(`array is wrong length`);a.forEach((t,r)=>{i[r].#e(e,t,n,e=>{a[r]=e})}),r(a);return}let i=n(this.type,t);i.then?e.push((async function(){r(await i)})()):r(i)}async walkAsync(e,t){let n=[],r=[e];return this.#e(n,e,t,e=>{r[0]=e}),n.length&&await Promise.all(n),r[0]}static from(t,n){if(e.isParamType(t))return t;if(typeof t==`string`)try{return e.from(lD(t),n)}catch{q(!1,`invalid param type`,`obj`,t)}else if(t instanceof cD){let r=``,i=``,a=null;fD(t,qE([`tuple`])).has(`tuple`)||t.peekType(`OPEN_PAREN`)?(i=`tuple`,a=t.popParams().map(t=>e.from(t)),r=`tuple(${a.map(e=>e.format()).join(`,`)})`):(r=vD(t.popType(`TYPE`)),i=r);let o=null,s=null;for(;t.length&&t.peekType(`BRACKET`);){let n=t.pop();o=new e(yD,``,r,i,null,a,s,o),s=n.value,r+=n.text,i=`array`,a=null}let c=null;if(fD(t,eD).has(`indexed`)){if(!n)throw Error(``);c=!0}let l=t.peekType(`ID`)?t.pop().text:``;if(t.length)throw Error(`leftover tokens`);return new e(yD,l,r,i,c,a,s,o)}let r=t.name;q(!r||typeof r==`string`&&r.match(oD),`invalid name`,`obj.name`,r);let i=t.indexed;i!=null&&(q(n,`parameter cannot be indexed`,`obj.indexed`,t.indexed),i=!!i);let a=t.type,o=a.match(_D);if(o){let n=parseInt(o[2]||`-1`),s=e.from({type:o[1],components:t.components});return new e(yD,r||``,a,`array`,i,null,n,s)}if(a===`tuple`||a.startsWith(`tuple(`)||a.startsWith(`(`)){let n=t.components==null?null:t.components.map(t=>e.from(t));return new e(yD,r||``,a,`tuple`,i,n,null,null)}return a=vD(t.type),new e(yD,r||``,a,a,i,null,null,null)}static isParamType(e){return e&&e[bD]===xD}},kD=class e{type;inputs;constructor(e,t,n){kv(e,yD,`Fragment`),n=Object.freeze(n.slice()),G(this,{type:t,inputs:n})}static from(t){if(typeof t==`string`){try{e.from(JSON.parse(t))}catch{}return e.from(lD(t))}if(t instanceof cD)switch(t.peekKeyword(QE)){case`constructor`:return PD.from(t);case`error`:return MD.from(t);case`event`:return ND.from(t);case`fallback`:case`receive`:return FD.from(t);case`function`:return ID.from(t);case`struct`:return LD.from(t)}else if(typeof t==`object`){switch(t.type){case`constructor`:return PD.from(t);case`error`:return MD.from(t);case`event`:return ND.from(t);case`fallback`:case`receive`:return FD.from(t);case`function`:return ID.from(t);case`struct`:return LD.from(t)}K(!1,`unsupported type: ${t.type}`,`UNSUPPORTED_OPERATION`,{operation:`Fragment.from`})}q(!1,`unsupported frgament object`,`obj`,t)}static isConstructor(e){return PD.isFragment(e)}static isError(e){return MD.isFragment(e)}static isEvent(e){return ND.isFragment(e)}static isFunction(e){return ID.isFragment(e)}static isStruct(e){return LD.isFragment(e)}},AD=class extends kD{name;constructor(e,t,n,r){super(e,t,r),q(typeof n==`string`&&n.match(oD),`invalid identifier`,`name`,n),r=Object.freeze(r.slice()),G(this,{name:n})}};function jD(e,t){return`(`+t.map(t=>t.format(e)).join(e===`full`?`, `:`,`)+`)`}var MD=class e extends AD{constructor(e,t,n){super(e,`error`,t,n),Object.defineProperty(this,bD,{value:SD})}get selector(){return Gw(this.format(`sighash`)).substring(0,10)}format(e){if(e??=`sighash`,e===`json`)return JSON.stringify({type:`error`,name:this.name,inputs:this.inputs.map(t=>JSON.parse(t.format(e)))});let t=[];return e!==`sighash`&&t.push(`error`),t.push(this.name+jD(e,this.inputs)),t.join(` `)}static from(t){if(e.isFragment(t))return t;if(typeof t==`string`)return e.from(lD(t));if(t instanceof cD){let n=dD(`error`,t),r=mD(t);return gD(t),new e(yD,n,r)}return new e(yD,t.name,t.inputs?t.inputs.map(OD.from):[])}static isFragment(e){return e&&e[bD]===SD}},ND=class e extends AD{anonymous;constructor(e,t,n,r){super(e,`event`,t,n),Object.defineProperty(this,bD,{value:CD}),G(this,{anonymous:r})}get topicHash(){return Gw(this.format(`sighash`))}format(e){if(e??=`sighash`,e===`json`)return JSON.stringify({type:`event`,anonymous:this.anonymous,name:this.name,inputs:this.inputs.map(t=>JSON.parse(t.format(e)))});let t=[];return e!==`sighash`&&t.push(`event`),t.push(this.name+jD(e,this.inputs)),e!==`sighash`&&this.anonymous&&t.push(`anonymous`),t.join(` `)}static getTopicHash(t,n){return n=(n||[]).map(e=>OD.from(e)),new e(yD,t,n,!1).topicHash}static from(t){if(e.isFragment(t))return t;if(typeof t==`string`)try{return e.from(lD(t))}catch{q(!1,`invalid event fragment`,`obj`,t)}else if(t instanceof cD){let n=dD(`event`,t),r=mD(t,!0),i=!!fD(t,qE([`anonymous`])).has(`anonymous`);return gD(t),new e(yD,n,r,i)}return new e(yD,t.name,t.inputs?t.inputs.map(e=>OD.from(e,!0)):[],!!t.anonymous)}static isFragment(e){return e&&e[bD]===CD}},PD=class e extends kD{payable;gas;constructor(e,t,n,r,i){super(e,t,n),Object.defineProperty(this,bD,{value:wD}),G(this,{payable:r,gas:i})}format(e){if(K(e!=null&&e!==`sighash`,`cannot format a constructor for sighash`,`UNSUPPORTED_OPERATION`,{operation:`format(sighash)`}),e===`json`)return JSON.stringify({type:`constructor`,stateMutability:this.payable?`payable`:`undefined`,payable:this.payable,gas:this.gas==null?void 0:this.gas,inputs:this.inputs.map(t=>JSON.parse(t.format(e)))});let t=[`constructor${jD(e,this.inputs)}`];return this.payable&&t.push(`payable`),this.gas!=null&&t.push(`@${this.gas.toString()}`),t.join(` `)}static from(t){if(e.isFragment(t))return t;if(typeof t==`string`)try{return e.from(lD(t))}catch{q(!1,`invalid constuctor fragment`,`obj`,t)}else if(t instanceof cD){fD(t,qE([`constructor`]));let n=mD(t),r=!!fD(t,JE).has(`payable`),i=hD(t);return gD(t),new e(yD,`constructor`,n,r,i)}return new e(yD,`constructor`,t.inputs?t.inputs.map(OD.from):[],!!t.payable,t.gas==null?null:t.gas)}static isFragment(e){return e&&e[bD]===wD}},FD=class e extends kD{payable;constructor(e,t,n){super(e,`fallback`,t),Object.defineProperty(this,bD,{value:TD}),G(this,{payable:n})}format(e){let t=this.inputs.length===0?`receive`:`fallback`;if(e===`json`){let e=this.payable?`payable`:`nonpayable`;return JSON.stringify({type:t,stateMutability:e})}return`${t}()${this.payable?` payable`:``}`}static from(t){if(e.isFragment(t))return t;if(typeof t==`string`)try{return e.from(lD(t))}catch{q(!1,`invalid fallback fragment`,`obj`,t)}else if(t instanceof cD){let n=t.toString();if(q(t.peekKeyword(qE([`fallback`,`receive`])),`type must be fallback or receive`,`obj`,n),t.popKeyword(qE([`fallback`,`receive`]))===`receive`){let n=mD(t);return q(n.length===0,`receive cannot have arguments`,`obj.inputs`,n),fD(t,qE([`payable`])),gD(t),new e(yD,[],!0)}let r=mD(t);r.length?q(r.length===1&&r[0].type===`bytes`,`invalid fallback inputs`,`obj.inputs`,r.map(e=>e.format(`minimal`)).join(`, `)):r=[OD.from(`bytes`)];let i=pD(t);if(q(i===`nonpayable`||i===`payable`,`fallback cannot be constants`,`obj.stateMutability`,i),fD(t,qE([`returns`])).has(`returns`)){let e=mD(t);q(e.length===1&&e[0].type===`bytes`,`invalid fallback outputs`,`obj.outputs`,e.map(e=>e.format(`minimal`)).join(`, `))}return gD(t),new e(yD,r,i===`payable`)}if(t.type===`receive`)return new e(yD,[],!0);if(t.type===`fallback`)return new e(yD,[OD.from(`bytes`)],t.stateMutability===`payable`);q(!1,`invalid fallback description`,`obj`,t)}static isFragment(e){return e&&e[bD]===TD}},ID=class e extends AD{constant;outputs;stateMutability;payable;gas;constructor(e,t,n,r,i,a){super(e,`function`,t,r),Object.defineProperty(this,bD,{value:ED}),i=Object.freeze(i.slice()),G(this,{constant:n===`view`||n===`pure`,gas:a,outputs:i,payable:n===`payable`,stateMutability:n})}get selector(){return Gw(this.format(`sighash`)).substring(0,10)}format(e){if(e??=`sighash`,e===`json`)return JSON.stringify({type:`function`,name:this.name,constant:this.constant,stateMutability:this.stateMutability===`nonpayable`?void 0:this.stateMutability,payable:this.payable,gas:this.gas==null?void 0:this.gas,inputs:this.inputs.map(t=>JSON.parse(t.format(e))),outputs:this.outputs.map(t=>JSON.parse(t.format(e)))});let t=[];return e!==`sighash`&&t.push(`function`),t.push(this.name+jD(e,this.inputs)),e!==`sighash`&&(this.stateMutability!==`nonpayable`&&t.push(this.stateMutability),this.outputs&&this.outputs.length&&(t.push(`returns`),t.push(jD(e,this.outputs))),this.gas!=null&&t.push(`@${this.gas.toString()}`)),t.join(` `)}static getSelector(t,n){return n=(n||[]).map(e=>OD.from(e)),new e(yD,t,`view`,n,[],null).selector}static from(t){if(e.isFragment(t))return t;if(typeof t==`string`)try{return e.from(lD(t))}catch{q(!1,`invalid function fragment`,`obj`,t)}else if(t instanceof cD){let n=dD(`function`,t),r=mD(t),i=pD(t),a=[];fD(t,qE([`returns`])).has(`returns`)&&(a=mD(t));let o=hD(t);return gD(t),new e(yD,n,i,r,a,o)}let n=t.stateMutability;return n??(n=`payable`,typeof t.constant==`boolean`?(n=`view`,t.constant||(n=`payable`,typeof t.payable==`boolean`&&!t.payable&&(n=`nonpayable`))):typeof t.payable==`boolean`&&!t.payable&&(n=`nonpayable`)),new e(yD,t.name,n,t.inputs?t.inputs.map(OD.from):[],t.outputs?t.outputs.map(OD.from):[],t.gas==null?null:t.gas)}static isFragment(e){return e&&e[bD]===ED}},LD=class e extends AD{constructor(e,t,n){super(e,`struct`,t,n),Object.defineProperty(this,bD,{value:DD})}format(){throw Error(`@TODO`)}static from(t){if(typeof t==`string`)try{return e.from(lD(t))}catch{q(!1,`invalid struct fragment`,`obj`,t)}else if(t instanceof cD){let n=dD(`struct`,t),r=mD(t);return gD(t),new e(yD,n,r)}return new e(yD,t.name,t.inputs?t.inputs.map(OD.from):[])}static isFragment(e){return e&&e[bD]===DD}},RD=new Map;RD.set(0,`GENERIC_PANIC`),RD.set(1,`ASSERT_FALSE`),RD.set(17,`OVERFLOW`),RD.set(18,`DIVIDE_BY_ZERO`),RD.set(33,`ENUM_RANGE_ERROR`),RD.set(34,`BAD_STORAGE_DATA`),RD.set(49,`STACK_UNDERFLOW`),RD.set(50,`ARRAY_RANGE_ERROR`),RD.set(65,`OUT_OF_MEMORY`),RD.set(81,`UNINITIALIZED_FUNCTION_CALL`);var zD=new RegExp(/^bytes([0-9]*)$/),BD=new RegExp(/^(u?int)([0-9]*)$/),VD=null,HD=1024;function UD(e,t,n,r){let i=`missing revert data`,a=null,o=null;if(n){i=`execution reverted`;let e=J(n);if(n=Y(n),e.length===0)i+=` (no data present; likely require(false) occurred`,a=`require(false)`;else if(e.length%32!=4)i+=` (could not decode reason; invalid data length)`;else if(Y(e.slice(0,4))===`0x08c379a0`)try{a=r.decode([`string`],e.slice(4))[0],o={signature:`Error(string)`,name:`Error`,args:[a]},i+=`: ${JSON.stringify(a)}`}catch{i+=` (could not decode reason; invalid string data)`}else if(Y(e.slice(0,4))===`0x4e487b71`)try{let t=Number(r.decode([`uint256`],e.slice(4))[0]);o={signature:`Panic(uint256)`,name:`Panic`,args:[t]},a=`Panic due to ${RD.get(t)||`UNKNOWN`}(${t})`,i+=`: ${a}`}catch{i+=` (could not decode panic code)`}else i+=` (unknown custom error)`}let s={to:t.to?IC(t.to):null,data:t.data||`0x`};return t.from&&(s.from=IC(t.from)),Tv(i,`CALL_EXCEPTION`,{action:e,data:n,reason:a,transaction:s,invocation:null,revert:o})}var WD=class e{#e(e){if(e.isArray())return new YC(this.#e(e.arrayChildren),e.arrayLength,e.name);if(e.isTuple())return new sw(e.components.map(e=>this.#e(e)),e.name);switch(e.baseType){case`address`:return new GC(e.name);case`bool`:return new XC(e.name);case`string`:return new ow(e.name);case`bytes`:return new QC(e.name);case``:return new tw(e.name)}let t=e.type.match(BD);if(t){let n=parseInt(t[2]||`256`);return q(n!==0&&n<=256&&n%8==0,`invalid `+t[1]+` bit length`,`param`,e),new aw(n/8,t[1]===`int`,e.name)}if(t=e.type.match(zD),t){let n=parseInt(t[1]);return q(n!==0&&n<=32,`invalid bytes length`,`param`,e),new $C(n,e.name)}q(!1,`invalid type`,`type`,e.type)}getDefaultValue(e){return new sw(e.map(e=>this.#e(OD.from(e))),`_`).defaultValue()}encode(e,t){Ev(t.length,e.length,`types/values length mismatch`);let n=new sw(e.map(e=>this.#e(OD.from(e))),`_`),r=new Qy;return n.encode(r,t),r.data}decode(e,t,n){return new sw(e.map(e=>this.#e(OD.from(e))),`_`).decode(new $y(t,n,HD))}static _setDefaultMaxInflation(e){q(typeof e==`number`&&Number.isInteger(e),`invalid defaultMaxInflation factor`,`value`,e),HD=e}static defaultAbiCoder(){return VD??=new e,VD}static getBuiltinCallException(t,n,r){return UD(t,n,r,e.defaultAbiCoder())}},GD=class{fragment;name;signature;topic;args;constructor(e,t,n){let r=e.name,i=e.format();G(this,{fragment:e,name:r,signature:i,topic:t,args:n})}},KD=class{fragment;name;args;signature;selector;value;constructor(e,t,n,r){let i=e.name,a=e.format();G(this,{fragment:e,name:i,args:n,signature:a,selector:t,value:r})}},qD=class{fragment;name;args;signature;selector;constructor(e,t,n){let r=e.name,i=e.format();G(this,{fragment:e,name:r,args:n,signature:i,selector:t})}},JD=class{hash;_isIndexed;static isIndexed(e){return!!(e&&e._isIndexed)}constructor(e){G(this,{hash:e,_isIndexed:!0})}},YD={0:`generic panic`,1:`assert(false)`,17:`arithmetic overflow`,18:`division or modulo by zero`,33:`enum overflow`,34:`invalid encoded storage byte array accessed`,49:`out-of-bounds array access; popping on an empty array`,50:`out-of-bounds access of an array or bytesN`,65:`out of memory`,81:`uninitialized function`},XD={"0x08c379a0":{signature:`Error(string)`,name:`Error`,inputs:[`string`],reason:e=>`reverted with reason string ${JSON.stringify(e)}`},"0x4e487b71":{signature:`Panic(uint256)`,name:`Panic`,inputs:[`uint256`],reason:e=>{let t=`unknown panic code`;return e>=0&&e<=255&&YD[e.toString()]&&(t=YD[e.toString()]),`reverted with panic code 0x${e.toString(16)} (${t})`}}},ZD=class e{fragments;deploy;fallback;receive;#e;#t;#n;#r;constructor(e){let t=[];t=typeof e==`string`?JSON.parse(e):e,this.#n=new Map,this.#e=new Map,this.#t=new Map;let n=[];for(let e of t)try{n.push(kD.from(e))}catch(t){console.log(`[Warning] Invalid Fragment ${JSON.stringify(e)}:`,t.message)}G(this,{fragments:Object.freeze(n)});let r=null,i=!1;this.#r=this.getAbiCoder(),this.fragments.forEach((e,t)=>{let n;switch(e.type){case`constructor`:if(this.deploy){console.log(`duplicate definition - constructor`);return}G(this,{deploy:e});return;case`fallback`:e.inputs.length===0?i=!0:(q(!r||e.payable!==r.payable,`conflicting fallback fragments`,`fragments[${t}]`,e),r=e,i=r.payable);return;case`function`:n=this.#n;break;case`event`:n=this.#t;break;case`error`:n=this.#e;break;default:return}let a=e.format();n.has(a)||n.set(a,e)}),this.deploy||G(this,{deploy:PD.from(`constructor()`)}),G(this,{fallback:r,receive:i})}format(e){let t=e?`minimal`:`full`;return this.fragments.map(e=>e.format(t))}formatJson(){let e=this.fragments.map(e=>e.format(`json`));return JSON.stringify(e.map(e=>JSON.parse(e)))}getAbiCoder(){return WD.defaultAbiCoder()}#i(e,t,n){if(Mv(e)){let t=e.toLowerCase();for(let e of this.#n.values())if(t===e.selector)return e;return null}if(e.indexOf(`(`)===-1){let r=[];for(let[t,n]of this.#n)t.split(`(`)[0]===e&&r.push(n);if(t){let e=t.length>0?t[t.length-1]:null,n=t.length,i=!0;WC.isTyped(e)&&e.type===`overrides`&&(i=!1,n--);for(let e=r.length-1;e>=0;e--){let t=r[e].inputs.length;t!==n&&(!i||t!==n-1)&&r.splice(e,1)}for(let e=r.length-1;e>=0;e--){let n=r[e].inputs;for(let i=0;i<t.length;i++)if(WC.isTyped(t[i])){if(i>=n.length){if(t[i].type===`overrides`)continue;r.splice(e,1);break}if(t[i].type!==n[i].baseType){r.splice(e,1);break}}}}if(r.length===1&&t&&t.length!==r[0].inputs.length){let e=t[t.length-1];(e==null||Array.isArray(e)||typeof e!=`object`)&&r.splice(0,1)}return r.length===0?null:(r.length>1&&n&&q(!1,`ambiguous function description (i.e. matches ${r.map(e=>JSON.stringify(e.format())).join(`, `)})`,`key`,e),r[0])}return this.#n.get(ID.from(e).format())||null}getFunctionName(e){let t=this.#i(e,null,!1);return q(t,`no matching function`,`key`,e),t.name}hasFunction(e){return!!this.#i(e,null,!1)}getFunction(e,t){return this.#i(e,t||null,!0)}forEachFunction(e){let t=Array.from(this.#n.keys());t.sort((e,t)=>e.localeCompare(t));for(let n=0;n<t.length;n++){let r=t[n];e(this.#n.get(r),n)}}#a(e,t,n){if(Mv(e)){let t=e.toLowerCase();for(let e of this.#t.values())if(t===e.topicHash)return e;return null}if(e.indexOf(`(`)===-1){let r=[];for(let[t,n]of this.#t)t.split(`(`)[0]===e&&r.push(n);if(t){for(let e=r.length-1;e>=0;e--)r[e].inputs.length<t.length&&r.splice(e,1);for(let e=r.length-1;e>=0;e--){let n=r[e].inputs;for(let i=0;i<t.length;i++)if(WC.isTyped(t[i])&&t[i].type!==n[i].baseType){r.splice(e,1);break}}}return r.length===0?null:(r.length>1&&n&&q(!1,`ambiguous event description (i.e. matches ${r.map(e=>JSON.stringify(e.format())).join(`, `)})`,`key`,e),r[0])}return this.#t.get(ND.from(e).format())||null}getEventName(e){let t=this.#a(e,null,!1);return q(t,`no matching event`,`key`,e),t.name}hasEvent(e){return!!this.#a(e,null,!1)}getEvent(e,t){return this.#a(e,t||null,!0)}forEachEvent(e){let t=Array.from(this.#t.keys());t.sort((e,t)=>e.localeCompare(t));for(let n=0;n<t.length;n++){let r=t[n];e(this.#t.get(r),n)}}getError(e,t){if(Mv(e)){let t=e.toLowerCase();if(XD[t])return MD.from(XD[t].signature);for(let e of this.#e.values())if(t===e.selector)return e;return null}if(e.indexOf(`(`)===-1){let t=[];for(let[n,r]of this.#e)n.split(`(`)[0]===e&&t.push(r);return t.length===0?e===`Error`?MD.from(`error Error(string)`):e===`Panic`?MD.from(`error Panic(uint256)`):null:(t.length>1&&q(!1,`ambiguous error description (i.e. ${t.map(e=>JSON.stringify(e.format())).join(`, `)})`,`name`,e),t[0])}return e=MD.from(e).format(),e===`Error(string)`?MD.from(`error Error(string)`):e===`Panic(uint256)`?MD.from(`error Panic(uint256)`):this.#e.get(e)||null}forEachError(e){let t=Array.from(this.#e.keys());t.sort((e,t)=>e.localeCompare(t));for(let n=0;n<t.length;n++){let r=t[n];e(this.#e.get(r),n)}}_decodeParams(e,t){return this.#r.decode(e,t)}_encodeParams(e,t){return this.#r.encode(e,t)}encodeDeploy(e){return this._encodeParams(this.deploy.inputs,e||[])}decodeErrorResult(e,t){if(typeof e==`string`){let t=this.getError(e);q(t,`unknown error`,`fragment`,e),e=t}return q(Lv(t,0,4)===e.selector,`data signature does not match error ${e.name}.`,`data`,t),this._decodeParams(e.inputs,Lv(t,4))}encodeErrorResult(e,t){if(typeof e==`string`){let t=this.getError(e);q(t,`unknown error`,`fragment`,e),e=t}return Fv([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionData(e,t){if(typeof e==`string`){let t=this.getFunction(e);q(t,`unknown function`,`fragment`,e),e=t}return q(Lv(t,0,4)===e.selector,`data signature does not match function ${e.name}.`,`data`,t),this._decodeParams(e.inputs,Lv(t,4))}encodeFunctionData(e,t){if(typeof e==`string`){let t=this.getFunction(e);q(t,`unknown function`,`fragment`,e),e=t}return Fv([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionResult(e,t){if(typeof e==`string`){let t=this.getFunction(e);q(t,`unknown function`,`fragment`,e),e=t}let n=`invalid length for result data`,r=jv(t);if(r.length%32==0)try{return this.#r.decode(e.outputs,r)}catch{n=`could not decode result data`}K(!1,n,`BAD_DATA`,{value:Y(r),info:{method:e.name,signature:e.format()}})}makeError(e,t){let n=J(e,`data`),r=WD.getBuiltinCallException(`call`,t,n);if(r.message.startsWith(`execution reverted (unknown custom error)`)){let e=Y(n.slice(0,4)),t=this.getError(e);if(t)try{let e=this.#r.decode(t.inputs,n.slice(4));r.revert={name:t.name,signature:t.format(),args:e},r.reason=r.revert.signature,r.message=`execution reverted: ${r.reason}`}catch{r.message=`execution reverted (coult not decode custom error)`}}let i=this.parseTransaction(t);return i&&(r.invocation={method:i.name,signature:i.signature,args:i.args}),r}encodeFunctionResult(e,t){if(typeof e==`string`){let t=this.getFunction(e);q(t,`unknown function`,`fragment`,e),e=t}return Y(this.#r.encode(e.outputs,t||[]))}encodeFilterTopics(e,t){if(typeof e==`string`){let t=this.getEvent(e);q(t,`unknown event`,`eventFragment`,e),e=t}K(t.length<=e.inputs.length,`too many arguments for ${e.format()}`,`UNEXPECTED_ARGUMENT`,{count:t.length,expectedCount:e.inputs.length});let n=[];e.anonymous||n.push(e.topicHash);let r=(e,t)=>e.type===`string`?Gw(t):e.type===`bytes`?yx(Y(t)):(e.type===`bool`&&typeof t==`boolean`?t=t?`0x01`:`0x00`:e.type.match(/^u?int/)?t=Zv(t):e.type.match(/^bytes/)?t=Bv(t,32):e.type===`address`&&this.#r.encode([`address`],[t]),zv(Y(t),32));for(t.forEach((t,i)=>{let a=e.inputs[i];if(!a.indexed){q(t==null,`cannot filter non-indexed parameters; must be null`,`contract.`+a.name,t);return}t==null?n.push(null):a.baseType===`array`||a.baseType===`tuple`?q(!1,`filtering with tuples or arrays not supported`,`contract.`+a.name,t):Array.isArray(t)?n.push(t.map(e=>r(a,e))):n.push(r(a,t))});n.length&&n[n.length-1]===null;)n.pop();return n}encodeEventLog(e,t){if(typeof e==`string`){let t=this.getEvent(e);q(t,`unknown event`,`eventFragment`,e),e=t}let n=[],r=[],i=[];return e.anonymous||n.push(e.topicHash),q(t.length===e.inputs.length,`event arguments/values mismatch`,`values`,t),e.inputs.forEach((e,a)=>{let o=t[a];if(e.indexed)if(e.type===`string`)n.push(Gw(o));else if(e.type===`bytes`)n.push(yx(o));else if(e.baseType===`tuple`||e.baseType===`array`)throw Error(`not implemented`);else n.push(this.#r.encode([e.type],[o]));else r.push(e),i.push(o)}),{data:this.#r.encode(r,i),topics:n}}decodeEventLog(e,t,n){if(typeof e==`string`){let t=this.getEvent(e);q(t,`unknown event`,`eventFragment`,e),e=t}if(n!=null&&!e.anonymous){let t=e.topicHash;q(Mv(n[0],32)&&n[0].toLowerCase()===t,`fragment/topic mismatch`,`topics[0]`,n[0]),n=n.slice(1)}let r=[],i=[],a=[];e.inputs.forEach((e,t)=>{e.indexed?e.type===`string`||e.type===`bytes`||e.baseType===`tuple`||e.baseType===`array`?(r.push(OD.from({type:`bytes32`,name:e.name})),a.push(!0)):(r.push(e),a.push(!1)):(i.push(e),a.push(!1))});let o=n==null?null:this.#r.decode(r,Fv(n)),s=this.#r.decode(i,t,!0),c=[],l=[],u=0,d=0;return e.inputs.forEach((e,t)=>{let n=null;if(e.indexed)if(o==null)n=new JD(null);else if(a[t])n=new JD(o[d++]);else try{n=o[d++]}catch(e){n=e}else try{n=s[u++]}catch(e){n=e}c.push(n),l.push(e.name||null)}),Yy.fromItems(c,l)}parseTransaction(e){let t=J(e.data,`tx.data`),n=X(e.value==null?0:e.value,`tx.value`),r=this.getFunction(Y(t.slice(0,4)));if(!r)return null;let i=this.#r.decode(r.inputs,t.slice(4));return new KD(r,r.selector,i,n)}parseCallResult(e){throw Error(`@TODO`)}parseLog(e){let t=this.getEvent(e.topics[0]);return!t||t.anonymous?null:new GD(t,t.topicHash,this.decodeEventLog(t,e.data,e.topics))}parseError(e){let t=Y(e),n=this.getError(Lv(t,0,4));if(!n)return null;let r=this.#r.decode(n.inputs,Lv(t,4));return new qD(n,n.selector,r)}static from(t){return t instanceof e?t:typeof t==`string`?new e(JSON.parse(t)):typeof t.formatJson==`function`?new e(t.formatJson()):typeof t.format==`function`?new e(t.format(`json`)):new e(t)}},QD=BigInt(0);function $D(e){return e??null}function eO(e){return e==null?null:e.toString()}var tO=class{gasPrice;maxFeePerGas;maxPriorityFeePerGas;constructor(e,t,n){G(this,{gasPrice:$D(e),maxFeePerGas:$D(t),maxPriorityFeePerGas:$D(n)})}toJSON(){let{gasPrice:e,maxFeePerGas:t,maxPriorityFeePerGas:n}=this;return{_type:`FeeData`,gasPrice:eO(e),maxFeePerGas:eO(t),maxPriorityFeePerGas:eO(n)}}};function nO(e){let t={};e.to&&(t.to=e.to),e.from&&(t.from=e.from),e.data&&(t.data=Y(e.data));let n=`chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value`.split(/,/);for(let r of n)!(r in e)||e[r]==null||(t[r]=X(e[r],`request.${r}`));let r=`type,nonce`.split(/,/);for(let n of r)!(n in e)||e[n]==null||(t[n]=Z(e[n],`request.${n}`));return e.accessList&&(t.accessList=lw(e.accessList)),e.authorizationList&&(t.authorizationList=e.authorizationList.slice()),`blockTag`in e&&(t.blockTag=e.blockTag),`enableCcipRead`in e&&(t.enableCcipRead=!!e.enableCcipRead),`customData`in e&&(t.customData=e.customData),`blobVersionedHashes`in e&&e.blobVersionedHashes&&(t.blobVersionedHashes=e.blobVersionedHashes.slice()),`kzg`in e&&(t.kzg=e.kzg),`blobWrapperVersion`in e&&(t.blobWrapperVersion=e.blobWrapperVersion),`blobs`in e&&e.blobs&&(t.blobs=e.blobs.map(e=>Nv(e)?Y(e):Object.assign({},e))),t}var rO=class{provider;number;hash;timestamp;parentHash;parentBeaconBlockRoot;nonce;difficulty;gasLimit;gasUsed;stateRoot;receiptsRoot;blobGasUsed;excessBlobGas;miner;prevRandao;extraData;baseFeePerGas;#e;constructor(e,t){this.#e=e.transactions.map(e=>typeof e==`string`?e:new oO(e,t)),G(this,{provider:t,hash:$D(e.hash),number:e.number,timestamp:e.timestamp,parentHash:e.parentHash,parentBeaconBlockRoot:e.parentBeaconBlockRoot,nonce:e.nonce,difficulty:e.difficulty,gasLimit:e.gasLimit,gasUsed:e.gasUsed,blobGasUsed:e.blobGasUsed,excessBlobGas:e.excessBlobGas,miner:e.miner,prevRandao:$D(e.prevRandao),extraData:e.extraData,baseFeePerGas:$D(e.baseFeePerGas),stateRoot:e.stateRoot,receiptsRoot:e.receiptsRoot})}get transactions(){return this.#e.map(e=>typeof e==`string`?e:e.hash)}get prefetchedTransactions(){let e=this.#e.slice();return e.length===0?[]:(K(typeof e[0]==`object`,`transactions were not prefetched with block request`,`UNSUPPORTED_OPERATION`,{operation:`transactionResponses()`}),e)}toJSON(){let{baseFeePerGas:e,difficulty:t,extraData:n,gasLimit:r,gasUsed:i,hash:a,miner:o,prevRandao:s,nonce:c,number:l,parentHash:u,parentBeaconBlockRoot:d,stateRoot:f,receiptsRoot:p,timestamp:m,transactions:h}=this;return{_type:`Block`,baseFeePerGas:eO(e),difficulty:eO(t),extraData:n,gasLimit:eO(r),gasUsed:eO(i),blobGasUsed:eO(this.blobGasUsed),excessBlobGas:eO(this.excessBlobGas),hash:a,miner:o,prevRandao:s,nonce:c,number:l,parentHash:u,timestamp:m,parentBeaconBlockRoot:d,stateRoot:f,receiptsRoot:p,transactions:h}}[Symbol.iterator](){let e=0,t=this.transactions;return{next:()=>e<this.length?{value:t[e++],done:!1}:{value:void 0,done:!0}}}get length(){return this.#e.length}get date(){return this.timestamp==null?null:new Date(this.timestamp*1e3)}async getTransaction(e){let t;if(typeof e==`number`)t=this.#e[e];else{let n=e.toLowerCase();for(let e of this.#e)if(typeof e==`string`){if(e!==n)continue;t=e;break}else{if(e.hash!==n)continue;t=e;break}}if(t==null)throw Error(`no such tx`);return typeof t==`string`?await this.provider.getTransaction(t):t}getPrefetchedTransaction(e){let t=this.prefetchedTransactions;if(typeof e==`number`)return t[e];e=e.toLowerCase();for(let n of t)if(n.hash===e)return n;q(!1,`no matching transaction`,`indexOrHash`,e)}isMined(){return!!this.hash}isLondon(){return!!this.baseFeePerGas}orphanedEvent(){if(!this.isMined())throw Error(``);return sO(this)}},iO=class{provider;transactionHash;blockHash;blockNumber;removed;address;data;topics;index;transactionIndex;constructor(e,t){this.provider=t;let n=Object.freeze(e.topics.slice());G(this,{transactionHash:e.transactionHash,blockHash:e.blockHash,blockNumber:e.blockNumber,removed:e.removed,address:e.address,data:e.data,topics:n,index:e.index,transactionIndex:e.transactionIndex})}toJSON(){let{address:e,blockHash:t,blockNumber:n,data:r,index:i,removed:a,topics:o,transactionHash:s,transactionIndex:c}=this;return{_type:`log`,address:e,blockHash:t,blockNumber:n,data:r,index:i,removed:a,topics:o,transactionHash:s,transactionIndex:c}}async getBlock(){let e=await this.provider.getBlock(this.blockHash);return K(!!e,`failed to find transaction`,`UNKNOWN_ERROR`,{}),e}async getTransaction(){let e=await this.provider.getTransaction(this.transactionHash);return K(!!e,`failed to find transaction`,`UNKNOWN_ERROR`,{}),e}async getTransactionReceipt(){let e=await this.provider.getTransactionReceipt(this.transactionHash);return K(!!e,`failed to find transaction receipt`,`UNKNOWN_ERROR`,{}),e}removedEvent(){return uO(this)}},aO=class{provider;to;from;contractAddress;hash;index;blockHash;blockNumber;logsBloom;gasUsed;blobGasUsed;cumulativeGasUsed;gasPrice;blobGasPrice;type;status;root;#e;constructor(e,t){this.#e=Object.freeze(e.logs.map(e=>new iO(e,t)));let n=QD;e.effectiveGasPrice==null?e.gasPrice!=null&&(n=e.gasPrice):n=e.effectiveGasPrice,G(this,{provider:t,to:e.to,from:e.from,contractAddress:e.contractAddress,hash:e.hash,index:e.index,blockHash:e.blockHash,blockNumber:e.blockNumber,logsBloom:e.logsBloom,gasUsed:e.gasUsed,cumulativeGasUsed:e.cumulativeGasUsed,blobGasUsed:e.blobGasUsed,gasPrice:n,blobGasPrice:e.blobGasPrice,type:e.type,status:e.status,root:e.root})}get logs(){return this.#e}toJSON(){let{to:e,from:t,contractAddress:n,hash:r,index:i,blockHash:a,blockNumber:o,logsBloom:s,logs:c,status:l,root:u}=this;return{_type:`TransactionReceipt`,blockHash:a,blockNumber:o,contractAddress:n,cumulativeGasUsed:eO(this.cumulativeGasUsed),from:t,gasPrice:eO(this.gasPrice),blobGasUsed:eO(this.blobGasUsed),blobGasPrice:eO(this.blobGasPrice),gasUsed:eO(this.gasUsed),hash:r,index:i,logs:c,logsBloom:s,root:u,status:l,to:e}}get length(){return this.logs.length}[Symbol.iterator](){let e=0;return{next:()=>e<this.length?{value:this.logs[e++],done:!1}:{value:void 0,done:!0}}}get fee(){return this.gasUsed*this.gasPrice}async getBlock(){let e=await this.provider.getBlock(this.blockHash);if(e==null)throw Error(`TODO`);return e}async getTransaction(){let e=await this.provider.getTransaction(this.hash);if(e==null)throw Error(`TODO`);return e}async getResult(){return await this.provider.getTransactionResult(this.hash)}async confirmations(){return await this.provider.getBlockNumber()-this.blockNumber+1}removedEvent(){return lO(this)}reorderedEvent(e){return K(!e||e.isMined(),`unmined 'other' transction cannot be orphaned`,`UNSUPPORTED_OPERATION`,{operation:`reorderedEvent(other)`}),cO(this,e)}},oO=class e{provider;blockNumber;blockHash;index;hash;type;to;from;nonce;gasLimit;gasPrice;maxPriorityFeePerGas;maxFeePerGas;maxFeePerBlobGas;data;value;chainId;signature;accessList;blobVersionedHashes;authorizationList;#e;constructor(e,t){this.provider=t,this.blockNumber=e.blockNumber==null?null:e.blockNumber,this.blockHash=e.blockHash==null?null:e.blockHash,this.hash=e.hash,this.index=e.index,this.type=e.type,this.from=e.from,this.to=e.to||null,this.gasLimit=e.gasLimit,this.nonce=e.nonce,this.data=e.data,this.value=e.value,this.gasPrice=e.gasPrice,this.maxPriorityFeePerGas=e.maxPriorityFeePerGas==null?null:e.maxPriorityFeePerGas,this.maxFeePerGas=e.maxFeePerGas==null?null:e.maxFeePerGas,this.maxFeePerBlobGas=e.maxFeePerBlobGas==null?null:e.maxFeePerBlobGas,this.chainId=e.chainId,this.signature=e.signature,this.accessList=e.accessList==null?null:e.accessList,this.blobVersionedHashes=e.blobVersionedHashes==null?null:e.blobVersionedHashes,this.authorizationList=e.authorizationList==null?null:e.authorizationList,this.#e=-1}toJSON(){let{blockNumber:e,blockHash:t,index:n,hash:r,type:i,to:a,from:o,nonce:s,data:c,signature:l,accessList:u,blobVersionedHashes:d}=this;return{_type:`TransactionResponse`,accessList:u,blockNumber:e,blockHash:t,blobVersionedHashes:d,chainId:eO(this.chainId),data:c,from:o,gasLimit:eO(this.gasLimit),gasPrice:eO(this.gasPrice),hash:r,maxFeePerGas:eO(this.maxFeePerGas),maxPriorityFeePerGas:eO(this.maxPriorityFeePerGas),maxFeePerBlobGas:eO(this.maxFeePerBlobGas),nonce:s,signature:l,to:a,index:n,type:i,value:eO(this.value)}}async getBlock(){let e=this.blockNumber;if(e==null){let t=await this.getTransaction();t&&(e=t.blockNumber)}if(e==null)return null;let t=this.provider.getBlock(e);if(t==null)throw Error(`TODO`);return t}async getTransaction(){return this.provider.getTransaction(this.hash)}async confirmations(){if(this.blockNumber==null){let{tx:e,blockNumber:t}=await xv({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber()});return e==null||e.blockNumber==null?0:t-e.blockNumber+1}return await this.provider.getBlockNumber()-this.blockNumber+1}async wait(e,t){let n=e??1,r=t??0,i=this.#e,a=-1,o=i===-1,s=async()=>{if(o)return null;let{blockNumber:e,nonce:t}=await xv({blockNumber:this.provider.getBlockNumber(),nonce:this.provider.getTransactionCount(this.from)});if(t<this.nonce){i=e;return}if(o)return null;let r=await this.getTransaction();if(!(r&&r.blockNumber!=null))for(a===-1&&(a=i-3,a<this.#e&&(a=this.#e));a<=e;){if(o)return null;let t=await this.provider.getBlock(a,!0);if(t==null)return;for(let e of t)if(e===this.hash)return;for(let r=0;r<t.length;r++){let a=await t.getTransaction(r);if(a.from===this.from&&a.nonce===this.nonce){if(o)return null;let t=await this.provider.getTransactionReceipt(a.hash);if(t==null||e-t.blockNumber+1<n)return;let r=`replaced`;a.data===this.data&&a.to===this.to&&a.value===this.value?r=`repriced`:a.data===`0x`&&a.from===a.to&&a.value===QD&&(r=`cancelled`),K(!1,`transaction was replaced`,`TRANSACTION_REPLACED`,{cancelled:r===`replaced`||r===`cancelled`,reason:r,replacement:a.replaceableTransaction(i),hash:a.hash,receipt:t})}}a++}},c=e=>{if(e==null||e.status!==0)return e;K(!1,`transaction execution reverted`,`CALL_EXCEPTION`,{action:`sendTransaction`,data:null,reason:null,invocation:null,revert:null,transaction:{to:e.to,from:e.from,data:``},receipt:e})},l=await this.provider.getTransactionReceipt(this.hash);if(n===0)return c(l);if(l){if(n===1||await l.confirmations()>=n)return c(l)}else if(await s(),n===0)return null;return await new Promise((e,t)=>{let a=[],l=()=>{a.forEach(e=>e())};if(a.push(()=>{o=!0}),r>0){let e=setTimeout(()=>{l(),t(Tv(`wait for transaction timeout`,`TIMEOUT`))},r);a.push(()=>{clearTimeout(e)})}let u=async r=>{if(await r.confirmations()>=n){l();try{e(c(r))}catch(e){t(e)}}};if(a.push(()=>{this.provider.off(this.hash,u)}),this.provider.on(this.hash,u),i>=0){let e=async()=>{try{await s()}catch(e){if(Cv(e,`TRANSACTION_REPLACED`)){l(),t(e);return}}o||this.provider.once(`block`,e)};a.push(()=>{this.provider.off(`block`,e)}),this.provider.once(`block`,e)}})}isMined(){return this.blockHash!=null}isLegacy(){return this.type===0}isBerlin(){return this.type===1}isLondon(){return this.type===2}isCancun(){return this.type===3}removedEvent(){return K(this.isMined(),`unmined transaction canot be orphaned`,`UNSUPPORTED_OPERATION`,{operation:`removeEvent()`}),lO(this)}reorderedEvent(e){return K(this.isMined(),`unmined transaction canot be orphaned`,`UNSUPPORTED_OPERATION`,{operation:`removeEvent()`}),K(!e||e.isMined(),`unmined 'other' transaction canot be orphaned`,`UNSUPPORTED_OPERATION`,{operation:`removeEvent()`}),cO(this,e)}replaceableTransaction(t){q(Number.isInteger(t)&&t>=0,`invalid startBlock`,`startBlock`,t);let n=new e(this,this.provider);return n.#e=t,n}};function sO(e){return{orphan:`drop-block`,hash:e.hash,number:e.number}}function cO(e,t){return{orphan:`reorder-transaction`,tx:e,other:t}}function lO(e){return{orphan:`drop-transaction`,tx:e}}function uO(e){return{orphan:`drop-log`,log:{transactionHash:e.transactionHash,blockHash:e.blockHash,blockNumber:e.blockNumber,address:e.address,data:e.data,topics:Object.freeze(e.topics.slice()),index:e.index}}}var dO=class extends iO{interface;fragment;args;constructor(e,t,n){super(e,e.provider);let r=t.decodeEventLog(n,e.data,e.topics);G(this,{args:r,fragment:n,interface:t})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}},fO=class extends iO{error;constructor(e,t){super(e,e.provider),G(this,{error:t})}},pO=class extends aO{#e;constructor(e,t,n){super(n,t),this.#e=e}get logs(){return super.logs.map(e=>{let t=e.topics.length?this.#e.getEvent(e.topics[0]):null;if(t)try{return new dO(e,this.#e,t)}catch(t){return new fO(e,t)}return e})}},mO=class extends oO{#e;constructor(e,t,n){super(n,t),this.#e=e}async wait(e,t){let n=await super.wait(e,t);return n==null?null:new pO(this.#e,this.provider,n)}},hO=class extends ay{log;constructor(e,t,n,r){super(e,t,n),G(this,{log:r})}async getBlock(){return await this.log.getBlock()}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}},gO=class extends hO{constructor(e,t,n,r,i){super(e,t,n,new dO(i,e.interface,r));let a=e.interface.decodeEventLog(r,this.log.data,this.log.topics);G(this,{args:a,fragment:r})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}},_O=BigInt(0);function vO(e){return e&&typeof e.call==`function`}function yO(e){return e&&typeof e.estimateGas==`function`}function bO(e){return e&&typeof e.resolveName==`function`}function xO(e){return e&&typeof e.sendTransaction==`function`}function SO(e){if(e!=null){if(bO(e))return e;if(e.provider)return e.provider}}var CO=class{#e;fragment;constructor(e,t,n){if(G(this,{fragment:t}),t.inputs.length<n.length)throw Error(`too many arguments`);let r=wO(e.runner,`resolveName`),i=bO(r)?r:null;this.#e=(async function(){let r=await Promise.all(t.inputs.map((e,t)=>n[t]==null?null:e.walkAsync(n[t],(e,t)=>e===`address`?Array.isArray(t)?Promise.all(t.map(e=>BC(e,i))):BC(t,i):t)));return e.interface.encodeFilterTopics(t,r)})()}getTopicFilter(){return this.#e}};function wO(e,t){return e==null?null:typeof e[t]==`function`?e:e.provider&&typeof e.provider[t]==`function`?e.provider:null}function TO(e){return e==null?null:e.provider||null}async function EO(e,t){let n=WC.dereference(e,`overrides`);q(typeof n==`object`,`invalid overrides parameter`,`overrides`,e);let r=nO(n);return q(r.to==null||(t||[]).indexOf(`to`)>=0,`cannot override to`,`overrides.to`,r.to),q(r.data==null||(t||[]).indexOf(`data`)>=0,`cannot override data`,`overrides.data`,r.data),r.from&&=r.from,r}async function DO(e,t,n){let r=wO(e,`resolveName`),i=bO(r)?r:null;return await Promise.all(t.map((e,t)=>e.walkAsync(n[t],(e,t)=>(t=WC.dereference(t,e),e===`address`?BC(t,i):t))))}function OO(e){let t=async function(t){let n=await EO(t,[`data`]);n.to=await e.getAddress(),n.from&&=await BC(n.from,SO(e.runner));let r=e.interface,i=X(n.value||_O,`overrides.value`)===_O,a=(n.data||`0x`)===`0x`;return r.fallback&&!r.fallback.payable&&r.receive&&!a&&!i&&q(!1,`cannot send data to receive or send value to non-payable fallback`,`overrides`,t),q(r.fallback||a,`cannot send data to receive-only contract`,`overrides.data`,n.data),q(r.receive||r.fallback&&r.fallback.payable||i,`cannot send value to non-payable fallback`,`overrides.value`,n.value),q(r.fallback||a,`cannot send data to receive-only contract`,`overrides.data`,n.data),n},n=async function(n){let r=wO(e.runner,`call`);K(vO(r),`contract runner does not support calling`,`UNSUPPORTED_OPERATION`,{operation:`call`});let i=await t(n);try{return await r.call(i)}catch(t){throw wv(t)&&t.data?e.interface.makeError(t.data,i):t}},r=async function(n){let r=e.runner;K(xO(r),`contract runner does not support sending transactions`,`UNSUPPORTED_OPERATION`,{operation:`sendTransaction`});let i=await r.sendTransaction(await t(n)),a=TO(e.runner);return new mO(e.interface,a,i)},i=async function(n){let r=wO(e.runner,`estimateGas`);return K(yO(r),`contract runner does not support gas estimation`,`UNSUPPORTED_OPERATION`,{operation:`estimateGas`}),await r.estimateGas(await t(n))},a=async e=>await r(e);return G(a,{_contract:e,estimateGas:i,populateTransaction:t,send:r,staticCall:n}),a}function kO(e,t){let n=function(...n){let r=e.interface.getFunction(t,n);return K(r,`no matching fragment`,`UNSUPPORTED_OPERATION`,{operation:`fragment`,info:{key:t,args:n}}),r},r=async function(...t){let r=n(...t),i={};if(r.inputs.length+1===t.length&&(i=await EO(t.pop()),i.from&&=await BC(i.from,SO(e.runner))),r.inputs.length!==t.length)throw Error(`internal error: fragment inputs doesn't match arguments; should not happen`);let a=await DO(e.runner,r.inputs,t);return Object.assign({},i,await xv({to:e.getAddress(),data:e.interface.encodeFunctionData(r,a)}))},i=async function(...e){let t=await s(...e);return t.length===1?t[0]:t},a=async function(...t){let n=e.runner;K(xO(n),`contract runner does not support sending transactions`,`UNSUPPORTED_OPERATION`,{operation:`sendTransaction`});let i=await n.sendTransaction(await r(...t)),a=TO(e.runner);return new mO(e.interface,a,i)},o=async function(...t){let n=wO(e.runner,`estimateGas`);return K(yO(n),`contract runner does not support gas estimation`,`UNSUPPORTED_OPERATION`,{operation:`estimateGas`}),await n.estimateGas(await r(...t))},s=async function(...t){let i=wO(e.runner,`call`);K(vO(i),`contract runner does not support calling`,`UNSUPPORTED_OPERATION`,{operation:`call`});let a=await r(...t),o=`0x`;try{o=await i.call(a)}catch(t){throw wv(t)&&t.data?e.interface.makeError(t.data,a):t}let s=n(...t);return e.interface.decodeFunctionResult(s,o)},c=async(...e)=>n(...e).constant?await i(...e):await a(...e);return G(c,{name:e.interface.getFunctionName(t),_contract:e,_key:t,getFragment:n,estimateGas:o,populateTransaction:r,send:a,staticCall:i,staticCallResult:s}),Object.defineProperty(c,`fragment`,{configurable:!1,enumerable:!0,get:()=>{let n=e.interface.getFunction(t);return K(n,`no matching fragment`,`UNSUPPORTED_OPERATION`,{operation:`fragment`,info:{key:t}}),n}}),c}function AO(e,t){let n=function(...n){let r=e.interface.getEvent(t,n);return K(r,`no matching fragment`,`UNSUPPORTED_OPERATION`,{operation:`fragment`,info:{key:t,args:n}}),r},r=function(...t){return new CO(e,n(...t),t)};return G(r,{name:e.interface.getEventName(t),_contract:e,_key:t,getFragment:n}),Object.defineProperty(r,`fragment`,{configurable:!1,enumerable:!0,get:()=>{let n=e.interface.getEvent(t);return K(n,`no matching fragment`,`UNSUPPORTED_OPERATION`,{operation:`fragment`,info:{key:t}}),n}}),r}var jO=Symbol.for(`_ethersInternal_contract`),MO=new WeakMap;function NO(e,t){MO.set(e[jO],t)}function PO(e){return MO.get(e[jO])}function FO(e){return e&&typeof e==`object`&&`getTopicFilter`in e&&typeof e.getTopicFilter==`function`&&e.fragment}async function IO(e,t){let n,r=null;if(Array.isArray(t)){let r=function(t){if(Mv(t,32))return t;let n=e.interface.getEvent(t);return q(n,`unknown fragment`,`name`,t),n.topicHash};n=t.map(e=>e==null?null:Array.isArray(e)?e.map(r):r(e))}else t===`*`?n=[null]:typeof t==`string`?Mv(t,32)?n=[t]:(r=e.interface.getEvent(t),q(r,`unknown fragment`,`event`,t),n=[r.topicHash]):FO(t)?n=await t.getTopicFilter():`fragment`in t?(r=t.fragment,n=[r.topicHash]):q(!1,`unknown event name`,`event`,t);n=n.map(e=>{if(e==null)return null;if(Array.isArray(e)){let t=Array.from(new Set(e.map(e=>e.toLowerCase())).values());return t.length===1?t[0]:(t.sort(),t)}return e.toLowerCase()});let i=n.map(e=>e==null?`null`:Array.isArray(e)?e.join(`|`):e).join(`&`);return{fragment:r,tag:i,topics:n}}async function LO(e,t){let{subs:n}=PO(e);return n.get((await IO(e,t)).tag)||null}async function RO(e,t,n){let r=TO(e.runner);K(r,`contract runner does not support subscribing`,`UNSUPPORTED_OPERATION`,{operation:t});let{fragment:i,tag:a,topics:o}=await IO(e,n),{addr:s,subs:c}=PO(e),l=c.get(a);if(!l){let t={address:s||e,topics:o},u=t=>{let r=i;if(r==null)try{r=e.interface.getEvent(t.topics[0])}catch{}if(r){let a=r;VO(e,n,i?e.interface.decodeEventLog(i,t.data,t.topics):[],r=>new gO(e,r,n,a,t))}else VO(e,n,[],r=>new hO(e,r,n,t))},d=[];l={tag:a,listeners:[],start:()=>{d.length||d.push(r.on(t,u))},stop:async()=>{if(d.length==0)return;let e=d;d=[],await Promise.all(e),r.off(t,u)}},c.set(a,l)}return l}var zO=Promise.resolve();async function BO(e,t,n,r){await zO;let i=await LO(e,t);if(!i)return!1;let a=i.listeners.length;return i.listeners=i.listeners.filter(({listener:t,once:i})=>{let a=Array.from(n);r&&a.push(r(i?null:t));try{t.call(e,...a)}catch{}return!i}),i.listeners.length===0&&(i.stop(),PO(e).subs.delete(i.tag)),a>0}async function VO(e,t,n,r){try{await zO}catch{}let i=BO(e,t,n,r);return zO=i,await i}var HO=[`then`],UO=class e{target;interface;runner;filters;[jO];fallback;constructor(e,t,n,r){q(typeof e==`string`||RC(e),`invalid value for Contract target`,`target`,e),n??=null;let i=ZD.from(t);G(this,{target:e,runner:n,interface:i}),Object.defineProperty(this,jO,{value:{}});let a,o=null,s=null;if(r){let e=TO(n);s=new mO(this.interface,e,r)}let c=new Map;if(typeof e==`string`)if(Mv(e))o=e,a=Promise.resolve(e);else{let t=wO(n,`resolveName`);if(!bO(t))throw Tv(`contract runner does not support name resolution`,`UNSUPPORTED_OPERATION`,{operation:`resolveName`});a=t.resolveName(e).then(t=>{if(t==null)throw Tv(`an ENS name used for a contract target must be correctly configured`,`UNCONFIGURED_NAME`,{value:e});return PO(this).addr=t,t})}else a=e.getAddress().then(e=>{if(e==null)throw Error(`TODO`);return PO(this).addr=e,e});NO(this,{addrPromise:a,addr:o,deployTx:s,subs:c});let l=new Proxy({},{get:(e,t,n)=>{if(typeof t==`symbol`||HO.indexOf(t)>=0)return Reflect.get(e,t,n);try{return this.getEvent(t)}catch(e){if(!Cv(e,`INVALID_ARGUMENT`)||e.argument!==`key`)throw e}},has:(e,t)=>HO.indexOf(t)>=0?Reflect.has(e,t):Reflect.has(e,t)||this.interface.hasEvent(String(t))});return G(this,{filters:l}),G(this,{fallback:i.receive||i.fallback?OO(this):null}),new Proxy(this,{get:(e,t,n)=>{if(typeof t==`symbol`||t in e||HO.indexOf(t)>=0)return Reflect.get(e,t,n);try{return e.getFunction(t)}catch(e){if(!Cv(e,`INVALID_ARGUMENT`)||e.argument!==`key`)throw e}},has:(e,t)=>typeof t==`symbol`||t in e||HO.indexOf(t)>=0?Reflect.has(e,t):e.interface.hasFunction(t)})}connect(t){return new e(this.target,this.interface,t)}attach(t){return new e(t,this.interface,this.runner)}async getAddress(){return await PO(this).addrPromise}async getDeployedCode(){let e=TO(this.runner);K(e,`runner does not support .provider`,`UNSUPPORTED_OPERATION`,{operation:`getDeployedCode`});let t=await e.getCode(await this.getAddress());return t===`0x`?null:t}async waitForDeployment(){let e=this.deploymentTransaction();if(e)return await e.wait(),this;if(await this.getDeployedCode()!=null)return this;let t=TO(this.runner);return K(t!=null,`contract runner does not support .provider`,`UNSUPPORTED_OPERATION`,{operation:`waitForDeployment`}),new Promise((e,n)=>{let r=async()=>{try{if(await this.getDeployedCode()!=null)return e(this);t.once(`block`,r)}catch(e){n(e)}};r()})}deploymentTransaction(){return PO(this).deployTx}getFunction(e){return typeof e!=`string`&&(e=e.format()),kO(this,e)}getEvent(e){return typeof e!=`string`&&(e=e.format()),AO(this,e)}async queryTransaction(e){throw Error(`@TODO`)}async queryFilter(e,t,n){t??=0,n??=`latest`;let{addr:r,addrPromise:i}=PO(this),a=r||await i,{fragment:o,topics:s}=await IO(this,e),c={address:a,topics:s,fromBlock:t,toBlock:n},l=TO(this.runner);return K(l,`contract runner does not have a provider`,`UNSUPPORTED_OPERATION`,{operation:`queryFilter`}),(await l.getLogs(c)).map(e=>{let t=o;if(t==null)try{t=this.interface.getEvent(e.topics[0])}catch{}if(t)try{return new dO(e,this.interface,t)}catch(t){return new fO(e,t)}return new iO(e,l)})}async on(e,t){let n=await RO(this,`on`,e);return n.listeners.push({listener:t,once:!1}),n.start(),this}async once(e,t){let n=await RO(this,`once`,e);return n.listeners.push({listener:t,once:!0}),n.start(),this}async emit(e,...t){return await VO(this,e,t,null)}async listenerCount(e){if(e){let t=await LO(this,e);return t?t.listeners.length:0}let{subs:t}=PO(this),n=0;for(let{listeners:e}of t.values())n+=e.length;return n}async listeners(e){if(e){let t=await LO(this,e);return t?t.listeners.map(({listener:e})=>e):[]}let{subs:t}=PO(this),n=[];for(let{listeners:e}of t.values())n=n.concat(e.map(({listener:e})=>e));return n}async off(e,t){let n=await LO(this,e);if(!n)return this;if(t){let e=n.listeners.map(({listener:e})=>e).indexOf(t);e>=0&&n.listeners.splice(e,1)}return(t==null||n.listeners.length===0)&&(n.stop(),PO(this).subs.delete(n.tag)),this}async removeAllListeners(e){if(e){let t=await LO(this,e);if(!t)return this;t.stop(),PO(this).subs.delete(t.tag)}else{let{subs:e}=PO(this);for(let{tag:t,stop:n}of e.values())n(),e.delete(t)}return this}async addListener(e,t){return await this.on(e,t)}async removeListener(e,t){return await this.off(e,t)}static buildClass(t){class n extends e{constructor(e,n=null){super(e,t,n)}}return n}static from(e,t,n){return n??=null,new this(e,t,n)}};function WO(){return UO}var GO=class extends WO(){};function KO(e){return e.match(/^ipfs:\/\/ipfs\//i)?e=e.substring(12):e.match(/^ipfs:\/\//i)?e=e.substring(7):q(!1,`unsupported IPFS format`,`link`,e),`https:/\/gateway.ipfs.io/ipfs/${e}`}var qO=class{name;constructor(e){G(this,{name:e})}connect(e){return this}supportsCoinType(e){return!1}async encodeAddress(e,t){throw Error(`unsupported coin`)}async decodeAddress(e,t){throw Error(`unsupported coin`)}},JO=RegExp(`^(ipfs)://(.*)$`,`i`),YO=[RegExp(`^(https)://(.*)$`,`i`),RegExp(`^(data):(.*)$`,`i`),JO,RegExp(`^eip155:[0-9]+/(erc[0-9]+):(.*)$`,`i`)],XO=class e{provider;address;name;#e;#t;constructor(e,t,n){G(this,{provider:e,address:t,name:n}),this.#e=null,this.#t=new GO(t,[`function supportsInterface(bytes4) view returns (bool)`,`function resolve(bytes, bytes) view returns (bytes)`,`function addr(bytes32) view returns (address)`,`function addr(bytes32, uint) view returns (bytes)`,`function text(bytes32, string) view returns (string)`,`function contenthash(bytes32) view returns (bytes)`],e)}async supportsWildcard(){return this.#e??=(async()=>{try{return await this.#t.supportsInterface(`0x9061b923`)}catch(e){if(Cv(e,`CALL_EXCEPTION`))return!1;throw this.#e=null,e}})(),await this.#e}async#n(e,t){t=(t||[]).slice();let n=this.#t.interface;t.unshift(kE(this.name));let r=null;await this.supportsWildcard()&&(r=n.getFunction(e),K(r,`missing fragment`,`UNKNOWN_ERROR`,{info:{funcName:e}}),t=[AE(this.name,255),n.encodeFunctionData(r,t)],e=`resolve(bytes,bytes)`),t.push({enableCcipRead:!0});try{let i=await this.#t[e](...t);return r?n.decodeFunctionResult(r,i)[0]:i}catch(e){if(!Cv(e,`CALL_EXCEPTION`))throw e}return null}async getAddress(e){if(e??=60,e===60)try{let e=await this.#n(`addr(bytes32)`);return e==null||e===`0x0000000000000000000000000000000000000000`?null:e}catch(e){if(Cv(e,`CALL_EXCEPTION`))return null;throw e}if(e>=0&&e<2147483648){let t=e+2147483648,n=await this.#n(`addr(bytes32,uint)`,[t]);if(Mv(n,20))return IC(n)}let t=null;for(let n of this.provider.plugins)if(n instanceof qO&&n.supportsCoinType(e)){t=n;break}if(t==null)return null;let n=await this.#n(`addr(bytes32,uint)`,[e]);if(n==null||n===`0x`)return null;let r=await t.decodeAddress(e,n);if(r!=null)return r;K(!1,`invalid coin data`,`UNSUPPORTED_OPERATION`,{operation:`getAddress(${e})`,info:{coinType:e,data:n}})}async getText(e){let t=await this.#n(`text(bytes32,string)`,[e]);return t==null||t===`0x`?null:t}async getContentHash(){let e=await this.#n(`contenthash(bytes32)`);if(e==null||e===`0x`)return null;let t=e.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);if(t){let e=t[1]===`e3010170`?`ipfs`:`ipns`,n=parseInt(t[4],16);if(t[5].length===n*2)return`${e}:/\/${ny(`0x`+t[2])}`}let n=e.match(/^0xe40101fa011b20([0-9a-f]*)$/);if(n&&n[1].length===64)return`bzz:/\/${n[1]}`;K(!1,`invalid or unsupported content hash data`,`UNSUPPORTED_OPERATION`,{operation:`getContentHash()`,info:{data:e}})}async getAvatar(){return(await this._getAvatar()).url}async _getAvatar(){let e=[{type:`name`,value:this.name}];try{let t=await this.getText(`avatar`);if(t==null)return e.push({type:`!avatar`,value:``}),{url:null,linkage:e};e.push({type:`avatar`,value:t});for(let n=0;n<YO.length;n++){let r=t.match(YO[n]);if(r==null)continue;let i=r[1].toLowerCase();switch(i){case`https`:case`data`:return e.push({type:`url`,value:t}),{linkage:e,url:t};case`ipfs`:{let n=KO(t);return e.push({type:`ipfs`,value:t}),e.push({type:`url`,value:n}),{linkage:e,url:n}}case`erc721`:case`erc1155`:{let n=i===`erc721`?`tokenURI(uint256)`:`uri(uint256)`;e.push({type:i,value:t});let a=await this.getAddress();if(a==null)return e.push({type:`!owner`,value:``}),{url:null,linkage:e};let o=(r[2]||``).split(`/`);if(o.length!==2)return e.push({type:`!${i}caip`,value:r[2]||``}),{url:null,linkage:e};let s=o[1],c=new GO(o[0],[`function tokenURI(uint) view returns (string)`,`function ownerOf(uint) view returns (address)`,`function uri(uint) view returns (string)`,`function balanceOf(address, uint256) view returns (uint)`],this.provider);if(i===`erc721`){let t=await c.ownerOf(s);if(a!==t)return e.push({type:`!owner`,value:t}),{url:null,linkage:e};e.push({type:`owner`,value:t})}else if(i===`erc1155`){let t=await c.balanceOf(a,s);if(!t)return e.push({type:`!balance`,value:`0`}),{url:null,linkage:e};e.push({type:`balance`,value:t.toString()})}let l=await c[n](s);if(l==null||l===`0x`)return e.push({type:`!metadata-url`,value:``}),{url:null,linkage:e};e.push({type:`metadata-url-base`,value:l}),i===`erc1155`&&(l=l.replace(`{id}`,Zv(s,32).substring(2)),e.push({type:`metadata-url-expanded`,value:l})),l.match(/^ipfs:/i)&&(l=KO(l)),e.push({type:`metadata-url`,value:l});let u={},d=await new Dy(l).send();d.assertOk();try{u=d.bodyJson}catch{try{e.push({type:`!metadata`,value:d.bodyText})}catch{let t=d.body;return t&&e.push({type:`!metadata`,value:Y(t)}),{url:null,linkage:e}}return{url:null,linkage:e}}if(!u)return e.push({type:`!metadata`,value:``}),{url:null,linkage:e};e.push({type:`metadata`,value:JSON.stringify(u)});let f=u.image;if(typeof f!=`string`)return e.push({type:`!imageUrl`,value:``}),{url:null,linkage:e};if(!f.match(/^(https:\/\/|data:)/i)){if(f.match(JO)==null)return e.push({type:`!imageUrl-ipfs`,value:f}),{url:null,linkage:e};e.push({type:`imageUrl-ipfs`,value:f}),f=KO(f)}return e.push({type:`url`,value:f}),{linkage:e,url:f}}}}}catch{}return{linkage:e,url:null}}static async getEnsAddress(e){let t=await e.getNetwork(),n=t.getPlugin(`org.ethers.plugins.network.Ens`);return K(n,`network does not support ENS`,`UNSUPPORTED_OPERATION`,{operation:`getEnsAddress`,info:{network:t}}),n.address}static async#r(t,n){let r=await e.getEnsAddress(t);try{let e=await new GO(r,[`function resolver(bytes32) view returns (address)`],t).resolver(kE(n),{enableCcipRead:!0});return e===`0x0000000000000000000000000000000000000000`?null:e}catch(e){throw e}return null}static async fromName(t,n){let r=n;for(;;){if(r===``||r===`.`||n!==`eth`&&r===`eth`)return null;let i=await e.#r(t,r);if(i!=null){let a=new e(t,i,n);return r!==n&&!await a.supportsWildcard()?null:a}r=r.split(`.`).slice(1).join(`.`)}}},ZO=BigInt(0);function QO(e,t){return(function(n){return n==null?t:e(n)})}function $O(e,t){return(n=>{if(t&&n==null)return null;if(!Array.isArray(n))throw Error(`not an array`);return n.map(t=>e(t))})}function ek(e,t){return(n=>{let r={};for(let i in e){let a=i;if(t&&i in t&&!(a in n)){for(let e of t[i])if(e in n){a=e;break}}try{let t=e[i](n[a]);t!==void 0&&(r[i]=t)}catch(e){K(!1,`invalid value for value.${i} (${e instanceof Error?e.message:`not-an-error`})`,`BAD_DATA`,{value:n})}}return r})}function tk(e){switch(e){case!0:case`true`:return!0;case!1:case`false`:return!1}q(!1,`invalid boolean; ${JSON.stringify(e)}`,`value`,e)}function nk(e){return q(Mv(e,!0),`invalid data`,`value`,e),e}function rk(e){return q(Mv(e,32),`invalid hash`,`value`,e),e}var ik=ek({address:IC,blockHash:rk,blockNumber:Z,data:nk,index:Z,removed:QO(tk,!1),topics:$O(rk),transactionHash:rk,transactionIndex:Z},{index:[`logIndex`]});function ak(e){return ik(e)}var ok=ek({hash:QO(rk),parentHash:rk,parentBeaconBlockRoot:QO(rk,null),number:Z,timestamp:Z,nonce:QO(nk),difficulty:X,gasLimit:X,gasUsed:X,stateRoot:QO(rk,null),receiptsRoot:QO(rk,null),blobGasUsed:QO(X,null),excessBlobGas:QO(X,null),miner:QO(IC),prevRandao:QO(rk,null),extraData:nk,baseFeePerGas:QO(X)},{prevRandao:[`mixHash`]});function sk(e){let t=ok(e);return t.transactions=e.transactions.map(e=>typeof e==`string`?e:fk(e)),t}var ck=ek({transactionIndex:Z,blockNumber:Z,transactionHash:rk,address:IC,topics:$O(rk),data:nk,index:Z,blockHash:rk},{index:[`logIndex`]});function lk(e){return ck(e)}var uk=ek({to:QO(IC,null),from:QO(IC,null),contractAddress:QO(IC,null),index:Z,root:QO(Y),gasUsed:X,blobGasUsed:QO(X,null),logsBloom:QO(nk),blockHash:rk,hash:rk,logs:$O(lk),blockNumber:Z,cumulativeGasUsed:X,effectiveGasPrice:QO(X),blobGasPrice:QO(X,null),status:QO(Z),type:QO(Z,0)},{effectiveGasPrice:[`gasPrice`],hash:[`transactionHash`],index:[`transactionIndex`]});function dk(e){return uk(e)}function fk(e){e.to&&X(e.to)===ZO&&(e.to=`0x0000000000000000000000000000000000000000`);let t=ek({hash:rk,index:QO(Z,void 0),type:e=>e===`0x`||e==null?0:Z(e),accessList:QO(lw,null),blobVersionedHashes:QO($O(rk,!0),null),authorizationList:QO($O(e=>{let t;if(e.signature)t=e.signature;else{let n=e.yParity;n===`0x1b`?n=0:n===`0x1c`&&(n=1),t=Object.assign({},e,{yParity:n})}return{address:IC(e.address),chainId:X(e.chainId),nonce:X(e.nonce),signature:EC.from(t)}},!1),null),blockHash:QO(rk,null),blockNumber:QO(Z,null),transactionIndex:QO(Z,null),from:IC,gasPrice:QO(X),maxPriorityFeePerGas:QO(X),maxFeePerGas:QO(X),maxFeePerBlobGas:QO(X,null),gasLimit:X,to:QO(IC,null),value:X,nonce:Z,data:nk,creates:QO(IC,null),chainId:QO(X,null)},{data:[`input`],gasLimit:[`gas`],index:[`transactionIndex`]})(e);if(t.to==null&&t.creates==null&&(t.creates=LC(t)),(e.type===1||e.type===2)&&e.accessList==null&&(t.accessList=[]),e.signature?t.signature=EC.from(e.signature):t.signature=EC.from(e),t.chainId==null){let e=t.signature.legacyChainId;e!=null&&(t.chainId=e)}return t.blockHash&&X(t.blockHash)===ZO&&(t.blockHash=null),t}var pk=`0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e`,mk=class e{name;constructor(e){G(this,{name:e})}clone(){return new e(this.name)}},hk=class e extends mk{effectiveBlock;txBase;txCreate;txDataZero;txDataNonzero;txAccessListStorageKey;txAccessListAddress;constructor(e,t){e??=0,super(`org.ethers.network.plugins.GasCost#${e||0}`);let n={effectiveBlock:e};function r(e,r){let i=(t||{})[e];i??=r,q(typeof i==`number`,`invalud value for ${e}`,`costs`,t),n[e]=i}r(`txBase`,21e3),r(`txCreate`,32e3),r(`txDataZero`,4),r(`txDataNonzero`,16),r(`txAccessListStorageKey`,1900),r(`txAccessListAddress`,2400),G(this,n)}clone(){return new e(this.effectiveBlock,this)}},gk=class e extends mk{address;targetNetwork;constructor(e,t){super(`org.ethers.plugins.network.Ens`),G(this,{address:e||pk,targetNetwork:t??1})}clone(){return new e(this.address,this.targetNetwork)}},_k=class extends mk{#e;#t;get url(){return this.#e}get processFunc(){return this.#t}constructor(e,t){super(`org.ethers.plugins.network.FetchUrlFeeDataPlugin`),this.#e=e,this.#t=t}clone(){return this}},vk=new Map,yk=class e{#e;#t;#n;constructor(e,t){this.#e=e,this.#t=X(t),this.#n=new Map}toJSON(){return{name:this.name,chainId:String(this.chainId)}}get name(){return this.#e}set name(e){this.#e=e}get chainId(){return this.#t}set chainId(e){this.#t=X(e,`chainId`)}matches(e){if(e==null)return!1;if(typeof e==`string`){try{return this.chainId===X(e)}catch{}return this.name===e}if(typeof e==`number`||typeof e==`bigint`){try{return this.chainId===X(e)}catch{}return!1}if(typeof e==`object`){if(e.chainId!=null){try{return this.chainId===X(e.chainId)}catch{}return!1}return e.name==null?!1:this.name===e.name}return!1}get plugins(){return Array.from(this.#n.values())}attachPlugin(e){if(this.#n.get(e.name))throw Error(`cannot replace existing plugin: ${e.name} `);return this.#n.set(e.name,e.clone()),this}getPlugin(e){return this.#n.get(e)||null}getPlugins(e){return this.plugins.filter(t=>t.name.split(`#`)[0]===e)}clone(){let t=new e(this.name,this.chainId);return this.plugins.forEach(e=>{t.attachPlugin(e.clone())}),t}computeIntrinsicGas(e){let t=this.getPlugin(`org.ethers.plugins.network.GasCost`)||new hk,n=t.txBase;if(e.to??(n+=t.txCreate),e.data)for(let r=2;r<e.data.length;r+=2)e.data.substring(r,r+2)===`00`?n+=t.txDataZero:n+=t.txDataNonzero;if(e.accessList){let r=lw(e.accessList);for(let e in r)n+=t.txAccessListAddress+t.txAccessListStorageKey*r[e].storageKeys.length}return n}static from(t){if(Ck(),t==null)return e.from(`mainnet`);if(typeof t==`number`&&(t=BigInt(t)),typeof t==`string`||typeof t==`bigint`){let n=vk.get(t);if(n)return n();if(typeof t==`bigint`)return new e(`unknown`,t);q(!1,`unknown network`,`network`,t)}if(typeof t.clone==`function`)return t.clone();if(typeof t==`object`){q(typeof t.name==`string`&&typeof t.chainId==`number`,`invalid network object name or chainId`,`network`,t);let n=new e(t.name,t.chainId);return(t.ensAddress||t.ensNetwork!=null)&&n.attachPlugin(new gk(t.ensAddress,t.ensNetwork)),n}q(!1,`invalid network`,`network`,t)}static register(e,t){typeof e==`number`&&(e=BigInt(e));let n=vk.get(e);n&&q(!1,`conflicting network for ${JSON.stringify(n.name)}`,`nameOrChainId`,e),vk.set(e,t)}};function bk(e,t){let n=String(e);if(!n.match(/^[0-9.]+$/))throw Error(`invalid gwei value: ${e}`);let r=n.split(`.`);if(r.length===1&&r.push(``),r.length!==2)throw Error(`invalid gwei value: ${e}`);for(;r[1].length<t;)r[1]+=`0`;if(r[1].length>9){let e=BigInt(r[1].substring(0,9));r[1].substring(9).match(/^0+$/)||e++,r[1]=e.toString()}return BigInt(r[0]+r[1])}function xk(e){return new _k(e,async(e,t,n)=>{n.setHeader(`User-Agent`,`ethers`);let r;try{let[t,i]=await Promise.all([n.send(),e()]);r=t;let a=r.bodyJson.standard;return{gasPrice:i.gasPrice,maxFeePerGas:bk(a.maxFee,9),maxPriorityFeePerGas:bk(a.maxPriorityFee,9)}}catch(e){K(!1,`error encountered with polygon gas station (${JSON.stringify(n.url)})`,`SERVER_ERROR`,{request:n,response:r,error:e})}})}var Sk=!1;function Ck(){if(Sk)return;Sk=!0;function e(e,t,n){let r=function(){let r=new yk(e,t);return n.ensNetwork!=null&&r.attachPlugin(new gk(null,n.ensNetwork)),r.attachPlugin(new hk),(n.plugins||[]).forEach(e=>{r.attachPlugin(e)}),r};yk.register(e,r),yk.register(t,r),n.altNames&&n.altNames.forEach(e=>{yk.register(e,r)})}e(`mainnet`,1,{ensNetwork:1,altNames:[`homestead`]}),e(`ropsten`,3,{ensNetwork:3}),e(`rinkeby`,4,{ensNetwork:4}),e(`goerli`,5,{ensNetwork:5}),e(`kovan`,42,{ensNetwork:42}),e(`sepolia`,11155111,{ensNetwork:11155111}),e(`holesky`,17e3,{ensNetwork:17e3}),e(`classic`,61,{}),e(`classicKotti`,6,{}),e(`arbitrum`,42161,{ensNetwork:1}),e(`arbitrum-goerli`,421613,{}),e(`arbitrum-sepolia`,421614,{}),e(`base`,8453,{ensNetwork:1}),e(`base-goerli`,84531,{}),e(`base-sepolia`,84532,{}),e(`bnb`,56,{ensNetwork:1}),e(`bnbt`,97,{}),e(`filecoin`,314,{}),e(`filecoin-calibration`,314159,{}),e(`linea`,59144,{ensNetwork:1}),e(`linea-goerli`,59140,{}),e(`linea-sepolia`,59141,{}),e(`matic`,137,{ensNetwork:1,plugins:[xk(`https://gasstation.polygon.technology/v2`)]}),e(`matic-amoy`,80002,{}),e(`matic-mumbai`,80001,{altNames:[`maticMumbai`,`maticmum`],plugins:[xk(`https://gasstation-testnet.polygon.technology/v2`)]}),e(`optimism`,10,{ensNetwork:1,plugins:[]}),e(`optimism-goerli`,420,{}),e(`optimism-sepolia`,11155420,{}),e(`xdai`,100,{ensNetwork:1})}function wk(e){return JSON.parse(JSON.stringify(e))}var Tk=class{#e;#t;#n;#r;constructor(e){this.#e=e,this.#t=null,this.#n=4e3,this.#r=-2}get pollingInterval(){return this.#n}set pollingInterval(e){this.#n=e}async#i(){try{let e=await this.#e.getBlockNumber();if(this.#r===-2){this.#r=e;return}if(e!==this.#r){for(let t=this.#r+1;t<=e;t++){if(this.#t==null)return;await this.#e.emit(`block`,t)}this.#r=e}}catch{}this.#t!=null&&(this.#t=this.#e._setTimeout(this.#i.bind(this),this.#n))}start(){this.#t||(this.#t=this.#e._setTimeout(this.#i.bind(this),this.#n),this.#i())}stop(){this.#t&&=(this.#e._clearTimeout(this.#t),null)}pause(e){this.stop(),e&&(this.#r=-2)}resume(){this.start()}},Ek=class{#e;#t;#n;constructor(e){this.#e=e,this.#n=!1,this.#t=e=>{this._poll(e,this.#e)}}async _poll(e,t){throw Error(`sub-classes must override this`)}start(){this.#n||(this.#n=!0,this.#t(-2),this.#e.on(`block`,this.#t))}stop(){this.#n&&(this.#n=!1,this.#e.off(`block`,this.#t))}pause(e){this.stop()}resume(){this.start()}},Dk=class extends Ek{#e;#t;constructor(e,t){super(e),this.#e=t,this.#t=-2}pause(e){e&&(this.#t=-2),super.pause(e)}async _poll(e,t){let n=await t.getBlock(this.#e);n!=null&&(this.#t===-2?this.#t=n.number:n.number>this.#t&&(t.emit(this.#e,n.number),this.#t=n.number))}},Ok=class extends Ek{#e;constructor(e,t){super(e),this.#e=wk(t)}async _poll(e,t){throw Error(`@TODO`)}},kk=class extends Ek{#e;constructor(e,t){super(e),this.#e=t}async _poll(e,t){let n=await t.getTransactionReceipt(this.#e);n&&t.emit(this.#e,n)}},Ak=class{#e;#t;#n;#r;#i;constructor(e,t){this.#e=e,this.#t=wk(t),this.#n=this.#a.bind(this),this.#r=!1,this.#i=-2}async#a(e){if(this.#i===-2)return;let t=wk(this.#t);t.fromBlock=this.#i+1,t.toBlock=e;let n=await this.#e.getLogs(t);if(n.length===0){this.#i<e-60&&(this.#i=e-60);return}for(let e of n)this.#e.emit(this.#t,e),this.#i=e.blockNumber}start(){this.#r||(this.#r=!0,this.#i===-2&&this.#e.getBlockNumber().then(e=>{this.#i=e}),this.#e.on(`block`,this.#n))}stop(){this.#r&&(this.#r=!1,this.#e.off(`block`,this.#n))}pause(e){this.stop(),e&&(this.#i=-2)}resume(){this.start()}},jk=BigInt(2),Mk=10;function Nk(e){return e&&typeof e.then==`function`}function Pk(e,t){return e+`:`+JSON.stringify(t,(e,t)=>{if(t==null)return`null`;if(typeof t==`bigint`)return`bigint:${t.toString()}`;if(typeof t==`string`)return t.toLowerCase();if(typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t);return e.sort(),e.reduce((e,n)=>(e[n]=t[n],e),{})}return t})}var Fk=class{name;constructor(e){G(this,{name:e})}start(){}stop(){}pause(e){}resume(){}};function Ik(e){return JSON.parse(JSON.stringify(e))}function Lk(e){return e=Array.from(new Set(e).values()),e.sort(),e}async function Rk(e,t){if(e==null)throw Error(`invalid event`);if(Array.isArray(e)&&(e={topics:e}),typeof e==`string`)switch(e){case`block`:case`debug`:case`error`:case`finalized`:case`network`:case`pending`:case`safe`:return{type:e,tag:e}}if(Mv(e,32)){let t=e.toLowerCase();return{type:`transaction`,tag:Pk(`tx`,{hash:t}),hash:t}}if(e.orphan){let t=e;return{type:`orphan`,tag:Pk(`orphan`,t),filter:Ik(t)}}if(e.address||e.topics){let n=e,r={topics:(n.topics||[]).map(e=>e==null?null:Array.isArray(e)?Lk(e.map(e=>e.toLowerCase())):e.toLowerCase())};if(n.address){let e=[],i=[],a=n=>{Mv(n)?e.push(n):i.push((async()=>{e.push(await BC(n,t))})())};Array.isArray(n.address)?n.address.forEach(a):a(n.address),i.length&&await Promise.all(i),r.address=Lk(e.map(e=>e.toLowerCase()))}return{filter:r,tag:Pk(`event`,r),type:`event`}}q(!1,`unknown ProviderEvent`,`event`,e)}function zk(){return new Date().getTime()}var Bk={cacheTimeout:250,pollingInterval:4e3},Vk=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t){if(this.#d=Object.assign({},Bk,t||{}),e===`any`)this.#a=!0,this.#i=null;else if(e){let t=yk.from(e);this.#a=!1,this.#i=Promise.resolve(t),setTimeout(()=>{this.emit(`network`,t,null)},0)}else this.#a=!1,this.#i=null;this.#s=-1,this.#o=new Map,this.#e=new Map,this.#t=new Map,this.#n=null,this.#r=!1,this.#c=1,this.#l=new Map,this.#u=!1}get pollingInterval(){return this.#d.pollingInterval}get provider(){return this}get plugins(){return Array.from(this.#t.values())}attachPlugin(e){if(this.#t.get(e.name))throw Error(`cannot replace existing plugin: ${e.name} `);return this.#t.set(e.name,e.connect(this)),this}getPlugin(e){return this.#t.get(e)||null}get disableCcipRead(){return this.#u}set disableCcipRead(e){this.#u=!!e}async#f(e){let t=this.#d.cacheTimeout;if(t<0)return await this._perform(e);let n=Pk(e.method,e),r=this.#o.get(n);return r||(r=this._perform(e),this.#o.set(n,r),setTimeout(()=>{this.#o.get(n)===r&&this.#o.delete(n)},t)),await r}async ccipReadFetch(e,t,n){if(this.disableCcipRead||n.length===0||e.to==null)return null;let r=e.to.toLowerCase(),i=t.toLowerCase(),a=[];for(let t=0;t<n.length;t++){let o=n[t],s=new Dy(o.replace(`{sender}`,r).replace(`{data}`,i));o.indexOf(`{data}`)===-1&&(s.body={data:i,sender:r}),this.emit(`debug`,{action:`sendCcipReadFetchRequest`,request:s,index:t,urls:n});let c=`unknown error`,l;try{l=await s.send()}catch(e){a.push(e.message),this.emit(`debug`,{action:`receiveCcipReadFetchError`,request:s,result:{error:e}});continue}try{let e=l.bodyJson;if(e.data)return this.emit(`debug`,{action:`receiveCcipReadFetchResult`,request:s,result:e}),e.data;e.message&&(c=e.message),this.emit(`debug`,{action:`receiveCcipReadFetchError`,request:s,result:e})}catch{}K(l.statusCode<400||l.statusCode>=500,`response not found during CCIP fetch: ${c}`,`OFFCHAIN_FAULT`,{reason:`404_MISSING_RESOURCE`,transaction:e,info:{url:o,errorMessage:c}}),a.push(c)}K(!1,`error encountered during CCIP fetch: ${a.map(e=>JSON.stringify(e)).join(`, `)}`,`OFFCHAIN_FAULT`,{reason:`500_SERVER_ERROR`,transaction:e,info:{urls:n,errorMessages:a}})}_wrapBlock(e,t){return new rO(sk(e),this)}_wrapLog(e,t){return new iO(ak(e),this)}_wrapTransactionReceipt(e,t){return new aO(dk(e),this)}_wrapTransactionResponse(e,t){return new oO(fk(e),this)}_detectNetwork(){K(!1,`sub-classes must implement this`,`UNSUPPORTED_OPERATION`,{operation:`_detectNetwork`})}async _perform(e){K(!1,`unsupported method: ${e.method}`,`UNSUPPORTED_OPERATION`,{operation:e.method,info:e})}async getBlockNumber(){let e=Z(await this.#f({method:`getBlockNumber`}),`%response`);return this.#s>=0&&(this.#s=e),e}_getAddress(e){return BC(e,this)}_getBlockTag(e){if(e==null)return`latest`;switch(e){case`earliest`:return`0x0`;case`finalized`:case`latest`:case`pending`:case`safe`:return e}if(Mv(e))return Mv(e,32)?e:$v(e);if(typeof e==`bigint`&&(e=Z(e,`blockTag`)),typeof e==`number`)return e>=0?$v(e):this.#s>=0?$v(this.#s+e):this.getBlockNumber().then(t=>$v(t+e));q(!1,`invalid blockTag`,`blockTag`,e)}_getFilter(e){let t=(e.topics||[]).map(e=>e==null?null:Array.isArray(e)?Lk(e.map(e=>e.toLowerCase())):e.toLowerCase()),n=`blockHash`in e?e.blockHash:void 0,r=(e,r,i)=>{let a;switch(e.length){case 0:break;case 1:a=e[0];break;default:e.sort(),a=e}if(n&&(r!=null||i!=null))throw Error(`invalid filter`);let o={};return a&&(o.address=a),t.length&&(o.topics=t),r&&(o.fromBlock=r),i&&(o.toBlock=i),n&&(o.blockHash=n),o},i=[];if(e.address)if(Array.isArray(e.address))for(let t of e.address)i.push(this._getAddress(t));else i.push(this._getAddress(e.address));let a;`fromBlock`in e&&(a=this._getBlockTag(e.fromBlock));let o;return`toBlock`in e&&(o=this._getBlockTag(e.toBlock)),i.filter(e=>typeof e!=`string`).length||a!=null&&typeof a!=`string`||o!=null&&typeof o!=`string`?Promise.all([Promise.all(i),a,o]).then(e=>r(e[0],e[1],e[2])):r(i,a,o)}_getTransactionRequest(e){let t=nO(e),n=[];if([`to`,`from`].forEach(e=>{if(t[e]==null)return;let r=BC(t[e],this);Nk(r)?n.push((async function(){t[e]=await r})()):t[e]=r}),t.blockTag!=null){let e=this._getBlockTag(t.blockTag);Nk(e)?n.push((async function(){t.blockTag=await e})()):t.blockTag=e}return n.length?(async function(){return await Promise.all(n),t})():t}async getNetwork(){if(this.#i==null){let e=(async()=>{try{let e=await this._detectNetwork();return this.emit(`network`,e,null),e}catch(t){throw this.#i===e&&(this.#i=null),t}})();return this.#i=e,(await e).clone()}let e=this.#i,[t,n]=await Promise.all([e,this._detectNetwork()]);return t.chainId!==n.chainId&&(this.#a?(this.emit(`network`,n,t),this.#i===e&&(this.#i=Promise.resolve(n))):K(!1,`network changed: ${t.chainId} => ${n.chainId} `,`NETWORK_ERROR`,{event:`changed`})),t.clone()}async getFeeData(){let e=await this.getNetwork(),t=async()=>{let{_block:t,gasPrice:n,priorityFee:r}=await xv({_block:this.#g(`latest`,!1),gasPrice:(async()=>{try{return X(await this.#f({method:`getGasPrice`}),`%response`)}catch{}return null})(),priorityFee:(async()=>{try{return X(await this.#f({method:`getPriorityFee`}),`%response`)}catch{}return null})()}),i=null,a=null,o=this._wrapBlock(t,e);return o&&o.baseFeePerGas&&(a=r??BigInt(`1000000000`),i=o.baseFeePerGas*jk+a),new tO(n,i,a)},n=e.getPlugin(`org.ethers.plugins.network.FetchUrlFeeDataPlugin`);if(n){let e=new Dy(n.url),r=await n.processFunc(t,this,e);return new tO(r.gasPrice,r.maxFeePerGas,r.maxPriorityFeePerGas)}return await t()}async estimateGas(e){let t=this._getTransactionRequest(e);return Nk(t)&&(t=await t),X(await this.#f({method:`estimateGas`,transaction:t}),`%response`)}async#p(e,t,n){K(n<Mk,`CCIP read exceeded maximum redirections`,`OFFCHAIN_FAULT`,{reason:`TOO_MANY_REDIRECTS`,transaction:Object.assign({},e,{blockTag:t,enableCcipRead:!0})});let r=nO(e);try{return Y(await this._perform({method:`call`,transaction:r,blockTag:t}))}catch(e){if(!this.disableCcipRead&&wv(e)&&e.data&&n>=0&&t===`latest`&&r.to!=null&&Lv(e.data,0,4)===`0x556f1830`){let i=e.data,a=await BC(r.to,this),o;try{o=Yk(Lv(e.data,4))}catch(e){K(!1,e.message,`OFFCHAIN_FAULT`,{reason:`BAD_DATA`,transaction:r,info:{data:i}})}K(o.sender.toLowerCase()===a.toLowerCase(),`CCIP Read sender mismatch`,`CALL_EXCEPTION`,{action:`call`,data:i,reason:`OffchainLookup`,transaction:r,invocation:null,revert:{signature:`OffchainLookup(address,string[],bytes,bytes4,bytes)`,name:`OffchainLookup`,args:o.errorArgs}});let s=await this.ccipReadFetch(r,o.calldata,o.urls);K(s!=null,`CCIP Read failed to fetch data`,`OFFCHAIN_FAULT`,{reason:`FETCH_FAILED`,transaction:r,info:{data:e.data,errorArgs:o.errorArgs}});let c={to:a,data:Fv([o.selector,qk([s,o.extraData])])};this.emit(`debug`,{action:`sendCcipReadCall`,transaction:c});try{let e=await this.#p(c,t,n+1);return this.emit(`debug`,{action:`receiveCcipReadCallResult`,transaction:Object.assign({},c),result:e}),e}catch(e){throw this.emit(`debug`,{action:`receiveCcipReadCallError`,transaction:Object.assign({},c),error:e}),e}}throw e}}async#m(e){let{value:t}=await xv({network:this.getNetwork(),value:e});return t}async call(e){let{tx:t,blockTag:n}=await xv({tx:this._getTransactionRequest(e),blockTag:this._getBlockTag(e.blockTag)});return await this.#m(this.#p(t,n,e.enableCcipRead?0:-1))}async#h(e,t,n){let r=this._getAddress(t),i=this._getBlockTag(n);return(typeof r!=`string`||typeof i!=`string`)&&([r,i]=await Promise.all([r,i])),await this.#m(this.#f(Object.assign(e,{address:r,blockTag:i})))}async getBalance(e,t){return X(await this.#h({method:`getBalance`},e,t),`%response`)}async getTransactionCount(e,t){return Z(await this.#h({method:`getTransactionCount`},e,t),`%response`)}async getCode(e,t){return Y(await this.#h({method:`getCode`},e,t))}async getStorage(e,t,n){let r=X(t,`position`);return Y(await this.#h({method:`getStorage`,position:r},e,n))}async broadcastTransaction(e){let{blockNumber:t,hash:n,network:r}=await xv({blockNumber:this.getBlockNumber(),hash:this._perform({method:`broadcastTransaction`,signedTransaction:e}),network:this.getNetwork()}),i=Ww.from(e);if(i.hash!==n)throw Error(`@TODO: the returned hash did not match`);return this._wrapTransactionResponse(i,r).replaceableTransaction(t)}async#g(e,t){if(Mv(e,32))return await this.#f({method:`getBlock`,blockHash:e,includeTransactions:t});let n=this._getBlockTag(e);return typeof n!=`string`&&(n=await n),await this.#f({method:`getBlock`,blockTag:n,includeTransactions:t})}async getBlock(e,t){let{network:n,params:r}=await xv({network:this.getNetwork(),params:this.#g(e,!!t)});return r==null?null:this._wrapBlock(r,n)}async getTransaction(e){let{network:t,params:n}=await xv({network:this.getNetwork(),params:this.#f({method:`getTransaction`,hash:e})});return n==null?null:this._wrapTransactionResponse(n,t)}async getTransactionReceipt(e){let{network:t,params:n}=await xv({network:this.getNetwork(),params:this.#f({method:`getTransactionReceipt`,hash:e})});if(n==null)return null;if(n.gasPrice==null&&n.effectiveGasPrice==null){let t=await this.#f({method:`getTransaction`,hash:e});if(t==null)throw Error(`report this; could not find tx or effectiveGasPrice`);n.effectiveGasPrice=t.gasPrice}return this._wrapTransactionReceipt(n,t)}async getTransactionResult(e){let{result:t}=await xv({network:this.getNetwork(),result:this.#f({method:`getTransactionResult`,hash:e})});return t==null?null:Y(t)}async getLogs(e){let t=this._getFilter(e);Nk(t)&&(t=await t);let{network:n,params:r}=await xv({network:this.getNetwork(),params:this.#f({method:`getLogs`,filter:t})});return r.map(e=>this._wrapLog(e,n))}_getProvider(e){K(!1,`provider cannot connect to target network`,`UNSUPPORTED_OPERATION`,{operation:`_getProvider()`})}async getResolver(e){return await XO.fromName(this,e)}async getAvatar(e){let t=await this.getResolver(e);return t?await t.getAvatar():null}async resolveName(e){let t=await this.getResolver(e);return t?await t.getAddress():null}async lookupAddress(e){e=IC(e);let t=kE(e.substring(2).toLowerCase()+`.addr.reverse`);try{let n=await new GO(await XO.getEnsAddress(this),[`function resolver(bytes32) view returns (address)`],this).resolver(t);if(n==null||n===`0x0000000000000000000000000000000000000000`)return null;let r=await new GO(n,[`function name(bytes32) view returns (string)`],this).name(t);return await this.resolveName(r)===e?r:null}catch(e){if(Cv(e,`BAD_DATA`)&&e.value===`0x`||Cv(e,`CALL_EXCEPTION`))return null;throw e}return null}async waitForTransaction(e,t,n){let r=t??1;return r===0?this.getTransactionReceipt(e):new Promise(async(t,i)=>{let a=null,o=(async n=>{try{let i=await this.getTransactionReceipt(e);if(i!=null&&n-i.blockNumber+1>=r){t(i),a&&=(clearTimeout(a),null);return}}catch(e){console.log(`EEE`,e)}this.once(`block`,o)});n!=null&&(a=setTimeout(()=>{a!=null&&(a=null,this.off(`block`,o),i(Tv(`timeout`,`TIMEOUT`,{reason:`timeout`})))},n)),o(await this.getBlockNumber())})}async waitForBlock(e){K(!1,`not implemented yet`,`NOT_IMPLEMENTED`,{operation:`waitForBlock`})}_clearTimeout(e){let t=this.#l.get(e);t&&(t.timer&&clearTimeout(t.timer),this.#l.delete(e))}_setTimeout(e,t){t??=0;let n=this.#c++,r=()=>{this.#l.delete(n),e()};if(this.paused)this.#l.set(n,{timer:null,func:r,time:t});else{let e=setTimeout(r,t);this.#l.set(n,{timer:e,func:r,time:zk()})}return n}_forEachSubscriber(e){for(let t of this.#e.values())e(t.subscriber)}_getSubscriber(e){switch(e.type){case`debug`:case`error`:case`network`:return new Fk(e.type);case`block`:{let e=new Tk(this);return e.pollingInterval=this.pollingInterval,e}case`safe`:case`finalized`:return new Dk(this,e.type);case`event`:return new Ak(this,e.filter);case`transaction`:return new kk(this,e.hash);case`orphan`:return new Ok(this,e.filter)}throw Error(`unsupported event: ${e.type}`)}_recoverSubscriber(e,t){for(let n of this.#e.values())if(n.subscriber===e){n.started&&n.subscriber.stop(),n.subscriber=t,n.started&&t.start(),this.#n!=null&&t.pause(this.#n);break}}async#_(e,t){let n=await Rk(e,this);return n.type===`event`&&t&&t.length>0&&t[0].removed===!0&&(n=await Rk({orphan:`drop-log`,log:t[0]},this)),this.#e.get(n.tag)||null}async#v(e){let t=await Rk(e,this),n=t.tag,r=this.#e.get(n);return r||(r={subscriber:this._getSubscriber(t),tag:n,addressableMap:new WeakMap,nameMap:new Map,started:!1,listeners:[]},this.#e.set(n,r)),r}async on(e,t){let n=await this.#v(e);return n.listeners.push({listener:t,once:!1}),n.started||(n.subscriber.start(),n.started=!0,this.#n!=null&&n.subscriber.pause(this.#n)),this}async once(e,t){let n=await this.#v(e);return n.listeners.push({listener:t,once:!0}),n.started||(n.subscriber.start(),n.started=!0,this.#n!=null&&n.subscriber.pause(this.#n)),this}async emit(e,...t){let n=await this.#_(e,t);if(!n||n.listeners.length===0)return!1;let r=n.listeners.length;return n.listeners=n.listeners.filter(({listener:n,once:r})=>{let i=new ay(this,r?null:n,e);try{n.call(this,...t,i)}catch{}return!r}),n.listeners.length===0&&(n.started&&n.subscriber.stop(),this.#e.delete(n.tag)),r>0}async listenerCount(e){if(e){let t=await this.#_(e);return t?t.listeners.length:0}let t=0;for(let{listeners:e}of this.#e.values())t+=e.length;return t}async listeners(e){if(e){let t=await this.#_(e);return t?t.listeners.map(({listener:e})=>e):[]}let t=[];for(let{listeners:e}of this.#e.values())t=t.concat(e.map(({listener:e})=>e));return t}async off(e,t){let n=await this.#_(e);if(!n)return this;if(t){let e=n.listeners.map(({listener:e})=>e).indexOf(t);e>=0&&n.listeners.splice(e,1)}return(!t||n.listeners.length===0)&&(n.started&&n.subscriber.stop(),this.#e.delete(n.tag)),this}async removeAllListeners(e){if(e){let{tag:t,started:n,subscriber:r}=await this.#v(e);n&&r.stop(),this.#e.delete(t)}else for(let[e,{started:t,subscriber:n}]of this.#e)t&&n.stop(),this.#e.delete(e);return this}async addListener(e,t){return await this.on(e,t)}async removeListener(e,t){return this.off(e,t)}get destroyed(){return this.#r}destroy(){this.removeAllListeners();for(let e of this.#l.keys())this._clearTimeout(e);this.#r=!0}get paused(){return this.#n!=null}set paused(e){!!e!==this.paused&&(this.paused?this.resume():this.pause(!1))}pause(e){if(this.#s=-1,this.#n!=null){if(this.#n==!!e)return;K(!1,`cannot change pause type; resume first`,`UNSUPPORTED_OPERATION`,{operation:`pause`})}this._forEachSubscriber(t=>t.pause(e)),this.#n=!!e;for(let e of this.#l.values())e.timer&&clearTimeout(e.timer),e.time=zk()-e.time}resume(){if(this.#n!=null){this._forEachSubscriber(e=>e.resume()),this.#n=null;for(let e of this.#l.values()){let t=e.time;t<0&&(t=0),e.time=zk(),setTimeout(e.func,t)}}}};function Hk(e,t){try{let n=Uk(e,t);if(n)return py(n)}catch{}return null}function Uk(e,t){if(e===`0x`)return null;try{let n=Z(Lv(e,t,t+32)),r=Z(Lv(e,n,n+32));return Lv(e,n+32,n+32+r)}catch{}return null}function Wk(e){let t=Qv(e);if(t.length>32)throw Error(`internal; should not happen`);let n=new Uint8Array(32);return n.set(t,32-t.length),n}function Gk(e){if(e.length%32==0)return e;let t=new Uint8Array(Math.ceil(e.length/32)*32);return t.set(e),t}var Kk=new Uint8Array([]);function qk(e){let t=[],n=0;for(let r=0;r<e.length;r++)t.push(Kk),n+=32;for(let r=0;r<e.length;r++){let i=J(e[r]);t[r]=Wk(n),t.push(Wk(i.length)),t.push(Gk(i)),n+=32+Math.ceil(i.length/32)*32}return Fv(t)}var Jk=`0x0000000000000000000000000000000000000000000000000000000000000000`;function Yk(e){let t={sender:``,urls:[],calldata:``,selector:``,extraData:``,errorArgs:[]};K(Iv(e)>=160,`insufficient OffchainLookup data`,`OFFCHAIN_FAULT`,{reason:`insufficient OffchainLookup data`});let n=Lv(e,0,32);K(Lv(n,0,12)===Lv(Jk,0,12),`corrupt OffchainLookup sender`,`OFFCHAIN_FAULT`,{reason:`corrupt OffchainLookup sender`}),t.sender=Lv(n,12);try{let n=[],r=Z(Lv(e,32,64)),i=Z(Lv(e,r,r+32)),a=Lv(e,r+32);for(let e=0;e<i;e++){let t=Hk(a,e*32);if(t==null)throw Error(`abort`);n.push(t)}t.urls=n}catch{K(!1,`corrupt OffchainLookup urls`,`OFFCHAIN_FAULT`,{reason:`corrupt OffchainLookup urls`})}try{let n=Uk(e,64);if(n==null)throw Error(`abort`);t.calldata=n}catch{K(!1,`corrupt OffchainLookup calldata`,`OFFCHAIN_FAULT`,{reason:`corrupt OffchainLookup calldata`})}K(Lv(e,100,128)===Lv(Jk,0,28),`corrupt OffchainLookup callbaackSelector`,`OFFCHAIN_FAULT`,{reason:`corrupt OffchainLookup callbaackSelector`}),t.selector=Lv(e,96,100);try{let n=Uk(e,128);if(n==null)throw Error(`abort`);t.extraData=n}catch{K(!1,`corrupt OffchainLookup extraData`,`OFFCHAIN_FAULT`,{reason:`corrupt OffchainLookup extraData`})}return t.errorArgs=`sender,urls,calldata,selector,extraData`.split(/,/).map(e=>t[e]),t}function Xk(e,t){if(e.provider)return e.provider;K(!1,`missing provider`,`UNSUPPORTED_OPERATION`,{operation:t})}async function Zk(e,t){let n=nO(t);if(n.to!=null&&(n.to=BC(n.to,e)),n.from!=null){let t=n.from;n.from=Promise.all([e.getAddress(),BC(t,e)]).then(([e,t])=>(q(e.toLowerCase()===t.toLowerCase(),`transaction from mismatch`,`tx.from`,t),e))}else n.from=e.getAddress();return await xv(n)}var Qk=class{provider;constructor(e){G(this,{provider:e||null})}async getNonce(e){return Xk(this,`getTransactionCount`).getTransactionCount(await this.getAddress(),e)}async populateCall(e){return await Zk(this,e)}async populateTransaction(e){let t=Xk(this,`populateTransaction`),n=await Zk(this,e);n.nonce??=await this.getNonce(`pending`),n.gasLimit??=await this.estimateGas(n);let r=await this.provider.getNetwork();n.chainId==null?n.chainId=r.chainId:q(X(n.chainId)===r.chainId,`transaction chainId mismatch`,`tx.chainId`,e.chainId);let i=n.maxFeePerGas!=null||n.maxPriorityFeePerGas!=null;if(n.gasPrice!=null&&(n.type===2||i)?q(!1,`eip-1559 transaction do not support gasPrice`,`tx`,e):(n.type===0||n.type===1)&&i&&q(!1,`pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas`,`tx`,e),(n.type===2||n.type==null)&&n.maxFeePerGas!=null&&n.maxPriorityFeePerGas!=null)n.type=2;else if(n.type===0||n.type===1){let e=await t.getFeeData();K(e.gasPrice!=null,`network does not support gasPrice`,`UNSUPPORTED_OPERATION`,{operation:`getGasPrice`}),n.gasPrice??=e.gasPrice}else{let e=await t.getFeeData();if(n.type==null)if(e.maxFeePerGas!=null&&e.maxPriorityFeePerGas!=null)if(n.authorizationList&&n.authorizationList.length?n.type=4:n.type=2,n.gasPrice!=null){let e=n.gasPrice;delete n.gasPrice,n.maxFeePerGas=e,n.maxPriorityFeePerGas=e}else n.maxFeePerGas??=e.maxFeePerGas,n.maxPriorityFeePerGas??=e.maxPriorityFeePerGas;else e.gasPrice==null?K(!1,`failed to get consistent fee data`,`UNSUPPORTED_OPERATION`,{operation:`signer.getFeeData`}):(K(!i,`network does not support EIP-1559`,`UNSUPPORTED_OPERATION`,{operation:`populateTransaction`}),n.gasPrice??=e.gasPrice,n.type=0);else (n.type===2||n.type===3||n.type===4)&&(n.maxFeePerGas??=e.maxFeePerGas,n.maxPriorityFeePerGas??=e.maxPriorityFeePerGas)}return await xv(n)}async populateAuthorization(e){let t=Object.assign({},e);return t.chainId??=(await Xk(this,`getNetwork`).getNetwork()).chainId,t.nonce??=await this.getNonce(),t}async estimateGas(e){return Xk(this,`estimateGas`).estimateGas(await this.populateCall(e))}async call(e){return Xk(this,`call`).call(await this.populateCall(e))}async resolveName(e){return await Xk(this,`resolveName`).resolveName(e)}async sendTransaction(e){let t=Xk(this,`sendTransaction`),n=await this.populateTransaction(e);delete n.from;let r=Ww.from(n);return await t.broadcastTransaction(await this.signTransaction(r))}authorize(e){K(!1,`authorization not implemented for this signer`,`UNSUPPORTED_OPERATION`,{operation:`authorize`})}};function $k(e){return JSON.parse(JSON.stringify(e))}var eA=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e,this.#t=null,this.#n=this.#o.bind(this),this.#r=!1,this.#i=null,this.#a=!1}_subscribe(e){throw Error(`subclasses must override this`)}_emitResults(e,t){throw Error(`subclasses must override this`)}_recover(e){throw Error(`subclasses must override this`)}async#o(e){try{this.#t??=this._subscribe(this.#e);let e=null;try{e=await this.#t}catch(e){if(!Cv(e,`UNSUPPORTED_OPERATION`)||e.operation!==`eth_newFilter`)throw e}if(e==null){this.#t=null,this.#e._recoverSubscriber(this,this._recover(this.#e));return}let t=await this.#e.getNetwork();if(this.#i||=t,this.#i.chainId!==t.chainId)throw Error(`chaid changed`);if(this.#a)return;let n=await this.#e.send(`eth_getFilterChanges`,[e]);await this._emitResults(this.#e,n)}catch(e){console.log(`@TODO`,e)}this.#e.once(`block`,this.#n)}#s(){let e=this.#t;e&&(this.#t=null,e.then(e=>{this.#e.destroyed||this.#e.send(`eth_uninstallFilter`,[e])}))}start(){this.#r||(this.#r=!0,this.#o(-2))}stop(){this.#r&&(this.#r=!1,this.#a=!0,this.#s(),this.#e.off(`block`,this.#n))}pause(e){e&&this.#s(),this.#e.off(`block`,this.#n)}resume(){this.start()}},tA=class extends eA{#e;constructor(e,t){super(e),this.#e=$k(t)}_recover(e){return new Ak(e,this.#e)}async _subscribe(e){return await e.send(`eth_newFilter`,[this.#e])}async _emitResults(e,t){for(let n of t)e.emit(this.#e,e._wrapLog(n,e._network))}},nA=class extends eA{async _subscribe(e){return await e.send(`eth_newPendingTransactionFilter`,[])}async _emitResults(e,t){for(let n of t)e.emit(`pending`,n)}},rA=`bigint,boolean,function,number,string,symbol`.split(/,/g);function iA(e){if(e==null||rA.indexOf(typeof e)>=0||typeof e.getAddress==`function`)return e;if(Array.isArray(e))return e.map(iA);if(typeof e==`object`)return Object.keys(e).reduce((t,n)=>(t[n]=e[n],t),{});throw Error(`should not happen: ${e} (${typeof e})`)}function aA(e){return new Promise(t=>{setTimeout(t,e)})}function oA(e){return e&&e.toLowerCase()}function sA(e){return e&&typeof e.pollingInterval==`number`}var cA={polling:!1,staticNetwork:null,batchStallTime:10,batchMaxSize:1<<20,batchMaxCount:100,cacheTimeout:250,pollingInterval:4e3},lA=class extends Qk{address;constructor(e,t){super(e),t=IC(t),G(this,{address:t})}connect(e){K(!1,`cannot reconnect JsonRpcSigner`,`UNSUPPORTED_OPERATION`,{operation:`signer.connect`})}async getAddress(){return this.address}async populateTransaction(e){return await this.populateCall(e)}async sendUncheckedTransaction(e){let t=iA(e),n=[];if(t.from){let r=t.from;n.push((async()=>{let n=await BC(r,this.provider);q(n!=null&&n.toLowerCase()===this.address.toLowerCase(),`from address mismatch`,`transaction`,e),t.from=n})())}else t.from=this.address;if(t.gasLimit??n.push((async()=>{t.gasLimit=await this.provider.estimateGas({...t,from:this.address})})()),t.to!=null){let e=t.to;n.push((async()=>{t.to=await BC(e,this.provider)})())}n.length&&await Promise.all(n);let r=this.provider.getRpcTransaction(t);return this.provider.send(`eth_sendTransaction`,[r])}async sendTransaction(e){let t=await this.provider.getBlockNumber(),n=await this.sendUncheckedTransaction(e);return await new Promise((e,r)=>{let i=[1e3,100],a=0,o=async()=>{try{let r=await this.provider.getTransaction(n);if(r!=null){e(r.replaceableTransaction(t));return}}catch(e){if(Cv(e,`CANCELLED`)||Cv(e,`BAD_DATA`)||Cv(e,`NETWORK_ERROR`)||Cv(e,`UNSUPPORTED_OPERATION`)){e.info??={},e.info.sendTransactionHash=n,r(e);return}if(Cv(e,`INVALID_ARGUMENT`)&&(a++,e.info??={},e.info.sendTransactionHash=n,a>10)){r(e);return}this.provider.emit(`error`,Tv(`failed to fetch transation after sending (will try again)`,`UNKNOWN_ERROR`,{error:e}))}this.provider._setTimeout(()=>{o()},i.pop()||4e3)};o()})}async signTransaction(e){let t=iA(e);if(t.from){let n=await BC(t.from,this.provider);q(n!=null&&n.toLowerCase()===this.address.toLowerCase(),`from address mismatch`,`transaction`,e),t.from=n}else t.from=this.address;let n=this.provider.getRpcTransaction(t);return await this.provider.send(`eth_signTransaction`,[n])}async signMessage(e){let t=typeof e==`string`?dy(e):e;return await this.provider.send(`personal_sign`,[Y(t),this.address.toLowerCase()])}async signTypedData(e,t,n){let r=iA(n),i=await KE.resolveNames(e,t,r,async e=>{let t=await BC(e);return q(t!=null,`TypedData does not support null address`,`value`,e),t});return await this.provider.send(`eth_signTypedData_v4`,[this.address.toLowerCase(),JSON.stringify(KE.getPayload(i.domain,t,i.value))])}async unlock(e){return this.provider.send(`personal_unlockAccount`,[this.address.toLowerCase(),e,null])}async _legacySignMessage(e){let t=typeof e==`string`?dy(e):e;return await this.provider.send(`eth_sign`,[this.address.toLowerCase(),Y(t)])}},uA=class extends Vk{#e;#t;#n;#r;#i;#a;#o;#s(){if(this.#r)return;let e=this._getOption(`batchMaxCount`)===1?0:this._getOption(`batchStallTime`);this.#r=setTimeout(()=>{this.#r=null;let e=this.#n;for(this.#n=[];e.length;){let t=[e.shift()];for(;e.length&&t.length!==this.#e.batchMaxCount;)if(t.push(e.shift()),JSON.stringify(t.map(e=>e.payload)).length>this.#e.batchMaxSize){e.unshift(t.pop());break}(async()=>{let e=t.length===1?t[0].payload:t.map(e=>e.payload);this.emit(`debug`,{action:`sendRpcPayload`,payload:e});try{let n=await this._send(e);this.emit(`debug`,{action:`receiveRpcResult`,result:n});for(let{resolve:e,reject:r,payload:i}of t){if(this.destroyed){r(Tv(`provider destroyed; cancelled request`,`UNSUPPORTED_OPERATION`,{operation:i.method}));continue}let t=n.filter(e=>e.id===i.id)[0];if(t==null){let e=Tv(`missing response for request`,`BAD_DATA`,{value:n,info:{payload:i}});this.emit(`error`,e),r(e);continue}if(`error`in t){r(this.getRpcError(i,t));continue}e(t.result)}}catch(e){this.emit(`debug`,{action:`receiveRpcError`,error:e});for(let{reject:n}of t)n(e)}})()}},e)}constructor(e,t){super(e,t),this.#t=1,this.#e=Object.assign({},cA,t||{}),this.#n=[],this.#r=null,this.#a=null,this.#o=null;{let e=null;this.#i={promise:new Promise(t=>{e=t}),resolve:e}}let n=this._getOption(`staticNetwork`);typeof n==`boolean`?(q(!n||e!==`any`,`staticNetwork cannot be used on special network 'any'`,`options`,t),n&&e!=null&&(this.#a=yk.from(e))):n&&(q(e==null||n.matches(e),`staticNetwork MUST match network object`,`options`,t),this.#a=n)}_getOption(e){return this.#e[e]}get _network(){return K(this.#a,`network is not available yet`,`NETWORK_ERROR`),this.#a}async _perform(e){if(e.method===`call`||e.method===`estimateGas`){let t=e.transaction;if(t&&t.type!=null&&X(t.type)&&t.maxFeePerGas==null&&t.maxPriorityFeePerGas==null){let n=await this.getFeeData();n.maxFeePerGas==null&&n.maxPriorityFeePerGas==null&&(e=Object.assign({},e,{transaction:Object.assign({},t,{type:void 0})}))}}let t=this.getRpcRequest(e);return t==null?super._perform(e):await this.send(t.method,t.args)}async _detectNetwork(){let e=this._getOption(`staticNetwork`);if(e)if(e===!0){if(this.#a)return this.#a}else return e;return this.#o?await this.#o:this.ready?(this.#o=(async()=>{try{let e=yk.from(X(await this.send(`eth_chainId`,[])));return this.#o=null,e}catch(e){throw this.#o=null,e}})(),await this.#o):(this.#o=(async()=>{let e={id:this.#t++,method:`eth_chainId`,params:[],jsonrpc:`2.0`};this.emit(`debug`,{action:`sendRpcPayload`,payload:e});let t;try{t=(await this._send(e))[0],this.#o=null}catch(e){throw this.#o=null,this.emit(`debug`,{action:`receiveRpcError`,error:e}),e}if(this.emit(`debug`,{action:`receiveRpcResult`,result:t}),`result`in t)return yk.from(X(t.result));throw this.getRpcError(e,t)})(),await this.#o)}_start(){this.#i==null||this.#i.resolve==null||(this.#i.resolve(),this.#i=null,(async()=>{for(;this.#a==null&&!this.destroyed;)try{this.#a=await this._detectNetwork()}catch(e){if(this.destroyed)break;console.log(`JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)`),this.emit(`error`,Tv(`failed to bootstrap network detection`,`NETWORK_ERROR`,{event:`initial-network-discovery`,info:{error:e}})),await aA(1e3)}this.#s()})())}async _waitUntilReady(){if(this.#i!=null)return await this.#i.promise}_getSubscriber(e){return e.type===`pending`?new nA(this):e.type===`event`?this._getOption(`polling`)?new Ak(this,e.filter):new tA(this,e.filter):e.type===`orphan`&&e.filter.orphan===`drop-log`?new Fk(`orphan`):super._getSubscriber(e)}get ready(){return this.#i==null}getRpcTransaction(e){let t={};return[`chainId`,`gasLimit`,`gasPrice`,`type`,`maxFeePerGas`,`maxPriorityFeePerGas`,`nonce`,`value`].forEach(n=>{if(e[n]==null)return;let r=n;n===`gasLimit`&&(r=`gas`),t[r]=$v(X(e[n],`tx.${n}`))}),[`from`,`to`,`data`].forEach(n=>{e[n]!=null&&(t[n]=Y(e[n]))}),e.accessList&&(t.accessList=lw(e.accessList)),e.blobVersionedHashes&&(t.blobVersionedHashes=e.blobVersionedHashes.map(e=>e.toLowerCase())),e.authorizationList&&(t.authorizationList=e.authorizationList.map(e=>{let t=uw(e);return{address:t.address,nonce:$v(t.nonce),chainId:$v(t.chainId),yParity:$v(t.signature.yParity),r:$v(t.signature.r),s:$v(t.signature.s)}})),t}getRpcRequest(e){switch(e.method){case`chainId`:return{method:`eth_chainId`,args:[]};case`getBlockNumber`:return{method:`eth_blockNumber`,args:[]};case`getGasPrice`:return{method:`eth_gasPrice`,args:[]};case`getPriorityFee`:return{method:`eth_maxPriorityFeePerGas`,args:[]};case`getBalance`:return{method:`eth_getBalance`,args:[oA(e.address),e.blockTag]};case`getTransactionCount`:return{method:`eth_getTransactionCount`,args:[oA(e.address),e.blockTag]};case`getCode`:return{method:`eth_getCode`,args:[oA(e.address),e.blockTag]};case`getStorage`:return{method:`eth_getStorageAt`,args:[oA(e.address),`0x`+e.position.toString(16),e.blockTag]};case`broadcastTransaction`:return{method:`eth_sendRawTransaction`,args:[e.signedTransaction]};case`getBlock`:if(`blockTag`in e)return{method:`eth_getBlockByNumber`,args:[e.blockTag,!!e.includeTransactions]};if(`blockHash`in e)return{method:`eth_getBlockByHash`,args:[e.blockHash,!!e.includeTransactions]};break;case`getTransaction`:return{method:`eth_getTransactionByHash`,args:[e.hash]};case`getTransactionReceipt`:return{method:`eth_getTransactionReceipt`,args:[e.hash]};case`call`:return{method:`eth_call`,args:[this.getRpcTransaction(e.transaction),e.blockTag]};case`estimateGas`:return{method:`eth_estimateGas`,args:[this.getRpcTransaction(e.transaction)]};case`getLogs`:return e.filter&&e.filter.address!=null&&(Array.isArray(e.filter.address)?e.filter.address=e.filter.address.map(oA):e.filter.address=oA(e.filter.address)),{method:`eth_getLogs`,args:[e.filter]}}return null}getRpcError(e,t){let{method:n}=e,{error:r}=t;if(n===`eth_estimateGas`&&r.message){let t=r.message;if(!t.match(/revert/i)&&t.match(/insufficient funds/i))return Tv(`insufficient funds`,`INSUFFICIENT_FUNDS`,{transaction:e.params[0],info:{payload:e,error:r}});if(t.match(/nonce/i)&&t.match(/too low/i))return Tv(`nonce has already been used`,`NONCE_EXPIRED`,{transaction:e.params[0],info:{payload:e,error:r}})}if(n===`eth_call`||n===`eth_estimateGas`){let t=pA(r),i=WD.getBuiltinCallException(n===`eth_call`?`call`:`estimateGas`,e.params[0],t?t.data:null);return i.info={error:r,payload:e},i}let i=JSON.stringify(hA(r));if(typeof r.message==`string`&&r.message.match(/user denied|ethers-user-denied/i))return Tv(`user rejected action`,`ACTION_REJECTED`,{action:{eth_sign:`signMessage`,personal_sign:`signMessage`,eth_signTypedData_v4:`signTypedData`,eth_signTransaction:`signTransaction`,eth_sendTransaction:`sendTransaction`,eth_requestAccounts:`requestAccess`,wallet_requestAccounts:`requestAccess`}[n]||`unknown`,reason:`rejected`,info:{payload:e,error:r}});if(n===`eth_sendRawTransaction`||n===`eth_sendTransaction`){let t=e.params[0];if(i.match(/insufficient funds|base fee exceeds gas limit/i))return Tv(`insufficient funds for intrinsic transaction cost`,`INSUFFICIENT_FUNDS`,{transaction:t,info:{error:r}});if(i.match(/nonce/i)&&i.match(/too low/i))return Tv(`nonce has already been used`,`NONCE_EXPIRED`,{transaction:t,info:{error:r}});if(i.match(/replacement transaction/i)&&i.match(/underpriced/i))return Tv(`replacement fee too low`,`REPLACEMENT_UNDERPRICED`,{transaction:t,info:{error:r}});if(i.match(/only replay-protected/i))return Tv(`legacy pre-eip-155 transactions not supported`,`UNSUPPORTED_OPERATION`,{operation:n,info:{transaction:t,info:{error:r}}})}let a=!!i.match(/the method .* does not exist/i);return a||r&&r.details&&r.details.startsWith(`Unauthorized method:`)&&(a=!0),a?Tv(`unsupported operation`,`UNSUPPORTED_OPERATION`,{operation:e.method,info:{error:r,payload:e}}):Tv(`could not coalesce error`,`UNKNOWN_ERROR`,{error:r,payload:e})}send(e,t){if(this.destroyed)return Promise.reject(Tv(`provider destroyed; cancelled request`,`UNSUPPORTED_OPERATION`,{operation:e}));let n=this.#t++,r=new Promise((r,i)=>{this.#n.push({resolve:r,reject:i,payload:{method:e,params:t,id:n,jsonrpc:`2.0`}})});return this.#s(),r}async getSigner(e){e??=0;let t=this.send(`eth_accounts`,[]);if(typeof e==`number`){let n=await t;if(e>=n.length)throw Error(`no such account`);return new lA(this,n[e])}let{accounts:n}=await xv({network:this.getNetwork(),accounts:t});e=IC(e);for(let t of n)if(IC(t)===e)return new lA(this,e);throw Error(`invalid account`)}async listAccounts(){return(await this.send(`eth_accounts`,[])).map(e=>new lA(this,e))}destroy(){this.#r&&=(clearTimeout(this.#r),null);for(let{payload:e,reject:t}of this.#n)t(Tv(`provider destroyed; cancelled request`,`UNSUPPORTED_OPERATION`,{operation:e.method}));this.#n=[],super.destroy()}},dA=class extends uA{#e;constructor(e,t){super(e,t);let n=this._getOption(`pollingInterval`);n??=cA.pollingInterval,this.#e=n}_getSubscriber(e){let t=super._getSubscriber(e);return sA(t)&&(t.pollingInterval=this.#e),t}get pollingInterval(){return this.#e}set pollingInterval(e){if(!Number.isInteger(e)||e<0)throw Error(`invalid interval`);this.#e=e,this._forEachSubscriber(e=>{sA(e)&&(e.pollingInterval=this.#e)})}},fA=class extends dA{#e;constructor(e,t,n){e??=`http://localhost:8545`,super(t,n),typeof e==`string`?this.#e=new Dy(e):this.#e=e.clone()}_getConnection(){return this.#e.clone()}async send(e,t){return await this._start(),await super.send(e,t)}async _send(e){let t=this._getConnection();t.body=JSON.stringify(e),t.setHeader(`content-type`,`application/json`);let n=await t.send();n.assertOk();let r=n.bodyJson;return Array.isArray(r)||(r=[r]),r}};function pA(e){if(e==null)return null;if(typeof e.message==`string`&&e.message.match(/revert/i)&&Mv(e.data))return{message:e.message,data:e.data};if(typeof e==`object`){for(let t in e){let n=pA(e[t]);if(n)return n}return null}if(typeof e==`string`)try{return pA(JSON.parse(e))}catch{}return null}function mA(e,t){if(e!=null){if(typeof e.message==`string`&&t.push(e.message),typeof e==`object`)for(let n in e)mA(e[n],t);if(typeof e==`string`)try{return mA(JSON.parse(e),t)}catch{}}}function hA(e){let t=[];return mA(e,t),t}var gA=[`function register(string agentURI) external returns (uint256 agentId)`,`function register(string agentURI, tuple(string metadataKey, bytes metadataValue)[] metadata) external returns (uint256 agentId)`,`function register() external returns (uint256 agentId)`,`function setAgentURI(uint256 agentId, string newURI) external`,`function tokenURI(uint256 agentId) external view returns (string)`,`function setAgentWallet(uint256 agentId, address newWallet, uint256 deadline, bytes signature) external`,`function getAgentWallet(uint256 agentId) external view returns (address)`,`function unsetAgentWallet(uint256 agentId) external`,`function nonces(address owner) external view returns (uint256)`,`function DOMAIN_SEPARATOR() external view returns (bytes32)`,`function getMetadata(uint256 agentId, string metadataKey) external view returns (bytes)`,`function setMetadata(uint256 agentId, string metadataKey, bytes metadataValue) external`,`function ownerOf(uint256 tokenId) external view returns (address)`,`function balanceOf(address owner) external view returns (uint256)`,`function totalSupply() external view returns (uint256)`,`function isAgent(uint256 agentId) external view returns (bool)`,`event Registered(uint256 indexed agentId, string agentURI, address indexed owner)`,`event URIUpdated(uint256 indexed agentId, string newURI, address indexed updatedBy)`,`event WalletSet(uint256 indexed agentId, address indexed wallet)`,`event WalletUnset(uint256 indexed agentId)`,`event MetadataSet(uint256 indexed agentId, string indexed indexedMetadataKey, string metadataKey, bytes metadataValue)`,`event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)`],_A={8453:{identityRegistry:``,reputationRegistry:``,validationRegistry:``},84532:{identityRegistry:``,reputationRegistry:``,validationRegistry:``},1:{identityRegistry:``,reputationRegistry:``,validationRegistry:``}},vA={base:8453,"base-mainnet":8453,"base-sepolia":84532,ethereum:1,mainnet:1},yA={8453:`https://mainnet.base.org`,84532:`https://sepolia.base.org`,1:`https://eth.llamarpc.com`};async function bA(e,{rpcURL:t,registry:n}={}){if(!e)throw Error(`loadManifest: source required`);if(e.startsWith(`agent://`))return xA(e,{rpcURL:t,registryOverride:n});if(e.startsWith(`ipfs://`)||e.startsWith(`ar://`)){let t=cv(e);return CA(await SA(t),{baseURI:wA(t)})}if(e.startsWith(`http`))return CA(await SA(e),{baseURI:wA(e)});throw Error(`Unsupported manifest source: ${e}`)}async function xA(e,{rpcURL:t,registryOverride:n}){let r=e.match(/^agent:\/\/([^/]+)\/(\d+)$/);if(!r)throw Error(`Malformed agent URI: ${e}`);let[,i,a]=r,o=vA[i.toLowerCase()]||Number(i);if(!o)throw Error(`Unknown chain: ${i}`);let s=_A[o],c=n||s?.identityRegistry;if(!c)throw Error(`No registry deployed on chain ${o}. Pass registry= override.`);let l=new GO(c,gA,new fA(t||yA[o])),u=BigInt(a),d=await l.tokenURI(u);if(!d)throw Error(`Agent ${a} on chain ${o} has no URI`);let f=cv(d),p=CA(await SA(f),{baseURI:wA(f)});return p.id={...p.id,chain:i,chainId:o,registry:c,agentId:a},p}async function SA(e){let t;try{t=await fetch(e)}catch{t=await lv(e)}if(!t.ok)throw Error(`Manifest fetch failed: ${e} (${t.status})`);return t.json()}function CA(e,{baseURI:t=``}={}){if(e.spec&&e.spec.startsWith(`agent-manifest/`)){let n={...e,_baseURI:t};return n.body=n.body||{},!n.body.uri&&n.image&&(n.body.uri=n.image),n}return e.type&&e.type.includes(`eip-8004`)?{spec:`agent-manifest/0.1`,_baseURI:t,_source:`erc8004-registration`,id:{agentId:(e.registrations?.[0]||{}).agentId?.toString()},name:e.name,description:e.description,image:e.image,body:{uri:e.image,format:`gltf-binary`},brain:{provider:`none`},voice:{tts:{provider:`browser`},stt:{provider:`browser`}},skills:[],memory:{mode:`local`},tools:[`wave`,`lookAt`,`play_clip`,`setExpression`],version:`0.1.0`}:{spec:`agent-manifest/0.1`,_baseURI:t,name:e.name||`Unnamed agent`,description:e.description||``,body:{uri:e.body?.uri||e.image||e.model||``,format:e.body?.format||`gltf-binary`},brain:e.brain||{provider:`none`},voice:e.voice||{tts:{provider:`browser`},stt:{provider:`browser`}},skills:e.skills||[],memory:e.memory||{mode:`local`},tools:e.tools||[`wave`,`lookAt`,`play_clip`,`setExpression`],version:e.version||`0.1.0`}}function wA(e){let t=e.lastIndexOf(`/`);return t>=0?e.slice(0,t+1):e}async function TA(e,t){if(!e._baseURI)return null;try{let n=new URL(t,e._baseURI).href,r=await fetch(n);return r.ok?r.text():null}catch{return null}}var EA=[`inline`,`floating`,`section`,`fullscreen`],DA=`
+ :host {
+ display: block;
+ position: relative;
+ width: 100%;
+ height: 480px;
+ --agent-bubble-radius: 16px;
+ --agent-accent: #3b82f6;
+ --agent-surface: rgba(17, 24, 39, 0.92);
+ --agent-on-surface: #f9fafb;
+ --agent-chat-font: system-ui, -apple-system, sans-serif;
+ --agent-mic-glow: #22c55e;
+ --agent-shadow: 0 20px 60px rgba(0,0,0,0.3);
+ contain: layout style;
+ }
+ :host([mode="floating"]) {
+ position: fixed;
+ z-index: 2147483000;
+ width: var(--agent-width, 320px);
+ height: var(--agent-height, 420px);
+ border-radius: var(--agent-bubble-radius);
+ overflow: hidden;
+ box-shadow: var(--agent-shadow);
+ }
+ :host([mode="fullscreen"]) {
+ position: fixed;
+ inset: 0;
+ width: 100vw;
+ height: 100vh;
+ z-index: 2147483000;
+ }
+ :host([hidden]) { display: none; }
+ .stage {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ }
+ .stage canvas { display: block; }
+ .chrome {
+ position: absolute;
+ left: 12px;
+ right: 12px;
+ bottom: 12px;
+ display: flex;
+ gap: 8px;
+ align-items: flex-end;
+ pointer-events: none;
+ }
+ .chrome > * { pointer-events: auto; }
+ .chat {
+ flex: 1;
+ max-height: 40%;
+ overflow-y: auto;
+ background: var(--agent-surface);
+ color: var(--agent-on-surface);
+ font: 14px/1.4 var(--agent-chat-font);
+ border-radius: 12px;
+ padding: 10px 12px;
+ backdrop-filter: blur(12px);
+ }
+ .chat:empty { display: none; }
+ .msg { margin: 4px 0; }
+ .msg .role { opacity: 0.55; font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; }
+ .input-row {
+ display: flex;
+ gap: 6px;
+ background: var(--agent-surface);
+ border-radius: 999px;
+ padding: 4px 4px 4px 14px;
+ backdrop-filter: blur(12px);
+ flex: 1;
+ }
+ .input-row input {
+ flex: 1;
+ background: transparent;
+ border: 0;
+ color: var(--agent-on-surface);
+ font: 14px var(--agent-chat-font);
+ outline: none;
+ }
+ button.icon {
+ width: 36px;
+ height: 36px;
+ border-radius: 50%;
+ border: 0;
+ background: var(--agent-accent);
+ color: white;
+ cursor: pointer;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ }
+ button.icon.mic[data-listening="true"] { box-shadow: 0 0 0 4px var(--agent-mic-glow); }
+ .poster {
+ position: absolute;
+ inset: 0;
+ background-size: contain;
+ background-position: center;
+ background-repeat: no-repeat;
+ transition: opacity 0.4s;
+ pointer-events: none;
+ }
+ .loading {
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ transform: translate(-50%, -50%);
+ color: var(--agent-on-surface);
+ font: 14px var(--agent-chat-font);
+ background: var(--agent-surface);
+ padding: 8px 14px;
+ border-radius: 999px;
+ }
+ .error {
+ position: absolute;
+ inset: 16px;
+ display: grid;
+ place-items: center;
+ color: var(--agent-on-surface);
+ background: var(--agent-surface);
+ border-radius: 12px;
+ padding: 16px;
+ font: 14px var(--agent-chat-font);
+ }
+`,OA=class extends HTMLElement{static get observedAttributes(){return[`src`,`manifest`,`body`,`mode`,`position`,`width`,`height`,`voice`,`api-key`,`key-proxy`]}constructor(){super(),this.attachShadow({mode:`open`}),this._viewer=null,this._scene=null,this._runtime=null,this._memory=null,this._skills=null,this._manifest=null,this._mounted=!1,this._booting=!1,this._listening=!1}connectedCallback(){this._renderShell(),this._applyLayout(),this._observeViewport(),this.hasAttribute(`eager`)&&this._boot()}disconnectedCallback(){this._teardown()}attributeChangedCallback(e,t,n){this._mounted&&([`mode`,`position`,`width`,`height`].includes(e)&&this._applyLayout(),[`src`,`manifest`,`body`].includes(e)&&(this._teardown(),this._boot()))}_renderShell(){let e=document.createElement(`style`);e.textContent=DA,this.shadowRoot.appendChild(e);let t=document.createElement(`div`);t.className=`stage`,t.part=`stage`,this.shadowRoot.appendChild(t),this._stageEl=t;let n=document.createElement(`div`);n.className=`poster`,this.getAttribute(`poster`)&&(n.style.backgroundImage=`url(${this.getAttribute(`poster`)})`),this.shadowRoot.appendChild(n),this._posterEl=n;let r=document.createElement(`div`);if(r.className=`loading`,r.textContent=`Loading...`,r.hidden=!0,this.shadowRoot.appendChild(r),this._loadingEl=r,!this.hasAttribute(`kiosk`)){let e=document.createElement(`div`);e.className=`chrome`,e.part=`chrome`;let t=document.createElement(`div`);t.className=`chat`,t.part=`chat`;let n=document.createElement(`div`);n.className=`input-row`;let r=document.createElement(`input`);r.type=`text`,r.placeholder=`Say something...`,r.addEventListener(`keydown`,e=>{if(e.key===`Enter`&&r.value.trim()){let e=r.value.trim();r.value=``,this.say(e)}});let i=document.createElement(`button`);i.className=`icon mic`,i.title=`Push to talk`,i.innerHTML=`🎙`,i.addEventListener(`click`,()=>this._toggleMic()),n.appendChild(r),n.appendChild(i),e.appendChild(t),e.appendChild(n),this.shadowRoot.appendChild(e),this._chatEl=t,this._inputEl=r,this._micEl=i}}_applyLayout(){let e=this.getAttribute(`mode`)||`inline`;if(!EA.includes(e))return;if(e===`floating`){let e=this.getAttribute(`position`)||`bottom-right`,t=(this.getAttribute(`offset`)||`24px 24px`).split(/\s+/),[n,r]=[t[0],t[1]||t[0]];this.style.top=this.style.bottom=this.style.left=this.style.right=``,e.includes(`top`)?this.style.top=n:this.style.bottom=n,e.includes(`left`)?this.style.left=r:e.includes(`right`)?this.style.right=r:e.includes(`center`)&&(this.style.left=`50%`,this.style.transform=`translateX(-50%)`)}else this.style.top=this.style.bottom=this.style.left=this.style.right=this.style.transform=``;let t=this.getAttribute(`width`),n=this.getAttribute(`height`);t&&this.style.setProperty(`--agent-width`,t),n&&this.style.setProperty(`--agent-height`,n),e===`inline`&&(t&&(this.style.width=t),n&&(this.style.height=n))}_observeViewport(){if(!this.hasAttribute(`eager`)){if(typeof IntersectionObserver>`u`){this._boot();return}this._io=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(this._io.disconnect(),this._boot())}),this._io.observe(this)}}async _boot(){if(!(this._booting||this._mounted)){this._booting=!0;try{this._loadingEl.hidden=!1,this.dispatchEvent(new CustomEvent(`agent:load-progress`,{detail:{phase:`manifest`,pct:.1}}));let e=await this._resolveManifest();if(this._manifest=e,this.dispatchEvent(new CustomEvent(`agent:load-progress`,{detail:{phase:`manifest`,pct:.3}})),typeof e.brain?.instructions==`string`&&e.brain.instructions.endsWith(`.md`)){let t=await TA(e,e.brain.instructions);t&&(e.instructions=kA(t))}else e.brain?.instructions&&(e.instructions=e.brain.instructions);this.dispatchEvent(new CustomEvent(`agent:load-progress`,{detail:{phase:`body`,pct:.45}}));let t=new J_(this._stageEl,{kiosk:this.hasAttribute(`kiosk`)});this._viewer=t;let n=cv(e.body?.uri);n&&await t.load(n,``,new Map),this._scene=new dv(t),this.dispatchEvent(new CustomEvent(`agent:load-progress`,{detail:{phase:`memory`,pct:.6}}));let r=e.id?.agentId||this.getAttribute(`memory-key`)||e.name||`anon`;this._memory=await vv.load({mode:this.getAttribute(`memory`)||e.memory?.mode||`local`,namespace:r,manifestURI:e._baseURI+`manifest.json`,fetchFn:fetch.bind(globalThis)}),this.dispatchEvent(new CustomEvent(`agent:load-progress`,{detail:{phase:`skills`,pct:.75}})),this._skills=new mv({trust:this.getAttribute(`skill-trust`)||`owned-only`,ownerAddress:e.id?.owner});let i=e.skills||[];for(let t of i)try{let n=await this._skills.install(t,{bundleBase:e._baseURI});this.dispatchEvent(new CustomEvent(`skill:loaded`,{detail:{name:n.name,uri:n.uri}}))}catch(e){console.warn(`[agent-3d] skill load failed`,t,e)}this.dispatchEvent(new CustomEvent(`agent:load-progress`,{detail:{phase:`brain`,pct:.9}}));let a={apiKey:this.getAttribute(`api-key`)||void 0,proxyURL:this.getAttribute(`key-proxy`)||void 0};this._runtime=new av({manifest:e,viewer:this._scene,memory:this._memory,skills:this._skills,providerConfig:a});for(let e of[`brain:thinking`,`brain:message`,`skill:tool-called`,`voice:speech-start`,`voice:speech-end`,`voice:transcript`,`voice:listen-start`,`memory:write`])this._runtime.addEventListener(e,t=>{this.dispatchEvent(new CustomEvent(e,{detail:t.detail,bubbles:!0,composed:!0})),e===`brain:message`&&this._chatEl&&this._renderMessage(t.detail)});this._mounted=!0,this._loadingEl.hidden=!0,this._posterEl.style.opacity=`0`,this.dispatchEvent(new CustomEvent(`agent:ready`,{detail:{agent:this,manifest:e},bubbles:!0,composed:!0}))}catch(e){console.error(`[agent-3d] boot failed`,e),this._loadingEl.hidden=!0,this._showError(e),this.dispatchEvent(new CustomEvent(`agent:error`,{detail:{phase:`boot`,error:e},bubbles:!0,composed:!0}))}finally{this._booting=!1}}}async _resolveManifest(){let e=this.getAttribute(`src`),t=this.getAttribute(`manifest`),n=this.getAttribute(`body`);if(e)return bA(e,{rpcURL:this.getAttribute(`rpc-url`),registry:this.getAttribute(`registry`)});if(t)return bA(t);if(n){let e=this.getAttribute(`instructions`);return{spec:`agent-manifest/0.1`,_baseURI:``,name:this.getAttribute(`name`)||`Agent`,body:{uri:n,format:`gltf-binary`},brain:{provider:this.getAttribute(`brain`)?`anthropic`:`none`,model:this.getAttribute(`brain`)||void 0,instructions:e||`You are an embodied 3D agent.`},instructions:e||`You are an embodied 3D agent.`,voice:{tts:{provider:`browser`},stt:{provider:`browser`}},skills:(this.getAttribute(`skills`)||``).split(`,`).map(e=>e.trim()).filter(Boolean).map(e=>({uri:e})),memory:{mode:this.getAttribute(`memory`)||`local`},tools:[`wave`,`lookAt`,`play_clip`,`setExpression`,`speak`,`remember`],version:`0.1.0`}}throw Error(`<agent-3d> requires src=, manifest=, or body= attribute`)}_renderMessage({role:e,content:t}){if(!this._chatEl||!t)return;let n=document.createElement(`div`);n.className=`msg`,n.innerHTML=`<div class="role">${e}</div><div class="body"></div>`,n.querySelector(`.body`).textContent=t,this._chatEl.appendChild(n),this._chatEl.scrollTop=this._chatEl.scrollHeight}_showError(e){let t=document.createElement(`div`);t.className=`error`,t.textContent=`Couldn't load agent: ${e.message||e}`,this.shadowRoot.appendChild(t)}async _toggleMic(){if(this._runtime){if(this._listening){this._runtime.stt?.stop(),this._listening=!1,this._micEl.dataset.listening=`false`;return}this._listening=!0,this._micEl.dataset.listening=`true`;try{let e=await this._runtime.listen();e&&await this.say(e,{voice:!0})}catch(e){console.warn(`[agent-3d] listen failed`,e)}finally{this._listening=!1,this._micEl.dataset.listening=`false`}}}_teardown(){try{this._io?.disconnect()}catch{}try{this._runtime?.destroy()}catch{}try{this._viewer?.dispose?.()}catch{}this._mounted=!1,this._runtime=this._viewer=this._scene=this._memory=this._skills=null}async say(e,t={}){return this._runtime||await this._waitForReady(),this._runtime.send(e,{voice:t.voice??this.hasAttribute(`voice`)})}async ask(e,t={}){return(await this.say(e,t))?.text||``}clearConversation(){this._runtime?.clearConversation()}async wave(e){return this._scene?.playAnimationByHint(`wave`,e)}async lookAt(e){return this._scene?.lookAt(e)}async play(e,t){return this._scene?.playClipByName(e,t)}async installSkill(e){if(!this._skills)throw Error(`Agent not mounted`);return this._skills.install({uri:e})}uninstallSkill(e){return this._skills?.uninstall(e)}get skills(){return this._skills?.all()||[]}get memory(){return this._memory}get manifest(){return this._manifest}get runtime(){return this._runtime}setMode(e){this.setAttribute(`mode`,e)}setPosition(e,t){this.setAttribute(`position`,e),t&&this.setAttribute(`offset`,t)}setSize(e,t){this.setAttribute(`width`,e),this.setAttribute(`height`,t)}pause(){this._runtime?.pause()}resume(){}destroy(){this._teardown()}_waitForReady(){return this._mounted?Promise.resolve():new Promise(e=>{let t=()=>{this.removeEventListener(`agent:ready`,t),e()};this.addEventListener(`agent:ready`,t),this._booting||this._boot()})}};function kA(e){let t=e.match(/^---\n[\s\S]*?\n---\n?([\s\S]*)$/);return t?t[1]:e}customElements.get(`agent-3d`)||customElements.define(`agent-3d`,OA),e.Agent3DElement=OA,e.Memory=vv,e.Runtime=av,e.SceneController=dv,e.Skill=pv,e.SkillRegistry=mv,e.Viewer=J_,e.defineElement=(e=`agent-3d`)=>{customElements.get(e)||customElements.define(e,OA)},e.fetchRelative=TA,e.fetchWithFallback=lv,e.loadManifest=bA,e.normalize=CA,e.resolveURI=cv});
\ No newline at end of file
diff --git a/dist-lib/agent/index.html b/dist-lib/agent/index.html
new file mode 100644
index 000000000..7ef5f08d4
--- /dev/null
+++ b/dist-lib/agent/index.html
@@ -0,0 +1,239 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <title>Agent Home — 3D Agent</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="description" content="An embodied 3D AI agent — body, place, identity, memory." />
+ <meta name="theme-color" content="#000000" />
+
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ <link rel="stylesheet" href="/style.css" />
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500&display=swap" rel="stylesheet" />
+
+ <style>
+ body {
+ overflow: auto;
+ display: flex;
+ flex-direction: column;
+ }
+
+ .agent-page-header {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ padding: 1rem 1.618rem;
+ border-bottom: 1px solid rgba(255,255,255,0.06);
+ }
+
+ .agent-page-header a {
+ color: rgba(255,255,255,0.4);
+ text-decoration: none;
+ font-size: 0.764rem;
+ }
+
+ .agent-page-header a:hover {
+ color: rgba(255,255,255,0.8);
+ }
+
+ .agent-page-hero {
+ max-width: 520px;
+ margin: 4rem auto 2rem;
+ padding: 0 1rem;
+ text-align: center;
+ }
+
+ .agent-page-title {
+ font-size: 1.618rem;
+ font-weight: 300;
+ color: #e5e5e5;
+ letter-spacing: -0.02em;
+ margin: 0 0 0.618rem;
+ }
+
+ .agent-page-subtitle {
+ font-size: 0.764rem;
+ color: rgba(255,255,255,0.35);
+ line-height: 1.618;
+ }
+
+ .agent-page-card-wrap {
+ max-width: 420px;
+ margin: 0 auto;
+ padding: 0 1rem 4rem;
+ }
+
+ /* Expand the timeline on standalone page */
+ .agent-page-card-wrap .agent-home-timeline {
+ max-height: 320px;
+ }
+
+ /* Expand the panel to fill the card */
+ .agent-page-card-wrap .agent-home-panel {
+ background: rgba(12, 12, 18, 0.98);
+ border: 1px solid rgba(255,255,255,0.08);
+ border-radius: 12px;
+ }
+
+ .agent-embed-hint {
+ max-width: 420px;
+ margin: 1.618rem auto 0;
+ padding: 0 1rem;
+ }
+
+ .agent-embed-code {
+ background: rgba(255,255,255,0.04);
+ border: 1px solid rgba(255,255,255,0.08);
+ border-radius: 8px;
+ padding: 0.618rem 1rem;
+ font-family: monospace;
+ font-size: 0.618rem;
+ color: rgba(255,255,255,0.4);
+ word-break: break-all;
+ }
+
+ .agent-embed-label {
+ font-size: 0.618rem;
+ color: rgba(255,255,255,0.25);
+ margin-bottom: 0.382rem;
+ }
+
+ .agent-skills-full {
+ max-width: 420px;
+ margin: 1.618rem auto 0;
+ padding: 0 1rem;
+ }
+
+ .agent-skills-title {
+ font-size: 0.618rem;
+ color: rgba(255,255,255,0.25);
+ margin-bottom: 0.618rem;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ }
+
+ .agent-skills-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
+ gap: 0.618rem;
+ }
+
+ .agent-skill-card {
+ background: rgba(255,255,255,0.04);
+ border: 1px solid rgba(255,255,255,0.07);
+ border-radius: 8px;
+ padding: 0.618rem;
+ }
+
+ .agent-skill-card-name {
+ font-size: 0.764rem;
+ font-weight: 500;
+ color: rgba(255,255,255,0.7);
+ margin-bottom: 0.236rem;
+ }
+
+ .agent-skill-card-desc {
+ font-size: 0.618rem;
+ color: rgba(255,255,255,0.3);
+ line-height: 1.382;
+ }
+
+ .loading-placeholder {
+ color: rgba(255,255,255,0.2);
+ font-size: 0.764rem;
+ text-align: center;
+ padding: 2rem;
+ }
+ </style>
+</head>
+<body>
+ <div class="agent-page-header">
+ <a href="/">← 3D Agent</a>
+ </div>
+
+ <div class="agent-page-hero">
+ <h1 class="agent-page-title" id="page-agent-name">Agent</h1>
+ <p class="agent-page-subtitle" id="page-agent-desc">
+ Embodied. Present. Persistent.
+ </p>
+ </div>
+
+ <!-- Agent home card rendered by AgentHome -->
+ <div class="agent-page-card-wrap">
+ <div id="agent-home-container">
+ <div class="loading-placeholder">Loading agent…</div>
+ </div>
+ </div>
+
+ <!-- Skills catalog -->
+ <div class="agent-skills-full" id="agent-skills-section" style="display:none">
+ <div class="agent-skills-title">Skills</div>
+ <div class="agent-skills-grid" id="agent-skills-grid"></div>
+ </div>
+
+ <!-- Embed code -->
+ <div class="agent-embed-hint" id="agent-embed-section" style="display:none">
+ <div class="agent-embed-label">Embed this agent</div>
+ <div class="agent-embed-code" id="agent-embed-code"></div>
+ </div>
+
+ <script type="module">
+ import { AgentIdentity } from '/src/agent-identity.js';
+ import { AgentMemory } from '/src/agent-memory.js';
+ import { AgentSkills } from '/src/agent-skills.js';
+ import { AgentHome } from '/src/agent-home.js';
+ import { protocol } from '/src/agent-protocol.js';
+
+ // Pull agent id from URL: /agent/:id
+ const agentId = location.pathname.split('/').filter(Boolean).pop();
+
+ async function main() {
+ const identity = new AgentIdentity({ agentId: agentId || undefined, autoLoad: false });
+ await identity.load();
+
+ // Update hero
+ document.getElementById('page-agent-name').textContent = identity.name;
+ if (identity.description) {
+ document.getElementById('page-agent-desc').textContent = identity.description;
+ }
+
+ // Render the agent home card
+ const container = document.getElementById('agent-home-container');
+ container.innerHTML = '';
+ const home = new AgentHome(container, identity, protocol, null);
+ await home.render();
+
+ // Render skills catalog
+ if (identity.skills?.length) {
+ const skills = new AgentSkills(protocol, identity.memory);
+ const section = document.getElementById('agent-skills-section');
+ const grid = document.getElementById('agent-skills-grid');
+ section.style.display = '';
+ skills.list().filter(s => identity.skills.includes(s.name)).forEach(skill => {
+ const card = document.createElement('div');
+ card.className = 'agent-skill-card';
+ card.innerHTML = `
+ <div class="agent-skill-card-name">${skill.name}</div>
+ <div class="agent-skill-card-desc">${skill.description}</div>
+ `;
+ grid.appendChild(card);
+ });
+ }
+
+ // Embed code
+ const embedSection = document.getElementById('agent-embed-section');
+ const embedCode = document.getElementById('agent-embed-code');
+ const embedUrl = `${location.origin}/agent/${identity.id}`;
+ embedSection.style.display = '';
+ embedCode.textContent = `<iframe src="${embedUrl}" width="420" height="520" frameborder="0" style="border-radius:12px;border:none;"></iframe>`;
+ }
+
+ main().catch(err => {
+ document.getElementById('agent-home-container').innerHTML =
+ `<div class="loading-placeholder">Could not load agent: ${err.message}</div>`;
+ });
+ </script>
+</body>
+</html>
diff --git a/dist-lib/animations/manifest.json b/dist-lib/animations/manifest.json
new file mode 100644
index 000000000..ab417c98a
--- /dev/null
+++ b/dist-lib/animations/manifest.json
@@ -0,0 +1,51 @@
+[
+ {
+ "name": "idle",
+ "url": "/animations/idle.glb",
+ "label": "Idle",
+ "icon": "🧍",
+ "loop": true
+ },
+ {
+ "name": "walking",
+ "url": "/animations/walking.glb",
+ "label": "Walking",
+ "icon": "🚶",
+ "loop": true
+ },
+ {
+ "name": "running",
+ "url": "/animations/running.glb",
+ "label": "Running",
+ "icon": "🏃",
+ "loop": true
+ },
+ {
+ "name": "waving",
+ "url": "/animations/waving.glb",
+ "label": "Waving",
+ "icon": "👋",
+ "loop": false
+ },
+ {
+ "name": "dancing",
+ "url": "/animations/dancing.glb",
+ "label": "Dancing",
+ "icon": "💃",
+ "loop": true
+ },
+ {
+ "name": "sitting",
+ "url": "/animations/sitting.glb",
+ "label": "Sitting",
+ "icon": "🪑",
+ "loop": true
+ },
+ {
+ "name": "jumping",
+ "url": "/animations/jumping.glb",
+ "label": "Jumping",
+ "icon": "🦘",
+ "loop": false
+ }
+]
diff --git a/dist-lib/avatars/cz.glb b/dist-lib/avatars/cz.glb
new file mode 100644
index 000000000..48f6b081e
Binary files /dev/null and b/dist-lib/avatars/cz.glb differ
diff --git a/dist-lib/dashboard/dashboard.js b/dist-lib/dashboard/dashboard.js
new file mode 100644
index 000000000..e6ed49544
--- /dev/null
+++ b/dist-lib/dashboard/dashboard.js
@@ -0,0 +1,269 @@
+// Dashboard single-file app. Uses native DOM — no framework.
+// Keeps bundle small and ensures anything rendering <model-viewer> works without bundler.
+
+export const state = { user: null };
+
+export const api = {
+ me: () => j('GET', '/api/auth/me'),
+ listAvatars: () => j('GET', '/api/avatars?limit=100'),
+ deleteAvatar: (id) => j('DELETE', `/api/avatars/${id}`),
+ patchAvatar: (id, patch) => j('PATCH', `/api/avatars/${id}`, patch),
+ presign: (body) => j('POST', '/api/avatars/presign', body),
+ createAvatar: (body) => j('POST', '/api/avatars', body),
+ listKeys: () => j('GET', '/api/keys'),
+ createKey: (body) => j('POST', '/api/keys', body),
+ revokeKey: (id) => j('DELETE', `/api/keys/${id}`),
+};
+
+async function j(method, path, body) {
+ const res = await fetch(path, {
+ method,
+ credentials: 'include',
+ headers: body ? { 'content-type': 'application/json' } : {},
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ const data = res.headers.get('content-type')?.includes('application/json')
+ ? await res.json()
+ : null;
+ if (!res.ok) throw Object.assign(new Error((data && data.error_description) || res.statusText), { status: res.status, data });
+ return data;
+}
+
+export function signOut() {
+ fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).finally(() => {
+ location.href = '/';
+ });
+}
+
+export function navigate(tab) {
+ document.querySelectorAll('aside a').forEach((a) => a.classList.toggle('active', a.dataset.tab === tab));
+ const main = document.getElementById('main');
+ main.innerHTML = '';
+ const renderer = tabs[tab] || tabs.avatars;
+ renderer(main);
+}
+
+const tabs = {
+ avatars: renderAvatars,
+ upload: renderUpload,
+ keys: renderKeys,
+ mcp: renderMcp,
+ billing: renderBilling,
+};
+
+// ── Avatars ─────────────────────────────────────────────────────────────────
+async function renderAvatars(root) {
+ root.innerHTML = `<h1>Your avatars</h1><p class="sub">Each avatar gets a stable URL and can be rendered in Claude or any app via MCP.</p><div id="list" class="cards"></div>`;
+ const list = root.querySelector('#list');
+ list.innerHTML = '<div class="muted">Loading…</div>';
+ try {
+ const { avatars } = await api.listAvatars();
+ if (!avatars.length) {
+ list.innerHTML = `<div class="empty">No avatars yet. <a href="#upload">Upload one</a> or create via the viewer.</div>`;
+ return;
+ }
+ list.innerHTML = '';
+ for (const a of avatars) list.appendChild(avatarCard(a));
+ } catch (e) {
+ list.innerHTML = `<div class="err">${esc(e.message)}</div>`;
+ }
+}
+
+function avatarCard(a) {
+ const el = document.createElement('div');
+ el.className = 'card';
+ const preview = a.model_url
+ ? `<model-viewer src="${attr(a.model_url)}" camera-controls auto-rotate shadow-intensity="1" exposure="1" tone-mapping="aces"></model-viewer>`
+ : `<span>Private · preview requires signed URL</span>`;
+ el.innerHTML = `
+ <div class="preview">${preview}</div>
+ <h3>${esc(a.name)}</h3>
+ <p class="meta">${a.size_bytes ? fmtSize(a.size_bytes) : ''} · ${esc(a.visibility)} · ${new Date(a.created_at).toLocaleDateString()}</p>
+ <div class="row" style="gap:6px; margin-bottom:10px">${a.tags.map((t) => `<span class="tag">${esc(t)}</span>`).join('')}</div>
+ <div class="row" style="justify-content:space-between">
+ <select data-vis>${['private','unlisted','public'].map((v) => `<option ${v===a.visibility?'selected':''} value="${v}">${v}</option>`).join('')}</select>
+ <button class="btn sec" data-del>Delete</button>
+ </div>
+ `;
+ el.querySelector('[data-vis]').addEventListener('change', async (e) => {
+ try {
+ await api.patchAvatar(a.id, { visibility: e.target.value });
+ } catch (err) { alert(err.message); }
+ });
+ el.querySelector('[data-del]').addEventListener('click', async () => {
+ if (!confirm(`Delete "${a.name}"?`)) return;
+ try {
+ await api.deleteAvatar(a.id);
+ el.remove();
+ } catch (err) { alert(err.message); }
+ });
+ return el;
+}
+
+// ── Upload ──────────────────────────────────────────────────────────────────
+function renderUpload(root) {
+ root.innerHTML = `
+ <h1>Upload avatar</h1><p class="sub">Upload a .glb file. It's stored on our CDN and made available via API and MCP.</p>
+ <form id="up" class="card" style="max-width:520px">
+ <label>File<input id="file" type="file" accept=".glb,model/gltf-binary" required></label>
+ <label style="display:block;margin-top:12px">Name<input id="name" required maxlength="120" style="width:100%"></label>
+ <label style="display:block;margin-top:12px">Description<textarea id="desc" rows="2" style="width:100%"></textarea></label>
+ <label style="display:block;margin-top:12px">Visibility
+ <select id="vis" style="width:100%">
+ <option value="private">Private (only you)</option>
+ <option value="unlisted">Unlisted (anyone with link)</option>
+ <option value="public">Public (discoverable)</option>
+ </select>
+ </label>
+ <label style="display:block;margin-top:12px">Tags (comma separated)<input id="tags" style="width:100%"></label>
+ <div id="progress" class="muted" style="margin-top:12px"></div>
+ <button class="btn" style="margin-top:16px" type="submit">Upload</button>
+ </form>
+ `;
+ const form = root.querySelector('#up');
+ const progress = root.querySelector('#progress');
+ form.addEventListener('submit', async (e) => {
+ e.preventDefault();
+ const file = root.querySelector('#file').files[0];
+ if (!file) return;
+ progress.textContent = 'Requesting upload URL…';
+ try {
+ const { upload_url, storage_key } = await api.presign({
+ size_bytes: file.size,
+ content_type: file.type || 'model/gltf-binary',
+ });
+ progress.textContent = `Uploading ${fmtSize(file.size)}…`;
+ await uploadToR2(upload_url, file, (pct) => (progress.textContent = `Uploading ${pct}%…`));
+ progress.textContent = 'Finalizing…';
+ const tags = (root.querySelector('#tags').value || '').split(',').map((s) => s.trim()).filter(Boolean);
+ const { avatar } = await api.createAvatar({
+ storage_key,
+ name: root.querySelector('#name').value,
+ description: root.querySelector('#desc').value || undefined,
+ visibility: root.querySelector('#vis').value,
+ tags,
+ size_bytes: file.size,
+ content_type: file.type || 'model/gltf-binary',
+ source: 'upload',
+ source_meta: {},
+ });
+ progress.innerHTML = `Uploaded! <a href="#avatars">View</a>`;
+ location.hash = 'avatars';
+ } catch (err) {
+ progress.textContent = '';
+ alert(err.message);
+ }
+ });
+}
+
+function uploadToR2(url, file, onProgress) {
+ return new Promise((resolve, reject) => {
+ const xhr = new XMLHttpRequest();
+ xhr.open('PUT', url);
+ xhr.setRequestHeader('content-type', file.type || 'model/gltf-binary');
+ xhr.upload.onprogress = (e) => e.lengthComputable && onProgress(Math.round((e.loaded / e.total) * 100));
+ xhr.onload = () => (xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new Error(`Upload failed (${xhr.status})`)));
+ xhr.onerror = () => reject(new Error('Network error during upload'));
+ xhr.send(file);
+ });
+}
+
+// ── API keys ────────────────────────────────────────────────────────────────
+async function renderKeys(root) {
+ root.innerHTML = `
+ <h1>API keys</h1><p class="sub">Server-side keys for calling the MCP server without OAuth. Treat like passwords.</p>
+ <div class="card" style="margin-bottom:16px">
+ <form id="new" class="row" style="flex-wrap:wrap;gap:10px">
+ <input id="kname" placeholder="Key name (e.g. my-app prod)" required>
+ <select id="kenv"><option value="live">live</option><option value="test">test</option></select>
+ <button class="btn" type="submit">Create key</button>
+ </form>
+ <div id="reveal"></div>
+ </div>
+ <div id="klist" class="card"></div>
+ `;
+ const klist = root.querySelector('#klist');
+ async function refresh() {
+ try {
+ const { keys } = await api.listKeys();
+ if (!keys.length) { klist.innerHTML = '<div class="muted">No keys yet.</div>'; return; }
+ klist.innerHTML = keys.map((k) => `
+ <div class="key-row">
+ <div>
+ <div><code>${esc(k.prefix)}…</code> — ${esc(k.name)}</div>
+ <div class="muted">scope: ${esc(k.scope)} · created ${new Date(k.created_at).toLocaleDateString()}${k.revoked_at?` · <b style="color:#f88">revoked</b>`:''}</div>
+ </div>
+ ${k.revoked_at ? '' : `<button class="btn sec" data-id="${esc(k.id)}">Revoke</button>`}
+ </div>
+ `).join('');
+ klist.querySelectorAll('button[data-id]').forEach((b) => b.addEventListener('click', async () => {
+ if (!confirm('Revoke this key?')) return;
+ try { await api.revokeKey(b.dataset.id); refresh(); } catch (e) { alert(e.message); }
+ }));
+ } catch (e) { klist.innerHTML = `<div class="err">${esc(e.message)}</div>`; }
+ }
+ root.querySelector('#new').addEventListener('submit', async (e) => {
+ e.preventDefault();
+ try {
+ const { key } = await api.createKey({
+ name: root.querySelector('#kname').value,
+ environment: root.querySelector('#kenv').value,
+ });
+ root.querySelector('#reveal').innerHTML = `
+ <div style="margin-top:10px">
+ <p class="muted">Copy this key now — you won't see it again.</p>
+ <pre><code>${esc(key.secret)}</code></pre>
+ </div>
+ `;
+ root.querySelector('#kname').value = '';
+ refresh();
+ } catch (err) { alert(err.message); }
+ });
+ refresh();
+}
+
+// ── MCP integration ─────────────────────────────────────────────────────────
+function renderMcp(root) {
+ const origin = location.origin;
+ root.innerHTML = `
+ <h1>Use from Claude &amp; other MCP clients</h1>
+ <p class="sub">Connect any MCP-compatible client to render your avatars inline.</p>
+
+ <h3 class="section">Remote MCP server URL</h3>
+ <pre><code>${esc(origin)}/api/mcp</code></pre>
+
+ <h3 class="section">Claude Desktop / Claude Code (remote)</h3>
+ <p class="muted">Add a Custom Connector in Claude. When prompted, sign in with your 3D Agent account.</p>
+ <pre><code>${esc(JSON.stringify({
+ mcpServers: {
+ '3d-agent': { url: `${origin}/api/mcp` }
+ }
+ }, null, 2))}</code></pre>
+
+ <h3 class="section">Programmatic (API key)</h3>
+ <p class="muted">Bypass OAuth for server-to-server usage. Pass key as a bearer token.</p>
+ <pre><code>curl -X POST ${esc(origin)}/api/mcp \\
+ -H "authorization: Bearer sk_live_…" \\
+ -H "content-type: application/json" \\
+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'</code></pre>
+
+ <h3 class="section">Available tools</h3>
+ <ul>
+ <li><b>list_my_avatars</b> — list avatars</li>
+ <li><b>get_avatar</b> — fetch by id or slug</li>
+ <li><b>search_public_avatars</b> — discover public avatars</li>
+ <li><b>render_avatar</b> — returns &lt;model-viewer&gt; HTML for rendering as a Claude artifact</li>
+ <li><b>delete_avatar</b> — remove an avatar (requires <code>avatars:delete</code>)</li>
+ </ul>
+ `;
+}
+
+// ── Billing placeholder ─────────────────────────────────────────────────────
+function renderBilling(root) {
+ root.innerHTML = `<h1>Plan &amp; usage</h1><p class="sub">You're on the <b>${esc(state.user.plan)}</b> plan.</p><div class="card muted">Detailed usage analytics coming soon.</div>`;
+}
+
+// ── utils ───────────────────────────────────────────────────────────────────
+function fmtSize(b) { if (b < 1024) return b + ' B'; if (b < 1024*1024) return (b/1024).toFixed(1) + ' KB'; return (b/1024/1024).toFixed(1) + ' MB'; }
+function esc(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c])); }
+function attr(s) { return esc(s); }
diff --git a/dist-lib/dashboard/index.html b/dist-lib/dashboard/index.html
new file mode 100644
index 000000000..574da0341
--- /dev/null
+++ b/dist-lib/dashboard/index.html
@@ -0,0 +1,84 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<title>Dashboard · 3D Agent</title>
+<link rel="icon" href="/favicon.ico">
+<style>
+ :root { color-scheme: dark; --accent:#6a5cff; --accent2:#ff5ca8; --border:#22222e; --bg:#0b0b10; --panel:#14141c; }
+ * { box-sizing: border-box; }
+ body { font:15px/1.55 -apple-system,system-ui,Segoe UI,Roboto,sans-serif; color:#eee; margin:0; background:var(--bg); min-height:100vh; }
+ a { color:#9a8cff; text-decoration:none; }
+ header { display:flex; align-items:center; justify-content:space-between; padding:16px 24px; border-bottom:1px solid var(--border); position:sticky; top:0; background:var(--bg); z-index:5; }
+ .brand { font-weight:600; letter-spacing:-.01em; }
+ nav a { margin-right:14px; color:#aaa; font-size:14px; }
+ nav a.active { color:#fff; }
+ .layout { display:grid; grid-template-columns:220px 1fr; min-height:calc(100vh - 57px); }
+ aside { border-right:1px solid var(--border); padding:20px 0; }
+ aside a { display:block; padding:9px 20px; color:#aaa; font-size:14px; border-left:2px solid transparent; }
+ aside a.active { color:#fff; background:rgba(106,92,255,.08); border-left-color:var(--accent); }
+ main { padding:28px; max-width:1100px; }
+ h1 { font-size:22px; margin:0 0 6px; letter-spacing:-.01em; }
+ .sub { color:#888; margin:0 0 22px; font-size:14px; }
+ .cards { display:grid; grid-template-columns:repeat(auto-fill,minmax(260px,1fr)); gap:14px; }
+ .card { background:var(--panel); border:1px solid var(--border); border-radius:14px; padding:16px; }
+ .card h3 { margin:0 0 4px; font-size:15px; }
+ .card .meta { font-size:12px; color:#888; margin:0 0 10px; }
+ .preview { aspect-ratio:1/1; background:#0f0f17; border-radius:10px; margin-bottom:10px; overflow:hidden; display:grid; place-items:center; color:#555; font-size:12px; }
+ .preview model-viewer { width:100%; height:100%; }
+ .row { display:flex; align-items:center; gap:8px; }
+ .tag { font-size:11px; padding:2px 7px; border-radius:99px; background:#20202c; color:#ccc; }
+ .btn { padding:9px 14px; border-radius:9px; border:0; font-size:13px; font-weight:600; cursor:pointer; background:var(--accent); color:#fff; }
+ .btn.sec { background:#222230; color:#ddd; }
+ .empty { text-align:center; padding:60px 20px; border:1px dashed var(--border); border-radius:14px; color:#888; }
+ .toolbar { display:flex; justify-content:space-between; align-items:center; margin-bottom:18px; }
+ .err { padding:12px; background:rgba(255,92,92,.1); border:1px solid rgba(255,92,92,.3); border-radius:8px; color:#ffb3b3; margin-bottom:14px; }
+ pre { background:#0f0f17; border:1px solid var(--border); border-radius:8px; padding:10px 12px; overflow:auto; font-size:12px; }
+ code { font-family: ui-monospace, SF Mono, Menlo, monospace; }
+ .key-row { display:flex; justify-content:space-between; align-items:center; padding:10px 0; border-bottom:1px solid var(--border); }
+ .key-row:last-child { border:0; }
+ .muted { color:#888; font-size:13px; }
+ .section { margin-top:34px; }
+ input, textarea, select { background:#0f0f17; border:1px solid var(--border); color:#eee; padding:9px 11px; border-radius:8px; font-size:14px; font-family:inherit; }
+ input:focus, textarea:focus, select:focus { outline:none; border-color:var(--accent); }
+</style>
+<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
+</head>
+<body>
+<header>
+ <div class="brand"><a href="/">3D Agent</a></div>
+ <div class="row">
+ <span id="user-email" class="muted"></span>
+ <button class="btn sec" onclick="signOut()">Sign out</button>
+ </div>
+</header>
+<div class="layout">
+ <aside>
+ <a href="#avatars" class="active" data-tab="avatars">Avatars</a>
+ <a href="#upload" data-tab="upload">Upload</a>
+ <a href="#keys" data-tab="keys">API keys</a>
+ <a href="#mcp" data-tab="mcp">MCP</a>
+ <a href="#billing" data-tab="billing">Plan &amp; usage</a>
+ </aside>
+ <main id="main"></main>
+</div>
+<script type="module">
+import { state, api, navigate, signOut } from './dashboard.js';
+window.signOut = signOut;
+
+(async () => {
+ try {
+ const me = await api.me();
+ state.user = me.user;
+ document.getElementById('user-email').textContent = me.user.email;
+ } catch {
+ location.href = '/login.html?next=' + encodeURIComponent(location.pathname + location.hash);
+ return;
+ }
+ navigate(location.hash.slice(1) || 'avatars');
+ window.addEventListener('hashchange', () => navigate(location.hash.slice(1) || 'avatars'));
+})();
+</script>
+</body>
+</html>
diff --git a/dist-lib/ddd.png b/dist-lib/ddd.png
new file mode 100644
index 000000000..f5998260b
Binary files /dev/null and b/dist-lib/ddd.png differ
diff --git a/dist-lib/favicon.ico b/dist-lib/favicon.ico
new file mode 100644
index 000000000..a0bdf04e1
Binary files /dev/null and b/dist-lib/favicon.ico differ
diff --git a/dist-lib/login.html b/dist-lib/login.html
new file mode 100644
index 000000000..0652eb8ad
--- /dev/null
+++ b/dist-lib/login.html
@@ -0,0 +1,70 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<title>Sign in · 3D Agent</title>
+<link rel="icon" href="/favicon.ico">
+<style>
+ :root { color-scheme: dark; --accent:#6a5cff; --accent2:#ff5ca8; }
+ * { box-sizing: border-box; }
+ body { font: 15px/1.5 -apple-system,system-ui,Segoe UI,Roboto,sans-serif; background:radial-gradient(1200px 600px at 50% -100px,#1a1a2e 0,#080814 60%); color:#eee; margin:0; min-height:100vh; display:grid; place-items:center; padding:24px; }
+ a { color:#9a8cff; }
+ .card { background:#14141c; border:1px solid #2a2a36; border-radius:16px; padding:32px; max-width:400px; width:100%; box-shadow:0 10px 40px rgba(0,0,0,.5); }
+ h1 { font-size:22px; margin:0 0 4px; letter-spacing:-0.01em; }
+ .sub { color:#888; margin:0 0 24px; font-size:14px; }
+ label { display:block; font-size:13px; color:#aaa; margin:14px 0 6px; }
+ input { width:100%; padding:11px 13px; background:#0f0f17; border:1px solid #2a2a36; border-radius:9px; color:#eee; font-size:15px; }
+ input:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px rgba(106,92,255,.15); }
+ button { width:100%; margin-top:20px; padding:12px 16px; border:0; border-radius:10px; background:linear-gradient(135deg,var(--accent),var(--accent2)); color:#fff; font-weight:600; font-size:15px; cursor:pointer; }
+ button:disabled { opacity:.6; cursor:default; }
+ .err { margin-top:14px; padding:10px 12px; background:rgba(255,92,92,.1); border:1px solid rgba(255,92,92,.3); border-radius:8px; color:#ffb3b3; font-size:13px; display:none; }
+ .foot { margin-top:20px; text-align:center; font-size:13px; color:#888; }
+ .brand { font-size:12px; letter-spacing:.1em; text-transform:uppercase; color:var(--accent); margin:0 0 8px; }
+</style>
+</head>
+<body>
+<form class="card" id="f">
+ <p class="brand">3D Agent</p>
+ <h1>Welcome back</h1>
+ <p class="sub">Sign in to manage your avatars.</p>
+ <label for="email">Email</label>
+ <input id="email" type="email" autocomplete="email" required>
+ <label for="password">Password</label>
+ <input id="password" type="password" autocomplete="current-password" required minlength="10">
+ <button id="submit" type="submit">Sign in</button>
+ <div class="err" id="err"></div>
+ <p class="foot">No account? <a href="/register.html">Create one</a></p>
+</form>
+<script>
+const params = new URLSearchParams(location.search);
+const next = params.get('next') || '/dashboard/';
+const form = document.getElementById('f');
+const err = document.getElementById('err');
+const btn = document.getElementById('submit');
+form.addEventListener('submit', async (e) => {
+ e.preventDefault();
+ err.style.display = 'none';
+ btn.disabled = true; btn.textContent = 'Signing in…';
+ try {
+ const res = await fetch('/api/auth/login', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ email: document.getElementById('email').value,
+ password: document.getElementById('password').value,
+ }),
+ });
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error_description || 'Sign-in failed');
+ location.href = next;
+ } catch (e) {
+ err.textContent = e.message;
+ err.style.display = 'block';
+ btn.disabled = false; btn.textContent = 'Sign in';
+ }
+});
+</script>
+</body>
+</html>
diff --git a/dist-lib/og-image.png b/dist-lib/og-image.png
new file mode 100644
index 000000000..c8d017dcf
Binary files /dev/null and b/dist-lib/og-image.png differ
diff --git a/dist-lib/pwa-192x192.png b/dist-lib/pwa-192x192.png
new file mode 100644
index 000000000..3438a05a3
Binary files /dev/null and b/dist-lib/pwa-192x192.png differ
diff --git a/dist-lib/pwa-512x512.png b/dist-lib/pwa-512x512.png
new file mode 100644
index 000000000..c6ce55590
Binary files /dev/null and b/dist-lib/pwa-512x512.png differ
diff --git a/dist-lib/pwa-icon.svg b/dist-lib/pwa-icon.svg
new file mode 100644
index 000000000..58713989d
--- /dev/null
+++ b/dist-lib/pwa-icon.svg
@@ -0,0 +1,89 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
+ <defs>
+ <!-- Vertex glow -->
+ <radialGradient id="vglow" cx="50%" cy="50%" r="50%">
+ <stop offset="0%" stop-color="#ffffff" stop-opacity="0.9"/>
+ <stop offset="30%" stop-color="#b8e8ff" stop-opacity="0.5"/>
+ <stop offset="100%" stop-color="#b8e8ff" stop-opacity="0"/>
+ </radialGradient>
+ <!-- Edge glow filter -->
+ <filter id="edgeGlow" x="-20%" y="-20%" width="140%" height="140%">
+ <feGaussianBlur stdDeviation="3" result="blur"/>
+ <feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>
+ </filter>
+ <!-- Strong vertex glow filter -->
+ <filter id="vtxGlow" x="-100%" y="-100%" width="300%" height="300%">
+ <feGaussianBlur stdDeviation="8" result="blur"/>
+ <feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>
+ </filter>
+ <!-- Cube face gradient — top -->
+ <linearGradient id="faceTop" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0%" stop-color="#1a2a3a" stop-opacity="0.7"/>
+ <stop offset="100%" stop-color="#0a1520" stop-opacity="0.85"/>
+ </linearGradient>
+ <!-- Cube face gradient — right -->
+ <linearGradient id="faceRight" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#0f1e2e" stop-opacity="0.8"/>
+ <stop offset="100%" stop-color="#060e18" stop-opacity="0.9"/>
+ </linearGradient>
+ <!-- Cube face gradient — left -->
+ <linearGradient id="faceLeft" x1="1" y1="0" x2="0" y2="1">
+ <stop offset="0%" stop-color="#0d1a28" stop-opacity="0.75"/>
+ <stop offset="100%" stop-color="#080f1a" stop-opacity="0.9"/>
+ </linearGradient>
+ </defs>
+
+ <!-- Background -->
+ <rect width="512" height="512" rx="96" fill="#080814"/>
+
+ <!-- Isometric cube — 3/4 view like 3d.png -->
+ <!-- Vertices: top=256,110 front-left=116,256 front-right=396,256
+ bottom=256,402 back-left=116,182 back-right=396,182 -->
+
+ <!-- Left face -->
+ <polygon points="256,110 116,182 116,330 256,402" fill="url(#faceLeft)" stroke="none"/>
+ <!-- Right face -->
+ <polygon points="256,110 396,182 396,330 256,402" fill="url(#faceRight)" stroke="none"/>
+ <!-- Top face -->
+ <polygon points="256,110 116,182 256,254 396,182" fill="url(#faceTop)" stroke="none"/>
+
+ <!-- Subtle inner grid lines on faces -->
+ <!-- Left face grid -->
+ <line x1="186" y1="146" x2="186" y2="366" stroke="#1a3a5a" stroke-width="0.5" opacity="0.3"/>
+ <line x1="116" y1="256" x2="256" y2="256" stroke="#1a3a5a" stroke-width="0.5" opacity="0.3"/>
+ <!-- Right face grid -->
+ <line x1="326" y1="146" x2="326" y2="366" stroke="#1a3a5a" stroke-width="0.5" opacity="0.3"/>
+ <line x1="256" y1="256" x2="396" y2="256" stroke="#1a3a5a" stroke-width="0.5" opacity="0.3"/>
+ <!-- Top face grid -->
+ <line x1="186" y1="146" x2="326" y2="146" stroke="#1a3a5a" stroke-width="0.5" opacity="0.25"/>
+ <line x1="256" y1="110" x2="256" y2="254" stroke="#1a3a5a" stroke-width="0.5" opacity="0.25"/>
+
+ <!-- Edges — glowing cyan/white like crystal cube -->
+ <!-- Top edges -->
+ <line x1="256" y1="110" x2="116" y2="182" stroke="#7ec8e3" stroke-width="2" opacity="0.7" filter="url(#edgeGlow)"/>
+ <line x1="256" y1="110" x2="396" y2="182" stroke="#7ec8e3" stroke-width="2" opacity="0.7" filter="url(#edgeGlow)"/>
+ <!-- Top front edge -->
+ <line x1="116" y1="182" x2="256" y2="254" stroke="#5aadcf" stroke-width="1.5" opacity="0.5" filter="url(#edgeGlow)"/>
+ <line x1="396" y1="182" x2="256" y2="254" stroke="#5aadcf" stroke-width="1.5" opacity="0.5" filter="url(#edgeGlow)"/>
+ <!-- Vertical edges -->
+ <line x1="116" y1="182" x2="116" y2="330" stroke="#5aadcf" stroke-width="1.8" opacity="0.5" filter="url(#edgeGlow)"/>
+ <line x1="396" y1="182" x2="396" y2="330" stroke="#5aadcf" stroke-width="1.8" opacity="0.5" filter="url(#edgeGlow)"/>
+ <line x1="256" y1="254" x2="256" y2="402" stroke="#4a9abf" stroke-width="1.5" opacity="0.4" filter="url(#edgeGlow)"/>
+ <!-- Bottom edges -->
+ <line x1="116" y1="330" x2="256" y2="402" stroke="#5aadcf" stroke-width="1.8" opacity="0.55" filter="url(#edgeGlow)"/>
+ <line x1="396" y1="330" x2="256" y2="402" stroke="#5aadcf" stroke-width="1.8" opacity="0.55" filter="url(#edgeGlow)"/>
+
+ <!-- Bright vertex glows — matching 3d.png's bright corner highlights -->
+ <!-- Top vertex — brightest -->
+ <circle cx="256" cy="110" r="14" fill="url(#vglow)" filter="url(#vtxGlow)"/>
+ <!-- Left vertex -->
+ <circle cx="116" cy="182" r="10" fill="url(#vglow)" opacity="0.6" filter="url(#vtxGlow)"/>
+ <!-- Right vertex -->
+ <circle cx="396" cy="182" r="10" fill="url(#vglow)" opacity="0.6" filter="url(#vtxGlow)"/>
+ <!-- Front-bottom vertex -->
+ <circle cx="256" cy="402" r="8" fill="url(#vglow)" opacity="0.35" filter="url(#vtxGlow)"/>
+ <!-- Mid vertices — subtler -->
+ <circle cx="256" cy="254" r="7" fill="url(#vglow)" opacity="0.3" filter="url(#vtxGlow)"/>
+ <circle cx="116" cy="330" r="7" fill="url(#vglow)" opacity="0.3" filter="url(#vtxGlow)"/>
+ <circle cx="396" cy="330" r="7" fill="url(#vglow)" opacity="0.4" filter="url(#vtxGlow)"/>
+</svg>
diff --git a/dist-lib/register.html b/dist-lib/register.html
new file mode 100644
index 000000000..5222f93f4
--- /dev/null
+++ b/dist-lib/register.html
@@ -0,0 +1,75 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<title>Create account · 3D Agent</title>
+<link rel="icon" href="/favicon.ico">
+<style>
+ :root { color-scheme: dark; --accent:#6a5cff; --accent2:#ff5ca8; }
+ * { box-sizing: border-box; }
+ body { font: 15px/1.5 -apple-system,system-ui,Segoe UI,Roboto,sans-serif; background:radial-gradient(1200px 600px at 50% -100px,#1a1a2e 0,#080814 60%); color:#eee; margin:0; min-height:100vh; display:grid; place-items:center; padding:24px; }
+ a { color:#9a8cff; }
+ .card { background:#14141c; border:1px solid #2a2a36; border-radius:16px; padding:32px; max-width:400px; width:100%; box-shadow:0 10px 40px rgba(0,0,0,.5); }
+ h1 { font-size:22px; margin:0 0 4px; letter-spacing:-0.01em; }
+ .sub { color:#888; margin:0 0 24px; font-size:14px; }
+ label { display:block; font-size:13px; color:#aaa; margin:14px 0 6px; }
+ input { width:100%; padding:11px 13px; background:#0f0f17; border:1px solid #2a2a36; border-radius:9px; color:#eee; font-size:15px; }
+ input:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px rgba(106,92,255,.15); }
+ .hint { font-size:12px; color:#666; margin-top:5px; }
+ button { width:100%; margin-top:20px; padding:12px 16px; border:0; border-radius:10px; background:linear-gradient(135deg,var(--accent),var(--accent2)); color:#fff; font-weight:600; font-size:15px; cursor:pointer; }
+ button:disabled { opacity:.6; cursor:default; }
+ .err { margin-top:14px; padding:10px 12px; background:rgba(255,92,92,.1); border:1px solid rgba(255,92,92,.3); border-radius:8px; color:#ffb3b3; font-size:13px; display:none; }
+ .foot { margin-top:20px; text-align:center; font-size:13px; color:#888; }
+ .brand { font-size:12px; letter-spacing:.1em; text-transform:uppercase; color:var(--accent); margin:0 0 8px; }
+</style>
+</head>
+<body>
+<form class="card" id="f">
+ <p class="brand">3D Agent</p>
+ <h1>Create your account</h1>
+ <p class="sub">Free plan: 10 avatars, 250 MB storage.</p>
+ <label for="name">Name</label>
+ <input id="name" type="text" autocomplete="name" maxlength="80">
+ <label for="email">Email</label>
+ <input id="email" type="email" autocomplete="email" required>
+ <label for="password">Password</label>
+ <input id="password" type="password" autocomplete="new-password" required minlength="10">
+ <div class="hint">At least 10 characters.</div>
+ <button id="submit" type="submit">Create account</button>
+ <div class="err" id="err"></div>
+ <p class="foot">Already have one? <a href="/login.html">Sign in</a></p>
+</form>
+<script>
+const params = new URLSearchParams(location.search);
+const next = params.get('next') || '/dashboard/';
+const form = document.getElementById('f');
+const err = document.getElementById('err');
+const btn = document.getElementById('submit');
+form.addEventListener('submit', async (e) => {
+ e.preventDefault();
+ err.style.display = 'none';
+ btn.disabled = true; btn.textContent = 'Creating…';
+ try {
+ const res = await fetch('/api/auth/register', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ email: document.getElementById('email').value,
+ password: document.getElementById('password').value,
+ display_name: document.getElementById('name').value || undefined,
+ }),
+ });
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error_description || 'Sign-up failed');
+ location.href = next;
+ } catch (e) {
+ err.textContent = e.message;
+ err.style.display = 'block';
+ btn.disabled = false; btn.textContent = 'Create account';
+ }
+});
+</script>
+</body>
+</html>
diff --git a/dist-lib/robots.txt b/dist-lib/robots.txt
new file mode 100644
index 000000000..223358ba6
--- /dev/null
+++ b/dist-lib/robots.txt
@@ -0,0 +1,3 @@
+User-agent: *
+Allow: /
+Sitemap: https://3d.irish/sitemap.xml
diff --git a/dist-lib/sitemap.xml b/dist-lib/sitemap.xml
new file mode 100644
index 000000000..9c7e903d2
--- /dev/null
+++ b/dist-lib/sitemap.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
+ <url>
+ <loc>https://3d.irish/</loc>
+ <lastmod>2026-04-14</lastmod>
+ <priority>1.0</priority>
+ </url>
+</urlset>
diff --git a/dist-lib/skills.mp4 b/dist-lib/skills.mp4
new file mode 100644
index 000000000..ee2cb2fe5
Binary files /dev/null and b/dist-lib/skills.mp4 differ
diff --git a/embed.html b/embed.html
new file mode 100644
index 000000000..a8c79bb14
--- /dev/null
+++ b/embed.html
@@ -0,0 +1,26 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Embed editor — 3D Agent</title>
+ <style>
+ html, body { margin: 0; padding: 0; height: 100%; background: #0b0d10; color: #fff; font-family: system-ui, sans-serif; }
+ #root { height: 100vh; }
+ </style>
+</head>
+<body>
+ <div id="root"></div>
+ <script type="module">
+ import { mountEmbedEditor } from './src/editor/embed-editor.js';
+ const url = new URL(location.href);
+ mountEmbedEditor(document.getElementById('root'), {
+ src: url.searchParams.get('src') || '',
+ mode: url.searchParams.get('mode') || 'floating',
+ position: url.searchParams.get('position') || 'bottom-right',
+ width: url.searchParams.get('width') || '320px',
+ height: url.searchParams.get('height') || '420px',
+ });
+ </script>
+</body>
+</html>
diff --git a/examples/coach-leo/SKILL.md b/examples/coach-leo/SKILL.md
new file mode 100644
index 000000000..a79fd30d4
--- /dev/null
+++ b/examples/coach-leo/SKILL.md
@@ -0,0 +1,13 @@
+---
+name: Coach Leo
+description: Top-level capability summary of this agent
+---
+
+# Coach Leo — Capabilities
+
+- Wave at users on greetings (via the `wave` skill).
+- Read glTF/body data to comment on your avatar.
+- Remember user context across sessions (memory is local by default).
+- Speak aloud when voice mode is on.
+
+Further skills can be added by setting `skills:` in `manifest.json`.
diff --git a/examples/coach-leo/instructions.md b/examples/coach-leo/instructions.md
new file mode 100644
index 000000000..d1c9a392b
--- /dev/null
+++ b/examples/coach-leo/instructions.md
@@ -0,0 +1,27 @@
+---
+name: Coach Leo
+model: claude-opus-4-6
+temperature: 0.8
+---
+
+You are Coach Leo, a former Argentine midfielder turned football coach. You
+wear the Argentina jersey with pride. You are warm, direct, and genuinely
+invested in the user's progress.
+
+## How you work
+
+- When the user greets you, call `wave()` to wave at them.
+- When they describe a drill or ask about form, set a focused expression
+ with `setExpression({ preset: "focused" })` while you explain, then smile
+ afterward.
+- If the user shares something worth remembering (their position, goals,
+ injuries, schedule), call `remember()` to save it durably.
+- Reference past memory naturally — don't recite, weave it in.
+- Keep replies short in voice mode: 1–2 sentences, then invite the user
+ to respond. Save long explanations for when they ask for depth.
+
+## Your voice
+
+- Direct. No coddling. "That's not quite right — try this instead."
+- Warm. Genuine wins get genuine praise.
+- Never break character.
diff --git a/examples/coach-leo/manifest.json b/examples/coach-leo/manifest.json
new file mode 100644
index 000000000..53d90aeeb
--- /dev/null
+++ b/examples/coach-leo/manifest.json
@@ -0,0 +1,35 @@
+{
+ "$schema": "https://3d-agent.io/schemas/manifest/0.1.json",
+ "spec": "agent-manifest/0.1",
+ "name": "Coach Leo",
+ "description": "Football coach. Reviews your form, cheers you on.",
+ "image": "/avatars/cz.glb",
+ "tags": ["coach", "football", "argentina"],
+ "body": {
+ "uri": "/avatars/cz.glb",
+ "format": "gltf-binary",
+ "rig": "mixamo",
+ "boundingBoxHeight": 1.78
+ },
+ "brain": {
+ "provider": "anthropic",
+ "model": "claude-opus-4-6",
+ "instructions": "instructions.md",
+ "temperature": 0.8,
+ "maxTokens": 2048
+ },
+ "voice": {
+ "tts": { "provider": "browser", "rate": 1.05 },
+ "stt": { "provider": "browser", "language": "en-US" }
+ },
+ "skills": [
+ { "uri": "../skills/wave/", "version": "0.1.0" }
+ ],
+ "memory": {
+ "mode": "local",
+ "index": "memory/MEMORY.md",
+ "maxTokens": 8192
+ },
+ "tools": ["wave", "lookAt", "play_clip", "setExpression", "speak", "remember"],
+ "version": "0.1.0"
+}
diff --git a/examples/minimal.html b/examples/minimal.html
new file mode 100644
index 000000000..75d2167c4
--- /dev/null
+++ b/examples/minimal.html
@@ -0,0 +1,65 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Minimal embed — 3D Agent</title>
+ <style>
+ body { margin: 0; font: 16px/1.5 system-ui, sans-serif; background: #fafafa; color: #111; }
+ main { max-width: 720px; margin: 0 auto; padding: 64px 32px; }
+ h1 { font-size: 40px; margin: 0 0 16px; }
+ p { color: #4b5563; }
+ .two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; margin: 48px 0; }
+ .card { background: white; border: 1px solid #e5e7eb; border-radius: 16px; padding: 24px; }
+ .card h2 { margin-top: 0; font-size: 18px; }
+ pre { background: #0a0d12; color: #a7f3d0; padding: 16px; border-radius: 8px; overflow-x: auto; font-size: 13px; }
+ </style>
+</head>
+<body>
+ <main>
+ <h1>Hello from the page</h1>
+ <p>
+ This is a plain HTML page. The floating agent in the corner was added
+ with a single <code>&lt;agent-3d&gt;</code> tag — no build step, no framework.
+ </p>
+
+ <div class="two-col">
+ <div class="card">
+ <h2>Inline embed</h2>
+ <p>The agent below is embedded inline, flowing with the page content.</p>
+ <agent-3d
+ body="/avatars/cz.glb"
+ instructions="You are a friendly 3D guide."
+ width="100%"
+ height="320px"
+ brain="claude-opus-4-6"
+ ></agent-3d>
+ </div>
+ <div class="card">
+ <h2>The snippet</h2>
+ <pre>&lt;agent-3d
+ body="/avatars/cz.glb"
+ width="100%"
+ height="320px"
+&gt;&lt;/agent-3d&gt;</pre>
+ </div>
+ </div>
+
+ <p>
+ Floating bubble in the corner ↘ — like a chatbot, but embodied.
+ </p>
+ </main>
+
+ <!-- Floating bubble — bottom-right of the viewport -->
+ <agent-3d
+ body="/avatars/cz.glb"
+ instructions="You are a cheerful 3D greeter. Wave when users say hi."
+ mode="floating"
+ position="bottom-right"
+ width="320px"
+ height="420px"
+ ></agent-3d>
+
+ <script type="module" src="../src/element.js"></script>
+</body>
+</html>
diff --git a/examples/skills/wave/SKILL.md b/examples/skills/wave/SKILL.md
new file mode 100644
index 000000000..9af24dcc6
--- /dev/null
+++ b/examples/skills/wave/SKILL.md
@@ -0,0 +1,22 @@
+---
+name: wave
+description: Wave at the user with context-appropriate enthusiasm.
+triggers:
+ - user_greeting
+ - user_farewell
+ - introduction
+cost: low
+---
+
+# Wave
+
+When the user greets you, says goodbye, or when you are introduced to
+someone, wave at them. Pick the style based on the vibe:
+
+- **casual** — default, for most greetings
+- **enthusiastic** — when the user seems excited, or after a shared win
+- **subtle** — in a professional context or mid-conversation
+
+Call `wave({ style: "casual" | "enthusiastic" | "subtle" })`.
+
+Do not wave more than once per turn. Do not wave if you just waved this session.
diff --git a/examples/skills/wave/handlers.js b/examples/skills/wave/handlers.js
new file mode 100644
index 000000000..2fc7375ca
--- /dev/null
+++ b/examples/skills/wave/handlers.js
@@ -0,0 +1,25 @@
+// Wave skill — handler implementation.
+// Falls back to the body's built-in wave clip if no style-specific clip is shipped.
+
+export async function wave(args, ctx) {
+ const { style = 'casual', duration_ms = 1500 } = args;
+
+ // Try to play a style-specific clip shipped with the skill bundle.
+ let played = false;
+ try {
+ const clip = await ctx.loadClip(new URL(`clips/wave-${style}.glb`, ctx.skillBaseURI).href);
+ if (clip) {
+ await ctx.viewer.play(clip, { blend: 0.2 });
+ played = true;
+ }
+ } catch {
+ // No bundled clip — fall through to hint-based lookup.
+ }
+
+ if (!played) {
+ played = ctx.viewer.playAnimationByHint('wave', { duration_ms });
+ }
+
+ ctx.memory.note('waved', { style, played });
+ return { ok: played, style };
+}
diff --git a/examples/skills/wave/manifest.json b/examples/skills/wave/manifest.json
new file mode 100644
index 000000000..e9c938855
--- /dev/null
+++ b/examples/skills/wave/manifest.json
@@ -0,0 +1,17 @@
+{
+ "spec": "skill/0.1",
+ "name": "wave",
+ "version": "0.1.0",
+ "description": "Wave at the user with context-appropriate enthusiasm.",
+ "license": "MIT",
+ "tags": ["greeting", "gesture", "mixamo-compatible"],
+ "requires": {
+ "rig": ["mixamo", "any"],
+ "runtime": ">=0.1.0",
+ "tools": []
+ },
+ "provides": {
+ "tools": ["wave"],
+ "triggers": ["greeting", "farewell", "introduction"]
+ }
+}
diff --git a/examples/skills/wave/tools.json b/examples/skills/wave/tools.json
new file mode 100644
index 000000000..3468710fb
--- /dev/null
+++ b/examples/skills/wave/tools.json
@@ -0,0 +1,25 @@
+{
+ "tools": [
+ {
+ "name": "wave",
+ "description": "Wave at the user.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "style": {
+ "type": "string",
+ "enum": ["casual", "enthusiastic", "subtle"],
+ "default": "casual"
+ },
+ "duration_ms": {
+ "type": "integer",
+ "minimum": 500,
+ "maximum": 5000,
+ "default": 1500
+ }
+ },
+ "required": []
+ }
+ }
+ ]
+}
diff --git a/examples/web-component.html b/examples/web-component.html
new file mode 100644
index 000000000..e208f2634
--- /dev/null
+++ b/examples/web-component.html
@@ -0,0 +1,45 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>&lt;mv-viewer&gt; Custom Element demo</title>
+ <style>
+ body { margin: 0; font-family: system-ui, sans-serif; background: #0f0f0f; color: #e9e9e9; padding: 24px; }
+ h1 { margin: 0 0 8px; font-weight: 500; }
+ h2 { margin: 24px 0 8px; font-size: 14px; font-weight: 500; color: #9a9a9a; text-transform: uppercase; letter-spacing: 0.05em; }
+ .grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); }
+ .log { font-family: ui-monospace, Menlo, monospace; font-size: 12px; color: #8fd4a4; background: #1a1a1a; border-radius: 4px; padding: 8px 12px; min-height: 24px; }
+ mv-viewer { border-radius: 8px; }
+ </style>
+ </head>
+ <body>
+ <h1>&lt;mv-viewer&gt; demo</h1>
+ <p>Minimal, auto-rotate, and poster/reveal variants of the Custom Element wrapper.</p>
+
+ <h2>Minimal</h2>
+ <mv-viewer id="v1" src="/avatars/cz.glb"></mv-viewer>
+ <div class="log" id="log1"></div>
+
+ <h2>Auto-rotate</h2>
+ <mv-viewer id="v2" src="/avatars/cz.glb" auto-rotate environment="Venice Sunset"></mv-viewer>
+
+ <h2>Poster &amp; reveal on interaction (click to load)</h2>
+ <mv-viewer
+ id="v3"
+ src="/avatars/cz.glb"
+ reveal="interaction"
+ poster="/3d.png"
+ disable-pan
+ ></mv-viewer>
+
+ <script type="module">
+ import '../src/components/ModelViewerElement.js';
+
+ const log = document.getElementById('log1');
+ const el = document.getElementById('v1');
+ el.addEventListener('load', (e) => (log.textContent = 'load ' + e.detail.src));
+ el.addEventListener('error', (e) => (log.textContent = 'error ' + e.detail.error));
+ </script>
+ </body>
+</html>
diff --git a/features.html b/features.html
index 60c3dc47e..dfca35d8f 100644
--- a/features.html
+++ b/features.html
@@ -224,5 +224,25 @@
});
})();
</script>
+
+ <script type="module">
+ // ?pretext=N opts into experimental hero behaviours. Default visitors see no change.
+ (async function () {
+ try {
+ const flag = new URLSearchParams(location.search).get('pretext');
+ if (!['1', '2', '3', '4'].includes(flag)) return;
+
+ const hero = document.querySelector('.hero');
+ if (!hero) return;
+
+ const { default: PretextHero } = await import('/src/features/hero-pretext.js');
+ const instance = new PretextHero(hero, { flag });
+ await instance.init();
+ window.__pretextHero = instance;
+ } catch (err) {
+ console.warn('[pretext-hero] init failed:', err);
+ }
+ })();
+ </script>
</body>
</html>
diff --git a/index.html b/index.html
index 7281d047c..d67f9b5f9 100644
--- a/index.html
+++ b/index.html
@@ -9,21 +9,21 @@
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"
/>
<meta name="author" content="nirholas" />
- <meta name="description" content="AI-powered 3D model viewer. Drag and drop glTF, GLB, and 3D files to preview instantly in your browser." />
- <meta name="keywords" content="3D viewer, glTF viewer, GLB viewer, 3D model viewer, online 3D viewer, WebGL, three.js, drag and drop 3D" />
+ <meta name="description" content="The first embodied 3D AI agent. Not a chatbot. A presence — with a body, a place, an identity, and memory." />
+ <meta name="keywords" content="3D agent, AI agent, embodied AI, glTF viewer, GLB viewer, 3D model viewer, WebGL, three.js, ERC-8004, agent identity" />
<meta name="theme-color" content="#000000" />
<!-- Open Graph -->
<meta property="og:type" content="website" />
- <meta property="og:title" content="3D Agent — AI-Powered 3D Model Viewer" />
- <meta property="og:description" content="Drag and drop glTF, GLB, and 3D files to preview instantly in your browser." />
+ <meta property="og:title" content="3D Agent — The First Embodied AI Agent" />
+ <meta property="og:description" content="Agents have always been imagined as present. We made that real." />
<meta property="og:url" content="https://3d.irish/" />
<meta property="og:site_name" content="3D Agent" />
<!-- Twitter / X -->
<meta name="twitter:card" content="summary_large_image" />
- <meta name="twitter:title" content="3D Agent — AI-Powered 3D Model Viewer" />
- <meta name="twitter:description" content="Drag and drop glTF, GLB, and 3D files to preview instantly in your browser." />
+ <meta name="twitter:title" content="3D Agent — Embodied AI" />
+ <meta name="twitter:description" content="The first 3D agent with a body, a place, an identity, and memory." />
<meta name="twitter:creator" content="@nichxbt" />
<link rel="canonical" href="https://3d.irish/" />
@@ -42,10 +42,20 @@
<a href="/" class="active">Viewer</a>
<a href="/features">Features</a>
<a href="/#register">Register Agent</a>
+ <a href="/dashboard" class="nav-dashboard">Dashboard</a>
</nav>
</header>
+
<main class="wrap">
+ <!-- Agent presence panel — rendered by AgentHome -->
+ <div class="agent-presence-sidebar" id="agent-presence-sidebar">
+ <div id="agent-home-container"></div>
+ </div>
+
+ <!-- 3D Viewer -->
<div class="viewer-container" id="viewer-container"></div>
+
+ <!-- Bottom bar -->
<div class="dropzone">
<div class="upload-btn">
<input type="file" name="file-input[]" id="file-input" multiple="" />
diff --git a/package-lock.json b/package-lock.json
index 4d672eaff..5f6b65274 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -13,6 +13,8 @@
"@aws-sdk/client-s3": "^3.651.0",
"@aws-sdk/s3-request-presigner": "^3.651.0",
"@chenglou/pretext": "^0.0.5",
+ "@gltf-transform/core": "^4.3.0",
+ "@gltf-transform/extensions": "^4.3.0",
"@neondatabase/serverless": "^0.10.1",
"@upstash/ratelimit": "^2.0.5",
"@upstash/redis": "^1.34.3",
@@ -31,7 +33,9 @@
"prettier": "^3.2.5",
"sharp": "^0.34.5",
"vite": "^8.0.8",
- "vite-plugin-pwa": "^1.2.0"
+ "vite-plugin-pwa": "^1.2.0",
+ "workbox-build": "^7.4.0",
+ "workbox-window": "^7.4.0"
}
},
"node_modules/@adraffy/ens-normalize": {
@@ -2503,6 +2507,8 @@
},
"node_modules/@emnapi/wasi-threads": {
"version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",
+ "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==",
"dev": true,
"license": "MIT",
"optional": true,
@@ -2510,6 +2516,31 @@
"tslib": "^2.4.0"
}
},
+ "node_modules/@gltf-transform/core": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/@gltf-transform/core/-/core-4.3.0.tgz",
+ "integrity": "sha512-ZeaQfszGJ9LYwELszu45CuDQCsE26lJNNe36FVmN8xclaT6WDdCj7fwGpQXo0/l/YgAVAHX+uO7YNBW75/SRYw==",
+ "license": "MIT",
+ "dependencies": {
+ "property-graph": "^4.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/donmccurdy"
+ }
+ },
+ "node_modules/@gltf-transform/extensions": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/@gltf-transform/extensions/-/extensions-4.3.0.tgz",
+ "integrity": "sha512-XDAjQPYVMHa/VDpSbfCBwI+/1muwRJCaXhUpLgnUzAjn0D//PgvIAcbNm1EwBl3LIWBSwjDUCn2LiMAjp+aXVw==",
+ "license": "MIT",
+ "dependencies": {
+ "@gltf-transform/core": "^4.3.0",
+ "ktx-parse": "^1.0.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/donmccurdy"
+ }
+ },
"node_modules/@img/colour": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
@@ -6078,6 +6109,12 @@
"node": ">=0.10.0"
}
},
+ "node_modules/ktx-parse": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/ktx-parse/-/ktx-parse-1.1.0.tgz",
+ "integrity": "sha512-mKp3y+FaYgR7mXWAbyyzpa/r1zDWeaunH+INJO4fou3hb45XuNSwar+7llrRyvpMWafxSIi99RNFJ05MHedaJQ==",
+ "license": "MIT"
+ },
"node_modules/leven": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz",
@@ -6768,6 +6805,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/property-graph": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/property-graph/-/property-graph-4.1.0.tgz",
+ "integrity": "sha512-AvPcP7XECNWy4LGmFQ77k7un4lSKM4eS29PTvW4ck95uYeLxXPWJM7hLuBqK91FaHqCcgJvIUCuNJjjxKE7VKQ==",
+ "license": "MIT"
+ },
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
@@ -7695,6 +7738,8 @@
},
"node_modules/undici-types": {
"version": "7.19.2",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.19.2.tgz",
+ "integrity": "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==",
"license": "MIT"
},
"node_modules/unicode-canonical-property-names-ecmascript": {
diff --git a/package.json b/package.json
index 71308b19b..eb468bdce 100644
--- a/package.json
+++ b/package.json
@@ -34,8 +34,11 @@
},
"scripts": {
"dev": "vite --port 3000",
+ "dev:lib": "TARGET=lib vite",
"build": "vite build",
- "clean": "rm -rf dist/* || true",
+ "build:lib": "TARGET=lib vite build",
+ "build:all": "npm run build && npm run build:lib",
+ "clean": "rm -rf dist/* dist-lib/* || true",
"generate-icons": "node scripts/generate-pwa-icons.mjs",
"test": "echo 'No tests configured' && exit 0",
"deploy": "npm run build && vercel --local-config vercel.json --prod",
@@ -46,6 +49,8 @@
"@aws-sdk/client-s3": "^3.651.0",
"@aws-sdk/s3-request-presigner": "^3.651.0",
"@chenglou/pretext": "^0.0.5",
+ "@gltf-transform/core": "^4.3.0",
+ "@gltf-transform/extensions": "^4.3.0",
"@neondatabase/serverless": "^0.10.1",
"@upstash/ratelimit": "^2.0.5",
"@upstash/redis": "^1.34.3",
diff --git a/prompts/pretext/01-install-and-scaffold.md b/prompts/pretext/01-install-and-scaffold.md
new file mode 100644
index 000000000..f6c8e5f67
--- /dev/null
+++ b/prompts/pretext/01-install-and-scaffold.md
@@ -0,0 +1,72 @@
+# Task: Install Pretext and scaffold the hero module
+
+## Context
+
+Repo: `/workspaces/3D`. The `/features` route is a static page: [features.html](../../features.html) + [features.css](../../features.css). It currently renders a two-column hero — text left, a `<model-viewer>` avatar right ([features.html:36-68](../../features.html#L36-L68)).
+
+We want to enhance the hero with [@chenglou/pretext](https://github.com/chenglou/pretext) — a DOM-free text measurement engine — so the subtitle can wrap around the avatar (task 02), the avatar can track the cursor (task 03), and optionally chase it with reflow per frame (task 04).
+
+This task lays the groundwork: install the library, scaffold a module, wire it up behind a feature flag, prove it loads.
+
+## Goal
+
+After this task, loading `/features?pretext=1` should:
+
+1. Initialize a `PretextHero` controller that has a handle on the hero DOM (title, subtitle, avatar container).
+2. Log `[pretext-hero] ready` once with the Pretext API in scope.
+3. Do nothing visible yet — no reflow, no cursor tracking. Those land in subsequent tasks.
+
+Without the flag, the page must render exactly as it does today.
+
+## Deliverable
+
+1. **Install the dep** — `npm install @chenglou/pretext`. Update [package.json](../../package.json) and [package-lock.json](../../package-lock.json). No other deps.
+2. **New file** `src/features/hero-pretext.js` — exports a default class `PretextHero` with:
+ - `constructor(root)` — `root` is the `.hero` element. Caches references to `.hero-content`, `.hero-title`, `.hero-subtitle`, `.hero-avatar`.
+ - `async init()` — dynamic-imports `@chenglou/pretext`, stores the API on `this.pretext`, logs `[pretext-hero] ready`, returns `this`.
+ - `dispose()` — no-op for now; reserved for later tasks.
+3. **Modify [features.html](../../features.html)** — at the bottom of `<body>`, add a small bootstrap `<script type="module">` that:
+ - Parses `new URLSearchParams(location.search).get('pretext')`.
+ - If the flag is `'1'` (or `'2'`, `'3'`, `'4'` — room for later tasks to enable themselves), dynamic-imports `/src/features/hero-pretext.js` and calls `new PretextHero(document.querySelector('.hero')).init()`.
+ - Wraps the whole thing in `try/catch` so a failure leaves the page in its current state.
+4. **Do NOT** modify [features.css](../../features.css) in this task.
+
+## Audit checklist
+
+- [ ] `npm install @chenglou/pretext` succeeds; lockfile updated.
+- [ ] `package.json` lists `@chenglou/pretext` under `dependencies` (not devDependencies).
+- [ ] `src/features/hero-pretext.js` is an ES module, default export, no top-level side effects.
+- [ ] Dynamic import of `@chenglou/pretext` uses the bare specifier — Vite resolves it.
+- [ ] The `?pretext=1` bootstrap runs only when the flag is present; default visitors see no change.
+- [ ] If `PretextHero.init()` throws, the failure is caught and the page keeps working.
+- [ ] `prefers-reduced-motion` is not relevant yet but should be acknowledged in a short comment at the top of `hero-pretext.js` so subsequent tasks don't forget.
+
+## Constraints
+
+- No CSS changes. No changes to [src/viewer.js](../../src/viewer.js), [src/app.js](../../src/app.js), or anything outside `features.*` and `src/features/`.
+- No TypeScript. Match the existing JS style in [src/](../../src/).
+- Do NOT implement text wrap, cursor tracking, or reflow in this task. Scaffolding only.
+- No `README.md` or other docs files.
+
+## Verification
+
+1. `node --check src/features/hero-pretext.js` — parses.
+2. `npx vite build` — completes. Note if it doesn't.
+3. Run the dev server, open `/features` — page renders exactly as before. No console log.
+4. Open `/features?pretext=1` — page renders identically, but console shows `[pretext-hero] ready` once and `window.__pretextHero` (optional, useful for debugging) holds the instance.
+5. Force a failure (temporarily rename the dep import) — page still renders; error is caught and logged.
+
+## Scope boundaries — do NOT do these
+
+- Do not call any Pretext layout APIs yet.
+- Do not attach mouse or scroll listeners.
+- Do not add a `<canvas>` or SVG overlay.
+- Do not change the avatar's `model-viewer` attributes.
+- Do not touch [style.css](../../style.css).
+
+## Reporting
+
+- Confirm the install + lockfile diff is minimal.
+- Report the Pretext API shape as seen via `console.log(Object.keys(mod))` inside `init()` — subsequent tasks need this.
+- Note the library version installed.
+- Note any Vite build warnings.
diff --git a/prompts/pretext/README.md b/prompts/pretext/README.md
new file mode 100644
index 000000000..6c8a8d48c
--- /dev/null
+++ b/prompts/pretext/README.md
@@ -0,0 +1,29 @@
+# Pretext hero experiments
+
+Self-contained prompt files for wiring [@chenglou/pretext](https://github.com/chenglou/pretext) — a 15KB DOM-free text measurement & layout engine — into the `/features` hero so the copy flows around the 3D avatar ([public/avatars/cz.glb](../../public/avatars/cz.glb)).
+
+Reference reading before starting any task:
+
+- Library: https://github.com/chenglou/pretext
+- Demos: https://chenglou.me/pretext/ (Dragon, Editorial Engine, Variable Typographic ASCII)
+- Community: https://github.com/qtakmalay/PreTextExperiments
+- npm: `@chenglou/pretext`
+
+Each task touches [features.html](../../features.html) and [features.css](../../features.css); [01](./01-install-and-scaffold.md) also adds the dep and a tiny module under [src/features/](../../src/features/).
+
+## Recommended execution order
+
+1. [01-install-and-scaffold.md](./01-install-and-scaffold.md) — **delegate-ready.** Install dep, add a `hero-pretext.js` module behind a feature flag. Unblocks 02–04.
+2. [02-hero-text-wrap.md](./02-hero-text-wrap.md) — **delegate-ready.** Static circle exclusion around avatar. The baseline "text parts around the avatar" effect. Depends on 01.
+3. [03-gaze-follow.md](./03-gaze-follow.md) — **delegate-ready.** Avatar head tracks cursor via `model-viewer`'s `camera-orbit`. Independent of Pretext reflow; safe to ship alongside 02.
+4. [04-dragon-mode.md](./04-dragon-mode.md) — **opt-in showcase.** Cursor-chasing avatar with per-frame text reflow. High visual payoff, medium gimmick risk — ship behind a query-string flag, not on by default. Depends on 01, 02.
+
+## Rules that apply to all tasks
+
+- Pretext's exclusion/obstacle API is not fully documented in the README — **read `node_modules/@chenglou/pretext/` source and the demos page before implementing.** If the needed API doesn't exist, fall back to manually splitting the text into two columns that flank the avatar and report this in your summary.
+- No changes to [src/viewer.js](../../src/viewer.js) or [src/app.js](../../src/app.js) — all work is scoped to `features.*` and a new `src/features/` folder.
+- Respect `prefers-reduced-motion` — cursor-follow and per-frame reflow must pause when the user has reduced motion enabled.
+- The feature must gracefully degrade: if Pretext fails to load, the current two-column hero must still render correctly.
+- `node --check` each new JS file. Run `npx vite build` and note whether it breaks. The pre-existing `@avaturn/sdk` resolution error in [src/avatar-creator.js](../../src/avatar-creator.js) is unrelated and should be ignored.
+- No new docs files beyond what each task explicitly requires.
+- If you discover an unrelated bug, note it in the reporting section. Do not fix it in the same change.
diff --git a/public/agent/index.html b/public/agent/index.html
new file mode 100644
index 000000000..7ef5f08d4
--- /dev/null
+++ b/public/agent/index.html
@@ -0,0 +1,239 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <title>Agent Home — 3D Agent</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="description" content="An embodied 3D AI agent — body, place, identity, memory." />
+ <meta name="theme-color" content="#000000" />
+
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ <link rel="stylesheet" href="/style.css" />
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500&display=swap" rel="stylesheet" />
+
+ <style>
+ body {
+ overflow: auto;
+ display: flex;
+ flex-direction: column;
+ }
+
+ .agent-page-header {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ padding: 1rem 1.618rem;
+ border-bottom: 1px solid rgba(255,255,255,0.06);
+ }
+
+ .agent-page-header a {
+ color: rgba(255,255,255,0.4);
+ text-decoration: none;
+ font-size: 0.764rem;
+ }
+
+ .agent-page-header a:hover {
+ color: rgba(255,255,255,0.8);
+ }
+
+ .agent-page-hero {
+ max-width: 520px;
+ margin: 4rem auto 2rem;
+ padding: 0 1rem;
+ text-align: center;
+ }
+
+ .agent-page-title {
+ font-size: 1.618rem;
+ font-weight: 300;
+ color: #e5e5e5;
+ letter-spacing: -0.02em;
+ margin: 0 0 0.618rem;
+ }
+
+ .agent-page-subtitle {
+ font-size: 0.764rem;
+ color: rgba(255,255,255,0.35);
+ line-height: 1.618;
+ }
+
+ .agent-page-card-wrap {
+ max-width: 420px;
+ margin: 0 auto;
+ padding: 0 1rem 4rem;
+ }
+
+ /* Expand the timeline on standalone page */
+ .agent-page-card-wrap .agent-home-timeline {
+ max-height: 320px;
+ }
+
+ /* Expand the panel to fill the card */
+ .agent-page-card-wrap .agent-home-panel {
+ background: rgba(12, 12, 18, 0.98);
+ border: 1px solid rgba(255,255,255,0.08);
+ border-radius: 12px;
+ }
+
+ .agent-embed-hint {
+ max-width: 420px;
+ margin: 1.618rem auto 0;
+ padding: 0 1rem;
+ }
+
+ .agent-embed-code {
+ background: rgba(255,255,255,0.04);
+ border: 1px solid rgba(255,255,255,0.08);
+ border-radius: 8px;
+ padding: 0.618rem 1rem;
+ font-family: monospace;
+ font-size: 0.618rem;
+ color: rgba(255,255,255,0.4);
+ word-break: break-all;
+ }
+
+ .agent-embed-label {
+ font-size: 0.618rem;
+ color: rgba(255,255,255,0.25);
+ margin-bottom: 0.382rem;
+ }
+
+ .agent-skills-full {
+ max-width: 420px;
+ margin: 1.618rem auto 0;
+ padding: 0 1rem;
+ }
+
+ .agent-skills-title {
+ font-size: 0.618rem;
+ color: rgba(255,255,255,0.25);
+ margin-bottom: 0.618rem;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ }
+
+ .agent-skills-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
+ gap: 0.618rem;
+ }
+
+ .agent-skill-card {
+ background: rgba(255,255,255,0.04);
+ border: 1px solid rgba(255,255,255,0.07);
+ border-radius: 8px;
+ padding: 0.618rem;
+ }
+
+ .agent-skill-card-name {
+ font-size: 0.764rem;
+ font-weight: 500;
+ color: rgba(255,255,255,0.7);
+ margin-bottom: 0.236rem;
+ }
+
+ .agent-skill-card-desc {
+ font-size: 0.618rem;
+ color: rgba(255,255,255,0.3);
+ line-height: 1.382;
+ }
+
+ .loading-placeholder {
+ color: rgba(255,255,255,0.2);
+ font-size: 0.764rem;
+ text-align: center;
+ padding: 2rem;
+ }
+ </style>
+</head>
+<body>
+ <div class="agent-page-header">
+ <a href="/">← 3D Agent</a>
+ </div>
+
+ <div class="agent-page-hero">
+ <h1 class="agent-page-title" id="page-agent-name">Agent</h1>
+ <p class="agent-page-subtitle" id="page-agent-desc">
+ Embodied. Present. Persistent.
+ </p>
+ </div>
+
+ <!-- Agent home card rendered by AgentHome -->
+ <div class="agent-page-card-wrap">
+ <div id="agent-home-container">
+ <div class="loading-placeholder">Loading agent…</div>
+ </div>
+ </div>
+
+ <!-- Skills catalog -->
+ <div class="agent-skills-full" id="agent-skills-section" style="display:none">
+ <div class="agent-skills-title">Skills</div>
+ <div class="agent-skills-grid" id="agent-skills-grid"></div>
+ </div>
+
+ <!-- Embed code -->
+ <div class="agent-embed-hint" id="agent-embed-section" style="display:none">
+ <div class="agent-embed-label">Embed this agent</div>
+ <div class="agent-embed-code" id="agent-embed-code"></div>
+ </div>
+
+ <script type="module">
+ import { AgentIdentity } from '/src/agent-identity.js';
+ import { AgentMemory } from '/src/agent-memory.js';
+ import { AgentSkills } from '/src/agent-skills.js';
+ import { AgentHome } from '/src/agent-home.js';
+ import { protocol } from '/src/agent-protocol.js';
+
+ // Pull agent id from URL: /agent/:id
+ const agentId = location.pathname.split('/').filter(Boolean).pop();
+
+ async function main() {
+ const identity = new AgentIdentity({ agentId: agentId || undefined, autoLoad: false });
+ await identity.load();
+
+ // Update hero
+ document.getElementById('page-agent-name').textContent = identity.name;
+ if (identity.description) {
+ document.getElementById('page-agent-desc').textContent = identity.description;
+ }
+
+ // Render the agent home card
+ const container = document.getElementById('agent-home-container');
+ container.innerHTML = '';
+ const home = new AgentHome(container, identity, protocol, null);
+ await home.render();
+
+ // Render skills catalog
+ if (identity.skills?.length) {
+ const skills = new AgentSkills(protocol, identity.memory);
+ const section = document.getElementById('agent-skills-section');
+ const grid = document.getElementById('agent-skills-grid');
+ section.style.display = '';
+ skills.list().filter(s => identity.skills.includes(s.name)).forEach(skill => {
+ const card = document.createElement('div');
+ card.className = 'agent-skill-card';
+ card.innerHTML = `
+ <div class="agent-skill-card-name">${skill.name}</div>
+ <div class="agent-skill-card-desc">${skill.description}</div>
+ `;
+ grid.appendChild(card);
+ });
+ }
+
+ // Embed code
+ const embedSection = document.getElementById('agent-embed-section');
+ const embedCode = document.getElementById('agent-embed-code');
+ const embedUrl = `${location.origin}/agent/${identity.id}`;
+ embedSection.style.display = '';
+ embedCode.textContent = `<iframe src="${embedUrl}" width="420" height="520" frameborder="0" style="border-radius:12px;border:none;"></iframe>`;
+ }
+
+ main().catch(err => {
+ document.getElementById('agent-home-container').innerHTML =
+ `<div class="loading-placeholder">Could not load agent: ${err.message}</div>`;
+ });
+ </script>
+</body>
+</html>
diff --git a/public/animations/manifest.json b/public/animations/manifest.json
new file mode 100644
index 000000000..ab417c98a
--- /dev/null
+++ b/public/animations/manifest.json
@@ -0,0 +1,51 @@
+[
+ {
+ "name": "idle",
+ "url": "/animations/idle.glb",
+ "label": "Idle",
+ "icon": "🧍",
+ "loop": true
+ },
+ {
+ "name": "walking",
+ "url": "/animations/walking.glb",
+ "label": "Walking",
+ "icon": "🚶",
+ "loop": true
+ },
+ {
+ "name": "running",
+ "url": "/animations/running.glb",
+ "label": "Running",
+ "icon": "🏃",
+ "loop": true
+ },
+ {
+ "name": "waving",
+ "url": "/animations/waving.glb",
+ "label": "Waving",
+ "icon": "👋",
+ "loop": false
+ },
+ {
+ "name": "dancing",
+ "url": "/animations/dancing.glb",
+ "label": "Dancing",
+ "icon": "💃",
+ "loop": true
+ },
+ {
+ "name": "sitting",
+ "url": "/animations/sitting.glb",
+ "label": "Sitting",
+ "icon": "🪑",
+ "loop": true
+ },
+ {
+ "name": "jumping",
+ "url": "/animations/jumping.glb",
+ "label": "Jumping",
+ "icon": "🦘",
+ "loop": false
+ }
+]
diff --git a/sdk/CHANGELOG.md b/sdk/CHANGELOG.md
new file mode 100644
index 000000000..69fc3d656
--- /dev/null
+++ b/sdk/CHANGELOG.md
@@ -0,0 +1,19 @@
+# Changelog
+
+All notable changes to `@nirholas/agent-kit` are documented here.
+
+The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+
+## [0.1.0] — 2026-04-14
+
+Initial public release.
+
+### Added
+- `AgentKit` — one-call class to ship an ERC-8004 agent (panel + registration + manifests).
+- `AgentPanel` — standalone floating chat UI with voice I/O. Bring your own `onMessage` handler.
+- ERC-8004 wallet + IPFS + on-chain registration flow via `registerAgent()`.
+- `.well-known` manifest generators: `agentRegistration()`, `agentCard()`, `aiPlugin()`.
+- Low-level exports: `IDENTITY_REGISTRY_ABI`, `REPUTATION_REGISTRY_ABI`, `VALIDATION_REGISTRY_ABI`, `REGISTRY_DEPLOYMENTS`, `agentRegistryId()`, `buildRegistrationJSON()`, `getIdentityRegistry()`, `connectWallet()`, `pinToIPFS()`.
+- TypeScript declarations (`index.d.ts`).
+- Standalone `styles.css` under the `.ak-*` namespace (no CSS-variable dependency).
+- Runnable example at `example/index.html`.
diff --git a/sdk/LICENSE b/sdk/LICENSE
new file mode 100644
index 000000000..4216cf919
--- /dev/null
+++ b/sdk/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 nirholas
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/sdk/README.md b/sdk/README.md
new file mode 100644
index 000000000..e2d179024
--- /dev/null
+++ b/sdk/README.md
@@ -0,0 +1,115 @@
+# @nirholas/agent-kit
+
+Ship an **ERC-8004 agent** with on-chain identity, a chat panel, and discoverable `.well-known` endpoints — in minutes.
+
+## Install
+
+```bash
+npm install @nirholas/agent-kit ethers
+```
+
+`ethers@^6` is a peer dependency (only needed if you call `register()`).
+
+## Quick start
+
+```js
+import { AgentKit } from '@nirholas/agent-kit';
+import '@nirholas/agent-kit/styles';
+
+const agent = new AgentKit({
+ name: 'My Agent',
+ description: 'Does cool stuff',
+ endpoint: 'https://myapp.com',
+ onMessage: async (text) => `You said: ${text}`,
+});
+
+agent.mount(document.body);
+```
+
+That's it — you now have a floating chat panel with voice I/O in the bottom-left corner.
+
+## Register on-chain
+
+```js
+await agent.register({
+ ipfsToken: 'your-web3storage-token',
+ imageFile: someFile, // optional
+ onStatus: (msg) => console.log(msg),
+});
+```
+
+Needs MetaMask (or any injected wallet) and a [web3.storage](https://web3.storage) API token. Requires a deployed ERC-8004 Identity Registry — set the address in `REGISTRY_DEPLOYMENTS` before calling.
+
+## Generate `.well-known` manifests
+
+```js
+const { agentRegistration, agentCard, aiPlugin } = agent.manifests({
+ openapiUrl: 'https://myapp.com/.well-known/openapi.yaml',
+});
+```
+
+Serve these JSON documents from:
+- `/.well-known/agent-registration.json` — ERC-8004 discovery
+- `/.well-known/agent-card.json` — A2A protocol
+- `/.well-known/ai-plugin.json` — OpenAI plugin manifest
+
+## API
+
+### `new AgentKit(options)`
+
+| Option | Type | Description |
+|---|---|---|
+| `name` | `string` **(required)** | Agent display name |
+| `endpoint` | `string` **(required)** | Your agent's public URL |
+| `description` | `string` | What the agent does |
+| `image` | `string` | Public URL to logo/avatar |
+| `version` | `string` | Semver version (default: `1.0.0`) |
+| `org` | `string` | Organization name for `agent-card.json` |
+| `skills` | `Array` | A2A skill definitions |
+| `services` | `Array` | Extra service entries (A2A, MCP endpoints) |
+| `onMessage` | `async (text) => string` | Your response handler |
+| `welcome` | `string` | Panel welcome message |
+| `voice` | `boolean` | Enable TTS on replies (default: `true`) |
+
+### Methods
+
+- `agent.mount(element?)` — attach panel to DOM (default: `document.body`)
+- `agent.open()` / `agent.close()` — show/hide the panel
+- `agent.addMessage(role, text)` — programmatically add a message (`role`: `'ak-agent'` or `'ak-user'`)
+- `agent.register(options)` — ERC-8004 on-chain registration
+- `agent.manifests(options)` — generate `.well-known` JSON documents
+- `agent.dispose()` — remove panel from DOM
+
+### Low-level exports
+
+For direct control:
+
+```js
+import {
+ AgentPanel,
+ connectWallet,
+ registerAgent,
+ pinToIPFS,
+ buildRegistrationJSON,
+ agentRegistration,
+ agentCard,
+ aiPlugin,
+ IDENTITY_REGISTRY_ABI,
+ REGISTRY_DEPLOYMENTS,
+} from '@nirholas/agent-kit';
+```
+
+## Configuring registry addresses
+
+Before calling `register()`, set your Identity Registry address in `sdk/src/erc8004/abi.js`:
+
+```js
+export const REGISTRY_DEPLOYMENTS = {
+ 8453: { identityRegistry: '0xYourBaseMainnetAddress' },
+ 84532: { identityRegistry: '0xYourBaseSepoliaAddress' },
+};
+```
+
+## License
+
+MIT
diff --git a/sdk/example/index.html b/sdk/example/index.html
new file mode 100644
index 000000000..11b30ba1d
--- /dev/null
+++ b/sdk/example/index.html
@@ -0,0 +1,131 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>@nirholas/agent-kit — demo</title>
+ <link rel="stylesheet" href="../src/styles.css" />
+ <style>
+ * { box-sizing: border-box; }
+ body {
+ margin: 0;
+ min-height: 100vh;
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
+ background: radial-gradient(ellipse at top, #1a1a2e 0%, #0a0a0a 60%);
+ color: #fff;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 32px;
+ text-align: center;
+ }
+ h1 {
+ font-size: 2rem;
+ margin: 0 0 12px;
+ font-weight: 500;
+ letter-spacing: -0.02em;
+ }
+ p {
+ max-width: 520px;
+ color: rgba(255, 255, 255, 0.6);
+ line-height: 1.6;
+ margin: 0 0 24px;
+ }
+ code {
+ background: rgba(255, 255, 255, 0.08);
+ padding: 2px 8px;
+ border-radius: 6px;
+ font-size: 0.85em;
+ }
+ .row { display: flex; gap: 12px; flex-wrap: wrap; justify-content: center; }
+ button.demo {
+ background: rgba(255, 255, 255, 0.08);
+ border: 1px solid rgba(255, 255, 255, 0.14);
+ color: #fff;
+ padding: 10px 18px;
+ border-radius: 10px;
+ font-family: inherit;
+ font-size: 13px;
+ cursor: pointer;
+ transition: all 0.2s ease;
+ }
+ button.demo:hover { background: rgba(255, 255, 255, 0.14); }
+ pre {
+ background: rgba(0, 0, 0, 0.5);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 10px;
+ padding: 16px;
+ text-align: left;
+ max-width: 640px;
+ width: 100%;
+ overflow-x: auto;
+ font-size: 12px;
+ color: rgba(255, 255, 255, 0.85);
+ }
+ </style>
+</head>
+<body>
+ <h1>agent-kit demo</h1>
+ <p>
+ Click the chat icon in the bottom-left to talk to the agent.
+ Try asking "what can you do" or "hello".
+ </p>
+
+ <div class="row">
+ <button class="demo" id="open-btn">Open panel</button>
+ <button class="demo" id="manifest-btn">Log manifests</button>
+ <button class="demo" id="say-btn">Inject message</button>
+ </div>
+
+ <pre id="out">// Click "Log manifests" to see the .well-known JSON this agent produces.</pre>
+
+ <script type="module">
+ import { AgentKit } from '../src/index.js';
+
+ const agent = new AgentKit({
+ name: 'Demo Agent',
+ description: 'A demo of @nirholas/agent-kit — the fastest way to ship an ERC-8004 agent.',
+ endpoint: 'https://demo.example.com',
+ image: 'https://demo.example.com/logo.png',
+ version: '0.1.0',
+ org: 'nirholas',
+ skills: [
+ {
+ id: 'greet',
+ name: 'Greet User',
+ description: 'Say hello',
+ tags: ['demo'],
+ examples: ['hello', 'hi'],
+ },
+ ],
+ onMessage: async (text) => {
+ const lower = text.toLowerCase();
+ if (/hello|hi|hey/.test(lower)) return 'Hey! This panel is powered by agent-kit.';
+ if (/what.*do|help/.test(lower)) return 'I can demo the SDK — try asking me about ERC-8004, manifests, or the chat panel.';
+ if (/erc|8004|chain|register/.test(lower)) return 'Call agent.register() to mint an on-chain identity via ERC-8004. Needs MetaMask + an IPFS token.';
+ if (/manifest|well.?known/.test(lower)) return 'agent.manifests() returns the 3 .well-known JSONs: agent-registration, agent-card, and ai-plugin.';
+ return `You said: "${text}". I'm just a demo — drop in your own onMessage handler for real logic.`;
+ },
+ });
+
+ agent.mount(document.body);
+
+ document.getElementById('open-btn').addEventListener('click', () => agent.open());
+
+ document.getElementById('manifest-btn').addEventListener('click', () => {
+ const manifests = agent.manifests({
+ openapiUrl: 'https://demo.example.com/.well-known/openapi.yaml',
+ });
+ document.getElementById('out').textContent = JSON.stringify(manifests, null, 2);
+ });
+
+ document.getElementById('say-btn').addEventListener('click', () => {
+ agent.open();
+ agent.addMessage('ak-agent', 'This message was injected from the host page via agent.addMessage().');
+ });
+
+ window.agent = agent;
+ </script>
+</body>
+</html>
diff --git a/sdk/package.json b/sdk/package.json
index f68c0b06e..8743902c6 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -1,12 +1,17 @@
{
- "name": "@speraxos/agent-kit",
+ "name": "@nirholas/agent-kit",
"version": "0.1.0",
"description": "Ship an ERC-8004 agent with on-chain identity, a chat panel, and discoverable .well-known endpoints in minutes.",
"type": "module",
"main": "./src/index.js",
"module": "./src/index.js",
+ "types": "./src/index.d.ts",
"exports": {
- ".": "./src/index.js",
+ ".": {
+ "types": "./src/index.d.ts",
+ "import": "./src/index.js",
+ "default": "./src/index.js"
+ },
"./styles": "./src/styles.css"
},
"files": [
diff --git a/sdk/src/erc8004/abi.js b/sdk/src/erc8004/abi.js
index bad922bbc..f1ad701d7 100644
--- a/sdk/src/erc8004/abi.js
+++ b/sdk/src/erc8004/abi.js
@@ -1,40 +1,111 @@
/**
- * ERC-8004 Identity Registry — minimal ABI.
+ * ERC-8004 Registry ABIs.
+ *
+ * Only the functions needed for agent registration, reputation, and validation.
* Full spec: https://eips.ethereum.org/EIPS/eip-8004
*/
export const IDENTITY_REGISTRY_ABI = [
+ // --- Registration ---
'function register(string agentURI) external returns (uint256 agentId)',
'function register(string agentURI, tuple(string metadataKey, bytes metadataValue)[] metadata) external returns (uint256 agentId)',
'function register() external returns (uint256 agentId)',
+
+ // --- URI ---
'function setAgentURI(uint256 agentId, string newURI) external',
'function tokenURI(uint256 agentId) external view returns (string)',
+
+ // --- Wallet ---
'function setAgentWallet(uint256 agentId, address newWallet, uint256 deadline, bytes signature) external',
'function getAgentWallet(uint256 agentId) external view returns (address)',
'function unsetAgentWallet(uint256 agentId) external',
+ 'function nonces(address owner) external view returns (uint256)',
+ 'function DOMAIN_SEPARATOR() external view returns (bytes32)',
+
+ // --- Metadata ---
'function getMetadata(uint256 agentId, string metadataKey) external view returns (bytes)',
'function setMetadata(uint256 agentId, string metadataKey, bytes metadataValue) external',
+
+ // --- ERC-721 basics ---
'function ownerOf(uint256 tokenId) external view returns (address)',
'function balanceOf(address owner) external view returns (uint256)',
'function totalSupply() external view returns (uint256)',
+ 'function isAgent(uint256 agentId) external view returns (bool)',
+
+ // --- Events ---
'event Registered(uint256 indexed agentId, string agentURI, address indexed owner)',
'event URIUpdated(uint256 indexed agentId, string newURI, address indexed updatedBy)',
+ 'event WalletSet(uint256 indexed agentId, address indexed wallet)',
+ 'event WalletUnset(uint256 indexed agentId)',
'event MetadataSet(uint256 indexed agentId, string indexed indexedMetadataKey, string metadataKey, bytes metadataValue)',
'event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)',
];
+export const REPUTATION_REGISTRY_ABI = [
+ // --- Submit ---
+ 'function submitFeedback(uint256 agentId, int8 score, string uri) external',
+
+ // --- Query ---
+ 'function getReputation(uint256 agentId) external view returns (int256 avgX100, uint256 count)',
+ 'function getFeedbackCount(uint256 agentId) external view returns (uint256)',
+ 'function getFeedback(uint256 agentId, uint256 index) external view returns (tuple(address from, int8 score, uint64 timestamp, string uri))',
+ 'function getFeedbackRange(uint256 agentId, uint256 offset, uint256 limit) external view returns (tuple(address from, int8 score, uint64 timestamp, string uri)[])',
+ 'function hasReviewed(uint256 agentId, address reviewer) external view returns (bool)',
+
+ // --- Events ---
+ 'event FeedbackSubmitted(uint256 indexed agentId, address indexed from, int8 score, string uri)',
+];
+
+export const VALIDATION_REGISTRY_ABI = [
+ // --- Admin ---
+ 'function addValidator(address v) external',
+ 'function removeValidator(address v) external',
+ 'function isValidator(address v) external view returns (bool)',
+ 'function owner() external view returns (address)',
+ 'function transferOwnership(address newOwner) external',
+
+ // --- Record ---
+ 'function recordValidation(uint256 agentId, bool passed, bytes32 proofHash, string proofURI, string kind) external',
+
+ // --- Query ---
+ 'function getValidationCount(uint256 agentId) external view returns (uint256)',
+ 'function getValidation(uint256 agentId, uint256 index) external view returns (tuple(address validator, bool passed, bytes32 proofHash, string proofURI, uint64 timestamp, string kind))',
+ 'function getLatestByKind(uint256 agentId, string kind) external view returns (tuple(address validator, bool passed, bytes32 proofHash, string proofURI, uint64 timestamp, string kind))',
+ 'function getValidationRange(uint256 agentId, uint256 offset, uint256 limit) external view returns (tuple(address validator, bool passed, bytes32 proofHash, string proofURI, uint64 timestamp, string kind)[])',
+
+ // --- Events ---
+ 'event ValidatorAdded(address indexed validator)',
+ 'event ValidatorRemoved(address indexed validator)',
+ 'event ValidationRecorded(uint256 indexed agentId, address indexed validator, bool passed, bytes32 proofHash, string kind)',
+];
+
/**
- * Known deployments — fill with your contract addresses.
- * Format: eip155:{chainId}:{address}
+ * Known deployments — add chain-specific addresses here.
+ * Format follows agentRegistry spec: eip155:{chainId}:{address}
*/
export const REGISTRY_DEPLOYMENTS = {
- 8453: { identityRegistry: '' }, // Base mainnet
- 84532: { identityRegistry: '' }, // Base Sepolia
- 1: { identityRegistry: '' }, // Ethereum mainnet
+ // Base mainnet (chain 8453)
+ 8453: {
+ identityRegistry: '', // TODO: fill once deployed
+ reputationRegistry: '', // TODO: fill once deployed
+ validationRegistry: '', // TODO: fill once deployed
+ },
+ // Base Sepolia testnet (chain 84532)
+ 84532: {
+ identityRegistry: '', // TODO: fill in from Deploy.s.sol broadcast output
+ reputationRegistry: '',
+ validationRegistry: '',
+ },
+ // Ethereum mainnet (chain 1) — if deployed
+ 1: {
+ identityRegistry: '',
+ reputationRegistry: '',
+ validationRegistry: '',
+ },
};
/**
- * Build the agentRegistry identifier per spec.
+ * Build the agentRegistry string per spec.
* @param {number} chainId
* @param {string} registryAddress
* @returns {string} e.g. "eip155:8453:0x742..."
diff --git a/sdk/src/index.d.ts b/sdk/src/index.d.ts
new file mode 100644
index 000000000..c4893b1b4
--- /dev/null
+++ b/sdk/src/index.d.ts
@@ -0,0 +1,241 @@
+/**
+ * @nirholas/agent-kit — TypeScript definitions
+ */
+
+// ---------------------------------------------------------------------------
+// Shared types
+// ---------------------------------------------------------------------------
+
+export interface ServiceEntry {
+ name: string;
+ endpoint: string;
+ version?: string;
+}
+
+export interface SkillDefinition {
+ id: string;
+ name: string;
+ description: string;
+ tags?: string[];
+ examples?: string[];
+}
+
+export interface RegistrationRecord {
+ agentId: number;
+ agentRegistry: string;
+}
+
+export interface RegistrationResult {
+ agentId: number;
+ registrationCID: string;
+ txHash: string;
+}
+
+export type StatusCallback = (message: string) => void;
+export type MessageHandler = (text: string) => string | Promise<string>;
+
+// ---------------------------------------------------------------------------
+// AgentPanel
+// ---------------------------------------------------------------------------
+
+export interface AgentPanelOptions {
+ title?: string;
+ welcome?: string;
+ placeholder?: string;
+ onMessage?: MessageHandler;
+ voice?: boolean;
+}
+
+export class AgentPanel {
+ constructor(options?: AgentPanelOptions);
+ mount(container: HTMLElement): this;
+ open(): void;
+ close(): void;
+ addMessage(role: 'ak-agent' | 'ak-user' | string, text: string): void;
+ dispose(): void;
+}
+
+// ---------------------------------------------------------------------------
+// AgentKit — the primary API
+// ---------------------------------------------------------------------------
+
+export interface AgentKitOptions {
+ /** Agent display name (required) */
+ name: string;
+ /** Agent public URL (required) */
+ endpoint: string;
+ /** What the agent does */
+ description?: string;
+ /** Public URL to logo/avatar */
+ image?: string;
+ /** Semver version string */
+ version?: string;
+ /** Organization name for agent-card.json */
+ org?: string;
+ /** A2A skill definitions */
+ skills?: SkillDefinition[];
+ /** Extra service entries */
+ services?: ServiceEntry[];
+ /** async response handler */
+ onMessage?: MessageHandler;
+ /** Panel welcome message */
+ welcome?: string;
+ /** Enable text-to-speech on replies */
+ voice?: boolean;
+}
+
+export interface RegisterOptions {
+ imageFile?: File;
+ services?: ServiceEntry[];
+ ipfsToken?: string;
+ onStatus?: StatusCallback;
+}
+
+export interface ManifestsOptions {
+ openapiUrl?: string;
+ registrations?: RegistrationRecord[];
+}
+
+export interface ManifestsResult {
+ agentRegistration: AgentRegistrationDocument;
+ agentCard: AgentCardDocument;
+ aiPlugin: AiPluginDocument;
+}
+
+export class AgentKit {
+ constructor(options: AgentKitOptions);
+ mount(container?: HTMLElement): this;
+ open(): this;
+ close(): this;
+ addMessage(role: string, text: string): this;
+ register(options?: RegisterOptions): Promise<RegistrationResult>;
+ manifests(options?: ManifestsOptions): ManifestsResult;
+ dispose(): void;
+}
+
+// ---------------------------------------------------------------------------
+// Manifest document shapes
+// ---------------------------------------------------------------------------
+
+export interface AgentRegistrationDocument {
+ type: string;
+ name: string;
+ description?: string;
+ image?: string;
+ active: boolean;
+ services: ServiceEntry[];
+ registrations: RegistrationRecord[];
+ supportedTrust: string[];
+}
+
+export interface AgentCardDocument {
+ name: string;
+ description?: string;
+ url: string;
+ provider: { organization: string; url: string };
+ version: string;
+ capabilities: {
+ streaming: boolean;
+ pushNotifications: boolean;
+ stateTransitionHistory: boolean;
+ };
+ authentication: { schemes: string[]; credentials: null };
+ defaultInputModes: string[];
+ defaultOutputModes: string[];
+ skills: SkillDefinition[];
+}
+
+export interface AiPluginDocument {
+ schema_version: 'v1';
+ name_for_human: string;
+ name_for_model: string;
+ description_for_human: string;
+ description_for_model: string;
+ auth: { type: 'none' };
+ api: { type: 'openapi'; url: string };
+ logo_url: string;
+ contact_email: string;
+ legal_info_url: string;
+}
+
+// ---------------------------------------------------------------------------
+// Manifest generators (low-level)
+// ---------------------------------------------------------------------------
+
+export function agentRegistration(opts: {
+ name: string;
+ description?: string;
+ endpoint: string;
+ image?: string;
+ services?: ServiceEntry[];
+ registrations?: RegistrationRecord[];
+}): AgentRegistrationDocument;
+
+export function agentCard(opts: {
+ name: string;
+ description?: string;
+ url: string;
+ version?: string;
+ org?: string;
+ skills?: SkillDefinition[];
+}): AgentCardDocument;
+
+export function aiPlugin(opts: {
+ name: string;
+ description?: string;
+ openapiUrl: string;
+ logoUrl?: string;
+ contactEmail?: string;
+ legalUrl?: string;
+}): AiPluginDocument;
+
+// ---------------------------------------------------------------------------
+// ERC-8004 low-level
+// ---------------------------------------------------------------------------
+
+export interface ConnectWalletResult {
+ provider: unknown;
+ signer: unknown;
+ address: string;
+ chainId: number;
+}
+
+export function connectWallet(): Promise<ConnectWalletResult>;
+
+export function pinToIPFS(blob: Blob | File, apiToken?: string): Promise<string>;
+
+export function buildRegistrationJSON(opts: {
+ name: string;
+ description?: string;
+ imageCID?: string | null;
+ agentId: number;
+ chainId: number;
+ registryAddr: string;
+ services?: ServiceEntry[];
+}): AgentRegistrationDocument;
+
+export function getIdentityRegistry(chainId: number, signer: unknown): unknown;
+
+export function registerAgent(opts: {
+ name: string;
+ description?: string;
+ endpoint: string;
+ imageFile?: File;
+ services?: ServiceEntry[];
+ apiToken?: string;
+ onStatus?: StatusCallback;
+}): Promise<RegistrationResult>;
+
+export const IDENTITY_REGISTRY_ABI: readonly string[];
+export const REPUTATION_REGISTRY_ABI: readonly string[];
+export const VALIDATION_REGISTRY_ABI: readonly string[];
+
+export interface RegistryDeployment {
+ identityRegistry: string;
+ reputationRegistry?: string;
+ validationRegistry?: string;
+}
+
+export const REGISTRY_DEPLOYMENTS: Record<number, RegistryDeployment>;
+
+export function agentRegistryId(chainId: number, registryAddress: string): string;
diff --git a/sdk/src/index.js b/sdk/src/index.js
index 237fafe96..d52199ec1 100644
--- a/sdk/src/index.js
+++ b/sdk/src/index.js
@@ -1,13 +1,13 @@
/**
- * @speraxos/agent-kit
+ * @nirholas/agent-kit
*
* Ship an ERC-8004 agent with on-chain identity, a chat panel,
* and discoverable .well-known endpoints in minutes.
*
* Quick start:
*
- * import { AgentKit } from '@speraxos/agent-kit';
- * import '@speraxos/agent-kit/styles';
+ * import { AgentKit } from '@nirholas/agent-kit';
+ * import '@nirholas/agent-kit/styles';
*
* const agent = new AgentKit({
* name: 'My Agent',
diff --git a/sdk/src/styles.css b/sdk/src/styles.css
index e2db54f38..db44f630c 100644
--- a/sdk/src/styles.css
+++ b/sdk/src/styles.css
@@ -1,5 +1,5 @@
-/* @speraxos/agent-kit — panel styles
- Import this file once in your app: import '@speraxos/agent-kit/styles'
+/* @nirholas/agent-kit — panel styles
+ Import this file once in your app: import '@nirholas/agent-kit/styles'
All classes are namespaced under .ak-* to avoid collisions.
*/
diff --git a/src/agent-avatar.js b/src/agent-avatar.js
index debbf0007..b6c74cd4a 100644
--- a/src/agent-avatar.js
+++ b/src/agent-avatar.js
@@ -20,7 +20,7 @@
*/
import { ACTION_TYPES } from './agent-protocol.js';
-import { Vector3, MathUtils } from 'three';
+import { Vector3, Box3, MathUtils } from 'three';
const DEG2RAD = Math.PI / 180;
@@ -190,7 +190,7 @@ export class AgentAvatar {
const target = action.payload?.target;
if (target === 'model' && this.viewer?.content) {
// Look at the bounding box center of the loaded model
- const box = new (await import('three').then(m => m.Box3))();
+ const box = new Box3();
const center = new Vector3();
box.setFromObject(this.viewer.content).getCenter(center);
this._lookTarget = center;
diff --git a/src/animation-manager.js b/src/animation-manager.js
new file mode 100644
index 000000000..3c2b3180b
--- /dev/null
+++ b/src/animation-manager.js
@@ -0,0 +1,355 @@
+import { AnimationMixer, LoopRepeat, LoopOnce } from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+
+/**
+ * Manages loading external animation clips (e.g. from Mixamo) and applying
+ * them to any skinned model with crossfade transitions.
+ *
+ * Usage:
+ * const mgr = new AnimationManager();
+ * mgr.attach(skinnedModel);
+ * await mgr.loadAnimation('idle', '/animations/idle.glb');
+ * mgr.play('idle');
+ * mgr.crossfadeTo('walking', 0.4);
+ */
+
+const DEFAULT_CROSSFADE = 0.35; // seconds
+
+export class AnimationManager {
+ constructor() {
+ /** @type {THREE.Object3D|null} */
+ this.model = null;
+ /** @type {AnimationMixer|null} */
+ this.mixer = null;
+ /** @type {Map<string, THREE.AnimationClip>} */
+ this.clips = new Map();
+ /** @type {Map<string, THREE.AnimationAction>} */
+ this.actions = new Map();
+ /** @type {string|null} */
+ this.currentName = null;
+ /** @type {THREE.AnimationAction|null} */
+ this.currentAction = null;
+ /** @type {GLTFLoader} */
+ this.loader = new GLTFLoader();
+ /** @type {Function|null} */
+ this.onChange = null;
+
+ this._animationDefs = [];
+ }
+
+ /**
+ * Attach the manager to a loaded model. Creates a new mixer.
+ * Call this every time a new model is loaded.
+ * @param {THREE.Object3D} model
+ */
+ attach(model) {
+ this.detach();
+ this.model = model;
+ this.mixer = new AnimationMixer(model);
+ this.actions.clear();
+ this.currentAction = null;
+ this.currentName = null;
+
+ // Re-create actions for any clips that were already loaded
+ for (const [name, clip] of this.clips) {
+ const retargetedClip = this._retargetClip(clip, name);
+ const action = this.mixer.clipAction(retargetedClip);
+ action.enabled = true;
+ this.actions.set(name, action);
+ }
+ }
+
+ /**
+ * Detach from current model, stop all actions, dispose mixer.
+ */
+ detach() {
+ if (this.mixer) {
+ this.mixer.stopAllAction();
+ this.mixer.uncacheRoot(this.mixer.getRoot());
+ this.mixer = null;
+ }
+ this.model = null;
+ this.actions.clear();
+ this.currentAction = null;
+ this.currentName = null;
+ }
+
+ /**
+ * Register animation definitions to be loaded lazily or eagerly.
+ * @param {Array<{name: string, url: string, loop?: boolean}>} defs
+ */
+ setAnimationDefs(defs) {
+ this._animationDefs = defs;
+ }
+
+ /**
+ * Get registered animation definitions.
+ * @returns {Array<{name: string, url: string, loop?: boolean}>}
+ */
+ getAnimationDefs() {
+ return this._animationDefs;
+ }
+
+ /**
+ * Load an animation clip from a GLB/glTF file and register it.
+ * If a model is attached, also creates the action.
+ * @param {string} name - Friendly name (e.g. "idle", "walking")
+ * @param {string} url - URL of the GLB/glTF containing the animation
+ * @param {object} [options]
+ * @param {boolean} [options.loop=true] - Whether to loop the animation
+ * @returns {Promise<THREE.AnimationClip>}
+ */
+ async loadAnimation(name, url, options = {}) {
+ // Return cached clip if already loaded
+ if (this.clips.has(name)) {
+ return this.clips.get(name);
+ }
+
+ const gltf = await new Promise((resolve, reject) => {
+ this.loader.load(url, resolve, undefined, reject);
+ });
+
+ const clip = gltf.animations[0];
+ if (!clip) {
+ throw new Error(`No animation found in ${url}`);
+ }
+
+ clip.name = name;
+ this.clips.set(name, clip);
+
+ // If we have a model attached, create the action immediately
+ if (this.model && this.mixer) {
+ const retargetedClip = this._retargetClip(clip, name);
+ const action = this.mixer.clipAction(retargetedClip);
+ action.enabled = true;
+ action.setLoop(options.loop === false ? LoopOnce : LoopRepeat);
+ if (options.loop === false) {
+ action.clampWhenFinished = true;
+ }
+ this.actions.set(name, action);
+ }
+
+ return clip;
+ }
+
+ /**
+ * Load all registered animation definitions.
+ * Loads in parallel, non-blocking. Failed loads are logged but don't throw.
+ * @returns {Promise<void>}
+ */
+ async loadAll() {
+ const promises = this._animationDefs.map(async (def) => {
+ try {
+ await this.loadAnimation(def.name, def.url, { loop: def.loop !== false });
+ } catch (e) {
+ console.warn(`[AnimationManager] Failed to load "${def.name}" from ${def.url}:`, e);
+ }
+ });
+ await Promise.all(promises);
+ }
+
+ /**
+ * Play a named animation immediately (no crossfade).
+ * @param {string} name
+ */
+ play(name) {
+ const action = this.actions.get(name);
+ if (!action) {
+ console.warn(`[AnimationManager] Animation "${name}" not loaded`);
+ return;
+ }
+
+ if (this.currentAction && this.currentAction !== action) {
+ this.currentAction.fadeOut(0.01);
+ }
+
+ action.reset().fadeIn(0.01).play();
+ this.currentAction = action;
+ this.currentName = name;
+
+ if (this.onChange) this.onChange(name);
+ }
+
+ /**
+ * Crossfade from the current animation to a named animation.
+ * @param {string} name
+ * @param {number} [duration] - Crossfade duration in seconds
+ */
+ crossfadeTo(name, duration = DEFAULT_CROSSFADE) {
+ if (name === this.currentName) return;
+
+ const nextAction = this.actions.get(name);
+ if (!nextAction) {
+ console.warn(`[AnimationManager] Animation "${name}" not loaded`);
+ return;
+ }
+
+ nextAction.reset();
+ nextAction.play();
+
+ if (this.currentAction) {
+ this.currentAction.crossFadeTo(nextAction, duration, true);
+ } else {
+ nextAction.fadeIn(duration);
+ }
+
+ this.currentAction = nextAction;
+ this.currentName = name;
+
+ if (this.onChange) this.onChange(name);
+ }
+
+ /**
+ * Stop all animations.
+ */
+ stopAll() {
+ if (this.mixer) {
+ this.mixer.stopAllAction();
+ }
+ this.currentAction = null;
+ this.currentName = null;
+ if (this.onChange) this.onChange(null);
+ }
+
+ /**
+ * Update the mixer. Call this in the render loop.
+ * @param {number} deltaTime - Time since last frame in seconds
+ */
+ update(deltaTime) {
+ if (this.mixer) {
+ this.mixer.update(deltaTime);
+ }
+ }
+
+ /**
+ * Retarget an animation clip to match the current model's skeleton.
+ * Handles common naming convention mismatches between Mixamo exports.
+ * @param {THREE.AnimationClip} clip
+ * @param {string} name
+ * @returns {THREE.AnimationClip}
+ * @private
+ */
+ _retargetClip(clip, name) {
+ if (!this.model) return clip;
+
+ // Collect bone names from the current model
+ const modelBones = new Set();
+ this.model.traverse((node) => {
+ if (node.isBone) {
+ modelBones.add(node.name);
+ }
+ });
+
+ if (modelBones.size === 0) return clip;
+
+ // Check if clip tracks already match model bones
+ const clipBoneNames = new Set();
+ for (const track of clip.tracks) {
+ const boneName = track.name.split('.')[0];
+ clipBoneNames.add(boneName);
+ }
+
+ // If most tracks already match, no retargeting needed
+ let matchCount = 0;
+ for (const boneName of clipBoneNames) {
+ if (modelBones.has(boneName)) matchCount++;
+ }
+ if (matchCount / clipBoneNames.size > 0.5) return clip;
+
+ // Build a name mapping for retargeting
+ const nameMap = this._buildBoneNameMap(modelBones, clipBoneNames);
+ if (!nameMap) return clip;
+
+ // Clone the clip with remapped track names
+ const newTracks = clip.tracks
+ .map((track) => {
+ const parts = track.name.split('.');
+ const boneName = parts[0];
+ const property = parts.slice(1).join('.');
+ const mappedName = nameMap.get(boneName);
+ if (!mappedName) return null;
+ const newTrack = track.clone();
+ newTrack.name = `${mappedName}.${property}`;
+ return newTrack;
+ })
+ .filter(Boolean);
+
+ return clip.clone().resetDuration();
+ }
+
+ /**
+ * Attempts to build a bone name mapping between two skeleton naming conventions.
+ * Supports: Mixamo → Mixamo, stripped prefixes, common standardizations.
+ * @param {Set<string>} modelBones
+ * @param {Set<string>} clipBones
+ * @returns {Map<string, string>|null}
+ * @private
+ */
+ _buildBoneNameMap(modelBones, clipBones) {
+ const map = new Map();
+
+ // Strategy 1: Strip common prefixes (e.g., "mixamorig:" vs "mixamorig1:")
+ const modelArr = [...modelBones];
+ const clipArr = [...clipBones];
+
+ const stripPrefix = (name) =>
+ name.replace(/^mixamorig\d*[_:]?/i, '').replace(/^Armature[_/]?/i, '');
+
+ const modelStripped = new Map(modelArr.map((n) => [stripPrefix(n), n]));
+
+ let matches = 0;
+ for (const clipBone of clipArr) {
+ const stripped = stripPrefix(clipBone);
+ if (modelStripped.has(stripped)) {
+ map.set(clipBone, modelStripped.get(stripped));
+ matches++;
+ }
+ }
+
+ // If we matched at least 50% of bones, consider it a valid mapping
+ if (matches / clipArr.length > 0.5) {
+ return map;
+ }
+
+ // Strategy 2: Case-insensitive matching
+ const modelLower = new Map(modelArr.map((n) => [n.toLowerCase(), n]));
+ map.clear();
+ matches = 0;
+
+ for (const clipBone of clipArr) {
+ if (modelLower.has(clipBone.toLowerCase())) {
+ map.set(clipBone, modelLower.get(clipBone.toLowerCase()));
+ matches++;
+ }
+ }
+
+ if (matches / clipArr.length > 0.5) {
+ return map;
+ }
+
+ return null;
+ }
+
+ /**
+ * Get the list of loaded animation names.
+ * @returns {string[]}
+ */
+ getLoadedNames() {
+ return [...this.clips.keys()];
+ }
+
+ /**
+ * Check if a specific animation is loaded.
+ * @param {string} name
+ * @returns {boolean}
+ */
+ isLoaded(name) {
+ return this.clips.has(name);
+ }
+
+ dispose() {
+ this.detach();
+ this.clips.clear();
+ this._animationDefs = [];
+ }
+}
diff --git a/src/app.js b/src/app.js
index 2ad7abd89..315ea8d00 100644
--- a/src/app.js
+++ b/src/app.js
@@ -1,6 +1,7 @@
import * as THREE from 'three';
import WebGL from 'three/addons/capabilities/WebGL.js';
import { Viewer } from './viewer.js';
+import { Editor } from './editor/index.js';
import { SimpleDropzone } from 'simple-dropzone';
import { Validator } from './validator.js';
import { Footer } from './components/footer';
@@ -17,6 +18,12 @@ import { AgentSkills } from './agent-skills.js';
import { AgentAvatar } from './agent-avatar.js';
import { AgentHome } from './agent-home.js';
+// Runtime — LLM brain, scene control, file-based memory, skill bundles
+import { SceneController } from './runtime/scene.js';
+import { Runtime } from './runtime/index.js';
+import { Memory } from './memory/index.js';
+import { SkillRegistry } from './skills/index.js';
+
window.THREE = THREE;
window.VIEWER = {};
@@ -38,10 +45,13 @@ class App {
model: hash.model || '',
preset: hash.preset || '',
cameraPosition: hash.cameraPosition ? hash.cameraPosition.split(',').map(Number) : null,
+ brain: hash.brain || 'none',
+ proxyURL: hash.proxyURL || '',
};
this.el = el;
this.viewer = null;
+ this.editor = null;
this.viewerEl = null;
this.spinnerEl = el.querySelector('.spinner');
this.dropEl = el.querySelector('.wrap');
@@ -54,6 +64,10 @@ class App {
this.skills = null; // initialised after identity loads
this.avatar = null; // initialised after viewer + content load
this.agentHome = null;
+ this.sceneCtrl = null; // SceneController — created when viewer is ready
+ this.runtime = null; // LLM Runtime — created after identity + memory load
+ this.fileMemory = null; // file-based Memory for LLM context
+ this.skillRegistry = null; // external skill bundle loader
// Wire validator results into the protocol
this._hookValidator();
@@ -94,10 +108,52 @@ class App {
// Skills need identity + memory
this.skills = new AgentSkills(protocol, this.identity.memory);
+ // File-based memory for LLM context injection
+ this.fileMemory = await Memory.load({
+ mode: 'local',
+ namespace: this.identity.id,
+ });
+
+ // External skill bundle loader (empty initially — skills load on demand)
+ this.skillRegistry = new SkillRegistry({ trust: 'owned-only' });
+
+ // LLM Runtime — the agent's brain. Defaults to 'none' provider
+ // (NichAgent pattern matching). Configure with #brain=anthropic&proxyURL=...
+ this.runtime = new Runtime({
+ manifest: {
+ name: this.identity.name || 'Agent',
+ instructions: [
+ `You are ${this.identity.name || 'Agent'}, an AI agent embedded in a 3D model viewer at 3d.irish.`,
+ 'You can control the 3D scene, remember things, and help users with their 3D work.',
+ 'Be concise, clear, and helpful. You are present and embodied — act like it.',
+ ].join(' '),
+ brain: {
+ provider: this.options.brain,
+ proxyURL: this.options.proxyURL || undefined,
+ },
+ tools: ['wave', 'lookAt', 'play_clip', 'setExpression', 'speak', 'remember'],
+ },
+ viewer: this.sceneCtrl, // null until viewer loads
+ memory: this.fileMemory,
+ skills: this.skillRegistry,
+ });
+
+ // Bridge Runtime assistant messages to the protocol bus
+ this.runtime.addEventListener('brain:message', (e) => {
+ if (e.detail.role === 'assistant' && e.detail.content) {
+ protocol.emit({
+ type: ACTION_TYPES.SPEAK,
+ payload: { text: e.detail.content, sentiment: 0 },
+ agentId: this.identity.id,
+ });
+ }
+ });
+
// Expose agent on window for debugging
window.VIEWER.agent_protocol = protocol;
window.VIEWER.agent_identity = this.identity;
window.VIEWER.agent_skills = this.skills;
+ window.VIEWER.agent_runtime = this.runtime;
// Announce presence
protocol.emit({
@@ -113,7 +169,7 @@ class App {
await this.agentHome.render();
}
- // Boot the voice/chat agent with skills wired in
+ // Boot the voice/chat agent with skills and runtime wired in
this._initNichAgent();
// Log all significant actions to identity history (fire-and-forget)
@@ -136,7 +192,7 @@ class App {
}
_initNichAgent() {
- const agent = new NichAgent(document.body, protocol, this.skills, this.identity);
+ const agent = new NichAgent(document.body, protocol, this.skills, this.identity, this.runtime);
window.VIEWER.agent = agent;
// Greet on first open
agent.onFirstOpen = () => {
@@ -153,6 +209,9 @@ class App {
createViewer() {
this.viewerEl = this.viewerContainerEl;
this.viewer = new Viewer(this.viewerEl, this.options);
+ this.editor = new Editor(this.viewer);
+ this.editor.attach();
+ window.VIEWER.editor = this.editor;
return this.viewer;
}
@@ -254,6 +313,18 @@ class App {
// Attach the avatar empathy system to the newly loaded content
this._attachAvatar(viewer);
+ // Notify the editor of the new model so it can rebuild panels
+ if (this.editor) {
+ this.editor.onContentChanged({
+ url: typeof rootFile === 'string' ? rootFile : null,
+ file: typeof rootFile === 'object' ? rootFile : null,
+ name: typeof rootFile === 'string' ? rootFile : rootFile.name,
+ });
+ }
+
+ // Configure external animations (Mixamo-style) for skinned models
+ this._configureAnimations(viewer);
+
if (!this.options.kiosk) {
this.validator.validate(fileURL, rootPath, fileMap, gltf);
}
@@ -267,10 +338,15 @@ class App {
this.avatar = new AgentAvatar(viewer, protocol, this.identity);
this.avatar.attach();
+ // Create (or replace) the SceneController for agent scene operations
+ this.sceneCtrl = new SceneController(viewer);
+ if (this.runtime) this.runtime.viewer = this.sceneCtrl;
+
// Update agent-home with the live avatar reference
if (this.agentHome) this.agentHome.avatar = this.avatar;
window.VIEWER.agent_avatar = this.avatar;
+ window.VIEWER.scene_ctrl = this.sceneCtrl;
// Let the skills system access the viewer
if (this.skills) {
@@ -278,6 +354,61 @@ class App {
}
}
+ /**
+ * Configure Mixamo-style external animations for the viewer.
+ * Looks for animation GLBs in /animations/ and registers them.
+ * Each GLB should contain a single animation clip exported from Mixamo
+ * (downloaded as GLB with "Without Skin" checked).
+ */
+ _configureAnimations(viewer) {
+ // Check if model has a skeleton
+ let hasSkeleton = false;
+ if (viewer.content) {
+ viewer.content.traverse((node) => {
+ if (node.isSkinnedMesh) hasSkeleton = true;
+ });
+ }
+ if (!hasSkeleton) return;
+
+ // Fetch the animation manifest
+ fetch('/animations/manifest.json')
+ .then((r) => {
+ if (!r.ok) throw new Error('No animation manifest');
+ return r.json();
+ })
+ .then((manifest) => {
+ if (Array.isArray(manifest) && manifest.length > 0) {
+ viewer.setAnimationDefs(manifest);
+ }
+ })
+ .catch(() => {
+ // No manifest — use sensible defaults if files exist
+ const defaults = [
+ { name: 'idle', url: '/animations/idle.glb', label: 'Idle' },
+ { name: 'walking', url: '/animations/walking.glb', label: 'Walking' },
+ { name: 'running', url: '/animations/running.glb', label: 'Running' },
+ { name: 'waving', url: '/animations/waving.glb', label: 'Waving' },
+ { name: 'dancing', url: '/animations/dancing.glb', label: 'Dancing' },
+ { name: 'sitting', url: '/animations/sitting.glb', label: 'Sitting' },
+ { name: 'jumping', url: '/animations/jumping.glb', label: 'Jumping' },
+ ];
+
+ // Probe which files actually exist (HEAD requests)
+ Promise.all(
+ defaults.map((def) =>
+ fetch(def.url, { method: 'HEAD' })
+ .then((r) => (r.ok ? def : null))
+ .catch(() => null),
+ ),
+ ).then((results) => {
+ const available = results.filter(Boolean);
+ if (available.length > 0) {
+ viewer.setAnimationDefs(available);
+ }
+ });
+ });
+ }
+
// ── Validator hook ────────────────────────────────────────────────────────
_hookValidator() {
diff --git a/src/components/ModelViewerElement.js b/src/components/ModelViewerElement.js
new file mode 100644
index 000000000..c26c91177
--- /dev/null
+++ b/src/components/ModelViewerElement.js
@@ -0,0 +1,251 @@
+import { Viewer } from '../viewer.js';
+import { LinearToneMapping, ACESFilmicToneMapping } from 'three';
+
+const STYLE_ID = 'mv-viewer-style';
+const DEFAULT_ENVIRONMENT = 'Neutral';
+
+const TONE_MAPPING = {
+ aces: ACESFilmicToneMapping,
+ linear: LinearToneMapping,
+};
+
+function injectStylesOnce() {
+ if (document.getElementById(STYLE_ID)) return;
+ const style = document.createElement('style');
+ style.id = STYLE_ID;
+ style.textContent = `
+ mv-viewer { display: block; position: relative; width: 100%; height: 480px; background: #191919; overflow: hidden; }
+ mv-viewer .mv-viewer__stage { position: absolute; inset: 0; }
+ mv-viewer .mv-viewer__poster { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; transition: opacity .3s ease; cursor: pointer; }
+ mv-viewer .mv-viewer__poster[data-hidden] { opacity: 0; pointer-events: none; }
+ `;
+ document.head.appendChild(style);
+}
+
+export class ModelViewerElement extends HTMLElement {
+ static get observedAttributes() {
+ return [
+ 'src',
+ 'environment',
+ 'exposure',
+ 'tone-mapping',
+ 'background-color',
+ 'auto-rotate',
+ 'camera-controls',
+ 'reveal',
+ 'poster',
+ 'disable-zoom',
+ 'disable-pan',
+ ];
+ }
+
+ constructor() {
+ super();
+ this._viewer = null;
+ this._stageEl = null;
+ this._posterEl = null;
+ this._pendingSrc = null;
+ this._loadedSrc = null;
+ this._revealed = false;
+ this._onControlsChange = null;
+ }
+
+ connectedCallback() {
+ if (this._viewer) return;
+ injectStylesOnce();
+
+ this._stageEl = document.createElement('div');
+ this._stageEl.className = 'mv-viewer__stage';
+ this.appendChild(this._stageEl);
+
+ const reveal = this.getAttribute('reveal') || 'auto';
+ const posterSrc = this.getAttribute('poster');
+ if (posterSrc) {
+ this._posterEl = document.createElement('img');
+ this._posterEl.className = 'mv-viewer__poster';
+ this._posterEl.src = posterSrc;
+ this._posterEl.alt = this.getAttribute('alt') || '';
+ this.appendChild(this._posterEl);
+ }
+
+ const envName = this.getAttribute('environment') || DEFAULT_ENVIRONMENT;
+ const options = {
+ kiosk: false,
+ preset: '',
+ cameraPosition: null,
+ // The Viewer reads options.preset/cameraPosition/kiosk in the constructor;
+ // everything else flows through state and methods after construction.
+ };
+
+ this._viewer = new Viewer(this._stageEl, options);
+ this._viewer.state.environment = envName;
+
+ // Initial attribute sync (before first load, invalidate for the env + lighting updates).
+ this._applyAttribute('exposure');
+ this._applyAttribute('tone-mapping');
+ this._applyAttribute('background-color');
+ this._applyAttribute('auto-rotate');
+ this._applyAttribute('camera-controls');
+ this._applyAttribute('disable-zoom');
+ this._applyAttribute('disable-pan');
+ this._viewer.updateEnvironment();
+ this._viewer.updateLights();
+ this._viewer.updateBackground();
+
+ this._onControlsChange = () => {
+ this.dispatchEvent(new CustomEvent('camera-change', { bubbles: true, composed: true }));
+ };
+ this._viewer.controls.addEventListener('change', this._onControlsChange);
+
+ const src = this.getAttribute('src');
+ if (src) {
+ if (reveal === 'interaction') {
+ this._pendingSrc = src;
+ const trigger = () => {
+ this.removeEventListener('click', trigger);
+ this.removeEventListener('pointerenter', trigger);
+ this._loadSrc(this._pendingSrc);
+ };
+ this.addEventListener('click', trigger, { once: true });
+ this.addEventListener('pointerenter', trigger, { once: true });
+ } else {
+ this._loadSrc(src);
+ }
+ }
+ }
+
+ disconnectedCallback() {
+ if (!this._viewer) return;
+ if (this._onControlsChange && this._viewer.controls) {
+ this._viewer.controls.removeEventListener('change', this._onControlsChange);
+ }
+ if (typeof this._viewer.dispose === 'function') {
+ this._viewer.dispose();
+ } else {
+ console.warn('[mv-viewer] Viewer.dispose() not available — disconnect will leak resources.');
+ }
+ this._viewer = null;
+ this._stageEl = null;
+ this._posterEl = null;
+ this._onControlsChange = null;
+ this.replaceChildren();
+ }
+
+ attributeChangedCallback(name, oldVal, newVal) {
+ if (!this._viewer) return; // Applied at connectedCallback.
+ if (oldVal === newVal) return;
+ this._applyAttribute(name, newVal);
+ }
+
+ _applyAttribute(name, newVal) {
+ const viewer = this._viewer;
+ if (!viewer) return;
+ if (newVal === undefined) newVal = this.getAttribute(name);
+
+ switch (name) {
+ case 'src': {
+ if (this._pendingSrc !== null) {
+ this._pendingSrc = newVal;
+ return;
+ }
+ if (newVal) this._loadSrc(newVal);
+ return;
+ }
+ case 'environment': {
+ viewer.state.environment = newVal || DEFAULT_ENVIRONMENT;
+ viewer.updateEnvironment();
+ return;
+ }
+ case 'exposure': {
+ const v = Number(newVal);
+ if (!Number.isFinite(v)) return;
+ // viewer.state.exposure is an EV offset (see updateLights); accept either a multiplier or an EV value.
+ // For attribute sugar, treat as a linear multiplier and convert to log2 EV.
+ viewer.state.exposure = v > 0 ? Math.log2(v) : 0;
+ viewer.updateLights();
+ return;
+ }
+ case 'tone-mapping': {
+ const mapped = TONE_MAPPING[(newVal || 'aces').toLowerCase()];
+ if (mapped === undefined) return;
+ viewer.state.toneMapping = mapped;
+ viewer.updateLights();
+ return;
+ }
+ case 'background-color': {
+ if (!newVal) return;
+ viewer.state.bgColor = newVal;
+ viewer.updateBackground();
+ return;
+ }
+ case 'auto-rotate': {
+ viewer.state.autoRotate = this.hasAttribute('auto-rotate');
+ viewer.updateDisplay();
+ return;
+ }
+ case 'camera-controls': {
+ // Default on; only off when explicitly set to "false".
+ const enabled = newVal === null || newVal === '' || newVal === 'true';
+ viewer.controls.enabled = enabled;
+ viewer.invalidate();
+ return;
+ }
+ case 'disable-zoom': {
+ viewer.controls.enableZoom = !this.hasAttribute('disable-zoom');
+ viewer.invalidate();
+ return;
+ }
+ case 'disable-pan': {
+ viewer.controls.enablePan = !this.hasAttribute('disable-pan');
+ viewer.invalidate();
+ return;
+ }
+ case 'reveal':
+ case 'poster':
+ // Only applied at connect time.
+ return;
+ }
+ }
+
+ _loadSrc(src) {
+ const viewer = this._viewer;
+ if (!viewer) return;
+ this._pendingSrc = null;
+
+ if (this._loadedSrc) viewer.clear();
+ this._loadedSrc = src;
+
+ viewer
+ .load(src, '', new Map())
+ .then(() => {
+ this._hidePoster();
+ this.dispatchEvent(
+ new CustomEvent('load', { bubbles: true, composed: true, detail: { src } }),
+ );
+ })
+ .catch((error) => {
+ this.dispatchEvent(
+ new CustomEvent('error', {
+ bubbles: true,
+ composed: true,
+ detail: { error, src },
+ }),
+ );
+ });
+ }
+
+ _hidePoster() {
+ if (!this._posterEl) return;
+ this._posterEl.setAttribute('data-hidden', '');
+ // Remove from DOM after fade so it stops capturing pointer events.
+ setTimeout(() => this._posterEl?.remove(), 400);
+ }
+
+ get viewer() {
+ return this._viewer;
+ }
+}
+
+if (typeof customElements !== 'undefined' && !customElements.get('mv-viewer')) {
+ customElements.define('mv-viewer', ModelViewerElement);
+}
diff --git a/src/components/animation-panel.jsx b/src/components/animation-panel.jsx
new file mode 100644
index 000000000..59605466c
--- /dev/null
+++ b/src/components/animation-panel.jsx
@@ -0,0 +1,68 @@
+/**
+ * Animation selector panel component.
+ * Renders a grid of animation buttons with active state highlighting.
+ * @param {object} props
+ * @param {Array<{name: string, label?: string, icon?: string, loaded: boolean}>} props.animations
+ * @param {string|null} props.active - Currently playing animation name
+ * @returns {string} HTML string
+ */
+export function AnimationPanel({ animations, active }) {
+ if (!animations || animations.length === 0) {
+ return '<div class="anim-panel anim-panel--empty"></div>';
+ }
+
+ const ICONS = {
+ idle: '🧍',
+ breathing: '🧍',
+ standing: '🧍',
+ walking: '🚶',
+ walk: '🚶',
+ running: '🏃',
+ run: '🏃',
+ waving: '👋',
+ wave: '👋',
+ dancing: '💃',
+ dance: '💃',
+ sitting: '🪑',
+ sit: '🪑',
+ jumping: '🦘',
+ jump: '🦘',
+ talking: '🗣️',
+ talk: '🗣️',
+ clapping: '👏',
+ clap: '👏',
+ punching: '👊',
+ punch: '👊',
+ kicking: '🦵',
+ kick: '🦵',
+ };
+
+ const buttons = animations
+ .map(({ name, label, icon, loaded }) => {
+ const isActive = active === name;
+ const displayIcon = icon || ICONS[name.toLowerCase()] || '▶';
+ const displayLabel = label || name.charAt(0).toUpperCase() + name.slice(1);
+ const activeClass = isActive ? ' anim-btn--active' : '';
+ const loadingClass = !loaded ? ' anim-btn--loading' : '';
+ return (
+ `<button class="anim-btn${activeClass}${loadingClass}" ` +
+ `data-anim="${name}" ` +
+ `title="${displayLabel}"` +
+ `${!loaded ? ' disabled' : ''}>` +
+ `<span class="anim-btn__icon">${displayIcon}</span>` +
+ `<span class="anim-btn__label">${displayLabel}</span>` +
+ `</button>`
+ );
+ })
+ .join('');
+
+ return (
+ `<div class="anim-panel">` +
+ `<div class="anim-panel__header">` +
+ `<span class="anim-panel__title">Animations</span>` +
+ `<button class="anim-panel__stop" title="Stop all">⏹</button>` +
+ `</div>` +
+ `<div class="anim-panel__grid">${buttons}</div>` +
+ `</div>`
+ );
+}
diff --git a/src/editor/embed-editor.js b/src/editor/embed-editor.js
new file mode 100644
index 000000000..a18721847
--- /dev/null
+++ b/src/editor/embed-editor.js
@@ -0,0 +1,584 @@
+// Embed editor — the "place, scale, preview, copy" UX.
+// Lets users drop an <agent-3d> exactly where they want on their actual site.
+//
+// Usage: import and call mountEmbedEditor(rootEl, { src, defaults }).
+
+import '../element.js'; // ensures <agent-3d> is registered
+
+const POSITIONS = [
+ { id: 'top-left', label: '↖' },
+ { id: 'top-center', label: '↑' },
+ { id: 'top-right', label: '↗' },
+ { id: 'bottom-left', label: '↙' },
+ { id: 'bottom-center', label: '↓' },
+ { id: 'bottom-right', label: '↘' },
+];
+
+const MODES = [
+ { id: 'floating', label: 'Floating bubble', hint: 'Fixed corner, follows scroll' },
+ { id: 'inline', label: 'Inline', hint: 'Flows with the page content' },
+ { id: 'section', label: 'Section', hint: 'Fills a container' },
+ { id: 'fullscreen', label: 'Fullscreen', hint: 'Takes over the viewport' },
+];
+
+const STYLE = `
+ .editor-root {
+ position: fixed;
+ inset: 0;
+ display: grid;
+ grid-template-columns: 1fr 360px;
+ background: #0b0d10;
+ color: #f4f4f5;
+ font: 14px/1.4 system-ui, -apple-system, sans-serif;
+ z-index: 1;
+ }
+ .stage-wrap {
+ position: relative;
+ overflow: hidden;
+ background: #1a1d21;
+ }
+ .stage-wrap iframe {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ background: white;
+ }
+ .stage-wrap .placeholder-site {
+ position: absolute;
+ inset: 0;
+ background:
+ linear-gradient(#ffffff, #fafbfc);
+ color: #111827;
+ padding: 64px 72px;
+ overflow: auto;
+ }
+ .placeholder-site .hero { height: 280px; border-radius: 16px; background: linear-gradient(135deg, #6366f1, #8b5cf6); margin-bottom: 32px; }
+ .placeholder-site .row { height: 18px; background: #e5e7eb; border-radius: 999px; margin: 12px 0; }
+ .placeholder-site .row.short { width: 60%; }
+ .placeholder-site .row.long { width: 92%; }
+ .placeholder-site h1 { font: 700 36px/1.2 system-ui; margin-bottom: 16px; }
+ .placeholder-site p { color: #4b5563; max-width: 640px; }
+
+ .agent-wrap {
+ position: absolute;
+ cursor: grab;
+ user-select: none;
+ touch-action: none;
+ }
+ .agent-wrap.dragging { cursor: grabbing; }
+ .agent-wrap agent-3d { width: 100%; height: 100%; }
+ .resize-handle {
+ position: absolute;
+ width: 14px;
+ height: 14px;
+ background: white;
+ border: 2px solid #3b82f6;
+ border-radius: 3px;
+ z-index: 2;
+ }
+ .resize-handle.se { right: -7px; bottom: -7px; cursor: nwse-resize; }
+ .resize-handle.sw { left: -7px; bottom: -7px; cursor: nesw-resize; }
+ .resize-handle.ne { right: -7px; top: -7px; cursor: nesw-resize; }
+ .resize-handle.nw { left: -7px; top: -7px; cursor: nwse-resize; }
+ .size-readout {
+ position: absolute;
+ top: -28px;
+ left: 0;
+ background: #111827;
+ color: #f9fafb;
+ font: 11px/1 monospace;
+ padding: 4px 6px;
+ border-radius: 4px;
+ }
+
+ .snapline {
+ position: absolute;
+ background: #3b82f6;
+ opacity: 0.6;
+ pointer-events: none;
+ }
+ .snapline.v { width: 1px; top: 0; bottom: 0; }
+ .snapline.h { height: 1px; left: 0; right: 0; }
+
+ .panel {
+ background: #0f1216;
+ border-left: 1px solid #1f2937;
+ display: flex;
+ flex-direction: column;
+ }
+ .panel-header {
+ padding: 16px 20px;
+ border-bottom: 1px solid #1f2937;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ }
+ .panel-header h2 { font: 600 16px system-ui; }
+ .panel-body { padding: 16px 20px; overflow-y: auto; flex: 1; }
+ .section-title { font: 600 11px system-ui; letter-spacing: 0.08em; text-transform: uppercase; color: #9ca3af; margin: 16px 0 8px; }
+
+ .mode-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
+ .mode-card {
+ padding: 10px 12px;
+ border-radius: 10px;
+ background: #111827;
+ border: 1px solid #1f2937;
+ cursor: pointer;
+ transition: border-color 0.15s;
+ }
+ .mode-card:hover { border-color: #3b82f6; }
+ .mode-card[aria-pressed="true"] { border-color: #3b82f6; background: #1e293b; }
+ .mode-card .ml { font-weight: 600; margin-bottom: 2px; }
+ .mode-card .mh { font-size: 12px; color: #9ca3af; }
+
+ .pos-grid {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 6px;
+ }
+ .pos-btn {
+ aspect-ratio: 1.8;
+ background: #111827;
+ border: 1px solid #1f2937;
+ color: #9ca3af;
+ border-radius: 8px;
+ font-size: 18px;
+ cursor: pointer;
+ }
+ .pos-btn[aria-pressed="true"] { background: #3b82f6; color: white; border-color: #3b82f6; }
+
+ .field-row { display: grid; grid-template-columns: 80px 1fr; gap: 8px; align-items: center; margin: 6px 0; }
+ .field-row label { color: #9ca3af; font-size: 12px; }
+ .field-row input, .field-row select {
+ background: #111827;
+ color: #f4f4f5;
+ border: 1px solid #1f2937;
+ border-radius: 6px;
+ padding: 6px 8px;
+ font: 13px system-ui;
+ width: 100%;
+ box-sizing: border-box;
+ }
+
+ .snippet-box {
+ background: #0a0d12;
+ border: 1px solid #1f2937;
+ border-radius: 10px;
+ padding: 12px;
+ font: 12px/1.5 ui-monospace, Menlo, monospace;
+ white-space: pre-wrap;
+ word-break: break-all;
+ color: #a7f3d0;
+ margin-top: 12px;
+ }
+ .actions { display: flex; gap: 8px; margin-top: 12px; }
+ .btn {
+ flex: 1;
+ background: #3b82f6;
+ color: white;
+ border: 0;
+ border-radius: 8px;
+ padding: 10px 12px;
+ font: 600 14px system-ui;
+ cursor: pointer;
+ }
+ .btn.secondary { background: transparent; border: 1px solid #1f2937; color: #e5e7eb; }
+ .btn:hover { filter: brightness(1.1); }
+ .btn[data-copied="true"] { background: #22c55e; }
+
+ .preview-url-row {
+ display: flex;
+ gap: 6px;
+ padding: 10px 16px;
+ background: #0f1216;
+ border-bottom: 1px solid #1f2937;
+ }
+ .preview-url-row input {
+ flex: 1;
+ background: #111827;
+ border: 1px solid #1f2937;
+ color: #e5e7eb;
+ padding: 6px 10px;
+ border-radius: 6px;
+ }
+ .preview-url-row button { background: #3b82f6; color: white; border: 0; border-radius: 6px; padding: 6px 12px; cursor: pointer; }
+`;
+
+export function mountEmbedEditor(root, options = {}) {
+ const defaults = {
+ src: options.src || '',
+ mode: options.mode || 'floating',
+ position: options.position || 'bottom-right',
+ offset: options.offset || '24px 24px',
+ width: options.width || '320px',
+ height: options.height || '420px',
+ ...options,
+ };
+
+ const state = { ...defaults };
+ const host = document.createElement('div');
+ const shadow = host.attachShadow({ mode: 'open' });
+ root.appendChild(host);
+
+ shadow.innerHTML = `
+ <style>${STYLE}</style>
+ <div class="editor-root">
+ <div class="stage-col">
+ <div class="preview-url-row">
+ <input type="text" placeholder="Paste your site URL to preview in-place (optional)" id="url-input">
+ <button id="url-load">Load site</button>
+ <button id="url-clear">Reset</button>
+ </div>
+ <div class="stage-wrap" id="stage">
+ <div class="placeholder-site" id="placeholder">
+ <h1>Your site goes here</h1>
+ <p>This is a preview of what the agent will look like placed on a real page. Paste your site URL above to see the embed on your actual content, or drag the agent around this mock page.</p>
+ <div class="hero"></div>
+ <div class="row long"></div>
+ <div class="row long"></div>
+ <div class="row short"></div>
+ <div class="row long"></div>
+ <div class="row short"></div>
+ </div>
+ <iframe id="preview-frame" hidden></iframe>
+ <div class="agent-wrap" id="agent-wrap">
+ <div class="size-readout" id="size-readout"></div>
+ <agent-3d eager kiosk id="preview-agent"></agent-3d>
+ <div class="resize-handle nw" data-h="nw"></div>
+ <div class="resize-handle ne" data-h="ne"></div>
+ <div class="resize-handle sw" data-h="sw"></div>
+ <div class="resize-handle se" data-h="se"></div>
+ </div>
+ </div>
+ </div>
+ <aside class="panel">
+ <div class="panel-header">
+ <h2>Embed editor</h2>
+ <span style="font-size:11px;color:#6b7280">beta</span>
+ </div>
+ <div class="panel-body">
+ <div class="section-title">Source</div>
+ <div class="field-row">
+ <label>src</label>
+ <input id="src-input" placeholder="agent://base/42 or ipfs://...">
+ </div>
+
+ <div class="section-title">Mode</div>
+ <div class="mode-grid" id="mode-grid"></div>
+
+ <div class="section-title" id="pos-title">Position</div>
+ <div class="pos-grid" id="pos-grid"></div>
+
+ <div class="section-title">Size</div>
+ <div class="field-row">
+ <label>Width</label>
+ <input id="w-input" value="${state.width}">
+ </div>
+ <div class="field-row">
+ <label>Height</label>
+ <input id="h-input" value="${state.height}">
+ </div>
+
+ <div class="section-title">Options</div>
+ <div class="field-row">
+ <label>Voice</label>
+ <select id="voice-select">
+ <option value="">on (default)</option>
+ <option value="off">off</option>
+ </select>
+ </div>
+ <div class="field-row">
+ <label>Camera</label>
+ <select id="camera-select">
+ <option value="on">controls on</option>
+ <option value="off">controls off</option>
+ </select>
+ </div>
+ <div class="field-row">
+ <label>AR</label>
+ <select id="ar-select">
+ <option value="off">off</option>
+ <option value="on">on</option>
+ </select>
+ </div>
+
+ <div class="section-title">Embed snippet</div>
+ <div class="snippet-box" id="snippet"></div>
+ <div class="actions">
+ <button class="btn" id="copy-btn">Copy snippet</button>
+ <button class="btn secondary" id="reset-btn">Reset</button>
+ </div>
+ </div>
+ </aside>
+ </div>
+ `;
+
+ const $ = (sel) => shadow.querySelector(sel);
+ const $$ = (sel) => shadow.querySelectorAll(sel);
+
+ const stage = $('#stage');
+ const agentWrap = $('#agent-wrap');
+ const agentEl = $('#preview-agent');
+ const readout = $('#size-readout');
+ const snippetEl = $('#snippet');
+ const srcInput = $('#src-input');
+ const wInput = $('#w-input');
+ const hInput = $('#h-input');
+ const copyBtn = $('#copy-btn');
+
+ srcInput.value = state.src;
+ if (state.src) agentEl.setAttribute('src', state.src);
+
+ // Mode cards
+ const modeGrid = $('#mode-grid');
+ for (const m of MODES) {
+ const card = document.createElement('div');
+ card.className = 'mode-card';
+ card.dataset.mode = m.id;
+ card.setAttribute('aria-pressed', String(m.id === state.mode));
+ card.tabIndex = 0;
+ card.innerHTML = `<div class="ml">${m.label}</div><div class="mh">${m.hint}</div>`;
+ card.addEventListener('click', () => { state.mode = m.id; sync(); });
+ modeGrid.appendChild(card);
+ }
+
+ // Position buttons
+ const posGrid = $('#pos-grid');
+ for (const p of POSITIONS) {
+ const btn = document.createElement('button');
+ btn.className = 'pos-btn';
+ btn.dataset.pos = p.id;
+ btn.setAttribute('aria-pressed', String(p.id === state.position));
+ btn.textContent = p.label;
+ btn.addEventListener('click', () => { state.position = p.id; sync(); });
+ posGrid.appendChild(btn);
+ }
+
+ // Input bindings
+ srcInput.addEventListener('change', () => { state.src = srcInput.value; sync(); });
+ wInput.addEventListener('change', () => { state.width = wInput.value; sync(); });
+ hInput.addEventListener('change', () => { state.height = hInput.value; sync(); });
+ $('#voice-select').addEventListener('change', (e) => { state.voice = e.target.value === 'off' ? false : true; sync(); });
+ $('#camera-select').addEventListener('change', (e) => { state.cameraControls = e.target.value === 'on'; sync(); });
+ $('#ar-select').addEventListener('change', (e) => { state.ar = e.target.value === 'on'; sync(); });
+
+ // URL preview
+ const urlInput = $('#url-input');
+ $('#url-load').addEventListener('click', () => {
+ const u = urlInput.value.trim();
+ if (!u) return;
+ const iframe = $('#preview-frame');
+ iframe.src = u;
+ iframe.hidden = false;
+ $('#placeholder').hidden = true;
+ });
+ $('#url-clear').addEventListener('click', () => {
+ $('#preview-frame').src = 'about:blank';
+ $('#preview-frame').hidden = true;
+ $('#placeholder').hidden = false;
+ });
+
+ // Drag
+ let dragState = null;
+ agentWrap.addEventListener('pointerdown', (e) => {
+ if (e.target.closest('.resize-handle')) return;
+ const rect = stage.getBoundingClientRect();
+ const agentRect = agentWrap.getBoundingClientRect();
+ dragState = {
+ kind: 'move',
+ offsetX: e.clientX - agentRect.left,
+ offsetY: e.clientY - agentRect.top,
+ stageRect: rect,
+ };
+ agentWrap.classList.add('dragging');
+ agentWrap.setPointerCapture(e.pointerId);
+ });
+
+ // Resize handles
+ $$('.resize-handle').forEach((h) => {
+ h.addEventListener('pointerdown', (e) => {
+ e.stopPropagation();
+ const rect = stage.getBoundingClientRect();
+ const agentRect = agentWrap.getBoundingClientRect();
+ dragState = {
+ kind: 'resize',
+ handle: h.dataset.h,
+ startX: e.clientX,
+ startY: e.clientY,
+ startW: agentRect.width,
+ startH: agentRect.height,
+ startLeft: agentRect.left - rect.left,
+ startTop: agentRect.top - rect.top,
+ stageRect: rect,
+ };
+ h.setPointerCapture(e.pointerId);
+ });
+ });
+
+ stage.addEventListener('pointermove', (e) => {
+ if (!dragState) return;
+ const rect = dragState.stageRect;
+ if (dragState.kind === 'move') {
+ const x = e.clientX - rect.left - dragState.offsetX;
+ const y = e.clientY - rect.top - dragState.offsetY;
+ const snapped = snapToCorner(x, y, agentWrap.offsetWidth, agentWrap.offsetHeight, rect.width, rect.height);
+ agentWrap.style.left = snapped.x + 'px';
+ agentWrap.style.top = snapped.y + 'px';
+ if (snapped.corner) {
+ state.position = snapped.corner;
+ state.offset = `${snapped.offsetV} ${snapped.offsetH}`;
+ syncPositionButtons();
+ writeSnippet();
+ }
+ } else if (dragState.kind === 'resize') {
+ const dx = e.clientX - dragState.startX;
+ const dy = e.clientY - dragState.startY;
+ let w = dragState.startW, h = dragState.startH;
+ let left = dragState.startLeft, top = dragState.startTop;
+ if (dragState.handle.includes('e')) w = dragState.startW + dx;
+ if (dragState.handle.includes('s')) h = dragState.startH + dy;
+ if (dragState.handle.includes('w')) { w = dragState.startW - dx; left = dragState.startLeft + dx; }
+ if (dragState.handle.includes('n')) { h = dragState.startH - dy; top = dragState.startTop + dy; }
+ w = Math.max(160, w); h = Math.max(200, h);
+ agentWrap.style.width = w + 'px';
+ agentWrap.style.height = h + 'px';
+ agentWrap.style.left = left + 'px';
+ agentWrap.style.top = top + 'px';
+ state.width = Math.round(w) + 'px';
+ state.height = Math.round(h) + 'px';
+ wInput.value = state.width;
+ hInput.value = state.height;
+ readout.textContent = `${state.width} × ${state.height}`;
+ writeSnippet();
+ }
+ });
+
+ stage.addEventListener('pointerup', () => {
+ if (dragState) {
+ agentWrap.classList.remove('dragging');
+ dragState = null;
+ }
+ });
+
+ copyBtn.addEventListener('click', async () => {
+ await navigator.clipboard.writeText(buildSnippet());
+ copyBtn.textContent = 'Copied ✓';
+ copyBtn.dataset.copied = 'true';
+ setTimeout(() => {
+ copyBtn.textContent = 'Copy snippet';
+ copyBtn.dataset.copied = 'false';
+ }, 1500);
+ });
+
+ $('#reset-btn').addEventListener('click', () => {
+ Object.assign(state, defaults);
+ srcInput.value = state.src;
+ wInput.value = state.width;
+ hInput.value = state.height;
+ sync();
+ });
+
+ // Show appropriate resize handles based on position
+ function syncPositionButtons() {
+ for (const btn of $$('.pos-btn')) btn.setAttribute('aria-pressed', String(btn.dataset.pos === state.position));
+ }
+ function syncModeCards() {
+ for (const card of $$('.mode-card')) card.setAttribute('aria-pressed', String(card.dataset.mode === state.mode));
+ }
+
+ function applyToPreview() {
+ // Size
+ agentWrap.style.width = state.width;
+ agentWrap.style.height = state.height;
+ readout.textContent = `${state.width} × ${state.height}`;
+
+ // Position — place the wrap inside the stage per mode + position
+ agentWrap.style.left = agentWrap.style.right = agentWrap.style.top = agentWrap.style.bottom = '';
+ if (state.mode === 'floating') {
+ const [vOff, hOff] = (state.offset || '24px 24px').split(/\s+/);
+ if (state.position.includes('top')) agentWrap.style.top = vOff;
+ else agentWrap.style.bottom = vOff;
+ if (state.position.includes('left')) agentWrap.style.left = hOff;
+ else if (state.position.includes('right')) agentWrap.style.right = hOff;
+ else if (state.position.includes('center')) {
+ agentWrap.style.left = '50%';
+ agentWrap.style.transform = 'translateX(-50%)';
+ }
+ $('#pos-title').style.display = '';
+ $('#pos-grid').style.display = '';
+ } else if (state.mode === 'fullscreen') {
+ agentWrap.style.inset = '0';
+ agentWrap.style.width = '100%';
+ agentWrap.style.height = '100%';
+ $('#pos-title').style.display = 'none';
+ $('#pos-grid').style.display = 'none';
+ } else {
+ // inline / section: center on stage
+ agentWrap.style.left = `calc(50% - ${parseInt(state.width) / 2}px)`;
+ agentWrap.style.top = `calc(50% - ${parseInt(state.height) / 2}px)`;
+ $('#pos-title').style.display = 'none';
+ $('#pos-grid').style.display = 'none';
+ }
+
+ // Agent attrs
+ if (state.src) agentEl.setAttribute('src', state.src); else agentEl.removeAttribute('src');
+ }
+
+ function buildSnippet() {
+ const attrs = [];
+ if (state.src) attrs.push(`src="${escapeAttr(state.src)}"`);
+ if (state.mode && state.mode !== 'inline') attrs.push(`mode="${state.mode}"`);
+ if (state.mode === 'floating') {
+ if (state.position !== 'bottom-right') attrs.push(`position="${state.position}"`);
+ if (state.offset && state.offset !== '24px 24px') attrs.push(`offset="${state.offset}"`);
+ }
+ if (state.width) attrs.push(`width="${state.width}"`);
+ if (state.height) attrs.push(`height="${state.height}"`);
+ if (state.voice === false) attrs.push(`voice="off"`);
+ if (state.cameraControls) attrs.push(`camera-controls`);
+ if (state.ar) attrs.push(`ar`);
+
+ const script = `<script type="module" src="https://cdn.3d-agent.io/agent-3d.js"></script>`;
+ const element = `<agent-3d ${attrs.join(' ')}></agent-3d>`;
+ return `${script}\n${element}`;
+ }
+
+ function writeSnippet() {
+ snippetEl.textContent = buildSnippet();
+ }
+
+ function sync() {
+ syncPositionButtons();
+ syncModeCards();
+ applyToPreview();
+ writeSnippet();
+ }
+
+ function snapToCorner(x, y, w, h, stageW, stageH) {
+ const SNAP = 48;
+ const corners = [
+ { corner: 'top-left', cx: 0, cy: 0 },
+ { corner: 'top-right', cx: stageW - w, cy: 0 },
+ { corner: 'bottom-left', cx: 0, cy: stageH - h },
+ { corner: 'bottom-right', cx: stageW - w, cy: stageH - h },
+ { corner: 'top-center', cx: (stageW - w) / 2, cy: 0 },
+ { corner: 'bottom-center', cx: (stageW - w) / 2, cy: stageH - h },
+ ];
+ for (const c of corners) {
+ if (Math.abs(x - c.cx) < SNAP && Math.abs(y - c.cy) < SNAP) {
+ // Compute offsets from nearest edge
+ const offV = c.corner.startsWith('top') ? `${Math.round(c.cy)}px` : `${Math.round(stageH - h - c.cy)}px`;
+ const offH = c.corner.endsWith('left') ? `${Math.round(c.cx)}px`
+ : c.corner.endsWith('right') ? `${Math.round(stageW - w - c.cx)}px`
+ : '0px';
+ return { x: c.cx, y: c.cy, corner: c.corner, offsetV: offV, offsetH: offH };
+ }
+ }
+ return { x, y };
+ }
+
+ function escapeAttr(s) { return String(s).replace(/"/g, '&quot;'); }
+
+ sync();
+ return { state, host };
+}
diff --git a/src/editor/glb-export.js b/src/editor/glb-export.js
new file mode 100644
index 000000000..41a228b06
--- /dev/null
+++ b/src/editor/glb-export.js
@@ -0,0 +1,125 @@
+/**
+ * GLB export pipeline using glTF-Transform.
+ *
+ * Reads the original GLB/GLTF bytes, applies accumulated edits from the
+ * EditorSession, and re-serializes as a valid GLB. We match Three.js edits
+ * back to glTF-Transform entities by NAME (UUIDs don't cross the boundary).
+ *
+ * Materials: names are typically unique within a glTF. If two materials
+ * share a name we still apply edits to the first match — correct 99% of
+ * the time and not worse than what the GUI would suggest.
+ */
+import { WebIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+
+/** Convert an Euler (XYZ order, radians) to a quaternion [x,y,z,w]. */
+function eulerToQuat([x, y, z]) {
+ const cx = Math.cos(x / 2),
+ sx = Math.sin(x / 2);
+ const cy = Math.cos(y / 2),
+ sy = Math.sin(y / 2);
+ const cz = Math.cos(z / 2),
+ sz = Math.sin(z / 2);
+ return [
+ sx * cy * cz + cx * sy * sz,
+ cx * sy * cz - sx * cy * sz,
+ cx * cy * sz + sx * sy * cz,
+ cx * cy * cz - sx * sy * sz,
+ ];
+}
+
+/**
+ * @param {EditorSession} session
+ * @returns {Promise<Uint8Array>} modified GLB bytes
+ */
+export async function exportEditedGLB(session) {
+ const buf = await session.getSourceBuffer();
+ if (!buf) throw new Error('No source buffer for export');
+
+ const io = new WebIO({ credentials: 'include' }).registerExtensions(ALL_EXTENSIONS);
+ const doc = await io.readBinary(new Uint8Array(buf));
+ const root = doc.getRoot();
+
+ applyMaterialEdits(root, session.materialEdits);
+ applyTransformAndVisibilityEdits(root, session.transformEdits, session.visibilityEdits);
+
+ return io.writeBinary(doc);
+}
+
+function applyMaterialEdits(root, edits) {
+ if (!edits || !Object.keys(edits).length) return;
+
+ const byName = new Map();
+ for (const mat of root.listMaterials()) {
+ const n = mat.getName();
+ if (!byName.has(n)) byName.set(n, mat);
+ }
+
+ for (const uuid in edits) {
+ const edit = edits[uuid];
+ const mat = byName.get(edit.name);
+ if (!mat) continue;
+
+ if (edit.baseColor) {
+ const [r, g, b] = edit.baseColor;
+ const alpha =
+ edit.opacity !== undefined ? edit.opacity : mat.getBaseColorFactor()[3] ?? 1;
+ mat.setBaseColorFactor([r, g, b, alpha]);
+ } else if (edit.opacity !== undefined) {
+ const f = mat.getBaseColorFactor() || [1, 1, 1, 1];
+ mat.setBaseColorFactor([f[0], f[1], f[2], edit.opacity]);
+ }
+
+ if (edit.metalness !== undefined) mat.setMetallicFactor(edit.metalness);
+ if (edit.roughness !== undefined) mat.setRoughnessFactor(edit.roughness);
+ if (edit.emissive) mat.setEmissiveFactor(edit.emissive);
+ if (edit.alphaMode !== undefined) mat.setAlphaMode(edit.alphaMode);
+ if (edit.alphaCutoff !== undefined) mat.setAlphaCutoff(edit.alphaCutoff);
+ if (edit.doubleSided !== undefined) mat.setDoubleSided(edit.doubleSided);
+ }
+}
+
+function applyTransformAndVisibilityEdits(root, transformEdits, visibilityEdits) {
+ const hasT = transformEdits && Object.keys(transformEdits).length > 0;
+ const hasV = visibilityEdits && Object.keys(visibilityEdits).length > 0;
+ if (!hasT && !hasV) return;
+
+ const byName = new Map();
+ for (const node of root.listNodes()) {
+ const n = node.getName();
+ if (n && !byName.has(n)) byName.set(n, node);
+ }
+
+ if (hasT) {
+ for (const uuid in transformEdits) {
+ const edit = transformEdits[uuid];
+ const node = byName.get(edit.name);
+ if (!node) continue;
+ if (edit.position) node.setTranslation(edit.position);
+ if (edit.rotation) node.setRotation(eulerToQuat(edit.rotation));
+ if (edit.scale) node.setScale(edit.scale);
+ }
+ }
+
+ if (hasV) {
+ for (const uuid in visibilityEdits) {
+ const edit = visibilityEdits[uuid];
+ if (edit.visible) continue;
+ const node = byName.get(edit.name);
+ if (!node) continue;
+ node.setScale([0, 0, 0]);
+ }
+ }
+}
+
+export function downloadGLB(bytes, filename = 'edited.glb') {
+ const blob = new Blob([bytes], { type: 'model/gltf-binary' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+}
diff --git a/src/editor/index.js b/src/editor/index.js
new file mode 100644
index 000000000..b8f2db361
--- /dev/null
+++ b/src/editor/index.js
@@ -0,0 +1,116 @@
+/**
+ * Editor — orchestrator that wires Material Editor, Texture Inspector,
+ * Scene Explorer, and GLB export into the Viewer.
+ *
+ * Usage:
+ * const editor = new Editor(viewer);
+ * editor.attach(); // once, after viewer constructed
+ * editor.onContentChanged({ url, file }); // every time a new model loads
+ */
+import { EditorSession } from './session.js';
+import { MaterialEditor } from './material-editor.js';
+import { SceneExplorer } from './scene-explorer.js';
+import { TextureInspector } from './texture-inspector.js';
+import { exportEditedGLB, downloadGLB } from './glb-export.js';
+
+export class Editor {
+ constructor(viewer) {
+ this.viewer = viewer;
+ this.session = new EditorSession(viewer);
+ this.materialEditor = new MaterialEditor(viewer, this.session);
+ this.textureInspector = new TextureInspector(viewer, this.session);
+ this.sceneExplorer = new SceneExplorer(viewer, this.session);
+ this.exportFolder = null;
+ this._exportCtrl = null;
+ this._attached = false;
+ }
+
+ attach() {
+ if (this._attached) return;
+ this._attached = true;
+ this.sceneExplorer.attach();
+ this._addExportFolder();
+ this.session.onChange(() => this._updateExportLabel());
+ }
+
+ onContentChanged({ url = null, file = null, name = null } = {}) {
+ this.session.reset({ url, file, name });
+ this.materialEditor.rebuild();
+ this.textureInspector.rebuild();
+ this.sceneExplorer.rebuild();
+ this._updateExportLabel();
+ }
+
+ _addExportFolder() {
+ if (!this.viewer.gui) return;
+ const folder = this.viewer.gui.addFolder('Editor');
+ this._exportCtrl = folder
+ .add(
+ {
+ download: () => this._exportGLB(),
+ },
+ 'download',
+ )
+ .name('💾 download GLB');
+ folder
+ .add(
+ {
+ explorer: () => this.sceneExplorer.toggle(),
+ },
+ 'explorer',
+ )
+ .name('🗂 scene panel [T]');
+ folder
+ .add(
+ {
+ reset: () => this._resetAll(),
+ },
+ 'reset',
+ )
+ .name('↺ revert all edits');
+ this.exportFolder = folder;
+ }
+
+ _updateExportLabel() {
+ if (!this._exportCtrl) return;
+ const count =
+ Object.keys(this.session.materialEdits).length +
+ Object.keys(this.session.transformEdits).length +
+ Object.keys(this.session.visibilityEdits).length;
+ const base = '💾 download GLB';
+ this._exportCtrl.name(count > 0 ? `${base} (${count})` : base);
+ }
+
+ async _exportGLB() {
+ try {
+ const bytes = await exportEditedGLB(this.session);
+ const base = (this.session.sourceName || 'model')
+ .replace(/\?.*$/, '')
+ .replace(/\.(glb|gltf)$/i, '');
+ downloadGLB(bytes, `${base}.edited.glb`);
+ } catch (err) {
+ console.error('[editor] GLB export failed', err);
+ window.alert('GLB export failed: ' + (err.message || err));
+ }
+ }
+
+ _resetAll() {
+ if (!this.session.isDirty()) return;
+ if (!window.confirm('Discard all edits and reload the model?')) return;
+ window.location.reload();
+ }
+
+ dispose() {
+ this.materialEditor.dispose();
+ this.textureInspector.dispose();
+ this.sceneExplorer.detach();
+ if (this.exportFolder && this.viewer.gui) {
+ try {
+ this.viewer.gui.removeFolder(this.exportFolder);
+ } catch (e) {}
+ }
+ this.exportFolder = null;
+ this._exportCtrl = null;
+ this._attached = false;
+ }
+}
diff --git a/src/editor/material-editor.js b/src/editor/material-editor.js
new file mode 100644
index 000000000..b26be0e34
--- /dev/null
+++ b/src/editor/material-editor.js
@@ -0,0 +1,180 @@
+/**
+ * MaterialEditor — live PBR editing via dat.gui subfolders.
+ *
+ * Collects unique MeshStandardMaterial / MeshPhysicalMaterial instances from
+ * the loaded content and builds one subfolder per material with controls that
+ * mutate the Three.js material directly (for viewport preview) and record
+ * the change on the EditorSession (for GLB export).
+ */
+import { FrontSide, BackSide, DoubleSide } from 'three';
+import { traverseMaterials } from '../viewer/internal.js';
+
+const SIDES = { Front: FrontSide, Back: BackSide, Double: DoubleSide };
+
+export class MaterialEditor {
+ constructor(viewer, session) {
+ this.viewer = viewer;
+ this.session = session;
+ this.gui = viewer.gui;
+ this.folder = null;
+ this.subfolders = [];
+ this.snapshots = new Map();
+ }
+
+ rebuild() {
+ this._clear();
+ if (!this.viewer.content || !this.gui) return;
+
+ const mats = [];
+ traverseMaterials(this.viewer.content, (mat) => {
+ if (mat && (mat.isMeshStandardMaterial || mat.isMeshPhysicalMaterial)) {
+ mats.push(mat);
+ }
+ });
+
+ if (mats.length === 0) return;
+
+ this.folder = this.gui.addFolder('Materials');
+
+ mats.forEach((mat, i) => {
+ const label = mat.name || `Material ${i + 1}`;
+ const sub = this.folder.addFolder(label);
+ this._addControls(sub, mat);
+ this.subfolders.push(sub);
+ });
+ }
+
+ _addControls(folder, mat) {
+ const snap = {
+ color: mat.color.getHex(),
+ metalness: mat.metalness,
+ roughness: mat.roughness,
+ emissive: mat.emissive.getHex(),
+ emissiveIntensity: mat.emissiveIntensity ?? 1,
+ opacity: mat.opacity,
+ transparent: mat.transparent,
+ alphaTest: mat.alphaTest,
+ wireframe: mat.wireframe,
+ flatShading: mat.flatShading,
+ envMapIntensity: mat.envMapIntensity ?? 1,
+ side: mat.side,
+ };
+ this.snapshots.set(mat.uuid, snap);
+
+ const proxy = {
+ color: '#' + mat.color.getHexString(),
+ emissive: '#' + mat.emissive.getHexString(),
+ side: Object.keys(SIDES).find((k) => SIDES[k] === mat.side) || 'Front',
+ };
+
+ const record = () => {
+ this.session.recordMaterialEdit(mat, {
+ name: mat.name,
+ baseColor: [mat.color.r, mat.color.g, mat.color.b],
+ metalness: mat.metalness,
+ roughness: mat.roughness,
+ emissive: [mat.emissive.r, mat.emissive.g, mat.emissive.b],
+ opacity: mat.opacity,
+ alphaMode: mat.transparent
+ ? 'BLEND'
+ : mat.alphaTest > 0
+ ? 'MASK'
+ : 'OPAQUE',
+ alphaCutoff: mat.alphaTest,
+ doubleSided: mat.side === DoubleSide,
+ });
+ mat.needsUpdate = true;
+ this.viewer.invalidate();
+ };
+
+ folder.addColor(proxy, 'color').name('base color').onChange((v) => {
+ mat.color.set(v);
+ record();
+ });
+ folder.add(mat, 'metalness', 0, 1, 0.01).onChange(record);
+ folder.add(mat, 'roughness', 0, 1, 0.01).onChange(record);
+ folder.addColor(proxy, 'emissive').onChange((v) => {
+ mat.emissive.set(v);
+ record();
+ });
+ folder.add(mat, 'emissiveIntensity', 0, 4, 0.01).name('emissive int').onChange(() => {
+ mat.needsUpdate = true;
+ this.viewer.invalidate();
+ });
+ folder.add(mat, 'opacity', 0, 1, 0.01).onChange(() => {
+ mat.transparent = mat.opacity < 1;
+ record();
+ });
+ folder.add(mat, 'transparent').onChange(record);
+ folder.add(mat, 'alphaTest', 0, 1, 0.01).name('alpha test').onChange(record);
+ folder.add(mat, 'wireframe').onChange(() => {
+ mat.needsUpdate = true;
+ this.viewer.invalidate();
+ });
+ folder.add(mat, 'flatShading').name('flat shading').onChange(() => {
+ mat.needsUpdate = true;
+ this.viewer.invalidate();
+ });
+ if (mat.envMapIntensity !== undefined) {
+ folder.add(mat, 'envMapIntensity', 0, 4, 0.01).name('env map int').onChange(() => {
+ this.viewer.invalidate();
+ });
+ }
+ folder.add(proxy, 'side', Object.keys(SIDES)).onChange((v) => {
+ mat.side = SIDES[v];
+ record();
+ });
+
+ folder
+ .add(
+ {
+ reset: () => this._reset(folder, mat, proxy),
+ },
+ 'reset',
+ )
+ .name('↺ reset');
+ }
+
+ _reset(folder, mat, proxy) {
+ const snap = this.snapshots.get(mat.uuid);
+ if (!snap) return;
+ mat.color.setHex(snap.color);
+ mat.emissive.setHex(snap.emissive);
+ mat.metalness = snap.metalness;
+ mat.roughness = snap.roughness;
+ mat.emissiveIntensity = snap.emissiveIntensity;
+ mat.opacity = snap.opacity;
+ mat.transparent = snap.transparent;
+ mat.alphaTest = snap.alphaTest;
+ mat.wireframe = snap.wireframe;
+ mat.flatShading = snap.flatShading;
+ if (mat.envMapIntensity !== undefined) mat.envMapIntensity = snap.envMapIntensity;
+ mat.side = snap.side;
+ proxy.color = '#' + mat.color.getHexString();
+ proxy.emissive = '#' + mat.emissive.getHexString();
+ proxy.side = Object.keys(SIDES).find((k) => SIDES[k] === mat.side) || 'Front';
+
+ this.session.clearMaterialEdit(mat);
+ mat.needsUpdate = true;
+ this.viewer.invalidate();
+
+ for (const ctrl of folder.__controllers) {
+ if (ctrl.updateDisplay) ctrl.updateDisplay();
+ }
+ }
+
+ _clear() {
+ if (this.folder && this.gui) {
+ try {
+ this.gui.removeFolder(this.folder);
+ } catch (e) {}
+ }
+ this.folder = null;
+ this.subfolders = [];
+ this.snapshots.clear();
+ }
+
+ dispose() {
+ this._clear();
+ }
+}
diff --git a/src/editor/scene-explorer.js b/src/editor/scene-explorer.js
new file mode 100644
index 000000000..b5ef43987
--- /dev/null
+++ b/src/editor/scene-explorer.js
@@ -0,0 +1,465 @@
+/**
+ * SceneExplorer — side panel with a collapsible scene tree, node inspector,
+ * click-to-select raycasting, and a TransformControls gizmo.
+ *
+ * All structural changes (position/rotation/scale/visibility) are written
+ * to the EditorSession so they can be re-applied at GLB export time.
+ */
+import { Box3, Raycaster, Vector3 } from 'three';
+import { TransformControls } from 'three/addons/controls/TransformControls.js';
+
+const ICONS = {
+ Mesh: '📦',
+ SkinnedMesh: '🧍',
+ Group: '🎯',
+ Object3D: '▫',
+ Bone: '🦴',
+ DirectionalLight: '💡',
+ PointLight: '💡',
+ SpotLight: '💡',
+ AmbientLight: '💡',
+ HemisphereLight: '💡',
+ PerspectiveCamera: '📷',
+ OrthographicCamera: '📷',
+ Scene: '🌳',
+};
+
+function escapeHTML(s) {
+ return String(s)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+
+function iconFor(node) {
+ return ICONS[node.type] || (node.isMesh ? '📦' : '▫');
+}
+
+export class SceneExplorer {
+ constructor(viewer, session) {
+ this.viewer = viewer;
+ this.session = session;
+ this.panel = null;
+ this.treeEl = null;
+ this.inspectorEl = null;
+ this.searchEl = null;
+ this.selectedNode = null;
+ this.transformControls = null;
+ this.raycaster = new Raycaster();
+ this._onKeyDown = this._onKeyDown.bind(this);
+ this._onPointerDown = this._onPointerDown.bind(this);
+ this._attached = false;
+ }
+
+ attach() {
+ if (this._attached) return;
+ this._attached = true;
+ this._buildPanel();
+ this._setupTransformControls();
+ this.viewer.renderer.domElement.addEventListener('pointerdown', this._onPointerDown);
+ window.addEventListener('keydown', this._onKeyDown);
+ }
+
+ detach() {
+ if (!this._attached) return;
+ this._attached = false;
+ if (this.panel) {
+ this.panel.remove();
+ this.panel = null;
+ }
+ if (this.transformControls) {
+ this.transformControls.detach();
+ this.viewer.scene.remove(this.transformControls);
+ this.transformControls.dispose?.();
+ this.transformControls = null;
+ }
+ if (this.viewer.renderer?.domElement) {
+ this.viewer.renderer.domElement.removeEventListener('pointerdown', this._onPointerDown);
+ }
+ window.removeEventListener('keydown', this._onKeyDown);
+ }
+
+ toggle(show) {
+ if (!this.panel) return;
+ const willShow = show === undefined ? this.panel.classList.contains('hidden') : show;
+ this.panel.classList.toggle('hidden', !willShow);
+ }
+
+ rebuild() {
+ if (!this.treeEl) return;
+ this.selectedNode = null;
+ this.transformControls?.detach();
+ this.treeEl.innerHTML = '';
+ this.inspectorEl.innerHTML =
+ '<div class="scene-explorer__empty">Select a node to inspect</div>';
+
+ if (!this.viewer.content) {
+ this.treeEl.innerHTML = '<div class="scene-explorer__empty">No model loaded</div>';
+ return;
+ }
+ this.treeEl.appendChild(this._buildNodeElement(this.viewer.content, 0, true));
+ }
+
+ _buildPanel() {
+ const panel = document.createElement('div');
+ panel.className = 'scene-explorer hidden';
+ panel.innerHTML = `
+ <div class="scene-explorer__header">
+ <span class="scene-explorer__title">Scene</span>
+ <button class="scene-explorer__close" title="Close [T]">×</button>
+ </div>
+ <input type="text" class="scene-explorer__search" placeholder="Search nodes…">
+ <div class="scene-explorer__hint">W translate · E rotate · R scale · Esc deselect</div>
+ <div class="scene-explorer__tree"></div>
+ <div class="scene-explorer__inspector"></div>
+ `;
+ this.viewer.el.appendChild(panel);
+ this.panel = panel;
+ this.treeEl = panel.querySelector('.scene-explorer__tree');
+ this.inspectorEl = panel.querySelector('.scene-explorer__inspector');
+ this.searchEl = panel.querySelector('.scene-explorer__search');
+
+ panel.querySelector('.scene-explorer__close').addEventListener('click', () => {
+ this.toggle(false);
+ });
+ this.searchEl.addEventListener('input', () => {
+ this._filter(this.searchEl.value);
+ });
+ }
+
+ _buildNodeElement(node, depth, autoExpand = false) {
+ const div = document.createElement('div');
+ div.className = 'scene-node';
+ div.dataset.uuid = node.uuid;
+
+ const hasChildren = node.children && node.children.length > 0;
+ const name = node.name || node.type;
+ const label = escapeHTML(name);
+
+ const row = document.createElement('div');
+ row.className = 'scene-node__row';
+ row.style.paddingLeft = depth * 12 + 'px';
+ row.innerHTML = `
+ <span class="scene-node__expander">${hasChildren ? '▸' : '·'}</span>
+ <span class="scene-node__icon">${iconFor(node)}</span>
+ <span class="scene-node__label" title="${label}">${label}</span>
+ <button class="scene-node__visibility" title="Toggle visibility">${node.visible ? '●' : '○'}</button>
+ `;
+
+ const childrenEl = document.createElement('div');
+ childrenEl.className = 'scene-node__children';
+ if (autoExpand) childrenEl.classList.add('open');
+
+ const expander = row.querySelector('.scene-node__expander');
+ const visBtn = row.querySelector('.scene-node__visibility');
+
+ row.addEventListener('click', (e) => {
+ if (e.target === visBtn || e.target === expander) return;
+ this.selectNode(node);
+ });
+ row.addEventListener('dblclick', () => this._frameNode(node));
+
+ if (hasChildren) {
+ expander.addEventListener('click', (e) => {
+ e.stopPropagation();
+ const open = childrenEl.classList.toggle('open');
+ expander.textContent = open ? '▾' : '▸';
+ });
+ if (autoExpand) expander.textContent = '▾';
+ }
+
+ visBtn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ node.visible = !node.visible;
+ visBtn.textContent = node.visible ? '●' : '○';
+ this.session.recordVisibilityEdit(node, node.visible);
+ this.viewer.invalidate();
+ });
+
+ div.appendChild(row);
+ div.appendChild(childrenEl);
+
+ if (hasChildren) {
+ node.children.forEach((child) => {
+ childrenEl.appendChild(this._buildNodeElement(child, depth + 1));
+ });
+ }
+ return div;
+ }
+
+ selectNode(node) {
+ this.selectedNode = node;
+ this.treeEl
+ .querySelectorAll('.scene-node__row.selected')
+ .forEach((r) => r.classList.remove('selected'));
+ const target = this.treeEl.querySelector(
+ `.scene-node[data-uuid="${node.uuid}"] > .scene-node__row`,
+ );
+ if (target) target.classList.add('selected');
+
+ if (
+ this.transformControls &&
+ node !== this.viewer.content.parent &&
+ !node.isScene &&
+ node !== this.viewer.defaultCamera
+ ) {
+ try {
+ this.transformControls.attach(node);
+ } catch (e) {}
+ }
+ this._renderInspector(node);
+ this.viewer.invalidate();
+ }
+
+ _renderInspector(node) {
+ if (!this.inspectorEl) return;
+ const rad2deg = 180 / Math.PI;
+ const parts = [];
+ parts.push(
+ `<div class="inspector__title">${escapeHTML(node.name || node.type)}</div>`,
+ );
+ parts.push(`<div class="inspector__sub">${node.type} · uuid: ${node.uuid.slice(0, 8)}</div>`);
+
+ parts.push('<div class="inspector__section">Transform</div>');
+ parts.push(this._vec3Row('pos', [node.position.x, node.position.y, node.position.z]));
+ parts.push(
+ this._vec3Row('rot°', [
+ node.rotation.x * rad2deg,
+ node.rotation.y * rad2deg,
+ node.rotation.z * rad2deg,
+ ]),
+ );
+ parts.push(this._vec3Row('scl', [node.scale.x, node.scale.y, node.scale.z]));
+
+ if (node.isMesh && node.geometry) {
+ const g = node.geometry;
+ const posAttr = g.getAttribute('position');
+ const vertices = posAttr ? posAttr.count : 0;
+ const index = g.getIndex();
+ const triangles = Math.round(index ? index.count / 3 : vertices / 3);
+ const attrs = Object.keys(g.attributes).join(', ');
+ parts.push('<div class="inspector__section">Geometry</div>');
+ parts.push(this._kv('vertices', vertices));
+ parts.push(this._kv('triangles', triangles));
+ parts.push(this._kv('indexed', index ? 'yes' : 'no'));
+ parts.push(this._kv('attrs', attrs));
+ if (posAttr) {
+ try {
+ const box = new Box3().setFromBufferAttribute(posAttr);
+ const size = new Vector3();
+ box.getSize(size);
+ parts.push(
+ this._kv(
+ 'size',
+ `${size.x.toFixed(2)} × ${size.y.toFixed(2)} × ${size.z.toFixed(2)}`,
+ ),
+ );
+ } catch (e) {}
+ }
+ const mats = Array.isArray(node.material) ? node.material : [node.material];
+ parts.push(
+ this._kv(
+ 'materials',
+ mats
+ .filter(Boolean)
+ .map((m) => m.name || m.type)
+ .join(', '),
+ ),
+ );
+ }
+
+ if (node.isLight) {
+ parts.push('<div class="inspector__section">Light</div>');
+ parts.push(this._kv('intensity', node.intensity?.toFixed(2)));
+ if (node.color) parts.push(this._kv('color', '#' + node.color.getHexString()));
+ if (node.distance !== undefined) parts.push(this._kv('distance', node.distance));
+ }
+
+ if (node.isCamera) {
+ parts.push('<div class="inspector__section">Camera</div>');
+ if (node.fov) parts.push(this._kv('fov', node.fov.toFixed(1) + '°'));
+ parts.push(this._kv('near', node.near));
+ parts.push(this._kv('far', node.far));
+ }
+
+ parts.push('<div class="inspector__section">Actions</div>');
+ parts.push(
+ `<div class="inspector__actions">
+ <button data-act="frame">Frame</button>
+ <button data-act="hide">${node.visible ? 'Hide' : 'Show'}</button>
+ <button data-act="deselect">Deselect</button>
+ </div>`,
+ );
+
+ this.inspectorEl.innerHTML = parts.join('');
+
+ this.inspectorEl.querySelectorAll('.vec3-row input').forEach((inp) => {
+ inp.addEventListener('change', () => this._onVec3Change(node));
+ });
+
+ this.inspectorEl.querySelector('[data-act="frame"]')?.addEventListener('click', () =>
+ this._frameNode(node),
+ );
+ this.inspectorEl.querySelector('[data-act="hide"]')?.addEventListener('click', () => {
+ node.visible = !node.visible;
+ this.session.recordVisibilityEdit(node, node.visible);
+ const visBtn = this.treeEl.querySelector(
+ `.scene-node[data-uuid="${node.uuid}"] .scene-node__visibility`,
+ );
+ if (visBtn) visBtn.textContent = node.visible ? '●' : '○';
+ this._renderInspector(node);
+ this.viewer.invalidate();
+ });
+ this.inspectorEl.querySelector('[data-act="deselect"]')?.addEventListener('click', () => {
+ this.transformControls?.detach();
+ this.selectedNode = null;
+ this.treeEl
+ .querySelectorAll('.scene-node__row.selected')
+ .forEach((r) => r.classList.remove('selected'));
+ this.inspectorEl.innerHTML =
+ '<div class="scene-explorer__empty">Select a node to inspect</div>';
+ this.viewer.invalidate();
+ });
+ }
+
+ _onVec3Change(node) {
+ const rows = this.inspectorEl.querySelectorAll('.vec3-row');
+ if (rows.length < 3) return;
+ const read = (row) => {
+ const inputs = row.querySelectorAll('input');
+ return [
+ parseFloat(inputs[0].value) || 0,
+ parseFloat(inputs[1].value) || 0,
+ parseFloat(inputs[2].value) || 0,
+ ];
+ };
+ const [px, py, pz] = read(rows[0]);
+ const [rx, ry, rz] = read(rows[1]);
+ const [sx, sy, sz] = read(rows[2]);
+ const deg2rad = Math.PI / 180;
+ node.position.set(px, py, pz);
+ node.rotation.set(rx * deg2rad, ry * deg2rad, rz * deg2rad);
+ node.scale.set(sx || 0.0001, sy || 0.0001, sz || 0.0001);
+ this.session.recordTransformEdit(node);
+ this.viewer.invalidate();
+ }
+
+ _vec3Row(label, values) {
+ const [x, y, z] = values;
+ return `<div class="inspector__row vec3-row">
+ <span class="inspector__label">${label}</span>
+ <span class="vec3">
+ <input type="number" step="0.01" value="${x.toFixed(3)}">
+ <input type="number" step="0.01" value="${y.toFixed(3)}">
+ <input type="number" step="0.01" value="${z.toFixed(3)}">
+ </span>
+ </div>`;
+ }
+
+ _kv(k, v) {
+ return `<div class="inspector__row">
+ <span class="inspector__label">${k}</span>
+ <span class="inspector__value">${escapeHTML(v ?? '')}</span>
+ </div>`;
+ }
+
+ _frameNode(node) {
+ const box = new Box3().setFromObject(node);
+ if (box.isEmpty()) return;
+ const center = new Vector3();
+ const size = new Vector3();
+ box.getCenter(center);
+ box.getSize(size);
+ const radius = Math.max(size.length(), 0.001);
+ const cam = this.viewer.defaultCamera;
+ const ctrl = this.viewer.controls;
+ const dir = cam.position.clone().sub(ctrl.target).normalize();
+ if (dir.lengthSq() < 1e-6) dir.set(0, 0, 1);
+ ctrl.target.copy(center);
+ cam.position.copy(center).add(dir.multiplyScalar(radius * 1.5));
+ ctrl.update();
+ this.viewer.invalidate();
+ }
+
+ _filter(query) {
+ const q = query.trim().toLowerCase();
+ const rows = this.treeEl.querySelectorAll('.scene-node');
+ rows.forEach((row) => {
+ const label = row.querySelector('.scene-node__label');
+ if (!label) return;
+ const match = !q || label.textContent.toLowerCase().includes(q);
+ row.classList.toggle('filtered-out', !match);
+ if (match && q) {
+ let p = row.parentElement;
+ while (p && p.classList.contains('scene-node__children')) {
+ p.classList.add('open');
+ const exp = p.previousElementSibling?.querySelector('.scene-node__expander');
+ if (exp) exp.textContent = '▾';
+ p = p.parentElement?.parentElement;
+ }
+ }
+ });
+ }
+
+ _setupTransformControls() {
+ const tc = new TransformControls(this.viewer.defaultCamera, this.viewer.renderer.domElement);
+ tc.addEventListener('dragging-changed', (e) => {
+ this.viewer.controls.enabled = !e.value;
+ });
+ tc.addEventListener('objectChange', () => {
+ if (this.selectedNode) {
+ this.session.recordTransformEdit(this.selectedNode);
+ if (this.inspectorEl && this.selectedNode === this.selectedNode) {
+ this._renderInspector(this.selectedNode);
+ }
+ }
+ this.viewer.invalidate();
+ });
+ tc.addEventListener('change', () => this.viewer.invalidate());
+ this.viewer.scene.add(tc);
+ this.transformControls = tc;
+ }
+
+ _onKeyDown(e) {
+ if (this.viewer.isInputFocused()) return;
+ if (!this.transformControls) return;
+
+ if (e.key === 't' || e.key === 'T') {
+ e.preventDefault();
+ this.toggle();
+ return;
+ }
+ if (this.panel?.classList.contains('hidden')) return;
+
+ if (e.key === 'w' || e.key === 'W') this.transformControls.setMode('translate');
+ else if (e.key === 'e' || e.key === 'E') this.transformControls.setMode('rotate');
+ else if (e.key === 'r' || e.key === 'R') this.transformControls.setMode('scale');
+ else if (e.key === 'Escape') {
+ this.transformControls.detach();
+ this.selectedNode = null;
+ }
+ }
+
+ _onPointerDown(e) {
+ if (e.button !== 0) return;
+ if (this.panel?.classList.contains('hidden')) return;
+ if (this.transformControls?.dragging) return;
+ if (!this.viewer.content) return;
+ if (this.panel && this.panel.contains(e.target)) return;
+
+ const rect = this.viewer.renderer.domElement.getBoundingClientRect();
+ const x = ((e.clientX - rect.left) / rect.width) * 2 - 1;
+ const y = -((e.clientY - rect.top) / rect.height) * 2 + 1;
+
+ this.raycaster.setFromCamera({ x, y }, this.viewer.defaultCamera);
+ const hits = this.raycaster.intersectObject(this.viewer.content, true);
+ if (hits.length > 0) {
+ let target = hits[0].object;
+ while (target.parent && !(target.isMesh || target.isLight || target.isCamera)) {
+ target = target.parent;
+ }
+ this.selectNode(target);
+ }
+ }
+}
diff --git a/src/editor/session.js b/src/editor/session.js
new file mode 100644
index 000000000..6960c0359
--- /dev/null
+++ b/src/editor/session.js
@@ -0,0 +1,108 @@
+/**
+ * EditorSession — central state for live-editable properties on a loaded model.
+ *
+ * Three kinds of edits are tracked and replayed at export time:
+ * - materialEdits keyed by Three.js material.uuid
+ * - transformEdits keyed by Three.js Object3D.uuid
+ * - visibilityEdits keyed by Three.js Object3D.uuid
+ *
+ * We also keep the raw source bytes so we can re-serialize a modified GLB
+ * via glTF-Transform without refetching. Bytes are captured lazily either
+ * from a URL or from a File.
+ */
+export class EditorSession {
+ constructor(viewer) {
+ this.viewer = viewer;
+ this.sourceURL = null;
+ this.sourceFile = null;
+ this.sourceBuffer = null;
+ this.sourceName = 'model';
+ this.materialEdits = {};
+ this.transformEdits = {};
+ this.visibilityEdits = {};
+ this._listeners = new Set();
+ }
+
+ reset({ url = null, file = null, name = null } = {}) {
+ this.sourceURL = url;
+ this.sourceFile = file;
+ this.sourceBuffer = null;
+ this.sourceName =
+ name ||
+ (file && file.name) ||
+ (url ? url.split('/').pop().split('?')[0] : 'model');
+ this.materialEdits = {};
+ this.transformEdits = {};
+ this.visibilityEdits = {};
+ this._emit();
+ }
+
+ onChange(fn) {
+ this._listeners.add(fn);
+ return () => this._listeners.delete(fn);
+ }
+
+ _emit() {
+ for (const fn of this._listeners) {
+ try {
+ fn(this);
+ } catch (e) {
+ console.warn('[editor.session] listener error', e);
+ }
+ }
+ }
+
+ recordMaterialEdit(material, patch) {
+ const key = material.uuid;
+ const existing = this.materialEdits[key] || { name: material.name, uuid: key };
+ this.materialEdits[key] = { ...existing, ...patch };
+ this._emit();
+ }
+
+ clearMaterialEdit(material) {
+ delete this.materialEdits[material.uuid];
+ this._emit();
+ }
+
+ recordTransformEdit(node) {
+ this.transformEdits[node.uuid] = {
+ name: node.name,
+ uuid: node.uuid,
+ position: node.position.toArray(),
+ rotation: [node.rotation.x, node.rotation.y, node.rotation.z],
+ scale: node.scale.toArray(),
+ };
+ this._emit();
+ }
+
+ recordVisibilityEdit(node, visible) {
+ this.visibilityEdits[node.uuid] = { name: node.name, visible };
+ this._emit();
+ }
+
+ isDirty() {
+ return (
+ Object.keys(this.materialEdits).length > 0 ||
+ Object.keys(this.transformEdits).length > 0 ||
+ Object.keys(this.visibilityEdits).length > 0
+ );
+ }
+
+ async getSourceBuffer() {
+ if (this.sourceBuffer) return this.sourceBuffer;
+
+ if (this.sourceFile) {
+ this.sourceBuffer = await this.sourceFile.arrayBuffer();
+ return this.sourceBuffer;
+ }
+
+ if (this.sourceURL) {
+ const res = await fetch(this.sourceURL);
+ if (!res.ok) throw new Error(`Failed to fetch source: ${res.status}`);
+ this.sourceBuffer = await res.arrayBuffer();
+ return this.sourceBuffer;
+ }
+
+ throw new Error('No source URL or File set on EditorSession');
+ }
+}
diff --git a/src/editor/texture-inspector.js b/src/editor/texture-inspector.js
new file mode 100644
index 000000000..b618d2b99
--- /dev/null
+++ b/src/editor/texture-inspector.js
@@ -0,0 +1,266 @@
+/**
+ * TextureInspector — catalogs every texture referenced by the loaded model,
+ * shows a grid of thumbnails with metadata, and opens a lightbox with
+ * per-channel extraction (R/G/B/A grayscale) for any texture.
+ */
+import { traverseMaterials } from '../viewer/internal.js';
+
+const SLOT_LABELS = {
+ map: 'Base Color',
+ normalMap: 'Normal',
+ metalnessMap: 'Metallic',
+ roughnessMap: 'Roughness',
+ aoMap: 'Occlusion',
+ emissiveMap: 'Emissive',
+ bumpMap: 'Bump',
+ alphaMap: 'Alpha',
+ displacementMap: 'Displacement',
+ clearcoatMap: 'Clearcoat',
+ clearcoatNormalMap: 'Clearcoat Normal',
+ clearcoatRoughnessMap: 'Clearcoat Roughness',
+ sheenColorMap: 'Sheen Color',
+ sheenRoughnessMap: 'Sheen Roughness',
+ specularColorMap: 'Specular Color',
+ specularIntensityMap: 'Specular Intensity',
+ transmissionMap: 'Transmission',
+ thicknessMap: 'Thickness',
+ lightMap: 'Light',
+};
+
+function drawSourceToCanvas(canvas, src) {
+ const ctx = canvas.getContext('2d');
+ ctx.imageSmoothingEnabled = true;
+ try {
+ ctx.drawImage(src, 0, 0, canvas.width, canvas.height);
+ return true;
+ } catch (e) {
+ ctx.fillStyle = '#222';
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ ctx.fillStyle = '#888';
+ ctx.font = '10px sans-serif';
+ ctx.fillText('preview unavailable', 8, canvas.height / 2);
+ return false;
+ }
+}
+
+export class TextureInspector {
+ constructor(viewer, session) {
+ this.viewer = viewer;
+ this.session = session;
+ this.gui = viewer.gui;
+ this.folder = null;
+ this.panel = null;
+ }
+
+ rebuild() {
+ this._clear();
+ if (!this.viewer.content || !this.gui) return;
+ const textures = this._collectTextures();
+ if (textures.length === 0) return;
+
+ this.folder = this.gui.addFolder('Textures');
+ this.folder
+ .add(
+ {
+ open: () => this._openPanel(textures),
+ },
+ 'open',
+ )
+ .name(`inspect (${textures.length})`);
+ }
+
+ _collectTextures() {
+ const byUuid = new Map();
+ traverseMaterials(this.viewer.content, (mat) => {
+ for (const slot in SLOT_LABELS) {
+ const tex = mat[slot];
+ if (!tex || !tex.image) continue;
+ const key = tex.uuid;
+ if (!byUuid.has(key)) {
+ byUuid.set(key, { tex, slots: new Set(), materials: new Set() });
+ }
+ const entry = byUuid.get(key);
+ entry.slots.add(SLOT_LABELS[slot]);
+ entry.materials.add(mat.name || mat.type);
+ }
+ });
+ return [...byUuid.values()];
+ }
+
+ _openPanel(textures) {
+ if (this.panel) this.panel.remove();
+
+ const panel = document.createElement('div');
+ panel.className = 'texture-inspector';
+ panel.innerHTML = `
+ <div class="texture-inspector__header">
+ <span class="texture-inspector__title">Texture Inspector · ${textures.length}</span>
+ <button class="texture-inspector__close" title="Close">×</button>
+ </div>
+ <div class="texture-inspector__grid"></div>
+ `;
+ document.body.appendChild(panel);
+ this.panel = panel;
+
+ panel.querySelector('.texture-inspector__close').addEventListener('click', () => {
+ panel.remove();
+ this.panel = null;
+ });
+
+ const grid = panel.querySelector('.texture-inspector__grid');
+ textures.forEach((entry) => grid.appendChild(this._buildCard(entry)));
+ }
+
+ _buildCard({ tex, slots, materials }) {
+ const img = tex.image;
+ const w = img.width || img.videoWidth || 0;
+ const h = img.height || img.videoHeight || 0;
+ const memMB = ((w * h * 4 * 1.33) / 1024 / 1024).toFixed(2);
+
+ const card = document.createElement('div');
+ card.className = 'texture-card';
+ const thumb = document.createElement('canvas');
+ thumb.className = 'texture-card__thumb';
+ thumb.width = 128;
+ thumb.height = 128;
+ drawSourceToCanvas(thumb, img);
+ card.appendChild(thumb);
+
+ const info = document.createElement('div');
+ info.className = 'texture-card__info';
+ info.innerHTML = `
+ <div class="texture-card__name">${[...slots].join(' · ')}</div>
+ <div class="texture-card__meta">${w}×${h} · ~${memMB} MB</div>
+ <div class="texture-card__mats">${[...materials].slice(0, 3).join(', ')}${
+ materials.size > 3 ? '…' : ''
+ }</div>
+ `;
+ card.appendChild(info);
+
+ thumb.addEventListener('click', () => this._openLightbox(tex, slots, materials));
+ card.addEventListener('click', (e) => {
+ if (e.target === thumb) return;
+ this._openLightbox(tex, slots, materials);
+ });
+ return card;
+ }
+
+ _openLightbox(tex, slots, materials) {
+ const img = tex.image;
+ const w = img.width || 256;
+ const h = img.height || 256;
+
+ const lb = document.createElement('div');
+ lb.className = 'texture-lightbox';
+ lb.innerHTML = `
+ <div class="texture-lightbox__bar">
+ <div class="texture-lightbox__meta">
+ <span class="texture-lightbox__title">${[...slots].join(' · ')}</span>
+ <span class="texture-lightbox__dim">${w}×${h}</span>
+ </div>
+ <div class="texture-lightbox__channels">
+ <button data-ch="rgb" class="active">RGB</button>
+ <button data-ch="r">R</button>
+ <button data-ch="g">G</button>
+ <button data-ch="b">B</button>
+ <button data-ch="a">A</button>
+ <button data-ch="checker" title="Alpha over checkerboard">⌗</button>
+ </div>
+ <button class="texture-lightbox__close" title="Close">×</button>
+ </div>
+ <div class="texture-lightbox__stage">
+ <canvas class="texture-lightbox__canvas" width="${w}" height="${h}"></canvas>
+ </div>
+ <div class="texture-lightbox__footer">Used by: ${[...materials].join(', ')}</div>
+ `;
+ document.body.appendChild(lb);
+
+ const canvas = lb.querySelector('.texture-lightbox__canvas');
+ const ctx = canvas.getContext('2d');
+ drawSourceToCanvas(canvas, img);
+
+ let imgData = null;
+ try {
+ imgData = ctx.getImageData(0, 0, w, h);
+ } catch (e) {
+ imgData = null;
+ }
+
+ const drawChecker = () => {
+ const tile = 16;
+ ctx.fillStyle = '#ccc';
+ ctx.fillRect(0, 0, w, h);
+ ctx.fillStyle = '#777';
+ for (let y = 0; y < h; y += tile) {
+ for (let x = (y / tile) % 2 === 0 ? 0 : tile; x < w; x += tile * 2) {
+ ctx.fillRect(x, y, tile, tile);
+ }
+ }
+ };
+
+ const drawChannel = (ch) => {
+ ctx.clearRect(0, 0, w, h);
+ if (ch === 'rgb') {
+ drawSourceToCanvas(canvas, img);
+ return;
+ }
+ if (ch === 'checker') {
+ drawChecker();
+ try {
+ ctx.drawImage(img, 0, 0, w, h);
+ } catch (e) {}
+ return;
+ }
+ if (!imgData) {
+ ctx.fillStyle = '#222';
+ ctx.fillRect(0, 0, w, h);
+ ctx.fillStyle = '#aaa';
+ ctx.font = '14px sans-serif';
+ ctx.fillText('channel extraction blocked (CORS)', 16, h / 2);
+ return;
+ }
+ const out = ctx.createImageData(w, h);
+ const idx = { r: 0, g: 1, b: 2, a: 3 }[ch];
+ for (let i = 0; i < imgData.data.length; i += 4) {
+ const v = imgData.data[i + idx];
+ out.data[i] = v;
+ out.data[i + 1] = v;
+ out.data[i + 2] = v;
+ out.data[i + 3] = 255;
+ }
+ ctx.putImageData(out, 0, 0);
+ };
+
+ lb.querySelectorAll('.texture-lightbox__channels button').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ lb.querySelectorAll('.texture-lightbox__channels button').forEach((b) =>
+ b.classList.remove('active'),
+ );
+ btn.classList.add('active');
+ drawChannel(btn.dataset.ch);
+ });
+ });
+
+ lb.querySelector('.texture-lightbox__close').addEventListener('click', () => lb.remove());
+ lb.addEventListener('click', (e) => {
+ if (e.target === lb) lb.remove();
+ });
+ }
+
+ _clear() {
+ if (this.folder && this.gui) {
+ try {
+ this.gui.removeFolder(this.folder);
+ } catch (e) {}
+ }
+ this.folder = null;
+ if (this.panel) {
+ this.panel.remove();
+ this.panel = null;
+ }
+ }
+
+ dispose() {
+ this._clear();
+ }
+}
diff --git a/src/element.js b/src/element.js
new file mode 100644
index 000000000..549480763
--- /dev/null
+++ b/src/element.js
@@ -0,0 +1,526 @@
+// <agent-3d> — the web component that ships the whole framework in one tag.
+// See specs/EMBED_SPEC.md
+
+import { Viewer } from './viewer.js';
+import { Runtime } from './runtime/index.js';
+import { SceneController } from './runtime/scene.js';
+import { SkillRegistry } from './skills/index.js';
+import { Memory } from './memory/index.js';
+import { loadManifest, fetchRelative } from './manifest.js';
+import { resolveURI } from './ipfs.js';
+
+const MODES = ['inline', 'floating', 'section', 'fullscreen'];
+
+const BASE_STYLE = `
+ :host {
+ display: block;
+ position: relative;
+ width: 100%;
+ height: 480px;
+ --agent-bubble-radius: 16px;
+ --agent-accent: #3b82f6;
+ --agent-surface: rgba(17, 24, 39, 0.92);
+ --agent-on-surface: #f9fafb;
+ --agent-chat-font: system-ui, -apple-system, sans-serif;
+ --agent-mic-glow: #22c55e;
+ --agent-shadow: 0 20px 60px rgba(0,0,0,0.3);
+ contain: layout style;
+ }
+ :host([mode="floating"]) {
+ position: fixed;
+ z-index: 2147483000;
+ width: var(--agent-width, 320px);
+ height: var(--agent-height, 420px);
+ border-radius: var(--agent-bubble-radius);
+ overflow: hidden;
+ box-shadow: var(--agent-shadow);
+ }
+ :host([mode="fullscreen"]) {
+ position: fixed;
+ inset: 0;
+ width: 100vw;
+ height: 100vh;
+ z-index: 2147483000;
+ }
+ :host([hidden]) { display: none; }
+ .stage {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ }
+ .stage canvas { display: block; }
+ .chrome {
+ position: absolute;
+ left: 12px;
+ right: 12px;
+ bottom: 12px;
+ display: flex;
+ gap: 8px;
+ align-items: flex-end;
+ pointer-events: none;
+ }
+ .chrome > * { pointer-events: auto; }
+ .chat {
+ flex: 1;
+ max-height: 40%;
+ overflow-y: auto;
+ background: var(--agent-surface);
+ color: var(--agent-on-surface);
+ font: 14px/1.4 var(--agent-chat-font);
+ border-radius: 12px;
+ padding: 10px 12px;
+ backdrop-filter: blur(12px);
+ }
+ .chat:empty { display: none; }
+ .msg { margin: 4px 0; }
+ .msg .role { opacity: 0.55; font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; }
+ .input-row {
+ display: flex;
+ gap: 6px;
+ background: var(--agent-surface);
+ border-radius: 999px;
+ padding: 4px 4px 4px 14px;
+ backdrop-filter: blur(12px);
+ flex: 1;
+ }
+ .input-row input {
+ flex: 1;
+ background: transparent;
+ border: 0;
+ color: var(--agent-on-surface);
+ font: 14px var(--agent-chat-font);
+ outline: none;
+ }
+ button.icon {
+ width: 36px;
+ height: 36px;
+ border-radius: 50%;
+ border: 0;
+ background: var(--agent-accent);
+ color: white;
+ cursor: pointer;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ }
+ button.icon.mic[data-listening="true"] { box-shadow: 0 0 0 4px var(--agent-mic-glow); }
+ .poster {
+ position: absolute;
+ inset: 0;
+ background-size: contain;
+ background-position: center;
+ background-repeat: no-repeat;
+ transition: opacity 0.4s;
+ pointer-events: none;
+ }
+ .loading {
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ transform: translate(-50%, -50%);
+ color: var(--agent-on-surface);
+ font: 14px var(--agent-chat-font);
+ background: var(--agent-surface);
+ padding: 8px 14px;
+ border-radius: 999px;
+ }
+ .error {
+ position: absolute;
+ inset: 16px;
+ display: grid;
+ place-items: center;
+ color: var(--agent-on-surface);
+ background: var(--agent-surface);
+ border-radius: 12px;
+ padding: 16px;
+ font: 14px var(--agent-chat-font);
+ }
+`;
+
+class Agent3DElement extends HTMLElement {
+ static get observedAttributes() {
+ return ['src', 'manifest', 'body', 'mode', 'position', 'width', 'height', 'voice', 'api-key', 'key-proxy'];
+ }
+
+ constructor() {
+ super();
+ this.attachShadow({ mode: 'open' });
+ this._viewer = null;
+ this._scene = null;
+ this._runtime = null;
+ this._memory = null;
+ this._skills = null;
+ this._manifest = null;
+ this._mounted = false;
+ this._booting = false;
+ this._listening = false;
+ }
+
+ connectedCallback() {
+ this._renderShell();
+ this._applyLayout();
+ this._observeViewport();
+ // Defer boot until visible unless `eager` attr is present
+ if (this.hasAttribute('eager')) this._boot();
+ }
+
+ disconnectedCallback() {
+ this._teardown();
+ }
+
+ attributeChangedCallback(name, oldVal, newVal) {
+ if (!this._mounted) return;
+ if (['mode', 'position', 'width', 'height'].includes(name)) this._applyLayout();
+ if (['src', 'manifest', 'body'].includes(name)) {
+ // Source change — reboot
+ this._teardown();
+ this._boot();
+ }
+ }
+
+ _renderShell() {
+ const style = document.createElement('style');
+ style.textContent = BASE_STYLE;
+ this.shadowRoot.appendChild(style);
+
+ const stage = document.createElement('div');
+ stage.className = 'stage';
+ stage.part = 'stage';
+ this.shadowRoot.appendChild(stage);
+ this._stageEl = stage;
+
+ const poster = document.createElement('div');
+ poster.className = 'poster';
+ if (this.getAttribute('poster')) {
+ poster.style.backgroundImage = `url(${this.getAttribute('poster')})`;
+ }
+ this.shadowRoot.appendChild(poster);
+ this._posterEl = poster;
+
+ const loading = document.createElement('div');
+ loading.className = 'loading';
+ loading.textContent = 'Loading...';
+ loading.hidden = true;
+ this.shadowRoot.appendChild(loading);
+ this._loadingEl = loading;
+
+ // Chat + input chrome (omitted in kiosk mode)
+ if (!this.hasAttribute('kiosk')) {
+ const chrome = document.createElement('div');
+ chrome.className = 'chrome';
+ chrome.part = 'chrome';
+
+ const chat = document.createElement('div');
+ chat.className = 'chat';
+ chat.part = 'chat';
+
+ const row = document.createElement('div');
+ row.className = 'input-row';
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.placeholder = 'Say something...';
+ input.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && input.value.trim()) {
+ const v = input.value.trim();
+ input.value = '';
+ this.say(v);
+ }
+ });
+ const micBtn = document.createElement('button');
+ micBtn.className = 'icon mic';
+ micBtn.title = 'Push to talk';
+ micBtn.innerHTML = '🎙';
+ micBtn.addEventListener('click', () => this._toggleMic());
+ row.appendChild(input);
+ row.appendChild(micBtn);
+
+ chrome.appendChild(chat);
+ chrome.appendChild(row);
+ this.shadowRoot.appendChild(chrome);
+ this._chatEl = chat;
+ this._inputEl = input;
+ this._micEl = micBtn;
+ }
+ }
+
+ _applyLayout() {
+ const mode = this.getAttribute('mode') || 'inline';
+ if (!MODES.includes(mode)) return;
+
+ if (mode === 'floating') {
+ const pos = this.getAttribute('position') || 'bottom-right';
+ const offset = (this.getAttribute('offset') || '24px 24px').split(/\s+/);
+ const [vOff, hOff] = [offset[0], offset[1] || offset[0]];
+ this.style.top = this.style.bottom = this.style.left = this.style.right = '';
+ if (pos.includes('top')) this.style.top = vOff;
+ else this.style.bottom = vOff;
+ if (pos.includes('left')) this.style.left = hOff;
+ else if (pos.includes('right')) this.style.right = hOff;
+ else if (pos.includes('center')) {
+ this.style.left = '50%';
+ this.style.transform = 'translateX(-50%)';
+ }
+ } else {
+ this.style.top = this.style.bottom = this.style.left = this.style.right = this.style.transform = '';
+ }
+
+ const width = this.getAttribute('width');
+ const height = this.getAttribute('height');
+ if (width) this.style.setProperty('--agent-width', width);
+ if (height) this.style.setProperty('--agent-height', height);
+ if (mode === 'inline') {
+ if (width) this.style.width = width;
+ if (height) this.style.height = height;
+ }
+ }
+
+ _observeViewport() {
+ if (this.hasAttribute('eager')) return;
+ if (typeof IntersectionObserver === 'undefined') { this._boot(); return; }
+ this._io = new IntersectionObserver((entries) => {
+ if (entries.some((e) => e.isIntersecting)) {
+ this._io.disconnect();
+ this._boot();
+ }
+ });
+ this._io.observe(this);
+ }
+
+ async _boot() {
+ if (this._booting || this._mounted) return;
+ this._booting = true;
+ try {
+ this._loadingEl.hidden = false;
+ this.dispatchEvent(new CustomEvent('agent:load-progress', { detail: { phase: 'manifest', pct: 0.1 } }));
+
+ const manifest = await this._resolveManifest();
+ this._manifest = manifest;
+ this.dispatchEvent(new CustomEvent('agent:load-progress', { detail: { phase: 'manifest', pct: 0.3 } }));
+
+ // Hydrate instructions.md if referenced
+ if (typeof manifest.brain?.instructions === 'string' && manifest.brain.instructions.endsWith('.md')) {
+ const text = await fetchRelative(manifest, manifest.brain.instructions);
+ if (text) manifest.instructions = stripFrontmatter(text);
+ } else if (manifest.brain?.instructions) {
+ manifest.instructions = manifest.brain.instructions;
+ }
+
+ // Build Viewer
+ this.dispatchEvent(new CustomEvent('agent:load-progress', { detail: { phase: 'body', pct: 0.45 } }));
+ const viewer = new Viewer(this._stageEl, { kiosk: this.hasAttribute('kiosk') });
+ this._viewer = viewer;
+ const bodyURI = resolveURI(manifest.body?.uri);
+ if (bodyURI) {
+ await viewer.load(bodyURI, '', new Map());
+ }
+ this._scene = new SceneController(viewer);
+
+ // Memory
+ this.dispatchEvent(new CustomEvent('agent:load-progress', { detail: { phase: 'memory', pct: 0.6 } }));
+ const memoryNamespace = manifest.id?.agentId || this.getAttribute('memory-key') || manifest.name || 'anon';
+ this._memory = await Memory.load({
+ mode: this.getAttribute('memory') || manifest.memory?.mode || 'local',
+ namespace: memoryNamespace,
+ manifestURI: manifest._baseURI + 'manifest.json',
+ fetchFn: fetch.bind(globalThis),
+ });
+
+ // Skills
+ this.dispatchEvent(new CustomEvent('agent:load-progress', { detail: { phase: 'skills', pct: 0.75 } }));
+ this._skills = new SkillRegistry({
+ trust: this.getAttribute('skill-trust') || 'owned-only',
+ ownerAddress: manifest.id?.owner,
+ });
+ const skillList = manifest.skills || [];
+ for (const spec of skillList) {
+ try {
+ const skill = await this._skills.install(spec, { bundleBase: manifest._baseURI });
+ this.dispatchEvent(new CustomEvent('skill:loaded', { detail: { name: skill.name, uri: skill.uri } }));
+ } catch (e) {
+ console.warn('[agent-3d] skill load failed', spec, e);
+ }
+ }
+
+ // Runtime
+ this.dispatchEvent(new CustomEvent('agent:load-progress', { detail: { phase: 'brain', pct: 0.9 } }));
+ const providerConfig = {
+ apiKey: this.getAttribute('api-key') || undefined,
+ proxyURL: this.getAttribute('key-proxy') || undefined,
+ };
+ this._runtime = new Runtime({
+ manifest,
+ viewer: this._scene,
+ memory: this._memory,
+ skills: this._skills,
+ providerConfig,
+ });
+ // Re-dispatch runtime events on the host
+ for (const ev of ['brain:thinking', 'brain:message', 'skill:tool-called', 'voice:speech-start', 'voice:speech-end', 'voice:transcript', 'voice:listen-start', 'memory:write']) {
+ this._runtime.addEventListener(ev, (e) => {
+ this.dispatchEvent(new CustomEvent(ev, { detail: e.detail, bubbles: true, composed: true }));
+ if (ev === 'brain:message' && this._chatEl) this._renderMessage(e.detail);
+ });
+ }
+
+ this._mounted = true;
+ this._loadingEl.hidden = true;
+ this._posterEl.style.opacity = '0';
+ this.dispatchEvent(new CustomEvent('agent:ready', {
+ detail: { agent: this, manifest },
+ bubbles: true,
+ composed: true,
+ }));
+ } catch (err) {
+ console.error('[agent-3d] boot failed', err);
+ this._loadingEl.hidden = true;
+ this._showError(err);
+ this.dispatchEvent(new CustomEvent('agent:error', {
+ detail: { phase: 'boot', error: err },
+ bubbles: true,
+ composed: true,
+ }));
+ } finally {
+ this._booting = false;
+ }
+ }
+
+ async _resolveManifest() {
+ const src = this.getAttribute('src');
+ const manifestAttr = this.getAttribute('manifest');
+ const body = this.getAttribute('body');
+ if (src) return loadManifest(src, { rpcURL: this.getAttribute('rpc-url'), registry: this.getAttribute('registry') });
+ if (manifestAttr) return loadManifest(manifestAttr);
+ if (body) {
+ // Ad-hoc agent from a bare GLB
+ const instructionsAttr = this.getAttribute('instructions');
+ return {
+ spec: 'agent-manifest/0.1',
+ _baseURI: '',
+ name: this.getAttribute('name') || 'Agent',
+ body: { uri: body, format: 'gltf-binary' },
+ brain: {
+ provider: this.getAttribute('brain') ? 'anthropic' : 'none',
+ model: this.getAttribute('brain') || undefined,
+ instructions: instructionsAttr || 'You are an embodied 3D agent.',
+ },
+ instructions: instructionsAttr || 'You are an embodied 3D agent.',
+ voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },
+ skills: (this.getAttribute('skills') || '').split(',').map((s) => s.trim()).filter(Boolean).map((uri) => ({ uri })),
+ memory: { mode: this.getAttribute('memory') || 'local' },
+ tools: ['wave', 'lookAt', 'play_clip', 'setExpression', 'speak', 'remember'],
+ version: '0.1.0',
+ };
+ }
+ throw new Error('<agent-3d> requires src=, manifest=, or body= attribute');
+ }
+
+ _renderMessage({ role, content }) {
+ if (!this._chatEl) return;
+ if (!content) return;
+ const msg = document.createElement('div');
+ msg.className = 'msg';
+ msg.innerHTML = `<div class="role">${role}</div><div class="body"></div>`;
+ msg.querySelector('.body').textContent = content;
+ this._chatEl.appendChild(msg);
+ this._chatEl.scrollTop = this._chatEl.scrollHeight;
+ }
+
+ _showError(err) {
+ const el = document.createElement('div');
+ el.className = 'error';
+ el.textContent = `Couldn't load agent: ${err.message || err}`;
+ this.shadowRoot.appendChild(el);
+ }
+
+ async _toggleMic() {
+ if (!this._runtime) return;
+ if (this._listening) {
+ this._runtime.stt?.stop();
+ this._listening = false;
+ this._micEl.dataset.listening = 'false';
+ return;
+ }
+ this._listening = true;
+ this._micEl.dataset.listening = 'true';
+ try {
+ const text = await this._runtime.listen();
+ if (text) await this.say(text, { voice: true });
+ } catch (e) {
+ console.warn('[agent-3d] listen failed', e);
+ } finally {
+ this._listening = false;
+ this._micEl.dataset.listening = 'false';
+ }
+ }
+
+ _teardown() {
+ try { this._io?.disconnect(); } catch {}
+ try { this._runtime?.destroy(); } catch {}
+ try { this._viewer?.dispose?.(); } catch {}
+ this._mounted = false;
+ this._runtime = this._viewer = this._scene = this._memory = this._skills = null;
+ }
+
+ // --- Public JS API ---
+
+ async say(text, opts = {}) {
+ if (!this._runtime) await this._waitForReady();
+ return this._runtime.send(text, { voice: opts.voice ?? this.hasAttribute('voice') });
+ }
+
+ async ask(text, opts = {}) {
+ const reply = await this.say(text, opts);
+ return reply?.text || '';
+ }
+
+ clearConversation() { this._runtime?.clearConversation(); }
+
+ async wave(opts) { return this._scene?.playAnimationByHint('wave', opts); }
+ async lookAt(target) { return this._scene?.lookAt(target); }
+ async play(name, opts) { return this._scene?.playClipByName(name, opts); }
+
+ async installSkill(uri) {
+ if (!this._skills) throw new Error('Agent not mounted');
+ return this._skills.install({ uri });
+ }
+ uninstallSkill(name) { return this._skills?.uninstall(name); }
+ get skills() { return this._skills?.all() || []; }
+ get memory() { return this._memory; }
+ get manifest() { return this._manifest; }
+ get runtime() { return this._runtime; }
+
+ setMode(mode) { this.setAttribute('mode', mode); }
+ setPosition(pos, offset) {
+ this.setAttribute('position', pos);
+ if (offset) this.setAttribute('offset', offset);
+ }
+ setSize(w, h) {
+ this.setAttribute('width', w);
+ this.setAttribute('height', h);
+ }
+
+ pause() { this._runtime?.pause(); }
+ resume() { /* viewer resumes via IntersectionObserver */ }
+ destroy() { this._teardown(); }
+
+ _waitForReady() {
+ if (this._mounted) return Promise.resolve();
+ return new Promise((resolve) => {
+ const on = () => { this.removeEventListener('agent:ready', on); resolve(); };
+ this.addEventListener('agent:ready', on);
+ if (!this._booting) this._boot();
+ });
+ }
+}
+
+function stripFrontmatter(text) {
+ const m = text.match(/^---\n[\s\S]*?\n---\n?([\s\S]*)$/);
+ return m ? m[1] : text;
+}
+
+if (!customElements.get('agent-3d')) {
+ customElements.define('agent-3d', Agent3DElement);
+}
+
+export { Agent3DElement };
diff --git a/src/features/hero-gaze.js b/src/features/hero-gaze.js
new file mode 100644
index 000000000..5d2a14ce8
--- /dev/null
+++ b/src/features/hero-gaze.js
@@ -0,0 +1,125 @@
+// Gaze follow — the hero avatar's camera-orbit tracks the user's cursor.
+//
+// Uses <model-viewer>'s camera-orbit attribute rather than reaching into the
+// Three.js scene, so this stays compatible with the CDN-loaded custom element
+// and never touches the main app viewer.
+//
+// When the cursor is active and near the hero, auto-rotate turns off and the
+// avatar tracks. When idle or the cursor leaves the viewport, auto-rotate
+// resumes so the avatar never freezes awkwardly mid-stare.
+
+const BASE_THETA_DEG = 20; // Matches features.html camera-orbit default
+const BASE_PHI_DEG = 80;
+const BASE_RADIUS = '2.4m';
+const THETA_RANGE_DEG = 35; // ±35° azimuth sweep
+const PHI_RANGE_DEG = 8; // ±8° polar sweep — subtle up/down
+const IDLE_MS = 2200; // Resume auto-rotate after this quiet
+const SMOOTH = 0.14; // Lerp factor toward the target per frame
+
+const PREFERS_REDUCED_MOTION =
+ typeof window !== 'undefined' &&
+ window.matchMedia &&
+ window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+export class HeroGaze {
+ constructor(hero) {
+ this.hero = hero;
+ this.modelViewer = hero.modelViewer;
+
+ this._targetTheta = BASE_THETA_DEG;
+ this._targetPhi = BASE_PHI_DEG;
+ this._currentTheta = BASE_THETA_DEG;
+ this._currentPhi = BASE_PHI_DEG;
+
+ this._lastMoveAt = 0;
+ this._rafId = null;
+ this._tracking = false;
+ this._attached = false;
+
+ this._onPointerMove = this._onPointerMove.bind(this);
+ this._onPointerLeave = this._onPointerLeave.bind(this);
+ this._tick = this._tick.bind(this);
+ }
+
+ attach() {
+ if (this._attached || !this.modelViewer) return;
+ if (PREFERS_REDUCED_MOTION) return;
+
+ this._attached = true;
+ window.addEventListener('pointermove', this._onPointerMove, { passive: true });
+ window.addEventListener('pointerleave', this._onPointerLeave);
+ document.addEventListener('mouseleave', this._onPointerLeave);
+
+ this._rafId = requestAnimationFrame(this._tick);
+ }
+
+ detach() {
+ if (!this._attached) return;
+ this._attached = false;
+
+ window.removeEventListener('pointermove', this._onPointerMove);
+ window.removeEventListener('pointerleave', this._onPointerLeave);
+ document.removeEventListener('mouseleave', this._onPointerLeave);
+
+ if (this._rafId != null) cancelAnimationFrame(this._rafId);
+ this._rafId = null;
+
+ // Restore auto-rotate so the hero doesn't stay stuck mid-turn.
+ this._setAutoRotate(true);
+ }
+
+ _onPointerMove(e) {
+ const w = window.innerWidth || 1;
+ const h = window.innerHeight || 1;
+
+ // Normalize cursor to [-1, 1] across viewport with (0,0) at center.
+ const nx = (e.clientX / w) * 2 - 1;
+ const ny = (e.clientY / h) * 2 - 1;
+
+ this._targetTheta = BASE_THETA_DEG + nx * THETA_RANGE_DEG;
+ // Cursor going DOWN should lift the avatar's gaze slightly (lower phi).
+ this._targetPhi = BASE_PHI_DEG - ny * PHI_RANGE_DEG;
+
+ this._lastMoveAt = performance.now();
+
+ if (!this._tracking) {
+ this._tracking = true;
+ this._setAutoRotate(false);
+ }
+ }
+
+ _onPointerLeave() {
+ this._lastMoveAt = 0;
+ this._targetTheta = BASE_THETA_DEG;
+ this._targetPhi = BASE_PHI_DEG;
+ }
+
+ _tick() {
+ if (!this._attached) return;
+
+ // Lerp toward the target so the gaze feels like smooth pursuit, not a snap.
+ this._currentTheta += (this._targetTheta - this._currentTheta) * SMOOTH;
+ this._currentPhi += (this._targetPhi - this._currentPhi) * SMOOTH;
+
+ // Only write the attribute while actively tracking; once we hand back to
+ // auto-rotate, model-viewer owns camera-orbit and we must not fight it.
+ if (this._tracking) {
+ const orbit = `${this._currentTheta.toFixed(2)}deg ${this._currentPhi.toFixed(2)}deg ${BASE_RADIUS}`;
+ this.modelViewer.setAttribute('camera-orbit', orbit);
+ }
+
+ const quietFor = performance.now() - this._lastMoveAt;
+ if (this._tracking && this._lastMoveAt > 0 && quietFor > IDLE_MS) {
+ this._tracking = false;
+ this._setAutoRotate(true);
+ }
+
+ this._rafId = requestAnimationFrame(this._tick);
+ }
+
+ _setAutoRotate(on) {
+ if (!this.modelViewer) return;
+ if (on) this.modelViewer.setAttribute('auto-rotate', '');
+ else this.modelViewer.removeAttribute('auto-rotate');
+ }
+}
diff --git a/src/features/hero-pretext.js b/src/features/hero-pretext.js
new file mode 100644
index 000000000..6cd81f4d2
--- /dev/null
+++ b/src/features/hero-pretext.js
@@ -0,0 +1,46 @@
+// Hero controller for /features — scaffolds submodules behind ?pretext=N flags.
+//
+// Respecting prefers-reduced-motion is the responsibility of any submodule that
+// animates (gaze, dragon reflow). The scaffold itself is inert.
+
+export default class PretextHero {
+ constructor(root, options = {}) {
+ this.root = root;
+ this.content = root?.querySelector('.hero-content') || null;
+ this.title = root?.querySelector('.hero-title') || null;
+ this.subtitle = root?.querySelector('.hero-subtitle') || null;
+ this.avatar = root?.querySelector('.hero-avatar') || null;
+ this.modelViewer = this.avatar?.querySelector('model-viewer') || null;
+
+ this.flag = String(options.flag ?? '1');
+ this.pretext = null;
+
+ this._gaze = null;
+ }
+
+ async init() {
+ const mod = await import('@chenglou/pretext');
+ this.pretext = mod;
+ console.log('[pretext-hero] ready');
+
+ // Flag-gated submodules. 2 and 4 are reserved for text-wrap + dragon mode.
+ if (this.flag === '3' || this.flag === '4') {
+ try {
+ const { HeroGaze } = await import('./hero-gaze.js');
+ this._gaze = new HeroGaze(this);
+ this._gaze.attach();
+ } catch (err) {
+ console.warn('[pretext-hero] gaze unavailable:', err);
+ }
+ }
+
+ return this;
+ }
+
+ dispose() {
+ if (this._gaze) {
+ this._gaze.detach();
+ this._gaze = null;
+ }
+ }
+}
diff --git a/src/lib.js b/src/lib.js
new file mode 100644
index 000000000..331670288
--- /dev/null
+++ b/src/lib.js
@@ -0,0 +1,21 @@
+// Library entry — imported by the CDN bundle <script type="module" src="agent-3d.js">.
+// Registers the custom element and exposes public API classes for programmatic use.
+
+import { Agent3DElement } from './element.js';
+
+export { Agent3DElement };
+export { Viewer } from './viewer.js';
+export { Runtime } from './runtime/index.js';
+export { SceneController } from './runtime/scene.js';
+export { SkillRegistry, Skill } from './skills/index.js';
+export { Memory } from './memory/index.js';
+export { loadManifest, normalize, fetchRelative } from './manifest.js';
+export { resolveURI, fetchWithFallback } from './ipfs.js';
+
+// Re-export the side-effectful element import for users who import the whole bundle.
+export const defineElement = (tag = 'agent-3d') => {
+ if (!customElements.get(tag)) customElements.define(tag, Agent3DElement);
+};
+
+// The element also self-registers on import, but calling defineElement() with a
+// custom tag lets consumers ship under their own brand.
diff --git a/src/manifest.js b/src/manifest.js
new file mode 100644
index 000000000..ba110fc2c
--- /dev/null
+++ b/src/manifest.js
@@ -0,0 +1,155 @@
+// Manifest loader — resolves agent://, ipfs://, https:// into a normalized manifest.
+// See specs/AGENT_MANIFEST.md
+
+import { JsonRpcProvider, Contract } from 'ethers';
+import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';
+import { resolveURI, fetchWithFallback } from './ipfs.js';
+
+const CHAIN_ALIASES = {
+ base: 8453,
+ 'base-mainnet': 8453,
+ 'base-sepolia': 84532,
+ ethereum: 1,
+ mainnet: 1,
+};
+
+const DEFAULT_RPCS = {
+ 8453: 'https://mainnet.base.org',
+ 84532: 'https://sepolia.base.org',
+ 1: 'https://eth.llamarpc.com',
+};
+
+export async function loadManifest(source, { rpcURL, registry: registryOverride } = {}) {
+ if (!source) throw new Error('loadManifest: source required');
+
+ if (source.startsWith('agent://')) {
+ return loadFromAgentURI(source, { rpcURL, registryOverride });
+ }
+ if (source.startsWith('ipfs://') || source.startsWith('ar://')) {
+ const url = resolveURI(source);
+ const json = await fetchManifestJSON(url);
+ return normalize(json, { baseURI: trimToDir(url) });
+ }
+ if (source.startsWith('http')) {
+ const json = await fetchManifestJSON(source);
+ return normalize(json, { baseURI: trimToDir(source) });
+ }
+ throw new Error(`Unsupported manifest source: ${source}`);
+}
+
+async function loadFromAgentURI(uri, { rpcURL, registryOverride }) {
+ // agent://{chain}/{agentId}
+ const m = uri.match(/^agent:\/\/([^/]+)\/(\d+)$/);
+ if (!m) throw new Error(`Malformed agent URI: ${uri}`);
+ const [, chainName, agentIdStr] = m;
+ const chainId = CHAIN_ALIASES[chainName.toLowerCase()] || Number(chainName);
+ if (!chainId) throw new Error(`Unknown chain: ${chainName}`);
+
+ const deployment = REGISTRY_DEPLOYMENTS[chainId];
+ const registryAddr = registryOverride || deployment?.identityRegistry;
+ if (!registryAddr) {
+ throw new Error(`No registry deployed on chain ${chainId}. Pass registry= override.`);
+ }
+
+ const provider = new JsonRpcProvider(rpcURL || DEFAULT_RPCS[chainId]);
+ const registry = new Contract(registryAddr, IDENTITY_REGISTRY_ABI, provider);
+ const agentId = BigInt(agentIdStr);
+
+ const tokenURI = await registry.tokenURI(agentId);
+ if (!tokenURI) throw new Error(`Agent ${agentIdStr} on chain ${chainId} has no URI`);
+
+ const resolved = resolveURI(tokenURI);
+ const json = await fetchManifestJSON(resolved);
+ const manifest = normalize(json, { baseURI: trimToDir(resolved) });
+
+ // Ensure id is stamped on the manifest
+ manifest.id = {
+ ...manifest.id,
+ chain: chainName,
+ chainId,
+ registry: registryAddr,
+ agentId: agentIdStr,
+ };
+ return manifest;
+}
+
+async function fetchManifestJSON(url) {
+ // Prefer fetchWithFallback if this is an IPFS URI we can detect.
+ let res;
+ try {
+ res = await fetch(url);
+ } catch {
+ res = await fetchWithFallback(url);
+ }
+ if (!res.ok) throw new Error(`Manifest fetch failed: ${url} (${res.status})`);
+ return res.json();
+}
+
+// Convert either a full AGENT_MANIFEST or a bare ERC-8004 registration JSON
+// into a uniform manifest object the runtime consumes.
+export function normalize(json, { baseURI = '' } = {}) {
+ // Full manifest — spec: "agent-manifest/0.1"
+ if (json.spec && json.spec.startsWith('agent-manifest/')) {
+ const m = { ...json, _baseURI: baseURI };
+ m.body = m.body || {};
+ if (!m.body.uri && m.image) m.body.uri = m.image;
+ return m;
+ }
+
+ // ERC-8004 registration JSON — adapt to manifest shape
+ if (json.type && json.type.includes('eip-8004')) {
+ const registration = json.registrations?.[0] || {};
+ return {
+ spec: 'agent-manifest/0.1',
+ _baseURI: baseURI,
+ _source: 'erc8004-registration',
+ id: { agentId: registration.agentId?.toString() },
+ name: json.name,
+ description: json.description,
+ image: json.image,
+ body: { uri: json.image, format: 'gltf-binary' },
+ brain: { provider: 'none' },
+ voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },
+ skills: [],
+ memory: { mode: 'local' },
+ tools: ['wave', 'lookAt', 'play_clip', 'setExpression'],
+ version: '0.1.0',
+ };
+ }
+
+ // Unknown / partial — best effort
+ return {
+ spec: 'agent-manifest/0.1',
+ _baseURI: baseURI,
+ name: json.name || 'Unnamed agent',
+ description: json.description || '',
+ body: {
+ uri: json.body?.uri || json.image || json.model || '',
+ format: json.body?.format || 'gltf-binary',
+ },
+ brain: json.brain || { provider: 'none' },
+ voice: json.voice || { tts: { provider: 'browser' }, stt: { provider: 'browser' } },
+ skills: json.skills || [],
+ memory: json.memory || { mode: 'local' },
+ tools: json.tools || ['wave', 'lookAt', 'play_clip', 'setExpression'],
+ version: json.version || '0.1.0',
+ };
+}
+
+function trimToDir(url) {
+ const i = url.lastIndexOf('/');
+ return i >= 0 ? url.slice(0, i + 1) : url;
+}
+
+// Load instructions.md, SKILL.md and other relative files referenced by the manifest
+export async function fetchRelative(manifest, relPath) {
+ if (!manifest._baseURI) return null;
+ try {
+ const url = new URL(relPath, manifest._baseURI).href;
+ const res = await fetch(url);
+ if (!res.ok) return null;
+ return res.text();
+ } catch {
+ return null;
+ }
+}
diff --git a/src/nich-agent.js b/src/nich-agent.js
index def8fa211..88e95200f 100644
--- a/src/nich-agent.js
+++ b/src/nich-agent.js
@@ -1,26 +1,72 @@
+/**
+ * NichAgent — Voice + Chat Interface
+ * ------------------------------------
+ * The conversational surface of the 3D agent.
+ * Now protocol-aware: responses go through the AgentProtocol bus,
+ * which drives the avatar's Empathy Layer and action timeline.
+ *
+ * Skills-aware: routes recognised intents to AgentSkills.perform()
+ * so the avatar performs them visibly, not just textually.
+ */
+
+import { ACTION_TYPES } from './agent-protocol.js';
+
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
export class NichAgent {
- constructor(containerEl) {
- this.container = containerEl;
- this.isReady = true;
+ /**
+ * @param {HTMLElement} containerEl
+ * @param {import('./agent-protocol.js').AgentProtocol} [protocol]
+ * @param {import('./agent-skills.js').AgentSkills} [skills]
+ * @param {import('./agent-identity.js').AgentIdentity} [identity]
+ * @param {import('./runtime/index.js').Runtime} [runtime]
+ */
+ constructor(containerEl, protocol = null, skills = null, identity = null, runtime = null) {
+ this.container = containerEl;
+ this.protocol = protocol;
+ this.skills = skills;
+ this.identity = identity;
+ this.runtime = runtime;
this.isSpeaking = false;
this.isListening = false;
this.recognition = null;
- this.synth = window.speechSynthesis;
- this.messages = [];
+ this.synth = window.speechSynthesis;
+ this.messages = [];
+ this.onFirstOpen = null;
+ this._hasOpened = false;
this._buildUI();
this._initSpeechRecognition();
+
+ // Listen for SPEAK actions to render them in the chat
+ if (this.protocol) {
+ this.protocol.on(ACTION_TYPES.SPEAK, (action) => {
+ const text = action.payload?.text;
+ if (text) {
+ this._addMessage('agent', text);
+ this._speak(text);
+ }
+ });
+
+ // Show skill status in chat
+ this.protocol.on(ACTION_TYPES.PERFORM_SKILL, (action) => {
+ const skill = action.payload?.skill;
+ if (skill && skill !== 'greet') {
+ this._addMessage('agent', `[performing: ${skill}]`, 'status');
+ }
+ });
+ }
}
+ // ── Speech Recognition ────────────────────────────────────────────────────
+
_initSpeechRecognition() {
if (!SpeechRecognition) return;
this.recognition = new SpeechRecognition();
- this.recognition.continuous = false;
- this.recognition.interimResults = false;
- this.recognition.lang = 'en-US';
+ this.recognition.continuous = false;
+ this.recognition.interimResults = false;
+ this.recognition.lang = 'en-US';
this.recognition.onresult = (event) => {
const text = event.results[0][0].transcript;
@@ -39,19 +85,24 @@ export class NichAgent {
};
}
+ // ── UI ────────────────────────────────────────────────────────────────────
+
_buildUI() {
this.panel = document.createElement('div');
- this.panel.className = 'nich-panel';
- this.panel.innerHTML = `
+ this.panel.className = 'nich-panel';
+ this.panel.innerHTML = `
<div class="nich-header">
- <span class="nich-title">SperaxOS</span>
- <button class="nich-close" aria-label="Close">&times;</button>
+ <span class="nich-title">${this.identity?.name || 'Agent'}</span>
+ <div class="nich-header-right">
+ <span class="nich-emotion-dot" id="nich-emotion-dot" title="Agent emotional state"></span>
+ <button class="nich-close" aria-label="Close">&times;</button>
+ </div>
</div>
<div class="nich-messages" id="agent-messages">
- <div class="nich-message agent">Hi! I'm your 3D Agent. Ask me about 3D models, controls, or drop a file to get started.</div>
+ <div class="nich-message agent">I'm here. Drop a model, ask me anything, or say "help".</div>
</div>
<div class="nich-controls">
- <input type="text" class="nich-input" placeholder="Ask the agent..." />
+ <input type="text" class="nich-input" placeholder="Ask the agent…" autocomplete="off" />
<button class="nich-send" aria-label="Send">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>
</button>
@@ -60,6 +111,7 @@ export class NichAgent {
<button class="nich-mic" aria-label="Toggle microphone">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm-1-9c0-.55.45-1 1-1s1 .45 1 1v6c0 .55-.45 1-1 1s-1-.45-1-1V5zm6 6c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/></svg>
</button>
+ <span class="nich-mic-hint">or press mic to speak</span>
</div>
`;
this.panel.style.display = 'none';
@@ -67,147 +119,195 @@ export class NichAgent {
this.toggleBtn = document.createElement('button');
this.toggleBtn.className = 'nich-toggle';
+ this.toggleBtn.setAttribute('aria-label', 'Talk to 3D Agent');
+ this.toggleBtn.title = 'Talk to Agent';
this.toggleBtn.innerHTML = `
- <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/><path d="M7 9h2v2H7zm4 0h2v2h-2zm4 0h2v2h-2z"/></svg>
+ <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
+ <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>
+ <path d="M7 9h2v2H7zm4 0h2v2h-2zm4 0h2v2h-2z"/>
+ </svg>
+ <span class="nich-toggle-label">Agent</span>
`;
- this.toggleBtn.title = 'Talk to 3D Agent';
this.container.appendChild(this.toggleBtn);
- this.toggleBtn.addEventListener('click', () => this._togglePanel());
+ this.toggleBtn.addEventListener('click', () => this._togglePanel());
this.panel.querySelector('.nich-close').addEventListener('click', () => this._togglePanel());
- this.panel.querySelector('.nich-send').addEventListener('click', () => this._send());
+ this.panel.querySelector('.nich-send').addEventListener('click', () => this._send());
this.panel.querySelector('.nich-input').addEventListener('keydown', (e) => {
if (e.key === 'Enter') this._send();
});
this.panel.querySelector('.nich-mic').addEventListener('click', () => this._toggleMic());
}
+ // ── Panel Toggle ──────────────────────────────────────────────────────────
+
_togglePanel() {
const visible = this.panel.style.display !== 'none';
this.panel.style.display = visible ? 'none' : 'flex';
this.toggleBtn.classList.toggle('active', !visible);
if (!visible) {
this.panel.querySelector('.nich-input').focus();
+ // First open triggers a greeting skill
+ if (!this._hasOpened) {
+ this._hasOpened = true;
+ if (this.onFirstOpen) this.onFirstOpen();
+ else if (this.skills) {
+ this.skills.perform('greet', {}, { identity: this.identity });
+ }
+ }
}
}
+ // ── Input Handling ────────────────────────────────────────────────────────
+
_send() {
const input = this.panel.querySelector('.nich-input');
- const text = input.value.trim();
+ const text = input.value.trim();
if (!text) return;
input.value = '';
-
this._addMessage('user', text);
this._handleInput(text);
}
- _handleInput(text) {
+ async _handleInput(text) {
+ const lower = text.toLowerCase();
+
+ // Route to skills first (high-precision pattern matching)
+ if (this.skills) {
+ const skillName = this._matchSkill(lower);
+ if (skillName) {
+ await this.skills.perform(skillName, { query: text }, { identity: this.identity });
+ return;
+ }
+ }
+
+ // Try Runtime LLM when a real provider is configured (not NullProvider)
+ if (this.runtime) {
+ try {
+ const { text: reply } = await this.runtime.send(text);
+ if (reply) {
+ this._addMessage('agent', reply);
+ this._speak(reply);
+ // Runtime events are bridged to protocol in app.js — no double emit
+ return;
+ }
+ } catch (err) {
+ console.warn('[NichAgent] Runtime error, falling back:', err.message);
+ }
+ }
+
+ // Fallback: pattern-match response (no LLM needed)
const response = this._generateResponse(text);
this._addMessage('agent', response);
this._speak(response);
+
+ if (this.protocol) {
+ this.protocol.emit({
+ type: ACTION_TYPES.SPEAK,
+ payload: { text: response, sentiment: 0 },
+ agentId: this.identity?.id || 'default',
+ });
+ }
}
- _generateResponse(input) {
- const lower = input.toLowerCase();
+ /**
+ * Map user input to a skill name.
+ * Returns null if no skill matches.
+ */
+ _matchSkill(lower) {
+ if (lower.match(/\b(present|describe|tell me about|what.*model|show me)\b/)) return 'present-model';
+ if (lower.match(/\b(validate|check|errors|warnings|valid)\b/)) return 'validate-model';
+ if (lower.match(/\b(remember|save|store|note|don't forget)\b/)) return 'remember';
+ if (lower.match(/\b(sign|signature|wallet|verify|prove)\b/)) return 'sign-action';
+ if (lower.match(/\b(think|recall|what do you know|context)\b/)) return 'think';
+ if (lower.match(/\b(help|what can you|commands|skills|abilities)\b/)) return 'help';
+ return null;
+ }
+
+ // ── Response Generation (fallback) ────────────────────────────────────────
- // Viewer info from window.VIEWER if available
+ _generateResponse(input) {
+ const lower = input.toLowerCase();
const viewer = window.VIEWER?.app?.viewer;
- if (lower.match(/\b(hello|hi|hey|sup)\b/)) {
- return 'Hey! Drop a 3D model into the viewer, or ask me about the controls.';
+ if (lower.match(/\b(hello|hi|hey|sup|yo)\b/)) {
+ return 'Hey! Drop a 3D model in or ask me about the controls.';
}
-
if (lower.match(/\b(how|what).*(upload|load|open|import)\b/)) {
- return 'You can drag and drop any glTF or GLB file onto the viewer, or click the upload button at the bottom. The model will load instantly in your browser.';
+ return 'Drag and drop any glTF or GLB file onto the viewer, or click the upload button. The model loads instantly in your browser.';
}
-
if (lower.match(/\b(rotate|spin|orbit)\b/)) {
- return 'Click and drag to orbit the camera around the model. You can enable auto-rotate in the Display controls panel on the right.';
+ return 'Click and drag to orbit. Enable auto-rotate in the Display controls panel on the right.';
}
-
if (lower.match(/\b(zoom)\b/)) {
- return 'Use the scroll wheel to zoom in and out. On mobile, pinch to zoom.';
+ return 'Scroll wheel to zoom. On mobile, pinch.';
}
-
if (lower.match(/\b(pan|move)\b/)) {
- return 'Right-click and drag to pan the camera. On mobile, use two fingers to pan. You can toggle screen-space panning in the Display panel.';
+ return 'Right-click and drag to pan. Two fingers on mobile.';
}
-
if (lower.match(/\b(wireframe)\b/)) {
- return 'Toggle wireframe mode from the Display controls panel on the right. It shows the mesh topology of your model.';
+ return 'Toggle wireframe in the Display controls panel — shows mesh topology.';
}
-
- if (lower.match(/\b(light|lighting|dark|bright)\b/)) {
- return 'Open the Lighting folder in the controls panel. You can change the environment map, adjust exposure, toggle punctual lights, and modify ambient and direct light intensity and color.';
+ if (lower.match(/\b(light|lighting|dark|bright|exposure)\b/)) {
+ return 'Open the Lighting folder in the controls panel. Change the environment map, adjust exposure, toggle punctual lights.';
}
-
- if (lower.match(/\b(animation|animate|play)\b/)) {
- return 'If your model has animations, they\'ll appear in the Animation folder. You can adjust playback speed or use "playAll" to play all clips at once.';
+ if (lower.match(/\b(animation|animate|play|clip)\b/)) {
+ return viewer?.clips?.length
+ ? `This model has ${viewer.clips.length} animation clip${viewer.clips.length !== 1 ? 's' : ''}. Find them in the Animation folder.`
+ : 'No animations on this model, or load a model first.';
}
-
if (lower.match(/\b(background|bg|color)\b/)) {
- return 'You can change the background color in the Display controls using the bgColor picker. Or toggle "background" to use the environment map as the background.';
+ return 'Change the background colour in the Display controls using the bgColor picker.';
}
-
if (lower.match(/\b(format|gltf|glb|supported|file)\b/)) {
- return 'This viewer supports glTF 2.0 (.gltf) and GLB (.glb) files. These are the standard formats for 3D on the web. You can convert other formats using tools like Blender.';
+ return 'Supports glTF 2.0 (.gltf) and GLB (.glb). Convert other formats with Blender.';
}
-
if (lower.match(/\b(skeleton|bones|rig)\b/)) {
- return 'Enable the skeleton helper in the Display panel to visualize the bone structure of rigged models.';
+ return 'Enable skeleton helper in the Display panel to visualise bone structure.';
}
-
- if (lower.match(/\b(grid)\b/)) {
- return 'Toggle the grid in the Display panel. It helps you understand the scale and orientation of your model.';
+ if (lower.match(/\b(screenshot|capture|photo)\b/)) {
+ return 'Press P to take a screenshot. It downloads as a PNG automatically.';
}
-
if (lower.match(/\b(performance|fps|stats)\b/)) {
- return 'Open the Performance folder in the controls panel to see an FPS counter and rendering stats.';
- }
-
- if (lower.match(/\b(validation|error|warning|report)\b/)) {
- if (viewer) {
- return 'After loading a model, the validator runs automatically and shows any issues at the bottom of the screen. Click the warning bar to see the full report.';
- }
- return 'Load a model first, then the validator will check it automatically and display any warnings or errors.';
+ return 'Open the Performance folder in the controls panel for live FPS/MS/MB stats.';
}
-
- if (lower.match(/\b(what|who).*(you|this|3d agent)\b/)) {
- return 'I\'m 3D Agent — your assistant for previewing and understanding 3D models. I can help you navigate controls, understand file formats, and troubleshoot issues.';
+ if (lower.match(/\b(who|what).*(you|this|agent)\b/)) {
+ return `I'm ${this.identity?.name || '3D Agent'} — present, embodied, and here to help with your 3D work.`;
}
-
- if (lower.match(/\b(help|commands|can you)\b/)) {
- return 'I can help with: loading models, camera controls (rotate, zoom, pan), lighting setup, animations, wireframe/skeleton views, validation reports, and format questions. Just ask!';
+ if (lower.match(/\b(memory|remember|memories)\b/)) {
+ const stats = this.identity?.memory?.stats;
+ if (stats?.total) {
+ return `I have ${stats.total} memories: ${stats.user || 0} about you, ${stats.project || 0} project notes, ${stats.feedback || 0} feedback entries.`;
+ }
+ return 'No memories yet. Tell me something worth remembering.';
}
- return 'I can help with model viewing, controls, lighting, animations, and file formats. Try asking about a specific feature, or drop a glTF/GLB file to get started!';
+ return "Try asking me to present or validate the loaded model, or drop a glTF/GLB file to get started.";
}
+ // ── Speech Synthesis ─────────────────────────────────────────────────────
+
_speak(text) {
if (!this.synth) return;
this.synth.cancel();
- const utterance = new SpeechSynthesisUtterance(text);
- utterance.rate = 1.0;
- utterance.pitch = 1.0;
- utterance.volume = 0.8;
-
- utterance.onstart = () => {
- this.isSpeaking = true;
- };
- utterance.onend = () => {
- this.isSpeaking = false;
- };
+ const utterance = new SpeechSynthesisUtterance(text);
+ utterance.rate = 1.0;
+ utterance.pitch = 1.0;
+ utterance.volume = 0.8;
+ utterance.onstart = () => { this.isSpeaking = true; };
+ utterance.onend = () => { this.isSpeaking = false; };
this.synth.speak(utterance);
}
+ // ── Mic Toggle ────────────────────────────────────────────────────────────
+
_toggleMic() {
if (!this.recognition) {
- this._addMessage('agent', 'Speech recognition is not supported in this browser. Try Chrome or Edge.');
+ this._addMessage('agent', 'Speech recognition not supported here. Try Chrome or Edge.');
return;
}
-
if (this.isListening) {
this.recognition.stop();
this.isListening = false;
@@ -219,16 +319,22 @@ export class NichAgent {
}
}
- _addMessage(role, text) {
- this.messages.push({ role, text });
+ // ── Message Rendering ────────────────────────────────────────────────────
+
+ _addMessage(role, text, type = '') {
+ if (role !== 'status') {
+ this.messages.push({ role, text });
+ }
const messagesEl = this.panel.querySelector('#agent-messages');
- const msgEl = document.createElement('div');
- msgEl.className = `nich-message ${role}`;
+ const msgEl = document.createElement('div');
+ msgEl.className = `nich-message ${role}${type ? ' ' + type : ''}`;
msgEl.textContent = text;
messagesEl.appendChild(msgEl);
messagesEl.scrollTop = messagesEl.scrollHeight;
}
+ // ── Dispose ───────────────────────────────────────────────────────────────
+
dispose() {
if (this.recognition) this.recognition.stop();
this.synth.cancel();
diff --git a/src/runtime/index.js b/src/runtime/index.js
new file mode 100644
index 000000000..eb7fdbef8
--- /dev/null
+++ b/src/runtime/index.js
@@ -0,0 +1,194 @@
+// Runtime — wires LLM + tool dispatch + speech + memory into a single agent brain.
+// Replaces the pattern-matched chatbot stub in avaturn-agent.js.
+
+import { createProvider } from './providers.js';
+import { createTTS, createSTT } from './speech.js';
+import { BUILTIN_TOOLS, BUILTIN_HANDLERS } from './tools.js';
+
+const MAX_TOOL_ITERATIONS = 8;
+
+export class Runtime extends EventTarget {
+ constructor({ manifest, viewer, memory, skills, providerConfig = {}, voiceConfig = {} } = {}) {
+ super();
+ this.manifest = manifest || {};
+ this.viewer = viewer;
+ this.memory = memory;
+ this.skills = skills;
+
+ this.provider = createProvider({
+ ...this.manifest.brain,
+ ...providerConfig,
+ });
+ this.tts = createTTS({ ...(this.manifest.voice?.tts), ...voiceConfig.tts });
+ this.stt = createSTT({ ...(this.manifest.voice?.stt), ...voiceConfig.stt });
+
+ this.messages = [];
+ this._busy = false;
+ }
+
+ get systemPrompt() {
+ const parts = [];
+ if (this.manifest.instructions) parts.push(this.manifest.instructions);
+ if (this.memory) {
+ parts.push('\n\n<memory>\n' + this.memory.contextBlock({
+ maxTokens: this.manifest.memory?.maxTokens || 8192,
+ }) + '\n</memory>');
+ }
+ if (this.skills) parts.push(this.skills.systemPrompt());
+ return parts.join('');
+ }
+
+ get tools() {
+ const builtinNames = new Set(this.manifest.tools || BUILTIN_TOOLS.map((t) => t.name));
+ const builtins = BUILTIN_TOOLS.filter((t) => builtinNames.has(t.name));
+ const skillTools = this.skills ? this.skills.allTools() : [];
+ return [...builtins, ...skillTools];
+ }
+
+ async send(userText, { voice = false } = {}) {
+ if (this._busy) {
+ throw new Error('Runtime busy — wait for current turn to finish');
+ }
+ this._busy = true;
+ try {
+ this.memory?.note('user_said', { text: userText });
+ this.messages.push({ role: 'user', content: userText });
+ this.dispatchEvent(new CustomEvent('brain:message', {
+ detail: { role: 'user', content: userText },
+ }));
+
+ const reply = await this._loop();
+
+ if (voice && reply.text && this.tts) {
+ this.dispatchEvent(new CustomEvent('voice:speech-start', { detail: { text: reply.text } }));
+ await this.tts.speak(reply.text);
+ this.dispatchEvent(new CustomEvent('voice:speech-end', {}));
+ }
+
+ return reply;
+ } finally {
+ this._busy = false;
+ }
+ }
+
+ async _loop() {
+ let iter = 0;
+ let finalText = '';
+
+ while (iter++ < MAX_TOOL_ITERATIONS) {
+ const response = await this.provider.complete({
+ system: this.systemPrompt,
+ messages: this.messages,
+ tools: this.tools,
+ });
+
+ if (response.thinking) {
+ this.dispatchEvent(new CustomEvent('brain:thinking', { detail: { content: response.thinking } }));
+ }
+
+ if (!response.toolCalls.length) {
+ finalText = response.text;
+ this.messages.push({ role: 'assistant', content: response.text });
+ this.dispatchEvent(new CustomEvent('brain:message', {
+ detail: { role: 'assistant', content: response.text },
+ }));
+ break;
+ }
+
+ // Record assistant turn with tool calls
+ this.messages.push(
+ this.provider.formatAssistantWithToolCalls(response.text, response.toolCalls),
+ );
+ if (response.text) {
+ this.dispatchEvent(new CustomEvent('brain:message', {
+ detail: { role: 'assistant', content: response.text },
+ }));
+ }
+
+ // Dispatch each tool call
+ const results = [];
+ for (const call of response.toolCalls) {
+ let output, isError = false;
+ try {
+ output = await this._dispatchTool(call);
+ } catch (err) {
+ output = { error: err.message || String(err) };
+ isError = true;
+ }
+ this.dispatchEvent(new CustomEvent('skill:tool-called', {
+ detail: { tool: call.name, args: call.input, result: output },
+ }));
+ results.push({ id: call.id, output, isError });
+ }
+ this.messages.push(this.provider.formatToolResults(results));
+ }
+
+ return { text: finalText };
+ }
+
+ async _dispatchTool(call) {
+ const ctx = this._context();
+
+ // Skill-provided tools first (they can shadow built-ins intentionally)
+ const skill = this.skills?.findSkillForTool(call.name);
+ if (skill) return skill.invoke(call.name, call.input, ctx);
+
+ // Built-in
+ const handler = BUILTIN_HANDLERS[call.name];
+ if (!handler) throw new Error(`Unknown tool: ${call.name}`);
+ return handler(call.input, ctx);
+ }
+
+ _context() {
+ const skills = this.skills;
+ return {
+ viewer: this.viewer,
+ memory: this.memory,
+ llm: {
+ complete: (prompt, opts) => this.provider.complete({
+ system: opts?.system || '',
+ messages: [{ role: 'user', content: prompt }],
+ tools: opts?.tools,
+ }),
+ },
+ speak: async (text) => {
+ if (!this.tts) return;
+ this.dispatchEvent(new CustomEvent('voice:speech-start', { detail: { text } }));
+ await this.tts.speak(text);
+ this.dispatchEvent(new CustomEvent('voice:speech-end', {}));
+ },
+ listen: (opts) => this.stt?.listen(opts),
+ fetch: (url, opts) => fetch(url, opts),
+ loadGLB: async (uri) => {
+ // Delegates to viewer's loader. Actual wiring in element.js binds this.
+ return this.viewer.loadGLB?.(uri);
+ },
+ loadClip: async (uri) => this.viewer.loadClip?.(uri),
+ loadJSON: async (uri) => (await fetch(uri)).json(),
+ call: async (toolName, args) => this._dispatchTool({ name: toolName, input: args }),
+ };
+ }
+
+ async listen({ onInterim, onFinal } = {}) {
+ if (!this.stt) throw new Error('STT not configured');
+ this.dispatchEvent(new CustomEvent('voice:listen-start', {}));
+ const text = await this.stt.listen({
+ onInterim: (t) => {
+ this.dispatchEvent(new CustomEvent('voice:transcript', { detail: { text: t, final: false } }));
+ onInterim?.(t);
+ },
+ onFinal: (t) => {
+ this.dispatchEvent(new CustomEvent('voice:transcript', { detail: { text: t, final: true } }));
+ onFinal?.(t);
+ },
+ });
+ return text;
+ }
+
+ clearConversation() {
+ this.messages = [];
+ }
+
+ pause() { this.tts?.cancel(); this.stt?.stop(); }
+ destroy() { this.pause(); this.messages = []; }
+}
diff --git a/src/runtime/scene.js b/src/runtime/scene.js
new file mode 100644
index 000000000..6639762f3
--- /dev/null
+++ b/src/runtime/scene.js
@@ -0,0 +1,205 @@
+// SceneController — wraps a Viewer instance with the scene-tool API the runtime
+// and skills expect (playClipByName, lookAt, setExpression, loadClip, loadGLB).
+//
+// Keeps viewer.js untouched while giving agents a coherent control surface.
+
+import { Vector3 } from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { resolveURI } from '../ipfs.js';
+
+const EXPRESSION_MAP = {
+ neutral: { /* reset all */ },
+ happy: { mouthSmile: 1, browInnerUp: 0.3, cheekSquintL: 0.4, cheekSquintR: 0.4 },
+ sad: { mouthFrownL: 0.8, mouthFrownR: 0.8, browDownL: 0.6, browDownR: 0.6 },
+ surprised: { jawOpen: 0.5, eyeWideL: 0.8, eyeWideR: 0.8, browInnerUp: 0.9 },
+ confused: { browInnerUp: 0.5, browOuterUpL: 0.4, mouthPressL: 0.3, mouthPressR: 0.3 },
+ focused: { browDownL: 0.4, browDownR: 0.4, eyeSquintL: 0.3, eyeSquintR: 0.3 },
+};
+
+export class SceneController {
+ constructor(viewer) {
+ this.viewer = viewer;
+ this._loader = new GLTFLoader();
+ this._userTarget = new Vector3(0, 1.6, 2); // approx user head position
+ }
+
+ // Expose the underlying Three.js handles skills may need
+ get scene() { return this.viewer.scene; }
+ get mixer() { return this.viewer.mixer; }
+ get clips() { return this.viewer.clips || []; }
+ get content() { return this.viewer.content; }
+
+ // Delegate raw load for ad-hoc cases
+ async load(url, rootPath = '', assetMap = new Map()) {
+ return this.viewer.load(url, rootPath, assetMap);
+ }
+
+ // --- Animation ---
+
+ playClipByName(name, { loop = false, fade_ms = 200 } = {}) {
+ const clip = this._findClip(name);
+ if (!clip || !this.viewer.mixer) return false;
+ const action = this.viewer.mixer.clipAction(clip);
+ action.reset();
+ action.setLoop(loop ? 2201 /* LoopRepeat */ : 2200 /* LoopOnce */);
+ action.clampWhenFinished = !loop;
+ action.fadeIn(fade_ms / 1000);
+ action.play();
+ this.viewer.state.actionStates[clip.name] = true;
+ this.viewer.invalidate();
+ return true;
+ }
+
+ playAnimationByHint(hint, opts) {
+ const lower = hint.toLowerCase();
+ const match = this.clips.find((c) => c.name.toLowerCase().includes(lower));
+ if (match) return this.playClipByName(match.name, opts);
+ // Fallback — skills can ship their own clips via loadClip
+ return false;
+ }
+
+ stopClip(name) {
+ if (!this.viewer.mixer) return;
+ const clip = name ? this._findClip(name) : null;
+ if (clip) {
+ const action = this.viewer.mixer.existingAction(clip);
+ if (action) action.fadeOut(0.2);
+ this.viewer.state.actionStates[clip.name] = false;
+ } else {
+ this.viewer.mixer.stopAllAction();
+ for (const k in this.viewer.state.actionStates) this.viewer.state.actionStates[k] = false;
+ }
+ this.viewer.invalidate();
+ }
+
+ async play(clip, opts) {
+ // Accept either a clip name or an AnimationClip instance.
+ if (typeof clip === 'string') return this.playClipByName(clip, opts);
+ if (!this.viewer.mixer || !clip) return false;
+ const action = this.viewer.mixer.clipAction(clip);
+ action.reset();
+ action.fadeIn((opts?.blend ?? 0.2));
+ action.play();
+ this.viewer.invalidate();
+ return true;
+ }
+
+ async loadClip(uri) {
+ const resolved = resolveURI(uri);
+ return new Promise((resolve, reject) => {
+ this._loader.load(
+ resolved,
+ (gltf) => resolve(gltf.animations?.[0] || null),
+ undefined,
+ reject,
+ );
+ });
+ }
+
+ async loadGLB(uri) {
+ const resolved = resolveURI(uri);
+ return new Promise((resolve, reject) => {
+ this._loader.load(resolved, resolve, undefined, reject);
+ });
+ }
+
+ // --- Gaze ---
+
+ lookAt(target) {
+ const t = this._resolveTarget(target);
+ if (!t || !this.viewer.content) return;
+ // Simple head-bone gaze if rig has Head, otherwise root rotation.
+ const head = this._findBone(['Head', 'head', 'mixamorigHead']);
+ if (head) {
+ head.lookAt(t);
+ } else {
+ this.viewer.content.lookAt(t.x, this.viewer.content.position.y, t.z);
+ }
+ this.viewer.invalidate();
+ }
+
+ _resolveTarget(target) {
+ if (target instanceof Vector3) return target;
+ if (target === 'camera') return this.viewer.activeCamera.position.clone();
+ if (target === 'center') return new Vector3(0, 1, 0);
+ if (target === 'user') return this._userTarget.clone();
+ return null;
+ }
+
+ _findBone(names) {
+ if (!this.viewer.content) return null;
+ let found = null;
+ this.viewer.content.traverse((n) => {
+ if (found) return;
+ if (n.isBone && names.includes(n.name)) found = n;
+ });
+ return found;
+ }
+
+ // --- Expression (morph targets) ---
+
+ setExpression(preset, intensity = 1) {
+ const influences = EXPRESSION_MAP[preset] || EXPRESSION_MAP.neutral;
+ if (!this.viewer.content) return;
+ this.viewer.content.traverse((mesh) => {
+ if (!mesh.morphTargetDictionary || !mesh.morphTargetInfluences) return;
+ // Reset all first
+ for (let i = 0; i < mesh.morphTargetInfluences.length; i++) {
+ mesh.morphTargetInfluences[i] = 0;
+ }
+ // Apply preset influences by morph target name
+ for (const [morphName, value] of Object.entries(influences)) {
+ const idx = mesh.morphTargetDictionary[morphName];
+ if (idx !== undefined) {
+ mesh.morphTargetInfluences[idx] = value * intensity;
+ }
+ }
+ });
+ this.viewer.invalidate();
+ }
+
+ // --- Movement ---
+
+ moveTo(position, { duration = 600 } = {}) {
+ if (!this.viewer.content) return;
+ const start = this.viewer.content.position.clone();
+ const end = new Vector3(position.x || 0, position.y || start.y, position.z || 0);
+ const startT = performance.now();
+ const tick = (dt) => {
+ const elapsed = performance.now() - startT;
+ const t = Math.min(elapsed / duration, 1);
+ const eased = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
+ this.viewer.content.position.lerpVectors(start, end, eased);
+ this.viewer.invalidate();
+ if (t >= 1) this._removeHook(tick);
+ };
+ this._addHook(tick);
+ }
+
+ // --- Per-frame hooks (uses Viewer._afterAnimateHooks extension point) ---
+
+ _addHook(fn) {
+ if (!this.viewer._afterAnimateHooks) this.viewer._afterAnimateHooks = [];
+ this.viewer._afterAnimateHooks.push(fn);
+ this.viewer._animating = true;
+ this.viewer.invalidate();
+ }
+
+ _removeHook(fn) {
+ const hooks = this.viewer._afterAnimateHooks;
+ if (!hooks) return;
+ const i = hooks.indexOf(fn);
+ if (i >= 0) hooks.splice(i, 1);
+ }
+
+ // --- Helpers ---
+
+ _findClip(name) {
+ if (!this.clips.length) return null;
+ const exact = this.clips.find((c) => c.name === name);
+ if (exact) return exact;
+ const ci = name.toLowerCase();
+ return this.clips.find((c) => c.name.toLowerCase() === ci)
+ || this.clips.find((c) => c.name.toLowerCase().includes(ci));
+ }
+}
diff --git a/src/runtime/speech.js b/src/runtime/speech.js
new file mode 100644
index 000000000..a010c89e6
--- /dev/null
+++ b/src/runtime/speech.js
@@ -0,0 +1,111 @@
+// Speech I/O — TTS and STT. Browser-native by default; provider-swappable.
+
+export class BrowserTTS {
+ constructor({ voiceId = 'default', rate = 1, pitch = 1, lang = 'en-US' } = {}) {
+ this.voiceId = voiceId;
+ this.rate = rate;
+ this.pitch = pitch;
+ this.lang = lang;
+ this._queue = [];
+ this._speaking = false;
+ }
+
+ async speak(text, { onStart, onEnd } = {}) {
+ if (!('speechSynthesis' in window)) return;
+ return new Promise((resolve) => {
+ const utter = new SpeechSynthesisUtterance(text);
+ utter.rate = this.rate;
+ utter.pitch = this.pitch;
+ utter.lang = this.lang;
+ const voice = this._pickVoice();
+ if (voice) utter.voice = voice;
+ utter.onstart = () => { this._speaking = true; onStart?.(); };
+ utter.onend = () => { this._speaking = false; onEnd?.(); resolve(); };
+ utter.onerror = () => { this._speaking = false; resolve(); };
+ window.speechSynthesis.speak(utter);
+ });
+ }
+
+ cancel() {
+ if ('speechSynthesis' in window) window.speechSynthesis.cancel();
+ this._speaking = false;
+ }
+
+ get speaking() { return this._speaking; }
+
+ _pickVoice() {
+ if (!('speechSynthesis' in window)) return null;
+ const voices = window.speechSynthesis.getVoices();
+ if (this.voiceId && this.voiceId !== 'default') {
+ const found = voices.find((v) => v.name === this.voiceId || v.voiceURI === this.voiceId);
+ if (found) return found;
+ }
+ return voices.find((v) => v.lang?.startsWith(this.lang.slice(0, 2))) || null;
+ }
+}
+
+export class BrowserSTT {
+ constructor({ language = 'en-US', continuous = false, interimResults = true } = {}) {
+ this.language = language;
+ this.continuous = continuous;
+ this.interimResults = interimResults;
+ this._recognition = null;
+ this._listening = false;
+ }
+
+ _ensure() {
+ if (this._recognition) return this._recognition;
+ const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
+ if (!SR) return null;
+ const r = new SR();
+ r.lang = this.language;
+ r.continuous = this.continuous;
+ r.interimResults = this.interimResults;
+ this._recognition = r;
+ return r;
+ }
+
+ async listen({ onInterim, onFinal } = {}) {
+ const r = this._ensure();
+ if (!r) throw new Error('SpeechRecognition unavailable in this browser');
+ return new Promise((resolve, reject) => {
+ let finalText = '';
+ r.onresult = (ev) => {
+ for (let i = ev.resultIndex; i < ev.results.length; i++) {
+ const res = ev.results[i];
+ const text = res[0].transcript;
+ if (res.isFinal) {
+ finalText += text;
+ onFinal?.(text);
+ } else {
+ onInterim?.(text);
+ }
+ }
+ };
+ r.onerror = (e) => { this._listening = false; reject(e.error); };
+ r.onend = () => { this._listening = false; resolve(finalText.trim()); };
+ this._listening = true;
+ try { r.start(); } catch (e) { this._listening = false; reject(e); }
+ });
+ }
+
+ stop() {
+ if (this._recognition && this._listening) this._recognition.stop();
+ }
+
+ get listening() { return this._listening; }
+}
+
+export function createTTS(config = {}) {
+ const provider = config.provider || 'browser';
+ if (provider === 'none') return null;
+ if (provider === 'browser') return new BrowserTTS(config);
+ throw new Error(`TTS provider "${provider}" not implemented yet`);
+}
+
+export function createSTT(config = {}) {
+ const provider = config.provider || 'browser';
+ if (provider === 'none') return null;
+ if (provider === 'browser') return new BrowserSTT(config);
+ throw new Error(`STT provider "${provider}" not implemented yet`);
+}
diff --git a/src/runtime/tools.js b/src/runtime/tools.js
new file mode 100644
index 000000000..f014a7b39
--- /dev/null
+++ b/src/runtime/tools.js
@@ -0,0 +1,118 @@
+// Built-in scene-tools — available to every agent without any skill installed.
+// See specs/AGENT_MANIFEST.md § Built-in tools.
+
+export const BUILTIN_TOOLS = [
+ {
+ name: 'wave',
+ description: 'Wave at the user. Use for greetings, farewells, or acknowledgments.',
+ input_schema: {
+ type: 'object',
+ properties: {
+ duration_ms: { type: 'integer', minimum: 500, maximum: 5000, default: 1500 },
+ },
+ },
+ },
+ {
+ name: 'lookAt',
+ description: 'Direct the agent\'s gaze toward a target.',
+ input_schema: {
+ type: 'object',
+ properties: {
+ target: {
+ type: 'string',
+ enum: ['user', 'camera', 'center'],
+ description: 'Where to look',
+ },
+ },
+ required: ['target'],
+ },
+ },
+ {
+ name: 'play_clip',
+ description: 'Play a named animation clip from the loaded body.',
+ input_schema: {
+ type: 'object',
+ properties: {
+ name: { type: 'string' },
+ loop: { type: 'boolean', default: false },
+ fade_ms: { type: 'integer', default: 200 },
+ },
+ required: ['name'],
+ },
+ },
+ {
+ name: 'setExpression',
+ description: 'Set facial expression via morph target preset.',
+ input_schema: {
+ type: 'object',
+ properties: {
+ preset: { type: 'string', enum: ['neutral', 'happy', 'sad', 'surprised', 'confused', 'focused'] },
+ intensity: { type: 'number', minimum: 0, maximum: 1, default: 1 },
+ },
+ required: ['preset'],
+ },
+ },
+ {
+ name: 'speak',
+ description: 'Say something out loud via TTS. Use this instead of plain text when voice is on.',
+ input_schema: {
+ type: 'object',
+ properties: { text: { type: 'string' } },
+ required: ['text'],
+ },
+ },
+ {
+ name: 'remember',
+ description: 'Save a durable memory about the user, a feedback rule, a project fact, or a reference.',
+ input_schema: {
+ type: 'object',
+ properties: {
+ key: { type: 'string', description: 'short snake_case filename, e.g. "user_role"' },
+ name: { type: 'string' },
+ description: { type: 'string' },
+ type: { type: 'string', enum: ['user', 'feedback', 'project', 'reference'] },
+ body: { type: 'string' },
+ },
+ required: ['key', 'name', 'description', 'type', 'body'],
+ },
+ },
+];
+
+export const BUILTIN_HANDLERS = {
+ async wave(args, ctx) {
+ const dur = args.duration_ms || 1500;
+ await ctx.viewer.playAnimationByHint?.('wave', { duration: dur });
+ ctx.memory.note('waved', { duration_ms: dur });
+ return { ok: true };
+ },
+
+ async lookAt(args, ctx) {
+ const target = args.target || 'user';
+ ctx.viewer.lookAt?.(target);
+ return { ok: true, target };
+ },
+
+ async play_clip(args, ctx) {
+ const { name, loop = false, fade_ms = 200 } = args;
+ const played = ctx.viewer.playClipByName?.(name, { loop, fade_ms });
+ if (!played) return { ok: false, error: `No clip named "${name}"` };
+ return { ok: true, name };
+ },
+
+ async setExpression(args, ctx) {
+ const { preset, intensity = 1 } = args;
+ ctx.viewer.setExpression?.(preset, intensity);
+ return { ok: true, preset };
+ },
+
+ async speak(args, ctx) {
+ await ctx.speak(args.text);
+ return { ok: true };
+ },
+
+ async remember(args, ctx) {
+ const { key, name, description, type, body } = args;
+ ctx.memory.write(key, { name, description, type, body });
+ return { ok: true, saved: key };
+ },
+};
diff --git a/src/viewer.js b/src/viewer.js
index f33d6bced..3297d8783 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -1,19 +1,13 @@
import {
- AmbientLight,
- AnimationMixer,
AxesHelper,
Box3,
Cache,
Color,
- DirectionalLight,
GridHelper,
- HemisphereLight,
LoaderUtils,
- LoadingManager,
PMREMGenerator,
PerspectiveCamera,
PointsMaterial,
- REVISION,
Scene,
SkeletonHelper,
Vector3,
@@ -23,11 +17,8 @@ import {
} from 'three';
import Stats from 'three/addons/libs/stats.module.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
-import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
-import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
-import { EXRLoader } from 'three/addons/loaders/EXRLoader.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { GUI } from 'dat.gui';
@@ -35,19 +26,19 @@ import { GUI } from 'dat.gui';
import { environments } from './environments.js';
import { createModelInfo } from './model-info.js';
import { buildAnnotations, renderAnnotationCanvas } from './annotations.js';
-
-const DEFAULT_CAMERA = '[default]';
-
-const MANAGER = new LoadingManager();
-const THREE_PATH = `https://unpkg.com/three@0.${REVISION}.x`;
-const DRACO_LOADER = new DRACOLoader(MANAGER).setDecoderPath(
- `${THREE_PATH}/examples/jsm/libs/draco/gltf/`,
-);
-const KTX2_LOADER = new KTX2Loader(MANAGER).setTranscoderPath(
- `${THREE_PATH}/examples/jsm/libs/basis/`,
-);
-
-const Preset = { ASSET_GENERATOR: 'assetgenerator' };
+import {
+ DEFAULT_CAMERA,
+ Preset,
+ MANAGER,
+ DRACO_LOADER,
+ KTX2_LOADER,
+ traverseMaterials,
+} from './viewer/internal.js';
+import { addLights, removeLights } from './viewer/lights.js';
+import { getCubeMapTexture } from './viewer/environment.js';
+import { takeScreenshot } from './viewer/screenshot.js';
+import { setClips, playAllClips } from './viewer/animation.js';
+import { AnimationManager } from './animation-manager.js';
Cache.enabled = true;
@@ -62,6 +53,10 @@ export class Viewer {
this.clips = [];
this.gui = null;
+ // External animation system (Mixamo-style)
+ this.animationManager = new AnimationManager();
+ this._animPanelEl = null;
+
this.state = {
environment:
options.preset === Preset.ASSET_GENERATOR
@@ -203,6 +198,10 @@ export class Viewer {
}
}
}
+ // External animation manager also drives the render loop
+ if (!animating && this.animationManager.currentAction) {
+ animating = true;
+ }
this._animating = animating;
}
@@ -228,6 +227,7 @@ export class Viewer {
this.controls.update();
this.stats.update();
if (this.mixer) this.mixer.update(dt);
+ this.animationManager.update(dt);
// Extension point for the AgentAvatar empathy tick and any other per-frame hooks
if (this._afterAnimateHooks) {
@@ -262,26 +262,7 @@ export class Viewer {
}
takeScreenshot() {
- // Render a fresh frame then capture via toBlob (avoids preserveDrawingBuffer overhead).
- this.renderer.render(this.scene, this.activeCamera);
- this.renderer.domElement.toBlob((blob) => {
- if (!blob) return;
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
- const url = URL.createObjectURL(blob);
- const link = document.createElement('a');
- link.download = `3d-screenshot-${timestamp}.png`;
- link.href = url;
- link.click();
- URL.revokeObjectURL(url);
- }, 'image/png');
- this.flashScreenshotFeedback();
- }
-
- flashScreenshotFeedback() {
- const overlay = document.createElement('div');
- overlay.className = 'screenshot-flash';
- this.el.appendChild(overlay);
- overlay.addEventListener('animationend', () => overlay.remove());
+ takeScreenshot(this);
}
resize() {
@@ -423,6 +404,10 @@ export class Viewer {
this.setClips(clips);
+ // Attach external animation manager to the new content
+ this.animationManager.attach(this.content);
+ this._setupAnimationPanel();
+
this.updateLights();
this.updateGUI();
this.updateEnvironment();
@@ -443,28 +428,12 @@ export class Viewer {
console.groupEnd();
}
- /**
- * @param {Array<THREE.AnimationClip} clips
- */
setClips(clips) {
- if (this.mixer) {
- this.mixer.stopAllAction();
- this.mixer.uncacheRoot(this.mixer.getRoot());
- this.mixer = null;
- }
-
- this.clips = clips;
- if (!clips.length) return;
-
- this.mixer = new AnimationMixer(this.content);
+ setClips(this, clips);
}
playAllClips() {
- this.clips.forEach((clip) => {
- this.mixer.clipAction(clip).reset().play();
- this.state.actionStates[clip.name] = true;
- });
- this.invalidate();
+ playAllClips(this);
}
/**
@@ -490,9 +459,9 @@ export class Viewer {
const lights = this.lights;
if (state.punctualLights && !lights.length) {
- this.addLights();
+ addLights(this);
} else if (!state.punctualLights && lights.length) {
- this.removeLights();
+ removeLights(this);
}
this.renderer.toneMapping = Number(state.toneMapping);
@@ -508,40 +477,12 @@ export class Viewer {
this.invalidate();
}
- addLights() {
- const state = this.state;
-
- if (this.options.preset === Preset.ASSET_GENERATOR) {
- const hemiLight = new HemisphereLight();
- hemiLight.name = 'hemi_light';
- this.scene.add(hemiLight);
- this.lights.push(hemiLight);
- return;
- }
-
- const light1 = new AmbientLight(state.ambientColor, state.ambientIntensity);
- light1.name = 'ambient_light';
- this.defaultCamera.add(light1);
-
- const light2 = new DirectionalLight(state.directColor, state.directIntensity);
- light2.position.set(0.5, 0, 0.866); // ~60º
- light2.name = 'main_light';
- this.defaultCamera.add(light2);
-
- this.lights.push(light1, light2);
- }
-
- removeLights() {
- this.lights.forEach((light) => light.parent.remove(light));
- this.lights.length = 0;
- }
-
updateEnvironment() {
const environment = environments.filter(
(entry) => entry.name === this.state.environment,
)[0];
- this.getCubeMapTexture(environment).then(({ envMap }) => {
+ getCubeMapTexture(this, environment).then(({ envMap }) => {
if (this._disposed || !this.scene) return;
this.scene.environment = envMap;
this.scene.background = this.state.transparentBg
@@ -551,39 +492,6 @@ export class Viewer {
});
}
- getCubeMapTexture(environment) {
- const { id, path } = environment;
-
- // neutral (THREE.RoomEnvironment)
- if (id === 'neutral') {
- return Promise.resolve({ envMap: this.neutralEnvironment });
- }
-
- // none
- if (id === '') {
- return Promise.resolve({ envMap: null });
- }
-
- return new Promise((resolve, reject) => {
- new EXRLoader().load(
- path,
- (texture) => {
- const envMap = this.pmremGenerator.fromEquirectangular(texture).texture;
- texture.dispose();
-
- if (this._loadedEnvironment && this._loadedEnvironment !== envMap) {
- this._loadedEnvironment.dispose();
- }
- this._loadedEnvironment = envMap;
-
- resolve({ envMap });
- },
- undefined,
- reject,
- );
- });
- }
-
updateDisplay() {
if (this.skeletonHelpers.length) {
this.skeletonHelpers.forEach((helper) => this.scene.remove(helper));
@@ -900,9 +808,148 @@ export class Viewer {
}
}
+ // ── External Animation Panel (Mixamo-style) ─────────────────────────────
+
+ /**
+ * Register a list of external animation definitions (name + URL).
+ * @param {Array<{name: string, url: string, label?: string, icon?: string, loop?: boolean}>} defs
+ */
+ setAnimationDefs(defs) {
+ this.animationManager.setAnimationDefs(defs);
+ if (this.content) this._setupAnimationPanel();
+ }
+
+ /**
+ * Create / rebuild the animation selector panel.
+ * @private
+ */
+ _setupAnimationPanel() {
+ // Remove existing panel
+ if (this._animPanelEl) {
+ this._animPanelEl.remove();
+ this._animPanelEl = null;
+ }
+
+ const defs = this.animationManager.getAnimationDefs();
+ if (defs.length === 0) return;
+
+ // Check model has a skeleton (no point showing anim panel for static meshes)
+ let hasSkeleton = false;
+ this.content.traverse((node) => {
+ if (node.isSkinnedMesh) hasSkeleton = true;
+ });
+ if (!hasSkeleton) return;
+
+ // Create panel container
+ const panel = document.createElement('div');
+ panel.className = 'anim-panel';
+ panel.innerHTML =
+ '<div class="anim-panel__header">' +
+ '<span class="anim-panel__title">Animations</span>' +
+ '<button class="anim-panel__stop" title="Stop all">⏹</button>' +
+ '</div>' +
+ '<div class="anim-panel__grid"></div>';
+ this.el.appendChild(panel);
+ this._animPanelEl = panel;
+
+ // Render buttons
+ this._renderAnimButtons();
+
+ // Load all animations in background
+ this.animationManager.loadAll().then(() => {
+ this._renderAnimButtons();
+ // Auto-play the first animation if nothing is playing
+ if (!this.animationManager.currentName && defs.length > 0) {
+ const firstName = defs[0].name;
+ if (this.animationManager.isLoaded(firstName)) {
+ this.animationManager.play(firstName);
+ this._renderAnimButtons();
+ this.invalidate();
+ this._recomputeAnimating();
+ this._updateRenderLoop();
+ }
+ }
+ });
+
+ // Stop button
+ panel.querySelector('.anim-panel__stop').addEventListener('click', () => {
+ this.animationManager.stopAll();
+ this._renderAnimButtons();
+ this.invalidate();
+ });
+
+ // Listen for changes from AnimationManager
+ this.animationManager.onChange = () => {
+ this._renderAnimButtons();
+ };
+ }
+
+ /**
+ * Render / re-render animation buttons in the panel.
+ * @private
+ */
+ _renderAnimButtons() {
+ if (!this._animPanelEl) return;
+
+ const grid = this._animPanelEl.querySelector('.anim-panel__grid');
+ const defs = this.animationManager.getAnimationDefs();
+ const activeName = this.animationManager.currentName;
+
+ const ICONS = {
+ idle: '🧍', breathing: '🧍', standing: '🧍',
+ walking: '🚶', walk: '🚶',
+ running: '🏃', run: '🏃',
+ waving: '👋', wave: '👋',
+ dancing: '💃', dance: '💃',
+ sitting: '🪑', sit: '🪑',
+ jumping: '🦘', jump: '🦘',
+ talking: '🗣️', talk: '🗣️',
+ clapping: '👏', clap: '👏',
+ punching: '👊', punch: '👊',
+ kicking: '🦵', kick: '🦵',
+ };
+
+ grid.innerHTML = defs.map((def) => {
+ const loaded = this.animationManager.isLoaded(def.name);
+ const isActive = activeName === def.name;
+ const icon = def.icon || ICONS[def.name.toLowerCase()] || '▶';
+ const label = def.label || def.name.charAt(0).toUpperCase() + def.name.slice(1);
+ return (
+ '<button class="anim-btn' +
+ (isActive ? ' anim-btn--active' : '') +
+ (loaded ? '' : ' anim-btn--loading') +
+ '" data-anim="' + def.name + '"' +
+ ' title="' + label + '"' +
+ (loaded ? '' : ' disabled') +
+ '>' +
+ '<span class="anim-btn__icon">' + icon + '</span>' +
+ '<span class="anim-btn__label">' + label + '</span>' +
+ '</button>'
+ );
+ }).join('');
+
+ // Bind click events
+ grid.querySelectorAll('.anim-btn:not([disabled])').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const name = btn.dataset.anim;
+ this.animationManager.crossfadeTo(name);
+ this.invalidate();
+ this._recomputeAnimating();
+ this._updateRenderLoop();
+ });
+ });
+ }
+
clear() {
if (!this.content) return;
+ // Detach external animation manager
+ this.animationManager.detach();
+ if (this._animPanelEl) {
+ this._animPanelEl.remove();
+ this._animPanelEl = null;
+ }
+
if (this.modelInfo) {
this.modelInfo.remove();
this.modelInfo = null;
@@ -961,6 +1008,13 @@ export class Viewer {
}
this.clips = [];
+ // Dispose external animation system
+ this.animationManager.dispose();
+ if (this._animPanelEl) {
+ this._animPanelEl.remove();
+ this._animPanelEl = null;
+ }
+
if (this.skeletonHelpers.length) {
this.skeletonHelpers.forEach((helper) => {
this.scene.remove(helper);
@@ -1060,17 +1114,3 @@ export class Viewer {
this._afterAnimateHooks = null;
}
}
-
-function traverseMaterials(object, callback) {
- const seen = new Set();
- object.traverse((node) => {
- if (!node.geometry) return;
- const materials = Array.isArray(node.material) ? node.material : [node.material];
- materials.forEach((mat) => {
- if (mat && !seen.has(mat.uuid)) {
- seen.add(mat.uuid);
- callback(mat);
- }
- });
- });
-}
diff --git a/src/viewer/animation.js b/src/viewer/animation.js
new file mode 100644
index 000000000..d01ad2bd0
--- /dev/null
+++ b/src/viewer/animation.js
@@ -0,0 +1,22 @@
+import { AnimationMixer } from 'three';
+
+export function setClips(viewer, clips) {
+ if (viewer.mixer) {
+ viewer.mixer.stopAllAction();
+ viewer.mixer.uncacheRoot(viewer.mixer.getRoot());
+ viewer.mixer = null;
+ }
+
+ viewer.clips = clips;
+ if (!clips.length) return;
+
+ viewer.mixer = new AnimationMixer(viewer.content);
+}
+
+export function playAllClips(viewer) {
+ viewer.clips.forEach((clip) => {
+ viewer.mixer.clipAction(clip).reset().play();
+ viewer.state.actionStates[clip.name] = true;
+ });
+ viewer.invalidate();
+}
diff --git a/src/viewer/environment.js b/src/viewer/environment.js
new file mode 100644
index 000000000..3925b9c71
--- /dev/null
+++ b/src/viewer/environment.js
@@ -0,0 +1,34 @@
+import { EXRLoader } from 'three/addons/loaders/EXRLoader.js';
+
+export function getCubeMapTexture(viewer, environment) {
+ const { id, path } = environment;
+
+ // neutral (THREE.RoomEnvironment)
+ if (id === 'neutral') {
+ return Promise.resolve({ envMap: viewer.neutralEnvironment });
+ }
+
+ // none
+ if (id === '') {
+ return Promise.resolve({ envMap: null });
+ }
+
+ return new Promise((resolve, reject) => {
+ new EXRLoader().load(
+ path,
+ (texture) => {
+ const envMap = viewer.pmremGenerator.fromEquirectangular(texture).texture;
+ texture.dispose();
+
+ if (viewer._loadedEnvironment && viewer._loadedEnvironment !== envMap) {
+ viewer._loadedEnvironment.dispose();
+ }
+ viewer._loadedEnvironment = envMap;
+
+ resolve({ envMap });
+ },
+ undefined,
+ reject,
+ );
+ });
+}
diff --git a/src/viewer/internal.js b/src/viewer/internal.js
new file mode 100644
index 000000000..76b7029d7
--- /dev/null
+++ b/src/viewer/internal.js
@@ -0,0 +1,29 @@
+import { LoadingManager, REVISION } from 'three';
+import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
+import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';
+
+export const DEFAULT_CAMERA = '[default]';
+export const Preset = { ASSET_GENERATOR: 'assetgenerator' };
+
+export const MANAGER = new LoadingManager();
+const THREE_PATH = `https://unpkg.com/three@0.${REVISION}.x`;
+export const DRACO_LOADER = new DRACOLoader(MANAGER).setDecoderPath(
+ `${THREE_PATH}/examples/jsm/libs/draco/gltf/`,
+);
+export const KTX2_LOADER = new KTX2Loader(MANAGER).setTranscoderPath(
+ `${THREE_PATH}/examples/jsm/libs/basis/`,
+);
+
+export function traverseMaterials(object, callback) {
+ const seen = new Set();
+ object.traverse((node) => {
+ if (!node.geometry) return;
+ const materials = Array.isArray(node.material) ? node.material : [node.material];
+ materials.forEach((mat) => {
+ if (mat && !seen.has(mat.uuid)) {
+ seen.add(mat.uuid);
+ callback(mat);
+ }
+ });
+ });
+}
diff --git a/src/viewer/lights.js b/src/viewer/lights.js
new file mode 100644
index 000000000..98a32f2ef
--- /dev/null
+++ b/src/viewer/lights.js
@@ -0,0 +1,30 @@
+import { AmbientLight, DirectionalLight, HemisphereLight } from 'three';
+import { Preset } from './internal.js';
+
+export function addLights(viewer) {
+ const { state, options } = viewer;
+
+ if (options.preset === Preset.ASSET_GENERATOR) {
+ const hemiLight = new HemisphereLight();
+ hemiLight.name = 'hemi_light';
+ viewer.scene.add(hemiLight);
+ viewer.lights.push(hemiLight);
+ return;
+ }
+
+ const light1 = new AmbientLight(state.ambientColor, state.ambientIntensity);
+ light1.name = 'ambient_light';
+ viewer.defaultCamera.add(light1);
+
+ const light2 = new DirectionalLight(state.directColor, state.directIntensity);
+ light2.position.set(0.5, 0, 0.866); // ~60º
+ light2.name = 'main_light';
+ viewer.defaultCamera.add(light2);
+
+ viewer.lights.push(light1, light2);
+}
+
+export function removeLights(viewer) {
+ viewer.lights.forEach((light) => light.parent.remove(light));
+ viewer.lights.length = 0;
+}
diff --git a/src/viewer/screenshot.js b/src/viewer/screenshot.js
new file mode 100644
index 000000000..b9ff956f1
--- /dev/null
+++ b/src/viewer/screenshot.js
@@ -0,0 +1,22 @@
+export function takeScreenshot(viewer) {
+ // Render a fresh frame then capture via toBlob (avoids preserveDrawingBuffer overhead).
+ viewer.renderer.render(viewer.scene, viewer.activeCamera);
+ viewer.renderer.domElement.toBlob((blob) => {
+ if (!blob) return;
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.download = `3d-screenshot-${timestamp}.png`;
+ link.href = url;
+ link.click();
+ URL.revokeObjectURL(url);
+ }, 'image/png');
+ flashScreenshotFeedback(viewer);
+}
+
+export function flashScreenshotFeedback(viewer) {
+ const overlay = document.createElement('div');
+ overlay.className = 'screenshot-flash';
+ viewer.el.appendChild(overlay);
+ overlay.addEventListener('animationend', () => overlay.remove());
+}
diff --git a/style.css b/style.css
index 6dadf2947..080e7c70e 100644
--- a/style.css
+++ b/style.css
@@ -1324,3 +1324,963 @@ footer .separator {
padding: var(--space-xs) var(--space-md);
}
}
+
+/* ============================================================================
+ Agent Presence System
+ The visual layer that makes agents real — not just JSON.
+ ============================================================================ */
+
+/* ── Sidebar layout ────────────────────────────────────────────────────────── */
+
+.agent-presence-sidebar {
+ position: fixed;
+ top: calc(var(--header-h) + var(--space-md));
+ left: var(--space-md);
+ width: 220px;
+ z-index: 50;
+ pointer-events: none;
+}
+
+.agent-home-panel {
+ background: rgba(10, 10, 16, 0.88);
+ border: 1px solid rgba(255, 255, 255, 0.07);
+ border-radius: var(--radius-lg);
+ backdrop-filter: blur(12px);
+ -webkit-backdrop-filter: blur(12px);
+ overflow: hidden;
+ pointer-events: all;
+ display: flex;
+ flex-direction: column;
+ gap: 0;
+}
+
+/* ── Identity card ─────────────────────────────────────────────────────────── */
+
+.agent-home-identity {
+ display: flex;
+ align-items: center;
+ gap: var(--space-sm);
+ padding: var(--space-sm) var(--space-sm);
+}
+
+.agent-home-avatar-ring {
+ width: 36px;
+ height: 36px;
+ border-radius: 50%;
+ border: 2px solid rgba(255,255,255,0.15);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ transition: border-color 0.6s ease, box-shadow 0.6s ease;
+}
+
+/* Emotion ring colours */
+.agent-home-avatar-ring[data-emotion="celebration"] {
+ border-color: rgba(134, 239, 172, 0.6);
+ box-shadow: 0 0 10px rgba(134, 239, 172, 0.25);
+}
+.agent-home-avatar-ring[data-emotion="concern"] {
+ border-color: rgba(252, 165, 89, 0.6);
+ box-shadow: 0 0 10px rgba(252, 165, 89, 0.2);
+}
+.agent-home-avatar-ring[data-emotion="curiosity"] {
+ border-color: rgba(147, 197, 253, 0.6);
+ box-shadow: 0 0 10px rgba(147, 197, 253, 0.2);
+}
+.agent-home-avatar-ring[data-emotion="empathy"] {
+ border-color: rgba(216, 180, 254, 0.6);
+ box-shadow: 0 0 10px rgba(216, 180, 254, 0.2);
+}
+.agent-home-avatar-ring[data-emotion="patience"] {
+ border-color: rgba(209, 213, 219, 0.4);
+}
+
+.agent-home-avatar-inner {
+ width: 28px;
+ height: 28px;
+ border-radius: 50%;
+ background: rgba(255,255,255,0.06);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 14px;
+}
+
+.agent-home-info {
+ flex: 1;
+ min-width: 0;
+}
+
+.agent-home-name {
+ font-size: var(--text-sm);
+ font-weight: 500;
+ color: #e5e5e5;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.agent-home-status {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ font-size: var(--text-xs);
+ color: rgba(255,255,255,0.4);
+ margin-top: 1px;
+}
+
+.agent-home-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: rgba(255,255,255,0.3);
+ flex-shrink: 0;
+}
+
+.agent-home-dot.online {
+ background: #4ade80;
+ box-shadow: 0 0 4px rgba(74, 222, 128, 0.5);
+ animation: agent-dot-pulse 2.5s ease infinite;
+}
+
+@keyframes agent-dot-pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.5; }
+}
+
+#agent-home-emotion-label {
+ transition: opacity 0.15s ease;
+}
+
+.agent-home-address {
+ font-size: 9px;
+ color: rgba(255,255,255,0.25);
+ font-family: monospace;
+ margin-top: 2px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.agent-home-actions {
+ display: flex;
+ align-items: center;
+ gap: var(--space-xs);
+ flex-shrink: 0;
+}
+
+.agent-home-btn {
+ background: none;
+ border: 1px solid rgba(255,255,255,0.1);
+ border-radius: var(--radius-sm);
+ color: rgba(255,255,255,0.4);
+ width: 24px;
+ height: 24px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ transition: color 0.2s, border-color 0.2s;
+ padding: 0;
+ font-size: var(--text-xs);
+}
+
+.agent-home-btn:hover {
+ color: rgba(255,255,255,0.8);
+ border-color: rgba(255,255,255,0.3);
+}
+
+.agent-home-badge {
+ font-size: 9px;
+ padding: 2px 5px;
+ border-radius: 999px;
+ display: flex;
+ align-items: center;
+ gap: 3px;
+ white-space: nowrap;
+}
+
+.agent-home-badge.erc8004 {
+ background: rgba(134, 239, 172, 0.1);
+ color: #4ade80;
+ border: 1px solid rgba(74, 222, 128, 0.2);
+}
+
+/* ── Skills strip ──────────────────────────────────────────────────────────── */
+
+.agent-home-skills-strip {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ padding: var(--space-xs) var(--space-sm);
+ border-top: 1px solid rgba(255,255,255,0.05);
+}
+
+.agent-skill-chip {
+ font-size: 9px;
+ padding: 2px 6px;
+ border-radius: 999px;
+ background: rgba(255,255,255,0.06);
+ color: rgba(255,255,255,0.45);
+ border: 1px solid rgba(255,255,255,0.08);
+ cursor: default;
+ transition: background 0.15s, color 0.15s;
+ white-space: nowrap;
+}
+
+.agent-skill-chip:hover {
+ background: rgba(255,255,255,0.1);
+ color: rgba(255,255,255,0.75);
+}
+
+/* ── Memory bar ────────────────────────────────────────────────────────────── */
+
+.agent-home-memory-bar {
+ display: flex;
+ align-items: center;
+ gap: var(--space-xs);
+ padding: var(--space-xs) var(--space-sm);
+ border-top: 1px solid rgba(255,255,255,0.05);
+ flex-wrap: wrap;
+}
+
+.agent-mem-chip {
+ font-size: 9px;
+ color: rgba(255,255,255,0.4);
+ cursor: default;
+}
+
+.agent-mem-total {
+ font-size: 9px;
+ color: rgba(255,255,255,0.2);
+ margin-left: auto;
+}
+
+.agent-mem-empty {
+ font-size: 9px;
+ color: rgba(255,255,255,0.2);
+ font-style: italic;
+}
+
+/* ── Action timeline ───────────────────────────────────────────────────────── */
+
+.agent-home-timeline {
+ max-height: 140px;
+ overflow-y: auto;
+ border-top: 1px solid rgba(255,255,255,0.05);
+ scrollbar-width: thin;
+ scrollbar-color: rgba(255,255,255,0.1) transparent;
+}
+
+.agent-timeline-empty {
+ font-size: 9px;
+ color: rgba(255,255,255,0.2);
+ font-style: italic;
+ padding: var(--space-xs) var(--space-sm);
+ text-align: center;
+}
+
+.agent-timeline-item {
+ display: flex;
+ align-items: flex-start;
+ gap: var(--space-xs);
+ padding: 4px var(--space-sm);
+ border-bottom: 1px solid rgba(255,255,255,0.03);
+ transition: background 0.15s;
+}
+
+.agent-timeline-item:hover {
+ background: rgba(255,255,255,0.03);
+}
+
+.agent-timeline-icon {
+ font-size: 10px;
+ flex-shrink: 0;
+ margin-top: 1px;
+ width: 14px;
+ text-align: center;
+}
+
+.agent-timeline-text {
+ font-size: 9px;
+ color: rgba(255,255,255,0.5);
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.agent-timeline-time {
+ font-size: 9px;
+ color: rgba(255,255,255,0.2);
+ flex-shrink: 0;
+ white-space: nowrap;
+}
+
+@keyframes agent-timeline-in {
+ from { opacity: 0; transform: translateY(-4px); }
+ to { opacity: 1; transform: translateY(0); }
+}
+
+/* ── NichAgent updates — emotion dot in header ─────────────────────────────── */
+
+.nich-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: var(--space-sm) var(--space-md);
+ border-bottom: 1px solid rgba(255,255,255,0.08);
+ background: rgba(255,255,255,0.03);
+}
+
+.nich-header-right {
+ display: flex;
+ align-items: center;
+ gap: var(--space-sm);
+}
+
+.nich-emotion-dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: rgba(255,255,255,0.2);
+ transition: background 0.4s ease, box-shadow 0.4s ease;
+}
+
+.nich-toggle-label {
+ font-size: 10px;
+ margin-top: 3px;
+ display: block;
+ color: rgba(255,255,255,0.5);
+}
+
+.nich-message.status {
+ font-size: var(--text-xs);
+ color: rgba(255,255,255,0.3);
+ font-style: italic;
+ padding: 2px var(--space-xs);
+}
+
+.nich-mic-hint {
+ font-size: var(--text-xs);
+ color: rgba(255,255,255,0.25);
+}
+
+.nich-mic-row {
+ display: flex;
+ align-items: center;
+ gap: var(--space-sm);
+ padding: var(--space-xs) var(--space-md);
+ border-top: 1px solid rgba(255,255,255,0.05);
+}
+
+/* ── Responsive — hide sidebar on narrow viewports ─────────────────────────── */
+
+@media screen and (max-width: 900px) {
+ .agent-presence-sidebar {
+ display: none;
+ }
+}
+
+/* ── Agent Home standalone page ─────────────────────────────────────────────── */
+
+.agent-home-page {
+ min-height: 100vh;
+ background: #000;
+ color: #e0e0e0;
+ font-family: 'Inter', sans-serif;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding: var(--space-2xl) var(--space-md);
+}
+
+.agent-home-page-card {
+ width: 100%;
+ max-width: 480px;
+ background: rgba(15, 15, 22, 0.95);
+ border: 1px solid rgba(255,255,255,0.08);
+ border-radius: 12px;
+ overflow: hidden;
+}
+
+.agent-home-page-card .agent-home-panel {
+ background: transparent;
+ border: none;
+ border-radius: 0;
+}
+
+.agent-home-page-card .agent-home-timeline {
+ max-height: 400px;
+}
+
+/******************************************************************************
+ * Animation Panel (Mixamo-style action selector)
+ */
+
+.anim-panel {
+ position: absolute;
+ bottom: var(--space-lg);
+ left: 50%;
+ transform: translateX(-50%);
+ z-index: 20;
+ background: rgba(10, 10, 16, 0.88);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: var(--radius-lg);
+ backdrop-filter: blur(16px);
+ -webkit-backdrop-filter: blur(16px);
+ padding: var(--space-xs) var(--space-sm);
+ max-width: 90vw;
+ animation: anim-panel-in 0.3s ease;
+}
+
+@keyframes anim-panel-in {
+ from { opacity: 0; transform: translateX(-50%) translateY(12px); }
+ to { opacity: 1; transform: translateX(-50%) translateY(0); }
+}
+
+.anim-panel--empty {
+ display: none;
+}
+
+.anim-panel__header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: var(--space-3xs) var(--space-xs);
+ margin-bottom: var(--space-3xs);
+}
+
+.anim-panel__title {
+ font-size: var(--text-xs);
+ color: rgba(255, 255, 255, 0.4);
+ font-weight: 500;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+}
+
+.anim-panel__stop {
+ background: none;
+ border: none;
+ color: rgba(255, 255, 255, 0.3);
+ font-size: var(--text-sm);
+ cursor: pointer;
+ padding: 2px 6px;
+ border-radius: var(--radius-sm);
+ transition: color 0.2s, background 0.2s;
+ line-height: 1;
+}
+
+.anim-panel__stop:hover {
+ color: #f87171;
+ background: rgba(248, 113, 113, 0.1);
+}
+
+.anim-panel__grid {
+ display: flex;
+ gap: var(--space-xs);
+ overflow-x: auto;
+ scrollbar-width: thin;
+ scrollbar-color: rgba(255, 255, 255, 0.1) transparent;
+ padding-bottom: 2px;
+}
+
+.anim-btn {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 3px;
+ padding: var(--space-xs) var(--space-sm);
+ min-width: 64px;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: var(--radius-md);
+ color: rgba(255, 255, 255, 0.6);
+ font-family: inherit;
+ font-size: var(--text-xs);
+ cursor: pointer;
+ transition: all 0.2s ease;
+ flex-shrink: 0;
+}
+
+.anim-btn:hover:not(:disabled) {
+ background: rgba(255, 255, 255, 0.1);
+ border-color: rgba(255, 255, 255, 0.2);
+ color: #fff;
+}
+
+.anim-btn--active {
+ background: rgba(123, 47, 247, 0.2);
+ border-color: rgba(123, 47, 247, 0.5);
+ color: #fff;
+ box-shadow: 0 0 12px rgba(123, 47, 247, 0.15);
+}
+
+.anim-btn--active:hover {
+ background: rgba(123, 47, 247, 0.3);
+}
+
+.anim-btn--loading {
+ opacity: 0.35;
+ cursor: wait;
+}
+
+.anim-btn__icon {
+ font-size: 1.3rem;
+ line-height: 1;
+}
+
+.anim-btn__label {
+ font-size: 9px;
+ font-weight: 500;
+ letter-spacing: 0.03em;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 72px;
+}
+
+@media screen and (max-width: 700px) {
+ .anim-panel {
+ bottom: var(--space-sm);
+ padding: var(--space-3xs) var(--space-xs);
+ max-width: 95vw;
+ }
+
+ .anim-btn {
+ min-width: 52px;
+ padding: var(--space-3xs) var(--space-xs);
+ }
+
+ .anim-btn__icon {
+ font-size: 1.1rem;
+ }
+
+ .anim-btn__label {
+ font-size: 8px;
+ }
+}
+
+/******************************************************************************
+ * Editor — Scene Explorer side panel, Texture Inspector, Texture Lightbox
+ * All dark-themed to match the existing viewer chrome.
+ */
+
+.scene-explorer {
+ position: absolute;
+ top: var(--space-sm);
+ left: var(--space-sm);
+ width: 320px;
+ max-height: calc(100% - var(--space-lg));
+ background: rgba(20, 20, 28, 0.96);
+ color: #e0e0e0;
+ border: 1px solid #2a2a36;
+ border-radius: var(--radius-md);
+ box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
+ display: flex;
+ flex-direction: column;
+ font-size: var(--text-sm);
+ z-index: 40;
+ backdrop-filter: blur(8px);
+ overflow: hidden;
+}
+.scene-explorer.hidden { display: none; }
+
+.scene-explorer__header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: var(--space-sm) var(--space-md);
+ border-bottom: 1px solid #2a2a36;
+ background: #0f0f16;
+}
+.scene-explorer__title {
+ font-weight: 600;
+ font-size: var(--text-sm);
+ letter-spacing: 0.02em;
+ text-transform: uppercase;
+ color: #b4a4ff;
+}
+.scene-explorer__close {
+ background: none;
+ border: none;
+ color: #aaa;
+ font-size: 18px;
+ line-height: 1;
+ padding: 2px 8px;
+ cursor: pointer;
+ border-radius: 4px;
+}
+.scene-explorer__close:hover { background: #2a2a36; color: #fff; }
+
+.scene-explorer__search {
+ margin: var(--space-xs) var(--space-sm);
+ background: #0b0b12;
+ border: 1px solid #2a2a36;
+ color: #ddd;
+ padding: 6px 10px;
+ border-radius: 4px;
+ font-size: var(--text-sm);
+ outline: none;
+}
+.scene-explorer__search:focus { border-color: #5e4fff; }
+
+.scene-explorer__hint {
+ padding: 2px var(--space-sm) var(--space-xs);
+ color: #666;
+ font-size: 10px;
+ font-family: monospace;
+}
+
+.scene-explorer__tree {
+ flex: 1;
+ overflow-y: auto;
+ padding: var(--space-2xs) var(--space-2xs);
+ max-height: 40vh;
+ border-bottom: 1px solid #2a2a36;
+}
+.scene-explorer__inspector {
+ overflow-y: auto;
+ padding: var(--space-sm);
+ max-height: 40vh;
+ background: #0c0c14;
+}
+.scene-explorer__empty {
+ color: #666;
+ font-size: var(--text-xs);
+ padding: var(--space-sm);
+ text-align: center;
+}
+
+.scene-node { }
+.scene-node__row {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 3px 4px;
+ cursor: pointer;
+ border-radius: 3px;
+ line-height: 1.4;
+ user-select: none;
+}
+.scene-node__row:hover { background: #1a1a26; }
+.scene-node__row.selected {
+ background: #2a1f5a;
+ color: #fff;
+}
+.scene-node__expander {
+ display: inline-block;
+ width: 12px;
+ color: #888;
+ text-align: center;
+ font-size: 10px;
+ flex-shrink: 0;
+}
+.scene-node__icon { flex-shrink: 0; font-size: 12px; }
+.scene-node__label {
+ flex: 1;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font-size: 12px;
+}
+.scene-node__visibility {
+ background: none;
+ border: none;
+ color: #888;
+ font-size: 10px;
+ cursor: pointer;
+ padding: 0 4px;
+ flex-shrink: 0;
+}
+.scene-node__visibility:hover { color: #fff; }
+
+.scene-node__children { display: none; }
+.scene-node__children.open { display: block; }
+.scene-node.filtered-out { display: none; }
+
+.inspector__title {
+ font-size: var(--text-base);
+ font-weight: 600;
+ color: #fff;
+ margin-bottom: 2px;
+}
+.inspector__sub {
+ color: #666;
+ font-size: 10px;
+ font-family: monospace;
+ margin-bottom: var(--space-xs);
+}
+.inspector__section {
+ margin-top: var(--space-sm);
+ margin-bottom: var(--space-2xs);
+ font-size: 10px;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: #888;
+ border-bottom: 1px solid #22222e;
+ padding-bottom: 2px;
+}
+.inspector__row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-xs);
+ padding: 2px 0;
+ font-size: 11px;
+}
+.inspector__label { color: #888; flex-shrink: 0; min-width: 40px; }
+.inspector__value {
+ color: #ccc;
+ font-family: monospace;
+ text-align: right;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.vec3-row .vec3 {
+ display: flex;
+ gap: 2px;
+}
+.vec3-row input {
+ width: 52px;
+ background: #0b0b12;
+ border: 1px solid #2a2a36;
+ color: #ccc;
+ padding: 2px 4px;
+ border-radius: 3px;
+ font-size: 10px;
+ font-family: monospace;
+ outline: none;
+}
+.vec3-row input:focus { border-color: #5e4fff; }
+
+.inspector__actions {
+ display: flex;
+ gap: var(--space-2xs);
+ margin-top: var(--space-2xs);
+ flex-wrap: wrap;
+}
+.inspector__actions button {
+ background: #22222e;
+ border: 1px solid #33334a;
+ color: #ccc;
+ padding: 4px 8px;
+ border-radius: 3px;
+ font-size: 10px;
+ cursor: pointer;
+}
+.inspector__actions button:hover { background: #2e2e40; color: #fff; }
+
+/* Texture Inspector modal */
+.texture-inspector {
+ position: fixed;
+ top: 80px;
+ right: 20px;
+ width: min(560px, calc(100vw - 40px));
+ max-height: calc(100vh - 100px);
+ background: rgba(20, 20, 28, 0.98);
+ border: 1px solid #2a2a36;
+ border-radius: var(--radius-md);
+ box-shadow: 0 15px 60px rgba(0, 0, 0, 0.6);
+ display: flex;
+ flex-direction: column;
+ z-index: 9998;
+ color: #e0e0e0;
+ overflow: hidden;
+}
+.texture-inspector__header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: var(--space-sm) var(--space-md);
+ border-bottom: 1px solid #2a2a36;
+ background: #0f0f16;
+}
+.texture-inspector__title {
+ font-weight: 600;
+ font-size: var(--text-sm);
+ color: #b4a4ff;
+ text-transform: uppercase;
+ letter-spacing: 0.02em;
+}
+.texture-inspector__close {
+ background: none;
+ border: none;
+ color: #aaa;
+ font-size: 18px;
+ cursor: pointer;
+ padding: 2px 8px;
+ border-radius: 4px;
+}
+.texture-inspector__close:hover { background: #2a2a36; color: #fff; }
+
+.texture-inspector__grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
+ gap: var(--space-sm);
+ padding: var(--space-sm);
+ overflow-y: auto;
+}
+
+.texture-card {
+ background: #0c0c14;
+ border: 1px solid #22222e;
+ border-radius: var(--radius-sm);
+ padding: var(--space-xs);
+ cursor: pointer;
+ transition: border-color 0.15s, transform 0.15s;
+}
+.texture-card:hover {
+ border-color: #5e4fff;
+ transform: translateY(-1px);
+}
+.texture-card__thumb {
+ width: 100%;
+ aspect-ratio: 1;
+ background: #000
+ url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="8" height="8" fill="%23333"/><rect x="8" y="8" width="8" height="8" fill="%23333"/></svg>') repeat;
+ image-rendering: pixelated;
+ border-radius: 3px;
+ display: block;
+}
+.texture-card__info { margin-top: var(--space-2xs); }
+.texture-card__name {
+ font-size: 11px;
+ font-weight: 500;
+ color: #ddd;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.texture-card__meta {
+ font-size: 10px;
+ color: #888;
+ font-family: monospace;
+}
+.texture-card__mats {
+ font-size: 10px;
+ color: #666;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ margin-top: 2px;
+}
+
+/* Texture Lightbox (full preview with channel toggles) */
+.texture-lightbox {
+ position: fixed;
+ inset: 0;
+ background: rgba(5, 5, 10, 0.92);
+ backdrop-filter: blur(4px);
+ z-index: 9999;
+ display: flex;
+ flex-direction: column;
+}
+.texture-lightbox__bar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: var(--space-sm) var(--space-md);
+ background: #0b0b12;
+ border-bottom: 1px solid #2a2a36;
+ gap: var(--space-md);
+ flex-wrap: wrap;
+}
+.texture-lightbox__meta {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+.texture-lightbox__title {
+ font-weight: 600;
+ font-size: var(--text-sm);
+ color: #fff;
+}
+.texture-lightbox__dim {
+ font-family: monospace;
+ font-size: 10px;
+ color: #888;
+}
+.texture-lightbox__channels {
+ display: flex;
+ gap: 2px;
+}
+.texture-lightbox__channels button {
+ background: #22222e;
+ border: 1px solid #33334a;
+ color: #aaa;
+ padding: 4px 10px;
+ border-radius: 3px;
+ font-size: 11px;
+ font-family: monospace;
+ cursor: pointer;
+ min-width: 32px;
+}
+.texture-lightbox__channels button:hover { background: #2e2e40; color: #fff; }
+.texture-lightbox__channels button.active {
+ background: #5e4fff;
+ border-color: #7262ff;
+ color: #fff;
+}
+.texture-lightbox__close {
+ background: none;
+ border: none;
+ color: #aaa;
+ font-size: 22px;
+ cursor: pointer;
+ padding: 2px 10px;
+ border-radius: 4px;
+}
+.texture-lightbox__close:hover { background: #2a2a36; color: #fff; }
+.texture-lightbox__stage {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow: auto;
+ padding: var(--space-md);
+ background:
+ linear-gradient(45deg, #1a1a22 25%, transparent 25%),
+ linear-gradient(-45deg, #1a1a22 25%, transparent 25%),
+ linear-gradient(45deg, transparent 75%, #1a1a22 75%),
+ linear-gradient(-45deg, transparent 75%, #1a1a22 75%);
+ background-size: 20px 20px;
+ background-position: 0 0, 0 10px, 10px -10px, 10px 0;
+}
+.texture-lightbox__canvas {
+ max-width: 100%;
+ max-height: 100%;
+ object-fit: contain;
+ image-rendering: pixelated;
+ border: 1px solid #2a2a36;
+ background: #000;
+}
+.texture-lightbox__footer {
+ padding: var(--space-xs) var(--space-md);
+ background: #0b0b12;
+ border-top: 1px solid #2a2a36;
+ color: #888;
+ font-size: 11px;
+ font-family: monospace;
+}
+
+@media (max-width: 700px) {
+ .scene-explorer {
+ width: calc(100vw - var(--space-md));
+ max-height: calc(100vh - var(--space-xl));
+ top: var(--space-xs);
+ left: var(--space-xs);
+ right: var(--space-xs);
+ }
+ .texture-inspector {
+ top: var(--space-xs);
+ right: var(--space-xs);
+ left: var(--space-xs);
+ width: auto;
+ max-height: calc(100vh - var(--space-lg));
+ }
+ .texture-lightbox__bar { padding: var(--space-xs); gap: var(--space-xs); }
+}
diff --git a/vercel.json b/vercel.json
index 85e9dd0af..00e334ebd 100644
--- a/vercel.json
+++ b/vercel.json
@@ -18,6 +18,15 @@
{ "src": "/dashboard/", "dest": "/public/dashboard/index.html" },
{ "src": "/dashboard/(.*)", "dest": "/public/dashboard/$1" },
+ { "src": "/api/agents/me", "dest": "/api/agents" },
+ { "src": "/api/agents/([^/]+)/wallet", "dest": "/api/agents/[id]" },
+ { "src": "/api/agents/([^/]+)", "dest": "/api/agents/[id]" },
+ { "src": "/api/agents", "dest": "/api/agents" },
+ { "src": "/api/agent-actions", "dest": "/api/agent-actions" },
+ { "src": "/api/agent-memory/([^/]+)", "dest": "/api/agent-memory" },
+ { "src": "/api/agent-memory", "dest": "/api/agent-memory" },
+ { "src": "/agent/([^/]+)", "dest": "/public/agent/index.html" },
+ { "src": "/agent", "dest": "/public/agent/index.html" },
{ "src": "/api/(.*)", "dest": "/api/$1" },
{
diff --git a/vite.config.js b/vite.config.js
index 8886687c6..ceda280d0 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -2,7 +2,17 @@ import { defineConfig } from 'vite';
import { resolve } from 'path';
import { VitePWA } from 'vite-plugin-pwa';
-export default defineConfig({
+// The build emits two targets controlled by the TARGET env var:
+//
+// TARGET=lib → builds dist-lib/agent-3d.js (ES module + UMD) for CDN use
+// TARGET=app → (default) builds the editor/app site into dist/
+//
+// npm run build → app
+// npm run build:lib → lib
+// npm run build:all → both
+const TARGET = process.env.TARGET || 'app';
+
+const appConfig = {
esbuild: {
jsx: 'transform',
jsxFactory: 'vhtml',
@@ -14,6 +24,7 @@ export default defineConfig({
input: {
main: resolve(__dirname, 'index.html'),
features: resolve(__dirname, 'features.html'),
+ embed: resolve(__dirname, 'embed.html'),
},
},
},
@@ -31,22 +42,9 @@ export default defineConfig({
scope: '/',
start_url: '/',
icons: [
- {
- src: 'pwa-192x192.png',
- sizes: '192x192',
- type: 'image/png',
- },
- {
- src: 'pwa-512x512.png',
- sizes: '512x512',
- type: 'image/png',
- },
- {
- src: 'pwa-512x512.png',
- sizes: '512x512',
- type: 'image/png',
- purpose: 'any maskable',
- },
+ { src: 'pwa-192x192.png', sizes: '192x192', type: 'image/png' },
+ { src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png' },
+ { src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png', purpose: 'any maskable' },
],
},
workbox: {
@@ -57,13 +55,8 @@ export default defineConfig({
handler: 'CacheFirst',
options: {
cacheName: 'google-fonts-cache',
- expiration: {
- maxEntries: 10,
- maxAgeSeconds: 60 * 60 * 24 * 365,
- },
- cacheableResponse: {
- statuses: [0, 200],
- },
+ expiration: { maxEntries: 10, maxAgeSeconds: 60 * 60 * 24 * 365 },
+ cacheableResponse: { statuses: [0, 200] },
},
},
{
@@ -71,17 +64,38 @@ export default defineConfig({
handler: 'CacheFirst',
options: {
cacheName: 'gstatic-fonts-cache',
- expiration: {
- maxEntries: 10,
- maxAgeSeconds: 60 * 60 * 24 * 365,
- },
- cacheableResponse: {
- statuses: [0, 200],
- },
+ expiration: { maxEntries: 10, maxAgeSeconds: 60 * 60 * 24 * 365 },
+ cacheableResponse: { statuses: [0, 200] },
},
},
],
},
}),
],
-});
+};
+
+// Library build — the web component + public API, for CDN drop-in:
+// <script type="module" src="https://cdn.example.com/agent-3d.js"></script>
+//
+// Three.js and ethers stay bundled (the element must be self-contained for a
+// zero-install embed). Size will be ~600-900KB gzipped; split via dynamic
+// imports in a later pass.
+const libConfig = {
+ build: {
+ outDir: 'dist-lib',
+ emptyOutDir: true,
+ chunkSizeWarningLimit: 2000,
+ lib: {
+ entry: resolve(__dirname, 'src/lib.js'),
+ name: 'Agent3D',
+ formats: ['es', 'umd'],
+ fileName: (format) => format === 'es' ? 'agent-3d.js' : 'agent-3d.umd.cjs',
+ },
+ rollupOptions: {
+ // No externals — we want a self-contained drop-in embed.
+ output: { inlineDynamicImports: false },
+ },
+ },
+};
+
+export default defineConfig(TARGET === 'lib' ? libConfig : appConfig);
diff --git a/yarn.lock b/yarn.lock
index 42062143e..498d35a67 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -63,7 +63,7 @@
"@smithy/util-utf8" "^2.0.0"
tslib "^2.6.2"
-"@aws-crypto/[email protected]", "@aws-crypto/sha256-js@^5.2.0":
+"@aws-crypto/sha256-js@^5.2.0", "@aws-crypto/[email protected]":
version "5.2.0"
resolved "https://registry.npmjs.org/@aws-crypto/sha256-js/-/sha256-js-5.2.0.tgz"
integrity sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==
@@ -79,7 +79,7 @@
dependencies:
tslib "^2.6.2"
-"@aws-crypto/[email protected]", "@aws-crypto/util@^5.2.0":
+"@aws-crypto/util@^5.2.0", "@aws-crypto/[email protected]":
version "5.2.0"
resolved "https://registry.npmjs.org/@aws-crypto/util/-/util-5.2.0.tgz"
integrity sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==
@@ -1384,132 +1384,36 @@
resolved "https://registry.npmjs.org/@chenglou/pretext/-/pretext-0.0.5.tgz"
integrity sha512-A8GZN10REdFGsyuiUgLV8jjPDDFMg5GmgxGWV0I3igxBOnzj+jgz2VMmVD7g+SFyoctfeqHFxbNatKSzVRWtRg==
-"@emnapi/[email protected]":
- version "1.9.2"
- resolved "https://registry.yarnpkg.com/@emnapi/core/-/core-1.9.2.tgz#3870265ecffc7352d01ead62d8d83d8358a2d034"
- integrity sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA==
+"@gltf-transform/core@^4.3.0":
+ version "4.3.0"
+ resolved "https://registry.npmjs.org/@gltf-transform/core/-/core-4.3.0.tgz"
+ integrity sha512-ZeaQfszGJ9LYwELszu45CuDQCsE26lJNNe36FVmN8xclaT6WDdCj7fwGpQXo0/l/YgAVAHX+uO7YNBW75/SRYw==
dependencies:
- "@emnapi/wasi-threads" "1.2.1"
- tslib "^2.4.0"
+ property-graph "^4.0.0"
-"@emnapi/[email protected]", "@emnapi/runtime@^1.7.0":
- version "1.9.2"
- resolved "https://registry.yarnpkg.com/@emnapi/runtime/-/runtime-1.9.2.tgz#8b469a3db160817cadb1de9050211a9d1ea84fa2"
- integrity sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw==
+"@gltf-transform/extensions@^4.3.0":
+ version "4.3.0"
+ resolved "https://registry.npmjs.org/@gltf-transform/extensions/-/extensions-4.3.0.tgz"
+ integrity sha512-XDAjQPYVMHa/VDpSbfCBwI+/1muwRJCaXhUpLgnUzAjn0D//PgvIAcbNm1EwBl3LIWBSwjDUCn2LiMAjp+aXVw==
dependencies:
- tslib "^2.4.0"
-
-"@emnapi/[email protected]":
- version "1.2.1"
- resolved "https://registry.yarnpkg.com/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz#28fed21a1ba1ce797c44a070abc94d42f3ae8548"
- integrity sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==
- dependencies:
- tslib "^2.4.0"
+ "@gltf-transform/core" "^4.3.0"
+ ktx-parse "^1.0.1"
"@img/colour@^1.0.0":
version "1.1.0"
resolved "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz"
integrity sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==
- version "0.34.5"
- resolved "https://registry.yarnpkg.com/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz#6e0732dcade126b6670af7aa17060b926835ea86"
- integrity sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==
- optionalDependencies:
- "@img/sharp-libvips-darwin-arm64" "1.2.4"
-
- version "0.34.5"
- resolved "https://registry.yarnpkg.com/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz#19bc1dd6eba6d5a96283498b9c9f401180ee9c7b"
- integrity sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==
- optionalDependencies:
- "@img/sharp-libvips-darwin-x64" "1.2.4"
-
- version "1.2.4"
- resolved "https://registry.yarnpkg.com/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz#2894c0cb87d42276c3889942e8e2db517a492c43"
- integrity sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==
-
- version "1.2.4"
- resolved "https://registry.yarnpkg.com/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz#e63681f4539a94af9cd17246ed8881734386f8cc"
- integrity sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==
-
- version "1.2.4"
- resolved "https://registry.yarnpkg.com/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz#b1b288b36864b3bce545ad91fa6dadcf1a4ad318"
- integrity sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==
-
- version "1.2.4"
- resolved "https://registry.yarnpkg.com/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz#b9260dd1ebe6f9e3bdbcbdcac9d2ac125f35852d"
- integrity sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==
-
- version "1.2.4"
- resolved "https://registry.yarnpkg.com/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz#4b83ecf2a829057222b38848c7b022e7b4d07aa7"
- integrity sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==
-
- version "1.2.4"
- resolved "https://registry.yarnpkg.com/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz#880b4678009e5a2080af192332b00b0aaf8a48de"
- integrity sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==
-
- version "1.2.4"
- resolved "https://registry.yarnpkg.com/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz#74f343c8e10fad821b38f75ced30488939dc59ec"
- integrity sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==
-
version "1.2.4"
resolved "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz"
integrity sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==
- version "1.2.4"
- resolved "https://registry.yarnpkg.com/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz#c8d6b48211df67137541007ee8d1b7b1f8ca8e06"
- integrity sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==
-
version "1.2.4"
resolved "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz"
integrity sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==
- version "0.34.5"
- resolved "https://registry.yarnpkg.com/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz#7aa7764ef9c001f15e610546d42fce56911790cc"
- integrity sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==
- optionalDependencies:
- "@img/sharp-libvips-linux-arm64" "1.2.4"
-
- version "0.34.5"
- resolved "https://registry.yarnpkg.com/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz#5fb0c3695dd12522d39c3ff7a6bc816461780a0d"
- integrity sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==
- optionalDependencies:
- "@img/sharp-libvips-linux-arm" "1.2.4"
-
- version "0.34.5"
- resolved "https://registry.yarnpkg.com/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz#9c213a81520a20caf66978f3d4c07456ff2e0813"
- integrity sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==
- optionalDependencies:
- "@img/sharp-libvips-linux-ppc64" "1.2.4"
-
- version "0.34.5"
- resolved "https://registry.yarnpkg.com/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz#cdd28182774eadbe04f62675a16aabbccb833f60"
- integrity sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==
- optionalDependencies:
- "@img/sharp-libvips-linux-riscv64" "1.2.4"
-
- version "0.34.5"
- resolved "https://registry.yarnpkg.com/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz#93eac601b9f329bb27917e0e19098c722d630df7"
- integrity sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==
- optionalDependencies:
- "@img/sharp-libvips-linux-s390x" "1.2.4"
-
version "0.34.5"
resolved "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz"
@@ -1517,13 +1421,6 @@
optionalDependencies:
"@img/sharp-libvips-linux-x64" "1.2.4"
- version "0.34.5"
- resolved "https://registry.yarnpkg.com/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz#d6515ee971bb62f73001a4829b9d865a11b77086"
- integrity sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==
- optionalDependencies:
- "@img/sharp-libvips-linuxmusl-arm64" "1.2.4"
-
version "0.34.5"
resolved "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz"
@@ -1531,28 +1428,6 @@
optionalDependencies:
"@img/sharp-libvips-linuxmusl-x64" "1.2.4"
- version "0.34.5"
- resolved "https://registry.yarnpkg.com/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz#2f15803aa626f8c59dd7c9d0bbc766f1ab52cfa0"
- integrity sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==
- dependencies:
- "@emnapi/runtime" "^1.7.0"
-
- version "0.34.5"
- resolved "https://registry.yarnpkg.com/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz#3706e9e3ac35fddfc1c87f94e849f1b75307ce0a"
- integrity sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==
-
- version "0.34.5"
- resolved "https://registry.yarnpkg.com/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz#0b71166599b049e032f085fb9263e02f4e4788de"
- integrity sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==
-
- version "0.34.5"
- resolved "https://registry.yarnpkg.com/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz#a81ffb00e69267cd0a1d626eaedb8a8430b2b2f8"
- integrity sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==
-
"@isaacs/cliui@^9.0.0":
version "9.0.0"
resolved "https://registry.npmjs.org/@isaacs/cliui/-/cliui-9.0.0.tgz"
@@ -1600,13 +1475,6 @@
"@jridgewell/resolve-uri" "^3.1.0"
"@jridgewell/sourcemap-codec" "^1.4.14"
-"@napi-rs/wasm-runtime@^1.1.3":
- version "1.1.3"
- resolved "https://registry.yarnpkg.com/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.3.tgz#1eeb8699770481306e5fcd84471f20fcb6177336"
- integrity sha512-xK9sGVbJWYb08+mTJt3/YV24WxvxpXcXtP6B172paPZ+Ts69Re9dAr7lKwJoeIx8OoeuimEiRZ7umkiUVClmmQ==
- dependencies:
- "@tybys/wasm-util" "^0.10.1"
-
"@neondatabase/serverless@^0.10.1":
version "0.10.4"
resolved "https://registry.npmjs.org/@neondatabase/serverless/-/serverless-0.10.4.tgz"
@@ -1631,51 +1499,6 @@
resolved "https://registry.npmjs.org/@oxc-project/types/-/types-0.124.0.tgz"
integrity sha512-VBFWMTBvHxS11Z5Lvlr3IWgrwhMTXV+Md+EQF0Xf60+wAdsGFTBx7X7K/hP4pi8N7dcm1RvcHwDxZ16Qx8keUg==
-"@rolldown/[email protected]":
- version "1.0.0-rc.15"
- resolved "https://registry.yarnpkg.com/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.15.tgz#ca20574c469ade7b941f90c9af5e83e7c67f06b7"
- integrity sha512-YYe6aWruPZDtHNpwu7+qAHEMbQ/yRl6atqb/AhznLTnD3UY99Q1jE7ihLSahNWkF4EqRPVC4SiR4O0UkLK02tA==
-
-"@rolldown/[email protected]":
- version "1.0.0-rc.15"
- resolved "https://registry.yarnpkg.com/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.15.tgz#ce2c5c7fc4958dfc94783dc09b3d09f3c2e1d072"
- integrity sha512-oArR/ig8wNTPYsXL+Mzhs0oxhxfuHRfG7Ikw7jXsw8mYOtk71W0OkF2VEVh699pdmzjPQsTjlD1JIOoHkLP1Fg==
-
-"@rolldown/[email protected]":
- version "1.0.0-rc.15"
- resolved "https://registry.yarnpkg.com/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.15.tgz#251ecdf1fdb751031cb6486907c105daaf9dab21"
- integrity sha512-YzeVqOqjPYvUbJSWJ4EDL8ahbmsIXQpgL3JVipmN+MX0XnXMeWomLN3Fb+nwCmP/jfyqte5I3XRSm7OfQrbyxw==
-
-"@rolldown/[email protected]":
- version "1.0.0-rc.15"
- resolved "https://registry.yarnpkg.com/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.15.tgz#dbcfe95f409bf671a77bd83bff0fdc877d217728"
- integrity sha512-9Erhx956jeQ0nNTyif1+QWAXDRD38ZNjr//bSHrt6wDwB+QkAfl2q6Mn1k6OBPerznjRmbM10lgRb1Pli4xZPw==
-
-"@rolldown/[email protected]":
- version "1.0.0-rc.15"
- resolved "https://registry.yarnpkg.com/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.15.tgz#ea002b45445be6f9ed1883a834b335bc2ccd510f"
- integrity sha512-cVwk0w8QbZJGTnP/AHQBs5yNwmpgGYStL88t4UIaqcvYJWBfS0s3oqVLZPwsPU6M0zlW4GqjP0Zq5MnAGwFeGA==
-
-"@rolldown/[email protected]":
- version "1.0.0-rc.15"
- resolved "https://registry.yarnpkg.com/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.15.tgz#12b96e7e7821a9dc2cd5c670ad56882987ed5c62"
- integrity sha512-eBZ/u8iAK9SoHGanqe/jrPnY0JvBN6iXbVOsbO38mbz+ZJsaobExAm1Iu+rxa4S1l2FjG0qEZn4Rc6X8n+9M+w==
-
-"@rolldown/[email protected]":
- version "1.0.0-rc.15"
- resolved "https://registry.yarnpkg.com/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.15.tgz#738b0f62f0b65bf676dfe48595017f1883859d1f"
- integrity sha512-ZvRYMGrAklV9PEkgt4LQM6MjQX2P58HPAuecwYObY2DhS2t35R0I810bKi0wmaYORt6m/2Sm+Z+nFgb0WhXNcQ==
-
-"@rolldown/[email protected]":
- version "1.0.0-rc.15"
- resolved "https://registry.yarnpkg.com/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.15.tgz#3088b9fbc2783033985b558316f87f39281bc533"
- integrity sha512-VDpgGBzgfg5hLg+uBpCLoFG5kVvEyafmfxGUV0UHLcL5irxAK7PKNeC2MwClgk6ZAiNhmo9FLhRYgvMmedLtnQ==
-
-"@rolldown/[email protected]":
- version "1.0.0-rc.15"
- resolved "https://registry.yarnpkg.com/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.15.tgz#ac0aa6f1b72e3151d56c43145a71c745cf862a9a"
- integrity sha512-y1uXY3qQWCzcPgRJATPSOUP4tCemh4uBdY7e3EZbVwCJTY3gLJWnQABgeUetvED+bt1FQ01OeZwvhLS2bpNrAQ==
-
"@rolldown/[email protected]":
version "1.0.0-rc.15"
resolved "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.15.tgz"
@@ -1686,30 +1509,6 @@
resolved "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.15.tgz"
integrity sha512-witB2O0/hU4CgfOOKUoeFgQ4GktPi1eEbAhaLAIpgD6+ZnhcPkUtPsoKKHRzmOoWPZue46IThdSgdo4XneOLYw==
-"@rolldown/[email protected]":
- version "1.0.0-rc.15"
- resolved "https://registry.yarnpkg.com/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.15.tgz#66ff691a65f9325171bced98e353b4cc4b0095c3"
- integrity sha512-UCL68NJ0Ud5zRipXZE9dF5PmirzJE4E4BCIOOssEnM7wLDsxjc6Qb0sGDxTNRTP53I6MZpygyCpY8Aa8sPfKPg==
-
-"@rolldown/[email protected]":
- version "1.0.0-rc.15"
- resolved "https://registry.yarnpkg.com/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.15.tgz#7db6c90aa510eef65d7d0f14e8ca23775e8e5eee"
- integrity sha512-ApLruZq/ig+nhaE7OJm4lDjayUnOHVUa77zGeqnqZ9pn0ovdVbbNPerVibLXDmWeUZXjIYIT8V3xkT58Rm9u5Q==
- dependencies:
- "@emnapi/core" "1.9.2"
- "@emnapi/runtime" "1.9.2"
- "@napi-rs/wasm-runtime" "^1.1.3"
-
-"@rolldown/[email protected]":
- version "1.0.0-rc.15"
- resolved "https://registry.yarnpkg.com/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.15.tgz#81f9097abbd4493cc13373b26f5a3da8461dbb47"
- integrity sha512-KmoUoU7HnN+Si5YWJigfTws1jz1bKBYDQKdbLspz0UaqjjFkddHsqorgiW1mxcAj88lYUE6NC/zJNwT+SloqtA==
-
-"@rolldown/[email protected]":
- version "1.0.0-rc.15"
- resolved "https://registry.yarnpkg.com/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.15.tgz#cef11bc89149f3a77771727be75490fbb13ae193"
- integrity sha512-3P2A8L+x75qavWLe/Dll3EYBJLQmtkJN8rfh+U/eR3MqMgL/h98PhYI+JFfXuDPgPeCB7iZAKiqii5vqOvnA0g==
-
"@rolldown/[email protected]":
version "1.0.0-rc.15"
resolved "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.15.tgz"
@@ -2271,23 +2070,16 @@
magic-string "^0.25.0"
string.prototype.matchall "^4.0.6"
-"@tybys/wasm-util@^0.10.1":
- version "0.10.1"
- resolved "https://registry.yarnpkg.com/@tybys/wasm-util/-/wasm-util-0.10.1.tgz#ecddd3205cf1e2d5274649ff0eedd2991ed7f414"
- integrity sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==
- dependencies:
- tslib "^2.4.0"
+"@types/estree@^1.0.0":
+ version "1.0.8"
+ resolved "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz"
+ integrity sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==
version "0.0.39"
resolved "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz"
integrity sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==
-"@types/estree@^1.0.0":
- version "1.0.8"
- resolved "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz"
- integrity sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==
-
"@types/node@*":
version "25.6.0"
resolved "https://registry.npmjs.org/@types/node/-/node-25.6.0.tgz"
@@ -2846,11 +2638,6 @@ fs-extra@^9.0.1:
jsonfile "^6.0.1"
universalify "^2.0.0"
-fsevents@~2.3.2, fsevents@~2.3.3:
- version "2.3.3"
- resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.3.tgz#cac6407785d03675a2a5e1a5305c697b347d90d6"
- integrity sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==
-
function-bind@^1.1.2:
version "1.1.2"
resolved "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz"
@@ -3259,46 +3046,16 @@ jsonpointer@^5.0.1:
resolved "https://registry.npmjs.org/jsonpointer/-/jsonpointer-5.0.1.tgz"
integrity sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ==
+ktx-parse@^1.0.1:
+ version "1.1.0"
+ resolved "https://registry.npmjs.org/ktx-parse/-/ktx-parse-1.1.0.tgz"
+ integrity sha512-mKp3y+FaYgR7mXWAbyyzpa/r1zDWeaunH+INJO4fou3hb45XuNSwar+7llrRyvpMWafxSIi99RNFJ05MHedaJQ==
+
leven@^3.1.0:
version "3.1.0"
resolved "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz"
integrity sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==
- version "1.32.0"
- resolved "https://registry.yarnpkg.com/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz#f033885116dfefd9c6f54787523e3514b61e1968"
- integrity sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==
-
- version "1.32.0"
- resolved "https://registry.yarnpkg.com/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz#50b71871b01c8199584b649e292547faea7af9b5"
- integrity sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==
-
- version "1.32.0"
- resolved "https://registry.yarnpkg.com/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz#35f3e97332d130b9ca181e11b568ded6aebc6d5e"
- integrity sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==
-
- version "1.32.0"
- resolved "https://registry.yarnpkg.com/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz#9777a76472b64ed6ff94342ad64c7bafd794a575"
- integrity sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==
-
- version "1.32.0"
- resolved "https://registry.yarnpkg.com/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz#13ae652e1ab73b9135d7b7da172f666c410ad53d"
- integrity sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==
-
- version "1.32.0"
- resolved "https://registry.yarnpkg.com/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz#417858795a94592f680123a1b1f9da8a0e1ef335"
- integrity sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==
-
- version "1.32.0"
- resolved "https://registry.yarnpkg.com/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz#6be36692e810b718040802fd809623cffe732133"
- integrity sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==
-
version "1.32.0"
resolved "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz"
@@ -3309,16 +3066,6 @@ [email protected]:
resolved "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz"
integrity sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==
- version "1.32.0"
- resolved "https://registry.yarnpkg.com/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz#4f30ba3fa5e925f5b79f945e8cc0d176c3b1ab38"
- integrity sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==
-
- version "1.32.0"
- resolved "https://registry.yarnpkg.com/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz#141aa5605645064928902bb4af045fa7d9f4220a"
- integrity sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==
-
lightningcss@^1.32.0:
version "1.32.0"
resolved "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz"
@@ -3574,6 +3321,11 @@ pretty-bytes@^6.1.1:
resolved "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-6.1.1.tgz"
integrity sha512-mQUvGU6aUFQ+rNvTIAcZuWGRT9a6f6Yrg9bHs4ImKF+HZCEK+plBvnAZYSIQztknZF2qnzNtr6F8s0+IuptdlQ==
+property-graph@^4.0.0:
+ version "4.1.0"
+ resolved "https://registry.npmjs.org/property-graph/-/property-graph-4.1.0.tgz"
+ integrity sha512-AvPcP7XECNWy4LGmFQ77k7un4lSKM4eS29PTvW4ck95uYeLxXPWJM7hLuBqK91FaHqCcgJvIUCuNJjjxKE7VKQ==
+
punycode@^2.1.0:
version "2.3.1"
resolved "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz"
@@ -3588,13 +3340,6 @@ query-string@^8.1.0:
filter-obj "^5.1.0"
split-on-first "^3.0.0"
-randombytes@^2.1.0:
- version "2.1.0"
- resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a"
- integrity sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==
- dependencies:
- safe-buffer "^5.1.0"
-
reflect.getprototypeof@^1.0.6, reflect.getprototypeof@^1.0.9:
version "1.0.10"
resolved "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz"
@@ -3714,11 +3459,6 @@ safe-array-concat@^1.1.3:
has-symbols "^1.1.0"
isarray "^2.0.5"
-safe-buffer@^5.1.0:
- version "5.2.1"
- resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6"
- integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==
-
safe-push-apply@^1.0.0:
version "1.0.0"
resolved "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz"
@@ -3746,12 +3486,10 @@ semver@^7.7.3:
resolved "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz"
integrity sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==
-serialize-javascript@^6.0.1:
- version "6.0.2"
- resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-6.0.2.tgz#defa1e055c83bf6d59ea805d8da862254eb6a6c2"
- integrity sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==
- dependencies:
- randombytes "^2.1.0"
+serialize-javascript@>=7.0.5:
+ version "7.0.5"
+ resolved "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.0.5.tgz"
+ integrity sha512-F4LcB0UqUl1zErq+1nYEEzSHJnIwb3AF2XWB94b+afhrekOUijwooAYqFyRbjYkm2PAKBabx6oYv/xDxNi8IBw==
set-function-length@^1.2.2:
version "1.2.2"
@@ -4050,16 +3788,16 @@ tr46@^1.0.1:
dependencies:
punycode "^2.1.0"
- version "2.7.0"
- resolved "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz"
- integrity sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==
-
tslib@^2.4.0, tslib@^2.6.2:
version "2.8.1"
resolved "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz"
integrity sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==
+ version "2.7.0"
+ resolved "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz"
+ integrity sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==
+
type-fest@^0.16.0:
version "0.16.0"
resolved "https://registry.npmjs.org/type-fest/-/type-fest-0.16.0.tgz"
@@ -4132,7 +3870,7 @@ undici-types@~6.19.2:
undici-types@~7.19.0:
version "7.19.2"
- resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-7.19.2.tgz#1b67fc26d0f157a0cba3a58a5b5c1e2276b8ba2a"
+ resolved "https://registry.npmjs.org/undici-types/-/undici-types-7.19.2.tgz"
integrity sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==
unicode-canonical-property-names-ecmascript@^2.0.0:
@@ -4303,7 +4041,7 @@ [email protected]:
workbox-build@^7.4.0:
version "7.4.0"
- resolved "https://registry.yarnpkg.com/workbox-build/-/workbox-build-7.4.0.tgz#033f88ebbd9c6312983f3fb9c17a4161369d693f"
+ resolved "https://registry.npmjs.org/workbox-build/-/workbox-build-7.4.0.tgz"
integrity sha512-Ntk1pWb0caOFIvwz/hfgrov/OJ45wPEhI5PbTywQcYjyZiVhT3UrwwUPl6TRYbTm4moaFYithYnl1lvZ8UjxcA==
dependencies:
"@apideck/better-ajv-errors" "^0.3.1"
@@ -4436,7 +4174,7 @@ [email protected]:
resolved "https://registry.npmjs.org/workbox-sw/-/workbox-sw-7.4.0.tgz"
integrity sha512-ltU+Kr3qWR6BtbdlMnCjobZKzeV1hN+S6UvDywBrwM19TTyqA03X66dzw1tEIdJvQ4lYKkBFox6IAEhoSEZ8Xw==
[email protected], workbox-window@^7.4.0:
+workbox-window@^7.4.0, [email protected]:
version "7.4.0"
resolved "https://registry.npmjs.org/workbox-window/-/workbox-window-7.4.0.tgz"
integrity sha512-/bIYdBLAVsNR3v7gYGaV4pQW3M3kEPx5E8vDxGvxo6khTrGtSSCS7QiFKv9ogzBgZiy0OXLP9zO28U/1nF1mfw==