From b8e92cd7b2cfdb3a63e12e1769f0a3f0cd668393 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 05:47:24 -0500 Subject: [PATCH 1/4] feat(rust): build the docs view and write the model explorer without Node The Rust port builds the port-neutral docs view from its loaded model (metaobjects::docs_view), byte-identical to TypeScript on every fixtures/explorer-conformance case, and a new opt-in docs-site generator writes explorer.json, the explorer app, explorer-model.js and explorer-stamp.js. The app is a canonical copy in metaobjects-codegen (synced by scripts/sync-explorer-app.sh, held by the explorer app copies gate) and ships in the published crate. Rust codegen now records generatedBy/sourceNode provenance in the hash manifest per the shared provenance vector, and the engine runs a run-output reader (docs-site) after every other generator, so gen and verify list the same files. The docs-site builder is engine, as the shared registry rules: eject refuses it and gen --list marks it [package-only]; an owned theme in codegen/docs-site/ replaces the shipped one. metaobjects::meta_endpoint adds the framework-free /_meta and /_meta/docs bodies (ETag and If-None-Match as TypeScript's). --- changelog.d/explorer-rust.md | 23 + docs/features/docs-view.md | 6 +- docs/features/explorer-data.md | 10 +- docs/features/explorer-site.md | 21 +- docs/features/metadata-api.md | 43 +- docs/ports/rust.md | 62 +- .../.gen-state/.hashes/tasks.json | 24 +- explorer-app/README.md | 1 + fixtures/codegen-skip-conformance/README.md | 4 +- fixtures/explorer-conformance/README.md | 6 + .../registry.json | 4 +- scripts/ci-local.sh | 3 +- scripts/sync-explorer-app.sh | 1 + server/rust/metaobjects-cli/src/lib.rs | 7 +- server/rust/metaobjects-cli/tests/cli.rs | 16 +- .../explorer-app/assets/3d-force-graph.min.js | 1056 ++++++++++++ .../explorer-app/assets/cytoscape.min.js | 32 + .../explorer-app/assets/explorer-app.js | 269 ++++ .../explorer-app/assets/explorer.css | 238 +++ .../explorer-app/assets/explorer.js | 422 +++++ .../explorer-app/index.html | 20 + server/rust/metaobjects-codegen/src/client.rs | 7 +- .../rust/metaobjects-codegen/src/commands.rs | 7 +- .../rust/metaobjects-codegen/src/docs_site.rs | 458 ++++++ server/rust/metaobjects-codegen/src/eject.rs | 46 + server/rust/metaobjects-codegen/src/engine.rs | 91 +- server/rust/metaobjects-codegen/src/entity.rs | 7 +- .../rust/metaobjects-codegen/src/generator.rs | 30 +- server/rust/metaobjects-codegen/src/hashes.rs | 62 +- server/rust/metaobjects-codegen/src/lib.rs | 3 + .../metaobjects-codegen/src/output_parser.rs | 11 +- .../metaobjects-codegen/src/output_prompt.rs | 14 +- .../metaobjects-codegen/src/render_helper.rs | 11 +- .../metaobjects-codegen/src/repository.rs | 11 +- .../rust/metaobjects-codegen/src/service.rs | 11 +- .../metaobjects-codegen/src/service_routes.rs | 10 +- .../metaobjects-codegen/tests/common/mod.rs | 7 +- .../metaobjects-codegen/tests/docs_site.rs | 231 +++ .../metaobjects-codegen/tests/entity_edges.rs | 1 + .../tests/generator_registry.rs | 29 +- .../rust/metaobjects-codegen/tests/golden.rs | 2 + .../tests/hash_manifest.rs | 56 + .../tests/list_query_conformance.rs | 1 + .../tests/reference_nodes.rs | 1 + .../metaobjects-codegen/tests/rules_inert.rs | 17 + .../metaobjects-codegen/tests/run_engine.rs | 24 +- server/rust/metaobjects/src/docs_view.rs | 1431 +++++++++++++++++ server/rust/metaobjects/src/json.rs | 43 +- server/rust/metaobjects/src/lib.rs | 2 + server/rust/metaobjects/src/loader.rs | 53 +- server/rust/metaobjects/src/meta_endpoint.rs | 113 ++ server/rust/metaobjects/src/providers.rs | 17 +- .../tests/docs_view_conformance.rs | 119 ++ 53 files changed, 5081 insertions(+), 113 deletions(-) create mode 100644 changelog.d/explorer-rust.md create mode 100644 server/rust/metaobjects-codegen/explorer-app/assets/3d-force-graph.min.js create mode 100644 server/rust/metaobjects-codegen/explorer-app/assets/cytoscape.min.js create mode 100644 server/rust/metaobjects-codegen/explorer-app/assets/explorer-app.js create mode 100644 server/rust/metaobjects-codegen/explorer-app/assets/explorer.css create mode 100644 server/rust/metaobjects-codegen/explorer-app/assets/explorer.js create mode 100644 server/rust/metaobjects-codegen/explorer-app/index.html create mode 100644 server/rust/metaobjects-codegen/src/docs_site.rs create mode 100644 server/rust/metaobjects-codegen/tests/docs_site.rs create mode 100644 server/rust/metaobjects/src/docs_view.rs create mode 100644 server/rust/metaobjects/src/meta_endpoint.rs create mode 100644 server/rust/metaobjects/tests/docs_view_conformance.rs diff --git a/changelog.d/explorer-rust.md b/changelog.d/explorer-rust.md new file mode 100644 index 0000000000..ef1a3eee7c --- /dev/null +++ b/changelog.d/explorer-rust.md @@ -0,0 +1,23 @@ +- **Rust: the model explorer with no Node.** The Rust port builds the docs view from its loaded + model (`metaobjects::docs_view::build`), byte for byte what TypeScript builds for every + `fixtures/explorer-conformance/` case. A new opt-in `docs-site` generator writes + `explorer.json`, the explorer app, `explorer-model.js` and `explorer-stamp.js` under + `site/`. It reads prompt texts from the metadata directories, `templates/` and a `prompts` + directory, and takes `subDir`, `title`, `stamp`, `verifyFile` and `routesFile` as options. + Each node lists the files generated for it: this run's (the engine runs the site after every + other generator) and the committed manifest's outside the run, so `cargo meta verify` renders + what `gen` wrote. The site builder is engine, as in every port: `cargo meta eject docs-site` + refuses, `gen --list` marks it `[package-only]`, and an owned theme in `codegen/docs-site/` + replaces the shipped one. The app files are a canonical copy in the crate + (`metaobjects-codegen/explorer-app/`, held to the root `explorer-app/` by the + `explorer app copies` gate) and ship in the published package. The running application can serve + the same view at `{apiPrefix}/_meta/docs`: `metaobjects::meta_endpoint::docs` builds it once and + carries its ETag, and the host mounts it as it mounts `/_meta` (`meta_endpoint::meta_json`, + new in Rust too). + + Rust codegen now also records which node each generated file came from, `{ "hash", + "generatedBy", "sourceNode" }` in the hash manifest, held to the shared `provenance` vector in + `fixtures/codegen-skip-conformance/manifests.json`. A file rendered for no single node, such as + a shared `meta_*` crate's, keeps the plain hash. Upgrading: the next `cargo meta gen` rewrites + the committed `.metaobjects/.gen-state/.hashes/` files once. Commit them; generated source + files do not change. diff --git a/docs/features/docs-view.md b/docs/features/docs-view.md index dde6a53ae1..7f9c072834 100644 --- a/docs/features/docs-view.md +++ b/docs/features/docs-view.md @@ -13,11 +13,11 @@ writes the same bytes for the same model, and the shared corpus [`fixtures/explorer-conformance/`](../../fixtures/explorer-conformance/) holds them to that. TypeScript builds it today, and so do Java and Kotlin (one JVM builder, `DocsView` in -`metadata`). `buildDocsView` and `serializeDocsView` are exported from `@metaobjectsdev/metadata`, +`metadata`) and Rust (`metaobjects::docs_view`). `buildDocsView` and `serializeDocsView` are exported from `@metaobjectsdev/metadata`, and `docsSiteFile()` writes the result as the site's `explorer.json` (see -[explorer-site.md](explorer-site.md)). C#, Python and Rust will build it as their own step of the same +[explorer-site.md](explorer-site.md)). C# and Python will build it as their own step of the same plan ([explorer-data.md](explorer-data.md#not-built-yet)). The explorer pages still render their -HTML in TypeScript; the JVM copies the app and writes the same `explorer.json`. +HTML in TypeScript; the JVM and Rust copy the app and write the same `explorer.json`. A page of your own is a template over the view: the TypeScript `template` generator renders it with the `perNode` and `perRequirement` scopes (and `data: "docsView"` on `perModel` and diff --git a/docs/features/explorer-data.md b/docs/features/explorer-data.md index a653375d57..ba34ecce2d 100644 --- a/docs/features/explorer-data.md +++ b/docs/features/explorer-data.md @@ -119,10 +119,10 @@ manifest reader takes `hash` from either form. The provenance field is named `generatedBy`, not `generator`. In a Java or Kotlin module's manifest, `generator` means that generator owns the file (ADR-0060), and the orphan sweep acts on that ownership, so a JVM entry carries both: `{ "hash", "generator", "outputDir", -"generatedBy", "sourceNode" }`. The four ports that write provenance write the same entry for the +"generatedBy", "sourceNode" }`. The five ports that write provenance write the same entry for the same records; the shared vector `provenance` in [`fixtures/codegen-skip-conformance/manifests.json`](../../fixtures/codegen-skip-conformance/manifests.json) -holds TypeScript, C#, Java and Python to it. Kotlin and Rust write no provenance yet. +holds TypeScript, C#, Java, Python and Rust to it. Kotlin writes no provenance yet. ## Building it by hand @@ -156,9 +156,9 @@ malformed leaves its part of the view empty. - **`usage`**: which hand-written modules import a generated module. The design marks it optional, and nothing builds it yet. -- **Provenance from the Kotlin and Rust generators.** Their manifest entries have no - `sourceNode` yet, so for those ports a node lists no files. -- **The docs view in C#, Python and Rust.** TypeScript, Java and Kotlin build it today; the +- **Provenance from the Kotlin generators.** Their manifest entries have no + `sourceNode` yet, so for that port a node lists no files. +- **The docs view in C# and Python.** TypeScript, Java, Kotlin and Rust build it today; the corpus is what the other ports will be held to. ## Verified by diff --git a/docs/features/explorer-site.md b/docs/features/explorer-site.md index 48c4990f82..e0f83b0831 100644 --- a/docs/features/explorer-site.md +++ b/docs/features/explorer-site.md @@ -73,7 +73,8 @@ same model and inputs: every port that builds the docs view is held to | TypeScript | `docsSiteFile()` (`meta gen`) | `output: "app"` (default) or `"static"`; `site: "classic"` for the earlier site | The model, the requirement ledger, the files and routes this run wrote and mounts | | Java | `com.metaobjects.generator.DocsSiteGenerator` (`mvn metaobjects:generate`), no Node | The app only | The model, the files generated per node (this execution's, and what the committed hash manifest records for the module's other executions), and a `verify --format json` payload when you name one (`verifyFile`) | | Kotlin | the same JVM `DocsSiteGenerator`, through `codegen-kotlin`'s registry | The app only | As Java; the Kotlin generators do not record provenance in the manifest yet, so their files are not listed | -| C#, Python, Rust | not yet | | | +| C#, Python | not yet | | | +| Rust | `docs-site` (`cargo meta gen`, `metaobjects_codegen::DocsSiteGenerator`), no Node | The app only | The model, the files generated per node (this run's, and what the committed hash manifest records outside the directories the run clears), and a `verify --format json` payload (`verifyFile`) and a routes file (`routesFile`) when you name them. Options and the owned theme: [the Rust port](../ports/rust.md#docs-site-the-model-explorer) | On the JVM, wire it like any other generator, with its own output directory: @@ -297,16 +298,17 @@ a dangling link. `createExplorer` (the page table both outputs draw from) and - An LLM-written summary, a test-result overlay, zoom levels and lenses on the map, and publishing the site. -- The docs view route in C#, Python and Rust: the contract is in +- The docs view route in C# and Python: the contract is in [metadata-api.md](metadata-api.md#the-docs-view-endpoint-get-_metadocs), and each port serves - it once it has its docs view builder. Java and Kotlin ship it (`MetaEndpoint.docs(root)`). -- The app in C#, Python and Rust: its files are in each port's package already (see + it once it has its docs view builder. Java and Kotlin ship it (`MetaEndpoint.docs(root)`), and + Rust (`metaobjects::meta_endpoint::docs`). +- The app in C# and Python: its files are in each port's package already (see `explorer-app/README.md`), and each port's docs-site generator is still to write them. - The static export and the classic site outside TypeScript. - "Hand-written code that imports it": the site reads no import graph, so the object pages say it was not scanned. -- Generated-file provenance from the Kotlin and Rust generators (see - [explorer-data.md](explorer-data.md)), so for those ports the generated-file lists are empty. +- Generated-file provenance from the Kotlin generators (see + [explorer-data.md](explorer-data.md)), so for that port the generated-file lists are empty. ## Verified by @@ -317,6 +319,13 @@ a dangling link. `createExplorer` (the page table both outputs draw from) and stamp, an owned theme wins, and the generator lists the manifest's files. - `server/java/metadata/src/test/java/com/metaobjects/io/json/MetaDocsEndpointTest.java`: the JVM docs view route body is the `model-alone` view, and its ETag is TypeScript's. +- `server/rust/metaobjects/tests/docs_view_conformance.rs`: the Rust docs view builder writes + every `fixtures/explorer-conformance/` case byte for byte, and the `/_meta/docs` body is the + `model-alone` view with TypeScript's ETag. +- `server/rust/metaobjects-codegen/tests/docs_site.rs`: the Rust site's app files are the + canonical copy, its model script has TypeScript's bytes and stamp, an owned theme wins, prompt + texts are read only inside the prompt directories, and a `cargo meta gen` run writes the shop + case's `explorer.json` over the manifest's files and verifies clean. - `server/typescript/packages/docs-site/test/explorer-app.test.ts`: the files the app output writes, the model and stamp files, owned templates and theme, and the committed bundle, run outside a browser, drawing every page the static export writes byte for byte on the shop, crm diff --git a/docs/features/metadata-api.md b/docs/features/metadata-api.md index fd4d35ca69..ed71d41aea 100644 --- a/docs/features/metadata-api.md +++ b/docs/features/metadata-api.md @@ -63,12 +63,13 @@ the package, including consumers with no HTTP surface at all. | Java (`metaobjects-metadata`) | `com.metaobjects.io.json.MetaEndpoint.META_ROUTE_PATH`, `MetaEndpoint.metaJson(MetaData root)` | Host mounts — `core-spring` carries `spring-context` but no `spring-web` | | Kotlin | consumes the Java `MetaEndpoint` symbol directly via the `metadata-ktx` facade — there is no separate Kotlin implementation | Host mounts | | Python (`metaobjects`) | `META_ROUTE_PATH`, `meta_json(root)` (both exported from the package root) | Host mounts — neither `metaobjects.runtime` nor `metaobjects.codegen.runtime` imports a web framework | +| Rust (`metaobjects`) | `metaobjects::meta_endpoint::META_ROUTE_PATH`, `meta_endpoint::meta_json(&tree, root)` | Host mounts — the `metaobjects` crate depends on no web framework | The response body is not a new thing to gate: each helper is a thin wrapper over that port's already-conformance-gated effective serializer (`canonicalSerializeEffective` / `SerializerJson.CanonicalSerializeEffective` / `CanonicalJsonSerializer.canonicalSerializeEffective` / -`canonical_serialize_effective`), so `/_meta`'s bytes ride on the existing +`canonical_serialize_effective`, in Python and in Rust), so `/_meta`'s bytes ride on the existing metadata conformance corpus rather than a new one built for this endpoint. The exact `content-type` header value is a per-port detail, not a pinned cross-port byte — TypeScript's mounts emit @@ -153,6 +154,20 @@ def meta() -> Response: return Response(meta_json(root), media_type="application/json") ``` +### Rust — axum + +```rust +use axum::{Router, routing::get}; +use metaobjects::meta_endpoint::{META_ROUTE_PATH, meta_json}; + +// tree, root: the model this app loaded. Serialized once: the model does not change after load. +let body = meta_json(&tree, root); +let app = Router::new().route( + &format!("/api{META_ROUTE_PATH}"), + get(move || async move { ([("content-type", "application/json")], body) }), +); +``` + ## Exposure Mounting `/_meta` is **opt-in** in every port — nothing registers it @@ -258,7 +273,31 @@ Kotlin calls the same symbols through `metadata-ktx`. To let the explorer read t `file://`, add `Access-Control-Allow-Origin: null` and `Access-Control-Expose-Headers: ETag` to that response, or use Spring's CORS configuration. -C#, Python and Rust serve the route once each has its docs view builder, with the +Rust ships the same helper in `metaobjects::meta_endpoint`, framework-free, and leaves the mount +to the host under the same guard: `docs(&tree, root, routes)` builds the view once and gives +`body`, `etag` and `matches(if_none_match)` (`META_DOCS_ROUTE_PATH`, +`meta_docs_json(&tree, root, routes)`, `meta_docs_etag`). With axum: + +```rust +use axum::{http::{HeaderMap, StatusCode, header}, response::IntoResponse, routing::get}; +use metaobjects::meta_endpoint::{META_DOCS_ROUTE_PATH, docs}; + +let docs = std::sync::Arc::new(docs(&tree, root, None)); +let app = app.route( + &format!("/api{META_DOCS_ROUTE_PATH}"), + get(move |headers: HeaderMap| async move { + let tag = headers.get(header::IF_NONE_MATCH).and_then(|v| v.to_str().ok()); + let common = [(header::ETAG, docs.etag.clone()), (header::CACHE_CONTROL, "no-cache".into())]; + if docs.matches(tag) { + (StatusCode::NOT_MODIFIED, common).into_response() + } else { + (common, [(header::CONTENT_TYPE, "application/json")], docs.body.clone()).into_response() + } + }), +); +``` + +C# and Python serve the route once each has its docs view builder, with the body that builder writes; their `/_meta` sections above show where each mounts it. ## Browser consumption diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 40a94feb12..b4aeb48501 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -35,7 +35,9 @@ The loader is the `metaobjects` crate, and the workspace at `server/rust/` adds | Frozen tree | The loader freezes the tree when it finishes. A frozen tree memoizes its resolved reads (effective children, attributes and array-ness), so many readers can share one. | | Timings | Every load records how long each phase and each validation pass took (`LoadResult::timings`). | | Report shapes | `metaobjects::report_shape::report_shape` derives an `object.report`'s fields (FR-044 Table B, with Table C's `required`): each dimension and measure, its subtype, and the `@of` field it takes its type from. It byte-matches `fixtures/persistence-conformance/report-shapes.json`, as every port does. | -| Code generation (`cargo meta`) | The run engine, twelve generators (`entity`, `rules-names`, `contract-types`, `repository`, `service`, `service-routes`, `client`, `commands`, `render-helper`, `output-parser`, `output-prompt`, and the opt-in `metamodel-docs`, the metamodel reference pages rendered from the shared Mustache set), the codegen and template drift gates and `eject`. See [The command](#the-command-cargo-meta) and [What `gen` writes](#what-gen-writes) below. | +| Docs view | `metaobjects::docs_view::build` builds the port-neutral docs view (`docs/features/docs-view.md`) from the loaded model, with the requirement ledger, the generated files and the routes when it is given them. It byte-matches `fixtures/explorer-conformance/`, as every port does. | +| Metadata routes | `metaobjects::meta_endpoint` holds the bodies of `GET /_meta` (`meta_json`) and `GET /_meta/docs` (`docs`, with its ETag and the `If-None-Match` check), framework-free, for the host to mount ([Metadata API](../features/metadata-api.md#rust--axum)). | +| Code generation (`cargo meta`) | The run engine, thirteen generators (`entity`, `rules-names`, `contract-types`, `repository`, `service`, `service-routes`, `client`, `commands`, `render-helper`, `output-parser`, `output-prompt`, and two opt-in docs generators: `metamodel-docs`, the metamodel reference pages rendered from the shared Mustache set, and `docs-site`, the model explorer), the codegen and template drift gates and `eject`. See [The command](#the-command-cargo-meta) and [What `gen` writes](#what-gen-writes) below. | ## The command: `cargo meta` @@ -78,15 +80,17 @@ one, and no eject is needed: The file takes that one key: a layer is only a generator, so there are no layer settings. An entry is a name, or `{"name": "", "options": {...}}` for a generator that takes options; the generator's `configure` reads them and refuses a key it does not know (`ERR_UNKNOWN_GENERATOR_OPTION`, -naming the options it takes). Of the shipped generators only `metamodel-docs` takes one (`subDir`), so +naming the options it takes). Of the shipped generators only the two docs generators take options +(`metamodel-docs` takes `subDir`; `docs-site` takes the six in [its section](#docs-site-the-model-explorer)), so any other option fails the run, also a run `--generators` narrows to other generators. A project with -no such file runs every generator but `service-routes` and `metamodel-docs`, which run only when they -are listed: an HTTP server is a choice the project makes, not a default, and so are the metamodel -reference pages. A generator that leaves the list has its files removed +no such file runs every generator but `service-routes`, `metamodel-docs` and `docs-site`, which run +only when they are listed: an HTTP server is a choice the project makes, not a default, and so are +the metamodel reference pages and the model explorer. A generator that leaves the list has its files removed on the next `gen` (a file somebody edited is refused by name instead), and the run fails, naming the file, for a name nothing offers, a duplicate, an unknown key, or a generator listed without one it builds on (`client`, `render-helper` and `output-parser` need `entity`; `commands` needs `entity` and `client`; each layer needs the one beneath it, up to `service-routes`, which needs `service`). `cargo meta gen --list` shows each generator -as `[configured]` or `[not configured]`, marks the opt-in one `[opt-in]`, and `--generators` narrows one run to some of the list. +as `[configured]` or `[not configured]`, marks the opt-in ones `[opt-in]` and the one that cannot be +ejected `[package-only]`, and `--generators` narrows one run to some of the list. **Exit codes** are the ones every port's tool uses: 0 success, 1 the run failed (a model that does not load, a refused file, drift), 2 a usage error. An unknown flag names the flags the command takes. @@ -482,6 +486,49 @@ An entity whose source has a read-only view beside its table (`source.rdb @kind: role) is written to the table and read back through the view, so the fields that view derives (`origin.*`) are in every answer, a write's included. +### `docs-site`: the model explorer + +The model explorer ([Explorer site](../features/explorer-site.md)), written with no Node: the +generator builds the docs view from the model this run loaded, and writes it with the explorer app +under `site/` in the output directory: + +```text +generated/site/ + index.html, assets/ the app: the same bytes in every port (the repository's explorer-app/) + explorer.json the docs view, byte for byte what every port writes for the model + explorer-model.js the docs view, the prompt texts, the title and the footer, as one script + explorer-stamp.js the model's hash, which the open app polls to reload itself +``` + +List it with its options: + +```json +{ "generators": ["entity", "client", { "name": "docs-site", "options": { "prompts": "prompts" } }] } +``` + +| Option | Default | What it does | +|---|---|---| +| `subDir` | `site` | The directory under the output it writes to; `""` writes at the output root | +| `title` | the project directory's name | The header and the home page title | +| `stamp` | none | Footer text, such as a version; none keeps the site a function of the model alone | +| `prompts` | none | A directory, relative to the project, of prompt `.mustache` sources outside the metadata directories and `templates/` (those two are always searched) | +| `verifyFile` | none | A `verify --format json` payload whose requirement rows the explorer shows. `cargo meta verify` has no requirement gate, so write it with another port's `verify` | +| `routesFile` | none | The routes the application mounts, `[{ node, method, path }]` with `node` a resolution key | + +Each node's page lists the files generated for it, read from the provenance the generators record +in the hash manifest (`generatedBy` and `sourceNode` on each file written for one node; a shared +crate's files stay a plain hash): the files this run wrote, and what the +committed manifest records outside the directories the run clears. The engine runs the generator +after every other one, so `cargo meta verify` renders the same lists the write run wrote. + +The site builder is engine, not a reference generator: `cargo meta eject docs-site` refuses, and +`gen --list` marks it `[package-only]`. What a project owns is the theme. Files in +`codegen/docs-site/` replace the shipped ones: `assets/explorer.css`, `assets/explorer.js`, and +`templates/explorer-*.mustache`, which the app uses in place of its own. Editing one regenerates. + +To read the docs view from the running application instead, mount `GET /_meta/docs` +([Metadata API](../features/metadata-api.md#rust--axum)) and open `index.html?source=`. + ### Owning a generator A generator is a reference helper @@ -607,7 +654,8 @@ regeneration, peak memory), so a port's speed can be tracked per feature next to ## What does not exist yet -- **Other generators.** There is no documentation generator. Projections and reports get no route, +- **Other generators.** The documentation generators are `metamodel-docs` and `docs-site`: there is no + per-entity reference page generator (`docs`, `api-docs`) and no static export of the explorer. Projections and reports get no route, client or commands yet, and a template over a sourceless `object.projection` payload gets no render function. - **The rest of the API-contract corpus.** The transport passes `core`, `write-through`, diff --git a/examples/rust-service/.metaobjects/.gen-state/.hashes/tasks.json b/examples/rust-service/.metaobjects/.gen-state/.hashes/tasks.json index 23a05f894a..7b07dd9322 100644 --- a/examples/rust-service/.metaobjects/.gen-state/.hashes/tasks.json +++ b/examples/rust-service/.metaobjects/.gen-state/.hashes/tasks.json @@ -1,6 +1,22 @@ { - "generated/tasks/src/task.rs": "c9494e046f1d9ec89cd5441247211303e2b26191bc4eed85f78f415b50a2b2e9", - "generated/tasks_http/src/task.rs": "f2c1bebac5452927c39a0c74c22e67ec2da699d5845d7e9bcccb6316f084b32e", - "generated/tasks_service/src/task.rs": "11fba25fd503ae858bcf6e3395c95b30ebcca1e4444dc4cfba1926c7fc8cfd11", - "generated/tasks_store/src/task.rs": "ae56db0385964c1f68b676bb0e29c3c10c5339cbfd3165e239b10a635fef5bda" + "generated/tasks/src/task.rs": { + "hash": "c9494e046f1d9ec89cd5441247211303e2b26191bc4eed85f78f415b50a2b2e9", + "generatedBy": "entity", + "sourceNode": "tasks::Task" + }, + "generated/tasks_http/src/task.rs": { + "hash": "f2c1bebac5452927c39a0c74c22e67ec2da699d5845d7e9bcccb6316f084b32e", + "generatedBy": "service-routes", + "sourceNode": "tasks::Task" + }, + "generated/tasks_service/src/task.rs": { + "hash": "11fba25fd503ae858bcf6e3395c95b30ebcca1e4444dc4cfba1926c7fc8cfd11", + "generatedBy": "service", + "sourceNode": "tasks::Task" + }, + "generated/tasks_store/src/task.rs": { + "hash": "ae56db0385964c1f68b676bb0e29c3c10c5339cbfd3165e239b10a635fef5bda", + "generatedBy": "repository", + "sourceNode": "tasks::Task" + } } diff --git a/explorer-app/README.md b/explorer-app/README.md index 41d6f759a3..6a593fdf88 100644 --- a/explorer-app/README.md +++ b/explorer-app/README.md @@ -40,6 +40,7 @@ Bun stops with an error that names the required version. | Python | `server/python/src/metaobjects/documentation/explorer_app/` | | Java and Kotlin | `server/java/codegen-base/src/main/resources/metaobjects/explorer-app/` | | C# | `server/csharp/MetaObjects.Codegen/ExplorerApp/` | +| Rust | `server/rust/metaobjects-codegen/explorer-app/` (compiled into the crate with `include_str!`, so it ships in the published package) | ## What a port writes beside the app diff --git a/fixtures/codegen-skip-conformance/README.md b/fixtures/codegen-skip-conformance/README.md index 40bec46c92..01232f36bd 100644 --- a/fixtures/codegen-skip-conformance/README.md +++ b/fixtures/codegen-skip-conformance/README.md @@ -43,8 +43,8 @@ vectors in `manifests.json` are run by each port's manifest unit tests, beside t as the loaded model, and the directory must hold exactly `afterFiles` (`goldenText` is one file's bytes in full). A record with a `sourceNode` makes the entry `{ "hash", , "generatedBy", "sourceNode" }`; one without returns it to the plain hash; a path with no recorded - hash is left out. Recording the same records again changes no file. TypeScript, C#, Java and - Python run it. + hash is left out. Recording the same records again changes no file. TypeScript, C#, Java, + Python and Rust run it (Rust in `server/rust/metaobjects-codegen/tests/hash_manifest.rs`). A port's tests also assert what the vectors cannot: two writes that change entries in two packages change two files and no third, a save that changes nothing writes nothing, a package that loses its diff --git a/fixtures/explorer-conformance/README.md b/fixtures/explorer-conformance/README.md index 150e0578f4..68edb523bc 100644 --- a/fixtures/explorer-conformance/README.md +++ b/fixtures/explorer-conformance/README.md @@ -110,3 +110,9 @@ Then review the diff: every changed line is a change to what a docs page can sho `hashes.json` as the gen-state manifest. - `server/java/metadata/src/test/java/com/metaobjects/io/json/MetaDocsEndpointTest.java`: the JVM docs view route body is `model-alone/expected.json`. +- `server/rust/metaobjects/tests/docs_view_conformance.rs`: the Rust builder reproduces every + case (it applies `provider.json` the same way), and the `/_meta/docs` body + (`metaobjects::meta_endpoint`) is `model-alone/expected.json`. +- `server/rust/metaobjects-codegen/tests/docs_site.rs`: the Rust `docs-site` generator writes + the shop case's `explorer.json` in a `cargo meta gen` run, reading `hashes.json` as the + gen-state manifest and `prompts/` for the prompt text. diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index a6d513edba..6d0bf84d9d 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -357,12 +357,12 @@ "concept": "The browsable HTML site of the model: navigation, search, a page per package and per object, ER diagrams.", "tier": "neutral", "layer": "docs", - "note": "It was `meta docs --site` until 1.1.0 (ADR-0034 Amendment 9). Java and Kotlin write the model explorer app over the docs view, with no Node (both run the JVM DocsSiteGenerator); the classic site and the page-per-screen static export stay TypeScript's.", + "note": "It was `meta docs --site` until 1.1.0 (ADR-0034 Amendment 9). Java, Kotlin and Rust write the model explorer app over the docs view, with no Node (Java and Kotlin the JVM DocsSiteGenerator, Rust its docs-site generator); the classic site and the page-per-screen static export stay TypeScript's.", "eject": { "exempt": "The site builder is engine: it assembles the page data the site's templates read, and what an adopter changes is those templates and the assets beside them, which `meta eject docs-site` copies into codegen/docs-site/ and the generator reads from there.", "ruling": "ADR-0034 Amendment 9 (restating Amendment 8, ruling 3)" }, - "ports": ["typescript", "java", "kotlin"] + "ports": ["typescript", "java", "kotlin", "rust"] }, "plantuml": { "concept": "PlantUML class diagram of the object model.", diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 9cbba46275..84a880812c 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -1138,7 +1138,8 @@ gate_explorer_app_drift() { server/typescript/packages/docs-site/app \ server/python/src/metaobjects/documentation/explorer_app \ server/java/codegen-base/src/main/resources/metaobjects/explorer-app \ - server/csharp/MetaObjects.Codegen/ExplorerApp; do + server/csharp/MetaObjects.Codegen/ExplorerApp \ + server/rust/metaobjects-codegen/explorer-app; do diff -r -x README.md explorer-app "$copy" || { echo " stale copy: $copy (run scripts/sync-explorer-app.sh)"; rc=1; } done return $rc diff --git a/scripts/sync-explorer-app.sh b/scripts/sync-explorer-app.sh index b2891126fa..c2721210a0 100755 --- a/scripts/sync-explorer-app.sh +++ b/scripts/sync-explorer-app.sh @@ -14,6 +14,7 @@ dests=( "$root/server/python/src/metaobjects/documentation/explorer_app" "$root/server/java/codegen-base/src/main/resources/metaobjects/explorer-app" "$root/server/csharp/MetaObjects.Codegen/ExplorerApp" + "$root/server/rust/metaobjects-codegen/explorer-app" ) for dst in "${dests[@]}"; do mkdir -p "$dst" diff --git a/server/rust/metaobjects-cli/src/lib.rs b/server/rust/metaobjects-cli/src/lib.rs index 4e2570de5e..7f6a47de85 100644 --- a/server/rust/metaobjects-cli/src/lib.rs +++ b/server/rust/metaobjects-cli/src/lib.rs @@ -424,9 +424,14 @@ fn list_generators( Some(c) => format!(" [owned: {}]", c.state), None => String::new(), }; + let package_only = if r.package_only { + " [package-only]" + } else { + "" + }; let _ = writeln!( out, - "{} - {} (layer: {}){}{state}", + "{} - {} (layer: {}){}{package_only}{state}", r.name, r.summary, r.layer, diff --git a/server/rust/metaobjects-cli/tests/cli.rs b/server/rust/metaobjects-cli/tests/cli.rs index acdd2cfe2f..2293061043 100644 --- a/server/rust/metaobjects-cli/tests/cli.rs +++ b/server/rust/metaobjects-cli/tests/cli.rs @@ -278,7 +278,11 @@ fn init_writes_the_generator_list_and_gen_list_shows_it_against_what_is_availabl "{out}" ); assert_eq!(out.matches("[configured]").count(), 10, "{out}"); - assert_eq!(out.matches("[not configured]").count(), 2, "{out}"); + assert_eq!(out.matches("[not configured]").count(), 3, "{out}"); + assert!( + out.contains("(layer: docs) [not configured] [package-only]"), + "docs-site is listed as package-only: {out}" + ); // An edited list is never overwritten by a second init. p.write( "metaobjects.config.json", @@ -291,7 +295,7 @@ fn init_writes_the_generator_list_and_gen_list_shows_it_against_what_is_availabl ); let out = ok(&p.run(&["meta", "gen", "--list"])); assert!(out.contains("runs: entity\n"), "{out}"); - assert_eq!(out.matches("[not configured]").count(), 11, "{out}"); + assert_eq!(out.matches("[not configured]").count(), 12, "{out}"); } #[test] @@ -603,6 +607,14 @@ fn eject_copies_the_generator_never_overwrites_and_undo_takes_back_only_identica !p.exists("codegen"), "every name is checked before anything is written" ); + let r = p.run(&["meta", "eject", "docs-site"]); + assert_eq!(r.status.code(), Some(2)); + assert!( + text(&r.stderr).contains("docs-site stays in the package and has no copy to eject") + && text(&r.stderr).contains("codegen/docs-site/"), + "{}", + text(&r.stderr) + ); let out = ok(&p.run(&["meta", "eject", "entity"])); assert!( diff --git a/server/rust/metaobjects-codegen/explorer-app/assets/3d-force-graph.min.js b/server/rust/metaobjects-codegen/explorer-app/assets/3d-force-graph.min.js new file mode 100644 index 0000000000..3903a12250 --- /dev/null +++ b/server/rust/metaobjects-codegen/explorer-app/assets/3d-force-graph.min.js @@ -0,0 +1,1056 @@ +/*! + * 3d-force-graph 1.77.0, https://github.com/vasturiano/3d-force-graph, vendored unchanged from the + * npm package (dist/3d-force-graph.min.js) below this notice. MIT License. + * + * The build bundles these packages. Each licence follows; DOMPurify is offered under + * MPL-2.0 OR Apache-2.0 and is used here under Apache-2.0. + * + * 3d-force-graph (MIT) + * @babel/runtime (MIT) + * @tweenjs/tween.js (MIT) + * accessor-fn (MIT) + * d3-array (ISC) + * d3-binarytree (MIT) + * d3-color (ISC) + * d3-dispatch (ISC) + * d3-force-3d (MIT) + * d3-format (ISC) + * d3-interpolate (ISC) + * d3-octree (MIT) + * d3-quadtree (ISC) + * d3-scale (ISC) + * d3-scale-chromatic (ISC) + * d3-selection (ISC) + * d3-time (ISC) + * d3-time-format (ISC) + * d3-timer (ISC) + * data-bind-mapper (MIT) + * dompurify ((MPL-2.0 OR Apache-2.0)) + * float-tooltip (MIT) + * internmap (ISC) + * kapsule (MIT) + * lodash-es (MIT) + * ngraph.events (BSD-3-Clause) + * ngraph.forcelayout (BSD-3-Clause) + * ngraph.graph (BSD-3-Clause) + * ngraph.merge (MIT) + * ngraph.random (BSD-3-Clause) + * polished (MIT) + * preact (MIT) + * three (MIT) + * three-forcegraph (MIT) + * three-render-objects (MIT) + * tinycolor2 (MIT) + * + * ---- 3d-force-graph (MIT) ---- + * + * MIT License + * + * Copyright (c) 2017 Vasco Asturiano + * + * 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. + * + * ---- @babel/runtime (MIT) ---- + * + * MIT License + * + * Copyright (c) 2014-present Sebastian McKenzie and other contributors + * + * 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. + * + * ---- @tweenjs/tween.js (MIT) ---- + * + * The MIT License + * + * Copyright (c) 2010-2012 Tween.js authors. + * + * Easing equations Copyright (c) 2001 Robert Penner http://robertpenner.com/easing/ + * + * 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. + * + * ---- accessor-fn (MIT) ---- + * + * MIT License + * + * Copyright (c) 2017 Vasco Asturiano + * + * 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. + * + * ---- d3-array (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-binarytree (MIT) ---- + * + * MIT License + * + * Copyright (c) 2017 Vasco Asturiano + * + * 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. + * + * ---- d3-color (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-dispatch (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-force-3d (MIT) ---- + * + * MIT License + * + * Copyright (c) 2017 Vasco Asturiano + * + * 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. + * + * ---- d3-format (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-interpolate (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-octree (MIT) ---- + * + * MIT License + * + * Copyright (c) 2017 Vasco Asturiano + * + * 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. + * + * ---- d3-quadtree (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-scale (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-scale-chromatic (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * Apache-Style Software License for ColorBrewer software and ColorBrewer Color Schemes + * + * Copyright 2002 Cynthia Brewer, Mark Harrower, and The Pennsylvania State University + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * ---- d3-selection (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-time (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-time-format (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-timer (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- data-bind-mapper (MIT) ---- + * + * MIT License + * + * Copyright (c) 2024 Vasco Asturiano + * + * 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. + * + * ---- dompurify ((MPL-2.0 OR Apache-2.0)) ---- + * + * Apache License + * Version 2.0, January 2004 + * http://www.apache.org/licenses/ + * + * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + * + * 1. Definitions. + * + * "License" shall mean the terms and conditions for use, reproduction, + * and distribution as defined by Sections 1 through 9 of this document. + * + * "Licensor" shall mean the copyright owner or entity authorized by + * the copyright owner that is granting the License. + * + * "Legal Entity" shall mean the union of the acting entity and all + * other entities that control, are controlled by, or are under common + * control with that entity. For the purposes of this definition, + * "control" means (i) the power, direct or indirect, to cause the + * direction or management of such entity, whether by contract or + * otherwise, or (ii) ownership of fifty percent (50%) or more of the + * outstanding shares, or (iii) beneficial ownership of such entity. + * + * "You" (or "Your") shall mean an individual or Legal Entity + * exercising permissions granted by this License. + * + * "Source" form shall mean the preferred form for making modifications, + * including but not limited to software source code, documentation + * source, and configuration files. + * + * "Object" form shall mean any form resulting from mechanical + * transformation or translation of a Source form, including but + * not limited to compiled object code, generated documentation, + * and conversions to other media types. + * + * "Work" shall mean the work of authorship, whether in Source or + * Object form, made available under the License, as indicated by a + * copyright notice that is included in or attached to the work + * (an example is provided in the Appendix below). + * + * "Derivative Works" shall mean any work, whether in Source or Object + * form, that is based on (or derived from) the Work and for which the + * editorial revisions, annotations, elaborations, or other modifications + * represent, as a whole, an original work of authorship. For the purposes + * of this License, Derivative Works shall not include works that remain + * separable from, or merely link (or bind by name) to the interfaces of, + * the Work and Derivative Works thereof. + * + * "Contribution" shall mean any work of authorship, including + * the original version of the Work and any modifications or additions + * to that Work or Derivative Works thereof, that is intentionally + * submitted to Licensor for inclusion in the Work by the copyright owner + * or by an individual or Legal Entity authorized to submit on behalf of + * the copyright owner. For the purposes of this definition, "submitted" + * means any form of electronic, verbal, or written communication sent + * to the Licensor or its representatives, including but not limited to + * communication on electronic mailing lists, source code control systems, + * and issue tracking systems that are managed by, or on behalf of, the + * Licensor for the purpose of discussing and improving the Work, but + * excluding communication that is conspicuously marked or otherwise + * designated in writing by the copyright owner as "Not a Contribution." + * + * "Contributor" shall mean Licensor and any individual or Legal Entity + * on behalf of whom a Contribution has been received by Licensor and + * subsequently incorporated within the Work. + * + * 2. Grant of Copyright License. Subject to the terms and conditions of + * this License, each Contributor hereby grants to You a perpetual, + * worldwide, non-exclusive, no-charge, royalty-free, irrevocable + * copyright license to reproduce, prepare Derivative Works of, + * publicly display, publicly perform, sublicense, and distribute the + * Work and such Derivative Works in Source or Object form. + * + * 3. Grant of Patent License. Subject to the terms and conditions of + * this License, each Contributor hereby grants to You a perpetual, + * worldwide, non-exclusive, no-charge, royalty-free, irrevocable + * (except as stated in this section) patent license to make, have made, + * use, offer to sell, sell, import, and otherwise transfer the Work, + * where such license applies only to those patent claims licensable + * by such Contributor that are necessarily infringed by their + * Contribution(s) alone or by combination of their Contribution(s) + * with the Work to which such Contribution(s) was submitted. If You + * institute patent litigation against any entity (including a + * cross-claim or counterclaim in a lawsuit) alleging that the Work + * or a Contribution incorporated within the Work constitutes direct + * or contributory patent infringement, then any patent licenses + * granted to You under this License for that Work shall terminate + * as of the date such litigation is filed. + * + * 4. Redistribution. You may reproduce and distribute copies of the + * Work or Derivative Works thereof in any medium, with or without + * modifications, and in Source or Object form, provided that You + * meet the following conditions: + * + * (a) You must give any other recipients of the Work or + * Derivative Works a copy of this License; and + * + * (b) You must cause any modified files to carry prominent notices + * stating that You changed the files; and + * + * (c) You must retain, in the Source form of any Derivative Works + * that You distribute, all copyright, patent, trademark, and + * attribution notices from the Source form of the Work, + * excluding those notices that do not pertain to any part of + * the Derivative Works; and + * + * (d) If the Work includes a "NOTICE" text file as part of its + * distribution, then any Derivative Works that You distribute must + * include a readable copy of the attribution notices contained + * within such NOTICE file, excluding those notices that do not + * pertain to any part of the Derivative Works, in at least one + * of the following places: within a NOTICE text file distributed + * as part of the Derivative Works; within the Source form or + * documentation, if provided along with the Derivative Works; or, + * within a display generated by the Derivative Works, if and + * wherever such third-party notices normally appear. The contents + * of the NOTICE file are for informational purposes only and + * do not modify the License. You may add Your own attribution + * notices within Derivative Works that You distribute, alongside + * or as an addendum to the NOTICE text from the Work, provided + * that such additional attribution notices cannot be construed + * as modifying the License. + * + * You may add Your own copyright statement to Your modifications and + * may provide additional or different license terms and conditions + * for use, reproduction, or distribution of Your modifications, or + * for any such Derivative Works as a whole, provided Your use, + * reproduction, and distribution of the Work otherwise complies with + * the conditions stated in this License. + * + * 5. Submission of Contributions. Unless You explicitly state otherwise, + * any Contribution intentionally submitted for inclusion in the Work + * by You to the Licensor shall be under the terms and conditions of + * this License, without any additional terms or conditions. + * Notwithstanding the above, nothing herein shall supersede or modify + * the terms of any separate license agreement you may have executed + * with Licensor regarding such Contributions. + * + * 6. Trademarks. This License does not grant permission to use the trade + * names, trademarks, service marks, or product names of the Licensor, + * except as required for reasonable and customary use in describing the + * origin of the Work and reproducing the content of the NOTICE file. + * + * 7. Disclaimer of Warranty. Unless required by applicable law or + * agreed to in writing, Licensor provides the Work (and each + * Contributor provides its Contributions) on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied, including, without limitation, any warranties or conditions + * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + * PARTICULAR PURPOSE. You are solely responsible for determining the + * appropriateness of using or redistributing the Work and assume any + * risks associated with Your exercise of permissions under this License. + * + * 8. Limitation of Liability. In no event and under no legal theory, + * whether in tort (including negligence), contract, or otherwise, + * unless required by applicable law (such as deliberate and grossly + * negligent acts) or agreed to in writing, shall any Contributor be + * liable to You for damages, including any direct, indirect, special, + * incidental, or consequential damages of any character arising as a + * result of this License or out of the use or inability to use the + * Work (including but not limited to damages for loss of goodwill, + * work stoppage, computer failure or malfunction, or any and all + * other commercial damages or losses), even if such Contributor + * has been advised of the possibility of such damages. + * + * 9. Accepting Warranty or Additional Liability. While redistributing + * the Work or Derivative Works thereof, You may choose to offer, + * and charge a fee for, acceptance of support, warranty, indemnity, + * or other liability obligations and/or rights consistent with this + * License. However, in accepting such obligations, You may act only + * on Your own behalf and on Your sole responsibility, not on behalf + * of any other Contributor, and only if You agree to indemnify, + * defend, and hold each Contributor harmless for any liability + * incurred by, or claims asserted against, such Contributor by reason + * of your accepting any such warranty or additional liability. + * + * END OF TERMS AND CONDITIONS + * + * APPENDIX: How to apply the Apache License to your work. + * + * To apply the Apache License to your work, attach the following + * boilerplate notice, with the fields enclosed by brackets "[]" + * replaced with your own identifying information. (Don't include + * the brackets!) The text should be enclosed in the appropriate + * comment syntax for the file format. We also recommend that a + * file or class name and description of purpose be included on the + * same "printed page" as the copyright notice for easier + * identification within third-party archives. + * + * Copyright [yyyy] [name of copyright owner] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ---- float-tooltip (MIT) ---- + * + * MIT License + * + * Copyright (c) 2022 Vasco Asturiano + * + * 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. + * + * ---- internmap (ISC) ---- + * + * Copyright 2021 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- kapsule (MIT) ---- + * + * MIT License + * + * Copyright (c) 2017 Vasco Asturiano + * + * 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. + * + * ---- lodash-es (MIT) ---- + * + * Copyright OpenJS Foundation and other contributors + * + * Based on Underscore.js, copyright Jeremy Ashkenas, + * DocumentCloud and Investigative Reporters & Editors + * + * This software consists of voluntary contributions made by many + * individuals. For exact contribution history, see the revision history + * available at https://github.com/lodash/lodash + * + * The following license applies to all parts of this software except as + * documented below: + * + * ==== + * + * 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. + * + * ==== + * + * Copyright and related rights for sample code are waived via CC0. Sample + * code is defined as all source code displayed within the prose of the + * documentation. + * + * CC0: http://creativecommons.org/publicdomain/zero/1.0/ + * + * ==== + * + * Files located in the node_modules and vendor directories are externally + * maintained libraries used by this software which have their own + * licenses; we recommend you read them, as their terms may differ from the + * terms above. + * + * ---- ngraph.events (BSD-3-Clause) ---- + * + * Copyright (c) 2013-2025 Andrei Kashcha + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * Neither the name of the Andrei Kashcha nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * ---- ngraph.forcelayout (BSD-3-Clause) ---- + * + * Copyright (c) 2013 - 2022, Andrei Kashcha + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * * Neither the name of the Andrei Kashcha nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * ---- ngraph.graph (BSD-3-Clause) ---- + * + * Copyright (c) 2013 - 2026, Andrei Kashcha + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * Neither the name of the Andrei Kashcha nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * ---- ngraph.merge (MIT) ---- + * + * The MIT License (MIT) + * + * Copyright (c) 2013-2019 Andrei Kashcha + * + * 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. + * + * ---- ngraph.random (BSD-3-Clause) ---- + * + * Copyright (c) 2013-2025, Andrei Kashcha + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * Neither the name of the Andrei Kashcha nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * ---- polished (MIT) ---- + * + * MIT License + * + * Copyright (c) 2016-Present Brian Hough and Maximilian Stoiber + * + * 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. + * + * ---- preact (MIT) ---- + * + * The MIT License (MIT) + * + * Copyright (c) 2015-present Jason Miller + * + * 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. + * + * ---- three (MIT) ---- + * + * The MIT License + * + * Copyright © 2010-2026 three.js authors + * + * 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. + * + * ---- three-forcegraph (MIT) ---- + * + * MIT License + * + * Copyright (c) 2017 Vasco Asturiano + * + * 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. + * + * ---- three-render-objects (MIT) ---- + * + * MIT License + * + * Copyright (c) 2018 Vasco Asturiano + * + * 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. + * + * ---- tinycolor2 (MIT) ---- + * + * Copyright (c), Brian Grinstead, http://briangrinstead.com + * + * 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. + */ +// Version 1.77.0 3d-force-graph - https://github.com/vasturiano/3d-force-graph +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).ForceGraph3D=t()}(this,(function(){"use strict";function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n>8&255]+Mt[e>>16&255]+Mt[e>>24&255]+"-"+Mt[255&t]+Mt[t>>8&255]+"-"+Mt[t>>16&15|64]+Mt[t>>24&255]+"-"+Mt[63&n|128]+Mt[n>>8&255]+"-"+Mt[n>>16&255]+Mt[n>>24&255]+Mt[255&i]+Mt[i>>8&255]+Mt[i>>16&255]+Mt[i>>24&255]).toLowerCase()}function Ct(e,t,n){return Math.max(t,Math.min(n,e))}function Nt(e,t){return(e%t+t)%t}function Pt(e,t,n){return(1-n)*e+n*t}function Dt(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 new Error("Invalid component type.")}}function Ut(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(4294967295*e);case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int32Array:return Math.round(2147483647*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw new Error("Invalid component type.")}}const Lt={DEG2RAD:wt,RAD2DEG:At,generateUUID:Rt,clamp:Ct,euclideanModulo:Nt,mapLinear:function(e,t,n,i,r){return i+(e-t)*(r-i)/(n-t)},inverseLerp:function(e,t,n){return e!==t?(n-e)/(t-e):0},lerp:Pt,damp:function(e,t,n,i){return Pt(e,t,1-Math.exp(-n*i))},pingpong:function(e,t=1){return t-Math.abs(Nt(e,2*t)-t)},smoothstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*(3-2*e)},smootherstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){void 0!==e&&(Et=e);let t=Et+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296},degToRad:function(e){return e*wt},radToDeg:function(e){return e*At},isPowerOfTwo:function(e){return!(e&e-1)&&0!==e},ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:function(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))},setQuaternionFromProperEuler:function(e,t,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),u=s((t+i)/2),c=a((t+i)/2),h=s((t-i)/2),d=a((t-i)/2),p=s((i-t)/2),f=a((i-t)/2);switch(r){case"XYX":e.set(o*c,l*h,l*d,o*u);break;case"YZY":e.set(l*d,o*c,l*h,o*u);break;case"ZXZ":e.set(l*h,l*d,o*c,o*u);break;case"XZX":e.set(o*c,l*f,l*p,o*u);break;case"YXY":e.set(l*p,o*c,l*f,o*u);break;case"ZYZ":e.set(l*f,l*p,o*c,o*u);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:Ut,denormalize:Dt};class It{constructor(e=0,t=0){It.prototype.isVector2=!0,this.x=e,this.y=t}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 new 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 new 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){const t=this.x,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[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=Ct(this.x,e.x,t.x),this.y=Ct(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Ct(this.x,e,t),this.y=Ct(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Ct(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){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Ct(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const 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){const n=Math.cos(t),i=Math.sin(t),r=this.x-e.x,s=this.y-e.y;return this.x=r*n-s*i+e.x,this.y=r*i+s*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Ot{constructor(e,t,n,i,r,s,a,o,l){Ot.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,n,i,r,s,a,o,l)}set(e,t,n,i,r,s,a,o,l){const u=this.elements;return u[0]=e,u[1]=i,u[2]=a,u[3]=t,u[4]=r,u[5]=o,u[6]=n,u[7]=s,u[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const 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){const 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){const n=e.elements,i=t.elements,r=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],u=n[4],c=n[7],h=n[2],d=n[5],p=n[8],f=i[0],m=i[3],g=i[6],_=i[1],v=i[4],y=i[7],x=i[2],b=i[5],S=i[8];return r[0]=s*f+a*_+o*x,r[3]=s*m+a*v+o*b,r[6]=s*g+a*y+o*S,r[1]=l*f+u*_+c*x,r[4]=l*m+u*v+c*b,r[7]=l*g+u*y+c*S,r[2]=h*f+d*_+p*x,r[5]=h*m+d*v+p*b,r[8]=h*g+d*y+p*S,this}multiplyScalar(e){const 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(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8];return t*s*u-t*a*l-n*r*u+n*a*o+i*r*l-i*s*o}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=u*s-a*l,h=a*o-u*r,d=l*r-s*o,p=t*c+n*h+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const f=1/p;return e[0]=c*f,e[1]=(i*l-u*n)*f,e[2]=(a*n-i*s)*f,e[3]=h*f,e[4]=(u*t-i*o)*f,e[5]=(i*r-a*t)*f,e[6]=d*f,e[7]=(n*o-l*t)*f,e[8]=(s*t-n*r)*f,this}transpose(){let e;const 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){const 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,i,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(n*o,n*l,-n*(o*s+l*a)+s+e,-i*l,i*o,-i*(-l*s+o*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(Ft.makeScale(e,t)),this}rotate(e){return this.premultiply(Ft.makeRotation(-e)),this}translate(e,t){return this.premultiply(Ft.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){const 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){const 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){const 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)}}const Ft=new Ot;function Bt(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 zt(){const e=kt("canvas");return e.style.display="block",e}const Gt={};function Vt(e){e in Gt||(Gt[e]=!0,console.warn(e))}const Ht=(new Ot).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),jt=(new Ot).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Wt(){const e={enabled:!0,workingColorSpace:at,spaces:{},convert:function(e,t,n){return!1!==this.enabled&&t!==n&&t&&n?(this.spaces[t].transfer===lt&&(e.r=qt(e.r),e.g=qt(e.g),e.b=qt(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===lt&&(e.r=$t(e.r),e.g=$t(e.g),e.b=$t(e.b)),e):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===rt?ot: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],i=[.3127,.329];return e.define({[at]:{primaries:t,whitePoint:i,transfer:ot,toXYZ:Ht,fromXYZ:jt,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:st},outputColorSpaceConfig:{drawingBufferColorSpace:st}},[st]:{primaries:t,whitePoint:i,transfer:lt,toXYZ:Ht,fromXYZ:jt,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:st}}}),e}const Xt=Wt();function qt(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function $t(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let Yt;class Kt{static getDataURL(e){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{void 0===Yt&&(Yt=kt("canvas")),Yt.width=e.width,Yt.height=e.height;const n=Yt.getContext("2d");e instanceof ImageData?n.putImageData(e,0,0):n.drawImage(e,0,0,e.width,e.height),t=Yt}return t.toDataURL("image/png")}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=kt("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const i=n.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(300!==this.mapping)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case q:e.x=e.x-Math.floor(e.x);break;case $:e.x=e.x<0?0:1;break;case Y:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case q:e.y=e.y-Math.floor(e.y);break;case $:e.y=e.y<0?0:1;break;case Y:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){!0===e&&this.pmremVersion++}}tn.DEFAULT_IMAGE=null,tn.DEFAULT_MAPPING=300,tn.DEFAULT_ANISOTROPY=1;class nn{constructor(e=0,t=0,n=0,i=1){nn.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,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,i){return this.x=e,this.y=t,this.z=n,this.w=i,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 new 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 new 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=void 0!==e.w?e.w:1,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){const t=this.x,n=this.y,i=this.z,r=this.w,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*t+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*t+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*t+s[7]*n+s[11]*i+s[15]*r,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);const 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,i,r;const s=.01,a=.1,o=e.elements,l=o[0],u=o[4],c=o[8],h=o[1],d=o[5],p=o[9],f=o[2],m=o[6],g=o[10];if(Math.abs(u-h)o&&e>_?e_?o=0?1:-1,i=1-t*t;if(i>Number.EPSILON){const r=Math.sqrt(i),s=Math.atan2(r,t*n);e=Math.sin(e*s)/r,a=Math.sin(a*s)/r}const r=a*n;if(o=o*e+h*r,l=l*e+d*r,u=u*e+p*r,c=c*e+f*r,e===1-a){const e=1/Math.sqrt(o*o+l*l+u*u+c*c);o*=e,l*=e,u*=e,c*=e}}e[t]=o,e[t+1]=l,e[t+2]=u,e[t+3]=c}static multiplyQuaternionsFlat(e,t,n,i,r,s){const a=n[i],o=n[i+1],l=n[i+2],u=n[i+3],c=r[s],h=r[s+1],d=r[s+2],p=r[s+3];return e[t]=a*p+u*c+o*d-l*h,e[t+1]=o*p+u*h+l*c-a*d,e[t+2]=l*p+u*d+a*h-o*c,e[t+3]=u*p-a*c-o*h-l*d,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,i){return this._x=e,this._y=t,this._z=n,this._w=i,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){const n=e._x,i=e._y,r=e._z,s=e._order,a=Math.cos,o=Math.sin,l=a(n/2),u=a(i/2),c=a(r/2),h=o(n/2),d=o(i/2),p=o(r/2);switch(s){case"XYZ":this._x=h*u*c+l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c-h*d*p;break;case"YXZ":this._x=h*u*c+l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c+h*d*p;break;case"ZXY":this._x=h*u*c-l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c-h*d*p;break;case"ZYX":this._x=h*u*c-l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c+h*d*p;break;case"YZX":this._x=h*u*c+l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c-h*d*p;break;case"XZY":this._x=h*u*c-l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c+h*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],i=t[4],r=t[8],s=t[1],a=t[5],o=t[9],l=t[2],u=t[6],c=t[10],h=n+a+c;if(h>0){const e=.5/Math.sqrt(h+1);this._w=.25/e,this._x=(u-o)*e,this._y=(r-l)*e,this._z=(s-i)*e}else if(n>a&&n>c){const e=2*Math.sqrt(1+n-a-c);this._w=(u-o)/e,this._x=.25*e,this._y=(i+s)/e,this._z=(r+l)/e}else if(a>c){const e=2*Math.sqrt(1+a-n-c);this._w=(r-l)/e,this._x=(i+s)/e,this._y=.25*e,this._z=(o+u)/e}else{const e=2*Math.sqrt(1+c-n-a);this._w=(s-i)/e,this._x=(r+l)/e,this._y=(o+u)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return nMath.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(Ct(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(0===n)return this;const i=Math.min(1,t/n);return this.slerp(e,i),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 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,i=e._y,r=e._z,s=e._w,a=t._x,o=t._y,l=t._z,u=t._w;return this._x=n*u+s*a+i*l-r*o,this._y=i*u+s*o+r*a-n*l,this._z=r*u+s*l+n*o-i*a,this._w=s*u-n*a-i*o-r*l,this._onChangeCallback(),this}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);const n=this._x,i=this._y,r=this._z,s=this._w;let a=s*e._w+n*e._x+i*e._y+r*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=s,this._x=n,this._y=i,this._z=r,this;const o=1-a*a;if(o<=Number.EPSILON){const e=1-t;return this._w=e*s+t*this._w,this._x=e*n+t*this._x,this._y=e*i+t*this._y,this._z=e*r+t*this._z,this.normalize(),this}const l=Math.sqrt(o),u=Math.atan2(l,a),c=Math.sin((1-t)*u)/l,h=Math.sin(t*u)/l;return this._w=s*c+this._w*h,this._x=n*c+this._x*h,this._y=i*c+this._y*h,this._z=r*c+this._z*h,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(i*Math.sin(e),i*Math.cos(e),r*Math.sin(t),r*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}}class un{constructor(e=0,t=0,n=0){un.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return void 0===n&&(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 new 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 new 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(hn.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(hn.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*i,this.y=r[1]*t+r[4]*n+r[7]*i,this.z=r[2]*t+r[5]*n+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=e.elements,s=1/(r[3]*t+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*t+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*t+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(e){const t=this.x,n=this.y,i=this.z,r=e.x,s=e.y,a=e.z,o=e.w,l=2*(s*i-a*n),u=2*(a*t-r*i),c=2*(r*n-s*t);return this.x=t+o*l+s*c-a*u,this.y=n+o*u+a*l-r*c,this.z=i+o*c+r*u-s*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*i,this.y=r[1]*t+r[5]*n+r[9]*i,this.z=r[2]*t+r[6]*n+r[10]*i,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=Ct(this.x,e.x,t.x),this.y=Ct(this.y,e.y,t.y),this.z=Ct(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Ct(this.x,e,t),this.y=Ct(this.y,e,t),this.z=Ct(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Ct(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){const n=e.x,i=e.y,r=e.z,s=t.x,a=t.y,o=t.z;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-i*s,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return cn.copy(this).projectOnVector(e),this.sub(cn)}reflect(e){return this.sub(cn.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Ct(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}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){const i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*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){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}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(){const e=Math.random()*Math.PI*2,t=2*Math.random()-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}}const cn=new un,hn=new ln;class dn{constructor(e=new un(1/0,1/0,1/0),t=new un(-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=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,fn),fn.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(Sn),Tn.subVectors(this.max,Sn),gn.subVectors(e.a,Sn),_n.subVectors(e.b,Sn),vn.subVectors(e.c,Sn),yn.subVectors(_n,gn),xn.subVectors(vn,_n),bn.subVectors(gn,vn);let t=[0,-yn.z,yn.y,0,-xn.z,xn.y,0,-bn.z,bn.y,yn.z,0,-yn.x,xn.z,0,-xn.x,bn.z,0,-bn.x,-yn.y,yn.x,0,-xn.y,xn.x,0,-bn.y,bn.x,0];return!!wn(t,gn,_n,vn,Tn)&&(t=[1,0,0,0,1,0,0,0,1],!!wn(t,gn,_n,vn,Tn)&&(Mn.crossVectors(yn,xn),t=[Mn.x,Mn.y,Mn.z],wn(t,gn,_n,vn,Tn)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,fn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(fn).length()),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()||(pn[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),pn[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),pn[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),pn[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),pn[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),pn[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),pn[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),pn[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(pn)),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)}}const pn=[new un,new un,new un,new un,new un,new un,new un,new un],fn=new un,mn=new dn,gn=new un,_n=new un,vn=new un,yn=new un,xn=new un,bn=new un,Sn=new un,Tn=new un,Mn=new un,En=new un;function wn(e,t,n,i,r){for(let s=0,a=e.length-3;s<=a;s+=3){En.fromArray(e,s);const a=r.x*Math.abs(En.x)+r.y*Math.abs(En.y)+r.z*Math.abs(En.z),o=t.dot(En),l=n.dot(En),u=i.dot(En);if(Math.max(-Math.max(o,l,u),Math.min(o,l,u))>a)return!1}return!0}const An=new dn,Rn=new un,Cn=new un;class Nn{constructor(e=new un,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){const n=this.center;void 0!==t?n.copy(t):An.setFromPoints(e).getCenter(n);let i=0;for(let t=0,r=e.length;tthis.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=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;Rn.subVectors(e,this.center);const t=Rn.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),n=.5*(e-this.radius);this.center.addScaledVector(Rn,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(Cn.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Rn.copy(e.center).add(Cn)),this.expandByPoint(Rn.copy(e.center).sub(Cn))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const Pn=new un,Dn=new un,Un=new un,Ln=new un,In=new un,On=new un,Fn=new un;class Bn{constructor(e=new un,t=new un(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,Pn)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const 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){const t=Pn.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Pn.copy(this.origin).addScaledVector(this.direction,t),Pn.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){Dn.copy(e).add(t).multiplyScalar(.5),Un.copy(t).sub(e).normalize(),Ln.copy(this.origin).sub(Dn);const r=.5*e.distanceTo(t),s=-this.direction.dot(Un),a=Ln.dot(this.direction),o=-Ln.dot(Un),l=Ln.lengthSq(),u=Math.abs(1-s*s);let c,h,d,p;if(u>0)if(c=s*o-a,h=s*a-o,p=r*u,c>=0)if(h>=-p)if(h<=p){const e=1/u;c*=e,h*=e,d=c*(c+s*h+2*a)+h*(s*c+h+2*o)+l}else h=r,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;else h=-r,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;else h<=-p?(c=Math.max(0,-(-s*r+a)),h=c>0?-r:Math.min(Math.max(-r,-o),r),d=-c*c+h*(h+2*o)+l):h<=p?(c=0,h=Math.min(Math.max(-r,-o),r),d=h*(h+2*o)+l):(c=Math.max(0,-(s*r+a)),h=c>0?r:Math.min(Math.max(-r,-o),r),d=-c*c+h*(h+2*o)+l);else h=s>0?-r:r,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,c),i&&i.copy(Dn).addScaledVector(Un,h),d}intersectSphere(e,t){Pn.subVectors(e.center,this.origin);const n=Pn.dot(this.direction),i=Pn.dot(Pn)-n*n,r=e.radius*e.radius;if(i>r)return null;const s=Math.sqrt(r-i),a=n-s,o=n+s;return o<0?null:a<0?this.at(o,t):this.at(a,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return null===n?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return!0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,r,s,a,o;const l=1/this.direction.x,u=1/this.direction.y,c=1/this.direction.z,h=this.origin;return l>=0?(n=(e.min.x-h.x)*l,i=(e.max.x-h.x)*l):(n=(e.max.x-h.x)*l,i=(e.min.x-h.x)*l),u>=0?(r=(e.min.y-h.y)*u,s=(e.max.y-h.y)*u):(r=(e.max.y-h.y)*u,s=(e.min.y-h.y)*u),n>s||r>i?null:((r>n||isNaN(n))&&(n=r),(s=0?(a=(e.min.z-h.z)*c,o=(e.max.z-h.z)*c):(a=(e.max.z-h.z)*c,o=(e.min.z-h.z)*c),n>o||a>i?null:((a>n||n!=n)&&(n=a),(o=0?n:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,Pn)}intersectTriangle(e,t,n,i,r){In.subVectors(t,e),On.subVectors(n,e),Fn.crossVectors(In,On);let s,a=this.direction.dot(Fn);if(a>0){if(i)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}Ln.subVectors(this.origin,e);const o=s*this.direction.dot(On.crossVectors(Ln,On));if(o<0)return null;const l=s*this.direction.dot(In.cross(Ln));if(l<0)return null;if(o+l>a)return null;const u=-s*Ln.dot(Fn);return u<0?null:this.at(u/a,r)}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)}}class kn{constructor(e,t,n,i,r,s,a,o,l,u,c,h,d,p,f,m){kn.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,n,i,r,s,a,o,l,u,c,h,d,p,f,m)}set(e,t,n,i,r,s,a,o,l,u,c,h,d,p,f,m){const g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=u,g[10]=c,g[14]=h,g[3]=d,g[7]=p,g[11]=f,g[15]=m,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 kn).fromArray(this.elements)}copy(e){const 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){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const 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){const t=this.elements,n=e.elements,i=1/zn.setFromMatrixColumn(e,0).length(),r=1/zn.setFromMatrixColumn(e,1).length(),s=1/zn.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*s,t[9]=n[9]*s,t[10]=n[10]*s,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,i=e.y,r=e.z,s=Math.cos(n),a=Math.sin(n),o=Math.cos(i),l=Math.sin(i),u=Math.cos(r),c=Math.sin(r);if("XYZ"===e.order){const e=s*u,n=s*c,i=a*u,r=a*c;t[0]=o*u,t[4]=-o*c,t[8]=l,t[1]=n+i*l,t[5]=e-r*l,t[9]=-a*o,t[2]=r-e*l,t[6]=i+n*l,t[10]=s*o}else if("YXZ"===e.order){const e=o*u,n=o*c,i=l*u,r=l*c;t[0]=e+r*a,t[4]=i*a-n,t[8]=s*l,t[1]=s*c,t[5]=s*u,t[9]=-a,t[2]=n*a-i,t[6]=r+e*a,t[10]=s*o}else if("ZXY"===e.order){const e=o*u,n=o*c,i=l*u,r=l*c;t[0]=e-r*a,t[4]=-s*c,t[8]=i+n*a,t[1]=n+i*a,t[5]=s*u,t[9]=r-e*a,t[2]=-s*l,t[6]=a,t[10]=s*o}else if("ZYX"===e.order){const e=s*u,n=s*c,i=a*u,r=a*c;t[0]=o*u,t[4]=i*l-n,t[8]=e*l+r,t[1]=o*c,t[5]=r*l+e,t[9]=n*l-i,t[2]=-l,t[6]=a*o,t[10]=s*o}else if("YZX"===e.order){const e=s*o,n=s*l,i=a*o,r=a*l;t[0]=o*u,t[4]=r-e*c,t[8]=i*c+n,t[1]=c,t[5]=s*u,t[9]=-a*u,t[2]=-l*u,t[6]=n*c+i,t[10]=e-r*c}else if("XZY"===e.order){const e=s*o,n=s*l,i=a*o,r=a*l;t[0]=o*u,t[4]=-c,t[8]=l*u,t[1]=e*c+r,t[5]=s*u,t[9]=n*c-i,t[2]=i*c-n,t[6]=a*u,t[10]=r*c+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(Vn,e,Hn)}lookAt(e,t,n){const i=this.elements;return Xn.subVectors(e,t),0===Xn.lengthSq()&&(Xn.z=1),Xn.normalize(),jn.crossVectors(n,Xn),0===jn.lengthSq()&&(1===Math.abs(n.z)?Xn.x+=1e-4:Xn.z+=1e-4,Xn.normalize(),jn.crossVectors(n,Xn)),jn.normalize(),Wn.crossVectors(Xn,jn),i[0]=jn.x,i[4]=Wn.x,i[8]=Xn.x,i[1]=jn.y,i[5]=Wn.y,i[9]=Xn.y,i[2]=jn.z,i[6]=Wn.z,i[10]=Xn.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,i=t.elements,r=this.elements,s=n[0],a=n[4],o=n[8],l=n[12],u=n[1],c=n[5],h=n[9],d=n[13],p=n[2],f=n[6],m=n[10],g=n[14],_=n[3],v=n[7],y=n[11],x=n[15],b=i[0],S=i[4],T=i[8],M=i[12],E=i[1],w=i[5],A=i[9],R=i[13],C=i[2],N=i[6],P=i[10],D=i[14],U=i[3],L=i[7],I=i[11],O=i[15];return r[0]=s*b+a*E+o*C+l*U,r[4]=s*S+a*w+o*N+l*L,r[8]=s*T+a*A+o*P+l*I,r[12]=s*M+a*R+o*D+l*O,r[1]=u*b+c*E+h*C+d*U,r[5]=u*S+c*w+h*N+d*L,r[9]=u*T+c*A+h*P+d*I,r[13]=u*M+c*R+h*D+d*O,r[2]=p*b+f*E+m*C+g*U,r[6]=p*S+f*w+m*N+g*L,r[10]=p*T+f*A+m*P+g*I,r[14]=p*M+f*R+m*D+g*O,r[3]=_*b+v*E+y*C+x*U,r[7]=_*S+v*w+y*N+x*L,r[11]=_*T+v*A+y*P+x*I,r[15]=_*M+v*R+y*D+x*O,this}multiplyScalar(e){const 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(){const e=this.elements,t=e[0],n=e[4],i=e[8],r=e[12],s=e[1],a=e[5],o=e[9],l=e[13],u=e[2],c=e[6],h=e[10],d=e[14];return e[3]*(+r*o*c-i*l*c-r*a*h+n*l*h+i*a*d-n*o*d)+e[7]*(+t*o*d-t*l*h+r*s*h-i*s*d+i*l*u-r*o*u)+e[11]*(+t*l*c-t*a*d-r*s*c+n*s*d+r*a*u-n*l*u)+e[15]*(-i*a*u-t*o*c+t*a*h+i*s*c-n*s*h+n*o*u)}transpose(){const e=this.elements;let 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){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=e[9],h=e[10],d=e[11],p=e[12],f=e[13],m=e[14],g=e[15],_=c*m*l-f*h*l+f*o*d-a*m*d-c*o*g+a*h*g,v=p*h*l-u*m*l-p*o*d+s*m*d+u*o*g-s*h*g,y=u*f*l-p*c*l+p*a*d-s*f*d-u*a*g+s*c*g,x=p*c*o-u*f*o-p*a*h+s*f*h+u*a*m-s*c*m,b=t*_+n*v+i*y+r*x;if(0===b)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const S=1/b;return e[0]=_*S,e[1]=(f*h*r-c*m*r-f*i*d+n*m*d+c*i*g-n*h*g)*S,e[2]=(a*m*r-f*o*r+f*i*l-n*m*l-a*i*g+n*o*g)*S,e[3]=(c*o*r-a*h*r-c*i*l+n*h*l+a*i*d-n*o*d)*S,e[4]=v*S,e[5]=(u*m*r-p*h*r+p*i*d-t*m*d-u*i*g+t*h*g)*S,e[6]=(p*o*r-s*m*r-p*i*l+t*m*l+s*i*g-t*o*g)*S,e[7]=(s*h*r-u*o*r+u*i*l-t*h*l-s*i*d+t*o*d)*S,e[8]=y*S,e[9]=(p*c*r-u*f*r-p*n*d+t*f*d+u*n*g-t*c*g)*S,e[10]=(s*f*r-p*a*r+p*n*l-t*f*l-s*n*g+t*a*g)*S,e[11]=(u*a*r-s*c*r-u*n*l+t*c*l+s*n*d-t*a*d)*S,e[12]=x*S,e[13]=(u*f*i-p*c*i+p*n*h-t*f*h-u*n*m+t*c*m)*S,e[14]=(p*a*i-s*f*i-p*n*o+t*f*o+s*n*m-t*a*m)*S,e[15]=(s*c*i-u*a*i+u*n*o-t*c*o-s*n*h+t*a*h)*S,this}scale(e){const t=this.elements,n=e.x,i=e.y,r=e.z;return t[0]*=n,t[4]*=i,t[8]*=r,t[1]*=n,t[5]*=i,t[9]*=r,t[2]*=n,t[6]*=i,t[10]*=r,t[3]*=n,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const 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],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}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){const 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){const 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){const 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){const n=Math.cos(t),i=Math.sin(t),r=1-n,s=e.x,a=e.y,o=e.z,l=r*s,u=r*a;return this.set(l*s+n,l*a-i*o,l*o+i*a,0,l*a+i*o,u*a+n,u*o-i*s,0,l*o-i*a,u*o+i*s,r*o*o+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,i,r,s){return this.set(1,n,r,0,e,1,s,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){const i=this.elements,r=t._x,s=t._y,a=t._z,o=t._w,l=r+r,u=s+s,c=a+a,h=r*l,d=r*u,p=r*c,f=s*u,m=s*c,g=a*c,_=o*l,v=o*u,y=o*c,x=n.x,b=n.y,S=n.z;return i[0]=(1-(f+g))*x,i[1]=(d+y)*x,i[2]=(p-v)*x,i[3]=0,i[4]=(d-y)*b,i[5]=(1-(h+g))*b,i[6]=(m+_)*b,i[7]=0,i[8]=(p+v)*S,i[9]=(m-_)*S,i[10]=(1-(h+f))*S,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){const i=this.elements;let r=zn.set(i[0],i[1],i[2]).length();const s=zn.set(i[4],i[5],i[6]).length(),a=zn.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),e.x=i[12],e.y=i[13],e.z=i[14],Gn.copy(this);const o=1/r,l=1/s,u=1/a;return Gn.elements[0]*=o,Gn.elements[1]*=o,Gn.elements[2]*=o,Gn.elements[4]*=l,Gn.elements[5]*=l,Gn.elements[6]*=l,Gn.elements[8]*=u,Gn.elements[9]*=u,Gn.elements[10]*=u,t.setFromRotationMatrix(Gn),n.x=r,n.y=s,n.z=a,this}makePerspective(e,t,n,i,r,s,a=2e3){const o=this.elements,l=2*r/(t-e),u=2*r/(n-i),c=(t+e)/(t-e),h=(n+i)/(n-i);let d,p;if(a===bt)d=-(s+r)/(s-r),p=-2*s*r/(s-r);else{if(a!==St)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);d=-s/(s-r),p=-s*r/(s-r)}return o[0]=l,o[4]=0,o[8]=c,o[12]=0,o[1]=0,o[5]=u,o[9]=h,o[13]=0,o[2]=0,o[6]=0,o[10]=d,o[14]=p,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(e,t,n,i,r,s,a=2e3){const o=this.elements,l=1/(t-e),u=1/(n-i),c=1/(s-r),h=(t+e)*l,d=(n+i)*u;let p,f;if(a===bt)p=(s+r)*c,f=-2*c;else{if(a!==St)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=r*c,f=-1*c}return o[0]=2*l,o[4]=0,o[8]=0,o[12]=-h,o[1]=0,o[5]=2*u,o[9]=0,o[13]=-d,o[2]=0,o[6]=0,o[10]=f,o[14]=-p,o[3]=0,o[7]=0,o[11]=0,o[15]=1,this}equals(e){const 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){const 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}}const zn=new un,Gn=new kn,Vn=new un(0,0,0),Hn=new un(1,1,1),jn=new un,Wn=new un,Xn=new un,qn=new kn,$n=new ln;class Yn{constructor(e=0,t=0,n=0,i=Yn.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,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,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,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){const i=e.elements,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],u=i[9],c=i[2],h=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(Ct(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(h,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Ct(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-c,r),this._z=0);break;case"ZXY":this._x=Math.asin(Ct(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-c,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-Ct(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(h,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(Ct(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,l),this._y=Math.atan2(-c,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-Ct(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(h,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-u,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===n&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return qn.makeRotationFromQuaternion(e),this.setFromRotationMatrix(qn,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return $n.setFromEuler(this),this.setFromQuaternion($n,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],void 0!==e[3]&&(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}}Yn.DEFAULT_ORDER="XYZ";class Kn{constructor(){this.mask=1}set(e){this.mask=1<>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map((e=>({boxInitialized:e.boxInitialized,boxMin:e.box.min.toArray(),boxMax:e.box.max.toArray(),sphereInitialized:e.sphereInitialized,sphereRadius:e.sphere.radius,sphereCenter:e.sphere.center.toArray()}))),i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),null!==this.boundingBox&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()})),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const n=t.shapes;if(Array.isArray(n))for(let t=0,i=n.length;t0){i.children=[];for(let t=0;t0){i.animations=[];for(let t=0;t0&&(n.geometries=t),i.length>0&&(n.materials=i),r.length>0&&(n.textures=r),a.length>0&&(n.images=a),o.length>0&&(n.shapes=o),l.length>0&&(n.skeletons=l),u.length>0&&(n.animations=u),c.length>0&&(n.nodes=c)}return n.object=i,n;function s(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}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)),!0===t)for(let t=0;t0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,n,i,r){pi.subVectors(i,t),fi.subVectors(n,t),mi.subVectors(e,t);const s=pi.dot(pi),a=pi.dot(fi),o=pi.dot(mi),l=fi.dot(fi),u=fi.dot(mi),c=s*l-a*a;if(0===c)return r.set(0,0,0),null;const h=1/c,d=(l*o-a*u)*h,p=(s*u-a*o)*h;return r.set(1-d-p,p,d)}static containsPoint(e,t,n,i){return null!==this.getBarycoord(e,t,n,i,gi)&&(gi.x>=0&&gi.y>=0&&gi.x+gi.y<=1)}static getInterpolation(e,t,n,i,r,s,a,o){return null===this.getBarycoord(e,t,n,i,gi)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(r,gi.x),o.addScaledVector(s,gi.y),o.addScaledVector(a,gi.z),o)}static getInterpolatedAttribute(e,t,n,i,r,s){return Ti.setScalar(0),Mi.setScalar(0),Ei.setScalar(0),Ti.fromBufferAttribute(e,t),Mi.fromBufferAttribute(e,n),Ei.fromBufferAttribute(e,i),s.setScalar(0),s.addScaledVector(Ti,r.x),s.addScaledVector(Mi,r.y),s.addScaledVector(Ei,r.z),s}static isFrontFacing(e,t,n,i){return pi.subVectors(n,t),fi.subVectors(e,t),pi.cross(fi).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),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 pi.subVectors(this.c,this.b),fi.subVectors(this.a,this.b),.5*pi.cross(fi).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return wi.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return wi.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,r){return wi.getInterpolation(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return wi.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return wi.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,i=this.b,r=this.c;let s,a;_i.subVectors(i,n),vi.subVectors(r,n),xi.subVectors(e,n);const o=_i.dot(xi),l=vi.dot(xi);if(o<=0&&l<=0)return t.copy(n);bi.subVectors(e,i);const u=_i.dot(bi),c=vi.dot(bi);if(u>=0&&c<=u)return t.copy(i);const h=o*c-u*l;if(h<=0&&o>=0&&u<=0)return s=o/(o-u),t.copy(n).addScaledVector(_i,s);Si.subVectors(e,r);const d=_i.dot(Si),p=vi.dot(Si);if(p>=0&&d<=p)return t.copy(r);const f=d*l-o*p;if(f<=0&&l>=0&&p<=0)return a=l/(l-p),t.copy(n).addScaledVector(vi,a);const m=u*p-d*c;if(m<=0&&c-u>=0&&d-p>=0)return yi.subVectors(r,i),a=(c-u)/(c-u+(d-p)),t.copy(i).addScaledVector(yi,a);const g=1/(m+f+h);return s=f*g,a=h*g,t.copy(n).addScaledVector(_i,s).addScaledVector(vi,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Ai={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},Ri={h:0,s:0,l:0},Ci={h:0,s:0,l:0};function Ni(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+6*(t-e)*(2/3-n):e}class Pi{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(void 0===t&&void 0===n){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&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=st){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,Xt.toWorkingColorSpace(this,t),this}setRGB(e,t,n,i=Xt.workingColorSpace){return this.r=e,this.g=t,this.b=n,Xt.toWorkingColorSpace(this,i),this}setHSL(e,t,n,i=Xt.workingColorSpace){if(e=Nt(e,1),t=Ct(t,0,1),n=Ct(n,0,1),0===t)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+t):n+t-n*t,r=2*n-i;this.r=Ni(r,i,e+1/3),this.g=Ni(r,i,e),this.b=Ni(r,i,e-1/3)}return Xt.toWorkingColorSpace(this,i),this}setStyle(e,t=st){function n(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const s=i[1],a=i[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const n=i[1],r=n.length;if(3===r)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(6===r)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=st){const n=Ai[e.toLowerCase()];return void 0!==n?this.setHex(n,t):console.warn("THREE.Color: Unknown color "+e),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=qt(e.r),this.g=qt(e.g),this.b=qt(e.b),this}copyLinearToSRGB(e){return this.r=$t(e.r),this.g=$t(e.g),this.b=$t(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=st){return Xt.fromWorkingColorSpace(Di.copy(this),e),65536*Math.round(Ct(255*Di.r,0,255))+256*Math.round(Ct(255*Di.g,0,255))+Math.round(Ct(255*Di.b,0,255))}getHexString(e=st){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Xt.workingColorSpace){Xt.fromWorkingColorSpace(Di.copy(this),t);const n=Di.r,i=Di.g,r=Di.b,s=Math.max(n,i,r),a=Math.min(n,i,r);let o,l;const u=(a+s)/2;if(a===s)o=0,l=0;else{const e=s-a;switch(l=u<=.5?e/(s+a):e/(2-s-a),s){case n:o=(i-r)/e+(i0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const n=e[t];if(void 0===n){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n:console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const n={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),void 0!==this.sheen&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(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()),void 0!==this.dispersion&&(n.dispersion=this.dispersion),void 0!==this.iridescence&&(n.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(n.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(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),void 0!==this.anisotropy&&(n.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(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,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapRotation&&(n.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(n.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(n.size=this.size),null!==this.shadowSide&&(n.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),0!==this.side&&(n.side=this.side),!0===this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=!0),this.blendSrc!==T&&(n.blendSrc=this.blendSrc),this.blendDst!==M&&(n.blendDst=this.blendDst),this.blendEquation!==g&&(n.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(n.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(n.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(n.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(n.depthFunc=this.depthFunc),!1===this.depthTest&&(n.depthTest=this.depthTest),!1===this.depthWrite&&(n.depthWrite=this.depthWrite),!1===this.colorWrite&&(n.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(n.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(n.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(n.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ut&&(n.stencilFail=this.stencilFail),this.stencilZFail!==ut&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==ut&&(n.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(n.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaHash&&(n.alphaHash=!0),!0===this.alphaToCoverage&&(n.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=!0),!0===this.forceSinglePass&&(n.forceSinglePass=!0),!0===this.wireframe&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(n.flatShading=!0),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),!1===this.fog&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(n.textures=t),r.length>0&&(n.images=r)}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;const t=e.clippingPlanes;let n=null;if(null!==t){const e=t.length;n=new Array(e);for(let i=0;i!==e;++i)n[i]=t[i].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){!0===e&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class Ii extends Li{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Pi(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 Yn,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}}const Oi=Fi();function Fi(){const e=new ArrayBuffer(4),t=new Float32Array(e),n=new Uint32Array(e),i=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(i[e]=0,i[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(i[e]=1024>>-t-14,i[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(i[e]=t+15<<10,i[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(i[e]=31744,i[256|e]=64512,r[e]=24,r[256|e]=24):(i[e]=31744,i[256|e]=64512,r[e]=13,r[256|e]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,n=0;for(;!(8388608&t);)t<<=1,n-=8388608;t&=-8388609,n+=947912704,s[e]=t|n}for(let e=1024;e<2048;++e)s[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)a[e]=e<<23;a[31]=1199570944,a[32]=2147483648;for(let e=33;e<63;++e)a[e]=2147483648+(e-32<<23);a[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(o[e]=1024);return{floatView:t,uint32View:n,baseTable:i,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function Bi(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=Ct(e,-65504,65504),Oi.floatView[0]=e;const t=Oi.uint32View[0],n=t>>23&511;return Oi.baseTable[n]+((8388607&t)>>Oi.shiftTable[n])}function ki(e){const t=e>>10;return Oi.uint32View[0]=Oi.mantissaTable[Oi.offsetTable[t]+(1023&e)]+Oi.exponentTable[t],Oi.floatView[0]}const zi=new un,Gi=new It;let Vi=0;class Hi{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Vi++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=n,this.usage=vt,this.updateRanges=[],this.gpuType=le,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&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 i=0,r=this.itemSize;it.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(){null===this.boundingBox&&(this.boundingBox=new dn);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new un(-1/0,-1/0,-1/0),new un(1/0,1/0,1/0));if(void 0!==e){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const n in t)void 0!==t[n]&&(e[n]=t[n]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const t in n){const i=n[t];e.data.attributes[t]=i.toJSON(e.data)}const i={};let r=!1;for(const t in this.morphAttributes){const n=this.morphAttributes[t],s=[];for(let t=0,i=n.length;t0&&(i[t]=s,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(e.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(e.data.boundingSphere={center:a.center.toArray(),radius:a.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;const t={};this.name=e.name;const n=e.index;null!==n&&this.setIndex(n.clone(t));const i=e.attributes;for(const e in i){const n=i[e];this.setAttribute(e,n.clone(t))}const r=e.morphAttributes;for(const e in r){const n=[],i=r[e];for(let e=0,r=i.length;e0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e(e.far-e.near)**2)return}nr.copy(r).invert(),ir.copy(e.ray).applyMatrix4(nr),null!==n.boundingBox&&!1===ir.intersectsBox(n.boundingBox)||this._computeIntersections(e,t,ir)}}_computeIntersections(e,t,n){let i;const r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,l=r.attributes.uv,u=r.attributes.uv1,c=r.attributes.normal,h=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(s))for(let r=0,o=h.length;rn.far?null:{distance:u,point:dr.clone(),object:e}}(e,t,n,i,ar,or,lr,hr);if(c){const e=new un;wi.getBarycoord(hr,ar,or,lr,e),r&&(c.uv=wi.getInterpolatedAttribute(r,o,l,u,e,new It)),s&&(c.uv1=wi.getInterpolatedAttribute(s,o,l,u,e,new It)),a&&(c.normal=wi.getInterpolatedAttribute(a,o,l,u,e,new un),c.normal.dot(i.direction)>0&&c.normal.multiplyScalar(-1));const t={a:o,b:l,c:u,normal:new un,materialIndex:0};wi.getNormal(ar,or,lr,t.normal),c.face=t,c.barycoord=e}return c}class mr extends tr{constructor(e=1,t=1,n=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};const a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],u=[],c=[];let h=0,d=0;function p(e,t,n,i,r,s,p,f,m,g,_){const v=s/m,y=p/g,x=s/2,b=p/2,S=f/2,T=m+1,M=g+1;let E=0,w=0;const A=new un;for(let s=0;s0?1:-1,u.push(A.x,A.y,A.z),c.push(o/m),c.push(1-s/g),E+=1}}for(let e=0;e0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const e in this.extensions)!0===this.extensions[e]&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class br extends di{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new kn,this.projectionMatrix=new kn,this.projectionMatrixInverse=new kn,this.coordinateSystem=bt}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)}}const Sr=new un,Tr=new It,Mr=new It;class Er extends br{constructor(e=50,t=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,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=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*At*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*wt*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*At*Math.atan(Math.tan(.5*wt*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){Sr.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Sr.x,Sr.y).multiplyScalar(-e/Sr.z),Sr.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Sr.x,Sr.y).multiplyScalar(-e/Sr.z)}getViewSize(e,t){return this.getViewBounds(e,Tr,Mr),t.subVectors(Mr,Tr)}setViewOffset(e,t,n,i,r,s){this.aspect=e/t,null===this.view&&(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=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*wt*this.fov)/this.zoom,n=2*t,i=this.aspect*n,r=-.5*i;const s=this.view;if(null!==this.view&&this.view.enabled){const e=s.fullWidth,a=s.fullHeight;r+=s.offsetX*i/e,t-=s.offsetY*n/a,i*=s.width/e,n*=s.height/a}const a=this.filmOffset;0!==a&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-n,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const 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,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const wr=-90;class Ar extends di{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Er(wr,1,e,t);i.layers=this.layers,this.add(i);const r=new Er(wr,1,e,t);r.layers=this.layers,this.add(r);const s=new Er(wr,1,e,t);s.layers=this.layers,this.add(s);const a=new Er(wr,1,e,t);a.layers=this.layers,this.add(a);const o=new Er(wr,1,e,t);o.layers=this.layers,this.add(o);const l=new Er(wr,1,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,i,r,s,a,o]=t;for(const e of t)this.remove(e);if(e===bt)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(e!==St)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const e of t)this.add(e),e.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,s,a,o,l,u]=this.children,c=e.getRenderTarget(),h=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const f=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,i),e.render(t,r),e.setRenderTarget(n,1,i),e.render(t,s),e.setRenderTarget(n,2,i),e.render(t,a),e.setRenderTarget(n,3,i),e.render(t,o),e.setRenderTarget(n,4,i),e.render(t,l),n.texture.generateMipmaps=f,e.setRenderTarget(n,5,i),e.render(t,u),e.setRenderTarget(c,h,d),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class Rr extends tn{constructor(e,t,n,i,r,s,a,o,l,u){super(e=void 0!==e?e:[],t=void 0!==t?t:V,n,i,r,s,a,o,l,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Cr extends sn{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new Rr(i,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=void 0!==t.generateMipmaps&&t.generateMipmaps,this.texture.minFilter=void 0!==t.minFilter?t.minFilter:J}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;const n={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new mr(5,5,5),r=new xr({name:"CubemapFromEquirect",uniforms:gr(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=t;const s=new pr(i,r),a=t.minFilter;t.minFilter===te&&(t.minFilter=J);return new Ar(1,10,this).update(e,s),t.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(e,t,n,i){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,n,i);e.setRenderTarget(r)}}let Nr=class extends di{constructor(){super(),this.isGroup=!0,this.type="Group"}};const Pr={type:"move"};class Dr{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new Nr,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return null===this._targetRay&&(this._targetRay=new Nr,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new un,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new un),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new Nr,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new un,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new un),this._grip}dispatchEvent(e){return null!==this._targetRay&&this._targetRay.dispatchEvent(e),null!==this._grip&&this._grip.dispatchEvent(e),null!==this._hand&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const 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}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(e,t,n){let i=null,r=null,s=null;const a=this._targetRay,o=this._grip,l=this._hand;if(e&&"visible-blurred"!==t.session.visibilityState){if(l&&e.hand){s=!0;for(const i of e.hand.values()){const e=t.getJointPose(i,n),r=this._getHandJoint(l,i);null!==e&&(r.matrix.fromArray(e.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.matrixWorldNeedsUpdate=!0,r.jointRadius=e.radius),r.visible=null!==e}const i=l.joints["index-finger-tip"],r=l.joints["thumb-tip"],a=i.position.distanceTo(r.position),o=.02,u=.005;l.inputState.pinching&&a>o+u?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&a<=o-u&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==o&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),null!==r&&(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));null!==a&&(i=t.getPose(e.targetRaySpace,n),null===i&&null!==r&&(i=r),null!==i&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Pr)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const n=new Nr;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class Ur extends di{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 Yn,this.environmentIntensity=1,this.environmentRotation=new Yn,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(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),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class Lr{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=vt,this.updateRanges=[],this.version=0,this.uuid=Rt()}onUploadCallback(){}set needsUpdate(e){!0===e&&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 i=0,r=this.stride;i1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){const 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){const n=t||Vr.getNormalMatrix(e),i=this.coplanarPoint(zr).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),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)}}const jr=new Nn,Wr=new un;class Xr{constructor(e=new Hr,t=new Hr,n=new Hr,i=new Hr,r=new Hr,s=new Hr){this.planes=[e,t,n,i,r,s]}set(e,t,n,i,r,s){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=2e3){const n=this.planes,i=e.elements,r=i[0],s=i[1],a=i[2],o=i[3],l=i[4],u=i[5],c=i[6],h=i[7],d=i[8],p=i[9],f=i[10],m=i[11],g=i[12],_=i[13],v=i[14],y=i[15];if(n[0].setComponents(o-r,h-l,m-d,y-g).normalize(),n[1].setComponents(o+r,h+l,m+d,y+g).normalize(),n[2].setComponents(o+s,h+u,m+p,y+_).normalize(),n[3].setComponents(o-s,h-u,m-p,y-_).normalize(),n[4].setComponents(o-a,h-c,m-f,y-v).normalize(),t===bt)n[5].setComponents(o+a,h+c,m+f,y+v).normalize();else{if(t!==St)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);n[5].setComponents(a,c,f,v).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),jr.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),jr.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(jr)}intersectsSprite(e){return jr.center.set(0,0,0),jr.radius=.7071067811865476,jr.applyMatrix4(e.matrixWorld),this.intersectsSphere(jr)}intersectsSphere(e){const t=this.planes,n=e.center,i=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(n)0?e.max.x:e.min.x,Wr.y=i.normal.y>0?e.max.y:e.min.y,Wr.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Wr)<0)return!1}return!0}containsPoint(e){const 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)}}class qr extends Li{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Pi(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}}const $r=new un,Yr=new un,Kr=new kn,Zr=new Bn,Qr=new Nn,Jr=new un,es=new un;function ts(e,t,n,i,r,s,a){const o=e.geometry.attributes.position;$r.fromBufferAttribute(o,r),Yr.fromBufferAttribute(o,s);if(n.distanceSqToSegment($r,Yr,Jr,es)>i)return;Jr.applyMatrix4(e.matrixWorld);const l=t.ray.origin.distanceTo(Jr);return lt.far?void 0:{distance:l,point:es.clone().applyMatrix4(e.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:e}}class ns extends Li{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Pi(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}}class is extends tn{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=K,this.minFilter=K,this.generateMipmaps=!1,this.needsUpdate=!0}}class rs extends tn{constructor(e,t,n,i,r,s,a,o,l,u=1026){if(u!==ye&&u!==xe)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===n&&u===ye&&(n=oe),void 0===n&&u===xe&&(n=de),super(null,i,r,s,a,o,u,n,l),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=void 0!==a?a:K,this.minFilter=void 0!==o?o:K,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Qt(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}class ss{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){console.warn("THREE.Curve: .getPoint() not implemented.")}getPointAt(e,t){const n=this.getUtoTmapping(e);return this.getPoint(n,t)}getPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t}getSpacedPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let n,i=this.getPoint(0),r=0;t.push(0);for(let s=1;s<=e;s++)n=this.getPoint(s/e),r+=n.distanceTo(i),t.push(r),i=n;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t=null){const n=this.getLengths();let i=0;const r=n.length;let s;s=t||e*n[r-1];let a,o=0,l=r-1;for(;o<=l;)if(i=Math.floor(o+(l-o)/2),a=n[i]-s,a<0)o=i+1;else{if(!(a>0)){l=i;break}l=i-1}if(i=l,n[i]===s)return i/(r-1);const u=n[i];return(i+(s-u)/(n[i+1]-u))/(r-1)}getTangent(e,t){const n=1e-4;let i=e-n,r=e+n;i<0&&(i=0),r>1&&(r=1);const s=this.getPoint(i),a=this.getPoint(r),o=t||(s.isVector2?new It:new un);return o.copy(a).sub(s).normalize(),o}getTangentAt(e,t){const n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){const n=new un,i=[],r=[],s=[],a=new un,o=new kn;for(let t=0;t<=e;t++){const n=t/e;i[t]=this.getTangentAt(n,new un)}r[0]=new un,s[0]=new un;let l=Number.MAX_VALUE;const u=Math.abs(i[0].x),c=Math.abs(i[0].y),h=Math.abs(i[0].z);u<=l&&(l=u,n.set(1,0,0)),c<=l&&(l=c,n.set(0,1,0)),h<=l&&n.set(0,0,1),a.crossVectors(i[0],n).normalize(),r[0].crossVectors(i[0],a),s[0].crossVectors(i[0],r[0]);for(let t=1;t<=e;t++){if(r[t]=r[t-1].clone(),s[t]=s[t-1].clone(),a.crossVectors(i[t-1],i[t]),a.length()>Number.EPSILON){a.normalize();const e=Math.acos(Ct(i[t-1].dot(i[t]),-1,1));r[t].applyMatrix4(o.makeRotationAxis(a,e))}s[t].crossVectors(i[t],r[t])}if(!0===t){let t=Math.acos(Ct(r[0].dot(r[e]),-1,1));t/=e,i[0].dot(a.crossVectors(r[0],r[e]))>0&&(t=-t);for(let n=1;n<=e;n++)r[n].applyMatrix4(o.makeRotationAxis(i[n],t*n)),s[n].crossVectors(i[n],r[n])}return{tangents:i,normals:r,binormals:s}}clone(){return(new this.constructor).copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class as extends ss{constructor(e=0,t=0,n=1,i=1,r=0,s=2*Math.PI,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(e,t=new It){const n=t,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)i;)r-=i;r0?0:(Math.floor(Math.abs(l)/r)+1)*r:0===u&&l===r-1&&(l=r-2,u=1),this.closed||l>0?a=i[(l-1)%r]:(ls.subVectors(i[0],i[1]).add(i[0]),a=ls);const c=i[l%r],h=i[(l+1)%r];if(this.closed||l+2i.length-2?i.length-1:s+1],c=i[s>i.length-3?i.length-1:s+2];return n.set(ds(a,o.x,l.x,u.x,c.x),ds(a,o.y,l.y,u.y,c.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t0||0!==i)&&(u.push(s,a,l),v+=3),(t>0||i!==r-1)&&(u.push(a,o,l),v+=3)}l.addGroup(g,v,0),g+=v}(),!1===s&&(e>0&&_(!0),t>0&&_(!1)),this.setIndex(u),this.setAttribute("position",new qi(c,3)),this.setAttribute("normal",new qi(h,3)),this.setAttribute("uv",new qi(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new vs(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class ys extends vs{constructor(e=1,t=1,n=32,i=1,r=!1,s=0,a=2*Math.PI){super(0,e,t,n,i,r,s,a),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:n,heightSegments:i,openEnded:r,thetaStart:s,thetaLength:a}}static fromJSON(e){return new ys(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class xs extends tr{constructor(e=1,t=1,n=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:i};const r=e/2,s=t/2,a=Math.floor(n),o=Math.floor(i),l=a+1,u=o+1,c=e/a,h=t/o,d=[],p=[],f=[],m=[];for(let e=0;e0)&&d.push(t,r,l),(e!==n-1||o0!=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}}class ws extends Li{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Pi(16777215),this.specular=new Pi(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Pi(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Yn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,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.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,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.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.flatShading=e.flatShading,this.fog=e.fog,this}}class As extends Li{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Pi(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Pi(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,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.gradientMap=e.gradientMap,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.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class Rs extends Li{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),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.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class Cs extends Li{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Pi(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Pi(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Yn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,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.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.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.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.flatShading=e.flatShading,this.fog=e.fog,this}}class Ns extends Li{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,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}}class Ps extends Li{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}}class Ds extends Li{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Pi(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,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.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Us extends qr{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}const Ls={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class Is{constructor(e,t,n){const i=this;let r,s=!1,a=0,o=0;const l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this.itemStart=function(e){o++,!1===s&&void 0!==i.onStart&&i.onStart(e,a,o),s=!0},this.itemEnd=function(e){a++,void 0!==i.onProgress&&i.onProgress(e,a,o),a===o&&(s=!1,void 0!==i.onLoad&&i.onLoad())},this.itemError=function(e){void 0!==i.onError&&i.onError(e)},this.resolveURL=function(e){return r?r(e):e},this.setURLModifier=function(e){return r=e,this},this.addHandler=function(e,t){return l.push(e,t),this},this.removeHandler=function(e){const t=l.indexOf(e);return-1!==t&&l.splice(t,2),this},this.getHandler=function(e){for(let t=0,n=l.length;te.start-t.start));let t=0;for(let e=1;e 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.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\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:"vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n\treturn 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\treturn 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\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform 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\tvec3 diffuseColor;\n\tfloat 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\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.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\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 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\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.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\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_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\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat 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\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.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\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_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\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#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\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat 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\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn 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\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn 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\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn 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\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn 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\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid 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\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\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\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.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\treflectedLight.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\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn 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\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphinstance_vertex:"#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform 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\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 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\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn 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\treturn 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\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#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\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_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\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t#else\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( 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\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = 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\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",cube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}",depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - 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\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",points_vert:"uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"},xa={common:{diffuse:{value:new Pi(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ot},alphaMap:{value:null},alphaMapTransform:{value:new Ot},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ot}},envmap:{envMap:{value:null},envMapRotation:{value:new Ot},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ot}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ot}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ot},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ot},normalScale:{value:new It(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ot},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ot}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ot}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ot}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Pi(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 Pi(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ot},alphaTest:{value:0},uvTransform:{value:new Ot}},sprite:{diffuse:{value:new Pi(16777215)},opacity:{value:1},center:{value:new It(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ot},alphaMap:{value:null},alphaMapTransform:{value:new Ot},alphaTest:{value:0}}},ba={basic:{uniforms:_r([xa.common,xa.specularmap,xa.envmap,xa.aomap,xa.lightmap,xa.fog]),vertexShader:ya.meshbasic_vert,fragmentShader:ya.meshbasic_frag},lambert:{uniforms:_r([xa.common,xa.specularmap,xa.envmap,xa.aomap,xa.lightmap,xa.emissivemap,xa.bumpmap,xa.normalmap,xa.displacementmap,xa.fog,xa.lights,{emissive:{value:new Pi(0)}}]),vertexShader:ya.meshlambert_vert,fragmentShader:ya.meshlambert_frag},phong:{uniforms:_r([xa.common,xa.specularmap,xa.envmap,xa.aomap,xa.lightmap,xa.emissivemap,xa.bumpmap,xa.normalmap,xa.displacementmap,xa.fog,xa.lights,{emissive:{value:new Pi(0)},specular:{value:new Pi(1118481)},shininess:{value:30}}]),vertexShader:ya.meshphong_vert,fragmentShader:ya.meshphong_frag},standard:{uniforms:_r([xa.common,xa.envmap,xa.aomap,xa.lightmap,xa.emissivemap,xa.bumpmap,xa.normalmap,xa.displacementmap,xa.roughnessmap,xa.metalnessmap,xa.fog,xa.lights,{emissive:{value:new Pi(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ya.meshphysical_vert,fragmentShader:ya.meshphysical_frag},toon:{uniforms:_r([xa.common,xa.aomap,xa.lightmap,xa.emissivemap,xa.bumpmap,xa.normalmap,xa.displacementmap,xa.gradientmap,xa.fog,xa.lights,{emissive:{value:new Pi(0)}}]),vertexShader:ya.meshtoon_vert,fragmentShader:ya.meshtoon_frag},matcap:{uniforms:_r([xa.common,xa.bumpmap,xa.normalmap,xa.displacementmap,xa.fog,{matcap:{value:null}}]),vertexShader:ya.meshmatcap_vert,fragmentShader:ya.meshmatcap_frag},points:{uniforms:_r([xa.points,xa.fog]),vertexShader:ya.points_vert,fragmentShader:ya.points_frag},dashed:{uniforms:_r([xa.common,xa.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ya.linedashed_vert,fragmentShader:ya.linedashed_frag},depth:{uniforms:_r([xa.common,xa.displacementmap]),vertexShader:ya.depth_vert,fragmentShader:ya.depth_frag},normal:{uniforms:_r([xa.common,xa.bumpmap,xa.normalmap,xa.displacementmap,{opacity:{value:1}}]),vertexShader:ya.meshnormal_vert,fragmentShader:ya.meshnormal_frag},sprite:{uniforms:_r([xa.sprite,xa.fog]),vertexShader:ya.sprite_vert,fragmentShader:ya.sprite_frag},background:{uniforms:{uvTransform:{value:new Ot},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:ya.background_vert,fragmentShader:ya.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Ot}},vertexShader:ya.backgroundCube_vert,fragmentShader:ya.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ya.cube_vert,fragmentShader:ya.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ya.equirect_vert,fragmentShader:ya.equirect_frag},distanceRGBA:{uniforms:_r([xa.common,xa.displacementmap,{referencePosition:{value:new un},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ya.distanceRGBA_vert,fragmentShader:ya.distanceRGBA_frag},shadow:{uniforms:_r([xa.lights,xa.fog,{color:{value:new Pi(0)},opacity:{value:1}}]),vertexShader:ya.shadow_vert,fragmentShader:ya.shadow_frag}};ba.physical={uniforms:_r([ba.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ot},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ot},clearcoatNormalScale:{value:new It(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ot},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ot},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ot},sheen:{value:0},sheenColor:{value:new Pi(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ot},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ot},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ot},transmissionSamplerSize:{value:new It},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ot},attenuationDistance:{value:0},attenuationColor:{value:new Pi(0)},specularColor:{value:new Pi(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ot},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ot},anisotropyVector:{value:new It},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ot}}]),vertexShader:ya.meshphysical_vert,fragmentShader:ya.meshphysical_frag};const Sa={r:0,b:0,g:0},Ta=new Yn,Ma=new kn;function Ea(e,t,n,i,r,s,a){const o=new Pi(0);let l,u,c=!0===s?0:1,h=null,d=0,p=null;function f(e){let i=!0===e.isScene?e.background:null;if(i&&i.isTexture){i=(e.backgroundBlurriness>0?n:t).get(i)}return i}function m(t,n){t.getRGB(Sa,vr(e)),i.buffers.color.setClear(Sa.r,Sa.g,Sa.b,n,a)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),c=t,m(o,c)},getClearAlpha:function(){return c},setClearAlpha:function(e){c=e,m(o,c)},render:function(t){let n=!1;const r=f(t);null===r?m(o,c):r&&r.isColor&&(m(r,1),n=!0);const s=e.xr.getEnvironmentBlendMode();"additive"===s?i.buffers.color.setClear(0,0,0,1,a):"alpha-blend"===s&&i.buffers.color.setClear(0,0,0,0,a),(e.autoClear||n)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))},addToRenderList:function(t,n){const i=f(n);i&&(i.isCubeTexture||i.mapping===X)?(void 0===u&&(u=new pr(new mr(1,1,1),new xr({name:"BackgroundCubeMaterial",uniforms:gr(ba.backgroundCube.uniforms),vertexShader:ba.backgroundCube.vertexShader,fragmentShader:ba.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!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}}),r.update(u)),Ta.copy(n.backgroundRotation),Ta.x*=-1,Ta.y*=-1,Ta.z*=-1,i.isCubeTexture&&!1===i.isRenderTargetTexture&&(Ta.y*=-1,Ta.z*=-1),u.material.uniforms.envMap.value=i,u.material.uniforms.flipEnvMap.value=i.isCubeTexture&&!1===i.isRenderTargetTexture?-1:1,u.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(Ma.makeRotationFromEuler(Ta)),u.material.toneMapped=Xt.getTransfer(i.colorSpace)!==lt,h===i&&d===i.version&&p===e.toneMapping||(u.material.needsUpdate=!0,h=i,d=i.version,p=e.toneMapping),u.layers.enableAll(),t.unshift(u,u.geometry,u.material,0,0,null)):i&&i.isTexture&&(void 0===l&&(l=new pr(new xs(2,2),new xr({name:"BackgroundMaterial",uniforms:gr(ba.background.uniforms),vertexShader:ba.background.vertexShader,fragmentShader:ba.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(l)),l.material.uniforms.t2D.value=i,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.toneMapped=Xt.getTransfer(i.colorSpace)!==lt,!0===i.matrixAutoUpdate&&i.updateMatrix(),l.material.uniforms.uvTransform.value.copy(i.matrix),h===i&&d===i.version&&p===e.toneMapping||(l.material.needsUpdate=!0,h=i,d=i.version,p=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null))},dispose:function(){void 0!==u&&(u.geometry.dispose(),u.material.dispose(),u=void 0),void 0!==l&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}}}function wa(e,t){const n=e.getParameter(e.MAX_VERTEX_ATTRIBS),i={},r=u(null);let s=r,a=!1;function o(t){return e.bindVertexArray(t)}function l(t){return e.deleteVertexArray(t)}function u(e){const t=[],i=[],r=[];for(let e=0;e=0){const n=r[t];let i=a[t];if(void 0===i&&("instanceMatrix"===t&&e.instanceMatrix&&(i=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(i=e.instanceColor)),void 0===n)return!0;if(n.attribute!==i)return!0;if(i&&n.data!==i.data)return!0;o++}}return s.attributesNum!==o||s.index!==i}(n,m,l,g),_&&function(e,t,n,i){const r={},a=t.attributes;let o=0;const l=n.getAttributes();for(const t in l){if(l[t].location>=0){let n=a[t];void 0===n&&("instanceMatrix"===t&&e.instanceMatrix&&(n=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(n=e.instanceColor));const i={};i.attribute=n,n&&n.data&&(i.data=n.data),r[t]=i,o++}}s.attributes=r,s.attributesNum=o,s.index=i}(n,m,l,g),null!==g&&t.update(g,e.ELEMENT_ARRAY_BUFFER),(_||a)&&(a=!1,function(n,i,r,s){c();const a=s.attributes,o=r.getAttributes(),l=i.defaultAttributeValues;for(const i in o){const r=o[i];if(r.location>=0){let o=a[i];if(void 0===o&&("instanceMatrix"===i&&n.instanceMatrix&&(o=n.instanceMatrix),"instanceColor"===i&&n.instanceColor&&(o=n.instanceColor)),void 0!==o){const i=o.normalized,a=o.itemSize,l=t.get(o);if(void 0===l)continue;const u=l.buffer,c=l.type,p=l.bytesPerElement,m=c===e.INT||c===e.UNSIGNED_INT||o.gpuType===ae;if(o.isInterleavedBufferAttribute){const t=o.data,l=t.stride,g=o.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";t="mediump"}return"mediump"===t&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let a=void 0!==n.precision?n.precision:"highp";const o=s(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=!0===n.logarithmicDepthBuffer,u=!0===n.reverseDepthBuffer&&t.has("EXT_clip_control"),c=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS);return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==r)return r;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");r=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r},getMaxPrecision:s,textureFormatReadable:function(t){return t===ge||i.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(n){const r=n===ue&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(n!==ne&&i.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==le&&!r)},precision:a,logarithmicDepthBuffer:l,reverseDepthBuffer:u,maxTextures:c,maxVertexTextures:h,maxTextureSize:e.getParameter(e.MAX_TEXTURE_SIZE),maxCubemapSize:e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),maxAttributes:e.getParameter(e.MAX_VERTEX_ATTRIBS),maxVertexUniforms:e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),maxVaryings:e.getParameter(e.MAX_VARYING_VECTORS),maxFragmentUniforms:e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),vertexTextures:h>0,maxSamples:e.getParameter(e.MAX_SAMPLES)}}function Ca(e){const t=this;let n=null,i=0,r=!1,s=!1;const a=new Hr,o=new Ot,l={value:null,needsUpdate:!1};function u(e,n,i,r){const s=null!==e?e.length:0;let u=null;if(0!==s){if(u=l.value,!0!==r||null===u){const t=i+4*s,r=n.matrixWorldInverse;o.getNormalMatrix(r),(null===u||u.length0);t.numPlanes=i,t.numIntersection=0}();else{const e=s?0:i,t=4*e;let r=f.clippingState||null;l.value=r,r=u(h,o,t,c);for(let e=0;e!==t;++e)r[e]=n[e];f.clippingState=r,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=e}}}function Na(e){let t=new WeakMap;function n(e,t){return t===j?e.mapping=V:t===W&&(e.mapping=H),e}function i(e){const n=e.target;n.removeEventListener("dispose",i);const r=t.get(n);void 0!==r&&(t.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping;if(s===j||s===W){if(t.has(r)){return n(t.get(r).texture,r.mapping)}{const s=r.image;if(s&&s.height>0){const a=new Cr(s.height);return a.fromEquirectangularTexture(e,r),t.set(r,a),r.addEventListener("dispose",i),n(a.texture,r.mapping)}return null}}}return r},dispose:function(){t=new WeakMap}}}const Pa=[.125,.215,.35,.446,.526,.582],Da=20,Ua=new Qs,La=new Pi;let Ia=null,Oa=0,Fa=0,Ba=!1;const ka=(1+Math.sqrt(5))/2,za=1/ka,Ga=[new un(-ka,za,0),new un(ka,za,0),new un(-za,0,ka),new un(za,0,ka),new un(0,ka,-za),new un(0,ka,za),new un(-1,1,-1),new un(1,1,-1),new un(-1,1,1),new un(1,1,1)],Va=new un;let Ha=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,i=100,r={}){const{size:s=256,position:a=Va}=r;Ia=this._renderer.getRenderTarget(),Oa=this._renderer.getActiveCubeFace(),Fa=this._renderer.getActiveMipmapLevel(),Ba=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(s);const o=this._allocateTargets();return o.depthBuffer=!0,this._sceneToCubeUV(e,n,i,o,a),t>0&&this._blur(o,0,0,t),this._applyPMREM(o),this._cleanup(o),o}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=qa(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Xa(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;ee-4?o=Pa[a-e+4-1]:0===a&&(o=0),i.push(o);const l=1/(s-2),u=-l,c=1+l,h=[u,u,c,u,c,c,u,u,c,c,u,c],d=6,p=6,f=3,m=2,g=1,_=new Float32Array(f*p*d),v=new Float32Array(m*p*d),y=new Float32Array(g*p*d);for(let e=0;e2?0:-1,i=[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];_.set(i,f*p*e),v.set(h,m*p*e);const r=[e,e,e,e,e,e];y.set(r,g*p*e)}const x=new tr;x.setAttribute("position",new Hi(_,f)),x.setAttribute("uv",new Hi(v,m)),x.setAttribute("faceIndex",new Hi(y,g)),t.push(x),r>4&&r--}return{lodPlanes:t,sizeLods:n,sigmas:i}}(i)),this._blurMaterial=function(e,t,n){const i=new Float32Array(Da),r=new un(0,1,0),s=new xr({name:"SphericalGaussianBlur",defines:{n:Da,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:$a(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1});return s}(i,e,t)}return i}_compileMaterial(e){const t=new pr(this._lodPlanes[0],e);this._renderer.compile(t,Ua)}_sceneToCubeUV(e,t,n,i,r){const s=new Er(90,1,t,n),a=[1,-1,1,1,1,1],o=[1,1,1,-1,-1,-1],l=this._renderer,u=l.autoClear,c=l.toneMapping;l.getClearColor(La),l.toneMapping=0,l.autoClear=!1;const h=new Ii({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1}),d=new pr(new mr,h);let p=!1;const f=e.background;f?f.isColor&&(h.color.copy(f),e.background=null,p=!0):(h.color.copy(La),p=!0);for(let t=0;t<6;t++){const n=t%3;0===n?(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x+o[t],r.y,r.z)):1===n?(s.up.set(0,0,a[t]),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y+o[t],r.z)):(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y,r.z+o[t]));const u=this._cubeSize;Wa(i,n*u,t>2?u:0,u,u),l.setRenderTarget(i),p&&l.render(d,s),l.render(e,s)}d.geometry.dispose(),d.material.dispose(),l.toneMapping=c,l.autoClear=u,e.background=f}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===V||e.mapping===H;i?(null===this._cubemapMaterial&&(this._cubemapMaterial=qa()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=Xa());const r=i?this._cubemapMaterial:this._equirectMaterial,s=new pr(this._lodPlanes[0],r);r.uniforms.envMap.value=e;const a=this._cubeSize;Wa(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,Ua)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const i=this._lodPlanes.length;for(let t=1;tDa&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const m=[];let g=0;for(let e=0;e_-4?i-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(u,Ua)}};function ja(e,t,n){const i=new sn(e,t,n);return i.texture.mapping=X,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function Wa(e,t,n,i,r){e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r)}function Xa(){return new xr({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:$a(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function qa(){return new xr({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:$a(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function $a(){return"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}function Ya(e){let t=new WeakMap,n=null;function i(e){const n=e.target;n.removeEventListener("dispose",i);const r=t.get(n);void 0!==r&&(t.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping,a=s===j||s===W,o=s===V||s===H;if(a||o){let s=t.get(r);const l=void 0!==s?s.texture.pmremVersion:0;if(r.isRenderTargetTexture&&r.pmremVersion!==l)return null===n&&(n=new Ha(e)),s=a?n.fromEquirectangular(r,s):n.fromCubemap(r,s),s.texture.pmremVersion=r.pmremVersion,t.set(r,s),s.texture;if(void 0!==s)return s.texture;{const l=r.image;return a&&l&&l.height>0||o&&l&&function(e){let t=0;const n=6;for(let i=0;it.maxTextureSize&&(x=Math.ceil(y/t.maxTextureSize),y=t.maxTextureSize);const b=new Float32Array(y*x*4*c),S=new an(b,y,x,c);S.type=le,S.needsUpdate=!0;const T=4*v;for(let E=0;E0)return e;const r=t*n;let s=oo[r];if(void 0===s&&(s=new Float32Array(r),oo[r]=s),0!==t){i.toArray(s,0);for(let i=1,r=0;i!==t;++i)r+=n,e[i].toArray(s,r)}return s}function fo(e,t){if(e.length!==t.length)return!1;for(let n=0,i=e.length;n":" "} ${r}: ${n[e]}`)}return i.join("\n")}(e.getShaderSource(t),i)}return r}function dl(e,t){const n=function(e){Xt._getMatrix(cl,Xt.workingColorSpace,e);const t=`mat3( ${cl.elements.map((e=>e.toFixed(4)))} )`;switch(Xt.getTransfer(e)){case ot:return[t,"LinearTransferOETF"];case lt:return[t,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}(t);return[`vec4 ${e}( vec4 value ) {`,`\treturn ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join("\n")}function pl(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 ); }"}const fl=new un;function ml(){Xt.getLuminanceCoefficients(fl);return["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${fl.x.toFixed(4)}, ${fl.y.toFixed(4)}, ${fl.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")}function gl(e){return""!==e}function _l(e,t){const 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)}const yl=/^[ \t]*#include +<([\w\d./]+)>/gm;function xl(e){return e.replace(yl,Sl)}const bl=new Map;function Sl(e,t){let n=ya[t];if(void 0===n){const e=bl.get(t);if(void 0===e)throw new Error("Can not resolve #include <"+t+">");n=ya[e],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,e)}return xl(n)}const Tl=/#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 Ml(e){return e.replace(Tl,El)}function El(e,t,n,i){let r="";for(let e=parseInt(t);e0&&(g+="\n"),_=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f].filter(gl).join("\n"),_.length>0&&(_+="\n")):(g=[wl(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f,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 "+c:"",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&&!1===n.flatShading?"#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&&!1===n.flatShading?"#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 "+l:"",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","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(gl).join("\n"),_=[wl(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f,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 "+u:"",n.envMap?"#define "+c:"",n.envMap?"#define "+h:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.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&&!1===n.flatShading?"#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 "+l:"",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;",0!==n.toneMapping?"#define TONE_MAPPING":"",0!==n.toneMapping?ya.tonemapping_pars_fragment:"",0!==n.toneMapping?pl("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",ya.colorspace_pars_fragment,dl("linearToOutputTexel",n.outputColorSpace),ml(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(gl).join("\n")),a=xl(a),a=_l(a,n),a=vl(a,n),o=xl(o),o=_l(o,n),o=vl(o,n),a=Ml(a),o=Ml(o),!0!==n.isRawShaderMaterial&&(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===xt?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===xt?"":"#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"+_);const y=v+g+a,x=v+_+o,b=ll(r,r.VERTEX_SHADER,y),S=ll(r,r.FRAGMENT_SHADER,x);function T(t){if(e.debug.checkShaderErrors){const n=r.getProgramInfoLog(m).trim(),i=r.getShaderInfoLog(b).trim(),s=r.getShaderInfoLog(S).trim();let a=!0,o=!0;if(!1===r.getProgramParameter(m,r.LINK_STATUS))if(a=!1,"function"==typeof e.debug.onShaderError)e.debug.onShaderError(r,m,b,S);else{const e=hl(r,b,"vertex"),i=hl(r,S,"fragment");console.error("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(m,r.VALIDATE_STATUS)+"\n\nMaterial Name: "+t.name+"\nMaterial Type: "+t.type+"\n\nProgram Info Log: "+n+"\n"+e+"\n"+i)}else""!==n?console.warn("THREE.WebGLProgram: Program Info Log:",n):""!==i&&""!==s||(o=!1);o&&(t.diagnostics={runnable:a,programLog:n,vertexShader:{log:i,prefix:g},fragmentShader:{log:s,prefix:_}})}r.deleteShader(b),r.deleteShader(S),M=new ol(r,m),E=function(e,t){const n={},i=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r0,$=s.clearcoat>0,Y=s.dispersion>0,K=s.iridescence>0,Z=s.sheen>0,Q=s.transmission>0,J=q&&!!s.anisotropyMap,ee=$&&!!s.clearcoatMap,te=$&&!!s.clearcoatNormalMap,ne=$&&!!s.clearcoatRoughnessMap,ie=K&&!!s.iridescenceMap,re=K&&!!s.iridescenceThicknessMap,se=Z&&!!s.sheenColorMap,ae=Z&&!!s.sheenRoughnessMap,oe=!!s.specularMap,le=!!s.specularColorMap,ue=!!s.specularIntensityMap,ce=Q&&!!s.transmissionMap,he=Q&&!!s.thicknessMap,de=!!s.gradientMap,pe=!!s.alphaMap,fe=s.alphaTest>0,me=!!s.alphaHash,ge=!!s.extensions;let _e=0;s.toneMapped&&(null!==P&&!0!==P.isXRRenderTarget||(_e=e.toneMapping));const ve={shaderID:T,shaderType:s.type,shaderName:s.name,vertexShader:w,fragmentShader:A,defines:s.defines,customVertexShaderID:R,customFragmentShaderID:C,isRawShaderMaterial:!0===s.isRawShaderMaterial,glslVersion:s.glslVersion,precision:p,batching:L,batchingColor:L&&null!==_._colorsTexture,instancing:U,instancingColor:U&&null!==_.instanceColor,instancingMorph:U&&null!==_.morphTexture,supportsVertexTextures:d,outputColorSpace:null===P?e.outputColorSpace:!0===P.isXRRenderTarget?P.texture.colorSpace:at,alphaToCoverage:!!s.alphaToCoverage,map:I,matcap:O,envMap:F,envMapMode:F&&b.mapping,envMapCubeUVHeight:S,aoMap:B,lightMap:k,bumpMap:z,normalMap:G,displacementMap:d&&V,emissiveMap:H,normalMapObjectSpace:G&&1===s.normalMapType,normalMapTangentSpace:G&&0===s.normalMapType,metalnessMap:j,roughnessMap:W,anisotropy:q,anisotropyMap:J,clearcoat:$,clearcoatMap:ee,clearcoatNormalMap:te,clearcoatRoughnessMap:ne,dispersion:Y,iridescence:K,iridescenceMap:ie,iridescenceThicknessMap:re,sheen:Z,sheenColorMap:se,sheenRoughnessMap:ae,specularMap:oe,specularColorMap:le,specularIntensityMap:ue,transmission:Q,transmissionMap:ce,thicknessMap:he,gradientMap:de,opaque:!1===s.transparent&&1===s.blending&&!1===s.alphaToCoverage,alphaMap:pe,alphaTest:fe,alphaHash:me,combine:s.combine,mapUv:I&&m(s.map.channel),aoMapUv:B&&m(s.aoMap.channel),lightMapUv:k&&m(s.lightMap.channel),bumpMapUv:z&&m(s.bumpMap.channel),normalMapUv:G&&m(s.normalMap.channel),displacementMapUv:V&&m(s.displacementMap.channel),emissiveMapUv:H&&m(s.emissiveMap.channel),metalnessMapUv:j&&m(s.metalnessMap.channel),roughnessMapUv:W&&m(s.roughnessMap.channel),anisotropyMapUv:J&&m(s.anisotropyMap.channel),clearcoatMapUv:ee&&m(s.clearcoatMap.channel),clearcoatNormalMapUv:te&&m(s.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ne&&m(s.clearcoatRoughnessMap.channel),iridescenceMapUv:ie&&m(s.iridescenceMap.channel),iridescenceThicknessMapUv:re&&m(s.iridescenceThicknessMap.channel),sheenColorMapUv:se&&m(s.sheenColorMap.channel),sheenRoughnessMapUv:ae&&m(s.sheenRoughnessMap.channel),specularMapUv:oe&&m(s.specularMap.channel),specularColorMapUv:le&&m(s.specularColorMap.channel),specularIntensityMapUv:ue&&m(s.specularIntensityMap.channel),transmissionMapUv:ce&&m(s.transmissionMap.channel),thicknessMapUv:he&&m(s.thicknessMap.channel),alphaMapUv:pe&&m(s.alphaMap.channel),vertexTangents:!!y.attributes.tangent&&(G||q),vertexColors:s.vertexColors,vertexAlphas:!0===s.vertexColors&&!!y.attributes.color&&4===y.attributes.color.itemSize,pointsUvs:!0===_.isPoints&&!!y.attributes.uv&&(I||pe),fog:!!v,useFog:!0===s.fog,fogExp2:!!v&&v.isFogExp2,flatShading:!0===s.flatShading,sizeAttenuation:!0===s.sizeAttenuation,logarithmicDepthBuffer:h,reverseDepthBuffer:D,skinning:!0===_.isSkinnedMesh,morphTargets:void 0!==y.morphAttributes.position,morphNormals:void 0!==y.morphAttributes.normal,morphColors:void 0!==y.morphAttributes.color,morphTargetsCount:E,morphTextureStride:N,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:s.dithering,shadowMapEnabled:e.shadowMap.enabled&&c.length>0,shadowMapType:e.shadowMap.type,toneMapping:_e,decodeVideoTexture:I&&!0===s.map.isVideoTexture&&Xt.getTransfer(s.map.colorSpace)===lt,decodeVideoTextureEmissive:H&&!0===s.emissiveMap.isVideoTexture&&Xt.getTransfer(s.emissiveMap.colorSpace)===lt,premultipliedAlpha:s.premultipliedAlpha,doubleSided:2===s.side,flipSided:1===s.side,useDepthPacking:s.depthPacking>=0,depthPacking:s.depthPacking||0,index0AttributeName:s.index0AttributeName,extensionClipCullDistance:ge&&!0===s.extensions.clipCullDistance&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ge&&!0===s.extensions.multiDraw||L)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:s.customProgramCacheKey()};return ve.vertexUv1s=u.has(1),ve.vertexUv2s=u.has(2),ve.vertexUv3s=u.has(3),u.clear(),ve},getProgramCacheKey:function(t){const n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),void 0!==t.defines)for(const e in t.defines)n.push(e),n.push(t.defines[e]);return!1===t.isRawShaderMaterial&&(!function(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)}(n,t),function(e,t){o.disableAll(),t.supportsVertexTextures&&o.enable(0);t.instancing&&o.enable(1);t.instancingColor&&o.enable(2);t.instancingMorph&&o.enable(3);t.matcap&&o.enable(4);t.envMap&&o.enable(5);t.normalMapObjectSpace&&o.enable(6);t.normalMapTangentSpace&&o.enable(7);t.clearcoat&&o.enable(8);t.iridescence&&o.enable(9);t.alphaTest&&o.enable(10);t.vertexColors&&o.enable(11);t.vertexAlphas&&o.enable(12);t.vertexUv1s&&o.enable(13);t.vertexUv2s&&o.enable(14);t.vertexUv3s&&o.enable(15);t.vertexTangents&&o.enable(16);t.anisotropy&&o.enable(17);t.alphaHash&&o.enable(18);t.batching&&o.enable(19);t.dispersion&&o.enable(20);t.batchingColor&&o.enable(21);e.push(o.mask),o.disableAll(),t.fog&&o.enable(0);t.useFog&&o.enable(1);t.flatShading&&o.enable(2);t.logarithmicDepthBuffer&&o.enable(3);t.reverseDepthBuffer&&o.enable(4);t.skinning&&o.enable(5);t.morphTargets&&o.enable(6);t.morphNormals&&o.enable(7);t.morphColors&&o.enable(8);t.premultipliedAlpha&&o.enable(9);t.shadowMapEnabled&&o.enable(10);t.doubleSided&&o.enable(11);t.flipSided&&o.enable(12);t.useDepthPacking&&o.enable(13);t.dithering&&o.enable(14);t.transmission&&o.enable(15);t.sheen&&o.enable(16);t.opaque&&o.enable(17);t.pointsUvs&&o.enable(18);t.decodeVideoTexture&&o.enable(19);t.decodeVideoTextureEmissive&&o.enable(20);t.alphaToCoverage&&o.enable(21);e.push(o.mask)}(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()},getUniforms:function(e){const t=f[e.type];let n;if(t){const e=ba[t];n=yr.clone(e.uniforms)}else n=e.uniforms;return n},acquireProgram:function(t,n){let i;for(let e=0,t=c.length;e0?i.push(c):!0===a.transparent?r.push(c):n.push(c)},unshift:function(e,t,a,o,l,u){const c=s(e,t,a,o,l,u);a.transmission>0?i.unshift(c):!0===a.transparent?r.unshift(c):n.unshift(c)},finish:function(){for(let n=t,i=e.length;n1&&n.sort(e||Ul),i.length>1&&i.sort(t||Ll),r.length>1&&r.sort(t||Ll)}}}function Ol(){let e=new WeakMap;return{get:function(t,n){const i=e.get(t);let r;return void 0===i?(r=new Il,e.set(t,[r])):n>=i.length?(r=new Il,i.push(r)):r=i[n],r},dispose:function(){e=new WeakMap}}}function Fl(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":n={direction:new un,color:new Pi};break;case"SpotLight":n={position:new un,direction:new un,color:new Pi,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new un,color:new Pi,distance:0,decay:0};break;case"HemisphereLight":n={direction:new un,skyColor:new Pi,groundColor:new Pi};break;case"RectAreaLight":n={color:new Pi,position:new un,halfWidth:new un,halfHeight:new un}}return e[t.id]=n,n}}}let Bl=0;function kl(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function zl(e){const t=new Fl,n=function(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new It};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new It,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=n,n}}}(),i={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++)i.probe.push(new un);const r=new un,s=new kn,a=new kn;return{setup:function(r){let s=0,a=0,o=0;for(let e=0;e<9;e++)i.probe[e].set(0,0,0);let l=0,u=0,c=0,h=0,d=0,p=0,f=0,m=0,g=0,_=0,v=0;r.sort(kl);for(let e=0,y=r.length;e0&&(!0===e.has("OES_texture_float_linear")?(i.rectAreaLTC1=xa.LTC_FLOAT_1,i.rectAreaLTC2=xa.LTC_FLOAT_2):(i.rectAreaLTC1=xa.LTC_HALF_1,i.rectAreaLTC2=xa.LTC_HALF_2)),i.ambient[0]=s,i.ambient[1]=a,i.ambient[2]=o;const y=i.hash;y.directionalLength===l&&y.pointLength===u&&y.spotLength===c&&y.rectAreaLength===h&&y.hemiLength===d&&y.numDirectionalShadows===p&&y.numPointShadows===f&&y.numSpotShadows===m&&y.numSpotMaps===g&&y.numLightProbes===v||(i.directional.length=l,i.spot.length=c,i.rectArea.length=h,i.point.length=u,i.hemi.length=d,i.directionalShadow.length=p,i.directionalShadowMap.length=p,i.pointShadow.length=f,i.pointShadowMap.length=f,i.spotShadow.length=m,i.spotShadowMap.length=m,i.directionalShadowMatrix.length=p,i.pointShadowMatrix.length=f,i.spotLightMatrix.length=m+g-_,i.spotLightMap.length=g,i.numSpotLightShadowsWithMaps=_,i.numLightProbes=v,y.directionalLength=l,y.pointLength=u,y.spotLength=c,y.rectAreaLength=h,y.hemiLength=d,y.numDirectionalShadows=p,y.numPointShadows=f,y.numSpotShadows=m,y.numSpotMaps=g,y.numLightProbes=v,i.version=Bl++)},setupView:function(e,t){let n=0,o=0,l=0,u=0,c=0;const h=t.matrixWorldInverse;for(let t=0,d=e.length;t=r.length?(s=new Gl(e),r.push(s)):s=r[i],s},dispose:function(){t=new WeakMap}}}function Hl(e,t,n){let i=new Xr;const r=new It,s=new It,a=new nn,o=new Ns({depthPacking:3201}),l=new Ps,u={},c=n.maxTextureSize,h={[p]:1,[f]:0,[m]:2},d=new xr({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new It},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"}),g=d.clone();g.defines.HORIZONTAL_PASS=1;const _=new tr;_.setAttribute("position",new Hi(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new pr(_,d),y=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let x=this.type;function b(n,i){const s=t.update(v);d.defines.VSM_SAMPLES!==n.blurSamples&&(d.defines.VSM_SAMPLES=n.blurSamples,g.defines.VSM_SAMPLES=n.blurSamples,d.needsUpdate=!0,g.needsUpdate=!0),null===n.mapPass&&(n.mapPass=new sn(r.x,r.y)),d.uniforms.shadow_pass.value=n.map.texture,d.uniforms.resolution.value=n.mapSize,d.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(i,null,s,d,v,null),g.uniforms.shadow_pass.value=n.mapPass.texture,g.uniforms.resolution.value=n.mapSize,g.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(i,null,s,g,v,null)}function S(t,n,i,r){let s=null;const a=!0===i.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(void 0!==a)s=a;else if(s=!0===i.isPointLight?l:o,e.localClippingEnabled&&!0===n.clipShadows&&Array.isArray(n.clippingPlanes)&&0!==n.clippingPlanes.length||n.displacementMap&&0!==n.displacementScale||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0){const e=s.uuid,t=n.uuid;let i=u[e];void 0===i&&(i={},u[e]=i);let r=i[t];void 0===r&&(r=s.clone(),i[t]=r,n.addEventListener("dispose",M)),s=r}if(s.visible=n.visible,s.wireframe=n.wireframe,s.side=3===r?null!==n.shadowSide?n.shadowSide:n.side:null!==n.shadowSide?n.shadowSide:h[n.side],s.alphaMap=n.alphaMap,s.alphaTest=n.alphaTest,s.map=n.map,s.clipShadows=n.clipShadows,s.clippingPlanes=n.clippingPlanes,s.clipIntersection=n.clipIntersection,s.displacementMap=n.displacementMap,s.displacementScale=n.displacementScale,s.displacementBias=n.displacementBias,s.wireframeLinewidth=n.wireframeLinewidth,s.linewidth=n.linewidth,!0===i.isPointLight&&!0===s.isMeshDistanceMaterial){e.properties.get(s).light=i}return s}function T(n,r,s,a,o){if(!1===n.visible)return;if(n.layers.test(r.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&3===o)&&(!n.frustumCulled||i.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,n.matrixWorld);const i=t.update(n),l=n.material;if(Array.isArray(l)){const t=i.groups;for(let u=0,c=t.length;uc||r.y>c)&&(r.x>c&&(s.x=Math.floor(c/m.x),r.x=s.x*m.x,h.mapSize.x=s.x),r.y>c&&(s.y=Math.floor(c/m.y),r.y=s.y*m.y,h.mapSize.y=s.y)),null===h.map||!0===p||!0===f){const e=3!==this.type?{minFilter:K,magFilter:K}:{};null!==h.map&&h.map.dispose(),h.map=new sn(r.x,r.y,e),h.map.texture.name=u.name+".shadowMap",h.camera.updateProjectionMatrix()}e.setRenderTarget(h.map),e.clear();const g=h.getViewportCount();for(let e=0;e=1):-1!==Y.indexOf("OpenGL ES")&&($=parseFloat(/^OpenGL ES (\d)/.exec(Y)[1]),q=$>=2);let K=null,Z={};const Q=e.getParameter(e.SCISSOR_BOX),J=e.getParameter(e.VIEWPORT),ee=(new nn).fromArray(Q),te=(new nn).fromArray(J);function ne(t,n,i,r){const s=new Uint8Array(4),a=e.createTexture();e.bindTexture(t,a),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let a=0;an||r.height>n)&&(i=n/Math.max(r.width,r.height)),i<1){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof VideoFrame&&e instanceof VideoFrame){const n=Math.floor(i*r.width),s=Math.floor(i*r.height);void 0===h&&(h=f(n,s));const a=t?f(n,s):h;a.width=n,a.height=s;return a.getContext("2d").drawImage(e,0,0,n,s),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+r.width+"x"+r.height+") to ("+n+"x"+s+")."),a}return"data"in e&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+r.width+"x"+r.height+")."),e}return e}function g(e){return e.generateMipmaps}function _(t){e.generateMipmap(t)}function v(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 y(n,i,r,s,a=!1){if(null!==n){if(void 0!==e[n])return e[n];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'")}let o=i;if(i===e.RED&&(r===e.FLOAT&&(o=e.R32F),r===e.HALF_FLOAT&&(o=e.R16F),r===e.UNSIGNED_BYTE&&(o=e.R8)),i===e.RED_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.R8UI),r===e.UNSIGNED_SHORT&&(o=e.R16UI),r===e.UNSIGNED_INT&&(o=e.R32UI),r===e.BYTE&&(o=e.R8I),r===e.SHORT&&(o=e.R16I),r===e.INT&&(o=e.R32I)),i===e.RG&&(r===e.FLOAT&&(o=e.RG32F),r===e.HALF_FLOAT&&(o=e.RG16F),r===e.UNSIGNED_BYTE&&(o=e.RG8)),i===e.RG_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RG8UI),r===e.UNSIGNED_SHORT&&(o=e.RG16UI),r===e.UNSIGNED_INT&&(o=e.RG32UI),r===e.BYTE&&(o=e.RG8I),r===e.SHORT&&(o=e.RG16I),r===e.INT&&(o=e.RG32I)),i===e.RGB_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RGB8UI),r===e.UNSIGNED_SHORT&&(o=e.RGB16UI),r===e.UNSIGNED_INT&&(o=e.RGB32UI),r===e.BYTE&&(o=e.RGB8I),r===e.SHORT&&(o=e.RGB16I),r===e.INT&&(o=e.RGB32I)),i===e.RGBA_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RGBA8UI),r===e.UNSIGNED_SHORT&&(o=e.RGBA16UI),r===e.UNSIGNED_INT&&(o=e.RGBA32UI),r===e.BYTE&&(o=e.RGBA8I),r===e.SHORT&&(o=e.RGBA16I),r===e.INT&&(o=e.RGBA32I)),i===e.RGB&&r===e.UNSIGNED_INT_5_9_9_9_REV&&(o=e.RGB9_E5),i===e.RGBA){const t=a?ot:Xt.getTransfer(s);r===e.FLOAT&&(o=e.RGBA32F),r===e.HALF_FLOAT&&(o=e.RGBA16F),r===e.UNSIGNED_BYTE&&(o=t===lt?e.SRGB8_ALPHA8:e.RGBA8),r===e.UNSIGNED_SHORT_4_4_4_4&&(o=e.RGBA4),r===e.UNSIGNED_SHORT_5_5_5_1&&(o=e.RGB5_A1)}return o!==e.R16F&&o!==e.R32F&&o!==e.RG16F&&o!==e.RG32F&&o!==e.RGBA16F&&o!==e.RGBA32F||t.get("EXT_color_buffer_float"),o}function x(t,n){let i;return t?null===n||n===oe||n===de?i=e.DEPTH24_STENCIL8:n===le?i=e.DEPTH32F_STENCIL8:n===se&&(i=e.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===n||n===oe||n===de?i=e.DEPTH_COMPONENT24:n===le?i=e.DEPTH_COMPONENT32F:n===se&&(i=e.DEPTH_COMPONENT16),i}function b(e,t){return!0===g(e)||e.isFramebufferTexture&&e.minFilter!==K&&e.minFilter!==J?Math.log2(Math.max(t.width,t.height))+1:void 0!==e.mipmaps&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function S(e){const t=e.target;t.removeEventListener("dispose",S),function(e){const t=i.get(e);if(void 0===t.__webglInit)return;const n=e.source,r=d.get(n);if(r){const i=r[t.__cacheKey];i.usedTimes--,0===i.usedTimes&&M(e),0===Object.keys(r).length&&d.delete(n)}i.remove(e)}(t),t.isVideoTexture&&c.delete(t)}function T(t){const n=t.target;n.removeEventListener("dispose",T),function(t){const n=i.get(t);t.depthTexture&&(t.depthTexture.dispose(),i.remove(t.depthTexture));if(t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let i=0;i0&&s.__version!==t.version){const e=t.image;if(null===e)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==e.complete)return void D(s,t,r);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}n.bindTexture(e.TEXTURE_2D,s.__webglTexture,e.TEXTURE0+r)}const A={[q]:e.REPEAT,[$]:e.CLAMP_TO_EDGE,[Y]:e.MIRRORED_REPEAT},R={[K]:e.NEAREST,[Z]:e.NEAREST_MIPMAP_NEAREST,[Q]:e.NEAREST_MIPMAP_LINEAR,[J]:e.LINEAR,[ee]:e.LINEAR_MIPMAP_NEAREST,[te]:e.LINEAR_MIPMAP_LINEAR},C={[ct]:e.NEVER,[_t]:e.ALWAYS,[ht]:e.LESS,[pt]:e.LEQUAL,[dt]:e.EQUAL,[gt]:e.GEQUAL,[ft]:e.GREATER,[mt]:e.NOTEQUAL};function N(n,s){if(s.type!==le||!1!==t.has("OES_texture_float_linear")||s.magFilter!==J&&s.magFilter!==ee&&s.magFilter!==Q&&s.magFilter!==te&&s.minFilter!==J&&s.minFilter!==ee&&s.minFilter!==Q&&s.minFilter!==te||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,A[s.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,A[s.wrapT]),n!==e.TEXTURE_3D&&n!==e.TEXTURE_2D_ARRAY||e.texParameteri(n,e.TEXTURE_WRAP_R,A[s.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,R[s.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,R[s.minFilter]),s.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,C[s.compareFunction])),!0===t.has("EXT_texture_filter_anisotropic")){if(s.magFilter===K)return;if(s.minFilter!==Q&&s.minFilter!==te)return;if(s.type===le&&!1===t.has("OES_texture_float_linear"))return;if(s.anisotropy>1||i.get(s).__currentAnisotropy){const a=t.get("EXT_texture_filter_anisotropic");e.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),i.get(s).__currentAnisotropy=s.anisotropy}}}function P(t,n){let i=!1;void 0===t.__webglInit&&(t.__webglInit=!0,n.addEventListener("dispose",S));const r=n.source;let s=d.get(r);void 0===s&&(s={},d.set(r,s));const o=function(e){const 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()}(n);if(o!==t.__cacheKey){void 0===s[o]&&(s[o]={texture:e.createTexture(),usedTimes:0},a.memory.textures++,i=!0),s[o].usedTimes++;const r=s[t.__cacheKey];void 0!==r&&(s[t.__cacheKey].usedTimes--,0===r.usedTimes&&M(n)),t.__cacheKey=o,t.__webglTexture=s[o].texture}return i}function D(t,a,o){let l=e.TEXTURE_2D;(a.isDataArrayTexture||a.isCompressedArrayTexture)&&(l=e.TEXTURE_2D_ARRAY),a.isData3DTexture&&(l=e.TEXTURE_3D);const u=P(t,a),c=a.source;n.bindTexture(l,t.__webglTexture,e.TEXTURE0+o);const h=i.get(c);if(c.version!==h.__version||!0===u){n.activeTexture(e.TEXTURE0+o);const t=Xt.getPrimaries(Xt.workingColorSpace),i=a.colorSpace===rt?null:Xt.getPrimaries(a.colorSpace),d=a.colorSpace===rt||t===i?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 p=m(a.image,!1,r.maxTextureSize);p=z(a,p);const f=s.convert(a.format,a.colorSpace),v=s.convert(a.type);let S,T=y(a.internalFormat,f,v,a.colorSpace,a.isVideoTexture);N(l,a);const M=a.mipmaps,E=!0!==a.isVideoTexture,w=void 0===h.__version||!0===u,A=c.dataReady,R=b(a,p);if(a.isDepthTexture)T=x(a.format===xe,a.type),w&&(E?n.texStorage2D(e.TEXTURE_2D,1,T,p.width,p.height):n.texImage2D(e.TEXTURE_2D,0,T,p.width,p.height,0,f,v,null));else if(a.isDataTexture)if(M.length>0){E&&w&&n.texStorage2D(e.TEXTURE_2D,R,T,M[0].width,M[0].height);for(let t=0,i=M.length;t0){const i=ga(S.width,S.height,a.format,a.type);for(const r of a.layerUpdates){const s=S.data.subarray(r*i/S.data.BYTES_PER_ELEMENT,(r+1)*i/S.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,r,S.width,S.height,1,f,s)}a.clearLayerUpdates()}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,S.width,S.height,p.depth,f,S.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,t,T,S.width,S.height,p.depth,0,S.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else E?A&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,S.width,S.height,p.depth,f,v,S.data):n.texImage3D(e.TEXTURE_2D_ARRAY,t,T,S.width,S.height,p.depth,0,f,v,S.data)}else{E&&w&&n.texStorage2D(e.TEXTURE_2D,R,T,M[0].width,M[0].height);for(let t=0,i=M.length;t0){const t=ga(p.width,p.height,a.format,a.type);for(const i of a.layerUpdates){const r=p.data.subarray(i*t/p.data.BYTES_PER_ELEMENT,(i+1)*t/p.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,i,p.width,p.height,1,f,v,r)}a.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,p.width,p.height,p.depth,f,v,p.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,T,p.width,p.height,p.depth,0,f,v,p.data);else if(a.isData3DTexture)E?(w&&n.texStorage3D(e.TEXTURE_3D,R,T,p.width,p.height,p.depth),A&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,p.width,p.height,p.depth,f,v,p.data)):n.texImage3D(e.TEXTURE_3D,0,T,p.width,p.height,p.depth,0,f,v,p.data);else if(a.isFramebufferTexture){if(w)if(E)n.texStorage2D(e.TEXTURE_2D,R,T,p.width,p.height);else{let t=p.width,i=p.height;for(let r=0;r>=1,i>>=1}}else if(M.length>0){if(E&&w){const t=G(M[0]);n.texStorage2D(e.TEXTURE_2D,R,T,t.width,t.height)}for(let t=0,i=M.length;t>c),i=Math.max(1,r.height>>c);u===e.TEXTURE_3D||u===e.TEXTURE_2D_ARRAY?n.texImage3D(u,c,p,t,i,r.depth,0,h,d,null):n.texImage2D(u,c,p,t,i,0,h,d,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),k(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,l,u,m.__webglTexture,0,B(r)):(u===e.TEXTURE_2D||u>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&u<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,l,u,m.__webglTexture,c),n.bindFramebuffer(e.FRAMEBUFFER,null)}function L(t,n,i){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){const r=n.depthTexture,s=r&&r.isDepthTexture?r.type:null,a=x(n.stencilBuffer,s),l=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,u=B(n);k(n)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,u,a,n.width,n.height):i?e.renderbufferStorageMultisample(e.RENDERBUFFER,u,a,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,a,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,l,e.RENDERBUFFER,t)}else{const t=n.textures;for(let r=0;r{delete r.__boundDepthTexture,delete r.__depthDisposeCallback,e.removeEventListener("dispose",t)};e.addEventListener("dispose",t),r.__depthDisposeCallback=t}r.__boundDepthTexture=e}if(t.depthTexture&&!r.__autoAllocateDepthBuffer){if(s)throw new Error("target.depthTexture not supported in Cube render targets");!function(t,r){if(r&&r.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(e.FRAMEBUFFER,t),!r.depthTexture||!r.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const s=i.get(r.depthTexture);s.__renderTarget=r,s.__webglTexture&&r.depthTexture.image.width===r.width&&r.depthTexture.image.height===r.height||(r.depthTexture.image.width=r.width,r.depthTexture.image.height=r.height,r.depthTexture.needsUpdate=!0),w(r.depthTexture,0);const a=s.__webglTexture,l=B(r);if(r.depthTexture.format===ye)k(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,a,0,l):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,a,0);else{if(r.depthTexture.format!==xe)throw new Error("Unknown depthTexture format");k(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,a,0,l):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,a,0)}}(r.__webglFramebuffer,t)}else if(s){r.__webglDepthbuffer=[];for(let i=0;i<6;i++)if(n.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer[i]),void 0===r.__webglDepthbuffer[i])r.__webglDepthbuffer[i]=e.createRenderbuffer(),L(r.__webglDepthbuffer[i],t,!1);else{const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,s=r.__webglDepthbuffer[i];e.bindRenderbuffer(e.RENDERBUFFER,s),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,s)}}else if(n.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer),void 0===r.__webglDepthbuffer)r.__webglDepthbuffer=e.createRenderbuffer(),L(r.__webglDepthbuffer,t,!1);else{const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,i=r.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,i),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,i)}n.bindFramebuffer(e.FRAMEBUFFER,null)}const O=[],F=[];function B(e){return Math.min(r.maxSamples,e.samples)}function k(e){const n=i.get(e);return e.samples>0&&!0===t.has("WEBGL_multisampled_render_to_texture")&&!1!==n.__useRenderToTexture}function z(e,t){const n=e.colorSpace,i=e.format,r=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||n!==at&&n!==rt&&(Xt.getTransfer(n)===lt?i===ge&&r===ne||console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",n)),t}function G(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement?(u.width=e.naturalWidth||e.width,u.height=e.naturalHeight||e.height):"undefined"!=typeof VideoFrame&&e instanceof VideoFrame?(u.width=e.displayWidth,u.height=e.displayHeight):(u.width=e.width,u.height=e.height),u}this.allocateTextureUnit=function(){const e=E;return e>=r.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+e+" texture units while this GPU supports only "+r.maxTextures),E+=1,e},this.resetTextureUnits=function(){E=0},this.setTexture2D=w,this.setTexture2DArray=function(t,r){const s=i.get(t);t.version>0&&s.__version!==t.version?D(s,t,r):n.bindTexture(e.TEXTURE_2D_ARRAY,s.__webglTexture,e.TEXTURE0+r)},this.setTexture3D=function(t,r){const s=i.get(t);t.version>0&&s.__version!==t.version?D(s,t,r):n.bindTexture(e.TEXTURE_3D,s.__webglTexture,e.TEXTURE0+r)},this.setTextureCube=function(t,a){const o=i.get(t);t.version>0&&o.__version!==t.version?function(t,a,o){if(6!==a.image.length)return;const l=P(t,a),u=a.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+o);const c=i.get(u);if(u.version!==c.__version||!0===l){n.activeTexture(e.TEXTURE0+o);const t=Xt.getPrimaries(Xt.workingColorSpace),i=a.colorSpace===rt?null:Xt.getPrimaries(a.colorSpace),h=a.colorSpace===rt||t===i?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,h);const d=a.isCompressedTexture||a.image[0].isCompressedTexture,p=a.image[0]&&a.image[0].isDataTexture,f=[];for(let e=0;e<6;e++)f[e]=d||p?p?a.image[e].image:a.image[e]:m(a.image[e],!0,r.maxCubemapSize),f[e]=z(a,f[e]);const v=f[0],x=s.convert(a.format,a.colorSpace),S=s.convert(a.type),T=y(a.internalFormat,x,S,a.colorSpace),M=!0!==a.isVideoTexture,E=void 0===c.__version||!0===l,w=u.dataReady;let A,R=b(a,v);if(N(e.TEXTURE_CUBE_MAP,a),d){M&&E&&n.texStorage2D(e.TEXTURE_CUBE_MAP,R,T,v.width,v.height);for(let t=0;t<6;t++){A=f[t].mipmaps;for(let i=0;i0&&R++;const t=G(f[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,R,T,t.width,t.height)}for(let t=0;t<6;t++)if(p){M?w&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,f[t].width,f[t].height,x,S,f[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,T,f[t].width,f[t].height,0,x,S,f[t].data);for(let i=0;i1;if(h||(void 0===l.__webglTexture&&(l.__webglTexture=e.createTexture()),l.__version=r.version,a.memory.textures++),c){o.__webglFramebuffer=[];for(let t=0;t<6;t++)if(r.mipmaps&&r.mipmaps.length>0){o.__webglFramebuffer[t]=[];for(let n=0;n0){o.__webglFramebuffer=[];for(let t=0;t0&&!1===k(t)){o.__webglMultisampledFramebuffer=e.createFramebuffer(),o.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let n=0;n0)for(let i=0;i0)for(let n=0;n0)if(!1===k(t)){const r=t.textures,s=t.width,a=t.height;let o=e.COLOR_BUFFER_BIT;const u=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,c=i.get(t),h=r.length>1;if(h)for(let t=0;t= 1.0 ) {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;\n\n\t} else {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;\n\n\t}\n\n}",uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new pr(new xs(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Yl extends Tt{constructor(e,t){super();const n=this;let i=null,r=1,s=null,a="local-floor",o=1,l=null,u=null,c=null,h=null,d=null,p=null;const f=new $l,m=t.getContextAttributes();let g=null,_=null;const v=[],y=[],x=new It;let b=null;const S=new Er;S.viewport=new nn;const T=new Er;T.viewport=new nn;const M=[S,T],E=new sa;let w=null,A=null;function R(e){const t=y.indexOf(e.inputSource);if(-1===t)return;const n=v[t];void 0!==n&&(n.update(e.inputSource,e.frame,l||s),n.dispatchEvent({type:e.type,data:e.inputSource}))}function C(){i.removeEventListener("select",R),i.removeEventListener("selectstart",R),i.removeEventListener("selectend",R),i.removeEventListener("squeeze",R),i.removeEventListener("squeezestart",R),i.removeEventListener("squeezeend",R),i.removeEventListener("end",C),i.removeEventListener("inputsourceschange",N);for(let e=0;e=0&&(y[i]=null,v[i].disconnect(n))}for(let t=0;t=y.length){y.push(n),i=e;break}if(null===y[e]){y[e]=n,i=e;break}}if(-1===i)break}const r=v[i];r&&r.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=v[e];return void 0===t&&(t=new Dr,v[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=v[e];return void 0===t&&(t=new Dr,v[e]=t),t.getGripSpace()},this.getHand=function(e){let t=v[e];return void 0===t&&(t=new Dr,v[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){r=e,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(e){a=e,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||s},this.setReferenceSpace=function(e){l=e},this.getBaseLayer=function(){return null!==h?h:d},this.getBinding=function(){return c},this.getFrame=function(){return p},this.getSession=function(){return i},this.setSession=async function(u){if(i=u,null!==i){g=e.getRenderTarget(),i.addEventListener("select",R),i.addEventListener("selectstart",R),i.addEventListener("selectend",R),i.addEventListener("squeeze",R),i.addEventListener("squeezestart",R),i.addEventListener("squeezeend",R),i.addEventListener("end",C),i.addEventListener("inputsourceschange",N),!0!==m.xrCompatible&&await t.makeXRCompatible(),b=e.getPixelRatio(),e.getSize(x);if("undefined"!=typeof XRWebGLBinding&&"createProjectionLayer"in XRWebGLBinding.prototype){let n=null,s=null,a=null;m.depth&&(a=m.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=m.stencil?xe:ye,s=m.stencil?de:oe);const o={colorFormat:t.RGBA8,depthFormat:a,scaleFactor:r};c=new XRWebGLBinding(i,t),h=c.createProjectionLayer(o),i.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),_=new sn(h.textureWidth,h.textureHeight,{format:ge,type:ne,depthTexture:new rs(h.textureWidth,h.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:m.stencil,colorSpace:e.outputColorSpace,samples:m.antialias?4:0,resolveDepthBuffer:!1===h.ignoreDepthValues,resolveStencilBuffer:!1===h.ignoreDepthValues})}else{const n={antialias:m.antialias,alpha:!0,depth:m.depth,stencil:m.stencil,framebufferScaleFactor:r};d=new XRWebGLLayer(i,t,n),i.updateRenderState({baseLayer:d}),e.setPixelRatio(1),e.setSize(d.framebufferWidth,d.framebufferHeight,!1),_=new sn(d.framebufferWidth,d.framebufferHeight,{format:ge,type:ne,colorSpace:e.outputColorSpace,stencilBuffer:m.stencil,resolveDepthBuffer:!1===d.ignoreDepthValues,resolveStencilBuffer:!1===d.ignoreDepthValues})}_.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await i.requestReferenceSpace(a),I.setContext(i),I.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==i)return i.environmentBlendMode},this.getDepthTexture=function(){return f.getDepthTexture()};const P=new un,D=new un;function U(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(null===i)return;let t=e.near,n=e.far;null!==f.texture&&(f.depthNear>0&&(t=f.depthNear),f.depthFar>0&&(n=f.depthFar)),E.near=T.near=S.near=t,E.far=T.far=S.far=n,w===E.near&&A===E.far||(i.updateRenderState({depthNear:E.near,depthFar:E.far}),w=E.near,A=E.far),S.layers.mask=2|e.layers.mask,T.layers.mask=4|e.layers.mask,E.layers.mask=S.layers.mask|T.layers.mask;const r=e.parent,s=E.cameras;U(E,r);for(let e=0;e0&&(e.alphaTest.value=i.alphaTest);const r=t.get(i),s=r.envMap,a=r.envMapRotation;s&&(e.envMap.value=s,Kl.copy(a),Kl.x*=-1,Kl.y*=-1,Kl.z*=-1,s.isCubeTexture&&!1===s.isRenderTargetTexture&&(Kl.y*=-1,Kl.z*=-1),e.envMapRotation.value.setFromMatrix4(Zl.makeRotationFromEuler(Kl)),e.flipEnvMap.value=s.isCubeTexture&&!1===s.isRenderTargetTexture?-1:1,e.reflectivity.value=i.reflectivity,e.ior.value=i.ior,e.refractionRatio.value=i.refractionRatio),i.lightMap&&(e.lightMap.value=i.lightMap,e.lightMapIntensity.value=i.lightMapIntensity,n(i.lightMap,e.lightMapTransform)),i.aoMap&&(e.aoMap.value=i.aoMap,e.aoMapIntensity.value=i.aoMapIntensity,n(i.aoMap,e.aoMapTransform))}return{refreshFogUniforms:function(t,n){n.color.getRGB(t.fogColor.value,vr(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)},refreshMaterialUniforms:function(e,r,s,a,o){r.isMeshBasicMaterial||r.isMeshLambertMaterial?i(e,r):r.isMeshToonMaterial?(i(e,r),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}(e,r)):r.isMeshPhongMaterial?(i(e,r),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}(e,r)):r.isMeshStandardMaterial?(i(e,r),function(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)}(e,r),r.isMeshPhysicalMaterial&&function(e,t,i){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),1===t.side&&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=i.texture,e.transmissionSamplerSize.value.set(i.width,i.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))}(e,r,o)):r.isMeshMatcapMaterial?(i(e,r),function(e,t){t.matcap&&(e.matcap.value=t.matcap)}(e,r)):r.isMeshDepthMaterial?i(e,r):r.isMeshDistanceMaterial?(i(e,r),function(e,n){const i=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(i.matrixWorld),e.nearDistance.value=i.shadow.camera.near,e.farDistance.value=i.shadow.camera.far}(e,r)):r.isMeshNormalMaterial?i(e,r):r.isLineBasicMaterial?(function(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))}(e,r),r.isLineDashedMaterial&&function(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}(e,r)):r.isPointsMaterial?function(e,t,i,r){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*i,e.scale.value=.5*r,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)}(e,r,s,a):r.isSpriteMaterial?function(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)}(e,r):r.isShadowMaterial?(e.color.value.copy(r.color),e.opacity.value=r.opacity):r.isShaderMaterial&&(r.uniformsNeedUpdate=!1)}}}function Jl(e,t,n,i){let r={},s={},a=[];const o=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function l(e,t,n,i){const r=e.value,s=t+"_"+n;if(void 0===i[s])return i[s]="number"==typeof r||"boolean"==typeof r?r:r.clone(),!0;{const e=i[s];if("number"==typeof r||"boolean"==typeof r){if(e!==r)return i[s]=r,!0}else if(!1===e.equals(r))return e.copy(r),!0}return!1}function u(e){const t={boundary:0,storage:0};return"number"==typeof e||"boolean"==typeof e?(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 c(t){const n=t.target;n.removeEventListener("dispose",c);const i=a.indexOf(n.__bindingPointIndex);a.splice(i,1),e.deleteBuffer(r[n.id]),delete r[n.id],delete s[n.id]}return{bind:function(e,t){const n=t.program;i.uniformBlockBinding(e,n)},update:function(n,h){let d=r[n.id];void 0===d&&(!function(e){const t=e.uniforms;let n=0;const i=16;for(let e=0,r=t.length;e0&&(n+=i-r);e.__size=n,e.__cache={}}(n),d=function(t){const n=function(){for(let e=0;e0){const e=du[0].object;eu.setFromNormalAndCoplanarPoint(t.getWorldDirection(eu.normal),au.setFromMatrixPosition(e.matrixWorld)),hu!==e&&null!==hu&&(this.dispatchEvent({type:"hoveroff",object:hu}),n.style.cursor="auto",hu=null),hu!==e&&(this.dispatchEvent({type:"hoveron",object:e}),n.style.cursor="pointer",hu=e)}else null!==hu&&(this.dispatchEvent({type:"hoveroff",object:hu}),n.style.cursor="auto",hu=null);ru.copy(tu)}}function vu(e){const t=this.object,n=this.domElement,i=this.raycaster;!1!==this.enabled&&(this._updatePointer(e),this._updateState(e),du.length=0,i.setFromCamera(tu,t),i.intersectObjects(this.objects,this.recursive,du),du.length>0&&(cu=!0===this.transformGroup?bu(du[0].object):du[0].object,eu.setFromNormalAndCoplanarPoint(t.getWorldDirection(eu.normal),au.setFromMatrixPosition(cu.matrixWorld)),i.ray.intersectPlane(eu,su)&&(this.state===fu?(ou.copy(cu.parent.matrixWorld).invert(),nu.copy(su).sub(au.setFromMatrixPosition(cu.matrixWorld))):this.state===mu&&(lu.set(0,1,0).applyQuaternion(t.quaternion).normalize(),uu.set(1,0,0).applyQuaternion(t.quaternion).normalize())),n.style.cursor="move",this.dispatchEvent({type:"dragstart",object:cu})),ru.copy(tu))}function yu(){!1!==this.enabled&&(cu&&(this.dispatchEvent({type:"dragend",object:cu}),cu=null),this.domElement.style.cursor=hu?"pointer":"auto",this.state=pu)}function xu(e){!1!==this.enabled&&e.preventDefault()}function bu(e,t=null){return e.isGroup&&(t=e),null===e.parent?t:bu(e.parent,t)}function Su(e,t,n){var i,r=1;function s(){var s,a,o=i.length,l=0,u=0,c=0;for(s=0;s=(r=(h+d)/2))?h=r:d=r,i=u,!(u=u[o=+a]))return i[o]=c,e;if(t===(s=+e._x.call(null,u.data)))return c.next=u,i?i[o]=c:e._root=c,e;do{i=i?i[o]=new Array(2):e._root=new Array(2),(a=t>=(r=(h+d)/2))?h=r:d=r}while((o=+a)==(l=+(s>=r)));return i[l]=u,i[o]=c,e}function Mu(e,t,n){this.node=e,this.x0=t,this.x1=n}function Eu(e){return e[0]}function wu(e,t){var n=new Au(null==t?Eu:t,NaN,NaN);return null==e?n:n.addAll(e)}function Au(e,t,n){this._x=e,this._x0=t,this._x1=n,this._root=void 0}function Ru(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var Cu=wu.prototype=Au.prototype;function Nu(e,t,n,i){if(isNaN(t)||isNaN(n))return e;var r,s,a,o,l,u,c,h,d,p=e._root,f={data:i},m=e._x0,g=e._y0,_=e._x1,v=e._y1;if(!p)return e._root=f,e;for(;p.length;)if((u=t>=(s=(m+_)/2))?m=s:_=s,(c=n>=(a=(g+v)/2))?g=a:v=a,r=p,!(p=p[h=c<<1|u]))return r[h]=f,e;if(o=+e._x.call(null,p.data),l=+e._y.call(null,p.data),t===o&&n===l)return f.next=p,r?r[h]=f:e._root=f,e;do{r=r?r[h]=new Array(4):e._root=new Array(4),(u=t>=(s=(m+_)/2))?m=s:_=s,(c=n>=(a=(g+v)/2))?g=a:v=a}while((h=c<<1|u)==(d=(l>=a)<<1|o>=s));return r[d]=p,r[h]=f,e}function Pu(e,t,n,i,r){this.node=e,this.x0=t,this.y0=n,this.x1=i,this.y1=r}function Du(e){return e[0]}function Uu(e){return e[1]}function Lu(e,t,n){var i=new Iu(null==t?Du:t,null==n?Uu:n,NaN,NaN,NaN,NaN);return null==e?i:i.addAll(e)}function Iu(e,t,n,i,r,s){this._x=e,this._y=t,this._x0=n,this._y0=i,this._x1=r,this._y1=s,this._root=void 0}function Ou(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}Cu.copy=function(){var e,t,n=new Au(this._x,this._x0,this._x1),i=this._root;if(!i)return n;if(!i.length)return n._root=Ru(i),n;for(e=[{source:i,target:n._root=new Array(2)}];i=e.pop();)for(var r=0;r<2;++r)(t=i.source[r])&&(t.length?e.push({source:t,target:i.target[r]=new Array(2)}):i.target[r]=Ru(t));return n},Cu.add=function(e){const t=+this._x.call(null,e);return Tu(this.cover(t),t,e)},Cu.addAll=function(e){Array.isArray(e)||(e=Array.from(e));const t=e.length,n=new Float64Array(t);let i=1/0,r=-1/0;for(let s,a=0;ar&&(r=s));if(i>r)return this;this.cover(i).cover(r);for(let i=0;ie||e>=n;)switch(r=+(el||(r=s.x1)=h))&&(s=u[u.length-1],u[u.length-1]=u[u.length-1-a],u[u.length-1-a]=s)}else{var d=Math.abs(e-+this._x.call(null,c.data));d=(a=(h+d)/2))?h=a:d=a,t=c,!(c=c[l=+o]))return this;if(!c.length)break;t[l+1&1]&&(n=t,u=l)}for(;c.data!==e;)if(i=c,!(c=c.next))return this;return(r=c.next)&&delete c.next,i?(r?i.next=r:delete i.next,this):t?(r?t[l]=r:delete t[l],(c=t[0]||t[1])&&c===(t[1]||t[0])&&!c.length&&(n?n[u]=c:this._root=c),this):(this._root=r,this)},Cu.removeAll=function(e){for(var t=0,n=e.length;t=(a=(y+S)/2))?y=a:S=a,(p=n>=(o=(x+T)/2))?x=o:T=o,(f=i>=(l=(b+M)/2))?b=l:M=l,s=_,!(_=_[m=f<<2|p<<1|d]))return s[m]=v,e;if(u=+e._x.call(null,_.data),c=+e._y.call(null,_.data),h=+e._z.call(null,_.data),t===u&&n===c&&i===h)return v.next=_,s?s[m]=v:e._root=v,e;do{s=s?s[m]=new Array(8):e._root=new Array(8),(d=t>=(a=(y+S)/2))?y=a:S=a,(p=n>=(o=(x+T)/2))?x=o:T=o,(f=i>=(l=(b+M)/2))?b=l:M=l}while((m=f<<2|p<<1|d)==(g=(h>=l)<<2|(c>=o)<<1|u>=a));return s[g]=_,s[m]=v,e}function ku(e,t,n,i,r,s,a){this.node=e,this.x0=t,this.y0=n,this.z0=i,this.x1=r,this.y1=s,this.z1=a}Fu.copy=function(){var e,t,n=new Iu(this._x,this._y,this._x0,this._y0,this._x1,this._y1),i=this._root;if(!i)return n;if(!i.length)return n._root=Ou(i),n;for(e=[{source:i,target:n._root=new Array(4)}];i=e.pop();)for(var r=0;r<4;++r)(t=i.source[r])&&(t.length?e.push({source:t,target:i.target[r]=new Array(4)}):i.target[r]=Ou(t));return n},Fu.add=function(e){const t=+this._x.call(null,e),n=+this._y.call(null,e);return Nu(this.cover(t,n),t,n,e)},Fu.addAll=function(e){var t,n,i,r,s=e.length,a=new Array(s),o=new Array(s),l=1/0,u=1/0,c=-1/0,h=-1/0;for(n=0;nc&&(c=i),rh&&(h=r));if(l>c||u>h)return this;for(this.cover(l,u).cover(c,h),n=0;ne||e>=r||i>t||t>=s;)switch(o=(td||(s=l.y0)>p||(a=l.x1)=_)<<1|e>=g)&&(l=f[f.length-1],f[f.length-1]=f[f.length-1-u],f[f.length-1-u]=l)}else{var v=e-+this._x.call(null,m.data),y=t-+this._y.call(null,m.data),x=v*v+y*y;if(x=(o=(f+g)/2))?f=o:g=o,(c=a>=(l=(m+_)/2))?m=l:_=l,t=p,!(p=p[h=c<<1|u]))return this;if(!p.length)break;(t[h+1&3]||t[h+2&3]||t[h+3&3])&&(n=t,d=h)}for(;p.data!==e;)if(i=p,!(p=p.next))return this;return(r=p.next)&&delete p.next,i?(r?i.next=r:delete i.next,this):t?(r?t[h]=r:delete t[h],(p=t[0]||t[1]||t[2]||t[3])&&p===(t[3]||t[2]||t[1]||t[0])&&!p.length&&(n?n[d]=p:this._root=p),this):(this._root=r,this)},Fu.removeAll=function(e){for(var t=0,n=e.length;tMath.sqrt((e-i)**2+(t-r)**2+(n-s)**2);function Gu(e){return e[0]}function Vu(e){return e[1]}function Hu(e){return e[2]}function ju(e,t,n,i){var r=new Wu(null==t?Gu:t,null==n?Vu:n,null==i?Hu:i,NaN,NaN,NaN,NaN,NaN,NaN);return null==e?r:r.addAll(e)}function Wu(e,t,n,i,r,s,a,o,l){this._x=e,this._y=t,this._z=n,this._x0=i,this._y0=r,this._z0=s,this._x1=a,this._y1=o,this._z1=l,this._root=void 0}function Xu(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var qu=ju.prototype=Wu.prototype;function $u(e){return function(){return e}}function Yu(e){return 1e-6*(e()-.5)}function Ku(e){return e.index}function Zu(e,t){var n=e.get(t);if(!n)throw new Error("node not found: "+t);return n}function Qu(e){var t,n,i,r,s,a,o,l=Ku,u=function(e){return 1/Math.min(s[e.source.index],s[e.target.index])},c=$u(30),h=1;function d(i){for(var s=0,l=e.length;s1&&(_=d.y+d.vy-c.y-c.vy||Yu(o)),r>2&&(v=d.z+d.vz-c.z-c.vz||Yu(o)),g*=p=((p=Math.sqrt(g*g+_*_+v*v))-n[m])/p*i*t[m],_*=p,v*=p,d.vx-=g*(f=a[m]),r>1&&(d.vy-=_*f),r>2&&(d.vz-=v*f),c.vx+=g*(f=1-f),r>1&&(c.vy+=_*f),r>2&&(c.vz+=v*f)}function p(){if(i){var r,o,u=i.length,c=e.length,h=new Map(i.map(((e,t)=>[l(e,t,i),e])));for(r=0,s=new Array(u);r"function"==typeof e))||Math.random,r=t.find((e=>[1,2,3].includes(e)))||2,p()},d.links=function(t){return arguments.length?(e=t,p(),d):e},d.id=function(e){return arguments.length?(l=e,d):l},d.iterations=function(e){return arguments.length?(h=+e,d):h},d.strength=function(e){return arguments.length?(u="function"==typeof e?e:$u(+e),f(),d):u},d.distance=function(e){return arguments.length?(c="function"==typeof e?e:$u(+e),m(),d):c},d}qu.copy=function(){var e,t,n=new Wu(this._x,this._y,this._z,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1),i=this._root;if(!i)return n;if(!i.length)return n._root=Xu(i),n;for(e=[{source:i,target:n._root=new Array(8)}];i=e.pop();)for(var r=0;r<8;++r)(t=i.source[r])&&(t.length?e.push({source:t,target:i.target[r]=new Array(8)}):i.target[r]=Xu(t));return n},qu.add=function(e){const t=+this._x.call(null,e),n=+this._y.call(null,e),i=+this._z.call(null,e);return Bu(this.cover(t,n,i),t,n,i,e)},qu.addAll=function(e){Array.isArray(e)||(e=Array.from(e));const t=e.length,n=new Float64Array(t),i=new Float64Array(t),r=new Float64Array(t);let s=1/0,a=1/0,o=1/0,l=-1/0,u=-1/0,c=-1/0;for(let h,d,p,f,m=0;ml&&(l=d),pu&&(u=p),fc&&(c=f));if(s>l||a>u||o>c)return this;this.cover(s,a,o).cover(l,u,c);for(let s=0;se||e>=a||r>t||t>=o||s>n||n>=l;)switch(c=(ng||(a=h.y0)>_||(o=h.z0)>v||(l=h.x1)=T)<<2|(t>=S)<<1|e>=b)&&(h=y[y.length-1],y[y.length-1]=y[y.length-1-d],y[y.length-1-d]=h)}else{var M=e-+this._x.call(null,x.data),E=t-+this._y.call(null,x.data),w=n-+this._z.call(null,x.data),A=M*M+E*E+w*w;if(A{if(!h.length)do{const s=h.data;zu(e,t,n,this._x(s),this._y(s),this._z(s))<=i&&r.push(s)}while(h=h.next);return d>l||p>u||f>c||m=(l=(_+x)/2))?_=l:x=l,(d=a>=(u=(v+b)/2))?v=u:b=u,(p=o>=(c=(y+S)/2))?y=c:S=c,t=g,!(g=g[f=p<<2|d<<1|h]))return this;if(!g.length)break;(t[f+1&7]||t[f+2&7]||t[f+3&7]||t[f+4&7]||t[f+5&7]||t[f+6&7]||t[f+7&7])&&(n=t,m=f)}for(;g.data!==e;)if(i=g,!(g=g.next))return this;return(r=g.next)&&delete g.next,i?(r?i.next=r:delete i.next,this):t?(r?t[f]=r:delete t[f],(g=t[0]||t[1]||t[2]||t[3]||t[4]||t[5]||t[6]||t[7])&&g===(t[7]||t[6]||t[5]||t[4]||t[3]||t[2]||t[1]||t[0])&&!g.length&&(n?n[m]=g:this._root=g),this):(this._root=r,this)},qu.removeAll=function(e){for(var t=0,n=e.length;t{}};function ec(){for(var e,t=0,n=arguments.length,i={};t=0&&(t=e.slice(n+1),e=e.slice(0,n)),e&&!i.hasOwnProperty(e))throw new Error("unknown type: "+e);return{type:e,name:t}}))),a=-1,o=s.length;if(!(arguments.length<2)){if(null!=t&&"function"!=typeof t)throw new Error("invalid callback: "+t);for(;++a0)for(var n,i,r=new Array(n),s=0;s=0&&t._call.call(void 0,e),t=t._next;--ac}()}finally{ac=0,function(){var e,t,n=rc,i=1/0;for(;n;)n._call?(i>n._time&&(i=n._time),e=n,n=n._next):(t=n._next,n._next=null,n=e?e._next=t:rc=t);sc=e,xc(i)}(),cc=0}}function yc(){var e=dc.now(),t=e-uc;t>1e3&&(hc-=t,uc=e)}function xc(e){ac||(oc&&(oc=clearTimeout(oc)),e-cc>24?(e<1/0&&(oc=setTimeout(vc,e-dc.now()-hc)),lc&&(lc=clearInterval(lc))):(lc||(uc=dc.now(),lc=setInterval(yc,1e3)),ac=1,pc(vc)))}gc.prototype=_c.prototype={constructor:gc,restart:function(e,t,n){if("function"!=typeof e)throw new TypeError("callback is not a function");n=(null==n?fc():+n)+(null==t?0:+t),this._next||sc===this||(sc?sc._next=this:rc=this,sc=this),this._call=e,this._time=n,xc()},stop:function(){this._call&&(this._call=null,this._time=1/0,xc())}};const bc=4294967296;function Sc(e){return e.x}function Tc(e){return e.y}function Mc(e){return e.z}var Ec,wc,Ac,Rc,Cc=Math.PI*(3-Math.sqrt(5)),Nc=20*Math.PI/(9+Math.sqrt(221));function Pc(e,t){t=t||2;var n,i=Math.min(3,Math.max(1,Math.round(t))),r=1,s=.001,a=1-Math.pow(s,1/300),o=0,l=.6,u=new Map,c=_c(p),h=ec("tick","end"),d=function(){let e=1;return()=>(e=(1664525*e+1013904223)%bc)/bc}();function p(){f(),h.call("tick",n),r1&&(null==c.fy?c.y+=c.vy*=l:(c.y=c.fy,c.vy=0)),i>2&&(null==c.fz?c.z+=c.vz*=l:(c.z=c.fz,c.vz=0));return n}function m(){for(var t,n=0,r=e.length;n1&&isNaN(t.y)||i>2&&isNaN(t.z)){var s=10*(i>2?Math.cbrt(.5+n):i>1?Math.sqrt(.5+n):n),a=n*Cc,o=n*Nc;1===i?t.x=s:2===i?(t.x=s*Math.cos(a),t.y=s*Math.sin(a)):(t.x=s*Math.sin(a)*Math.cos(o),t.y=s*Math.cos(a),t.z=s*Math.sin(a)*Math.sin(o))}(isNaN(t.vx)||i>1&&isNaN(t.vy)||i>2&&isNaN(t.vz))&&(t.vx=0,i>1&&(t.vy=0),i>2&&(t.vz=0))}}function g(t){return t.initialize&&t.initialize(e,d,i),t}return null==e&&(e=[]),m(),n={tick:f,restart:function(){return c.restart(p),n},stop:function(){return c.stop(),n},numDimensions:function(e){return arguments.length?(i=Math.min(3,Math.max(1,Math.round(e))),u.forEach(g),n):i},nodes:function(t){return arguments.length?(e=t,m(),u.forEach(g),n):e},alpha:function(e){return arguments.length?(r=+e,n):r},alphaMin:function(e){return arguments.length?(s=+e,n):s},alphaDecay:function(e){return arguments.length?(a=+e,n):+a},alphaTarget:function(e){return arguments.length?(o=+e,n):o},velocityDecay:function(e){return arguments.length?(l=1-e,n):1-l},randomSource:function(e){return arguments.length?(d=e,u.forEach(g),n):d},force:function(e,t){return arguments.length>1?(null==t?u.delete(e):u.set(e,g(t)),n):u.get(e)},find:function(){var t,n,r,s,a,o,l=Array.prototype.slice.call(arguments),u=l.shift()||0,c=(i>1?l.shift():null)||0,h=(i>2?l.shift():null)||0,d=l.shift()||1/0,p=0,f=e.length;for(d*=d,p=0;p1?(h.on(e,t),n):h.on(e)}}}function Dc(){var e,t,n,i,r,s,a=$u(-30),o=1,l=1/0,u=.81;function c(i){var s,a=e.length,o=(1===t?wu(e,Sc):2===t?Lu(e,Sc,Tc):3===t?ju(e,Sc,Tc,Mc):null).visitAfter(d);for(r=i,s=0;s1&&(e.y=a/c),t>2&&(e.z=o/c)}else{(n=e).x=n.data.x,t>1&&(n.y=n.data.y),t>2&&(n.z=n.data.z);do{u+=s[n.data.index]}while(n=n.next)}e.value=u}function p(e,a,c,h,d){if(!e.value)return!0;var p=[c,h,d][t-1],f=e.x-n.x,m=t>1?e.y-n.y:0,g=t>2?e.z-n.z:0,_=p-a,v=f*f+m*m+g*g;if(_*_/u1&&0===m&&(v+=(m=Yu(i))*m),t>2&&0===g&&(v+=(g=Yu(i))*g),v1&&(n.vy+=m*e.value*r/v),t>2&&(n.vz+=g*e.value*r/v)),!0;if(!(e.length||v>=l)){(e.data!==n||e.next)&&(0===f&&(v+=(f=Yu(i))*f),t>1&&0===m&&(v+=(m=Yu(i))*m),t>2&&0===g&&(v+=(g=Yu(i))*g),v1&&(n.vy+=m*_),t>2&&(n.vz+=g*_))}while(e=e.next)}}return c.initialize=function(n,...r){e=n,i=r.find((e=>"function"==typeof e))||Math.random,t=r.find((e=>[1,2,3].includes(e)))||2,h()},c.strength=function(e){return arguments.length?(a="function"==typeof e?e:$u(+e),h(),c):a},c.distanceMin=function(e){return arguments.length?(o=e*e,c):Math.sqrt(o)},c.distanceMax=function(e){return arguments.length?(l=e*e,c):Math.sqrt(l)},c.theta=function(e){return arguments.length?(u=e*e,c):Math.sqrt(u)},c}function Uc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Lc(){if(wc)return Ec;return wc=1,Ec=function(e){!function(e){if(!e)throw new Error("Eventify cannot use falsy object as events subject");for(var t=["on","fire","off"],n=0;n1&&(i=Array.prototype.splice.call(arguments,1));for(var s=0;s0&&(g.fire("changed",h),h.length=0)}function C(e){if("function"!=typeof e)throw new Error("Function is expected to iterate over graph nodes. You passed "+e);for(var t=a.values(),n=t.next();!n.done;){if(e(n.value))return!0;n=t.next()}}};var e=Lc();function t(e,t){this.id=e,this.links=null,this.data=t}function n(e,t){e.links?e.links.add(t):e.links=new Set([t])}function i(e,t,n,i){this.fromId=e,this.toId=t,this.data=n,this.id=i}function r(e,t){return e.toString()+"👉 "+t.toString()}return Ac}(),Gc=Uc(zc),Vc={exports:{}},Hc={exports:{}};function jc(){return Oc||(Oc=1,Ic=function(e){return 0===e?"x":1===e?"y":2===e?"z":"c"+(e+1)}),Ic}function Wc(){if(Bc)return Fc;Bc=1;const e=jc();return Fc=function(t){return function(n,i){let r=i&&i.indent||0,s=i&&void 0!==i.join?i.join:"\n",a=Array(r+1).join(" "),o=[];for(let i=0;i>>19))+(e<<5)&4294967295)^e<<9))+(e<<3)&4294967295)^e>>>16),this.seed=e,(268435455&e)/268435456}return ah=1,ch.exports=e,ch.exports.random=e,ch.exports.randomIterator=function(t,n){var i=n||e();if("function"!=typeof i.next)throw new Error("customRandom does not match expected API: next() function is missing");return{forEach:function(e){var n,r,s;for(n=t.length-1;n>0;--n)r=i.next(n+1),s=t[r],t[r]=t[n],t[n]=s,e(s);t.length&&e(t[0])},shuffle:function(){var e,n,r;for(e=t.length-1;e>0;--e)n=i.next(e+1),r=t[n],t[n]=t[e],t[e]=r;return t}}},t.prototype.next=function(e){return Math.floor(this.nextDouble()*e)},t.prototype.nextDouble=i,t.prototype.uniform=i,t.prototype.gaussian=function(){var e,t,n;do{e=(t=2*this.nextDouble()-1)*t+(n=2*this.nextDouble()-1)*n}while(e>=1||0===e);return t*Math.sqrt(-2*Math.log(e)/e)},t.prototype.levy=function(){var e=1.5,t=Math.pow(n(2.5)*Math.sin(Math.PI*e/2)/(n(1.25)*e*Math.pow(2,.25)),1/e);return this.gaussian()*t/Math.pow(Math.abs(this.gaussian()),1/e)},ch.exports}().random(42),b=[],S=[],T=m(l,x),M=g(b,l,x),E=v(l,x),w=_(l),A=[],R=new Map,C=0;D("nbody",(function(){if(0===b.length)return;T.insertBodies(b);var e=b.length;for(;e--;){var t=b[e];t.isPinned||(t.reset(),T.updateBodyForce(t),w.update(t))}})),D("spring",(function(){var e=S.length;for(;e--;)E.update(S[e])}));var N={bodies:b,quadTree:T,springs:S,settings:l,addForce:D,removeForce:function(e){var t=A.indexOf(R.get(e));if(t<0)return;A.splice(t,1),R.delete(e)},getForces:function(){return R},step:function(){for(var e=0;enew f(e))(e);return b.push(t),t},removeBody:function(e){if(e){var t=b.indexOf(e);if(!(t<0))return b.splice(t,1),0===b.length&&M.reset(),!0}},addSpring:function(e,t,n,i){if(!e||!t)throw new Error("Cannot add null spring to force simulator");"number"!=typeof n&&(n=-1);var r=new u(e,t,n,i>=0?i:-1);return S.push(r),r},getTotalMovement:function(){return 0},removeSpring:function(e){if(e){var t=S.indexOf(e);return t>-1?(S.splice(t,1),!0):void 0}},getBestNewBodyPosition:function(e){return M.getBestNewPosition(e)},getBBox:P,getBoundingBox:P,invalidateBBox:function(){console.warn("invalidateBBox() is deprecated, bounds always recomputed on `getBBox()` call")},gravity:function(e){return void 0!==e?(l.gravity=e,T.options({gravity:e}),this):l.gravity},theta:function(e){return void 0!==e?(l.theta=e,T.options({theta:e}),this):l.theta},random:x};return function(e,t){for(var n in e)o(e,t,n)}(l,N),h(N),N;function P(){return M.update(),M.box}function D(e,t){if(R.has(e))throw new Error("Force "+e+" is already added");R.set(e,t),A.push(t)}};var e=function(){if(kc)return Hc.exports;kc=1;const e=Wc();function t(e,t){return`\n${i(e,t)}\n${n(e)}\nreturn {Body: Body, Vector: Vector};\n`}function n(t){let n=e(t),i=n("{var}",{join:", "});return`\nfunction Body(${i}) {\n this.isPinned = false;\n this.pos = new Vector(${i});\n this.force = new Vector();\n this.velocity = new Vector();\n this.mass = 1;\n\n this.springCount = 0;\n this.springLength = 0;\n}\n\nBody.prototype.reset = function() {\n this.force.reset();\n this.springCount = 0;\n this.springLength = 0;\n}\n\nBody.prototype.setPosition = function (${i}) {\n ${n("this.pos.{var} = {var} || 0;",{indent:2})}\n};`}function i(t,n){let i=e(t),r="";return n&&(r=`${i("\n\t var v{var};\n\tObject.defineProperty(this, '{var}', {\n\t set: function(v) { \n\t if (!Number.isFinite(v)) throw new Error('Cannot set non-numbers to {var}');\n\t v{var} = v; \n\t },\n\t get: function() { return v{var}; }\n\t});")}`),`function Vector(${i("{var}",{join:", "})}) {\n ${r}\n if (typeof arguments[0] === 'object') {\n // could be another vector\n let v = arguments[0];\n ${i('if (!Number.isFinite(v.{var})) throw new Error("Expected value is not a finite number at Vector constructor ({var})");',{indent:4})}\n ${i("this.{var} = v.{var};",{indent:4})}\n } else {\n ${i('this.{var} = typeof {var} === "number" ? {var} : 0;',{indent:4})}\n }\n }\n \n Vector.prototype.reset = function () {\n ${i("this.{var} = ",{join:""})}0;\n };`}return Hc.exports=function(e,n){let i=t(e,n),{Body:r}=new Function(i)();return r},Hc.exports.generateCreateBodyFunctionBody=t,Hc.exports.getVectorCode=i,Hc.exports.getBodyCode=n,Hc.exports}(),t=function(){if(Xc)return qc.exports;Xc=1;const e=Wc(),t=jc();function n(n){let l=e(n),u=Math.pow(2,n),c=`\n${o()}\n${a(n)}\n${i(n)}\n${s(n)}\n${r(n)}\n\nfunction createQuadTree(options, random) {\n options = options || {};\n options.gravity = typeof options.gravity === 'number' ? options.gravity : -1;\n options.theta = typeof options.theta === 'number' ? options.theta : 0.8;\n\n var gravity = options.gravity;\n var updateQueue = [];\n var insertStack = new InsertStack();\n var theta = options.theta;\n\n var nodesCache = [];\n var currentInCache = 0;\n var root = newNode();\n\n return {\n insertBodies: insertBodies,\n\n /**\n * Gets root node if it is present\n */\n getRoot: function() {\n return root;\n },\n\n updateBodyForce: update,\n\n options: function(newOptions) {\n if (newOptions) {\n if (typeof newOptions.gravity === 'number') {\n gravity = newOptions.gravity;\n }\n if (typeof newOptions.theta === 'number') {\n theta = newOptions.theta;\n }\n\n return this;\n }\n\n return {\n gravity: gravity,\n theta: theta\n };\n }\n };\n\n function newNode() {\n // To avoid pressure on GC we reuse nodes.\n var node = nodesCache[currentInCache];\n if (node) {\n${function(e){let t=[];for(let n=0;n {var}max) {var}max = pos.{var};",{indent:6})}\n }\n\n // Makes the bounds square.\n var maxSideLength = -Infinity;\n ${l("if ({var}max - {var}min > maxSideLength) maxSideLength = {var}max - {var}min ;",{indent:4})}\n\n currentInCache = 0;\n root = newNode();\n ${l("root.min_{var} = {var}min;",{indent:4})}\n ${l("root.max_{var} = {var}min + maxSideLength;",{indent:4})}\n\n i = bodies.length - 1;\n if (i >= 0) {\n root.body = bodies[i];\n }\n while (i--) {\n insert(bodies[i], root);\n }\n }\n\n function insert(newBody) {\n insertStack.reset();\n insertStack.push(root, newBody);\n\n while (!insertStack.isEmpty()) {\n var stackItem = insertStack.pop();\n var node = stackItem.node;\n var body = stackItem.body;\n\n if (!node.body) {\n // This is internal node. Update the total mass of the node and center-of-mass.\n ${l("var {var} = body.pos.{var};",{indent:8})}\n node.mass += body.mass;\n ${l("node.mass_{var} += body.mass * {var};",{indent:8})}\n\n // Recursively insert the body in the appropriate quadrant.\n // But first find the appropriate quadrant.\n var quadIdx = 0; // Assume we are in the 0's quad.\n ${l("var min_{var} = node.min_{var};",{indent:8})}\n ${l("var max_{var} = (min_{var} + node.max_{var}) / 2;",{indent:8})}\n\n${function(){let e=[],i=Array(8+1).join(" ");for(let r=0;r max_${t(r)}) {`),e.push(i+` quadIdx = quadIdx + ${Math.pow(2,r)};`),e.push(i+` min_${t(r)} = max_${t(r)};`),e.push(i+` max_${t(r)} = node.max_${t(r)};`),e.push(i+"}");return e.join("\n")}()}\n\n var child = getChild(node, quadIdx);\n\n if (!child) {\n // The node is internal but this quadrant is not taken. Add\n // subnode to it.\n child = newNode();\n ${l("child.min_{var} = min_{var};",{indent:10})}\n ${l("child.max_{var} = max_{var};",{indent:10})}\n child.body = body;\n\n setChild(node, quadIdx, child);\n } else {\n // continue searching in this quadrant.\n insertStack.push(child, body);\n }\n } else {\n // We are trying to add to the leaf node.\n // We have to convert current leaf into internal node\n // and continue adding two nodes.\n var oldBody = node.body;\n node.body = null; // internal nodes do not cary bodies\n\n if (isSamePosition(oldBody.pos, body.pos)) {\n // Prevent infinite subdivision by bumping one node\n // anywhere in this quadrant\n var retriesCount = 3;\n do {\n var offset = random.nextDouble();\n ${l("var d{var} = (node.max_{var} - node.min_{var}) * offset;",{indent:12})}\n\n ${l("oldBody.pos.{var} = node.min_{var} + d{var};",{indent:12})}\n retriesCount -= 1;\n // Make sure we don't bump it out of the box. If we do, next iteration should fix it\n } while (retriesCount > 0 && isSamePosition(oldBody.pos, body.pos));\n\n if (retriesCount === 0 && isSamePosition(oldBody.pos, body.pos)) {\n // This is very bad, we ran out of precision.\n // if we do not return from the method we'll get into\n // infinite loop here. So we sacrifice correctness of layout, and keep the app running\n // Next layout iteration should get larger bounding box in the first step and fix this\n return;\n }\n }\n // Next iteration should subdivide node further.\n insertStack.push(node, oldBody);\n insertStack.push(node, body);\n }\n }\n }\n}\nreturn createQuadTree;\n\n`;return c}function i(t){let n=e(t);return`\n function isSamePosition(point1, point2) {\n ${n("var d{var} = Math.abs(point1.{var} - point2.{var});",{indent:2})}\n \n return ${n("d{var} < 1e-8",{join:" && "})};\n } \n`}function r(e){var t=Math.pow(2,e);return`\nfunction setChild(node, idx, child) {\n ${function(){let e=[];for(let n=0;n 0) {\n return this.stack[--this.popIdx];\n }\n },\n reset: function () {\n this.popIdx = 0;\n }\n};\n\nfunction InsertStackElement(node, body) {\n this.node = node; // QuadTree node\n this.body = body; // physical body which needs to be inserted to node\n}\n"}return qc.exports=function(e){let t=n(e);return new Function(t)()},qc.exports.generateQuadTreeFunctionBody=n,qc.exports.getInsertStackCode=o,qc.exports.getQuadNodeCode=a,qc.exports.isSamePosition=i,qc.exports.getChildBodyCode=s,qc.exports.setChildBodyCode=r,qc.exports}(),n=function(){if($c)return Yc.exports;$c=1,Yc.exports=function(e){let n=t(e);return new Function("bodies","settings","random",n)},Yc.exports.generateFunctionBody=t;const e=Wc();function t(t){let n=e(t);return`\n var boundingBox = {\n ${n("min_{var}: 0, max_{var}: 0,",{indent:4})}\n };\n\n return {\n box: boundingBox,\n\n update: updateBoundingBox,\n\n reset: resetBoundingBox,\n\n getBestNewPosition: function (neighbors) {\n var ${n("base_{var} = 0",{join:", "})};\n\n if (neighbors.length) {\n for (var i = 0; i < neighbors.length; ++i) {\n let neighborPos = neighbors[i].pos;\n ${n("base_{var} += neighborPos.{var};",{indent:10})}\n }\n\n ${n("base_{var} /= neighbors.length;",{indent:8})}\n } else {\n ${n("base_{var} = (boundingBox.min_{var} + boundingBox.max_{var}) / 2;",{indent:8})}\n }\n\n var springLength = settings.springLength;\n return {\n ${n("{var}: base_{var} + (random.nextDouble() - 0.5) * springLength,",{indent:8})}\n };\n }\n };\n\n function updateBoundingBox() {\n var i = bodies.length;\n if (i === 0) return; // No bodies - no borders.\n\n ${n("var max_{var} = -Infinity;",{indent:4})}\n ${n("var min_{var} = Infinity;",{indent:4})}\n\n while(i--) {\n // this is O(n), it could be done faster with quadtree, if we check the root node bounds\n var bodyPos = bodies[i].pos;\n ${n("if (bodyPos.{var} < min_{var}) min_{var} = bodyPos.{var};",{indent:6})}\n ${n("if (bodyPos.{var} > max_{var}) max_{var} = bodyPos.{var};",{indent:6})}\n }\n\n ${n("boundingBox.min_{var} = min_{var};",{indent:4})}\n ${n("boundingBox.max_{var} = max_{var};",{indent:4})}\n }\n\n function resetBoundingBox() {\n ${n("boundingBox.min_{var} = boundingBox.max_{var} = 0;",{indent:4})}\n }\n`}return Yc.exports}(),i=function(){if(Kc)return Zc.exports;Kc=1;const e=Wc();function t(t){return`\n if (!Number.isFinite(options.dragCoefficient)) throw new Error('dragCoefficient is not a finite number');\n\n return {\n update: function(body) {\n ${e(t)("body.force.{var} -= options.dragCoefficient * body.velocity.{var};",{indent:6})}\n }\n };\n`}return Zc.exports=function(e){let n=t(e);return new Function("options",n)},Zc.exports.generateCreateDragForceFunctionBody=t,Zc.exports}(),r=function(){if(Qc)return Jc.exports;Qc=1;const e=Wc();function t(t){let n=e(t);return`\n if (!Number.isFinite(options.springCoefficient)) throw new Error('Spring coefficient is not a number');\n if (!Number.isFinite(options.springLength)) throw new Error('Spring length is not a number');\n\n return {\n /**\n * Updates forces acting on a spring\n */\n update: function (spring) {\n var body1 = spring.from;\n var body2 = spring.to;\n var length = spring.length < 0 ? options.springLength : spring.length;\n ${n("var d{var} = body2.pos.{var} - body1.pos.{var};",{indent:6})}\n var r = Math.sqrt(${n("d{var} * d{var}",{join:" + "})});\n\n if (r === 0) {\n ${n("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:8})}\n r = Math.sqrt(${n("d{var} * d{var}",{join:" + "})});\n }\n\n var d = r - length;\n var coefficient = ((spring.coefficient > 0) ? spring.coefficient : options.springCoefficient) * d / r;\n\n ${n("body1.force.{var} += coefficient * d{var}",{indent:6})};\n body1.springCount += 1;\n body1.springLength += r;\n\n ${n("body2.force.{var} -= coefficient * d{var}",{indent:6})};\n body2.springCount += 1;\n body2.springLength += r;\n }\n };\n`}return Jc.exports=function(e){let n=t(e);return new Function("options","random",n)},Jc.exports.generateCreateSpringForceFunctionBody=t,Jc.exports}(),s=function(){if(eh)return sh.exports;eh=1;const e=Wc();function t(t){let n=e(t);return`\n var length = bodies.length;\n if (length === 0) return 0;\n\n ${n("var d{var} = 0, t{var} = 0;",{indent:2})}\n\n for (var i = 0; i < length; ++i) {\n var body = bodies[i];\n if (body.isPinned) continue;\n\n if (adaptiveTimeStepWeight && body.springCount) {\n timeStep = (adaptiveTimeStepWeight * body.springLength/body.springCount);\n }\n\n var coeff = timeStep / body.mass;\n\n ${n("body.velocity.{var} += coeff * body.force.{var};",{indent:4})}\n ${n("var v{var} = body.velocity.{var};",{indent:4})}\n var v = Math.sqrt(${n("v{var} * v{var}",{join:" + "})});\n\n if (v > 1) {\n // We normalize it so that we move within timeStep range. \n // for the case when v <= 1 - we let velocity to fade out.\n ${n("body.velocity.{var} = v{var} / v;",{indent:6})}\n }\n\n ${n("d{var} = timeStep * body.velocity.{var};",{indent:4})}\n\n ${n("body.pos.{var} += d{var};",{indent:4})}\n\n ${n("t{var} += Math.abs(d{var});",{indent:4})}\n }\n\n return (${n("t{var} * t{var}",{join:" + "})})/length;\n`}return sh.exports=function(e){let n=t(e);return new Function("bodies","timeStep","adaptiveTimeStepWeight",n)},sh.exports.generateIntegratorFunctionBody=t,sh.exports}(),a={};function o(e,t,n){if(e.hasOwnProperty(n)&&"function"!=typeof t[n]){var i=Number.isFinite(e[n]);t[n]=i?function(i){if(void 0!==i){if(!Number.isFinite(i))throw new Error("Value of "+n+" should be a valid number.");return e[n]=i,t}return e[n]}:function(i){return void 0!==i?(e[n]=i,t):e[n]}}}return oh}var dh=function(){if(uh)return Vc.exports;uh=1,Vc.exports=function(n,i){if(!n)throw new Error("Graph structure cannot be undefined");var r=(i&&i.createSimulator||hh())(i);if(Array.isArray(i))throw new Error("Physics settings is expected to be an object");var s=n.version>19?function(e){var t=n.getLinks(e);return t?1+t.size/3:1}:function(e){var t=n.getLinks(e);return t?1+t.length/3:1};i&&"function"==typeof i.nodeMass&&(s=i.nodeMass);var a=new Map,o={},l=0,u=r.settings.springTransform||t;l=0,n.forEachNode((function(e){m(e.id),l+=1})),n.forEachLink(_),n.on("changed",f);var c=!1,h={step:function(){if(0===l)return d(!0),!0;var e=r.step();h.lastMove=e,h.fire("step");var t=e/l<=.01;return d(t),t},getNodePosition:function(e){return x(e).pos},setNodePosition:function(e){var t=x(e);t.setPosition.apply(t,Array.prototype.slice.call(arguments,1))},getLinkPosition:function(e){var t=o[e];if(t)return{from:t.from.pos,to:t.to.pos}},getGraphRect:function(){return r.getBBox()},forEachBody:p,pinNode:function(e,t){x(e.id).isPinned=!!t},isNodePinned:function(e){return x(e.id).isPinned},dispose:function(){n.off("changed",f),h.fire("disposed")},getBody:function(e){return a.get(e)},getSpring:function(e,t){var i;if(void 0===t)i="object"!=typeof e?e:e.id;else{var r=n.hasLink(e,t);if(!r)return;i=r.id}return o[i]},getForceVectorLength:function(){var e=0,t=0;return p((function(n){e+=Math.abs(n.force.x),t+=Math.abs(n.force.y)})),Math.sqrt(e*e+t*t)},simulator:r,graph:n,lastMove:0};return e(h),h;function d(e){var t;c!==e&&(c=e,t=e,h.fire("stable",t))}function p(e){a.forEach(e)}function f(e){for(var t=0;t=t||n<0||h&&e-u>=s}function m(){var e=vh();if(f(e))return g(e);o=setTimeout(m,function(e){var n=t-(e-l);return h?Oh(n,s-(e-u)):n}(e))}function g(e){return o=void 0,d&&i?p(e):(i=r=void 0,a)}function _(){var e=vh(),n=f(e);if(i=arguments,r=this,l=e,n){if(void 0===o)return function(e){return u=e,o=setTimeout(m,t),c?p(e):a}(l);if(h)return clearTimeout(o),o=setTimeout(m,t),p(l)}return void 0===o&&(o=setTimeout(m,t)),a}return t=Lh(t)||0,fh(n)&&(c=!!n.leading,s=(h="maxWait"in n)?Ih(Lh(n.maxWait)||0,t):s,d="trailing"in n?!!n.trailing:d),_.cancel=function(){void 0!==o&&clearTimeout(o),u=0,i=l=r=o=void 0},_.flush=function(){return void 0===o?a:g(vh())},_}function Bh(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n=t)&&(n=t);else{let i=-1;for(let r of e)null!=(r=t(r,++i,e))&&(n=r)&&(n=r)}return n}function $h(e,t){let n;if(void 0===t)for(const t of e)null!=t&&(n>t||void 0===n&&t>=t)&&(n=t);else{let i=-1;for(let r of e)null!=(r=t(r,++i,e))&&(n>r||void 0===n&&r>=r)&&(n=r)}return n}function Yh(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}if(e=Bd(e,360),t=Bd(t,100),n=Bd(n,100),0===t)i=r=s=n;else{var o=n<.5?n*(1+t):n+t-n*t,l=2*n-o;i=a(l,o,e+1/3),r=a(l,o,e),s=a(l,o,e-1/3)}return{r:255*i,g:255*r,b:255*s}}(e.h,i,s),a=!0,o="hsl"),e.hasOwnProperty("a")&&(n=e.a));return n=Fd(n),{ok:a,format:e.format||o,r:Math.min(255,Math.max(t.r,0)),g:Math.min(255,Math.max(t.g,0)),b:Math.min(255,Math.max(t.b,0)),a:n}}(e);this._originalInput=e,this._r=n.r,this._g=n.g,this._b=n.b,this._a=n.a,this._roundA=Math.round(100*this._a)/100,this._format=t.format||n.format,this._gradientType=t.gradientType,this._r<1&&(this._r=Math.round(this._r)),this._g<1&&(this._g=Math.round(this._g)),this._b<1&&(this._b=Math.round(this._b)),this._ok=n.ok}function yd(e,t,n){e=Bd(e,255),t=Bd(t,255),n=Bd(n,255);var i,r,s=Math.max(e,t,n),a=Math.min(e,t,n),o=(s+a)/2;if(s==a)i=r=0;else{var l=s-a;switch(r=o>.5?l/(2-s-a):l/(s+a),s){case e:i=(t-n)/l+(t>1)+720)%360;--t;)i.h=(i.h+r)%360,s.push(vd(i));return s}function Ld(e,t){t=t||6;for(var n=vd(e).toHsv(),i=n.h,r=n.s,s=n.v,a=[],o=1/t;t--;)a.push(vd({h:i,s:r,v:s})),s=(s+o)%1;return a}vd.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(299*e.r+587*e.g+114*e.b)/1e3},getLuminance:function(){var e,t,n,i=this.toRgb();return e=i.r/255,t=i.g/255,n=i.b/255,.2126*(e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4))+.7152*(t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))},setAlpha:function(e){return this._a=Fd(e),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var e=xd(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=xd(this._r,this._g,this._b),t=Math.round(360*e.h),n=Math.round(100*e.s),i=Math.round(100*e.v);return 1==this._a?"hsv("+t+", "+n+"%, "+i+"%)":"hsva("+t+", "+n+"%, "+i+"%, "+this._roundA+")"},toHsl:function(){var e=yd(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=yd(this._r,this._g,this._b),t=Math.round(360*e.h),n=Math.round(100*e.s),i=Math.round(100*e.l);return 1==this._a?"hsl("+t+", "+n+"%, "+i+"%)":"hsla("+t+", "+n+"%, "+i+"%, "+this._roundA+")"},toHex:function(e){return bd(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,n,i,r){var s=[Gd(Math.round(e).toString(16)),Gd(Math.round(t).toString(16)),Gd(Math.round(n).toString(16)),Gd(Hd(i))];if(r&&s[0].charAt(0)==s[0].charAt(1)&&s[1].charAt(0)==s[1].charAt(1)&&s[2].charAt(0)==s[2].charAt(1)&&s[3].charAt(0)==s[3].charAt(1))return s[0].charAt(0)+s[1].charAt(0)+s[2].charAt(0)+s[3].charAt(0);return s.join("")}(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+")":"rgba("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:Math.round(100*Bd(this._r,255))+"%",g:Math.round(100*Bd(this._g,255))+"%",b:Math.round(100*Bd(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+Math.round(100*Bd(this._r,255))+"%, "+Math.round(100*Bd(this._g,255))+"%, "+Math.round(100*Bd(this._b,255))+"%)":"rgba("+Math.round(100*Bd(this._r,255))+"%, "+Math.round(100*Bd(this._g,255))+"%, "+Math.round(100*Bd(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(Od[bd(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+Sd(this._r,this._g,this._b,this._a),n=t,i=this._gradientType?"GradientType = 1, ":"";if(e){var r=vd(e);n="#"+Sd(r._r,r._g,r._b,r._a)}return"progid:DXImageTransform.Microsoft.gradient("+i+"startColorstr="+t+",endColorstr="+n+")"},toString:function(e){var t=!!e;e=e||this._format;var n=!1,i=this._a<1&&this._a>=0;return t||!i||"hex"!==e&&"hex6"!==e&&"hex3"!==e&&"hex4"!==e&&"hex8"!==e&&"name"!==e?("rgb"===e&&(n=this.toRgbString()),"prgb"===e&&(n=this.toPercentageRgbString()),"hex"!==e&&"hex6"!==e||(n=this.toHexString()),"hex3"===e&&(n=this.toHexString(!0)),"hex4"===e&&(n=this.toHex8String(!0)),"hex8"===e&&(n=this.toHex8String()),"name"===e&&(n=this.toName()),"hsl"===e&&(n=this.toHslString()),"hsv"===e&&(n=this.toHsvString()),n||this.toHexString()):"name"===e&&0===this._a?this.toName():this.toRgbString()},clone:function(){return vd(this.toString())},_applyModification:function(e,t){var n=e.apply(null,[this].concat([].slice.call(t)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(wd,arguments)},brighten:function(){return this._applyModification(Ad,arguments)},darken:function(){return this._applyModification(Rd,arguments)},desaturate:function(){return this._applyModification(Td,arguments)},saturate:function(){return this._applyModification(Md,arguments)},greyscale:function(){return this._applyModification(Ed,arguments)},spin:function(){return this._applyModification(Cd,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(Ud,arguments)},complement:function(){return this._applyCombination(Nd,arguments)},monochromatic:function(){return this._applyCombination(Ld,arguments)},splitcomplement:function(){return this._applyCombination(Dd,arguments)},triad:function(){return this._applyCombination(Pd,[3])},tetrad:function(){return this._applyCombination(Pd,[4])}},vd.fromRatio=function(e,t){if("object"==md(e)){var n={};for(var i in e)e.hasOwnProperty(i)&&(n[i]="a"===i?e[i]:Vd(e[i]));e=n}return vd(e,t)},vd.equals=function(e,t){return!(!e||!t)&&vd(e).toRgbString()==vd(t).toRgbString()},vd.random=function(){return vd.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})},vd.mix=function(e,t,n){n=0===n?0:n||50;var i=vd(e).toRgb(),r=vd(t).toRgb(),s=n/100;return vd({r:(r.r-i.r)*s+i.r,g:(r.g-i.g)*s+i.g,b:(r.b-i.b)*s+i.b,a:(r.a-i.a)*s+i.a})}, +// =4.5;break;case"AAlarge":r=s>=3;break;case"AAAsmall":r=s>=7}return r},vd.mostReadable=function(e,t,n){var i,r,s,a,o=null,l=0;r=(n=n||{}).includeFallbackColors,s=n.level,a=n.size;for(var u=0;ul&&(l=i,o=vd(t[u]));return vd.isReadable(e,o,{level:s,size:a})||!r?o:(n.includeFallbackColors=!1,vd.mostReadable(e,["#fff","#000"],n))};var Id=vd.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},Od=vd.hexNames=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}(Id);function Fd(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function Bd(e,t){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(e)&&(e="100%");var n=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(e);return e=Math.min(t,Math.max(0,parseFloat(e))),n&&(e=parseInt(e*t,10)/100),Math.abs(e-t)<1e-6?1:e%t/parseFloat(t)}function kd(e){return Math.min(1,Math.max(0,e))}function zd(e){return parseInt(e,16)}function Gd(e){return 1==e.length?"0"+e:""+e}function Vd(e){return e<=1&&(e=100*e+"%"),e}function Hd(e){return Math.round(255*parseFloat(e)).toString(16)}function jd(e){return zd(e)/255}var Wd,Xd,qd,$d=(Xd="[\\s|\\(]+("+(Wd="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+Wd+")[,|\\s]+("+Wd+")\\s*\\)?",qd="[\\s|\\(]+("+Wd+")[,|\\s]+("+Wd+")[,|\\s]+("+Wd+")[,|\\s]+("+Wd+")\\s*\\)?",{CSS_UNIT:new RegExp(Wd),rgb:new RegExp("rgb"+Xd),rgba:new RegExp("rgba"+qd),hsl:new RegExp("hsl"+Xd),hsla:new RegExp("hsla"+qd),hsv:new RegExp("hsv"+Xd),hsva:new RegExp("hsva"+qd),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function Yd(e){return!!$d.CSS_UNIT.exec(e)}function Kd(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n1&&void 0!==arguments[1]?arguments[1]:{},r=i.dataBindAttr,s=void 0===r?"__data":r,a=i.objBindAttr,o=void 0===a?"__threeObj":a;return Jd(this,t),sp(n=Qd(this,t),"scene",void 0),tp(n,bp,void 0),tp(n,Sp,void 0),n.scene=e,np(bp,n,s),np(Sp,n,o),n.onRemoveObj((function(){})),n}return lp(t,e),rp(t,[{key:"onCreateObj",value:function(e){var n=this;return pp(t,"onCreateObj",this)([function(t){var i=e(t);return t[ep(Sp,n)]=i,i[ep(bp,n)]=t,n.scene.add(i),i}]),this}},{key:"onRemoveObj",value:function(e){var n=this;return pp(t,"onRemoveObj",this)([function(i,r){var s=pp(t,"getData",n)([i]);e(i,r),n.scene.remove(i),xp(i),delete s[ep(Sp,n)]}]),this}}])}(hd),Mp=function(e){return isNaN(e)?parseInt(vd(e).toHex(),16):e},Ep=function(e){return isNaN(e)?vd(e).getAlpha():1},wp=function e(){var t=new jh,n=[],i=[],r=pd;function s(e){let s=t.get(e);if(void 0===s){if(r!==pd)return r;t.set(e,s=n.push(e)-1)}return i[s%i.length]}return s.domain=function(e){if(!arguments.length)return n.slice();n=[],t=new jh;for(const i of e)t.has(i)||t.set(i,n.push(i)-1);return s},s.range=function(e){return arguments.length?(i=Array.from(e),s):i.slice()},s.unknown=function(e){return arguments.length?(r=e,s):r},s.copy=function(){return e(n,i).unknown(r)},dd.apply(s,arguments),s}(fd);function Ap(e,t,n){t&&"string"==typeof n&&e.filter((function(e){return!e[n]})).forEach((function(e){e[n]=wp(t(e))}))}var Rp=window.THREE?window.THREE:{Group:Nr,Mesh:pr,MeshLambertMaterial:Cs,Color:Pi,BufferGeometry:tr,BufferAttribute:Hi,Matrix4:kn,Vector3:un,SphereGeometry:bs,CylinderGeometry:vs,TubeGeometry:Ss,ConeGeometry:ys,Line:class extends di{constructor(e=new tr,t=new qr){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(){const e=this.geometry;if(null===e.index){const t=e.attributes.position,n=[0];for(let e=1,i=t.count;e0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e2?-60:-30),e<3&&i(t.graphData.nodes,"z"),e<2&&i(t.graphData.nodes,"y")}},dagMode:{onChange:function(e,t){!e&&"d3"===t.forceEngine&&(t.graphData.nodes||[]).forEach((function(e){return e.fx=e.fy=e.fz=void 0}))}},dagLevelDistance:{},dagNodeFilter:{default:function(e){return!0}},onDagError:{triggerUpdate:!1},nodeRelSize:{default:4},nodeId:{default:"id"},nodeVal:{default:"val"},nodeResolution:{default:8},nodeColor:{default:"color"},nodeAutoColorBy:{},nodeOpacity:{default:.75},nodeVisibility:{default:!0},nodeThreeObject:{},nodeThreeObjectExtend:{default:!1},nodePositionUpdate:{triggerUpdate:!1},linkSource:{default:"source"},linkTarget:{default:"target"},linkVisibility:{default:!0},linkColor:{default:"color"},linkAutoColorBy:{},linkOpacity:{default:.2},linkWidth:{},linkResolution:{default:6},linkCurvature:{default:0,triggerUpdate:!1},linkCurveRotation:{default:0,triggerUpdate:!1},linkMaterial:{},linkThreeObject:{},linkThreeObjectExtend:{default:!1},linkPositionUpdate:{triggerUpdate:!1},linkDirectionalArrowLength:{default:0},linkDirectionalArrowColor:{},linkDirectionalArrowRelPos:{default:.5,triggerUpdate:!1},linkDirectionalArrowResolution:{default:8},linkDirectionalParticles:{default:0},linkDirectionalParticleSpeed:{default:.01,triggerUpdate:!1},linkDirectionalParticleWidth:{default:.5},linkDirectionalParticleColor:{},linkDirectionalParticleResolution:{default:4},forceEngine:{default:"d3"},d3AlphaMin:{default:0},d3AlphaDecay:{default:.0228,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaDecay(e)}},d3AlphaTarget:{default:0,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaTarget(e)}},d3VelocityDecay:{default:.4,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.velocityDecay(e)}},ngraphPhysics:{default:{timeStep:20,gravity:-1.2,theta:.8,springLength:30,springCoefficient:8e-4,dragCoefficient:.02}},warmupTicks:{default:0,triggerUpdate:!1},cooldownTicks:{default:1/0,triggerUpdate:!1},cooldownTime:{default:15e3,triggerUpdate:!1},onLoading:{default:function(){},triggerUpdate:!1},onFinishLoading:{default:function(){},triggerUpdate:!1},onUpdate:{default:function(){},triggerUpdate:!1},onFinishUpdate:{default:function(){},triggerUpdate:!1},onEngineTick:{default:function(){},triggerUpdate:!1},onEngineStop:{default:function(){},triggerUpdate:!1}},methods:{refresh:function(e){return e._flushObjects=!0,e._rerender(),this},d3Force:function(e,t,n){return void 0===n?e.d3ForceLayout.force(t):(e.d3ForceLayout.force(t,n),this)},d3ReheatSimulation:function(e){return e.d3ForceLayout.alpha(1),this.resetCountdown(),this},resetCountdown:function(e){return e.cntTicks=0,e.startTickTime=new Date,e.engineRunning=!0,this},tickFrame:function(e){var t,n,i,r,s="ngraph"!==e.forceEngine;return e.engineRunning&&function(){++e.cntTicks>e.cooldownTicks||new Date-e.startTickTime>e.cooldownTime||s&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()0){var f=o.x-a.x,m=o.y-a.y||0,g=(new Rp.Vector3).subVectors(h,c),_=g.clone().multiplyScalar(l).cross(0!==f||0!==m?new Rp.Vector3(0,0,1):new Rp.Vector3(0,1,0)).applyAxisAngle(g.normalize(),p).add((new Rp.Vector3).addVectors(c,h).divideScalar(2));u=new Rp.QuadraticBezierCurve3(c,_,h)}else{var v=70*l,y=-p,x=y+Math.PI/2;u=new Rp.CubicBezierCurve3(c,new Rp.Vector3(v*Math.cos(x),v*Math.sin(x),0).add(c),new Rp.Vector3(v*Math.cos(y),v*Math.sin(y),0).add(c),h)}t.__curve=u}else t.__curve=null}}e.linkDataMapper.entries().forEach((function(t){var i=dp(t,2),r=i[0],l=i[1];if(l){var u=s?r:e.layout.getLinkPosition(e.layout.graph.getLink(r.source,r.target).id),c=u[s?"source":"from"],h=u[s?"target":"to"];if(c&&h&&c.hasOwnProperty("x")&&h.hasOwnProperty("x")){o(r);var d=a(r);if(!e.linkPositionUpdate||!e.linkPositionUpdate(d?l.children[1]:l,{start:{x:c.x,y:c.y,z:c.z},end:{x:h.x,y:h.y,z:h.z}},r)||d){var p=30,f=r.__curve,m=l.children.length?l.children[0]:l;if("Line"===m.type){if(f){var g=f.getPoints(p);m.geometry.getAttribute("position").array.length!==3*g.length&&m.geometry[Np]("position",new Rp.BufferAttribute(new Float32Array(3*g.length),3)),m.geometry.setFromPoints(g)}else{var _=m.geometry.getAttribute("position");_&&_.array&&6===_.array.length||m.geometry[Np]("position",_=new Rp.BufferAttribute(new Float32Array(6),3)),_.array[0]=c.x,_.array[1]=c.y||0,_.array[2]=c.z||0,_.array[3]=h.x,_.array[4]=h.y||0,_.array[5]=h.z||0,_.needsUpdate=!0}m.geometry.computeBoundingSphere()}else if("Mesh"===m.type)if(f){m.geometry.type.match(/^Tube(Buffer)?Geometry$/)||(m.position.set(0,0,0),m.rotation.set(0,0,0),m.scale.set(1,1,1));var v=Math.ceil(10*n(r))/10/2,y=new Rp.TubeGeometry(f,p,v,e.linkResolution,!1);m.geometry.dispose(),m.geometry=y}else{if(!m.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)){var x=Math.ceil(10*n(r))/10/2,b=new Rp.CylinderGeometry(x,x,1,e.linkResolution,1,!1);b[Pp]((new Rp.Matrix4).makeTranslation(0,.5,0)),b[Pp]((new Rp.Matrix4).makeRotationX(Math.PI/2)),m.geometry.dispose(),m.geometry=b}var S=new Rp.Vector3(c.x,c.y||0,c.z||0),T=new Rp.Vector3(h.x,h.y||0,h.z||0),M=S.distanceTo(T);m.position.x=S.x,m.position.y=S.y,m.position.z=S.z,m.scale.z=M,m.parent.localToWorld(T),m.lookAt(T)}}}}}))}(),t=Hh(e.linkDirectionalArrowRelPos),n=Hh(e.linkDirectionalArrowLength),i=Hh(e.nodeVal),e.arrowDataMapper.entries().forEach((function(r){var a=dp(r,2),o=a[0],l=a[1];if(l){var u=s?o:e.layout.getLinkPosition(e.layout.graph.getLink(o.source,o.target).id),c=u[s?"source":"from"],h=u[s?"target":"to"];if(c&&h&&c.hasOwnProperty("x")&&h.hasOwnProperty("x")){var d=Math.cbrt(Math.max(0,i(c)||1))*e.nodeRelSize,p=Math.cbrt(Math.max(0,i(h)||1))*e.nodeRelSize,f=n(o),m=t(o),g=o.__curve?function(e){return o.__curve.getPoint(e)}:function(e){var t=function(e,t,n,i){return t[e]+(n[e]-t[e])*i||0};return{x:t("x",c,h,e),y:t("y",c,h,e),z:t("z",c,h,e)}},_=o.__curve?o.__curve.getLength():Math.sqrt(["x","y","z"].map((function(e){return Math.pow((h[e]||0)-(c[e]||0),2)})).reduce((function(e,t){return e+t}),0)),v=d+f+(_-d-p-f)*m,y=g(v/_),x=g((v-f)/_);["x","y","z"].forEach((function(e){return l.position[e]=x[e]}));var b=ip(Rp.Vector3,fp(["x","y","z"].map((function(e){return y[e]}))));l.parent.localToWorld(b),l.lookAt(b)}}})),r=Hh(e.linkDirectionalParticleSpeed),e.graphData.links.forEach((function(t){var n=e.particlesDataMapper.getObj(t),i=n&&n.children,a=t.__singleHopPhotonsObj&&t.__singleHopPhotonsObj.children;if(a&&a.length||i&&i.length){var o=s?t:e.layout.getLinkPosition(e.layout.graph.getLink(t.source,t.target).id),l=o[s?"source":"from"],u=o[s?"target":"to"];if(l&&u&&l.hasOwnProperty("x")&&u.hasOwnProperty("x")){var c=r(t),h=t.__curve?function(e){return t.__curve.getPoint(e)}:function(e){var t=function(e,t,n,i){return t[e]+(n[e]-t[e])*i||0};return{x:t("x",l,u,e),y:t("y",l,u,e),z:t("z",l,u,e)}};[].concat(fp(i||[]),fp(a||[])).forEach((function(e,t){var n="singleHopPhotons"===e.parent.__linkThreeObjType;if(e.hasOwnProperty("__progressRatio")||(e.__progressRatio=n?0:t/i.length),e.__progressRatio+=c,e.__progressRatio>=1){if(n)return e.parent.remove(e),void xp(e);e.__progressRatio=e.__progressRatio%1}var r=e.__progressRatio,s=h(r);["x","y","z"].forEach((function(t){return e.position[t]=s[t]}))}))}}})),this},emitParticle:function(e,t){if(t&&e.graphData.links.includes(t)){if(!t.__singleHopPhotonsObj){var n=new Rp.Group;n.__linkThreeObjType="singleHopPhotons",t.__singleHopPhotonsObj=n,e.graphScene.add(n)}var i=Hh(e.linkDirectionalParticleWidth),r=Math.ceil(10*i(t))/10/2,s=e.linkDirectionalParticleResolution,a=new Rp.SphereGeometry(r,s,s),o=Hh(e.linkColor),l=Hh(e.linkDirectionalParticleColor)(t)||o(t)||"#f0f0f0",u=new Rp.Color(Mp(l)),c=3*e.linkOpacity,h=new Rp.MeshLambertMaterial({color:u,transparent:!0,opacity:c});t.__singleHopPhotonsObj.add(new Rp.Mesh(a,h))}return this},getGraphBbox:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0};if(!e.initialised)return null;var n=function e(n){var i=[];if(n.geometry){n.geometry.computeBoundingBox();var r=new Rp.Box3;r.copy(n.geometry.boundingBox).applyMatrix4(n.matrixWorld),i.push(r)}return i.concat.apply(i,fp((n.children||[]).filter((function(e){return!e.hasOwnProperty("__graphObjType")||"node"===e.__graphObjType&&t(e.__data)})).map(e)))}(e.graphScene);return n.length?Object.assign.apply(Object,fp(["x","y","z"].map((function(e){return sp({},e,[$h(n,(function(t){return t.min[e]})),qh(n,(function(t){return t.max[e]}))])})))):null}},stateInit:function(){return{d3ForceLayout:Pc().force("link",Qu()).force("charge",Dc()).force("center",Su()).force("dagRadial",null).stop(),engineRunning:!1}},init:function(e,t){t.graphScene=e,t.nodeDataMapper=new Tp(e,{objBindAttr:"__threeObj"}),t.linkDataMapper=new Tp(e,{objBindAttr:"__lineObj"}),t.arrowDataMapper=new Tp(e,{objBindAttr:"__arrowObj"}),t.particlesDataMapper=new Tp(e,{objBindAttr:"__photonsObj"})},update:function(e,t){var n=function(e){return e.some((function(e){return t.hasOwnProperty(e)}))};if(e.engineRunning=!1,"function"==typeof e.onUpdate&&e.onUpdate(),null!==e.nodeAutoColorBy&&n(["nodeAutoColorBy","graphData","nodeColor"])&&Ap(e.graphData.nodes,Hh(e.nodeAutoColorBy),e.nodeColor),null!==e.linkAutoColorBy&&n(["linkAutoColorBy","graphData","linkColor"])&&Ap(e.graphData.links,Hh(e.linkAutoColorBy),e.linkColor),e._flushObjects||n(["graphData","nodeThreeObject","nodeThreeObjectExtend","nodeVal","nodeColor","nodeVisibility","nodeRelSize","nodeResolution","nodeOpacity"])){var i=Hh(e.nodeThreeObject),r=Hh(e.nodeThreeObjectExtend),s=Hh(e.nodeVal),a=Hh(e.nodeColor),o=Hh(e.nodeVisibility),l={},u={};(e._flushObjects||n(["nodeThreeObject","nodeThreeObjectExtend"]))&&e.nodeDataMapper.clear(),e.nodeDataMapper.onCreateObj((function(t){var n,s=i(t),a=r(t);return s&&e.nodeThreeObject===s&&(s=s.clone()),s&&!a?n=s:((n=new Rp.Mesh).__graphDefaultObj=!0,s&&a&&n.add(s)),n.__graphObjType="node",n})).onUpdateObj((function(t,n){if(t.__graphDefaultObj){var i=s(n)||1,r=Math.cbrt(i)*e.nodeRelSize,o=e.nodeResolution;t.geometry.type.match(/^Sphere(Buffer)?Geometry$/)&&t.geometry.parameters.radius===r&&t.geometry.parameters.widthSegments===o||(l.hasOwnProperty(i)||(l[i]=new Rp.SphereGeometry(r,o,o)),t.geometry.dispose(),t.geometry=l[i]);var c=a(n),h=new Rp.Color(Mp(c||"#ffffaa")),d=e.nodeOpacity*Ep(c);"MeshLambertMaterial"===t.material.type&&t.material.color.equals(h)&&t.material.opacity===d||(u.hasOwnProperty(c)||(u[c]=new Rp.MeshLambertMaterial({color:h,transparent:!0,opacity:d})),t.material.dispose(),t.material=u[c])}})).digest(e.graphData.nodes.filter(o))}if(e._flushObjects||n(["graphData","linkThreeObject","linkThreeObjectExtend","linkMaterial","linkColor","linkWidth","linkVisibility","linkResolution","linkOpacity","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution"])){var c=Hh(e.linkThreeObject),h=Hh(e.linkThreeObjectExtend),d=Hh(e.linkMaterial),p=Hh(e.linkVisibility),f=Hh(e.linkColor),m=Hh(e.linkWidth),g={},_={},v={},y=e.graphData.links.filter(p);if((e._flushObjects||n(["linkThreeObject","linkThreeObjectExtend","linkWidth"]))&&e.linkDataMapper.clear(),e.linkDataMapper.onRemoveObj((function(e){var t=e.__data&&e.__data.__singleHopPhotonsObj;t&&(t.parent.remove(t),xp(t),delete e.__data.__singleHopPhotonsObj)})).onCreateObj((function(t){var n,i,r=c(t),s=h(t);if(r&&e.linkThreeObject===r&&(r=r.clone()),!r||s)if(!!m(t))n=new Rp.Mesh;else{var a=new Rp.BufferGeometry;a[Np]("position",new Rp.BufferAttribute(new Float32Array(6),3)),n=new Rp.Line(a)}return r?s?((i=new Rp.Group).__graphDefaultObj=!0,i.add(n),i.add(r)):i=r:(i=n).__graphDefaultObj=!0,i.renderOrder=10,i.__graphObjType="link",i})).onUpdateObj((function(t,n){if(t.__graphDefaultObj){var i=t.children.length?t.children[0]:t,r=Math.ceil(10*m(n))/10,s=!!r;if(s){var a=r/2,o=e.linkResolution;if(!i.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)||i.geometry.parameters.radiusTop!==a||i.geometry.parameters.radialSegments!==o){if(!g.hasOwnProperty(r)){var l=new Rp.CylinderGeometry(a,a,1,o,1,!1);l[Pp]((new Rp.Matrix4).makeTranslation(0,.5,0)),l[Pp]((new Rp.Matrix4).makeRotationX(Math.PI/2)),g[r]=l}i.geometry.dispose(),i.geometry=g[r]}}var u=d(n);if(u)i.material=u;else{var c=f(n),h=new Rp.Color(Mp(c||"#f0f0f0")),p=e.linkOpacity*Ep(c),y=s?"MeshLambertMaterial":"LineBasicMaterial";if(i.material.type!==y||!i.material.color.equals(h)||i.material.opacity!==p){var x=s?_:v;x.hasOwnProperty(c)||(x[c]=new Rp[y]({color:h,transparent:p<1,opacity:p,depthWrite:p>=1})),i.material.dispose(),i.material=x[c]}}}})).digest(y),e.linkDirectionalArrowLength||t.hasOwnProperty("linkDirectionalArrowLength")){var x=Hh(e.linkDirectionalArrowLength),b=Hh(e.linkDirectionalArrowColor);e.arrowDataMapper.onCreateObj((function(){var e=new Rp.Mesh(void 0,new Rp.MeshLambertMaterial({transparent:!0}));return e.__linkThreeObjType="arrow",e})).onUpdateObj((function(t,n){var i=x(n),r=e.linkDirectionalArrowResolution;if(!t.geometry.type.match(/^Cone(Buffer)?Geometry$/)||t.geometry.parameters.height!==i||t.geometry.parameters.radialSegments!==r){var s=new Rp.ConeGeometry(.25*i,i,r);s.translate(0,i/2,0),s.rotateX(Math.PI/2),t.geometry.dispose(),t.geometry=s}var a=b(n)||f(n)||"#f0f0f0";t.material.color=new Rp.Color(Mp(a)),t.material.opacity=3*e.linkOpacity*Ep(a)})).digest(y.filter(x))}if(e.linkDirectionalParticles||t.hasOwnProperty("linkDirectionalParticles")){var S=Hh(e.linkDirectionalParticles),T=Hh(e.linkDirectionalParticleWidth),M=Hh(e.linkDirectionalParticleColor),E={},w={};e.particlesDataMapper.onCreateObj((function(){var e=new Rp.Group;return e.__linkThreeObjType="photons",e.__photonDataMapper=new Tp(e),e})).onUpdateObj((function(t,n){var i,r=Math.round(Math.abs(S(n))),s=!!t.children.length&&t.children[0],a=Math.ceil(10*T(n))/10/2,o=e.linkDirectionalParticleResolution;s&&s.geometry.parameters.radius===a&&s.geometry.parameters.widthSegments===o?i=s.geometry:(w.hasOwnProperty(a)||(w[a]=new Rp.SphereGeometry(a,o,o)),i=w[a],s&&s.geometry.dispose());var l,u=M(n)||f(n)||"#f0f0f0",c=new Rp.Color(Mp(u)),h=3*e.linkOpacity;s&&s.material.color.equals(c)&&s.material.opacity===h?l=s.material:(E.hasOwnProperty(u)||(E[u]=new Rp.MeshLambertMaterial({color:c,transparent:!0,opacity:h})),l=E[u],s&&s.material.dispose()),t.__photonDataMapper.id((function(e){return e.idx})).onCreateObj((function(){return new Rp.Mesh(i,l)})).onUpdateObj((function(e){e.geometry=i,e.material=l})).digest(fp(new Array(r)).map((function(e,t){return{idx:t}})))})).digest(y.filter(S))}}if(e._flushObjects=!1,n(["graphData","nodeId","linkSource","linkTarget","numDimensions","forceEngine","dagMode","dagNodeFilter","dagLevelDistance"])){e.engineRunning=!1,e.graphData.links.forEach((function(t){t.source=t[e.linkSource],t.target=t[e.linkTarget]}));var A,R="ngraph"!==e.forceEngine;if(R){(A=e.d3ForceLayout).stop().alpha(1).numDimensions(e.numDimensions).nodes(e.graphData.nodes);var C=e.d3ForceLayout.force("link");C&&C.id((function(t){return t[e.nodeId]})).links(e.graphData.links);var N=e.dagMode&&function(e,t){var n=e.nodes,i=e.links,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=r.nodeFilter,a=void 0===s?function(){return!0}:s,o=r.onLoopError,l=void 0===o?function(e){throw"Invalid DAG structure! Found cycle in node path: ".concat(e.join(" -> "),".")}:o,u={};n.forEach((function(e){return u[t(e)]={data:e,out:[],depth:-1,skip:!a(e)}})),i.forEach((function(e){var n=e.source,i=e.target,r=l(n),s=l(i);if(!u.hasOwnProperty(r))throw"Missing source node with id: ".concat(r);if(!u.hasOwnProperty(s))throw"Missing target node with id: ".concat(s);var a=u[r],o=u[s];function l(e){return"object"===gp(e)?t(e):e}a.out.push(o)}));var c=[];return function e(n){for(var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=function(){var s=n[a];if(-1!==i.indexOf(s)){var o=[].concat(fp(i.slice(i.indexOf(s))),[s]).map((function(e){return t(e.data)}));return c.some((function(e){return e.length===o.length&&e.every((function(e,t){return e===o[t]}))}))||(c.push(o),l(o)),1}r>s.depth&&(s.depth=r,e(s.out,[].concat(fp(i),[s]),r+(s.skip?0:1)))},a=0,o=n.length;a1&&(c.vy+=d*m),s>2&&(c.vz+=p*m)}}function c(){if(r){var t,n=r.length;for(a=new Array(n),o=new Array(n),t=0;t[1,2,3].includes(e)))||2,c()},u.strength=function(e){return arguments.length?(l="function"==typeof e?e:$u(+e),c(),u):l},u.radius=function(t){return arguments.length?(e="function"==typeof t?t:$u(+t),c(),u):e},u.x=function(e){return arguments.length?(t=+e,u):t},u.y=function(e){return arguments.length?(n=+e,u):n},u.z=function(e){return arguments.length?(i=+e,u):i},u}((function(t){var n=N[t[e.nodeId]]||-1;return("radialin"===e.dagMode?P-n:n)*D})).strength((function(t){return e.dagNodeFilter(t)?1:0})):null)}else{var O=Cp.graph();e.graphData.nodes.forEach((function(t){O.addNode(t[e.nodeId])})),e.graphData.links.forEach((function(e){O.addLink(e.source,e.target)})),A=Cp.forcelayout(O,function(e){for(var t=1;t0&&e.d3ForceLayout.alpha()2&&void 0!==arguments[2]&&arguments[2],n=function(n){function i(){var n;Jd(this,i);for(var r=arguments.length,s=new Array(r),a=0;a1&&void 0!==arguments[1]?arguments[1]:Object);return Object.keys(e()).forEach((function(e){return n.prototype[e]=function(){var t,n=(t=this.__kapsuleInstance)[e].apply(t,arguments);return n===this.__kapsuleInstance?this:n}})),n}(Dp,(window.THREE?window.THREE:{Group:Nr}).Group,!0);const Lp=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveMap","envMap","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"];class Ip{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Lp,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}getRenderObjectData(e){let t=this.renderObjects.get(e);if(void 0===t){const{geometry:n,material:i,object:r}=e;if(t={material:this.getMaterialData(i),geometry:{id:n.id,attributes:this.getAttributesData(n.attributes),indexVersion:n.index?n.index.version:null,drawRange:{start:n.drawRange.start,count:n.drawRange.count}},worldMatrix:r.matrixWorld.clone()},r.center&&(t.center=r.center.clone()),r.morphTargetInfluences&&(t.morphTargetInfluences=r.morphTargetInfluences.slice()),null!==e.bundle&&(t.version=e.bundle.version),t.material.transmission>0){const{width:n,height:i}=e.context;t.bufferWidth=n,t.bufferHeight=i}this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const n in e){const i=e[n];t[n]={version:i.version}}return t}containsNode(e){const t=e.material;for(const e in t)if(t[e]&&t[e].isNode)return!0;return null!==e.renderer.nodes.modelViewMatrix||null!==e.renderer.nodes.modelNormalViewMatrix}getMaterialData(e){const t={};for(const n of this.refreshUniforms){const i=e[n];null!=i&&("object"==typeof i&&void 0!==i.clone?!0===i.isTexture?t[n]={id:i.id,version:i.version}:t[n]=i.clone():t[n]=i)}return t}equals(e){const{object:t,material:n,geometry:i}=e,r=this.getRenderObjectData(e);if(!0!==r.worldMatrix.equals(t.matrixWorld))return r.worldMatrix.copy(t.matrixWorld),!1;const s=r.material;for(const e in s){const t=s[e],i=n[e];if(void 0!==t.equals){if(!1===t.equals(i))return t.copy(i),!1}else if(!0===i.isTexture){if(t.id!==i.id||t.version!==i.version)return t.id=i.id,t.version=i.version,!1}else if(t!==i)return s[e]=i,!1}if(s.transmission>0){const{width:t,height:n}=e.context;if(r.bufferWidth!==t||r.bufferHeight!==n)return r.bufferWidth=t,r.bufferHeight=n,!1}const a=r.geometry,o=i.attributes,l=a.attributes,u=Object.keys(l),c=Object.keys(o);if(a.id!==i.id)return a.id=i.id,!1;if(u.length!==c.length)return r.geometry.attributes=this.getAttributesData(o),!1;for(const e of u){const t=l[e],n=o[e];if(void 0===n)return delete l[e],!1;if(t.version!==n.version)return t.version=n.version,!1}const h=i.index,d=a.indexVersion,p=h?h.version:null;if(d!==p)return a.indexVersion=p,!1;if(a.drawRange.start!==i.drawRange.start||a.drawRange.count!==i.drawRange.count)return a.drawRange.start=i.drawRange.start,a.drawRange.count=i.drawRange.count,!1;if(r.morphTargetInfluences){let e=!1;for(let n=0;n>>16,2246822507),n^=Math.imul(i^i>>>13,3266489909),i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&i)+(n>>>0)}const Fp=e=>Op(e),Bp=(...e)=>Op(e);function kp(e,t=!1){const n=[];!0===e.isNode&&(n.push(e.id),e=e.getSelf());for(const{property:i,childNode:r}of zp(e))n.push(Op(i.slice(0,-4)),r.getCacheKey(t));return Op(n)}function*zp(e,t=!1){for(const n in e){if(!0===n.startsWith("_"))continue;const i=e[n];if(!0===Array.isArray(i))for(let e=0;ee.charCodeAt(0))).buffer):null;var i}function Wp(e){let t=Vp.get(e);return void 0===t&&(t={},Vp.set(e,t)),t}const Xp="vertex",qp="none",$p="frame",Yp="render",Kp="object",Zp="readOnly",Qp="writeOnly",Jp="readWrite",ef=["setup","analyze","generate"],tf=["fragment","vertex","compute"],nf=["x","y","z","w"];let rf=0;class sf extends Tt{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=qp,this.updateBeforeType=qp,this.updateAfterType=qp,this.uuid=Lt.generateUUID(),this.version=0,this.global=!1,this.isNode=!0,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:rf++})}set needsUpdate(e){!0===e&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,$p)}onRenderUpdate(e){return this.onUpdate(e,Yp)}onObjectUpdate(e){return this.onUpdate(e,Kp)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of zp(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(e=!1){return!0!==(e=e||this.version!==this._cacheKeyVersion)&&null!==this._cacheKey||(this._cacheKey=Bp(kp(this,e),this.customCacheKey()),this._cacheKeyVersion=this.version),this._cacheKey}customCacheKey(){return 0}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}setup(e){const t=e.getNodeProperties(this);let n=0;for(const e of this.getChildren())t["node"+n++]=e;return t.outputNode||null}analyze(e){if(1===e.increaseUsage(this)){const t=e.getNodeProperties(this);for(const n of Object.values(t))n&&!0===n.isNode&&n.build(e)}}generate(e,t){const{outputNode:n}=e.getNodeProperties(this);if(n&&!0===n.isNode)return n.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const n=this.getShared(e);if(this!==n)return n.build(e,t);e.addNode(this),e.addChain(this);let i=null;const r=e.getBuildStage();if("setup"===r){this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0;const n=this.setup(e),i=n&&!0===n.isNode;for(const n of Object.values(t))n&&!0===n.isNode&&n.build(e);i&&n.build(e),t.outputNode=n}}else if("analyze"===r)this.analyze(e);else if("generate"===r){if(1===this.generate.length){const n=this.getNodeType(e),r=e.getDataFromNode(this);i=r.snippet,void 0===i?(i=this.generate(e)||"",r.snippet=i):void 0!==r.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),i=e.format(i,n,t)}else i=this.generate(e,t)||""}return e.removeChain(this),e.addSequentialNode(this),i}getSerializeChildren(){return zp(this)}serialize(e){const t=this.getSerializeChildren(),n={};for(const{property:i,index:r,childNode:s}of t)void 0!==r?(void 0===n[i]&&(n[i]=Number.isInteger(r)?[]:{}),n[i][r]=s.toJSON(e.meta).uuid):n[i]=s.toJSON(e.meta).uuid;Object.keys(n).length>0&&(e.inputNodes=n)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const n in e.inputNodes)if(Array.isArray(e.inputNodes[n])){const i=[];for(const r of e.inputNodes[n])i.push(t[r]);this[n]=i}else if("object"==typeof e.inputNodes[n]){const i={};for(const r in e.inputNodes[n]){const s=e.inputNodes[n][r];i[r]=t[s]}this[n]=i}else{const i=e.inputNodes[n];this[n]=t[i]}}}toJSON(e){const{uuid:t,type:n}=this,i=void 0===e||"string"==typeof e;i&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];function s(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(void 0===r&&(r={uuid:t,type:n,meta:e,metadata:{version:4.6,type:"Node",generator:"Node.toJSON"}},!0!==i&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta),i){const t=s(e.textures),n=s(e.images),i=s(e.nodes);t.length>0&&(r.textures=t),n.length>0&&(r.images=n),i.length>0&&(r.nodes=i)}return r}}class af extends sf{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}generate(e){return`${this.node.build(e)}[ ${this.indexNode.build(e,"uint")} ]`}}class of extends sf{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let n=null;for(const i of this.convertTo.split("|"))null!==n&&e.getTypeLength(t)!==e.getTypeLength(i)||(n=i);return n}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const n=this.node,i=this.getNodeType(e),r=n.build(e,i);return e.format(r,i,t)}}class lf extends sf{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const n=e.getVectorType(this.getNodeType(e,t)),i=e.getDataFromNode(this);if(void 0!==i.propertyName)return e.format(i.propertyName,n,t);if("void"!==n&&"void"!==t&&this.hasDependencies(e)){const r=super.build(e,n),s=e.getVarFromNode(this,null,n),a=e.getPropertyName(s);return e.addLineFlowCode(`${a} = ${r}`,this),i.snippet=r,i.propertyName=a,e.format(i.propertyName,n,t)}}return super.build(e,t)}}class uf extends lf{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce(((t,n)=>t+e.getTypeLength(n.getNodeType(e))),0))}generate(e,t){const n=this.getNodeType(e),i=this.nodes,r=e.getComponentType(n),s=[];for(const t of i){let n=t.build(e);const i=e.getComponentType(t.getNodeType(e));i!==r&&(n=e.format(n,i,r)),s.push(n)}const a=`${e.getType(n)}( ${s.join(", ")} )`;return e.format(a,n,t)}}const cf=nf.join("");class hf extends sf{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(nf.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}generate(e,t){const n=this.node,i=e.getTypeLength(n.getNodeType(e));let r=null;if(i>1){let s=null;this.getVectorLength()>=i&&(s=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=n.build(e,s);r=this.components.length===i&&this.components===cf.slice(0,this.components.length)?e.format(a,s,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else r=n.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class df extends lf{static get type(){return"SetNode"}constructor(e,t,n){super(),this.sourceNode=e,this.components=t,this.targetNode=n}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:n,targetNode:i}=this,r=this.getNodeType(e),s=e.getComponentType(i.getNodeType(e)),a=e.getTypeFromLength(n.length,s),o=i.build(e,a),l=t.build(e,r),u=e.getTypeLength(r),c=[];for(let e=0;ee.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),Sf=e=>bf(e).split("").sort().join(""),Tf={setup(e,t){const n=t.shift();return e(qf(n),...t)},get(e,t,n){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(vf.assign(n,...e),n);if(yf.has(t)){const i=yf.get(t);return e.isStackNode?(...e)=>n.add(i(...e)):(...e)=>i(n,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&yf.has(t.slice(0,t.length-6))){const i=yf.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>n.assign(e[0],i(...e)):(...e)=>n.assign(i(n,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=bf(t),Xf(new hf(n,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=Sf(t.slice(3).toLowerCase()),n=>Xf(new df(e,t,n));if(!0===/^flip[XYZWRGBASTPQ]{1,4}$/.test(t))return t=Sf(t.slice(4).toLowerCase()),()=>Xf(new pf(Xf(e),t));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),Xf(new hf(e,t));if(!0===/^\d+$/.test(t))return Xf(new af(n,new gf(Number(t),"uint")));if(!0===/^get$/.test(t))return e=>Xf(new _f(n,e))}return Reflect.get(e,t,n)},set:(e,t,n,i)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,n,i):(i[t].assign(n),!0)},Mf=new WeakMap,Ef=new WeakMap,wf=function(e,t=null){for(const n in e)e[n]=Xf(e[n],t);return e},Af=function(e,t=null){const n=e.length;for(let i=0;iXf(null!==i?Object.assign(e,i):e);return null===t?(...t)=>r(new e(...$f(t))):null!==n?(n=Xf(n),(...i)=>r(new e(t,...$f(i),n))):(...n)=>r(new e(t,...$f(n)))},Cf=function(e,...t){return Xf(new e(...$f(t)))};class Nf extends sf{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,inputNodes:n}=this,i=e.getNodeProperties(t);if(i.onceOutput)return i.onceOutput;let r=null;if(t.layout){let i=Ef.get(e.constructor);void 0===i&&(i=new WeakMap,Ef.set(e.constructor,i));let s=i.get(t);void 0===s&&(s=Xf(e.buildFunctionNode(t)),i.set(t,s)),e.addInclude(s),r=Xf(s.call(n))}else{const i=t.jsFunc,s=null!==n||i.length>1?i(n||[],e):i(e);r=Xf(s)}return t.once&&(i.onceOutput=r),r}getOutputNode(e){const t=e.getNodeProperties(this);return null===t.outputNode&&(t.outputNode=this.setupOutput(e)),t.outputNode}setup(e){return this.getOutputNode(e)}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}generate(e,t){return this.getOutputNode(e).build(e,t)}}class Pf extends sf{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}call(e=null){return qf(e),Xf(new Nf(this,e))}setup(){return this.call()}}const Df=[!1,!0],Uf=[0,1,2,3],Lf=[-1,-2],If=[.5,1.5,1/3,1e-6,1e6,Math.PI,2*Math.PI,1/Math.PI,2/Math.PI,1/(2*Math.PI),Math.PI/2],Of=new Map;for(const e of Df)Of.set(e,new gf(e));const Ff=new Map;for(const e of Uf)Ff.set(e,new gf(e,"uint"));const Bf=new Map([...Ff].map((e=>new gf(e.value,"int"))));for(const e of Lf)Bf.set(e,new gf(e,"int"));const kf=new Map([...Bf].map((e=>new gf(e.value))));for(const e of If)kf.set(e,new gf(e));for(const e of If)kf.set(-e,new gf(-e));const zf={bool:Of,uint:Ff,ints:Bf,float:kf},Gf=new Map([...Of,...kf]),Vf=(e,t)=>Gf.has(e)?Gf.get(e):!0===e.isNode?e:new gf(e,t),Hf=function(e,t=null){return(...n)=>{if((0===n.length||!["bool","float","int","uint"].includes(e)&&n.every((e=>"object"!=typeof e)))&&(n=[jp(e,...n)]),1===n.length&&null!==t&&t.has(n[0]))return Xf(t.get(n[0]));if(1===n.length){const t=Vf(n[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?Xf(t):Xf(new of(t,e))}const i=n.map((e=>Vf(e)));return Xf(new uf(i,e))}},jf=e=>"object"==typeof e&&null!==e?e.value:e;function Wf(e,t){return new Proxy(new Pf(e,t),Tf)}const Xf=(e,t=null)=>function(e,t=null){const n=Hp(e);if("node"===n){let t=Mf.get(e);return void 0===t&&(t=new Proxy(e,Tf),Mf.set(e,t),Mf.set(t,t)),t}return null===t&&("float"===n||"boolean"===n)||n&&"shader"!==n&&"string"!==n?Xf(Vf(e,t)):"shader"===n?Zf(e):e}(e,t),qf=(e,t=null)=>new wf(e,t),$f=(e,t=null)=>new Af(e,t),Yf=(...e)=>new Rf(...e),Kf=(...e)=>new Cf(...e),Zf=(e,t)=>{const n=new Wf(e,t),i=(...e)=>{let t;return qf(e),t=e[0]&&e[0].isNode?[...e]:e[0],n.call(t)};return i.shaderNode=n,i.setLayout=e=>(n.setLayout(e),i),i.once=()=>(n.once=!0,i),i};xf("toGlobal",(e=>(e.global=!0,e)));const Qf=e=>{vf=e},Jf=()=>vf,em=(...e)=>vf.If(...e);xf("append",(function(e){return vf&&vf.add(e),e}));const tm=new Hf("color"),nm=new Hf("float",zf.float),im=new Hf("int",zf.ints),rm=new Hf("uint",zf.uint),sm=new Hf("bool",zf.bool),am=new Hf("vec2"),om=new Hf("ivec2"),lm=new Hf("uvec2"),um=new Hf("bvec2"),cm=new Hf("vec3"),hm=new Hf("ivec3"),dm=new Hf("uvec3"),pm=new Hf("bvec3"),fm=new Hf("vec4"),mm=new Hf("ivec4"),gm=new Hf("uvec4"),_m=new Hf("bvec4"),vm=new Hf("mat2"),ym=new Hf("mat3"),xm=new Hf("mat4");xf("toColor",tm),xf("toFloat",nm),xf("toInt",im),xf("toUint",rm),xf("toBool",sm),xf("toVec2",am),xf("toIVec2",om),xf("toUVec2",lm),xf("toBVec2",um),xf("toVec3",cm),xf("toIVec3",hm),xf("toUVec3",dm),xf("toBVec3",pm),xf("toVec4",fm),xf("toIVec4",mm),xf("toUVec4",gm),xf("toBVec4",_m),xf("toMat2",vm),xf("toMat3",ym),xf("toMat4",xm);xf("element",Yf(af)),xf("convert",((e,t)=>Xf(new of(Xf(e),t))));class bm extends lf{static get type(){return"ArrayNode"}constructor(e,t,n=null){super(e),this.count=t,this.values=n,this.isArrayNode=!0}getNodeType(e){return null===this.nodeType&&(this.nodeType=this.values[0].getNodeType(e)),this.nodeType}getElementType(e){return this.getNodeType(e)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}xf("toArray",((e,t)=>((...e)=>{let t;if(1===e.length){const n=e[0];t=new bm(null,n.length,n)}else{const n=e[0],i=e[1];t=new bm(n,i)}return Xf(t)})(Array(t).fill(e))));class Sm extends sf{static get type(){return"UniformGroupNode"}constructor(e,t=!1,n=1){super("string"),this.name=e,this.shared=t,this.order=n,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const Tm=e=>new Sm(e),Mm=(e,t=0)=>new Sm(e,!0,t),Em=Mm("frame"),wm=Mm("render"),Am=Tm("object");class Rm extends ff{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=Am}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const n=this.getSelf();return e=e.bind(n),super.onUpdate((t=>{const i=e(t,n);void 0!==i&&(this.value=i)}),t)}generate(e,t){const n=this.getNodeType(e),i=this.getUniformHash(e);let r=e.getNodeFromHash(i);void 0===r&&(e.setHashNode(this,i),r=this);const s=r.getInputType(e),a=e.getUniformFromNode(r,s,e.shaderStage,this.name||e.context.label),o=e.getPropertyName(a);return void 0!==e.context.label&&delete e.context.label,e.format(o,n,t)}}const Cm=(e,t)=>{const n=(e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null)(t||e),i=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return Xf(new Rm(i,n))};class Nm extends sf{static get type(){return"PropertyNode"}constructor(e,t=null,n=!1){super(e),this.name=t,this.varying=n,this.isPropertyNode=!0}getHash(e){return this.name||super.getHash(e)}isGlobal(){return!0}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const Pm=(e,t)=>Xf(new Nm(e,t)),Dm=(e,t)=>Xf(new Nm(e,t,!0)),Um=Kf(Nm,"vec4","DiffuseColor"),Lm=Kf(Nm,"vec3","EmissiveColor"),Im=Kf(Nm,"float","Roughness"),Om=Kf(Nm,"float","Metalness"),Fm=Kf(Nm,"float","Clearcoat"),Bm=Kf(Nm,"float","ClearcoatRoughness"),km=Kf(Nm,"vec3","Sheen"),zm=Kf(Nm,"float","SheenRoughness"),Gm=Kf(Nm,"float","Iridescence"),Vm=Kf(Nm,"float","IridescenceIOR"),Hm=Kf(Nm,"float","IridescenceThickness"),jm=Kf(Nm,"float","AlphaT"),Wm=Kf(Nm,"float","Anisotropy"),Xm=Kf(Nm,"vec3","AnisotropyT"),qm=Kf(Nm,"vec3","AnisotropyB"),$m=Kf(Nm,"color","SpecularColor"),Ym=Kf(Nm,"float","SpecularF90"),Km=Kf(Nm,"float","Shininess"),Zm=Kf(Nm,"vec4","Output"),Qm=Kf(Nm,"float","dashSize"),Jm=Kf(Nm,"float","gapSize"),eg=Kf(Nm,"float","IOR"),tg=Kf(Nm,"float","Transmission"),ng=Kf(Nm,"float","Thickness"),ig=Kf(Nm,"float","AttenuationDistance"),rg=Kf(Nm,"color","AttenuationColor"),sg=Kf(Nm,"float","Dispersion");class ag extends lf{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const n=e.getTypeLength(t.node.getNodeType(e));return nf.join("").slice(0,n)!==t.components}return!1}generate(e,t){const{targetNode:n,sourceNode:i}=this,r=this.needsSplitAssign(e),s=n.getNodeType(e),a=n.context({assign:!0}).build(e),o=i.build(e,s),l=i.getNodeType(e),u=e.getDataFromNode(this);let c;if(!0===u.initialized)"void"!==t&&(c=a);else if(r){const i=e.getVarFromNode(this,null,s),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${o}`,this);const l=n.node.context({assign:!0}).build(e);for(let t=0;t{const i=n.type;let r;return r="pointer"===i?"&"+t.build(e):t.build(e,i),r};if(Array.isArray(r))for(let e=0;e(t=t.length>1||t[0]&&!0===t[0].isNode?$f(t):qf(t[0]),Xf(new og(Xf(e),t)))));class lg extends lf{static get type(){return"OperatorNode"}constructor(e,t,n,...i){if(super(),i.length>0){let r=new lg(e,t,n);for(let t=0;t>"===n||"<<"===n)return e.getIntegerType(s);if("!"===n||"=="===n||"&&"===n||"||"===n||"^^"===n)return"bool";if("<"===n||">"===n||"<="===n||">="===n){const n=t?e.getTypeLength(t):Math.max(e.getTypeLength(s),e.getTypeLength(a));return n>1?`bvec${n}`:"bool"}if(e.isMatrix(s)){if("float"===a)return s;if(e.isVector(a))return e.getVectorFromMatrix(s);if(e.isMatrix(a))return s}else if(e.isMatrix(a)){if("float"===s)return a;if(e.isVector(s))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(s)?a:s}generate(e,t){const n=this.op,i=this.aNode,r=this.bNode,s=this.getNodeType(e,t);let a=null,o=null;"void"!==s?(a=i.getNodeType(e),o=void 0!==r?r.getNodeType(e):null,"<"===n||">"===n||"<="===n||">="===n||"=="===n?e.isVector(a)?o=a:a!==o&&(a=o="float"):">>"===n||"<<"===n?(a=s,o=e.changeComponentType(o,"uint")):e.isMatrix(a)?"float"===o?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=s):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=s:o=s):a=o=s;const l=i.build(e,a),u=void 0!==r?r.build(e,o):null,c=e.getTypeLength(t),h=e.getFunctionOperator(n);return"void"!==t?"<"===n&&c>1?e.useComparisonMethod?e.format(`${e.getMethod("lessThan",t)}( ${l}, ${u} )`,s,t):e.format(`( ${l} < ${u} )`,s,t):"<="===n&&c>1?e.useComparisonMethod?e.format(`${e.getMethod("lessThanEqual",t)}( ${l}, ${u} )`,s,t):e.format(`( ${l} <= ${u} )`,s,t):">"===n&&c>1?e.useComparisonMethod?e.format(`${e.getMethod("greaterThan",t)}( ${l}, ${u} )`,s,t):e.format(`( ${l} > ${u} )`,s,t):">="===n&&c>1?e.useComparisonMethod?e.format(`${e.getMethod("greaterThanEqual",t)}( ${l}, ${u} )`,s,t):e.format(`( ${l} >= ${u} )`,s,t):"!"===n||"~"===n?e.format(`(${n}${l})`,a,t):h?e.format(`${h}( ${l}, ${u} )`,s,t):e.isMatrix(a)&&"float"===o?e.format(`( ${u} ${n} ${l} )`,s,t):"float"===a&&e.isMatrix(o)?e.format(`${l} ${n} ${u}`,s,t):e.format(`( ${l} ${n} ${u} )`,s,t):"void"!==a?h?e.format(`${h}( ${l}, ${u} )`,s,t):e.isMatrix(a)&&"float"===o?e.format(`${u} ${n} ${l}`,s,t):e.format(`${l} ${n} ${u}`,s,t):void 0}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const ug=Yf(lg,"+"),cg=Yf(lg,"-"),hg=Yf(lg,"*"),dg=Yf(lg,"/"),pg=Yf(lg,"%"),fg=Yf(lg,"=="),mg=Yf(lg,"!="),gg=Yf(lg,"<"),_g=Yf(lg,">"),vg=Yf(lg,"<="),yg=Yf(lg,">="),xg=Yf(lg,"&&"),bg=Yf(lg,"||"),Sg=Yf(lg,"!"),Tg=Yf(lg,"^^"),Mg=Yf(lg,"&"),Eg=Yf(lg,"~"),wg=Yf(lg,"|"),Ag=Yf(lg,"^"),Rg=Yf(lg,"<<"),Cg=Yf(lg,">>");xf("add",ug),xf("sub",cg),xf("mul",hg),xf("div",dg),xf("modInt",pg),xf("equal",fg),xf("notEqual",mg),xf("lessThan",gg),xf("greaterThan",_g),xf("lessThanEqual",vg),xf("greaterThanEqual",yg),xf("and",xg),xf("or",bg),xf("not",Sg),xf("xor",Tg),xf("bitAnd",Mg),xf("bitNot",Eg),xf("bitOr",wg),xf("bitXor",Ag),xf("shiftLeft",Rg),xf("shiftRight",Cg);xf("remainder",((...e)=>(console.warn("TSL.OperatorNode: .remainder() has been renamed to .modInt()."),pg(...e))));class Ng extends lf{static get type(){return"MathNode"}constructor(e,t,n=null,i=null){super(),this.method=e,this.aNode=t,this.bNode=n,this.cNode=i,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),n=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,r=e.isMatrix(t)?0:e.getTypeLength(t),s=e.isMatrix(n)?0:e.getTypeLength(n),a=e.isMatrix(i)?0:e.getTypeLength(i);return r>s&&r>a?t:s>a?n:a>r?i:t}getNodeType(e){const t=this.method;return t===Ng.LENGTH||t===Ng.DISTANCE||t===Ng.DOT?"float":t===Ng.CROSS?"vec3":t===Ng.ALL?"bool":t===Ng.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):t===Ng.MOD?this.aNode.getNodeType(e):this.getInputType(e)}generate(e,t){let n=this.method;const i=this.getNodeType(e),r=this.getInputType(e),s=this.aNode,a=this.bNode,o=this.cNode,l=e.renderer.coordinateSystem;if(n===Ng.TRANSFORM_DIRECTION){let n=s,i=a;e.isMatrix(n.getNodeType(e))?i=fm(cm(i),0):n=fm(cm(n),0);const r=hg(n,i).xyz;return Wg(r).build(e,t)}if(n===Ng.NEGATE)return e.format("( - "+s.build(e,r)+" )",i,t);if(n===Ng.ONE_MINUS)return cg(1,s).build(e,t);if(n===Ng.RECIPROCAL)return dg(1,s).build(e,t);if(n===Ng.DIFFERENCE)return Jg(cg(s,a)).build(e,t);{const u=[];return n===Ng.CROSS||n===Ng.MOD?u.push(s.build(e,i),a.build(e,i)):l===bt&&n===Ng.STEP?u.push(s.build(e,1===e.getTypeLength(s.getNodeType(e))?"float":r),a.build(e,r)):l===bt&&(n===Ng.MIN||n===Ng.MAX)||n===Ng.MOD?u.push(s.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)):n===Ng.REFRACT?u.push(s.build(e,r),a.build(e,r),o.build(e,"float")):n===Ng.MIX?u.push(s.build(e,r),a.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):(l===St&&n===Ng.ATAN&&null!==a&&(n="atan2"),u.push(s.build(e,r)),null!==a&&u.push(a.build(e,r)),null!==o&&u.push(o.build(e,r))),e.format(`${e.getMethod(n,i)}( ${u.join(", ")} )`,i,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}Ng.ALL="all",Ng.ANY="any",Ng.RADIANS="radians",Ng.DEGREES="degrees",Ng.EXP="exp",Ng.EXP2="exp2",Ng.LOG="log",Ng.LOG2="log2",Ng.SQRT="sqrt",Ng.INVERSE_SQRT="inversesqrt",Ng.FLOOR="floor",Ng.CEIL="ceil",Ng.NORMALIZE="normalize",Ng.FRACT="fract",Ng.SIN="sin",Ng.COS="cos",Ng.TAN="tan",Ng.ASIN="asin",Ng.ACOS="acos",Ng.ATAN="atan",Ng.ABS="abs",Ng.SIGN="sign",Ng.LENGTH="length",Ng.NEGATE="negate",Ng.ONE_MINUS="oneMinus",Ng.DFDX="dFdx",Ng.DFDY="dFdy",Ng.ROUND="round",Ng.RECIPROCAL="reciprocal",Ng.TRUNC="trunc",Ng.FWIDTH="fwidth",Ng.TRANSPOSE="transpose",Ng.BITCAST="bitcast",Ng.EQUALS="equals",Ng.MIN="min",Ng.MAX="max",Ng.MOD="mod",Ng.STEP="step",Ng.REFLECT="reflect",Ng.DISTANCE="distance",Ng.DIFFERENCE="difference",Ng.DOT="dot",Ng.CROSS="cross",Ng.POW="pow",Ng.TRANSFORM_DIRECTION="transformDirection",Ng.MIX="mix",Ng.CLAMP="clamp",Ng.REFRACT="refract",Ng.SMOOTHSTEP="smoothstep",Ng.FACEFORWARD="faceforward";const Pg=nm(1e-6),Dg=nm(Math.PI),Ug=Yf(Ng,Ng.ALL),Lg=Yf(Ng,Ng.ANY),Ig=Yf(Ng,Ng.RADIANS),Og=Yf(Ng,Ng.DEGREES),Fg=Yf(Ng,Ng.EXP),Bg=Yf(Ng,Ng.EXP2),kg=Yf(Ng,Ng.LOG),zg=Yf(Ng,Ng.LOG2),Gg=Yf(Ng,Ng.SQRT),Vg=Yf(Ng,Ng.INVERSE_SQRT),Hg=Yf(Ng,Ng.FLOOR),jg=Yf(Ng,Ng.CEIL),Wg=Yf(Ng,Ng.NORMALIZE),Xg=Yf(Ng,Ng.FRACT),qg=Yf(Ng,Ng.SIN),$g=Yf(Ng,Ng.COS),Yg=Yf(Ng,Ng.TAN),Kg=Yf(Ng,Ng.ASIN),Zg=Yf(Ng,Ng.ACOS),Qg=Yf(Ng,Ng.ATAN),Jg=Yf(Ng,Ng.ABS),e_=Yf(Ng,Ng.SIGN),t_=Yf(Ng,Ng.LENGTH),n_=Yf(Ng,Ng.NEGATE),i_=Yf(Ng,Ng.ONE_MINUS),r_=Yf(Ng,Ng.DFDX),s_=Yf(Ng,Ng.DFDY),a_=Yf(Ng,Ng.ROUND),o_=Yf(Ng,Ng.RECIPROCAL),l_=Yf(Ng,Ng.TRUNC),u_=Yf(Ng,Ng.FWIDTH),c_=Yf(Ng,Ng.TRANSPOSE);Ng.BITCAST;const h_=Yf(Ng,Ng.EQUALS),d_=Yf(Ng,Ng.MIN),p_=Yf(Ng,Ng.MAX),f_=Yf(Ng,Ng.MOD),m_=Yf(Ng,Ng.STEP),g_=Yf(Ng,Ng.REFLECT),__=Yf(Ng,Ng.DISTANCE),v_=Yf(Ng,Ng.DIFFERENCE),y_=Yf(Ng,Ng.DOT),x_=Yf(Ng,Ng.CROSS),b_=Yf(Ng,Ng.POW),S_=Yf(Ng,Ng.POW,2),T_=Yf(Ng,Ng.POW,3),M_=Yf(Ng,Ng.POW,4),E_=Yf(Ng,Ng.TRANSFORM_DIRECTION),w_=e=>y_(e,e),A_=Yf(Ng,Ng.MIX),R_=(e,t=0,n=1)=>Xf(new Ng(Ng.CLAMP,Xf(e),Xf(t),Xf(n))),C_=Yf(Ng,Ng.REFRACT),N_=Yf(Ng,Ng.SMOOTHSTEP),P_=Yf(Ng,Ng.FACEFORWARD),D_=Zf((([e])=>{const t=y_(e.xy,am(12.9898,78.233)),n=f_(t,Dg);return Xg(qg(n).mul(43758.5453))}));xf("all",Ug),xf("any",Lg),xf("equals",h_),xf("radians",Ig),xf("degrees",Og),xf("exp",Fg),xf("exp2",Bg),xf("log",kg),xf("log2",zg),xf("sqrt",Gg),xf("inverseSqrt",Vg),xf("floor",Hg),xf("ceil",jg),xf("normalize",Wg),xf("fract",Xg),xf("sin",qg),xf("cos",$g),xf("tan",Yg),xf("asin",Kg),xf("acos",Zg),xf("atan",Qg),xf("abs",Jg),xf("sign",e_),xf("length",t_),xf("lengthSq",w_),xf("negate",n_),xf("oneMinus",i_),xf("dFdx",r_),xf("dFdy",s_),xf("round",a_),xf("reciprocal",o_),xf("trunc",l_),xf("fwidth",u_),xf("atan2",((e,t)=>(console.warn('THREE.TSL: "atan2" is overloaded. Use "atan" instead.'),Qg(e,t)))),xf("min",d_),xf("max",p_),xf("mod",f_),xf("step",m_),xf("reflect",g_),xf("distance",__),xf("dot",y_),xf("cross",x_),xf("pow",b_),xf("pow2",S_),xf("pow3",T_),xf("pow4",M_),xf("transformDirection",E_),xf("mix",((e,t,n)=>A_(t,n,e))),xf("clamp",R_),xf("refract",C_),xf("smoothstep",((e,t,n)=>N_(t,n,e))),xf("faceForward",P_),xf("difference",v_),xf("saturate",(e=>R_(e))),xf("cbrt",(e=>hg(e_(e),b_(Jg(e),1/3)))),xf("transpose",c_),xf("rand",D_);class U_ extends sf{static get type(){return"ConditionalNode"}constructor(e,t,n=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=n}getNodeType(e){const{ifNode:t,elseNode:n}=e.getNodeProperties(this);if(void 0===t)return this.setup(e),this.getNodeType(e);const i=t.getNodeType(e);if(null!==n){const t=n.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(i))return t}return i}setup(e){const t=this.condNode.cache(),n=this.ifNode.cache(),i=this.elseNode?this.elseNode.cache():null,r=e.context.nodeBlock;e.getDataFromNode(n).parentNodeBlock=r,null!==i&&(e.getDataFromNode(i).parentNodeBlock=r);const s=e.getNodeProperties(this);s.condNode=t,s.ifNode=n.context({nodeBlock:n}),s.elseNode=i?i.context({nodeBlock:i}):null}generate(e,t){const n=this.getNodeType(e),i=e.getDataFromNode(this);if(void 0!==i.nodeProperty)return i.nodeProperty;const{condNode:r,ifNode:s,elseNode:a}=e.getNodeProperties(this),o="void"!==t,l=o?Pm(n).build(e):"";i.nodeProperty=l;const u=r.build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${u} ) {\n\n`).addFlowTab();let c=s.build(e,n);if(c&&(c=o?l+" = "+c+";":"return "+c+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+c+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,n);t&&(t=o?l+" = "+t+";":"return "+t+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(l,n,t)}}const L_=Yf(U_);xf("select",L_);xf("cond",((...e)=>(console.warn("TSL.ConditionalNode: cond() has been renamed to select()."),L_(...e))));class I_ extends sf{static get type(){return"ContextNode"}constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}analyze(e){this.node.build(e)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value});const n=this.node.build(e);return e.setContext(t),n}generate(e,t){const n=e.getContext();e.setContext({...e.context,...this.value});const i=this.node.build(e,t);return e.setContext(n),i}}const O_=Yf(I_);xf("context",O_),xf("label",((e,t)=>O_(e,{label:t})));class F_ extends sf{static get type(){return"VarNode"}constructor(e,t=null,n=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=n}getHash(e){return this.name||super.getHash(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:n,readOnly:i}=this,{renderer:r}=e,s=!0===r.backend.isWebGPUBackend;let a=!1,o=!1;i&&(a=e.isDeterministic(t),o=s?i:a);const l=e.getVectorType(this.getNodeType(e)),u=t.build(e,l),c=e.getVarFromNode(this,n,l,void 0,o),h=e.getPropertyName(c);let d=h;if(o)if(s)d=a?`const ${h}`:`let ${h}`;else{const n=e.getArrayCount(t);d=`const ${e.getVar(c.type,h,n)}`}return e.addLineFlowCode(`${d} = ${u}`,this),h}}const B_=Yf(F_);xf("toVar",((e,t=null)=>B_(e,t).append())),xf("toConst",((e,t=null)=>B_(e,t,!0).append()));xf("temp",(e=>(console.warn('TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.'),B_(e))));class k_ extends sf{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0}isGlobal(){return!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let n=t.varying;if(void 0===n){const i=this.name,r=this.getNodeType(e);t.varying=n=e.getVaryingFromNode(this,i,r),t.node=this.node}return n.needsInterpolation||(n.needsInterpolation="fragment"===e.shaderStage),n}setup(e){this.setupVarying(e)}analyze(e){return this.setupVarying(e),this.node.analyze(e)}generate(e){const t=e.getNodeProperties(this),n=this.setupVarying(e),i="fragment"===e.shaderStage&&!0===t.reassignPosition&&e.context.needsPositionReassign;if(void 0===t.propertyName||i){const r=this.getNodeType(e),s=e.getPropertyName(n,Xp);e.flowNodeFromShaderStage(Xp,this.node,r,s),t.propertyName=s,i?t.reassignPosition=!1:void 0===t.reassignPosition&&e.context.isPositionNodeInput&&(t.reassignPosition=!0)}return e.getPropertyName(n)}}const z_=Yf(k_);xf("toVarying",z_),xf("toVertexStage",(e=>z_(e))),xf("varying",((...e)=>(console.warn("TSL.VaryingNode: .varying() has been renamed to .toVarying()."),z_(...e)))),xf("vertexStage",((...e)=>(console.warn("TSL.VaryingNode: .vertexStage() has been renamed to .toVertexStage()."),z_(...e))));const G_=Zf((([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),n=e.mul(.0773993808),i=e.lessThanEqual(.04045);return A_(t,n,i)})).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),V_=Zf((([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),n=e.mul(12.92),i=e.lessThanEqual(.0031308);return A_(t,n,i)})).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),H_="WorkingColorSpace",j_="OutputColorSpace";class W_ extends lf{static get type(){return"ColorSpaceNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this.source=t,this.target=n}resolveColorSpace(e,t){return t===H_?Xt.workingColorSpace:t===j_?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,n=this.resolveColorSpace(e,this.source),i=this.resolveColorSpace(e,this.target);let r=t;return!1!==Xt.enabled&&n!==i&&n&&i?(Xt.getTransfer(n)===lt&&(r=fm(G_(r.rgb),r.a)),Xt.getPrimaries(n)!==Xt.getPrimaries(i)&&(r=fm(ym(Xt._getMatrix(new Ot,n,i)).mul(r.rgb),r.a)),Xt.getTransfer(i)===lt&&(r=fm(V_(r.rgb),r.a)),r):r}}const X_=(e,t)=>Xf(new W_(Xf(e),t,H_));xf("toOutputColorSpace",(e=>Xf(new W_(Xf(e),H_,j_)))),xf("toWorkingColorSpace",(e=>Xf(new W_(Xf(e),j_,H_)))),xf("workingToColorSpace",((e,t)=>Xf(new W_(Xf(e),H_,t)))),xf("colorSpaceToWorking",X_);let q_=class extends af{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,n,i)}};class $_ extends sf{static get type(){return"ReferenceBaseNode"}constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.updateType=Kp}setGroup(e){return this.group=e,this}element(e){return Xf(new q_(this,Xf(e)))}setNodeType(e){const t=Cm(null,e).getSelf();null!==this.group&&t.setGroup(this.group),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;eXf(new Y_(e,t,n));class Z_ extends lf{static get type(){return"ToneMappingNode"}constructor(e,t=Q_,n=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=n}customCacheKey(){return Bp(this.toneMapping)}setup(e){const t=this.colorNode||e.context.color,n=this.toneMapping;if(0===n)return t;let i=null;const r=e.renderer.library.getToneMappingFunction(n);return null!==r?i=fm(r(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",n),i=t),i}}const Q_=K_("toneMappingExposure","float");xf("toneMapping",((e,t,n)=>((e,t,n)=>Xf(new Z_(e,Xf(t),Xf(n))))(t,n,e)));class J_ extends ff{static get type(){return"BufferAttributeNode"}constructor(e,t=null,n=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=n,this.bufferOffset=i,this.usage=vt,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(0===this.bufferStride&&0===this.bufferOffset){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),n=this.value,i=e.getTypeLength(t),r=this.bufferStride||i,s=this.bufferOffset,a=!0===n.isInterleavedBuffer?n:new Lr(n,r),o=new Or(a,i,s);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),n=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(n);let r=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=i,r=i;else{r=z_(this).build(e,t)}return r}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&!0===this.attribute.isBufferAttribute&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}const ev=(e,t=null,n=0,i=0)=>Xf(new J_(e,t,n,i)),tv=(e,t=null,n=0,i=0)=>ev(e,t,n,i).setInstanced(!0),nv=(e,t=null,n=0,i=0)=>((e,t=null,n=0,i=0)=>ev(e,t,n,i).setUsage(yt))(e,t,n,i).setInstanced(!0);xf("toAttribute",(e=>ev(e.value)));class iv extends sf{static get type(){return"ComputeNode"}constructor(e,t,n=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=n,this.dispatchCount=0,this.version=1,this.name="",this.updateBeforeType=Kp,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}label(e){return this.name=e,this}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let n=t[0];for(let e=1;eXf(new iv(Xf(e),t,n))));class rv extends sf{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!0}getNodeType(e){const t=e.getCache(),n=e.getCacheFromNode(this,this.parent);e.setCache(n);const i=this.node.getNodeType(e);return e.setCache(t),i}build(e,...t){const n=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const r=this.node.build(e,...t);return e.setCache(n),r}}const sv=(e,t)=>Xf(new rv(Xf(e),t));xf("cache",sv);class av extends sf{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}xf("bypass",Yf(av));class ov extends sf{static get type(){return"RemapNode"}constructor(e,t,n,i=nm(0),r=nm(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=n,this.outLowNode=i,this.outHighNode=r,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:n,outLowNode:i,outHighNode:r,doClamp:s}=this;let a=e.sub(t).div(n.sub(t));return!0===s&&(a=a.clamp()),a.mul(r.sub(i)).add(i)}}const lv=Yf(ov,null,null,{doClamp:!1}),uv=Yf(ov);xf("remap",lv),xf("remapClamp",uv);class cv extends sf{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const n=this.getNodeType(e),i=this.snippet;if("void"!==n)return e.format(`( ${i} )`,n,t);e.addLineFlowCode(i,this)}}const hv=Yf(cv);xf("discard",(e=>(e?L_(e,hv("discard")):hv("discard")).append()));class dv extends lf{static get type(){return"RenderOutputNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=n,this.isRenderOutputNode=!0}setup({context:e}){let t=this.colorNode||e.color;const n=(null!==this.toneMapping?this.toneMapping:e.toneMapping)||0,i=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||rt;return 0!==n&&(t=t.toneMapping(n)),i!==rt&&i!==Xt.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}xf("renderOutput",((e,t=null,n=null)=>Xf(new dv(Xf(e),t,n))));class pv extends sf{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(null===t){const n=this.getAttributeName(e);if(e.hasGeometryAttribute(n)){const i=e.geometry.getAttribute(n);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),n=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const i=e.geometry.getAttribute(t),r=e.getTypeFromAttribute(i),s=e.getAttribute(t,r);if("vertex"===e.shaderStage)return e.format(s.name,r,n);return z_(this).build(e,n)}return console.warn(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(n)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const fv=(e,t)=>Xf(new pv(e,t)),mv=(e=0)=>fv("uv"+(e>0?e:""),"vec2");class gv extends sf{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const n=this.textureNode.build(e,"property"),i=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${n}, ${i} )`,this.getNodeType(e),t)}}const _v=Yf(gv);class vv extends Rm{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=$p}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,n=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(n&&void 0!==n.width){const{width:e,height:t}=n;this.value=Math.log2(Math.max(e,t))}}}const yv=Yf(vv);class xv extends Rm{static get type(){return"TextureNode"}constructor(e,t=null,n=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=n,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=qp,this.referenceNode=null,this._value=e,this._matrixUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===oe?"uvec4":this.value.type===ae?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return mv(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=Cm(this.value.matrix)),this._matrixUniform.mul(cm(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?Yp:qp,this}setupUV(e,t){const n=this.value;return e.isFlipY()&&(n.image instanceof ImageBitmap&&!0===n.flipY||!0===n.isRenderTargetTexture||!0===n.isFramebufferTexture||!0===n.isDepthTexture)&&(t=this.sampler?t.flipY():t.setY(im(_v(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const n=this.value;if(!n||!0!==n.isTexture)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");let i=this.uvNode;null!==i&&!0!==e.context.forceUVContext||!e.context.getUV||(i=e.context.getUV(this)),i||(i=this.getDefaultUV()),!0===this.updateMatrix&&(i=this.getTransformedUV(i)),i=this.setupUV(e,i);let r=this.levelNode;null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),t.uvNode=i,t.levelNode=r,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,n,i,r,s,a,o){const l=this.value;let u;return u=i?e.generateTextureLevel(l,t,n,i,s):r?e.generateTextureBias(l,t,n,r,s):o?e.generateTextureGrad(l,t,n,o,s):a?e.generateTextureCompare(l,t,n,a,s):!1===this.sampler?e.generateTextureLoad(l,t,n,s):e.generateTexture(l,t,n,s),u}generate(e,t){const n=this.value,i=e.getNodeProperties(this),r=super.generate(e,"property");if("sampler"===t)return r+"_sampler";if(e.isReference(t))return r;{const s=e.getDataFromNode(this);let a=s.propertyName;if(void 0===a){const{uvNode:t,levelNode:n,biasNode:o,compareNode:l,depthNode:u,gradNode:c}=i,h=this.generateUV(e,t),d=n?n.build(e,"float"):null,p=o?o.build(e,"float"):null,f=u?u.build(e,"int"):null,m=l?l.build(e,"float"):null,g=c?[c[0].build(e,"vec2"),c[1].build(e,"vec2")]:null,_=e.getVarFromNode(this);a=e.getPropertyName(_);const v=this.generateSnippet(e,r,h,d,p,f,m,g);e.addLineFlowCode(`${a} = ${v}`,this),s.snippet=v,s.propertyName=a}let o=a;const l=this.getNodeType(e);return e.needsToWorkingColorSpace(n)&&(o=X_(hv(o,l),n.colorSpace).setup(e).build(e,l)),e.format(o,l,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return console.warn("THREE.TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=Xf(e),t.referenceNode=this.getSelf(),Xf(t)}blur(e){const t=this.clone();return t.biasNode=Xf(e).mul(yv(t)),t.referenceNode=this.getSelf(),Xf(t)}level(e){const t=this.clone();return t.levelNode=Xf(e),t.referenceNode=this.getSelf(),Xf(t)}size(e){return _v(this,e)}bias(e){const t=this.clone();return t.biasNode=Xf(e),t.referenceNode=this.getSelf(),Xf(t)}compare(e){const t=this.clone();return t.compareNode=Xf(e),t.referenceNode=this.getSelf(),Xf(t)}grad(e,t){const n=this.clone();return n.gradNode=[Xf(e),Xf(t)],n.referenceNode=this.getSelf(),Xf(n)}depth(e){const t=this.clone();return t.depthNode=Xf(e),t.referenceNode=this.getSelf(),Xf(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix()}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e}}const bv=Yf(xv),Sv=(...e)=>bv(...e).setSampler(!1);class Tv extends Rm{static get type(){return"BufferNode"}constructor(e,t,n=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=n}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Mv=(e,t,n)=>Xf(new Tv(e,t,n));class Ev extends af{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),n=this.getNodeType(),i=this.node.getPaddedType();return e.format(t,i,n)}}class wv extends Tv{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Hp(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Yp,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,n=this.elementType;if("float"===n||"int"===n||"uint"===n)for(let n=0;nXf(new wv(e,t)),Rv=Cm(0,"uint").setGroup(Mm("cameraIndex")).toVarying("v_cameraIndex"),Cv=Cm("float").label("cameraNear").setGroup(wm).onRenderUpdate((({camera:e})=>e.near)),Nv=Cm("float").label("cameraFar").setGroup(wm).onRenderUpdate((({camera:e})=>e.far)),Pv=Zf((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.projectionMatrix);t=Av(n).setGroup(wm).label("cameraProjectionMatrices").element(Rv).toVar("cameraProjectionMatrix")}else t=Cm("mat4").label("cameraProjectionMatrix").setGroup(wm).onRenderUpdate((({camera:e})=>e.projectionMatrix));return t})).once()(),Dv=Zf((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.matrixWorldInverse);t=Av(n).setGroup(wm).label("cameraViewMatrices").element(Rv).toVar("cameraViewMatrix")}else t=Cm("mat4").label("cameraViewMatrix").setGroup(wm).onRenderUpdate((({camera:e})=>e.matrixWorldInverse));return t})).once()(),Uv=Cm(new un).label("cameraPosition").setGroup(wm).onRenderUpdate((({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),Lv=new Nn;class Iv extends sf{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Kp,this._uniformNode=new Rm(null)}getNodeType(){const e=this.scope;return e===Iv.WORLD_MATRIX?"mat4":e===Iv.POSITION||e===Iv.VIEW_POSITION||e===Iv.DIRECTION||e===Iv.SCALE?"vec3":e===Iv.RADIUS?"float":void 0}update(e){const t=this.object3d,n=this._uniformNode,i=this.scope;if(i===Iv.WORLD_MATRIX)n.value=t.matrixWorld;else if(i===Iv.POSITION)n.value=n.value||new un,n.value.setFromMatrixPosition(t.matrixWorld);else if(i===Iv.SCALE)n.value=n.value||new un,n.value.setFromMatrixScale(t.matrixWorld);else if(i===Iv.DIRECTION)n.value=n.value||new un,t.getWorldDirection(n.value);else if(i===Iv.VIEW_POSITION){const i=e.camera;n.value=n.value||new un,n.value.setFromMatrixPosition(t.matrixWorld),n.value.applyMatrix4(i.matrixWorldInverse)}else if(i===Iv.RADIUS){const i=e.object.geometry;null===i.boundingSphere&&i.computeBoundingSphere(),Lv.copy(i.boundingSphere).applyMatrix4(t.matrixWorld),n.value=Lv.radius}}generate(e){const t=this.scope;return t===Iv.WORLD_MATRIX?this._uniformNode.nodeType="mat4":t===Iv.POSITION||t===Iv.VIEW_POSITION||t===Iv.DIRECTION||t===Iv.SCALE?this._uniformNode.nodeType="vec3":t===Iv.RADIUS&&(this._uniformNode.nodeType="float"),this._uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Iv.WORLD_MATRIX="worldMatrix",Iv.POSITION="position",Iv.SCALE="scale",Iv.VIEW_POSITION="viewPosition",Iv.DIRECTION="direction",Iv.RADIUS="radius",Iv.DIRECTION,Iv.WORLD_MATRIX;const Ov=Yf(Iv,Iv.POSITION);Iv.SCALE,Iv.VIEW_POSITION,Iv.RADIUS;class Fv extends Iv{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Bv=Kf(Fv,Fv.WORLD_MATRIX),kv=Cm(new Ot).onObjectUpdate((({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld))),zv=Zf((e=>e.renderer.nodes.modelViewMatrix||Gv)).once()().toVar("modelViewMatrix"),Gv=Dv.mul(Bv),Vv=fv("position","vec3"),Hv=Vv.toVarying("positionLocal"),jv=Vv.toVarying("positionPrevious"),Wv=Bv.mul(Hv).xyz.toVarying("v_positionWorld").context({needsPositionReassign:!0}),Xv=Hv.transformDirection(Bv).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection").context({needsPositionReassign:!0}),qv=Zf((e=>e.context.setupPositionView()),"vec3").once()().toVarying("v_positionView").context({needsPositionReassign:!0}),$v=qv.negate().toVarying("v_positionViewDirection").normalize().toVar("positionViewDirection");class Yv extends sf{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){const{renderer:t,material:n}=e;return t.coordinateSystem===bt&&1===n.side?"false":e.getFrontFacing()}}const Kv=nm(Kf(Yv)).mul(2).sub(1),Zv=fv("normal","vec3"),Qv=Zf((e=>!1===e.geometry.hasAttribute("normal")?(console.warn('TSL.NormalNode: Vertex attribute "normal" not found on geometry.'),cm(0,1,0)):Zv),"vec3").once()().toVar("normalLocal"),Jv=qv.dFdx().cross(qv.dFdy()).normalize().toVar("normalFlat"),ey=Zf((e=>{let t;return t=!0===e.material.flatShading?Jv:z_(ay(Qv),"v_normalView").normalize(),t}),"vec3").once()().toVar("normalView"),ty=z_(ey.transformDirection(Dv),"v_normalWorld").normalize().toVar("normalWorld"),ny=Zf((e=>e.context.setupNormal().context({getUV:null})),"vec3").once()().mul(Kv).toVar("transformedNormalView"),iy=ny.transformDirection(Dv).toVar("transformedNormalWorld"),ry=Zf((e=>e.context.setupClearcoatNormal().context({getUV:null})),"vec3").once()().mul(Kv).toVar("transformedClearcoatNormalView"),sy=Zf((([e,t=Bv])=>{const n=ym(t),i=e.div(cm(n[0].dot(n[0]),n[1].dot(n[1]),n[2].dot(n[2])));return n.mul(i).xyz})),ay=Zf((([e],t)=>{const n=t.renderer.nodes.modelNormalViewMatrix;if(null!==n)return n.transformDirection(e);const i=kv.mul(e);return Dv.transformDirection(i)})),oy=new Yn,ly=new kn,uy=Cm(0).onReference((({material:e})=>e)).onObjectUpdate((({material:e})=>e.refractionRatio)),cy=Cm(1).onReference((({material:e})=>e)).onObjectUpdate((function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity})),hy=Cm(new kn).onReference((function(e){return e.material})).onObjectUpdate((function({material:e,scene:t}){const n=null!==t.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation;return n?(oy.copy(n),ly.makeRotationFromEuler(oy)):ly.identity(),ly})),dy=$v.negate().reflect(ny),py=$v.negate().refract(ny,uy),fy=dy.transformDirection(Dv).toVar("reflectVector"),my=py.transformDirection(Dv).toVar("reflectVector");class gy extends xv{static get type(){return"CubeTextureNode"}constructor(e,t=null,n=null,i=null){super(e,t,n,i),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===V?fy:e.mapping===H?my:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),cm(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return e.renderer.coordinateSystem!==St&&n.isRenderTargetTexture||(t=cm(t.x.negate(),t.yz)),hy.mul(t)}generateUV(e,t){return t.build(e,"vec3")}}const _y=Yf(gy);class vy extends af{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,n,i)}}class yy extends sf{static get type(){return"ReferenceNode"}constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.name=null,this.updateType=Kp}element(e){return Xf(new vy(this,Xf(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;t=null!==this.count?Mv(null,e,this.count):Array.isArray(this.getValueFromReference())?Av(null,e):"texture"===e?bv(null):"cubeTexture"===e?_y(null):Cm(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.label(this.name),this.node=t.getSelf()}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;eXf(new yy(e,t,n)),by=(e,t,n,i)=>Xf(new yy(e,t,i,n));class Sy extends yy{static get type(){return"MaterialReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.material=n,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const Ty=(e,t,n=null)=>Xf(new Sy(e,t,n)),My=Zf((e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),fv("tangent","vec4"))))(),Ey=My.xyz.toVar("tangentLocal"),wy=zv.mul(fm(Ey,0)).xyz.toVarying("v_tangentView").normalize().toVar("tangentView");var Ay;const Ry=ym(wy,z_((Ay=ey.cross(wy),Ay.mul(My.w).xyz),"v_bitangentView").normalize().toVar("bitangentView"),ey),Cy=(()=>{let e=qm.cross($v);return e=e.cross(qm).normalize(),e=A_(e,ny,Wm.mul(Im.oneMinus()).oneMinus().pow2().pow2()).normalize(),e})(),Ny=Zf((e=>{const{eye_pos:t,surf_norm:n,mapN:i,uv:r}=e,s=t.dFdx(),a=t.dFdy(),o=r.dFdx(),l=r.dFdy(),u=n,c=a.cross(u),h=u.cross(s),d=c.mul(o.x).add(h.mul(l.x)),p=c.mul(o.y).add(h.mul(l.y)),f=d.dot(d).max(p.dot(p)),m=Kv.mul(f.inverseSqrt());return ug(d.mul(i.x,m),p.mul(i.y,m),u.mul(i.z)).normalize()}));class Py extends lf{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0}setup(e){const{normalMapType:t,scaleNode:n}=this;let i=this.node.mul(2).sub(1);null!==n&&(i=cm(i.xy.mul(n),i.z));let r=null;if(1===t)r=ay(i);else if(0===t){r=!0===e.hasGeometryAttribute("tangent")?Ry.mul(i).normalize():Ny({eye_pos:qv,surf_norm:ey,mapN:i,uv:mv()})}return r}}const Dy=Yf(Py),Uy=Zf((({textureNode:e,bumpScale:t})=>{const n=t=>e.cache().context({getUV:e=>t(e.uvNode||mv()),forceUVContext:!0}),i=nm(n((e=>e)));return am(nm(n((e=>e.add(e.dFdx())))).sub(i),nm(n((e=>e.add(e.dFdy())))).sub(i)).mul(t)})),Ly=Zf((e=>{const{surf_pos:t,surf_norm:n,dHdxy:i}=e,r=t.dFdx().normalize(),s=n,a=t.dFdy().normalize().cross(s),o=s.cross(r),l=r.dot(a).mul(Kv),u=l.sign().mul(i.x.mul(a).add(i.y.mul(o)));return l.abs().mul(n).sub(u).normalize()}));class Iy extends lf{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=Uy({textureNode:this.textureNode,bumpScale:e});return Ly({surf_pos:qv,surf_norm:ey,dHdxy:t})}}const Oy=Yf(Iy),Fy=new Map;class By extends sf{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let n=Fy.get(e);return void 0===n&&(n=Ty(e,t),Fy.set(e,n)),n}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache("map"===e?"map":e+"Map","texture")}setup(e){const t=e.context.material,n=this.scope;let i=null;if(n===By.COLOR){const e=void 0!==t.color?this.getColor(n):cm();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(n===By.OPACITY){const e=this.getFloat(n);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(n===By.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:nm(1);else if(n===By.SPECULAR_INTENSITY){const e=this.getFloat(n);i=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(n).a):e}else if(n===By.SPECULAR_COLOR){const e=this.getColor(n);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(n).rgb):e}else if(n===By.ROUGHNESS){const e=this.getFloat(n);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(n).g):e}else if(n===By.METALNESS){const e=this.getFloat(n);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(n).b):e}else if(n===By.EMISSIVE){const e=this.getFloat("emissiveIntensity"),r=this.getColor(n).mul(e);i=t.emissiveMap&&!0===t.emissiveMap.isTexture?r.mul(this.getTexture(n)):r}else if(n===By.NORMAL)t.normalMap?(i=Dy(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType):i=t.bumpMap?Oy(this.getTexture("bump").r,this.getFloat("bumpScale")):ey;else if(n===By.CLEARCOAT){const e=this.getFloat(n);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===By.CLEARCOAT_ROUGHNESS){const e=this.getFloat(n);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===By.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?Dy(this.getTexture(n),this.getCache(n+"Scale","vec2")):ey;else if(n===By.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));i=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(n===By.SHEEN_ROUGHNESS){const e=this.getFloat(n);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(n).a):e,i=i.clamp(.07,1)}else if(n===By.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(n);i=vm(bx.x,bx.y,bx.y.negate(),bx.x).mul(e.rg.mul(2).sub(am(1)).normalize().mul(e.b))}else i=bx;else if(n===By.IRIDESCENCE_THICKNESS){const e=xy("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=xy("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(n).g).add(r)}else i=e}else if(n===By.TRANSMISSION){const e=this.getFloat(n);i=t.transmissionMap?e.mul(this.getTexture(n).r):e}else if(n===By.THICKNESS){const e=this.getFloat(n);i=t.thicknessMap?e.mul(this.getTexture(n).g):e}else if(n===By.IOR)i=this.getFloat(n);else if(n===By.LIGHT_MAP)i=this.getTexture(n).rgb.mul(this.getFloat("lightMapIntensity"));else if(n===By.AO)i=this.getTexture(n).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else{const t=this.getNodeType(e);i=this.getCache(n,t)}return i}}By.ALPHA_TEST="alphaTest",By.COLOR="color",By.OPACITY="opacity",By.SHININESS="shininess",By.SPECULAR="specular",By.SPECULAR_STRENGTH="specularStrength",By.SPECULAR_INTENSITY="specularIntensity",By.SPECULAR_COLOR="specularColor",By.REFLECTIVITY="reflectivity",By.ROUGHNESS="roughness",By.METALNESS="metalness",By.NORMAL="normal",By.CLEARCOAT="clearcoat",By.CLEARCOAT_ROUGHNESS="clearcoatRoughness",By.CLEARCOAT_NORMAL="clearcoatNormal",By.EMISSIVE="emissive",By.ROTATION="rotation",By.SHEEN="sheen",By.SHEEN_ROUGHNESS="sheenRoughness",By.ANISOTROPY="anisotropy",By.IRIDESCENCE="iridescence",By.IRIDESCENCE_IOR="iridescenceIOR",By.IRIDESCENCE_THICKNESS="iridescenceThickness",By.IOR="ior",By.TRANSMISSION="transmission",By.THICKNESS="thickness",By.ATTENUATION_DISTANCE="attenuationDistance",By.ATTENUATION_COLOR="attenuationColor",By.LINE_SCALE="scale",By.LINE_DASH_SIZE="dashSize",By.LINE_GAP_SIZE="gapSize",By.LINE_WIDTH="linewidth",By.LINE_DASH_OFFSET="dashOffset",By.POINT_SIZE="size",By.DISPERSION="dispersion",By.LIGHT_MAP="light",By.AO="ao";const ky=Kf(By,By.ALPHA_TEST),zy=Kf(By,By.COLOR),Gy=Kf(By,By.SHININESS),Vy=Kf(By,By.EMISSIVE),Hy=Kf(By,By.OPACITY),jy=Kf(By,By.SPECULAR),Wy=Kf(By,By.SPECULAR_INTENSITY),Xy=Kf(By,By.SPECULAR_COLOR),qy=Kf(By,By.SPECULAR_STRENGTH),$y=Kf(By,By.REFLECTIVITY),Yy=Kf(By,By.ROUGHNESS),Ky=Kf(By,By.METALNESS),Zy=Kf(By,By.NORMAL),Qy=Kf(By,By.CLEARCOAT),Jy=Kf(By,By.CLEARCOAT_ROUGHNESS),ex=Kf(By,By.CLEARCOAT_NORMAL),tx=Kf(By,By.ROTATION),nx=Kf(By,By.SHEEN),ix=Kf(By,By.SHEEN_ROUGHNESS),rx=Kf(By,By.ANISOTROPY),sx=Kf(By,By.IRIDESCENCE),ax=Kf(By,By.IRIDESCENCE_IOR),ox=Kf(By,By.IRIDESCENCE_THICKNESS),lx=Kf(By,By.TRANSMISSION),ux=Kf(By,By.THICKNESS),cx=Kf(By,By.IOR),hx=Kf(By,By.ATTENUATION_DISTANCE),dx=Kf(By,By.ATTENUATION_COLOR),px=Kf(By,By.LINE_SCALE),fx=Kf(By,By.LINE_DASH_SIZE),mx=Kf(By,By.LINE_GAP_SIZE);By.LINE_WIDTH;const gx=Kf(By,By.LINE_DASH_OFFSET),_x=Kf(By,By.POINT_SIZE),vx=Kf(By,By.DISPERSION),yx=Kf(By,By.LIGHT_MAP),xx=Kf(By,By.AO),bx=Cm(new It).onReference((function(e){return e.material})).onRenderUpdate((function({material:e}){this.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation))})),Sx=Zf((e=>e.context.setupModelViewProjection()),"vec4").once()().toVarying("v_modelViewProjection");class Tx extends sf{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),n=this.scope;let i,r;if(n===Tx.VERTEX)i=e.getVertexIndex();else if(n===Tx.INSTANCE)i=e.getInstanceIndex();else if(n===Tx.DRAW)i=e.getDrawIndex();else if(n===Tx.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(n===Tx.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(n!==Tx.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+n);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=z_(this).build(e,t)}return r}}Tx.VERTEX="vertex",Tx.INSTANCE="instance",Tx.SUBGROUP="subgroup",Tx.INVOCATION_LOCAL="invocationLocal",Tx.INVOCATION_SUBGROUP="invocationSubgroup",Tx.DRAW="draw";const Mx=Kf(Tx,Tx.VERTEX),Ex=Kf(Tx,Tx.INSTANCE);Tx.SUBGROUP,Tx.INVOCATION_SUBGROUP,Tx.INVOCATION_LOCAL;const wx=Kf(Tx,Tx.DRAW);class Ax extends sf{static get type(){return"InstanceNode"}constructor(e,t,n){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=n,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=$p,this.buffer=null,this.bufferColor=null}setup(e){const{count:t,instanceMatrix:n,instanceColor:i}=this;let{instanceMatrixNode:r,instanceColorNode:s}=this;if(null===r){if(t<=1e3)r=Mv(n.array,"mat4",Math.max(t,1)).element(Ex);else{const e=new la(n.array,16,1);this.buffer=e;const t=n.usage===yt?nv:tv,i=[t(e,"vec4",16,0),t(e,"vec4",16,4),t(e,"vec4",16,8),t(e,"vec4",16,12)];r=xm(...i)}this.instanceMatrixNode=r}if(i&&null===s){const e=new kr(i.array,3),t=i.usage===yt?nv:tv;this.bufferColor=e,s=cm(t(e,"vec3",3,0)),this.instanceColorNode=s}const a=r.mul(Hv).xyz;if(Hv.assign(a),e.hasGeometryAttribute("normal")){const e=sy(Qv,r);Qv.assign(e)}null!==this.instanceColorNode&&Dm("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMatrix.usage!==yt&&null!==this.buffer&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version),this.instanceColor&&this.instanceColor.usage!==yt&&null!==this.bufferColor&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)}}class Rx extends Ax{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:n,instanceColor:i}=e;super(t,n,i),this.instancedMesh=e}}const Cx=Yf(Rx);class Nx extends sf{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){null===this.batchingIdNode&&(null===e.getDrawIndex()?this.batchingIdNode=Ex:this.batchingIdNode=wx);const t=Zf((([e])=>{const t=im(_v(Sv(this.batchMesh._indirectTexture),0)),n=im(e).modInt(t),i=im(e).div(t);return Sv(this.batchMesh._indirectTexture,om(n,i)).x})).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),n=t(im(this.batchingIdNode)),i=this.batchMesh._matricesTexture,r=_v(Sv(i),0),s=nm(n).mul(4).toInt().toVar(),a=s.modInt(r),o=s.div(im(r)),l=xm(Sv(i,om(a,o)),Sv(i,om(a.add(1),o)),Sv(i,om(a.add(2),o)),Sv(i,om(a.add(3),o))),u=this.batchMesh._colorsTexture;if(null!==u){const e=Zf((([e])=>{const t=_v(Sv(u),0).x,n=e,i=n.modInt(t),r=n.div(t);return Sv(u,om(i,r)).rgb})).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(n);Dm("vec3","vBatchColor").assign(t)}const c=ym(l);Hv.assign(l.mul(Hv));const h=Qv.div(cm(c[0].dot(c[0]),c[1].dot(c[1]),c[2].dot(c[2]))),d=c.mul(h).xyz;Qv.assign(d),e.hasGeometryAttribute("tangent")&&Ey.mulAssign(c)}}const Px=Yf(Nx),Dx=new WeakMap;class Ux extends sf{static get type(){return"SkinningNode"}constructor(e,t=!1){let n,i,r;super("void"),this.skinnedMesh=e,this.useReference=t,this.updateType=Kp,this.skinIndexNode=fv("skinIndex","uvec4"),this.skinWeightNode=fv("skinWeight","vec4"),t?(n=xy("bindMatrix","mat4"),i=xy("bindMatrixInverse","mat4"),r=by("skeleton.boneMatrices","mat4",e.skeleton.bones.length)):(n=Cm(e.bindMatrix,"mat4"),i=Cm(e.bindMatrixInverse,"mat4"),r=Mv(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length)),this.bindMatrixNode=n,this.bindMatrixInverseNode=i,this.boneMatricesNode=r,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=Hv){const{skinIndexNode:n,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:s}=this,a=e.element(n.x),o=e.element(n.y),l=e.element(n.z),u=e.element(n.w),c=r.mul(t),h=ug(a.mul(i.x).mul(c),o.mul(i.y).mul(c),l.mul(i.z).mul(c),u.mul(i.w).mul(c));return s.mul(h).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=Qv){const{skinIndexNode:n,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:s}=this,a=e.element(n.x),o=e.element(n.y),l=e.element(n.z),u=e.element(n.w);let c=ug(i.x.mul(a),i.y.mul(o),i.z.mul(l),i.w.mul(u));return c=s.mul(c).mul(r),c.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=by("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,jv)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===Wp(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&jv.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(Hv.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();Qv.assign(t),e.hasGeometryAttribute("tangent")&&Ey.assign(t)}}generate(e,t){if("void"!==t)return Hv.build(e,t)}update(e){const t=(this.useReference?e.object:this.skinnedMesh).skeleton;Dx.get(t)!==e.frameId&&(Dx.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}class Lx extends sf{static get type(){return"LoopNode"}constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const n={};for(let e=0,t=this.params.length-1;eNumber(s)?">=":"<"));const c={start:r,end:s},h=c.start,d=c.end;let p="",f="",m="";u||(u="int"===o||"uint"===o?l.includes("<")?"++":"--":l.includes("<")?"+= 1.":"-= 1."),p+=e.getVar(o,a)+" = "+h,f+=a+" "+l+" "+d,m+=a+" "+u;const g=`for ( ${p}; ${f}; ${m} )`;e.addFlowCode((0===t?"\n":"")+e.tab+g+" {\n\n").addFlowTab()}const r=i.build(e,"void"),s=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+r);for(let t=0,n=this.params.length-1;tXf(new Lx($f(e,"int"))).append(),Ox=new WeakMap,Fx=new nn,Bx=Zf((({bufferMap:e,influence:t,stride:n,width:i,depth:r,offset:s})=>{const a=im(Mx).mul(n).add(s),o=a.div(i),l=a.sub(o.mul(i));return Sv(e,om(l,o)).depth(r).mul(t)}));class kx extends sf{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Cm(1),this.updateType=Kp}setup(e){const{geometry:t}=e,n=void 0!==t.morphAttributes.position,i=t.hasAttribute("normal")&&void 0!==t.morphAttributes.normal,r=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,s=void 0!==r?r.length:0,{texture:a,stride:o,size:l}=function(e){const t=void 0!==e.morphAttributes.position,n=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,r=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,s=void 0!==r?r.length:0;let a=Ox.get(e);if(void 0===a||a.count!==s){void 0!==a&&a.texture.dispose();const o=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],u=e.morphAttributes.color||[];let c=0;!0===t&&(c=1),!0===n&&(c=2),!0===i&&(c=3);let h=e.attributes.position.count*c,d=1;const p=4096;h>p&&(d=Math.ceil(h/p),h=p);const f=new Float32Array(h*d*4*s),m=new an(f,h,d,s);m.type=le,m.needsUpdate=!0;const g=4*c;for(let v=0;v{const t=nm(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Sv(this.mesh.morphTexture,om(im(e).add(1),im(Ex))).r):t.assign(xy("morphTargetInfluences","float").element(e).toVar()),!0===n&&Hv.addAssign(Bx({bufferMap:a,influence:t,stride:o,width:u,depth:e,offset:im(0)})),!0===i&&Qv.addAssign(Bx({bufferMap:a,influence:t,stride:o,width:u,depth:e,offset:im(1)}))}))}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce(((e,t)=>e+t),0)}}const zx=Yf(kx);class Gx extends sf{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class Vx extends Gx{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Hx extends I_{static get type(){return"LightingContextNode"}constructor(e,t=null,n=null,i=null){super(e),this.lightingModel=t,this.backdropNode=n,this.backdropAlphaNode=i,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,n={directDiffuse:cm().toVar("directDiffuse"),directSpecular:cm().toVar("directSpecular"),indirectDiffuse:cm().toVar("indirectDiffuse"),indirectSpecular:cm().toVar("indirectSpecular")};return{radiance:cm().toVar("radiance"),irradiance:cm().toVar("irradiance"),iblIrradiance:cm().toVar("iblIrradiance"),ambientOcclusion:nm(1).toVar("ambientOcclusion"),reflectedLight:n,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const jx=Yf(Hx);class Wx extends Gx{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}let Xx,qx;class $x extends sf{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===$x.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=qp;return this.scope!==$x.SIZE&&this.scope!==$x.VIEWPORT||(e=Yp),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===$x.VIEWPORT?null!==t?qx.copy(t.viewport):(e.getViewport(qx),qx.multiplyScalar(e.getPixelRatio())):null!==t?(Xx.width=t.width,Xx.height=t.height):e.getDrawingBufferSize(Xx)}setup(){const e=this.scope;let t=null;return t=e===$x.SIZE?Cm(Xx||(Xx=new It)):e===$x.VIEWPORT?Cm(qx||(qx=new nn)):am(Zx.div(Kx)),t}generate(e){if(this.scope===$x.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const n=e.getNodeProperties(Kx).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${n}.y - ${t}.y )`}return t}return super.generate(e)}}$x.COORDINATE="coordinate",$x.VIEWPORT="viewport",$x.SIZE="size",$x.UV="uv";const Yx=Kf($x,$x.UV),Kx=Kf($x,$x.SIZE),Zx=Kf($x,$x.COORDINATE),Qx=Kf($x,$x.VIEWPORT);Qx.zw,Qx.xy;const Jx=new It;class eb extends xv{static get type(){return"ViewportTextureNode"}constructor(e=Yx,t=null,n=null){null===n&&((n=new is).minFilter=te),super(n,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=$p}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(Jx);const n=this.value;n.image.width===Jx.width&&n.image.height===Jx.height||(n.image.width=Jx.width,n.image.height=Jx.height,n.needsUpdate=!0);const i=n.generateMipmaps;n.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(n),n.generateMipmaps=i}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const tb=Yf(eb,null,null,{generateMipmaps:!0});let nb=null;class ib extends eb{static get type(){return"ViewportDepthTextureNode"}constructor(e=Yx,t=null){null===nb&&(nb=new rs),super(e,t,nb)}}const rb=Yf(ib);class sb extends sf{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===sb.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,n=this.valueNode;let i=null;if(t===sb.DEPTH_BASE)null!==n&&(i=cb().assign(n));else if(t===sb.DEPTH)i=e.isPerspectiveCamera?ob(qv.z,Cv,Nv):ab(qv.z,Cv,Nv);else if(t===sb.LINEAR_DEPTH)if(null!==n)if(e.isPerspectiveCamera){const e=lb(n,Cv,Nv);i=ab(e,Cv,Nv)}else i=n;else i=ab(qv.z,Cv,Nv);return i}}sb.DEPTH_BASE="depthBase",sb.DEPTH="depth",sb.LINEAR_DEPTH="linearDepth";const ab=(e,t,n)=>e.add(t).div(t.sub(n)),ob=(e,t,n)=>t.add(e).mul(n).div(n.sub(t).mul(e)),lb=(e,t,n)=>t.mul(n).div(n.sub(t).mul(e).sub(n)),ub=(e,t,n)=>{t=t.max(1e-6).toVar();const i=zg(e.negate().div(t)),r=zg(n.div(t));return i.div(r)},cb=Yf(sb,sb.DEPTH_BASE),hb=Kf(sb,sb.DEPTH);sb.LINEAR_DEPTH;rb(),hb.assign=e=>cb(e);const db=Yf(class extends sf{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}});class pb extends sf{static get type(){return"ClippingNode"}constructor(e=pb.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:n,unionPlanes:i}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===pb.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(n,i):this.scope===pb.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(n,i)}setupAlphaToCoverage(e,t){return Zf((()=>{const n=nm().toVar("distanceToPlane"),i=nm().toVar("distanceToGradient"),r=nm(1).toVar("clipOpacity"),s=t.length;if(!1===this.hardwareClipping&&s>0){const e=Av(t);Ix(s,(({i:t})=>{const s=e.element(t);n.assign(qv.dot(s.xyz).negate().add(s.w)),i.assign(n.fwidth().div(2)),r.mulAssign(N_(i.negate(),i,n))}))}const a=e.length;if(a>0){const t=Av(e),s=nm(1).toVar("intersectionClipOpacity");Ix(a,(({i:e})=>{const r=t.element(e);n.assign(qv.dot(r.xyz).negate().add(r.w)),i.assign(n.fwidth().div(2)),s.mulAssign(N_(i.negate(),i,n).oneMinus())})),r.mulAssign(s.oneMinus())}Um.a.mulAssign(r),Um.a.equal(0).discard()}))()}setupDefault(e,t){return Zf((()=>{const n=t.length;if(!1===this.hardwareClipping&&n>0){const e=Av(t);Ix(n,(({i:t})=>{const n=e.element(t);qv.dot(n.xyz).greaterThan(n.w).discard()}))}const i=e.length;if(i>0){const t=Av(e),n=sm(!0).toVar("clipped");Ix(i,(({i:e})=>{const i=t.element(e);n.assign(qv.dot(i.xyz).greaterThan(i.w).and(n))})),n.discard()}}))()}setupHardwareClipping(e,t){const n=e.length;return t.enableHardwareClipping(n),Zf((()=>{const i=Av(e),r=db(t.getClipDistance());Ix(n,(({i:e})=>{const t=i.element(e),n=qv.dot(t.xyz).sub(t.w).negate();r.element(e).assign(n)}))}))()}}pb.ALPHA_TO_COVERAGE="alphaToCoverage",pb.DEFAULT="default",pb.HARDWARE="hardware";const fb=Zf((([e])=>Xg(hg(1e4,qg(hg(17,e.x).add(hg(.1,e.y)))).mul(ug(.1,Jg(qg(hg(13,e.y).add(e.x)))))))),mb=Zf((([e])=>fb(am(fb(e.xy),e.z)))),gb=Zf((([e])=>{const t=p_(t_(r_(e.xyz)),t_(s_(e.xyz))),n=nm(1).div(nm(.05).mul(t)).toVar("pixScale"),i=am(Bg(Hg(zg(n))),Bg(jg(zg(n)))),r=am(mb(Hg(i.x.mul(e.xyz))),mb(Hg(i.y.mul(e.xyz)))),s=Xg(zg(n)),a=ug(hg(s.oneMinus(),r.x),hg(s,r.y)),o=d_(s,s.oneMinus()),l=cm(a.mul(a).div(hg(2,o).mul(cg(1,o))),a.sub(hg(.5,o)).div(cg(1,o)),cg(1,cg(1,a).mul(cg(1,a)).div(hg(2,o).mul(cg(1,o))))),u=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(l.x,l.y),l.z);return R_(u,1e-6,1)})).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class _b extends Li{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.shadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null}customProgramCacheKey(){return this.type+kp(this)}build(e){this.setup(e)}setupObserver(e){return new Ip(e)}setup(e){e.context.setupNormal=()=>this.setupNormal(e),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,n=t.getRenderTarget();e.addStack();const i=this.vertexNode||this.setupVertex(e);let r;e.stack.outputNode=i,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const s=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==n?!0===n.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const i=this.setupLighting(e);null!==s&&e.stack.add(s);const a=fm(i,Um.a).max(0);if(r=this.setupOutput(e,a),Zm.assign(r),null!==this.outputNode&&(r=this.outputNode),null!==n){const e=t.getMRT(),n=this.mrtNode;null!==e?(r=e,null!==n&&(r=e.merge(n))):null!==n&&(r=n)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=fm(t)),r=this.setupOutput(e,t)}e.stack.outputNode=r,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:n}=e.clippingContext;let i=null;if(t.length>0||n.length>0){const t=e.renderer.samples;this.alphaToCoverage&&t>1?i=Xf(new pb(pb.ALPHA_TO_COVERAGE)):e.stack.add(Xf(new pb))}return i}setupHardwareClipping(e){if(this.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.add(Xf(new pb(pb.HARDWARE))),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:n}=e;let i=this.depthNode;if(null===i){const e=t.getMRT();e&&e.has("depth")?i=e.get("depth"):!0===t.logarithmicDepthBuffer&&(i=n.isPerspectiveCamera?ub(qv.z,Cv,Nv):ab(qv.z,Cv,Nv))}null!==i&&hb.assign(i).append()}setupPositionView(){return zv.mul(Hv).xyz}setupModelViewProjection(){return Pv.mul(qv)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),Sx}setupPosition(e){const{object:t,geometry:n}=e;var i;if((n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&zx(t).append(),!0===t.isSkinnedMesh&&(i=t,Xf(new Ux(i,!0))).append(),this.displacementMap){const e=Ty("displacementMap","texture"),t=Ty("displacementScale","float"),n=Ty("displacementBias","float");Hv.addAssign(Qv.normalize().mul(e.x.mul(t).add(n)))}return t.isBatchedMesh&&Px(t).append(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&Cx(t).append(),null!==this.positionNode&&Hv.assign(this.positionNode.context({isPositionNodeInput:!0})),Hv}setupDiffuseColor({object:e,geometry:t}){let n=this.colorNode?fm(this.colorNode):zy;if(!0===this.vertexColors&&t.hasAttribute("color")&&(n=fm(n.xyz.mul(fv("color","vec3")),n.a)),e.instanceColor){n=Dm("vec3","vInstanceColor").mul(n)}if(e.isBatchedMesh&&e._colorsTexture){n=Dm("vec3","vBatchColor").mul(n)}Um.assign(n);const i=this.opacityNode?nm(this.opacityNode):Hy;if(Um.a.assign(Um.a.mul(i)),null!==this.alphaTestNode||this.alphaTest>0){const e=null!==this.alphaTestNode?nm(this.alphaTestNode):ky;Um.a.lessThanEqual(e).discard()}!0===this.alphaHash&&Um.a.lessThan(gb(Hv)).discard(),!1===this.transparent&&1===this.blending&&!1===this.alphaToCoverage&&Um.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?cm(0):Um.rgb}setupNormal(){return this.normalNode?cm(this.normalNode):Zy}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Ty("envMap","cubeTexture"):Ty("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Wx(yx)),t}setupLights(e){const t=[],n=this.setupEnvironment(e);n&&n.isLightingNode&&t.push(n);const i=this.setupLightMap(e);if(i&&i.isLightingNode&&t.push(i),null!==this.aoNode||e.material.aoMap){const e=null!==this.aoNode?this.aoNode:xx;t.push(new Vx(e))}let r=this.lightsNode||e.lightsNode;return t.length>0&&(r=e.renderer.lighting.createNode([...r.getLights(),...t])),r}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:n,backdropAlphaNode:i,emissiveNode:r}=this,s=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let a=this.setupOutgoingLight(e);if(s&&s.getScope().hasLights){const t=this.setupLightingModel(e)||null;a=jx(s,t,n,i)}else null!==n&&(a=cm(null!==i?A_(a,n,i):n));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(Lm.assign(cm(r||Vy)),a=a.add(Lm)),a}setupFog(e,t){const n=e.fogNode;return n&&(Zm.assign(t),t=fm(n)),t}setupOutput(e,t){return!0===this.fog&&(t=this.setupFog(e,t)),t}setDefaultValues(e){for(const t in e){const n=e[t];void 0===this[t]&&(this[t]=n,n&&n.clone&&(this[t]=n.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const e in t)void 0===Object.getOwnPropertyDescriptor(this.constructor.prototype,e)&&void 0!==t[e].get&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{},nodes:{}});const n=Li.prototype.toJSON.call(this,e),i=zp(this);n.inputNodes={};for(const{property:t,childNode:r}of i)n.inputNodes[t]=r.toJSON(e).uuid;function r(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(t){const t=r(e.textures),i=r(e.images),s=r(e.nodes);t.length>0&&(n.textures=t),i.length>0&&(n.images=i),s.length>0&&(n.nodes=s)}return n}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.shadowPositionNode=e.shadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}const vb=new qr;class yb extends _b{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(vb),this.setValues(e)}}const xb=new Us;class bb extends _b{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(xb),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?nm(this.offsetNode):gx,t=this.dashScaleNode?nm(this.dashScaleNode):px,n=this.dashSizeNode?nm(this.dashSizeNode):fx,i=this.gapSizeNode?nm(this.gapSizeNode):mx;Qm.assign(n),Jm.assign(i);const r=z_(fv("lineDistance").mul(t));(e?r.add(e):r).mod(Qm.add(Jm)).greaterThan(Qm).discard()}}const Sb=new Rs;class Tb extends _b{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(Sb),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?nm(this.opacityNode):Hy;Um.assign(X_(fm(Xf(ny).mul(.5).add(.5),e),st))}}class Mb extends lf{static get type(){return"EquirectUVNode"}constructor(e=Xv){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),n=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return am(t,n)}}const Eb=Yf(Mb);class wb extends Cr{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const n=t.minFilter,i=t.generateMipmaps;t.generateMipmaps=!0,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;const r=new mr(5,5,5),s=Eb(Xv),a=new _b;a.colorNode=bv(t,s,0),a.side=1,a.blending=0;const o=new pr(r,a),l=new Ur;l.add(o),t.minFilter===te&&(t.minFilter=J);const u=new Ar(1,10,this),c=e.getMRT();return e.setMRT(null),u.update(e,l),e.setMRT(c),t.minFilter=n,t.currentGenerateMipmaps=i,o.geometry.dispose(),o.material.dispose(),this}}const Ab=new WeakMap;class Rb extends lf{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=_y();const t=new Rr;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Yp}updateBefore(e){const{renderer:t,material:n}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const e=i.isTextureNode?i.value:n[i.property];if(e&&e.isTexture){const n=e.mapping;if(n===j||n===W){if(Ab.has(e)){const t=Ab.get(e);Nb(t,e.mapping),this._cubeTexture=t}else{const n=e.image;if(function(e){return null!=e&&e.height>0}(n)){const i=new wb(n.height);i.fromEquirectangularTexture(t,e),Nb(i.texture,e.mapping),this._cubeTexture=i.texture,Ab.set(e,i.texture),e.addEventListener("dispose",Cb)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function Cb(e){const t=e.target;t.removeEventListener("dispose",Cb);const n=Ab.get(t);void 0!==n&&(Ab.delete(t),n.dispose())}function Nb(e,t){t===j?e.mapping=V:t===W&&(e.mapping=H)}const Pb=Yf(Rb);class Db extends Gx{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Pb(this.envNode)}}class Ub extends Gx{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=nm(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class Lb{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Ib extends Lb{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,n=e.reflectedLight,i=e.irradianceLightMap;n.indirectDiffuse.assign(fm(0)),i?n.indirectDiffuse.addAssign(i):n.indirectDiffuse.addAssign(fm(1,1,1,0)),n.indirectDiffuse.mulAssign(t),n.indirectDiffuse.mulAssign(Um.rgb)}finish(e){const{material:t,context:n}=e,i=n.outgoingLight,r=e.context.environment;if(r)switch(t.combine){case 0:i.rgb.assign(A_(i.rgb,i.rgb.mul(r.rgb),qy.mul($y)));break;case 1:i.rgb.assign(A_(i.rgb,r.rgb,qy.mul($y)));break;case 2:i.rgb.addAssign(r.rgb.mul(qy.mul($y)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",t.combine)}}}const Ob=new Ii;class Fb extends _b{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Ob),this.setValues(e)}setupNormal(){return ey}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Db(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Ub(yx)),t}setupOutgoingLight(){return Um.rgb}setupLightingModel(){return new Ib}}const Bb=Zf((({f0:e,f90:t,dotVH:n})=>{const i=n.mul(-5.55473).sub(6.98316).mul(n).exp2();return e.mul(i.oneMinus()).add(t.mul(i))})),kb=Zf((e=>e.diffuseColor.mul(1/Math.PI))),zb=Zf((({dotNH:e})=>Km.mul(nm(.5)).add(1).mul(nm(1/Math.PI)).mul(e.pow(Km)))),Gb=Zf((({lightDirection:e})=>{const t=e.add($v).normalize(),n=ny.dot(t).clamp(),i=$v.dot(t).clamp(),r=Bb({f0:$m,f90:1,dotVH:i}),s=nm(.25),a=zb({dotNH:n});return r.mul(s).mul(a)}));class Vb extends Ib{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const i=ny.dot(e).clamp().mul(t);n.directDiffuse.addAssign(i.mul(kb({diffuseColor:Um.rgb}))),!0===this.specular&&n.directSpecular.addAssign(i.mul(Gb({lightDirection:e})).mul(qy))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(n.mul(kb({diffuseColor:Um}))),i.indirectDiffuse.mulAssign(t)}}const Hb=new Cs;class jb extends _b{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Hb),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Db(t):null}setupLightingModel(){return new Vb(!1)}}const Wb=new ws;class Xb extends _b{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Wb),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Db(t):null}setupLightingModel(){return new Vb}setupVariants(){const e=(this.shininessNode?nm(this.shininessNode):Gy).max(1e-4);Km.assign(e);const t=this.specularNode||jy;$m.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const qb=Zf((e=>{if(!1===e.geometry.hasAttribute("normal"))return nm(0);const t=ey.dFdx().abs().max(ey.dFdy().abs());return t.x.max(t.y).max(t.z)})),$b=Zf((e=>{const{roughness:t}=e,n=qb();let i=t.max(.0525);return i=i.add(n),i=i.min(1),i})),Yb=Zf((({alpha:e,dotNL:t,dotNV:n})=>{const i=e.pow2(),r=t.mul(i.add(i.oneMinus().mul(n.pow2())).sqrt()),s=n.mul(i.add(i.oneMinus().mul(t.pow2())).sqrt());return dg(.5,r.add(s).max(Pg))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),Kb=Zf((({alphaT:e,alphaB:t,dotTV:n,dotBV:i,dotTL:r,dotBL:s,dotNV:a,dotNL:o})=>{const l=o.mul(cm(e.mul(n),t.mul(i),a).length()),u=a.mul(cm(e.mul(r),t.mul(s),o).length());return dg(.5,l.add(u)).saturate()})).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),Zb=Zf((({alpha:e,dotNH:t})=>{const n=e.pow2(),i=t.pow2().mul(n.oneMinus()).oneMinus();return n.div(i.pow2()).mul(1/Math.PI)})).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),Qb=nm(1/Math.PI),Jb=Zf((({alphaT:e,alphaB:t,dotNH:n,dotTH:i,dotBH:r})=>{const s=e.mul(t),a=cm(t.mul(i),e.mul(r),s.mul(n)),o=a.dot(a),l=s.div(o);return Qb.mul(s.mul(l.pow2()))})).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),eS=Zf((e=>{const{lightDirection:t,f0:n,f90:i,roughness:r,f:s,USE_IRIDESCENCE:a,USE_ANISOTROPY:o}=e,l=e.normalView||ny,u=r.pow2(),c=t.add($v).normalize(),h=l.dot(t).clamp(),d=l.dot($v).clamp(),p=l.dot(c).clamp(),f=$v.dot(c).clamp();let m,g,_=Bb({f0:n,f90:i,dotVH:f});if(jf(a)&&(_=Gm.mix(_,s)),jf(o)){const e=Xm.dot(t),n=Xm.dot($v),i=Xm.dot(c),r=qm.dot(t),s=qm.dot($v),a=qm.dot(c);m=Kb({alphaT:jm,alphaB:u,dotTV:n,dotBV:s,dotTL:e,dotBL:r,dotNV:d,dotNL:h}),g=Jb({alphaT:jm,alphaB:u,dotNH:p,dotTH:i,dotBH:a})}else m=Yb({alpha:u,dotNL:h,dotNV:d}),g=Zb({alpha:u,dotNH:p});return _.mul(m).mul(g)})),tS=Zf((({roughness:e,dotNV:t})=>{const n=fm(-1,-.0275,-.572,.022),i=fm(1,.0425,1.04,-.04),r=e.mul(n).add(i),s=r.x.mul(r.x).min(t.mul(-9.28).exp2()).mul(r.x).add(r.y);return am(-1.04,1.04).mul(s).add(r.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),nS=Zf((e=>{const{dotNV:t,specularColor:n,specularF90:i,roughness:r}=e,s=tS({dotNV:t,roughness:r});return n.mul(s.x).add(i.mul(s.y))})),iS=Zf((({f:e,f90:t,dotVH:n})=>{const i=n.oneMinus().saturate(),r=i.mul(i),s=i.mul(r,r).clamp(0,.9999);return e.sub(cm(t).mul(s)).div(s.oneMinus())})).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),rS=Zf((({roughness:e,dotNH:t})=>{const n=e.pow2(),i=nm(1).div(n),r=t.pow2().oneMinus().max(.0078125);return nm(2).add(i).mul(r.pow(i.mul(.5))).div(2*Math.PI)})).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),sS=Zf((({dotNV:e,dotNL:t})=>nm(1).div(nm(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),aS=Zf((({lightDirection:e})=>{const t=e.add($v).normalize(),n=ny.dot(e).clamp(),i=ny.dot($v).clamp(),r=ny.dot(t).clamp(),s=rS({roughness:zm,dotNH:r}),a=sS({dotNV:i,dotNL:n});return km.mul(s).mul(a)})),oS=Zf((({N:e,V:t,roughness:n})=>{const i=e.dot(t).saturate(),r=am(n,i.oneMinus().sqrt());return r.assign(r.mul(.984375).add(.0078125)),r})).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),lS=Zf((({f:e})=>{const t=e.length();return p_(t.mul(t).add(e.z).div(t.add(1)),0)})).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),uS=Zf((({v1:e,v2:t})=>{const n=e.dot(t),i=n.abs().toVar(),r=i.mul(.0145206).add(.4965155).mul(i).add(.8543985).toVar(),s=i.add(4.1616724).mul(i).add(3.417594).toVar(),a=r.div(s),o=n.greaterThan(0).select(a,p_(n.mul(n).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(a));return e.cross(t).mul(o)})).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),cS=Zf((({N:e,V:t,P:n,mInv:i,p0:r,p1:s,p2:a,p3:o})=>{const l=s.sub(r).toVar(),u=o.sub(r).toVar(),c=l.cross(u),h=cm().toVar();return em(c.dot(n.sub(r)).greaterThanEqual(0),(()=>{const l=t.sub(e.mul(t.dot(e))).normalize(),u=e.cross(l).negate(),c=i.mul(ym(l,u,e).transpose()).toVar(),d=c.mul(r.sub(n)).normalize().toVar(),p=c.mul(s.sub(n)).normalize().toVar(),f=c.mul(a.sub(n)).normalize().toVar(),m=c.mul(o.sub(n)).normalize().toVar(),g=cm(0).toVar();g.addAssign(uS({v1:d,v2:p})),g.addAssign(uS({v1:p,v2:f})),g.addAssign(uS({v1:f,v2:m})),g.addAssign(uS({v1:m,v2:d})),h.assign(cm(lS({f:g})))})),h})).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),hS=1/6,dS=e=>hg(hS,hg(e,hg(e,e.negate().add(3)).sub(3)).add(1)),pS=e=>hg(hS,hg(e,hg(e,hg(3,e).sub(6))).add(4)),fS=e=>hg(hS,hg(e,hg(e,hg(-3,e).add(3)).add(3)).add(1)),mS=e=>hg(hS,b_(e,3)),gS=e=>dS(e).add(pS(e)),_S=e=>fS(e).add(mS(e)),vS=e=>ug(-1,pS(e).div(dS(e).add(pS(e)))),yS=e=>ug(1,mS(e).div(fS(e).add(mS(e)))),xS=(e,t,n)=>{const i=e.uvNode,r=hg(i,t.zw).add(.5),s=Hg(r),a=Xg(r),o=gS(a.x),l=_S(a.x),u=vS(a.x),c=yS(a.x),h=vS(a.y),d=yS(a.y),p=am(s.x.add(u),s.y.add(h)).sub(.5).mul(t.xy),f=am(s.x.add(c),s.y.add(h)).sub(.5).mul(t.xy),m=am(s.x.add(u),s.y.add(d)).sub(.5).mul(t.xy),g=am(s.x.add(c),s.y.add(d)).sub(.5).mul(t.xy),_=gS(a.y).mul(ug(o.mul(e.sample(p).level(n)),l.mul(e.sample(f).level(n)))),v=_S(a.y).mul(ug(o.mul(e.sample(m).level(n)),l.mul(e.sample(g).level(n))));return _.add(v)},bS=Zf((([e,t=nm(3)])=>{const n=am(e.size(im(t))),i=am(e.size(im(t.add(1)))),r=dg(1,n),s=dg(1,i),a=xS(e,fm(r,n),Hg(t)),o=xS(e,fm(s,i),jg(t));return Xg(t).mix(a,o)})),SS=Zf((([e,t,n,i,r])=>{const s=cm(C_(t.negate(),Wg(e),dg(1,i))),a=cm(t_(r[0].xyz),t_(r[1].xyz),t_(r[2].xyz));return Wg(s).mul(n.mul(a))})).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),TS=Zf((([e,t])=>e.mul(R_(t.mul(2).sub(2),0,1)))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),MS=tb(),ES=tb(),wS=Zf((([e,t,n],{material:i})=>{const r=(1===i.side?MS:ES).sample(e),s=zg(Kx.x).mul(TS(t,n));return bS(r,s)})),AS=Zf((([e,t,n])=>(em(n.notEqual(0),(()=>{const i=kg(t).negate().div(n);return Fg(i.negate().mul(e))})),cm(1)))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),RS=Zf((([e,t,n,i,r,s,a,o,l,u,c,h,d,p,f])=>{let m,g;if(f){m=fm().toVar(),g=cm().toVar();const r=c.sub(1).mul(f.mul(.025)),s=cm(c.sub(r),c,c.add(r));Ix({start:0,end:3},(({i:r})=>{const c=s.element(r),f=SS(e,t,h,c,o),_=a.add(f),v=u.mul(l.mul(fm(_,1))),y=am(v.xy.div(v.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(am(y.x,y.y.oneMinus()));const x=wS(y,n,c);m.element(r).assign(x.element(r)),m.a.addAssign(x.a),g.element(r).assign(i.element(r).mul(AS(t_(f),d,p).element(r)))})),m.a.divAssign(3)}else{const r=SS(e,t,h,c,o),s=a.add(r),f=u.mul(l.mul(fm(s,1))),_=am(f.xy.div(f.w)).toVar();_.addAssign(1),_.divAssign(2),_.assign(am(_.x,_.y.oneMinus())),m=wS(_,n,c),g=i.mul(AS(t_(r),d,p))}const _=g.rgb.mul(m.rgb),v=e.dot(t).clamp(),y=cm(nS({dotNV:v,specularColor:r,specularF90:s,roughness:n})),x=g.r.add(g.g,g.b).div(3);return fm(y.oneMinus().mul(_),m.a.oneMinus().mul(x).oneMinus())})),CS=ym(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),NS=(e,t)=>e.sub(t).div(e.add(t)).pow2(),PS=Zf((({outsideIOR:e,eta2:t,cosTheta1:n,thinFilmThickness:i,baseF0:r})=>{const s=A_(e,t,N_(0,.03,i)),a=e.div(s).pow2().mul(n.pow2().oneMinus()).oneMinus();em(a.lessThan(0),(()=>cm(1)));const o=a.sqrt(),l=NS(s,e),u=Bb({f0:l,f90:1,dotVH:n}),c=u.oneMinus(),h=s.lessThan(e).select(Math.PI,0),d=nm(Math.PI).sub(h),p=(e=>{const t=e.sqrt();return cm(1).add(t).div(cm(1).sub(t))})(r.clamp(0,.9999)),f=NS(p,s.toVec3()),m=Bb({f0:f,f90:1,dotVH:o}),g=cm(p.x.lessThan(s).select(Math.PI,0),p.y.lessThan(s).select(Math.PI,0),p.z.lessThan(s).select(Math.PI,0)),_=s.mul(i,o,2),v=cm(d).add(g),y=u.mul(m).clamp(1e-5,.9999),x=y.sqrt(),b=c.pow2().mul(m).div(cm(1).sub(y)),S=u.add(b).toVar(),T=b.sub(c).toVar();return Ix({start:1,end:2,condition:"<=",name:"m"},(({m:e})=>{T.mulAssign(x);const t=((e,t)=>{const n=e.mul(2*Math.PI*1e-9),i=cm(54856e-17,44201e-17,52481e-17),r=cm(1681e3,1795300,2208400),s=cm(43278e5,93046e5,66121e5),a=nm(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(n.mul(2239900).add(t.x).cos()).mul(n.pow2().mul(-45282e5).exp());let o=i.mul(s.mul(2*Math.PI).sqrt()).mul(r.mul(n).add(t).cos()).mul(n.pow2().negate().mul(s).exp());return o=cm(o.x.add(a),o.y,o.z).div(1.0685e-7),CS.mul(o)})(nm(e).mul(_),nm(e).mul(v)).mul(2);S.addAssign(T.mul(t))})),S.max(cm(0))})).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),DS=Zf((({normal:e,viewDir:t,roughness:n})=>{const i=e.dot(t).saturate(),r=n.pow2(),s=L_(n.lessThan(.25),nm(-339.2).mul(r).add(nm(161.4).mul(n)).sub(25.9),nm(-8.48).mul(r).add(nm(14.3).mul(n)).sub(9.95)),a=L_(n.lessThan(.25),nm(44).mul(r).sub(nm(23.7).mul(n)).add(3.26),nm(1.97).mul(r).sub(nm(3.27).mul(n)).add(.72));return L_(n.lessThan(.25),0,nm(.1).mul(n).sub(.025)).add(s.mul(i).add(a).exp()).mul(1/Math.PI).saturate()})),US=cm(.04),LS=nm(1);class IS extends Lb{constructor(e=!1,t=!1,n=!1,i=!1,r=!1,s=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=n,this.anisotropy=i,this.transmission=r,this.dispersion=s,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=cm().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=cm().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=cm().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=cm().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=cm().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=ny.dot($v).clamp();this.iridescenceFresnel=PS({outsideIOR:nm(1),eta2:Vm,cosTheta1:e,thinFilmThickness:Hm,baseF0:$m}),this.iridescenceF0=iS({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=Wv,n=Uv.sub(Wv).normalize(),i=iy,r=e.context;r.backdrop=RS(i,n,Im,Um,$m,Ym,t,Bv,Dv,Pv,eg,ng,rg,ig,this.dispersion?sg:null),r.backdropAlpha=tg,Um.a.mulAssign(A_(1,r.backdrop.a,tg))}super.start(e)}computeMultiscattering(e,t,n){const i=ny.dot($v).clamp(),r=tS({roughness:Im,dotNV:i}),s=(this.iridescenceF0?Gm.mix($m,this.iridescenceF0):$m).mul(r.x).add(n.mul(r.y)),a=r.x.add(r.y).oneMinus(),o=$m.add($m.oneMinus().mul(.047619)),l=s.mul(o).div(a.mul(o).oneMinus());e.addAssign(s),t.addAssign(l.mul(a))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const i=ny.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(i.mul(aS({lightDirection:e}))),!0===this.clearcoat){const n=ry.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(n.mul(eS({lightDirection:e,f0:US,f90:LS,roughness:Bm,normalView:ry})))}n.directDiffuse.addAssign(i.mul(kb({diffuseColor:Um.rgb}))),n.directSpecular.addAssign(i.mul(eS({lightDirection:e,f0:$m,f90:1,roughness:Im,iridescence:this.iridescence,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:n,halfHeight:i,reflectedLight:r,ltc_1:s,ltc_2:a}){const o=t.add(n).sub(i),l=t.sub(n).sub(i),u=t.sub(n).add(i),c=t.add(n).add(i),h=ny,d=$v,p=qv.toVar(),f=oS({N:h,V:d,roughness:Im}),m=s.sample(f).toVar(),g=a.sample(f).toVar(),_=ym(cm(m.x,0,m.y),cm(0,1,0),cm(m.z,0,m.w)).toVar(),v=$m.mul(g.x).add($m.oneMinus().mul(g.y)).toVar();r.directSpecular.addAssign(e.mul(v).mul(cS({N:h,V:d,P:p,mInv:_,p0:o,p1:l,p2:u,p3:c}))),r.directDiffuse.addAssign(e.mul(Um).mul(cS({N:h,V:d,P:p,mInv:ym(1,0,0,0,1,0,0,0,1),p0:o,p1:l,p2:u,p3:c})))}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:n}=e.context;n.indirectDiffuse.addAssign(t.mul(kb({diffuseColor:Um})))}indirectSpecular(e){const{radiance:t,iblIrradiance:n,reflectedLight:i}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(n.mul(km,DS({normal:ny,viewDir:$v,roughness:zm}))),!0===this.clearcoat){const e=ry.dot($v).clamp(),t=nS({dotNV:e,specularColor:US,specularF90:LS,roughness:Bm});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=cm().toVar("singleScattering"),s=cm().toVar("multiScattering"),a=n.mul(1/Math.PI);this.computeMultiscattering(r,s,Ym);const o=r.add(s),l=Um.mul(o.r.max(o.g).max(o.b).oneMinus());i.indirectSpecular.addAssign(t.mul(r)),i.indirectSpecular.addAssign(s.mul(a)),i.indirectDiffuse.addAssign(l.mul(a))}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:n}=e.context,i=ny.dot($v).clamp().add(t),r=Im.mul(-16).oneMinus().negate().exp2(),s=t.sub(i.pow(r).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),n.indirectDiffuse.mulAssign(t),n.indirectSpecular.mulAssign(s)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=ry.dot($v).clamp(),n=Bb({dotVH:e,f0:US,f90:LS}),i=t.mul(Fm.mul(n).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Fm));t.assign(i)}if(!0===this.sheen){const e=km.r.max(km.g).max(km.b).mul(.157).oneMinus(),n=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(n)}}}const OS=nm(1),FS=nm(-2),BS=nm(.8),kS=nm(-1),zS=nm(.4),GS=nm(2),VS=nm(.305),HS=nm(3),jS=nm(.21),WS=nm(4),XS=nm(4),qS=nm(16),$S=Zf((([e])=>{const t=cm(Jg(e)).toVar(),n=nm(-1).toVar();return em(t.x.greaterThan(t.z),(()=>{em(t.x.greaterThan(t.y),(()=>{n.assign(L_(e.x.greaterThan(0),0,3))})).Else((()=>{n.assign(L_(e.y.greaterThan(0),1,4))}))})).Else((()=>{em(t.z.greaterThan(t.y),(()=>{n.assign(L_(e.z.greaterThan(0),2,5))})).Else((()=>{n.assign(L_(e.y.greaterThan(0),1,4))}))})),n})).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),YS=Zf((([e,t])=>{const n=am().toVar();return em(t.equal(0),(()=>{n.assign(am(e.z,e.y).div(Jg(e.x)))})).ElseIf(t.equal(1),(()=>{n.assign(am(e.x.negate(),e.z.negate()).div(Jg(e.y)))})).ElseIf(t.equal(2),(()=>{n.assign(am(e.x.negate(),e.y).div(Jg(e.z)))})).ElseIf(t.equal(3),(()=>{n.assign(am(e.z.negate(),e.y).div(Jg(e.x)))})).ElseIf(t.equal(4),(()=>{n.assign(am(e.x.negate(),e.z).div(Jg(e.y)))})).Else((()=>{n.assign(am(e.x,e.y).div(Jg(e.z)))})),hg(.5,n.add(1))})).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),KS=Zf((([e])=>{const t=nm(0).toVar();return em(e.greaterThanEqual(BS),(()=>{t.assign(OS.sub(e).mul(kS.sub(FS)).div(OS.sub(BS)).add(FS))})).ElseIf(e.greaterThanEqual(zS),(()=>{t.assign(BS.sub(e).mul(GS.sub(kS)).div(BS.sub(zS)).add(kS))})).ElseIf(e.greaterThanEqual(VS),(()=>{t.assign(zS.sub(e).mul(HS.sub(GS)).div(zS.sub(VS)).add(GS))})).ElseIf(e.greaterThanEqual(jS),(()=>{t.assign(VS.sub(e).mul(WS.sub(HS)).div(VS.sub(jS)).add(HS))})).Else((()=>{t.assign(nm(-2).mul(zg(hg(1.16,e))))})),t})).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),ZS=Zf((([e,t])=>{const n=e.toVar();n.assign(hg(2,n).sub(1));const i=cm(n,1).toVar();return em(t.equal(0),(()=>{i.assign(i.zyx)})).ElseIf(t.equal(1),(()=>{i.assign(i.xzy),i.xz.mulAssign(-1)})).ElseIf(t.equal(2),(()=>{i.x.mulAssign(-1)})).ElseIf(t.equal(3),(()=>{i.assign(i.zyx),i.xz.mulAssign(-1)})).ElseIf(t.equal(4),(()=>{i.assign(i.xzy),i.xy.mulAssign(-1)})).ElseIf(t.equal(5),(()=>{i.z.mulAssign(-1)})),i})).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),QS=Zf((([e,t,n,i,r,s])=>{const a=nm(n),o=cm(t),l=R_(KS(a),FS,s),u=Xg(l),c=Hg(l),h=cm(JS(e,o,c,i,r,s)).toVar();return em(u.notEqual(0),(()=>{const t=cm(JS(e,o,c.add(1),i,r,s)).toVar();h.assign(A_(h,t,u))})),h})),JS=Zf((([e,t,n,i,r,s])=>{const a=nm(n).toVar(),o=cm(t),l=nm($S(o)).toVar(),u=nm(p_(XS.sub(a),0)).toVar();a.assign(p_(a,XS));const c=nm(Bg(a)).toVar(),h=am(YS(o,l).mul(c.sub(2)).add(1)).toVar();return em(l.greaterThan(2),(()=>{h.y.addAssign(c),l.subAssign(3)})),h.x.addAssign(l.mul(c)),h.x.addAssign(u.mul(hg(3,qS))),h.y.addAssign(hg(4,Bg(s).sub(c))),h.x.mulAssign(i),h.y.mulAssign(r),e.sample(h).grad(am(),am())})),eT=Zf((({envMap:e,mipInt:t,outputDirection:n,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const l=$g(i),u=n.mul(l).add(r.cross(n).mul(qg(i))).add(r.mul(r.dot(n).mul(l.oneMinus())));return JS(e,u,t,s,a,o)})),tT=Zf((({n:e,latitudinal:t,poleAxis:n,outputDirection:i,weights:r,samples:s,dTheta:a,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h})=>{const d=cm(L_(t,n,x_(n,i))).toVar();em(Ug(d.equals(cm(0))),(()=>{d.assign(cm(i.z,0,i.x.negate()))})),d.assign(Wg(d));const p=cm().toVar();return p.addAssign(r.element(0).mul(eT({theta:0,axis:d,outputDirection:i,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h}))),Ix({start:im(1),end:e},(({i:e})=>{em(e.greaterThanEqual(s),(()=>{hv("break").append()}));const t=nm(a.mul(nm(e))).toVar();p.addAssign(r.element(e).mul(eT({theta:t.mul(-1),axis:d,outputDirection:i,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h}))),p.addAssign(r.element(e).mul(eT({theta:t,axis:d,outputDirection:i,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h})))})),fm(p,1)})),nT=[.125,.215,.35,.446,.526,.582],iT=20,rT=new Qs(-1,1,1,-1,0,1),sT=new Er(90,1),aT=new Pi;let oT=null,lT=0,uT=0;const cT=(1+Math.sqrt(5))/2,hT=1/cT,dT=[new un(-cT,hT,0),new un(cT,hT,0),new un(-hT,0,cT),new un(hT,0,cT),new un(0,cT,-hT),new un(0,cT,hT),new un(-1,1,-1),new un(1,1,-1),new un(-1,1,1),new un(1,1,1)],pT=new un,fT=new WeakMap,mT=[3,1,5,0,4,2],gT=ZS(mv(),fv("faceIndex")).normalize(),_T=cm(gT.x,gT.y,gT.z);class vT{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,n=.1,i=100,r={}){const{size:s=256,position:a=pT,renderTarget:o=null}=r;if(this._setSize(s),!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.");const s=o||this._allocateTargets();return r.renderTarget=s,this.fromSceneAsync(e,t,n,i,r),s}oT=this._renderer.getRenderTarget(),lT=this._renderer.getActiveCubeFace(),uT=this._renderer.getActiveMipmapLevel();const l=o||this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(e,n,i,l,a),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}async fromSceneAsync(e,t=0,n=.1,i=100,r={}){return!1===this._hasInitialized&&await this._renderer.init(),this.fromScene(e,t,n,i,r)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead."),this._setSizeFromTexture(e);const n=t||this._allocateTargets();return this.fromEquirectangularAsync(e,n),n}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const n=t||this._allocateTargets();return this.fromCubemapAsync(e,t),n}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=ST(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=TT(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose(),null!==this._backgroundBox&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===V||e.mapping===H?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;ee-4?l=nT[o-e+4-1]:0===o&&(l=0),i.push(l);const u=1/(a-2),c=-u,h=1+u,d=[c,c,h,c,h,h,c,c,h,h,c,h],p=6,f=6,m=3,g=2,_=1,v=new Float32Array(m*f*p),y=new Float32Array(g*f*p),x=new Float32Array(_*f*p);for(let e=0;e2?0:-1,i=[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],r=mT[e];v.set(i,m*f*r),y.set(d,g*f*r);const s=[r,r,r,r,r,r];x.set(s,_*f*r)}const b=new tr;b.setAttribute("position",new Hi(v,m)),b.setAttribute("uv",new Hi(y,g)),b.setAttribute("faceIndex",new Hi(x,_)),t.push(b),r.push(new pr(b,null)),s>4&&s--}return{lodPlanes:t,sizeLods:n,sigmas:i,lodMeshes:r}}(i)),this._blurMaterial=function(e,t,n){const i=Av(new Array(iT).fill(0)),r=Cm(new un(0,1,0)),s=Cm(0),a=nm(iT),o=Cm(0),l=Cm(1),u=bv(null),c=Cm(0),h=nm(1/t),d=nm(1/n),p=nm(e),f={n:a,latitudinal:o,weights:i,poleAxis:r,outputDirection:_T,dTheta:s,samples:l,envMap:u,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},m=bT("blur");return m.fragmentNode=tT({...f,latitudinal:o.equal(1)}),fT.set(m,f),m}(i,e,t)}return i}async _compileMaterial(e){const t=new pr(this._lodPlanes[0],e);await this._renderer.compile(t,rT)}_sceneToCubeUV(e,t,n,i,r){const s=sT;s.near=t,s.far=n;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],l=this._renderer,u=l.autoClear;l.getClearColor(aT),l.autoClear=!1;let c=this._backgroundBox;if(null===c){const e=new Ii({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1});c=new pr(new mr,e)}let h=!1;const d=e.background;d?d.isColor&&(c.material.color.copy(d),e.background=null,h=!0):(c.material.color.copy(aT),h=!0),l.setRenderTarget(i),l.clear(),h&&l.render(c,s);for(let t=0;t<6;t++){const n=t%3;0===n?(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x+o[t],r.y,r.z)):1===n?(s.up.set(0,0,a[t]),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y+o[t],r.z)):(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y,r.z+o[t]));const u=this._cubeSize;xT(i,n*u,t>2?u:0,u,u),l.render(e,s)}l.autoClear=u,e.background=d}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===V||e.mapping===H;i?null===this._cubemapMaterial&&(this._cubemapMaterial=ST(e)):null===this._equirectMaterial&&(this._equirectMaterial=TT(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const s=this._lodMeshes[0];s.material=r;const a=this._cubeSize;xT(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,rT)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const i=this._lodPlanes.length;for(let t=1;tiT&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const m=[];let g=0;for(let e=0;e_-4?i-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(u,rT)}}function yT(e,t,n){const i=new rn(e,t,n);return i.texture.mapping=X,i.texture.name="PMREM.cubeUv",i.texture.isPMREMTexture=!0,i.scissorTest=!0,i}function xT(e,t,n,i,r){e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r)}function bT(e){const t=new _b;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function ST(e){const t=bT("cubemap");return t.fragmentNode=_y(e,_T),t}function TT(e){const t=bT("equirect");return t.fragmentNode=bv(e,Eb(_T),0),t}const MT=new WeakMap;function ET(e,t,n){const i=function(e){let t=MT.get(e);void 0===t&&(t=new WeakMap,MT.set(e,t));return t}(t);let r=i.get(e);if((void 0!==r?r.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const n=6;for(let i=0;i0}(t))return null;r=n.fromEquirectangular(e,r)}r.pmremVersion=e.pmremVersion,i.set(e,r)}return r.texture}class wT extends lf{static get type(){return"PMREMNode"}constructor(e,t=null,n=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=n,this._generator=null;const i=new tn;i.isRenderTargetTexture=!0,this._texture=bv(i),this._width=Cm(0),this._height=Cm(0),this._maxMip=Cm(0),this.updateBeforeType=Yp}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=function(e){const t=Math.log2(e)-2,n=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:n,maxMip:t}}(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const n=t?t.pmremVersion:-1,i=this._value;n!==i.pmremVersion&&(t=!0===i.isPMREMTexture?i:ET(i,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new vT(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this)),t=hy.mul(cm(t.x,t.y.negate(),t.z));let n=this.levelNode;return null===n&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),QS(this._texture,t,n,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const AT=Yf(wT),RT=new WeakMap;class CT extends Gx{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let n=this.envNode;if(n.isTextureNode||n.isMaterialReferenceNode){const e=n.isTextureNode?n.value:t[n.property];let i=RT.get(e);void 0===i&&(i=AT(e),RT.set(e,i)),n=i}const i=!0===t.useAnisotropy||t.anisotropy>0?Cy:ny,r=n.context(NT(Im,i)).mul(cy),s=n.context(PT(iy)).mul(Math.PI).mul(cy),a=sv(r),o=sv(s);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const l=e.context.lightingModel.clearcoatRadiance;if(l){const e=n.context(NT(Bm,ry)).mul(cy),t=sv(e);l.addAssign(t)}}}const NT=(e,t)=>{let n=null;return{getUV:()=>(null===n&&(n=$v.negate().reflect(t),n=e.mul(e).mix(n,t).normalize(),n=n.transformDirection(Dv)),n),getTextureLevel:()=>e}},PT=e=>({getUV:()=>e,getTextureLevel:()=>nm(1)}),DT=new Ms;class UT extends _b{static get type(){return"MeshStandardNodeMaterial"}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(DT),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new CT(t):null}setupLightingModel(){return new IS}setupSpecular(){const e=A_(cm(.04),Um.rgb,Om);$m.assign(e),Ym.assign(1)}setupVariants(){const e=this.metalnessNode?nm(this.metalnessNode):Ky;Om.assign(e);let t=this.roughnessNode?nm(this.roughnessNode):Yy;t=$b({roughness:t}),Im.assign(t),this.setupSpecular(),Um.assign(fm(Um.rgb.mul(e.oneMinus()),Um.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const LT=new Es;class IT extends UT{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(LT),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||null!==this.clearcoatNode}get useIridescence(){return this.iridescence>0||null!==this.iridescenceNode}get useSheen(){return this.sheen>0||null!==this.sheenNode}get useAnisotropy(){return this.anisotropy>0||null!==this.anisotropyNode}get useTransmission(){return this.transmission>0||null!==this.transmissionNode}get useDispersion(){return this.dispersion>0||null!==this.dispersionNode}setupSpecular(){const e=this.iorNode?nm(this.iorNode):cx;eg.assign(e),$m.assign(A_(d_(S_(eg.sub(1).div(eg.add(1))).mul(Xy),cm(1)).mul(Wy),Um.rgb,Om)),Ym.assign(A_(Wy,1,Om))}setupLightingModel(){return new IS(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?nm(this.clearcoatNode):Qy,t=this.clearcoatRoughnessNode?nm(this.clearcoatRoughnessNode):Jy;Fm.assign(e),Bm.assign($b({roughness:t}))}if(this.useSheen){const e=this.sheenNode?cm(this.sheenNode):nx,t=this.sheenRoughnessNode?nm(this.sheenRoughnessNode):ix;km.assign(e),zm.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?nm(this.iridescenceNode):sx,t=this.iridescenceIORNode?nm(this.iridescenceIORNode):ax,n=this.iridescenceThicknessNode?nm(this.iridescenceThicknessNode):ox;Gm.assign(e),Vm.assign(t),Hm.assign(n)}if(this.useAnisotropy){const e=(this.anisotropyNode?am(this.anisotropyNode):rx).toVar();Wm.assign(e.length()),em(Wm.equal(0),(()=>{e.assign(am(1,0))})).Else((()=>{e.divAssign(am(Wm)),Wm.assign(Wm.saturate())})),jm.assign(Wm.pow2().mix(Im.pow2(),1)),Xm.assign(Ry[0].mul(e.x).add(Ry[1].mul(e.y))),qm.assign(Ry[1].mul(e.x).sub(Ry[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?nm(this.transmissionNode):lx,t=this.thicknessNode?nm(this.thicknessNode):ux,n=this.attenuationDistanceNode?nm(this.attenuationDistanceNode):hx,i=this.attenuationColorNode?cm(this.attenuationColorNode):dx;if(tg.assign(e),ng.assign(t),ig.assign(n),rg.assign(i),this.useDispersion){const e=this.dispersionNode?nm(this.dispersionNode):vx;sg.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?cm(this.clearcoatNormalNode):ex}setup(e){e.context.setupClearcoatNormal=()=>this.setupClearcoatNormal(e),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}const OT=Zf((({normal:e,lightDirection:t,builder:n})=>{const i=e.dot(t),r=am(i.mul(.5).add(.5),0);if(n.material.gradientMap){const e=Ty("gradientMap","texture").context({getUV:()=>r});return cm(e.r)}{const e=r.fwidth().mul(.5);return A_(cm(.7),cm(1),N_(nm(.7).sub(e.x),nm(.7).add(e.x),r.x))}}));class FT extends Lb{direct({lightDirection:e,lightColor:t,reflectedLight:n},i){const r=OT({normal:Zv,lightDirection:e,builder:i}).mul(t);n.directDiffuse.addAssign(r.mul(kb({diffuseColor:Um.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(n.mul(kb({diffuseColor:Um}))),i.indirectDiffuse.mulAssign(t)}}const BT=new As;class kT extends _b{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(BT),this.setValues(e)}setupLightingModel(){return new FT}}class zT extends lf{static get type(){return"MatcapUVNode"}constructor(){super("vec2")}setup(){const e=cm($v.z,0,$v.x.negate()).normalize(),t=$v.cross(e);return am(e.dot(ny),t.dot(ny)).mul(.495).add(.5)}}const GT=Kf(zT),VT=new Ds;class HT extends _b{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(VT),this.setValues(e)}setupVariants(e){const t=GT;let n;n=e.material.matcap?Ty("matcap","texture").context({getUV:()=>t}):cm(A_(.2,.8,t.y)),Um.rgb.mulAssign(n.rgb)}}class jT extends lf{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:n}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),i=t.sin();return vm(e,i,i.negate(),e).mul(n)}{const e=t,i=xm(fm(1,0,0,0),fm(0,$g(e.x),qg(e.x).negate(),0),fm(0,qg(e.x),$g(e.x),0),fm(0,0,0,1)),r=xm(fm($g(e.y),0,qg(e.y),0),fm(0,1,0,0),fm(qg(e.y).negate(),0,$g(e.y),0),fm(0,0,0,1)),s=xm(fm($g(e.z),qg(e.z).negate(),0,0),fm(qg(e.z),$g(e.z),0,0),fm(0,0,1,0),fm(0,0,0,1));return i.mul(r).mul(s).mul(fm(n,1)).xyz}}}const WT=Yf(jT),XT=new Fr;class qT extends _b{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(XT),this.setValues(e)}setupPositionView(e){const{object:t,camera:n}=e,i=this.sizeAttenuation,{positionNode:r,rotationNode:s,scaleNode:a}=this,o=zv.mul(cm(r||0));let l=am(Bv[0].xyz.length(),Bv[1].xyz.length());if(null!==a&&(l=l.mul(am(a))),!1===i)if(n.isPerspectiveCamera)l=l.mul(o.z.negate());else{const e=nm(2).div(Pv.element(1).element(1));l=l.mul(e.mul(2))}let u=Vv.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,n)=>Xf(new $_(e,t,n)))("center","vec2",t);u=u.sub(e.sub(.5))}u=u.mul(l);const c=nm(s||tx),h=WT(u,c);return fm(o.xy.add(h),o.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const $T=new ns;class YT extends qT{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues($T),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return zv.mul(cm(e||Hv)).xyz}setupVertex(e){const t=super.setupVertex(e);if(!0!==e.material.isNodeMaterial)return t;const{rotationNode:n,scaleNode:i,sizeNode:r}=this,s=Vv.xy.toVar(),a=Qx.z.div(Qx.w);if(n&&n.isNode){const e=nm(n);s.assign(WT(s,e))}let o=null!==r?am(r):_x;return!0===this.sizeAttenuation&&(o=o.mul(o.div(qv.z.negate()))),i&&i.isNode&&(o=o.mul(am(i))),s.mulAssign(o.mul(2)),s.assign(s.div(Qx.z)),s.y.assign(s.y.mul(a)),s.assign(s.mul(t.w)),t.addAssign(fm(s,0,0)),t}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}class KT extends Lb{constructor(){super(),this.shadowNode=nm(1).toVar("shadowMask")}direct({shadowMask:e}){this.shadowNode.mulAssign(e)}finish(e){Um.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Um.rgb)}}const ZT=new Ts;class QT extends _b{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.setDefaultValues(ZT),this.setValues(e)}setupLightingModel(){return new KT}}Pm("vec3"),Pm("vec3"),Pm("vec3");class JT{constructor(e,t){this.nodes=e,this.info=t,this._context=self,this._animationLoop=null,this._requestId=null}start(){const e=(t,n)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,null!==this._animationLoop&&this._animationLoop(t,n)};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class eM{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;for(let n=0;n{this.dispose()},this.material.addEventListener("dispose",this.onMaterialDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return null!==this.clippingContext&&this.clippingContext.cacheKey!==this.clippingContextCacheKey&&(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return!0===this.material.hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,n=[],i=new Set;for(const r of e){const e=r.node&&r.node.attribute?r.node.attribute:t.getAttribute(r.name);if(void 0===e)continue;n.push(e);const s=e.isInterleavedBufferAttribute?e.data:e;i.add(s)}return this.attributes=n,this.vertexBuffers=Array.from(i.values()),n}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:n,group:i,drawRange:r}=this,s=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a,l=n.isInstancedBufferGeometry?n.instanceCount:e.count>1?e.count:1;if(0===l)return null;if(s.instanceCount=l,!0===e.isBatchedMesh)return s;let u=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(u=2);let c=r.start*u,h=(r.start+r.count)*u;null!==i&&(c=Math.max(c,i.start*u),h=Math.min(h,(i.start+i.count)*u));const d=n.attributes.position;let p=1/0;o?p=a.count:null!=d&&(p=d.count),c=Math.max(c,0),h=Math.min(h,p);const f=h-c;return f<0||f===1/0?null:(s.vertexCount=f,s.firstVertex=c,s)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const n of Object.keys(e.attributes).sort()){const i=e.attributes[n];t+=n+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}for(const n of Object.keys(e.morphAttributes).sort()){const i=e.morphAttributes[n];t+="morph-"+n+",";for(let e=0,n=i.length;e1&&(n+=e.uuid+","),n+=e.receiveShadow+",",Op(n)}get needsGeometryUpdate(){return this.geometry.id!==this.object.geometry.id}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return!0!==this.material.isShadowPassMaterial&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=Bp(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Bp(e,1)),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const iM=[];class rM{constructor(e,t,n,i,r,s){this.renderer=e,this.nodes=t,this.geometries=n,this.pipelines=i,this.bindings=r,this.info=s,this.chainMaps={}}get(e,t,n,i,r,s,a,o){const l=this.getChainMap(o);iM[0]=e,iM[1]=t,iM[2]=s,iM[3]=r;let u=l.get(iM);return void 0===u?(u=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,i,r,s,a,o),l.set(iM,u)):(u.updateClipping(a),u.needsGeometryUpdate&&u.setGeometry(e.geometry),(u.version!==t.version||u.needsUpdate)&&(u.initialCacheKey!==u.getCacheKey()?(u.dispose(),u=this.get(e,t,n,i,r,s,a,o)):u.version=t.version)),iM.length=0,u}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new eM)}dispose(){this.chainMaps={}}createRenderObject(e,t,n,i,r,s,a,o,l,u,c){const h=this.getChainMap(c),d=new nM(e,t,n,i,r,s,a,o,l,u);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.delete(d),this.nodes.delete(d),h.delete(d.getChainArray())},d}}class sM{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const aM=1,oM=2,lM=3,uM=4,cM=16;class hM extends sM{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return void 0!==t&&this.backend.destroyAttribute(e),t}update(e,t){const n=this.get(e);if(void 0===n.version)t===aM?this.backend.createAttribute(e):t===oM?this.backend.createIndexAttribute(e):t===lM?this.backend.createStorageAttribute(e):t===uM&&this.backend.createIndirectStorageAttribute(e),n.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(n.version{this.info.memory.geometries--;const i=t.index,r=e.getAttributes();null!==i&&this.attributes.delete(i);for(const e of r)this.attributes.delete(e);const s=this.wireframes.get(t);void 0!==s&&this.attributes.delete(s),t.removeEventListener("dispose",n)};t.addEventListener("dispose",n)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,lM):this.updateAttribute(e,aM);const n=this.getIndex(e);null!==n&&this.updateAttribute(n,oM);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,uM)}updateAttribute(e,t){const n=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,n)):this.attributeCall.get(e.data)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e.data,n),this.attributeCall.set(e,n)):this.attributeCall.get(e)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e,n))}getIndirect(e){return e.geometry.indirect}getIndex(e){const{geometry:t,material:n}=e;let i=t.index;if(!0===n.wireframe){const e=this.wireframes;let n=e.get(t);void 0===n?(n=pM(t),e.set(t,n)):n.version!==dM(t)&&(this.attributes.delete(n),n=pM(t),e.set(t,n)),i=n}return i}}class mM{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,n){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=n*(t/3):e.isPoints?this.render.points+=n*t:e.isLineSegments?this.render.lines+=n*(t/2):e.isLine?this.render.lines+=n*(t-1):console.error("THREE.WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class gM{constructor(e){this.cacheKey=e,this.usedTimes=0}}class _M extends gM{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}}class vM extends gM{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let yM=0;class xM{constructor(e,t,n,i=null,r=null){this.id=yM++,this.code=e,this.stage=t,this.name=n,this.transforms=i,this.attributes=r,this.usedTimes=0}}class bM extends sM{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:n}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.computeProgram.usedTimes--);const s=this.nodes.getForCompute(e);let a=this.programs.compute.get(s.computeShader);void 0===a&&(r&&0===r.computeProgram.usedTimes&&this._releaseProgram(r.computeProgram),a=new xM(s.computeShader,"compute",e.name,s.transforms,s.nodeAttributes),this.programs.compute.set(s.computeShader,a),n.createProgram(a));const o=this._getComputeCacheKey(e,a);let l=this.caches.get(o);void 0===l&&(r&&0===r.usedTimes&&this._releasePipeline(r),l=this._getComputePipeline(e,a,o,t)),l.usedTimes++,a.usedTimes++,i.version=e.version,i.pipeline=l}return i.pipeline}getForRender(e,t=null){const{backend:n}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const s=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(s.vertexShader);void 0===o&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),o=new xM(s.vertexShader,"vertex",a),this.programs.vertex.set(s.vertexShader,o),n.createProgram(o));let l=this.programs.fragment.get(s.fragmentShader);void 0===l&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),l=new xM(s.fragmentShader,"fragment",a),this.programs.fragment.set(s.fragmentShader,l),n.createProgram(l));const u=this._getRenderCacheKey(e,o,l);let c=this.caches.get(u);void 0===c?(r&&0===r.usedTimes&&this._releasePipeline(r),c=this._getRenderPipeline(e,o,l,u,t)):e.pipeline=c,c.usedTimes++,o.usedTimes++,l.usedTimes++,i.pipeline=c}return i.pipeline}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,0===t.usedTimes&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,0===t.computeProgram.usedTimes&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,0===t.vertexProgram.usedTimes&&this._releaseProgram(t.vertexProgram),0===t.fragmentProgram.usedTimes&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,n,i){n=n||this._getComputeCacheKey(e,t);let r=this.caches.get(n);return void 0===r&&(r=new vM(n,t),this.caches.set(n,r),this.backend.createComputePipeline(r,i)),r}_getRenderPipeline(e,t,n,i,r){i=i||this._getRenderCacheKey(e,t,n);let s=this.caches.get(i);return void 0===s&&(s=new _M(i,t,n),this.caches.set(i,s),e.pipeline=s,this.backend.createRenderPipeline(e,r)),s}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,n){return t.id+","+n.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,n=e.stage;this.programs[n].delete(t)}_needsComputeUpdate(e){const t=this.get(e);return void 0===t.pipeline||t.version!==e.version}_needsRenderUpdate(e){return void 0===this.get(e).pipeline||this.backend.needsRenderUpdate(e)}}class SM extends sM{constructor(e,t,n,i,r,s){super(),this.backend=e,this.textures=n,this.pipelines=r,this.attributes=i,this.nodes=t,this.info=s,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const n=this.get(e);void 0===n.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),n.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const n=this.get(e);void 0===n.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),n.bindGroup=e)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isStorageBuffer){const e=t.attribute,n=e.isIndirectStorageBufferAttribute?uM:lM;this.attributes.update(e,n)}}_update(e,t){const{backend:n}=this;let i=!1,r=!0,s=0,a=0;for(const t of e.bindings){if(t.isNodeUniformsGroup){if(!1===this.nodes.updateGroup(t))continue}if(t.isStorageBuffer){const e=t.attribute,n=e.isIndirectStorageBufferAttribute?uM:lM;this.attributes.update(e,n)}if(t.isUniformBuffer){t.update()&&n.updateBinding(t)}else if(t.isSampler)t.update();else if(t.isSampledTexture){const e=this.textures.get(t.texture);t.needsBindingsUpdate(e.generation)&&(i=!0);const o=t.update(),l=t.texture;o&&this.textures.updateTexture(l);const u=n.get(l);if(void 0!==u.externalTexture||e.isDefaultTexture?r=!1:(s=10*s+l.id,a+=l.version),!0===n.isWebGPUBackend&&void 0===u.texture&&void 0===u.externalTexture&&(console.error("Bindings._update: binding should be available:",t,o,l,t.textureNode.value,i),this.textures.updateTexture(l),i=!0),!0===l.isStorageTexture){const e=this.get(l);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(l)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(l),e.needsMipmap=!1)}}}!0===i&&this.backend.updateBindings(e,t,r?s:0,a)}}function TM(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.material.id!==t.material.id?e.material.id-t.material.id:e.z!==t.z?e.z-t.z:e.id-t.id}function MM(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?t.z-e.z:e.id-t.id}function EM(e){return(e.transmission>0||e.transmissionNode)&&2===e.side&&!1===e.forceSinglePass}class wM{constructor(e,t,n){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,n),this.lightsArray=[],this.scene=t,this.camera=n,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,n,i,r,s,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:n,groupOrder:i,renderOrder:e.renderOrder,z:r,group:s,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=n,o.groupOrder=i,o.renderOrder=e.renderOrder,o.z=r,o.group=s,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,n,i,r,s,a){const o=this.getNextRenderItem(e,t,n,i,r,s,a);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===n.transparent||n.transmission>0?(EM(n)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,n,i,r,s,a){const o=this.getNextRenderItem(e,t,n,i,r,s,a);!0===n.transparent||n.transmission>0?(EM(n)&&this.transparentDoublePass.unshift(o),this.transparent.unshift(o)):this.opaque.unshift(o)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||TM),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||MM),this.transparent.length>1&&this.transparent.sort(t||MM)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,l=a.height>>t;let u=e.depthTexture||r[t];const c=!0===e.depthBuffer||!0===e.stencilBuffer;let h=!1;void 0===u&&c&&(u=new rs,u.format=e.stencilBuffer?xe:ye,u.type=e.stencilBuffer?de:oe,u.image.width=o,u.image.height=l,r[t]=u),n.width===a.width&&a.height===n.height||(h=!0,u&&(u.needsUpdate=!0,u.image.width=o,u.image.height=l)),n.width=a.width,n.height=a.height,n.textures=s,n.depthTexture=u||null,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,n.renderTarget=e,n.sampleCount!==i&&(h=!0,u&&(u.needsUpdate=!0),n.sampleCount=i);const d={sampleCount:i};if(!0!==e.isXRRenderTarget){for(let e=0;e{e.removeEventListener("dispose",t);for(let e=0;e0){const i=e.image;if(void 0===i)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)console.warn("THREE.Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const n=[];for(const t of e.images)n.push(t);t.images=n}else t.image=i;void 0!==n.isDefaultTexture&&!0!==n.isDefaultTexture||(r.createTexture(e,t),n.isDefaultTexture=!1,n.generation=e.version),!0===e.source.dataReady&&r.updateTexture(e,t),t.needsMipmaps&&0===e.mipmaps.length&&r.generateMipmaps(e)}}else r.createDefaultTexture(e),n.isDefaultTexture=!0,n.generation=e.version}if(!0!==n.initialized){n.initialized=!0,n.generation=e.version,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e),this.info.memory.textures--};e.addEventListener("dispose",t)}n.version=e.version}getSize(e,t=OM){let n=e.images?e.images[0]:e.image;return n?(void 0!==n.image&&(n=n.image),t.width=n.width||1,t.height=n.height||1,t.depth=e.isCubeTexture?6:n.depth||1):t.width=t.height=t.depth=1,t}getMipLevels(e,t,n){let i;return i=e.isCompressedTexture?e.mipmaps?e.mipmaps.length:1:Math.floor(Math.log2(Math.max(t,n)))+1,i}needsMipmaps(e){return this.isEnvironmentTexture(e)||!0===e.isCompressedTexture||e.generateMipmaps}isEnvironmentTexture(e){const t=e.mapping;return t===j||t===W||t===V||t===H}_destroyTexture(e){this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e)}}class BM extends Pi{constructor(e,t,n,i=1){super(e,t,n),this.a=i}set(e,t,n,i=1){return this.a=i,super.set(e,t,n)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class kM extends Nm{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}class zM extends sf{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}add(e){return this.nodes.push(e),this}If(e,t){const n=new Wf(t);return this._currentCond=L_(e,n),this.add(this._currentCond)}ElseIf(e,t){const n=new Wf(t),i=L_(e,n);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new Wf(e),this}build(e,...t){const n=Jf();Qf(this);for(const t of this.nodes)t.build(e,"void");return Qf(n),this.outputNode?this.outputNode.build(e,...t):super.build(e,...t)}else(...e){return console.warn("TSL.StackNode: .else() has been renamed to .Else()."),this.Else(...e)}elseif(...e){return console.warn("TSL.StackNode: .elseif() has been renamed to .ElseIf()."),this.ElseIf(...e)}}const GM=Yf(zM);new Hr,new un,new un,new un,new kn,new un(0,0,-1),new nn,new un,new un,new nn,new It;const VM=new rn;Yx.flipX(),VM.depthTexture=new rs(1,1);const HM=new Qs(-1,1,1,-1,0,1);class jM extends tr{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new qi([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new qi(t,2))}}const WM=new jM;class XM extends pr{constructor(e=null){super(WM,e),this.camera=HM,this.isQuadMesh=!0}async renderAsync(e){return e.renderAsync(this,HM)}render(e){e.render(this,HM)}}const qM=new Yn,$M=new kn;class YM extends sf{static get type(){return"SceneNode"}constructor(e=YM.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,n=null!==this.scene?this.scene:e.scene;let i;return t===YM.BACKGROUND_BLURRINESS?i=xy("backgroundBlurriness","float",n):t===YM.BACKGROUND_INTENSITY?i=xy("backgroundIntensity","float",n):t===YM.BACKGROUND_ROTATION?i=Cm("mat4").label("backgroundRotation").setGroup(wm).onRenderUpdate((()=>{const e=n.background;return null!==e&&e.isTexture&&300!==e.mapping?(qM.copy(n.backgroundRotation),qM.x*=-1,qM.y*=-1,qM.z*=-1,$M.makeRotationFromEuler(qM)):$M.identity(),$M})):console.error("THREE.SceneNode: Unknown scope:",t),i}}YM.BACKGROUND_BLURRINESS="backgroundBlurriness",YM.BACKGROUND_INTENSITY="backgroundIntensity",YM.BACKGROUND_ROTATION="backgroundRotation";const KM=Kf(YM,YM.BACKGROUND_BLURRINESS),ZM=Kf(YM,YM.BACKGROUND_INTENSITY),QM=Kf(YM,YM.BACKGROUND_ROTATION);Zf((({texture:e,uv:t})=>{const n=1e-4,i=cm().toVar();return em(t.x.lessThan(n),(()=>{i.assign(cm(1,0,0))})).ElseIf(t.y.lessThan(n),(()=>{i.assign(cm(0,1,0))})).ElseIf(t.z.lessThan(n),(()=>{i.assign(cm(0,0,1))})).ElseIf(t.x.greaterThan(.9999),(()=>{i.assign(cm(-1,0,0))})).ElseIf(t.y.greaterThan(.9999),(()=>{i.assign(cm(0,-1,0))})).ElseIf(t.z.greaterThan(.9999),(()=>{i.assign(cm(0,0,-1))})).Else((()=>{const n=.01,r=e.sample(t.add(cm(-.01,0,0))).r.sub(e.sample(t.add(cm(n,0,0))).r),s=e.sample(t.add(cm(0,-.01,0))).r.sub(e.sample(t.add(cm(0,n,0))).r),a=e.sample(t.add(cm(0,0,-.01))).r.sub(e.sample(t.add(cm(0,0,n))).r);i.assign(cm(r,s,a))})),i.normalize()}));const JM=new It;class eE extends xv{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class tE extends eE{static get type(){return"PassMultipleTextureNode"}constructor(e,t,n=!1){super(e,null),this.textureName=t,this.previousTexture=n}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){return new this.constructor(this.passNode,this.textureName,this.previousTexture)}}class nE extends lf{static get type(){return"PassNode"}constructor(e,t,n,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=n,this.options=i,this._pixelRatio=1,this._width=1,this._height=1;const r=new rs;r.isRenderTargetTexture=!0,r.name="depth";const s=new rn(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ue,...i});s.texture.name="output",s.depthTexture=r,this.renderTarget=s,this._textures={output:s.texture,depth:r},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Cm(0),this._cameraFar=Cm(0),this._mrt=null,this._layers=null,this._resolution=1,this.isPassNode=!0,this.updateBeforeType=$p}setResolution(e){return this._resolution=e,this}getResolution(){return this._resolution}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}isGlobal(){return!0}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return void 0===t&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const n=this._textures[e],i=this.renderTarget.textures.indexOf(n);this.renderTarget.textures[i]=t,this._textures[e]=t,this._previousTextures[e]=n,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=Xf(new tE(this,e)),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),t=Xf(new tE(this,e,!0)),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const n=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=lb(this.getTextureNode(e),n,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const n=this._cameraNear,i=this._cameraFar,r=this.getViewZNode(e);this._linearDepthNodes[e]=t=ab(r,n,i)}return t}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,!0===e.backend.isWebGLBackend&&(this.renderTarget.samples=0),this.renderTarget.texture.type=e.getColorBufferType(),this.scope===nE.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:n}=this;let i,r;const s=t.getOutputRenderTarget();s&&!0===s.isXRRenderTarget?(r=1,i=t.xr.getCamera(),t.xr.updateCamera(i),JM.set(s.width,s.height)):(i=this.camera,r=t.getPixelRatio(),t.getSize(JM)),this._pixelRatio=r,this.setSize(JM.width,JM.height);const a=t.getRenderTarget(),o=t.getMRT(),l=i.layers.mask;this._cameraNear.value=i.near,this._cameraFar.value=i.far,null!==this._layers&&(i.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(n,i),t.setRenderTarget(a),t.setMRT(o),i.layers.mask=l}setSize(e,t){this._width=e,this._height=t;const n=this._width*this._pixelRatio*this._resolution,i=this._height*this._pixelRatio*this._resolution;this.renderTarget.setSize(n,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}nE.COLOR="color",nE.DEPTH="depth";const iE=Zf((([e,t])=>e.mul(t).clamp())).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),rE=Zf((([e,t])=>(e=e.mul(t)).div(e.add(1)).clamp())).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),sE=Zf((([e,t])=>{const n=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),i=e.mul(e.mul(6.2).add(1.7)).add(.06);return n.div(i).pow(2.2)})).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),aE=Zf((([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),n=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(n)})),oE=Zf((([e,t])=>{const n=ym(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=ym(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=n.mul(e),e=aE(e),(e=i.mul(e)).clamp()})).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),lE=ym(cm(1.6605,-.1246,-.0182),cm(-.5876,1.1329,-.1006),cm(-.0728,-.0083,1.1187)),uE=ym(cm(.6274,.0691,.0164),cm(.3293,.9195,.088),cm(.0433,.0113,.8956)),cE=Zf((([e])=>{const t=cm(e).toVar(),n=cm(t.mul(t)).toVar(),i=cm(n.mul(n)).toVar();return nm(15.5).mul(i.mul(n)).sub(hg(40.14,i.mul(t))).add(hg(31.96,i).sub(hg(6.868,n.mul(t))).add(hg(.4298,n).add(hg(.1191,t).sub(.00232))))})),hE=Zf((([e,t])=>{const n=cm(e).toVar(),i=ym(cm(.856627153315983,.137318972929847,.11189821299995),cm(.0951212405381588,.761241990602591,.0767994186031903),cm(.0482516061458583,.101439036467562,.811302368396859)),r=ym(cm(1.1271005818144368,-.1413297634984383,-.14132976349843826),cm(-.11060664309660323,1.157823702216272,-.11060664309660294),cm(-.016493938717834573,-.016493938717834257,1.2519364065950405)),s=nm(-12.47393),a=nm(4.026069);return n.mulAssign(t),n.assign(uE.mul(n)),n.assign(i.mul(n)),n.assign(p_(n,1e-10)),n.assign(zg(n)),n.assign(n.sub(s).div(a.sub(s))),n.assign(R_(n,0,1)),n.assign(cE(n)),n.assign(r.mul(n)),n.assign(b_(p_(cm(0),n),cm(2.2))),n.assign(lE.mul(n)),n.assign(R_(n,0,1)),n})).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),dE=Zf((([e,t])=>{const n=nm(.76),i=nm(.15);e=e.mul(t);const r=d_(e.r,d_(e.g,e.b)),s=L_(r.lessThan(.08),r.sub(hg(6.25,r.mul(r))),.04);e.subAssign(s);const a=p_(e.r,p_(e.g,e.b));em(a.lessThan(n),(()=>e));const o=cg(1,n),l=cg(1,o.mul(o).div(a.add(o.sub(n))));e.mulAssign(l.div(a));const u=cg(1,dg(1,i.mul(a.sub(l)).add(1)));return A_(e,cm(l),u)})).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class pE extends sf{static get type(){return"CodeNode"}constructor(e="",t=[],n=""){super("code"),this.isCodeNode=!0,this.code=e,this.includes=t,this.language=n}isGlobal(){return!0}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const n of t)n.build(e);const n=e.getCodeFromNode(this,this.getNodeType(e));return n.code=this.code,n.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}class fE extends pE{static get type(){return"FunctionNode"}constructor(e="",t=[],n=""){super(e,t,n)}getNodeType(e){return this.getNodeFunction(e).type}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let n=t.nodeFunction;return void 0===n&&(n=e.parser.parseFunction(this.code),t.nodeFunction=n),n}generate(e,t){super.generate(e);const n=this.getNodeFunction(e),i=n.name,r=n.type,s=e.getCodeFromNode(this,r);""!==i&&(s.name=i);const a=e.getPropertyName(s),o=this.getNodeFunction(e).getCode(a);return s.code=o+"\n","property"===t?a:e.format(`${a}()`,r,t)}}function mE(e){let t;const n=e.context.getViewZ;return void 0!==n&&(t=n(this)),(t||qv.z).negate()}const gE=Zf((([e,t],n)=>{const i=mE(n);return N_(e,t,i)})),_E=Zf((([e],t)=>{const n=mE(t);return e.mul(e,n,n).negate().exp().oneMinus()})),vE=Zf((([e,t])=>fm(t.toFloat().mix(Zm.rgb,e.toVec3()),Zm.a)));Yf(class extends sf{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:n}=e;!0===n.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}});class yE extends lf{static get type(){return"AtomicFunctionNode"}constructor(e,t,n,i=null){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=n,this.storeNode=i}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=this.method,n=this.getNodeType(e),i=this.getInputType(e),r=this.pointerNode,s=this.valueNode,a=[];a.push(`&${r.build(e,i)}`),null!==s&&a.push(s.build(e,i));const o=`${e.getMethod(t,n)}( ${a.join(", ")} )`;if(null!==this.storeNode){const t=this.storeNode.build(e,i);e.addLineFlowCode(`${t} = ${o}`,this)}else e.addLineFlowCode(o,this)}}let xE;function bE(e){xE=xE||new WeakMap;let t=xE.get(e);return void 0===t&&xE.set(e,t={}),t}function SE(e){const t=bE(e);return t.shadowMatrix||(t.shadowMatrix=Cm("mat4").setGroup(wm).onRenderUpdate((()=>(!0!==e.castShadow&&e.shadow.updateMatrices(e),e.shadow.matrix))))}function TE(e){const t=bE(e);return t.position||(t.position=Cm(new un).setGroup(wm).onRenderUpdate(((t,n)=>n.value.setFromMatrixPosition(e.matrixWorld))))}function ME(e){const t=bE(e);return t.viewPosition||(t.viewPosition=Cm(new un).setGroup(wm).onRenderUpdate((({camera:t},n)=>{n.value=n.value||new un,n.value.setFromMatrixPosition(e.matrixWorld),n.value.applyMatrix4(t.matrixWorldInverse)})))}yE.ATOMIC_LOAD="atomicLoad",yE.ATOMIC_STORE="atomicStore",yE.ATOMIC_ADD="atomicAdd",yE.ATOMIC_SUB="atomicSub",yE.ATOMIC_MAX="atomicMax",yE.ATOMIC_MIN="atomicMin",yE.ATOMIC_AND="atomicAnd",yE.ATOMIC_OR="atomicOr",yE.ATOMIC_XOR="atomicXor",Yf(yE);const EE=e=>Dv.transformDirection(TE(e).sub(function(e){const t=bE(e);return t.targetPosition||(t.targetPosition=Cm(new un).setGroup(wm).onRenderUpdate(((t,n)=>n.value.setFromMatrixPosition(e.target.matrixWorld))))}(e))),wE=(e,t)=>{for(const n of t)if(n.isAnalyticLightNode&&n.light.id===e)return n;return null},AE=new WeakMap;class RE extends sf{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=cm().toVar("totalDiffuse"),this.totalSpecularNode=cm().toVar("totalSpecular"),this.outgoingLightNode=cm().toVar("outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=[],t=this._lights;for(let n=0;ne.sort(((e,t)=>e.id-t.id)))(this._lights),r=e.renderer.library;for(const e of i)if(e.isNode)t.push(Xf(e));else{let i=null;if(null!==n&&(i=wE(e.id,n)),null===i){const n=r.getLightNodeClass(e.constructor);if(null===n){console.warn(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let i=null;AE.has(e)?i=AE.get(e):(i=Xf(new n(e)),AE.set(e,i)),t.push(i)}}this._lightNodes=t}setupDirectLight(e,t,n){const{lightingModel:i,reflectedLight:r}=e.context;i.direct({...n,lightNode:t,reflectedLight:r},e)}setupDirectRectAreaLight(e,t,n){const{lightingModel:i,reflectedLight:r}=e.context;i.directRectArea({...n,lightNode:t,reflectedLight:r},e)}setupLights(e,t){for(const n of t)n.build(e)}getLightNodes(e){return null===this._lightNodes&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let n=this.outgoingLightNode;const i=e.context,r=i.lightingModel,s=e.getDataFromNode(this);if(r){const{totalDiffuseNode:t,totalSpecularNode:a}=this;i.outgoingLight=n;const o=e.addStack();s.nodes=o.nodes,r.start(e);const{backdrop:l,backdropAlpha:u}=i,{directDiffuse:c,directSpecular:h,indirectDiffuse:d,indirectSpecular:p}=i.reflectedLight;let f=c.add(d);null!==l&&(f=cm(null!==u?u.mix(f,l):l),i.material.transparent=!0),t.assign(f),a.assign(h.add(p)),n.assign(t.add(a)),r.finish(e),n=n.bypass(e.removeStack())}else s.nodes=[];return e.lightsNode=t,n}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class CE extends sf{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Yp,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){NE.assign(t.shadowPositionNode||e.shadowPositionWorld||Wv)}dispose(){this.updateBeforeType=qp}}const NE=Pm("vec3","shadowPositionWorld");function PE(e,t){return t=function(e,t={}){return t.toneMapping=e.toneMapping,t.toneMappingExposure=e.toneMappingExposure,t.outputColorSpace=e.outputColorSpace,t.renderTarget=e.getRenderTarget(),t.activeCubeFace=e.getActiveCubeFace(),t.activeMipmapLevel=e.getActiveMipmapLevel(),t.renderObjectFunction=e.getRenderObjectFunction(),t.pixelRatio=e.getPixelRatio(),t.mrt=e.getMRT(),t.clearColor=e.getClearColor(t.clearColor||new Pi),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.scissorTest=e.getScissorTest(),t}(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}const DE=new WeakMap,UE=Zf((([e,t,n])=>{let i=Wv.sub(e).length();return i=i.sub(t).div(n.sub(t)),i=i.saturate(),i})),LE=e=>{let t=DE.get(e);if(void 0===t){const n=e.isPointLight?(e=>{const t=e.shadow.camera,n=xy("near","float",t).setGroup(wm),i=xy("far","float",t).setGroup(wm),r=Ov(e);return UE(r,n,i)})(e):null;t=new _b,t.colorNode=fm(0,0,0,1),t.depthNode=n,t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.fog=!1,DE.set(e,t)}return t},IE=Zf((({depthTexture:e,shadowCoord:t})=>bv(e,t.xy).compare(t.z))),OE=Zf((({depthTexture:e,shadowCoord:t,shadow:n})=>{const i=(t,n)=>bv(e,t).compare(n),r=xy("mapSize","vec2",n).setGroup(wm),s=xy("radius","float",n).setGroup(wm),a=am(1).div(r),o=a.x.negate().mul(s),l=a.y.negate().mul(s),u=a.x.mul(s),c=a.y.mul(s),h=o.div(2),d=l.div(2),p=u.div(2),f=c.div(2);return ug(i(t.xy.add(am(o,l)),t.z),i(t.xy.add(am(0,l)),t.z),i(t.xy.add(am(u,l)),t.z),i(t.xy.add(am(h,d)),t.z),i(t.xy.add(am(0,d)),t.z),i(t.xy.add(am(p,d)),t.z),i(t.xy.add(am(o,0)),t.z),i(t.xy.add(am(h,0)),t.z),i(t.xy,t.z),i(t.xy.add(am(p,0)),t.z),i(t.xy.add(am(u,0)),t.z),i(t.xy.add(am(h,f)),t.z),i(t.xy.add(am(0,f)),t.z),i(t.xy.add(am(p,f)),t.z),i(t.xy.add(am(o,c)),t.z),i(t.xy.add(am(0,c)),t.z),i(t.xy.add(am(u,c)),t.z)).mul(1/17)})),FE=Zf((({depthTexture:e,shadowCoord:t,shadow:n})=>{const i=(t,n)=>bv(e,t).compare(n),r=xy("mapSize","vec2",n).setGroup(wm),s=am(1).div(r),a=s.x,o=s.y,l=t.xy,u=Xg(l.mul(r).add(.5));return l.subAssign(u.mul(s)),ug(i(l,t.z),i(l.add(am(a,0)),t.z),i(l.add(am(0,o)),t.z),i(l.add(s),t.z),A_(i(l.add(am(a.negate(),0)),t.z),i(l.add(am(a.mul(2),0)),t.z),u.x),A_(i(l.add(am(a.negate(),o)),t.z),i(l.add(am(a.mul(2),o)),t.z),u.x),A_(i(l.add(am(0,o.negate())),t.z),i(l.add(am(0,o.mul(2))),t.z),u.y),A_(i(l.add(am(a,o.negate())),t.z),i(l.add(am(a,o.mul(2))),t.z),u.y),A_(A_(i(l.add(am(a.negate(),o.negate())),t.z),i(l.add(am(a.mul(2),o.negate())),t.z),u.x),A_(i(l.add(am(a.negate(),o.mul(2))),t.z),i(l.add(am(a.mul(2),o.mul(2))),t.z),u.x),u.y)).mul(1/9)})),BE=Zf((({depthTexture:e,shadowCoord:t})=>{const n=nm(1).toVar(),i=bv(e).sample(t.xy).rg,r=m_(t.z,i.x);return em(r.notEqual(nm(1)),(()=>{const e=t.z.sub(i.x),s=p_(0,i.y.mul(i.y));let a=s.div(s.add(e.mul(e)));a=R_(cg(a,.3).div(.95-.3)),n.assign(R_(p_(r,a)))})),n})),kE=Zf((({samples:e,radius:t,size:n,shadowPass:i})=>{const r=nm(0).toVar(),s=nm(0).toVar(),a=e.lessThanEqual(nm(1)).select(nm(0),nm(2).div(e.sub(1))),o=e.lessThanEqual(nm(1)).select(nm(0),nm(-1));Ix({start:im(0),end:im(e),type:"int",condition:"<"},(({i:e})=>{const l=o.add(nm(e).mul(a)),u=i.sample(ug(Zx.xy,am(0,l).mul(t)).div(n)).x;r.addAssign(u),s.addAssign(u.mul(u))})),r.divAssign(e),s.divAssign(e);const l=Gg(s.sub(r.mul(r)));return am(r,l)})),zE=Zf((({samples:e,radius:t,size:n,shadowPass:i})=>{const r=nm(0).toVar(),s=nm(0).toVar(),a=e.lessThanEqual(nm(1)).select(nm(0),nm(2).div(e.sub(1))),o=e.lessThanEqual(nm(1)).select(nm(0),nm(-1));Ix({start:im(0),end:im(e),type:"int",condition:"<"},(({i:e})=>{const l=o.add(nm(e).mul(a)),u=i.sample(ug(Zx.xy,am(l,0).mul(t)).div(n));r.addAssign(u.x),s.addAssign(ug(u.y.mul(u.y),u.x.mul(u.x)))})),r.divAssign(e),s.divAssign(e);const l=Gg(s.sub(r.mul(r)));return am(r,l)})),GE=[IE,OE,FE,BE];let VE;const HE=new XM;class jE extends CE{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:i,shadow:r}){const s=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),a=t({depthTexture:n,shadowCoord:i,shadow:r});return s.select(a,nm(1))}setupShadowCoord(e,t){const{shadow:n}=this,{renderer:i}=e,r=xy("bias","float",n).setGroup(wm);let s,a=t;if(n.camera.isOrthographicCamera||!0!==i.logarithmicDepthBuffer)a=a.xyz.div(a.w),s=a.z,i.coordinateSystem===St&&(s=s.mul(2).sub(1));else{const e=a.w;a=a.xy.div(e);const t=xy("near","float",n.camera).setGroup(wm),i=xy("far","float",n.camera).setGroup(wm);s=ub(e.negate(),t,i)}return a=cm(a.x,a.y.oneMinus(),s.add(r)),a}getShadowFilterFn(e){return GE[e]}setupShadow(e){const{renderer:t}=e,{light:n,shadow:i}=this,r=t.shadowMap.type,s=new rs(i.mapSize.width,i.mapSize.height);s.compareFunction=ht;const a=e.createRenderTarget(i.mapSize.width,i.mapSize.height);if(a.depthTexture=s,i.camera.updateProjectionMatrix(),3===r){s.compareFunction=null,this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:Te,type:ue}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:Te,type:ue});const t=bv(s),n=bv(this.vsmShadowMapVertical.texture),r=xy("blurSamples","float",i).setGroup(wm),a=xy("radius","float",i).setGroup(wm),o=xy("mapSize","vec2",i).setGroup(wm);let l=this.vsmMaterialVertical||(this.vsmMaterialVertical=new _b);l.fragmentNode=kE({samples:r,radius:a,size:o,shadowPass:t}).context(e.getSharedContext()),l.name="VSMVertical",l=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new _b),l.fragmentNode=zE({samples:r,radius:a,size:o,shadowPass:n}).context(e.getSharedContext()),l.name="VSMHorizontal"}const o=xy("intensity","float",i).setGroup(wm),l=xy("normalBias","float",i).setGroup(wm),u=SE(n).mul(NE.add(iy.mul(l))),c=this.setupShadowCoord(e,u),h=i.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===h)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const d=3===r?this.vsmShadowMapHorizontal.texture:s,p=this.setupShadowFilter(e,{filterFn:h,shadowTexture:a.texture,depthTexture:d,shadowCoord:c,shadow:i}),f=bv(a.texture,c),m=A_(1,p.rgb.mix(f,1),o.mul(f.a)).toVar();return this.shadowMap=a,this.shadow.map=a,m}setup(e){if(!1!==e.renderer.shadowMap.enabled)return Zf((()=>{let t=this._node;return this.setupShadowPosition(e),null===t&&(this._node=t=this.setupShadow(e)),e.material.shadowNode&&console.warn('THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(t=e.material.receivedShadowNode(t)),t}))()}renderShadow(e){const{shadow:t,shadowMap:n,light:i}=this,{renderer:r,scene:s}=e;t.updateMatrices(i),n.setSize(t.mapSize.width,t.mapSize.height),r.render(s,t.camera)}updateShadow(e){const{shadowMap:t,light:n,shadow:i}=this,{renderer:r,scene:s,camera:a}=e,o=r.shadowMap.type,l=t.depthTexture.version;this._depthVersionCached=l,i.camera.layers.mask=a.layers.mask;const u=r.getRenderObjectFunction(),c=r.getMRT(),h=!!c&&c.has("velocity");VE=function(e,t,n){return n=function(e,t){return t=function(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}(t,n=PE(e,n)),n}(r,s,VE),s.overrideMaterial=LE(n),r.setRenderObjectFunction(((e,t,n,s,l,u,...c)=>{(!0===e.castShadow||e.receiveShadow&&3===o)&&(h&&(Wp(e).useVelocity=!0),e.onBeforeShadow(r,e,a,i.camera,s,t.overrideMaterial,u),r.renderObject(e,t,n,s,l,u,...c),e.onAfterShadow(r,e,a,i.camera,s,t.overrideMaterial,u))})),r.setRenderTarget(t),this.renderShadow(e),r.setRenderObjectFunction(u),!0!==n.isPointLight&&3===o&&this.vsmPass(r),function(e,t,n){!function(e,t){e.toneMapping=t.toneMapping,e.toneMappingExposure=t.toneMappingExposure,e.outputColorSpace=t.outputColorSpace,e.setRenderTarget(t.renderTarget,t.activeCubeFace,t.activeMipmapLevel),e.setRenderObjectFunction(t.renderObjectFunction),e.setPixelRatio(t.pixelRatio),e.setMRT(t.mrt),e.setClearColor(t.clearColor,t.clearAlpha),e.autoClear=t.autoClear,e.setScissorTest(t.scissorTest)}(e,n),function(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}(t,n)}(r,s,VE)}vsmPass(e){const{shadow:t}=this;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height),e.setRenderTarget(this.vsmShadowMapVertical),HE.material=this.vsmMaterialVertical,HE.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),HE.material=this.vsmMaterialHorizontal,HE.render(e)}dispose(){this.shadowMap.dispose(),this.shadowMap=null,null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null),super.dispose()}updateBefore(e){const{shadow:t}=this;let n=t.needsUpdate||t.autoUpdate;n&&(this._cameraFrameId[e.camera]===e.frameId&&(n=!1),this._cameraFrameId[e.camera]=e.frameId),n&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const WE=new Pi,XE=Zf((([e,t])=>{const n=e.toVar(),i=Jg(n),r=dg(1,p_(i.x,p_(i.y,i.z)));i.mulAssign(r),n.mulAssign(r.mul(t.mul(2).oneMinus()));const s=am(n.xy).toVar(),a=t.mul(1.5).oneMinus();return em(i.z.greaterThanEqual(a),(()=>{em(n.z.greaterThan(0),(()=>{s.x.assign(cg(4,n.x))}))})).ElseIf(i.x.greaterThanEqual(a),(()=>{const e=e_(n.x);s.x.assign(n.z.mul(e).add(e.mul(2)))})).ElseIf(i.y.greaterThanEqual(a),(()=>{const e=e_(n.y);s.x.assign(n.x.add(e.mul(2)).add(2)),s.y.assign(n.z.mul(e).sub(2))})),am(.125,.25).mul(s).add(am(.375,.75)).flipY()})).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),qE=Zf((({depthTexture:e,bd3D:t,dp:n,texelSize:i})=>bv(e,XE(t,i.y)).compare(n))),$E=Zf((({depthTexture:e,bd3D:t,dp:n,texelSize:i,shadow:r})=>{const s=xy("radius","float",r).setGroup(wm),a=am(-1,1).mul(s).mul(i.y);return bv(e,XE(t.add(a.xyy),i.y)).compare(n).add(bv(e,XE(t.add(a.yyy),i.y)).compare(n)).add(bv(e,XE(t.add(a.xyx),i.y)).compare(n)).add(bv(e,XE(t.add(a.yyx),i.y)).compare(n)).add(bv(e,XE(t,i.y)).compare(n)).add(bv(e,XE(t.add(a.xxy),i.y)).compare(n)).add(bv(e,XE(t.add(a.yxy),i.y)).compare(n)).add(bv(e,XE(t.add(a.xxx),i.y)).compare(n)).add(bv(e,XE(t.add(a.yxx),i.y)).compare(n)).mul(1/9)})),YE=Zf((({filterFn:e,depthTexture:t,shadowCoord:n,shadow:i})=>{const r=n.xyz.toVar(),s=r.length(),a=Cm("float").setGroup(wm).onRenderUpdate((()=>i.camera.near)),o=Cm("float").setGroup(wm).onRenderUpdate((()=>i.camera.far)),l=xy("bias","float",i).setGroup(wm),u=Cm(i.mapSize).setGroup(wm),c=nm(1).toVar();return em(s.sub(o).lessThanEqual(0).and(s.sub(a).greaterThanEqual(0)),(()=>{const n=s.sub(a).div(o.sub(a)).toVar();n.addAssign(l);const h=r.normalize(),d=am(1).div(u.mul(am(4,2)));c.assign(e({depthTexture:t,bd3D:h,dp:n,texelSize:d,shadow:i}))})),c})),KE=new nn,ZE=new It,QE=new It;class JE extends jE{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?qE:$E}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:n,depthTexture:i,shadowCoord:r,shadow:s}){return YE({filterFn:t,shadowTexture:n,depthTexture:i,shadowCoord:r,shadow:s})}renderShadow(e){const{shadow:t,shadowMap:n,light:i}=this,{renderer:r,scene:s}=e,a=t.getFrameExtents();QE.copy(t.mapSize),QE.multiply(a),n.setSize(QE.width,QE.height),ZE.copy(t.mapSize);const o=r.autoClear,l=r.getClearColor(WE),u=r.getClearAlpha();r.autoClear=!1,r.setClearColor(t.clearColor,t.clearAlpha),r.clear();const c=t.getViewportCount();for(let e=0;eXf(new jE(e,t)))(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let n=this.shadowColorNode;if(null===n){const t=this.light.shadow.shadowNode;let i;i=void 0!==t?Xf(t):this.setupShadowNode(e),this.shadowNode=i,this.shadowColorNode=n=this.colorNode.mul(i),this.baseColorNode=this.colorNode}this.colorNode=n}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),n=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),n&&e.lightsNode.setupDirectRectAreaLight(e,this,n)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const tw=Zf((({lightDistance:e,cutoffDistance:t,decayExponent:n})=>{const i=e.pow(n).max(.01).reciprocal();return t.greaterThan(0).select(i.mul(e.div(t).pow4().oneMinus().clamp().pow2()),i)}));class nw extends ew{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Cm(0).setGroup(wm),this.decayExponentNode=Cm(2).setGroup(wm)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>Xf(new JE(e,t)))(this.light)}setupDirect(e){return(({color:e,lightVector:t,cutoffDistance:n,decayExponent:i})=>{const r=t.normalize(),s=t.length(),a=tw({lightDistance:s,cutoffDistance:n,decayExponent:i});return{lightDirection:r,lightColor:e.mul(a)}})({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}Zf((([e=mv()],{renderer:t,material:n})=>{const i=nm(1).toVar(),r=w_(e.mul(2).sub(1));if(n.alphaToCoverage&&t.samples>1){const e=nm(r.fwidth()).toVar();i.assign(N_(e.oneMinus(),e.add(1),r).oneMinus())}else r.greaterThan(1).discard();return i}));const iw=Zf((([e,t])=>{const n=e.x,i=e.y,r=e.z;let s=t.element(0).mul(.886227);return s=s.add(t.element(1).mul(1.023328).mul(i)),s=s.add(t.element(2).mul(1.023328).mul(r)),s=s.add(t.element(3).mul(1.023328).mul(n)),s=s.add(t.element(4).mul(.858086).mul(n).mul(i)),s=s.add(t.element(5).mul(.858086).mul(i).mul(r)),s=s.add(t.element(6).mul(r.mul(r).mul(.743125).sub(.247708))),s=s.add(t.element(7).mul(.858086).mul(n).mul(r)),s=s.add(t.element(8).mul(.429043).mul(hg(n,n).sub(hg(i,i)))),s})),rw=new BM;class sw extends sM{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,n){const i=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let s=!1;if(null===r)i._clearColor.getRGB(rw),rw.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(rw),rw.a=1,s=!0;else if(!0===r.isNode){const n=this.get(e),s=r;rw.copy(i._clearColor);let a=n.backgroundMesh;if(void 0===a){const e=O_(fm(s).mul(ZM),{getUV:()=>QM.mul(ty),getTextureLevel:()=>KM});let t=Sx;t=t.setZ(t.w);const i=new _b;i.name="Background.material",i.side=1,i.depthTest=!1,i.depthWrite=!1,i.fog=!1,i.lights=!1,i.vertexNode=t,i.colorNode=e,n.backgroundMeshNode=e,n.backgroundMesh=a=new pr(new bs(1,32,32),i),a.frustumCulled=!1,a.name="Background.mesh",a.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)}}const o=s.getCacheKey();n.backgroundCacheKey!==o&&(n.backgroundMeshNode.node=fm(s).mul(ZM),n.backgroundMeshNode.needsUpdate=!0,a.material.needsUpdate=!0,n.backgroundCacheKey=o),t.unshift(a,a.geometry,a.material,0,0,null,null)}else console.error("THREE.Renderer: Unsupported background configuration.",r);const a=i.xr.getEnvironmentBlendMode();if("additive"===a?rw.set(0,0,0,1):"alpha-blend"===a&&rw.set(0,0,0,0),!0===i.autoClear||!0===s){const e=n.clearColorValue;e.r=rw.r,e.g=rw.g,e.b=rw.b,e.a=rw.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(e.r*=e.a,e.g*=e.a,e.b*=e.a),n.depthClearValue=i._clearDepth,n.stencilClearValue=i._clearStencil,n.clearColor=!0===i.autoClearColor,n.clearDepth=!0===i.autoClearDepth,n.clearStencil=!0===i.autoClearStencil}else n.clearColor=!1,n.clearDepth=!1,n.clearStencil=!1}}let aw=0;class ow{constructor(e="",t=[],n=0,i=[]){this.name=e,this.bindings=t,this.index=n,this.bindingsReference=i,this.id=aw++}}class lw{constructor(e,t,n,i,r,s,a,o,l,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=n,this.transforms=u,this.nodeAttributes=i,this.bindings=r,this.updateNodes=s,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=l,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const n=new ow(t.name,[],t.index,t);e.push(n);for(const e of t.bindings)n.bindings.push(e.clone())}else e.push(t)}return e}}class uw{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}}class cw{constructor(e,t,n){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=n.getSelf()}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class hw{constructor(e,t,n=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=n,this.count=i}}class dw extends hw{constructor(e,t){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0}}class pw{constructor(e,t,n=""){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}}let fw=0;class mw{constructor(e=null){this.id=fw++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return void 0===t&&null!==this.parent&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class gw{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class _w{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class vw extends _w{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class yw extends _w{constructor(e,t=new It){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class xw extends _w{constructor(e,t=new un){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class bw extends _w{constructor(e,t=new nn){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class Sw extends _w{constructor(e,t=new Pi){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class Tw extends _w{constructor(e,t=new fa){super(e,t),this.isMatrix2Uniform=!0,this.boundary=16,this.itemSize=4}}class Mw extends _w{constructor(e,t=new Ot){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class Ew extends _w{constructor(e,t=new kn){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class ww extends vw{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Aw extends yw{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Rw extends xw{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Cw extends bw{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Nw extends Sw{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Pw extends Tw{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Dw extends Mw{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Uw extends Ew{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}const Lw=new WeakMap,Iw=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),Ow=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class Fw{constructor(e,t,n){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=n,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.flow={code:""},this.chaining=[],this.stack=GM(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new mw,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.useComparisonMethod=!1}getBindGroupsCache(){let e=Lw.get(this.renderer);return void 0===e&&(e=new eM,Lw.set(this.renderer,e)),e}createRenderTarget(e,t,n){return new rn(e,t,n)}createCubeRenderTarget(e,t){return new wb(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const n=this.getBindGroupsCache(),i=[];let r,s=!0;for(const e of t)i.push(e),s=s&&!0!==e.groupNode.shared;return s?(r=n.get(i),void 0===r&&(r=new ow(e,i,this.bindingsIndexes[e].group,i),n.set(i,r))):r=new ow(e,i,this.bindingsIndexes[e].group,i),r}getBindGroupArray(e,t){const n=this.bindings[t];let i=n[e];return void 0===i&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),n[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(null===e){const t={},n=this.bindings;for(const e of tf)for(const i in n[e]){const r=n[e][i];(t[i]||(t[i]=[])).push(...r)}e=[];for(const n in t){const i=t[n],r=this._getBindGroup(n,i);e.push(r)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort(((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order));for(let t=0;t=0?`${Math.round(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${Ow(t.r)}, ${Ow(t.g)}, ${Ow(t.b)} )`;const n=this.getTypeLength(e),i=this.getComponentType(e),r=e=>this.generateConst(i,e);if(2===n)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(3===n)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(4===n&&"mat2"!==e)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(n>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).join(", ")} )`;if(n>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return"color"===e?"vec3":e}hasGeometryAttribute(e){return this.geometry&&void 0!==this.geometry.getAttribute(e)}getAttribute(e,t){const n=this.attributes;for(const t of n)if(t.name===e)return t;const i=new uw(e,t);return n.push(i),i}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===ae)return"int";if(t===oe)return"uint"}return"float"}getElementType(e){return"mat2"===e?"vec2":"mat3"===e?"vec3":"mat4"===e?"vec4":this.getComponentType(e)}getComponentType(e){if("float"===(e=this.getVectorType(e))||"bool"===e||"int"===e||"uint"===e)return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return null===t?null:"b"===t[1]?"bool":"i"===t[1]?"int":"u"===t[1]?"uint":"float"}getVectorType(e){return"color"===e?"vec3":"texture"===e||"cubeTexture"===e||"storageTexture"===e||"texture3D"===e?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;let n=function(e){return Gp.get(e)}(e);const i="float"===t?"":t[0];return!0===/mat2/.test(t)&&(n=n.replace("vec","mat")),i+n}getTypeFromArray(e){return Iw.get(e.constructor)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const n=t.array,i=e.itemSize,r=e.normalized;let s;return e instanceof Xi||!0===r||(s=this.getTypeFromArray(n)),this.getTypeFromLength(i,s)}getTypeLength(e){const t=this.getVectorType(e),n=/vec([2-4])/.exec(t);return null!==n?Number(n[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}addStack(){return this.stack=GM(this.stack),this.stacks.push(Jf()||this.stack),Qf(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,Qf(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,n=null){let i=(n=null===n?e.isGlobal(this)?this.globalCache:this.cache:n).getData(e);return void 0===i&&(i={},n.setData(e,i)),void 0===i[t]&&(i[t]={}),i[t]}getNodeProperties(e,t="any"){const n=this.getDataFromNode(e,t);return n.properties||(n.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const n=this.getDataFromNode(e);let i=n.bufferAttribute;if(void 0===i){const r=this.uniforms.index++;i=new uw("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),n.bufferAttribute=i}return i}getStructTypeFromNode(e,t,n=null,i=this.shaderStage){const r=this.getDataFromNode(e,i,this.globalCache);let s=r.structType;if(void 0===s){const e=this.structs.index++;null===n&&(n="StructType"+e),s=new gw(n,t),this.structs[i].push(s),r.structType=s}return s}getOutputStructTypeFromNode(e,t){const n=this.getStructTypeFromNode(e,t,"OutputType","fragment");return n.output=!0,n}getUniformFromNode(e,t,n=this.shaderStage,i=null){const r=this.getDataFromNode(e,n,this.globalCache);let s=r.uniform;if(void 0===s){const a=this.uniforms.index++;s=new cw(i||"nodeUniform"+a,t,e),this.uniforms[n].push(s),r.uniform=s}return s}getArrayCount(e){let t=null;return e.isArrayNode?t=e.count:e.isVarNode&&e.node.isArrayNode&&(t=e.node.count),t}getVarFromNode(e,t=null,n=e.getNodeType(this),i=this.shaderStage,r=!1){const s=this.getDataFromNode(e,i);let a=s.variable;if(void 0===a){const o=r?"_const":"_var",l=this.vars[i]||(this.vars[i]=[]),u=this.vars[o]||(this.vars[o]=0);null===t&&(t=(r?"nodeConst":"nodeVar")+u,this.vars[o]++);const c=this.getArrayCount(e);a=new hw(t,n,r,c),r||l.push(a),s.variable=a}return a}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(null!==e.values)for(const t of e.values)if(!this.isDeterministic(t))return!1;return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,n=e.getNodeType(this)){const i=this.getDataFromNode(e,"any");let r=i.varying;if(void 0===r){const e=this.varyings,s=e.length;null===t&&(t="nodeVarying"+s),r=new dw(t,n),e.push(r),i.varying=r}return r}getCodeFromNode(e,t,n=this.shaderStage){const i=this.getDataFromNode(e);let r=i.code;if(void 0===r){const e=this.codes[n]||(this.codes[n]=[]),s=e.length;r=new pw("nodeCode"+s,t),e.push(r),i.code=r}return r}addFlowCodeHierarchy(e,t){const{flowCodes:n,flowCodeBlock:i}=this.getDataFromNode(e);let r=!0,s=t;for(;s;){if(!0===i.get(s)){r=!1;break}s=this.getDataFromNode(s).parentNodeBlock}if(r)for(const e of n)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,n){const i=this.getDataFromNode(e),r=i.flowCodes||(i.flowCodes=[]),s=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);r.push(t),s.set(n,!0)}addLineFlowCode(e,t=null){return""===e||(null!==t&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e+=";\n"),this.flow.code+=e),this}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+="\t",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),n=this.flowChildNode(e,t);return this.flowsData.set(e,n),n}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new fE,n=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=n,t}flowShaderNode(e){const t=e.layout,n={[Symbol.iterator](){let e=0;const t=Object.values(this);return{next:()=>({value:t[e],done:e++>=t.length})}}};for(const e of t.inputs)n[e.name]=new kM(e.type,e.name);e.layout=null;const i=e.call(n),r=this.flowStagesNode(i,t.type);return e.layout=t,r}flowStagesNode(e,t=null){const n=this.flow,i=this.vars,r=this.cache,s=this.buildStage,a=this.stack,o={code:""};this.flow=o,this.vars={},this.cache=new mw,this.stack=GM();for(const n of ef)this.setBuildStage(n),o.result=e.build(this,t);return o.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=i,this.cache=r,this.stack=a,this.setBuildStage(s),o}getFunctionOperator(){return null}flowChildNode(e,t=null){const n=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=n,i}flowNodeFromShaderStage(e,t,n=null,i=null){const r=this.shaderStage;this.setShaderStage(e);const s=this.flowChildNode(t,n);return null!==i&&(s.code+=`${this.tab+i} = ${s.result};\n`),this.flowCode[e]=this.flowCode[e]+s.code,this.setShaderStage(r),s}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){console.warn("Abstract function.")}getVaryings(){console.warn("Abstract function.")}getVar(e,t,n=null){return`${null!==n?this.generateArrayDeclaration(e,n):this.getType(e)} ${t}`}getVars(e){let t="";const n=this.vars[e];if(void 0!==n)for(const e of n)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){console.warn("Abstract function.")}getCodes(e){const t=this.codes[e];let n="";if(void 0!==t)for(const e of t)n+=e.code+"\n";return n}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){console.warn("Abstract function.")}build(){const{object:e,material:t,renderer:n}=this;if(null!==t){let e=n.library.fromMaterial(t);null===e&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new _b),e.build(this)}else this.addFlow("compute",e);for(const e of ef){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of tf){this.setShaderStage(t);const n=this.flowNodes[t];for(const t of n)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getNodeUniform(e,t){if("float"===t||"int"===t||"uint"===t)return new ww(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new Aw(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new Rw(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new Cw(e);if("color"===t)return new Nw(e);if("mat2"===t)return new Pw(e);if("mat3"===t)return new Dw(e);if("mat4"===t)return new Uw(e);throw new Error(`Uniform "${t}" not declared.`)}format(e,t,n){if((t=this.getVectorType(t))===(n=this.getVectorType(n))||null===n||this.isReference(n))return e;const i=this.getTypeLength(t),r=this.getTypeLength(n);return 16===i&&9===r?`${this.getType(n)}(${e}[0].xyz, ${e}[1].xyz, ${e}[2].xyz)`:9===i&&4===r?`${this.getType(n)}(${e}[0].xy, ${e}[1].xy)`:i>4||r>4||0===r?e:i===r?`${this.getType(n)}( ${e} )`:i>r?this.format(`${e}.${"xyz".slice(0,r)}`,this.getTypeFromLength(r,this.getComponentType(t)),n):4===r&&i>1?`${this.getType(n)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===i?`${this.getType(n)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===i&&r>1&&t!==this.getComponentType(n)&&(e=`${this.getType(this.getComponentType(n))}( ${e} )`),`${this.getType(n)}( ${e} )`)}getSignature(){return`// Three.js r${s} - Node System\n`}createNodeMaterial(e="NodeMaterial"){throw new Error(`THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${e}() instead.`)}}class Bw{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let n=e.get(t);return void 0===n&&(n={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,n)),n}updateBeforeNode(e){const t=e.getUpdateBeforeType(),n=e.updateReference(this);if(t===$p){const{frameMap:t}=this._getMaps(this.updateBeforeMap,n);t.get(n)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(n,this.frameId)}else if(t===Yp){const{renderMap:t}=this._getMaps(this.updateBeforeMap,n);t.get(n)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(n,this.renderId)}else t===Kp&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),n=e.updateReference(this);if(t===$p){const{frameMap:t}=this._getMaps(this.updateAfterMap,n);t.get(n)!==this.frameId&&!1!==e.updateAfter(this)&&t.set(n,this.frameId)}else if(t===Yp){const{renderMap:t}=this._getMaps(this.updateAfterMap,n);t.get(n)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(n,this.renderId)}else t===Kp&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),n=e.updateReference(this);if(t===$p){const{frameMap:t}=this._getMaps(this.updateMap,n);t.get(n)!==this.frameId&&!1!==e.update(this)&&t.set(n,this.frameId)}else if(t===Yp){const{renderMap:t}=this._getMaps(this.updateMap,n);t.get(n)!==this.renderId&&!1!==e.update(this)&&t.set(n,this.renderId)}else t===Kp&&e.update(this)}update(){this.frameId++,void 0===this.lastTime&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class kw{constructor(e,t,n=null,i="",r=!1){this.type=e,this.name=t,this.count=n,this.qualifier=i,this.isConst=r}}kw.isNodeFunctionInput=!0;class zw extends ew{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:EE(this.light),lightColor:e}}}const Gw=new kn,Vw=new kn;let Hw=null;class jw extends ew{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Cm(new un).setGroup(wm),this.halfWidth=Cm(new un).setGroup(wm),this.updateType=Yp}update(e){super.update(e);const{light:t}=this,n=e.camera.matrixWorldInverse;Vw.identity(),Gw.copy(t.matrixWorld),Gw.premultiply(n),Vw.extractRotation(Gw),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(Vw),this.halfHeight.value.applyMatrix4(Vw)}setupDirectRectArea(e){let t,n;e.isAvailable("float32Filterable")?(t=bv(Hw.LTC_FLOAT_1),n=bv(Hw.LTC_FLOAT_2)):(t=bv(Hw.LTC_HALF_1),n=bv(Hw.LTC_HALF_2));const{colorNode:i,light:r}=this;return{lightColor:i,lightPosition:ME(r),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:n}}static setLTC(e){Hw=e}}class Ww extends ew{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Cm(0).setGroup(wm),this.penumbraCosNode=Cm(0).setGroup(wm),this.cutoffDistanceNode=Cm(0).setGroup(wm),this.decayExponentNode=Cm(0).setGroup(wm)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e){const{coneCosNode:t,penumbraCosNode:n}=this;return N_(t,n,e)}setupDirect(e){const{colorNode:t,cutoffDistanceNode:n,decayExponentNode:i,light:r}=this,s=this.getLightVector(e),a=s.normalize(),o=a.dot(EE(r)),l=this.getSpotAttenuation(o),u=s.length(),c=tw({lightDistance:u,cutoffDistance:n,decayExponent:i});let h=t.mul(l).mul(c);if(r.map){const t=function(e,t=Wv){const n=SE(e).mul(t);return n.xyz.div(n.w)}(r,e.context.positionWorld),n=bv(r.map,t.xy).onRenderUpdate((()=>r.map));h=t.mul(2).sub(1).abs().lessThan(1).all().select(h.mul(n),h)}return{lightColor:h,lightDirection:a}}}class Xw extends Ww{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e){const t=this.light.iesMap;let n=null;if(t&&!0===t.isTexture){const i=e.acos().mul(1/Math.PI);n=bv(t,am(i,0),0).r}else n=super.getSpotAttenuation(e);return n}}class qw extends ew{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class $w extends ew{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=TE(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Cm(new Pi).setGroup(wm)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:n,lightDirectionNode:i}=this,r=ey.dot(i).mul(.5).add(.5),s=A_(n,t,r);e.context.irradiance.addAssign(s)}}class Yw extends ew{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new un);this.lightProbe=Av(t)}update(e){const{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){const t=iw(ty,this.lightProbe);e.context.irradiance.addAssign(t)}}class Kw{parseFunction(){console.warn("Abstract function.")}}class Zw{constructor(e,t,n="",i=""){this.type=e,this.inputs=t,this.name=n,this.precision=i}getCode(){console.warn("Abstract function.")}}Zw.isNodeFunction=!0;const Qw=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,Jw=/[a-z_0-9]+/gi,eA="#pragma main";class tA extends Zw{constructor(e){const{type:t,inputs:n,name:i,precision:r,inputsCode:s,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(eA),n=-1!==t?e.slice(t+12):e,i=n.match(Qw);if(null!==i&&5===i.length){const r=i[4],s=[];let a=null;for(;null!==(a=Jw.exec(r));)s.push(a);const o=[];let l=0;for(;l0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==n||i){const r=this.getCacheNode("background",n,(()=>{if(!0===n.isCubeTexture||n.mapping===j||n.mapping===W||n.mapping===X){if(e.backgroundBlurriness>0||n.mapping===X)return AT(n);{let e;return e=!0===n.isCubeTexture?_y(n):bv(n),Pb(e)}}if(!0===n.isTexture)return bv(n,Yx.flipY()).setUpdateMatrix(!0);!0!==n.isColor&&console.error("WebGPUNodes: Unsupported background configuration.",n)}),i);t.backgroundNode=r,t.background=n,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,n,i=!1){const r=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let s=r.get(t);return(void 0===s||i)&&(s=n(),r.set(t,s)),s}updateFog(e){const t=this.get(e),n=e.fog;if(n){if(t.fog!==n){const e=this.getCacheNode("fog",n,(()=>{if(n.isFogExp2){const e=xy("color","color",n).setGroup(wm),t=xy("density","float",n).setGroup(wm);return vE(e,_E(t))}if(n.isFog){const e=xy("color","color",n).setGroup(wm),t=xy("near","float",n).setGroup(wm),i=xy("far","float",n).setGroup(wm);return vE(e,gE(t,i))}console.error("THREE.Renderer: Unsupported fog configuration.",n)}));t.fogNode=e,t.fog=n}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),n=e.environment;if(n){if(t.environment!==n){const e=this.getCacheNode("environment",n,(()=>!0===n.isCubeTexture?_y(n):!0===n.isTexture?bv(n):void console.error("Nodes: Unsupported environment configuration.",n)));t.environmentNode=e,t.environment=n}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,n=null,i=null,r=null){const s=this.nodeFrame;return s.renderer=e,s.scene=t,s.object=n,s.camera=i,s.material=r,s}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace}hasOutputChange(e){return iA.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,n=this.getOutputCacheKey(),i=bv(e,Yx).renderOutput(t.toneMapping,t.currentColorSpace);return iA.set(e,n),i}updateBefore(e){const t=e.getNodeBuilderState();for(const n of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(n)}updateAfter(e){const t=e.getNodeBuilderState();for(const n of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(n)}updateForCompute(e){const t=this.getNodeFrame(),n=this.getForCompute(e);for(const e of n.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(const e of n.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new Bw,this.nodeBuilderCache=new Map,this.cacheLib={}}}const oA=new Hr;class lA{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new Ot,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,n){const i=e.length;for(let r=0;r0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},r=new XRWebGLLayer(e,i,n);this._glBaseLayer=r,e.updateRenderState({baseLayer:r}),t.setPixelRatio(1),t.setSize(r.framebufferWidth,r.framebufferHeight,!1),this._xrRenderTarget=new gA(r.framebufferWidth,r.framebufferHeight,{format:ge,type:ne,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===r.ignoreDepthValues,resolveStencilBuffer:!1===r.ignoreDepthValues})}this.setFoveation(this.getFoveation()),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const n=e.near,i=e.far,r=this._cameraXR,s=this._cameraL,a=this._cameraR;r.near=a.near=s.near=n,r.far=a.far=s.far=i,this._currentDepthNear===r.near&&this._currentDepthFar===r.far||(t.updateRenderState({depthNear:r.near,depthFar:r.far}),this._currentDepthNear=r.near,this._currentDepthFar=r.far),s.layers.mask=2|e.layers.mask,a.layers.mask=4|e.layers.mask,r.layers.mask=s.layers.mask|a.layers.mask;const o=e.parent,l=r.cameras;xA(r,o);for(let e=0;e=0&&(n[s]=null,t[s].disconnect(r))}for(let i=0;i=n.length){n.push(r),s=e;break}if(null===n[e]){n[e]=r,s=e;break}}if(-1===s)break}const a=t[s];a&&a.connect(r)}}function MA(e,t){if(void 0===t)return;const n=this._cameraXR,i=this._renderer,r=i.backend,s=this._glBaseLayer,a=this.getReferenceSpace(),o=t.getViewerPose(a);if(this._xrFrame=t,null!==o){const e=o.views;null!==this._glBaseLayer&&r.setXRTarget(s.framebuffer);let t=!1;e.length!==n.cameras.length&&(n.cameras.length=0,t=!0);for(let i=0;i{await this.compileAsync(e,t);const i=this._renderLists.get(e,t),r=this._renderContexts.get(e,t,this._renderTarget),s=e.overrideMaterial||n.material,a=this._objects.get(n,s,e,t,i.lightsNode,r,r.clippingContext),{fragmentShader:o,vertexShader:l}=a.getNodeBuilderState();return{fragmentShader:o,vertexShader:l}}}}async init(){if(this._initialized)throw new Error("Renderer: Backend has already been initialized.");return null!==this._initPromise||(this._initPromise=new Promise((async(e,t)=>{let n=this.backend;try{await n.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=n=this._getFallback(e),await n.init(this)}catch(e){return void t(e)}}this._nodes=new aA(this,n),this._animation=new JT(this._nodes,this.info),this._attributes=new hM(n),this._background=new sw(this,this._nodes),this._geometries=new fM(this._attributes,this.info),this._textures=new FM(this,n,this.info),this._pipelines=new bM(n,this._nodes),this._bindings=new SM(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new rM(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new RM(this.lighting),this._bundles=new hA,this._renderContexts=new IM,this._animation.start(),this._initialized=!0,e(this)}))),this._initPromise}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,n=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const i=this._nodes.nodeFrame,r=i.renderId,s=this._currentRenderContext,a=this._currentRenderObjectFunction,o=this._compilationPromises,l=!0===e.isScene?e:EA;null===n&&(n=e);const u=this._renderTarget,c=this._renderContexts.get(n,t,u),h=this._activeMipmapLevel,d=[];this._currentRenderContext=c,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=d,i.renderId++,i.update(),c.depth=this.depth,c.stencil=this.stencil,c.clippingContext||(c.clippingContext=new lA),c.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,u);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p,c.clippingContext),n!==e&&n.traverseVisible((function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)})),p.finish(),null!==u){this._textures.updateRenderTarget(u,h);const e=this._textures.get(u);c.textures=e.textures,c.depthTexture=e.depthTexture}else c.textures=null,c.depthTexture=null;this._background.update(l,p,c);const f=p.opaque,m=p.transparent,g=p.transparentDoublePass,_=p.lightsNode;!0===this.opaque&&f.length>0&&this._renderObjects(f,t,l,_),!0===this.transparent&&m.length>0&&this._renderTransparents(m,g,t,l,_),i.renderId=r,this._currentRenderContext=s,this._currentRenderObjectFunction=a,this._compilationPromises=o,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(d)}async renderAsync(e,t){!1===this._initialized&&await this.init(),this._renderScene(e,t)}async waitForGPU(){await this.backend.waitForGPU()}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getColorBufferType(){return this._colorBufferType}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),console.error(t),this._isDeviceLost=!0}_renderBundle(e,t,n){const{bundleGroup:i,camera:r,renderList:s}=e,a=this._currentRenderContext,o=this._bundles.get(i,r),l=this.backend.get(o);void 0===l.renderContexts&&(l.renderContexts=new Set);const u=i.version!==l.version,c=!1===l.renderContexts.has(a)||u;if(l.renderContexts.add(a),c){this.backend.beginBundle(a),(void 0===l.renderObjects||u)&&(l.renderObjects=[]),this._currentRenderBundle=o;const e=s.opaque;!0===this.opaque&&e.length>0&&this._renderObjects(e,r,t,n),this._currentRenderBundle=null,this.backend.finishBundle(a,o),l.version=i.version}else{const{renderObjects:e}=l;for(let t=0,n=e.length;t>=h,p.viewportValue.height>>=h,p.viewportValue.minDepth=y,p.viewportValue.maxDepth=x,p.viewport=!1===p.viewportValue.equals(AA),p.scissorValue.copy(_).multiplyScalar(v).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(AA),p.scissorValue.width>>=h,p.scissorValue.height>>=h,p.clippingContext||(p.clippingContext=new lA),p.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,d),CA.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),RA.setFromProjectionMatrix(CA,f);const b=this._renderLists.get(e,t);if(b.begin(),this._projectObject(e,t,0,b,p.clippingContext),b.finish(),!0===this.sortObjects&&b.sort(this._opaqueSort,this._transparentSort),null!==d){this._textures.updateRenderTarget(d,h);const e=this._textures.get(d);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=d,p.depth=d.depthBuffer,p.stencil=d.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=this.domElement.width,p.height=this.domElement.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=h,p.height>>=h,p.activeCubeFace=c,p.activeMipmapLevel=h,p.occlusionQueryCount=b.occlusionQueryCount,this._background.update(l,b,p),this.backend.beginRender(p);const{bundles:S,lightsNode:T,transparentDoublePass:M,transparent:E,opaque:w}=b;return S.length>0&&this._renderBundles(S,l,T),!0===this.opaque&&w.length>0&&this._renderObjects(w,t,l,T),!0===this.transparent&&E.length>0&&this._renderTransparents(E,M,t,l,T),this.backend.finishRender(p),r.renderId=s,this._currentRenderContext=a,this._currentRenderObjectFunction=o,null!==i&&(this.setRenderTarget(u,c,h),this._renderOutput(d)),l.onAfterRender(this,e,t,d),p}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const n=this.autoClear,i=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=n,this.xr.enabled=i}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,n){this._width=e,this._height=t,this._pixelRatio=n,this.domElement.width=Math.floor(e*n),this.domElement.height=Math.floor(t*n),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize()}setSize(e,t,n=!0){this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===n&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize()}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,n,i){const r=this._scissor;e.isVector4?r.copy(e):r.set(e,t,n,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,n,i,r=0,s=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,n,i),a.minDepth=r,a.maxDepth=s}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,n=!0){if(!1===this._initialized)return console.warn("THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead."),this.clearAsync(e,t,n);const i=this._renderTarget||this._getFrameBufferTarget();let r=null;if(null!==i){this._textures.updateRenderTarget(i);const e=this._textures.get(i);r=this._renderContexts.getForClear(i),r.textures=e.textures,r.depthTexture=e.depthTexture,r.width=e.width,r.height=e.height,r.renderTarget=i,r.depth=i.depthBuffer,r.stencil=i.stencilBuffer,r.clearColorValue=this.backend.getClearColor()}this.backend.clear(e,t,n,r),null!==i&&null===this._renderTarget&&this._renderOutput(i)}clearColor(){return this.clear(!0,!1,!1)}clearDepth(){return this.clear(!1,!0,!1)}clearStencil(){return this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,n=!0){!1===this._initialized&&await this.init(),this.clear(e,t,n)}async clearColorAsync(){this.clearAsync(!0,!1,!1)}async clearDepthAsync(){this.clearAsync(!1,!0,!1)}async clearStencilAsync(){this.clearAsync(!1,!1,!0)}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:at}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),null!==this._frameBufferTarget&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach((e=>{null!==e&&e.dispose()})),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,n=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=n}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,n=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const i=this.backend,r=this._pipelines,s=this._bindings,a=this._nodes,o=Array.isArray(e)?e:[e];if(void 0===o[0]||!0!==o[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const t of o){if(!1===r.has(t)){const e=()=>{t.removeEventListener("dispose",e),r.delete(t),s.delete(t),a.delete(t)};t.addEventListener("dispose",e);const n=t.onInitFunction;null!==n&&n.call(t,{renderer:this})}a.updateForCompute(t),s.updateForCompute(t);const n=s.getForCompute(t),o=r.getForCompute(t,n);i.compute(e,t,n,o)}i.finishCompute(e),t.renderId=n}async computeAsync(e){!1===this._initialized&&await this.init(),this.compute(e)}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){return!1===this._initialized?(console.warn("THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead."),!1):this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){!1===this._initialized&&await this.init(),this._textures.updateTexture(e)}initTexture(e){!1===this._initialized&&console.warn("THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead."),this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=NA.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void console.error("THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.");t=NA.copy(t).floor()}else t=NA.set(0,0,e.image.width,e.image.height);let n,i=this._currentRenderContext;null!==i?n=i.renderTarget:(n=this._renderTarget||this._getFrameBufferTarget(),null!==n&&(this._textures.updateRenderTarget(n),i=this._textures.get(n))),this._textures.updateTexture(e,{renderTarget:n}),this.backend.copyFramebufferToTexture(e,i,t)}copyTextureToTexture(e,t,n=null,i=null,r=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,n,i,r)}async readRenderTargetPixelsAsync(e,t,n,i,r,s=0,a=0){return this.backend.copyTextureToBuffer(e.textures[s],t,n,i,r,a)}_projectObject(e,t,n,i,r){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder,e.isClippingGroup&&e.enabled&&(r=r.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){if(!e.frustumCulled||RA.intersectsSprite(e)){!0===this.sortObjects&&NA.setFromMatrixPosition(e.matrixWorld).applyMatrix4(CA);const{geometry:t,material:s}=e;s.visible&&i.push(e,t,s,n,NA.z,null,r)}}else if(e.isLineLoop)console.error("THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||RA.intersectsObject(e))){const{geometry:t,material:s}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),NA.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(CA)),Array.isArray(s)){const a=t.groups;for(let o=0,l=a.length;o0){for(const{material:e}of t)e.side=1;this._renderObjects(t,n,i,r,"backSide");for(const{material:e}of t)e.side=0;this._renderObjects(e,n,i,r);for(const{material:e}of t)e.side=2}else this._renderObjects(e,n,i,r)}_renderObjects(e,t,n,i,r=null){for(let s=0,a=e.length;s0,e.isShadowPassMaterial&&(e.side=null===r.shadowSide?r.side:r.shadowSide,r.depthNode&&r.depthNode.isNode&&(h=e.depthNode,e.depthNode=r.depthNode),r.castShadowNode&&r.castShadowNode.isNode&&(c=e.colorNode,e.colorNode=r.castShadowNode)),r=e}!0===r.transparent&&2===r.side&&!1===r.forceSinglePass?(r.side=1,this._handleObjectFunction(e,r,t,n,a,s,o,"backSide"),r.side=0,this._handleObjectFunction(e,r,t,n,a,s,o,l),r.side=2):this._handleObjectFunction(e,r,t,n,a,s,o,l),void 0!==u&&(t.overrideMaterial.positionNode=u),void 0!==h&&(t.overrideMaterial.depthNode=h),void 0!==c&&(t.overrideMaterial.colorNode=c),e.onAfterRender(this,t,n,i,r,s)}_renderObjectDirect(e,t,n,i,r,s,a,o){const l=this._objects.get(e,t,n,i,r,this._currentRenderContext,a,o);l.drawRange=e.geometry.drawRange,l.group=s;const u=this._nodes.needsRefresh(l);if(u&&(this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l)),this._pipelines.updateForRender(l),null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(l),l.bundle=this._currentRenderBundle.bundleGroup}this.backend.draw(l,this.info),u&&this._nodes.updateAfter(l)}_createObjectPipeline(e,t,n,i,r,s,a,o){const l=this._objects.get(e,t,n,i,r,this._currentRenderContext,a,o);l.drawRange=e.geometry.drawRange,l.group=s,this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l),this._pipelines.getForRender(l,this._compilationPromises),this._nodes.updateAfter(l)}get compile(){return this.compileAsync}}class DA{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}class UA extends DA{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t}get byteLength(){return(e=this._buffer.byteLength)+(cM-e%cM)%cM;var e}get buffer(){return this._buffer}update(){return!0}}class LA extends UA{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let IA=0;class OA extends LA{constructor(e,t){super("UniformBuffer_"+IA++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class FA extends LA{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){let e=0;for(let t=0,n=this.uniforms.length;t0?i:"";t=`${e.name} {\n\t${n} ${r.name}[${s}];\n};\n`}else{t=`${this.getVectorType(r.type)} ${this.getPropertyName(r,e)};`,s=!0}const a=r.node.precision;if(null!==a&&(t=XA[a]+" "+t),s){t="\t"+t;const e=r.groupNode.name;(i[e]||(i[e]=[])).push(t)}else t="uniform "+t,n.push(t)}let r="";for(const t in i){const n=i[t];r+=this._getGLSLUniformStruct(e+"_"+t,n.join("\n"))+"\n"}return r+=n.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==ae){let n=e;e.isInterleavedBufferAttribute&&(n=e.data);const i=n.array;!1==(i instanceof Uint32Array||i instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let n=0;for(const i of e)t+=`layout( location = ${n++} ) in ${i.type} ${i.name};\n`}return t}getStructMembers(e){const t=[];for(const n of e.members)t.push(`\t${n.type} ${n.name};`);return t.join("\n")}getStructs(e){const t=[],n=this.structs[e],i=[];for(const e of n)if(e.output)for(const t of e.members)i.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let n="struct "+e.name+" {\n";n+=this.getStructMembers(e),n+="\n};\n",t.push(n)}return 0===i.length&&i.push("layout( location = 0 ) out vec4 fragColor;"),"\n"+i.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const n=this.varyings;if("vertex"===e||"compute"===e)for(const i of n){"compute"===e&&(i.needsInterpolation=!0);const n=this.getType(i.type);if(i.needsInterpolation){t+=`${n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":""} out ${n} ${i.name};\n`}else t+=`${n} ${i.name};\n`}else if("fragment"===e)for(const e of n)if(e.needsInterpolation){const n=this.getType(e.type);t+=`${n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":""}in ${n} ${e.name};\n`}for(const n of this.builtins[e])t+=`${n};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce(((e,t)=>e*t),1)}u`}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,n=this.shaderStage){const i=this.extensions[n]||(this.extensions[n]=new Map);!1===i.has(e)&&i.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if("vertex"===e){const t=this.renderer.backend.extensions;this.object.isBatchedMesh&&t.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const n=this.extensions[e];if(void 0!==n)for(const{name:e,behavior:i}of n.values())t.push(`#extension ${e} : ${i}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=qA[e];if(void 0===t){let n;switch(t=!1,e){case"float32Filterable":n="OES_texture_float_linear";break;case"clipDistance":n="WEBGL_clip_cull_distance"}if(void 0!==n){const e=this.renderer.backend.extensions;e.has(n)&&(e.get(n),t=!0)}qA[e]=t}return t}isFlipY(){return!0}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let n=0;n0&&(n+="\n"),n+=`\t// flow -> ${s}\n\t`),n+=`${i.code}\n\t`,e===r&&"compute"!==t&&(n+="// result\n\t","vertex"===t?(n+="gl_Position = ",n+=`${i.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(n+="fragColor = ",n+=`${i.result};`)))}const s=e[t];s.extensions=this.getExtensions(t),s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.vars=this.getVars(t),s.structs=this.getStructs(t),s.codes=this.getCodes(t),s.transforms=this.getTransforms(t),s.flow=n}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,n,i=null){const r=super.getUniformFromNode(e,t,n,i),s=this.getDataFromNode(e,n,this.globalCache);let a=s.uniformGPU;if(void 0===a){const i=e.groupNode,o=i.name,l=this.getBindGroupArray(o,n);if("texture"===t)a=new VA(r.name,r.node,i),l.push(a);else if("cubeTexture"===t)a=new HA(r.name,r.node,i),l.push(a);else if("texture3D"===t)a=new jA(r.name,r.node,i),l.push(a);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,r.name=`buffer${e.id}`;const t=new OA(e,i);t.name=e.name,l.push(t),a=t}else{const e=this.uniformGroups[n]||(this.uniformGroups[n]={});let s=e[o];void 0===s&&(s=new kA(n+"_"+o,i),e[o]=s,l.push(s)),a=this.getNodeUniform(r,t),s.addUniform(a)}s.uniformGPU=a}return r}}let KA=null,ZA=null;class QA{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={render:null,compute:null}}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}createSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void Vt("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return void Vt(`WebGPURenderer: No timestamp query pool for type '${e}' found.`);const n=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=n,n}async waitForGPU(){}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return KA=KA||new It,this.renderer.getDrawingBufferSize(KA)}setScissorTest(){}getClearColor(){const e=this.renderer;return ZA=ZA||new BM,e.getClearColor(ZA),ZA.getRGB(ZA),ZA}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:zt(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${s} webgpu`),this.domElement=e),e}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}dispose(){}}let JA,eR,tR=0;class nR{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[1^this.activeBufferIndex]}switchBuffers(){this.activeBufferIndex^=1}}class iR{constructor(e){this.backend=e}createAttribute(e,t){const n=this.backend,{gl:i}=n,r=e.array,s=e.usage||i.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=n.get(a);let l,u=o.bufferGPU;if(void 0===u&&(u=this._createBuffer(i,t,r,s),o.bufferGPU=u,o.bufferType=t,o.version=a.version),r instanceof Float32Array)l=i.FLOAT;else if(r instanceof Uint16Array)l=e.isFloat16BufferAttribute?i.HALF_FLOAT:i.UNSIGNED_SHORT;else if(r instanceof Int16Array)l=i.SHORT;else if(r instanceof Uint32Array)l=i.UNSIGNED_INT;else if(r instanceof Int32Array)l=i.INT;else if(r instanceof Int8Array)l=i.BYTE;else if(r instanceof Uint8Array)l=i.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);l=i.UNSIGNED_BYTE}let c={bufferGPU:u,bufferType:t,type:l,byteLength:r.byteLength,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:l===i.INT||l===i.UNSIGNED_INT||e.gpuType===ae,id:tR++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,s);c=new nR(c,e)}n.set(e,c)}updateAttribute(e){const t=this.backend,{gl:n}=t,i=e.array,r=e.isInterleavedBufferAttribute?e.data:e,s=t.get(r),a=s.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(n.bindBuffer(a,s.bufferGPU),0===o.length)n.bufferSubData(a,0,i);else{for(let e=0,t=o.length;e1?this.enable(i.SAMPLE_ALPHA_TO_COVERAGE):this.disable(i.SAMPLE_ALPHA_TO_COVERAGE),n>0&&this.currentClippingPlanes!==n){const e=12288;for(let t=0;t<8;t++)t{!function r(){const s=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(s===e.WAIT_FAILED)return e.deleteSync(t),void i();s!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),n()):requestAnimationFrame(r)}()}))}}let aR,oR,lR,uR=!1;class cR{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===uR&&(this._init(),uR=!0)}_init(){const e=this.gl;aR={[q]:e.REPEAT,[$]:e.CLAMP_TO_EDGE,[Y]:e.MIRRORED_REPEAT},oR={[K]:e.NEAREST,[Z]:e.NEAREST_MIPMAP_NEAREST,[Q]:e.NEAREST_MIPMAP_LINEAR,[J]:e.LINEAR,[ee]:e.LINEAR_MIPMAP_NEAREST,[te]:e.LINEAR_MIPMAP_LINEAR},lR={[ct]:e.NEVER,[_t]:e.ALWAYS,[ht]:e.LESS,[pt]:e.LEQUAL,[dt]:e.EQUAL,[gt]:e.GEQUAL,[ft]:e.GREATER,[mt]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let n;return n=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:!0===e.isData3DTexture?t.TEXTURE_3D:t.TEXTURE_2D,n}getInternalFormat(e,t,n,i,r=!1){const{gl:s,extensions:a}=this;if(null!==e){if(void 0!==s[e])return s[e];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+e+"'")}let o=t;return t===s.RED&&(n===s.FLOAT&&(o=s.R32F),n===s.HALF_FLOAT&&(o=s.R16F),n===s.UNSIGNED_BYTE&&(o=s.R8),n===s.UNSIGNED_SHORT&&(o=s.R16),n===s.UNSIGNED_INT&&(o=s.R32UI),n===s.BYTE&&(o=s.R8I),n===s.SHORT&&(o=s.R16I),n===s.INT&&(o=s.R32I)),t===s.RED_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.R8UI),n===s.UNSIGNED_SHORT&&(o=s.R16UI),n===s.UNSIGNED_INT&&(o=s.R32UI),n===s.BYTE&&(o=s.R8I),n===s.SHORT&&(o=s.R16I),n===s.INT&&(o=s.R32I)),t===s.RG&&(n===s.FLOAT&&(o=s.RG32F),n===s.HALF_FLOAT&&(o=s.RG16F),n===s.UNSIGNED_BYTE&&(o=s.RG8),n===s.UNSIGNED_SHORT&&(o=s.RG16),n===s.UNSIGNED_INT&&(o=s.RG32UI),n===s.BYTE&&(o=s.RG8I),n===s.SHORT&&(o=s.RG16I),n===s.INT&&(o=s.RG32I)),t===s.RG_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RG8UI),n===s.UNSIGNED_SHORT&&(o=s.RG16UI),n===s.UNSIGNED_INT&&(o=s.RG32UI),n===s.BYTE&&(o=s.RG8I),n===s.SHORT&&(o=s.RG16I),n===s.INT&&(o=s.RG32I)),t===s.RGB&&(n===s.FLOAT&&(o=s.RGB32F),n===s.HALF_FLOAT&&(o=s.RGB16F),n===s.UNSIGNED_BYTE&&(o=s.RGB8),n===s.UNSIGNED_SHORT&&(o=s.RGB16),n===s.UNSIGNED_INT&&(o=s.RGB32UI),n===s.BYTE&&(o=s.RGB8I),n===s.SHORT&&(o=s.RGB16I),n===s.INT&&(o=s.RGB32I),n===s.UNSIGNED_BYTE&&(o=i===st&&!1===r?s.SRGB8:s.RGB8),n===s.UNSIGNED_SHORT_5_6_5&&(o=s.RGB565),n===s.UNSIGNED_SHORT_5_5_5_1&&(o=s.RGB5_A1),n===s.UNSIGNED_SHORT_4_4_4_4&&(o=s.RGB4),n===s.UNSIGNED_INT_5_9_9_9_REV&&(o=s.RGB9_E5)),t===s.RGB_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RGB8UI),n===s.UNSIGNED_SHORT&&(o=s.RGB16UI),n===s.UNSIGNED_INT&&(o=s.RGB32UI),n===s.BYTE&&(o=s.RGB8I),n===s.SHORT&&(o=s.RGB16I),n===s.INT&&(o=s.RGB32I)),t===s.RGBA&&(n===s.FLOAT&&(o=s.RGBA32F),n===s.HALF_FLOAT&&(o=s.RGBA16F),n===s.UNSIGNED_BYTE&&(o=s.RGBA8),n===s.UNSIGNED_SHORT&&(o=s.RGBA16),n===s.UNSIGNED_INT&&(o=s.RGBA32UI),n===s.BYTE&&(o=s.RGBA8I),n===s.SHORT&&(o=s.RGBA16I),n===s.INT&&(o=s.RGBA32I),n===s.UNSIGNED_BYTE&&(o=i===st&&!1===r?s.SRGB8_ALPHA8:s.RGBA8),n===s.UNSIGNED_SHORT_4_4_4_4&&(o=s.RGBA4),n===s.UNSIGNED_SHORT_5_5_5_1&&(o=s.RGB5_A1)),t===s.RGBA_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RGBA8UI),n===s.UNSIGNED_SHORT&&(o=s.RGBA16UI),n===s.UNSIGNED_INT&&(o=s.RGBA32UI),n===s.BYTE&&(o=s.RGBA8I),n===s.SHORT&&(o=s.RGBA16I),n===s.INT&&(o=s.RGBA32I)),t===s.DEPTH_COMPONENT&&(n===s.UNSIGNED_SHORT&&(o=s.DEPTH_COMPONENT16),n===s.UNSIGNED_INT&&(o=s.DEPTH_COMPONENT24),n===s.FLOAT&&(o=s.DEPTH_COMPONENT32F)),t===s.DEPTH_STENCIL&&n===s.UNSIGNED_INT_24_8&&(o=s.DEPTH24_STENCIL8),o!==s.R16F&&o!==s.R32F&&o!==s.RG16F&&o!==s.RG32F&&o!==s.RGBA16F&&o!==s.RGBA32F||a.get("EXT_color_buffer_float"),o}setTextureParameters(e,t){const{gl:n,extensions:i,backend:r}=this;n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,n.NONE),n.texParameteri(e,n.TEXTURE_WRAP_S,aR[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,aR[t.wrapT]),e!==n.TEXTURE_3D&&e!==n.TEXTURE_2D_ARRAY||n.texParameteri(e,n.TEXTURE_WRAP_R,aR[t.wrapR]),n.texParameteri(e,n.TEXTURE_MAG_FILTER,oR[t.magFilter]);const s=void 0!==t.mipmaps&&t.mipmaps.length>0,a=t.minFilter===J&&s?te:t.minFilter;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,oR[a]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,lR[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===K)return;if(t.minFilter!==Q&&t.minFilter!==te)return;if(t.type===le&&!1===i.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const s=i.get("EXT_texture_filter_anisotropic");n.texParameterf(e,s.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,r.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:n,defaultTextures:i}=this,r=this.getGLTextureType(e);let s=i[r];void 0===s&&(s=t.createTexture(),n.state.bindTexture(r,s),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),i[r]=s),n.set(e,{textureGPU:s,glTextureType:r,isDefault:!0})}createTexture(e,t){const{gl:n,backend:i}=this,{levels:r,width:s,height:a,depth:o}=t,l=i.utils.convert(e.format,e.colorSpace),u=i.utils.convert(e.type),c=this.getInternalFormat(e.internalFormat,l,u,e.colorSpace,e.isVideoTexture),h=n.createTexture(),d=this.getGLTextureType(e);i.state.bindTexture(d,h),this.setTextureParameters(d,e),e.isDataArrayTexture||e.isCompressedArrayTexture?n.texStorage3D(n.TEXTURE_2D_ARRAY,r,c,s,a,o):e.isData3DTexture?n.texStorage3D(n.TEXTURE_3D,r,c,s,a,o):e.isVideoTexture||n.texStorage2D(d,r,c,s,a),i.set(e,{textureGPU:h,glTextureType:d,glFormat:l,glType:u,glInternalFormat:c})}copyBufferToTexture(e,t){const{gl:n,backend:i}=this,{textureGPU:r,glTextureType:s,glFormat:a,glType:o}=i.get(t),{width:l,height:u}=t.source.data;n.bindBuffer(n.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(s,r),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.texSubImage2D(s,0,0,0,l,u,a,o,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:n}=this,{width:i,height:r}=t,{textureGPU:s,glTextureType:a,glFormat:o,glType:l,glInternalFormat:u}=this.backend.get(e);if(e.isRenderTargetTexture||void 0===s)return;const c=e=>e.isDataTexture?e.image.data:"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||e instanceof OffscreenCanvas?e:e.data;if(this.backend.state.bindTexture(a,s),this.setTextureParameters(a,e),e.isCompressedTexture){const i=e.mipmaps,r=t.image;for(let t=0;t0,h=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(c){const n=0!==a||0!==o;let c,d;if(!0===e.isDepthTexture?(c=i.DEPTH_BUFFER_BIT,d=i.DEPTH_ATTACHMENT,t.stencil&&(c|=i.STENCIL_BUFFER_BIT)):(c=i.COLOR_BUFFER_BIT,d=i.COLOR_ATTACHMENT0),n){const e=this.backend.get(t.renderTarget),n=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;r.bindFramebuffer(i.DRAW_FRAMEBUFFER,n),r.bindFramebuffer(i.READ_FRAMEBUFFER,d);const p=h-o-u;i.blitFramebuffer(a,p,a+l,p+u,a,p,a+l,p+u,c,i.NEAREST),r.bindFramebuffer(i.READ_FRAMEBUFFER,n),r.bindTexture(i.TEXTURE_2D,s),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,p,l,u),r.unbindTexture()}else{const e=i.createFramebuffer();r.bindFramebuffer(i.DRAW_FRAMEBUFFER,e),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,d,i.TEXTURE_2D,s,0),i.blitFramebuffer(0,0,l,u,0,0,l,u,c,i.NEAREST),i.deleteFramebuffer(e)}}else r.bindTexture(i.TEXTURE_2D,s),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,h-u-o,l,u),r.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,n,i=!1){const{gl:r}=this,s=t.renderTarget,{depthTexture:a,depthBuffer:o,stencilBuffer:l,width:u,height:c}=s;if(r.bindRenderbuffer(r.RENDERBUFFER,e),o&&!l){let t=r.DEPTH_COMPONENT24;if(!0===i){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(r.RENDERBUFFER,s.samples,t,u,c)}else n>0?(a&&a.isDepthTexture&&a.type===r.FLOAT&&(t=r.DEPTH_COMPONENT32F),r.renderbufferStorageMultisample(r.RENDERBUFFER,n,t,u,c)):r.renderbufferStorage(r.RENDERBUFFER,t,u,c);r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,e)}else o&&l&&(n>0?r.renderbufferStorageMultisample(r.RENDERBUFFER,n,r.DEPTH24_STENCIL8,u,c):r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,u,c),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,e))}async copyTextureToBuffer(e,t,n,i,r,s){const{backend:a,gl:o}=this,{textureGPU:l,glFormat:u,glType:c}=this.backend.get(e),h=o.createFramebuffer();o.bindFramebuffer(o.READ_FRAMEBUFFER,h);const d=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+s:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,d,l,0);const p=this._getTypedArrayType(c),f=i*r*this._getBytesPerTexel(c,u),m=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.bufferData(o.PIXEL_PACK_BUFFER,f,o.STREAM_READ),o.readPixels(t,n,i,r,u,c,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const g=new p(f/p.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,g),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteFramebuffer(h),g}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:n}=this;let i=0;return e===n.UNSIGNED_BYTE&&(i=1),e!==n.UNSIGNED_SHORT_4_4_4_4&&e!==n.UNSIGNED_SHORT_5_5_5_1&&e!==n.UNSIGNED_SHORT_5_6_5&&e!==n.UNSIGNED_SHORT&&e!==n.HALF_FLOAT||(i=2),e!==n.UNSIGNED_INT&&e!==n.FLOAT||(i=4),t===n.RGBA?4*i:t===n.RGB?3*i:t===n.ALPHA?i:void 0}}class hR{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return void 0===t&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class dR{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const pR={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBKIT_WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-bc",EXT_texture_compression_bptc:"texture-compression-bptc",EXT_disjoint_timer_query_webgl2:"timestamp-query"};class fR{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){const{gl:n,mode:i,object:r,type:s,info:a,index:o}=this;0!==o?n.drawElements(i,t,s,e):n.drawArrays(i,e,t),a.update(r,t,1)}renderInstances(e,t,n){const{gl:i,mode:r,type:s,index:a,object:o,info:l}=this;0!==n&&(0!==a?i.drawElementsInstanced(r,t,s,e,n):i.drawArraysInstanced(r,e,t,n),l.update(o,t,n))}renderMultiDraw(e,t,n){const{extensions:i,mode:r,object:s,info:a}=this;if(0===n)return;const o=i.get("WEBGL_multi_draw");if(null===o)for(let i=0;ithis.maxQueries)return Vt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e.id,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(null==t)return;if(null!==this.activeQuery)return;const n=this.queries[t];if(n)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,n),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){console.error("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){console.error("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=[];for(const[t,n]of this.queryStates)if("ended"===n){const n=this.queries[t];e.push(this.resolveQuery(n))}if(0===e.length)return this.lastValue;const t=(await Promise.all(e)).reduce(((e,t)=>e+t),0);return this.lastValue=t,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,t}catch(e){return console.error("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise((t=>{if(this.isDisposed)return void t(this.lastValue);let n,i=!1;const r=e=>{i||(i=!0,n&&(clearTimeout(n),n=null),t(e))},s=()=>{if(this.isDisposed)r(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void r(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(n=setTimeout(s,1));const i=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(i)/1e6)}catch(e){console.error("Error checking query:",e),t(this.lastValue)}};s()}))}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class _R extends QA{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this.trackTimestamp=!0===e.trackTimestamp,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,n={antialias:e.samples>0,alpha:!0,depth:e.depth,stencil:e.stencil},i=void 0!==t.context?t.context:e.domElement.getContext("webgl2",n);function r(t){t.preventDefault();const n={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(n)}this._onContextLost=r,e.domElement.addEventListener("webglcontextlost",r,!1),this.gl=i,this.extensions=new hR(this),this.capabilities=new dR(this),this.attributeUtils=new iR(this),this.textureUtils=new cR(this),this.bufferRenderer=new fR(this),this.state=new rR(this),this.utils=new sR(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile")}get coordinateSystem(){return bt}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async waitForGPU(){await this.utils._clientWaitAsync()}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,n=null){const i=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:i.RGBA8}),null!==n){const t=e.stencilBuffer?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:n,glInternalFormat:t}),e.autoAllocateDepthBuffer=!1,!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&console.warn("THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided")}}initTimestampQuery(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t]||(this.timestampQueryPool[t]=new gR(this.gl,t,2048));const n=this.timestampQueryPool[t];null!==n.allocateQueriesForContext(e)&&n.beginQuery(e)}prepareTimestampBuffer(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t].endQuery(e)}getContext(){return this.gl}beginRender(e){const{state:t,gl:n}=this,i=this.get(e);if(e.viewport?this.updateViewport(e):t.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),e.scissor){const{x:n,y:i,width:r,height:s}=e.scissorValue;t.scissor(n,e.height-s-i,r,s)}this.initTimestampQuery(e),i.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const r=e.occlusionQueryCount;r>0&&(i.currentOcclusionQueries=i.occlusionQueries,i.currentOcclusionQueryObjects=i.occlusionQueryObjects,i.lastOcclusionObject=null,i.occlusionQueries=new Array(r),i.occlusionQueryObjects=new Array(r),i.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:n}=this,i=this.get(e),r=i.previousContext;n.resetVertexState();const s=e.occlusionQueryCount;s>0&&(s>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(null!==a)for(let e=0;e0&&!1===this._useMultisampledRTT(e.renderTarget)){const r=i.framebuffers[e.getCacheKey()],s=t.COLOR_BUFFER_BIT,a=i.msaaFrameBuffer,o=e.textures;n.bindFramebuffer(t.READ_FRAMEBUFFER,a),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,r);for(let n=0;n{let a=0;for(let t=0;t{t.isBatchedMesh?null!==t._multiDrawInstances?(Vt("THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),_.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?_.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):Vt("THREE.WebGLRenderer: WEBGL_multi_draw not supported."):y>1?_.renderInstances(x,v,y):_.render(x,v)};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const n=this.get(e.camera),i=e.camera.cameras,r=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===n.indexesGPU||n.indexesGPU.length!==i.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let n=0,r=i.length;n{const r=this.parallel,s=()=>{n.getProgramParameter(a,r.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),t()):requestAnimationFrame(s)};s()}));t.push(r)}else this._completeCompile(e,i)}_handleSource(e,t){const n=e.split("\n"),i=[],r=Math.max(t-6,0),s=Math.min(t+6,n.length);for(let e=r;e":" "} ${r}: ${n[e]}`)}return i.join("\n")}_getShaderErrors(e,t,n){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=e.getShaderInfoLog(t).trim();if(i&&""===r)return"";const s=/ERROR: 0:(\d+)/.exec(r);if(s){const i=parseInt(s[1]);return n.toUpperCase()+"\n\n"+r+"\n\n"+this._handleSource(e.getShaderSource(t),i)}return r}_logProgramError(e,t,n){if(this.renderer.debug.checkShaderErrors){const i=this.gl,r=i.getProgramInfoLog(e).trim();if(!1===i.getProgramParameter(e,i.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(i,e,n,t);else{const s=this._getShaderErrors(i,n,"vertex"),a=this._getShaderErrors(i,t,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+s+"\n"+a)}else""!==r&&console.warn("THREE.WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:n,gl:i}=this,r=this.get(t),{programGPU:s,fragmentShader:a,vertexShader:o}=r;!1===i.getProgramParameter(s,i.LINK_STATUS)&&this._logProgramError(s,a,o),n.useProgram(s);const l=e.getBindings();this._setupBindings(l,s),this.set(t,{programGPU:s})}createComputePipeline(e,t){const{state:n,gl:i}=this,r={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(r);const{computeProgram:s}=e,a=i.createProgram(),o=this.get(r).shaderGPU,l=this.get(s).shaderGPU,u=s.transforms,c=[],h=[];for(let e=0;epR[t]===e)),n=this.extensions;for(let e=0;e0&&!1===_){if(void 0===f){const i=[];f=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,f);const r=[],u=e.textures;for(let n=0;n0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e.autoAllocateDepthBuffer}dispose(){const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const vR="point-list",yR="line-list",xR="line-strip",bR="triangle-list",SR="triangle-strip",TR="never",MR="less",ER="equal",wR="less-equal",AR="greater",RR="not-equal",CR="greater-equal",NR="always",PR="store",DR="load",UR="clear",LR="ccw",IR="none",OR="front",FR="back",BR="uint16",kR="uint32",zR={R8Unorm:"r8unorm",R8Snorm:"r8snorm",R8Uint:"r8uint",R8Sint:"r8sint",R16Uint:"r16uint",R16Sint:"r16sint",R16Float:"r16float",RG8Unorm:"rg8unorm",RG8Snorm:"rg8snorm",RG8Uint:"rg8uint",RG8Sint:"rg8sint",R32Uint:"r32uint",R32Sint:"r32sint",R32Float:"r32float",RG16Uint:"rg16uint",RG16Sint:"rg16sint",RG16Float:"rg16float",RGBA8Unorm:"rgba8unorm",RGBA8UnormSRGB:"rgba8unorm-srgb",RGBA8Snorm:"rgba8snorm",RGBA8Uint:"rgba8uint",RGBA8Sint:"rgba8sint",BGRA8Unorm:"bgra8unorm",BGRA8UnormSRGB:"bgra8unorm-srgb",RGB9E5UFloat:"rgb9e5ufloat",RGB10A2Unorm:"rgb10a2unorm",RG32Uint:"rg32uint",RG32Sint:"rg32sint",RG32Float:"rg32float",RGBA16Uint:"rgba16uint",RGBA16Sint:"rgba16sint",RGBA16Float:"rgba16float",RGBA32Uint:"rgba32uint",RGBA32Sint:"rgba32sint",RGBA32Float:"rgba32float",Depth16Unorm:"depth16unorm",Depth24Plus:"depth24plus",Depth24PlusStencil8:"depth24plus-stencil8",Depth32Float:"depth32float",Depth32FloatStencil8:"depth32float-stencil8",BC1RGBAUnorm:"bc1-rgba-unorm",BC1RGBAUnormSRGB:"bc1-rgba-unorm-srgb",BC2RGBAUnorm:"bc2-rgba-unorm",BC2RGBAUnormSRGB:"bc2-rgba-unorm-srgb",BC3RGBAUnorm:"bc3-rgba-unorm",BC3RGBAUnormSRGB:"bc3-rgba-unorm-srgb",BC4RUnorm:"bc4-r-unorm",BC5RGUnorm:"bc5-rg-unorm",BC5RGSnorm:"bc5-rg-snorm",BC6HRGBUFloat:"bc6h-rgb-ufloat",BC6HRGBFloat:"bc6h-rgb-float",BC7RGBAUnorm:"bc7-rgba-unorm",BC7RGBAUnormSRGB:"bc7-rgba-srgb",ETC2RGB8Unorm:"etc2-rgb8unorm",ETC2RGB8UnormSRGB:"etc2-rgb8unorm-srgb",ETC2RGB8A1Unorm:"etc2-rgb8a1unorm",ETC2RGB8A1UnormSRGB:"etc2-rgb8a1unorm-srgb",ETC2RGBA8Unorm:"etc2-rgba8unorm",ETC2RGBA8UnormSRGB:"etc2-rgba8unorm-srgb",EACR11Unorm:"eac-r11unorm",EACR11Snorm:"eac-r11snorm",EACRG11Unorm:"eac-rg11unorm",EACRG11Snorm:"eac-rg11snorm",ASTC4x4Unorm:"astc-4x4-unorm",ASTC4x4UnormSRGB:"astc-4x4-unorm-srgb",ASTC5x4Unorm:"astc-5x4-unorm",ASTC5x4UnormSRGB:"astc-5x4-unorm-srgb",ASTC5x5Unorm:"astc-5x5-unorm",ASTC5x5UnormSRGB:"astc-5x5-unorm-srgb",ASTC6x5Unorm:"astc-6x5-unorm",ASTC6x5UnormSRGB:"astc-6x5-unorm-srgb",ASTC6x6Unorm:"astc-6x6-unorm",ASTC6x6UnormSRGB:"astc-6x6-unorm-srgb",ASTC8x5Unorm:"astc-8x5-unorm",ASTC8x5UnormSRGB:"astc-8x5-unorm-srgb",ASTC8x6Unorm:"astc-8x6-unorm",ASTC8x6UnormSRGB:"astc-8x6-unorm-srgb",ASTC8x8Unorm:"astc-8x8-unorm",ASTC8x8UnormSRGB:"astc-8x8-unorm-srgb",ASTC10x5Unorm:"astc-10x5-unorm",ASTC10x5UnormSRGB:"astc-10x5-unorm-srgb",ASTC10x6Unorm:"astc-10x6-unorm",ASTC10x6UnormSRGB:"astc-10x6-unorm-srgb",ASTC10x8Unorm:"astc-10x8-unorm",ASTC10x8UnormSRGB:"astc-10x8-unorm-srgb",ASTC10x10Unorm:"astc-10x10-unorm",ASTC10x10UnormSRGB:"astc-10x10-unorm-srgb",ASTC12x10Unorm:"astc-12x10-unorm",ASTC12x10UnormSRGB:"astc-12x10-unorm-srgb",ASTC12x12Unorm:"astc-12x12-unorm",ASTC12x12UnormSRGB:"astc-12x12-unorm-srgb"},GR="clamp-to-edge",VR="repeat",HR="mirror-repeat",jR="linear",WR="nearest",XR="zero",qR="one",$R="src",YR="one-minus-src",KR="src-alpha",ZR="one-minus-src-alpha",QR="dst",JR="one-minus-dst",eC="dst-alpha",tC="one-minus-dst-alpha",nC="src-alpha-saturated",iC="constant",rC="one-minus-constant",sC="add",aC="subtract",oC="reverse-subtract",lC="min",uC="max",cC=0,hC=15,dC="keep",pC="zero",fC="replace",mC="invert",gC="increment-clamp",_C="decrement-clamp",vC="increment-wrap",yC="decrement-wrap",xC="storage",bC="read-only-storage",SC="write-only",TC="read-only",MC="read-write",EC="float",wC="unfilterable-float",AC="depth",RC="sint",CC="uint",NC="2d",PC="3d",DC="2d",UC="2d-array",LC="cube",IC="3d",OC="all",FC="vertex",BC="instance",kC={DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups"};class zC extends DA{constructor(e,t){super(e),this.texture=t,this.version=t?t.version:0,this.isSampler=!0}}class GC extends zC{constructor(e,t,n){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n}update(){this.texture=this.textureNode.value}}class VC extends UA{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let HC=0;class jC extends VC{constructor(e,t){super("StorageBuffer_"+HC++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Jp,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class WC extends sM{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:jR}),this.flipYSampler=e.createSampler({minFilter:WR}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4,\n\t@location( 0 ) vTex : vec2\n};\n\n@vertex\nfn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array< vec2, 4 >(\n\t\tvec2( -1.0, 1.0 ),\n\t\tvec2( 1.0, 1.0 ),\n\t\tvec2( -1.0, -1.0 ),\n\t\tvec2( 1.0, -1.0 )\n\t);\n\n\tvar tex = array< vec2, 4 >(\n\t\tvec2( 0.0, 0.0 ),\n\t\tvec2( 1.0, 0.0 ),\n\t\tvec2( 0.0, 1.0 ),\n\t\tvec2( 1.0, 1.0 )\n\t);\n\n\tVarys.vTex = tex[ vertexIndex ];\n\tVarys.Position = vec4( pos[ vertexIndex ], 0.0, 1.0 );\n\n\treturn Varys;\n\n}\n"}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img, imgSampler, vTex );\n\n}\n"}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );\n\n}\n"})}getTransferPipeline(e){let t=this.transferPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:SR,stripIndexFormat:kR},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:SR,stripIndexFormat:kR},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,n=0){const i=t.format,{width:r,height:s}=t.size,a=this.getTransferPipeline(i),o=this.getFlipYPipeline(i),l=this.device.createTexture({size:{width:r,height:s,depthOrArrayLayers:1},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),u=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:DC,baseArrayLayer:n}),c=l.createView({baseMipLevel:0,mipLevelCount:1,dimension:DC,baseArrayLayer:0}),h=this.device.createCommandEncoder({}),d=(e,t,n)=>{const i=e.getBindGroupLayout(0),r=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),s=h.beginRenderPass({colorAttachments:[{view:n,loadOp:UR,storeOp:PR,clearValue:[0,0,0,0]}]});s.setPipeline(e),s.setBindGroup(0,r),s.draw(4,1,0,0),s.end()};d(a,u,c),d(o,c,u),this.device.queue.submit([h.finish()]),l.destroy()}generateMipmaps(e,t,n=0){const i=this.get(e);void 0===i.useCount&&(i.useCount=0,i.layers=[]);const r=i.layers[n]||this._mipmapCreateBundles(e,t,n),s=this.device.createCommandEncoder({});this._mipmapRunBundles(s,r),this.device.queue.submit([s.finish()]),0!==i.useCount&&(i.layers[n]=r),i.useCount++}_mipmapCreateBundles(e,t,n){const i=this.getTransferPipeline(t.format),r=i.getBindGroupLayout(0);let s=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:DC,baseArrayLayer:n});const a=[];for(let o=1;o1;for(let a=0;a]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,ZC=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,QC={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2":"vec2","vec2":"ivec2","vec2":"uvec2","vec2":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3":"vec3","vec3":"ivec3","vec3":"uvec3","vec3":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4":"vec4","vec4":"ivec4","vec4":"uvec4","vec4":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2":"mat2",mat2x2f:"mat2","mat3x3":"mat3",mat3x3f:"mat3","mat4x4":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"};class JC extends Zw{constructor(e){const{type:t,inputs:n,name:i,inputsCode:r,blockCode:s,outputType:a}=(e=>{const t=(e=e.trim()).match(KC);if(null!==t&&4===t.length){const n=t[2],i=[];let r=null;for(;null!==(r=ZC.exec(n));)i.push({name:r[1],type:r[2]});const s=[];for(let e=0;e "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class eN extends Kw{parseFunction(e){return new JC(e)}}const tN="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},nN={[Zp]:"read",[Qp]:"write",[Jp]:"read_write"},iN={[q]:"repeat",[$]:"clamp",[Y]:"mirror"},rN={vertex:tN?tN.VERTEX:1,fragment:tN?tN.FRAGMENT:2,compute:tN?tN.COMPUTE:4},sN={instance:!0,swizzleAssign:!1,storageBuffer:!0},aN={"^^":"tsl_xor"},oN={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3",vec2:"vec2",ivec2:"vec2",uvec2:"vec2",bvec2:"vec2",vec3:"vec3",ivec3:"vec3",uvec3:"vec3",bvec3:"vec3",vec4:"vec4",ivec4:"vec4",uvec4:"vec4",bvec4:"vec4",mat2:"mat2x2",mat3:"mat3x3",mat4:"mat4x4"},lN={},uN={tsl_xor:new pE("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new pE("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new pE("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new pE("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new pE("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new pE("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new pE("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new pE("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new pE("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4 { return vec4( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new pE("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new pE("fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }"),clampWrapping_float:new pE("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new pE("\nfn tsl_biquadraticTexture( map : texture_2d, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},cN={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast"};"undefined"!=typeof navigator&&/Windows/g.test(navigator.userAgent)&&(uN.pow_float=new pE("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),uN.pow_vec2=new pE("fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }",[uN.pow_float]),uN.pow_vec3=new pE("fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }",[uN.pow_float]),uN.pow_vec4=new pE("fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }",[uN.pow_float]),cN.pow_float="tsl_pow_float",cN.pow_vec2="tsl_pow_vec2",cN.pow_vec3="tsl_pow_vec3",cN.pow_vec4="tsl_pow_vec4");let hN="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(hN+="diagnostic( off, derivative_uniformity );\n");class dN extends Fw{constructor(e,t){super(e,t,new eN),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==rt}_generateTextureSample(e,t,n,i,r=this.shaderStage){return"fragment"===r?i?`textureSample( ${t}, ${t}_sampler, ${n}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n):this.generateTextureLod(e,t,n,i,"0")}_generateVideoSample(e,t,n=this.shaderStage){if("fragment"===n)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2( ${t}.x, 1.0 - ${t}.y ) )`;console.error(`WebGPURenderer: THREE.VideoTexture does not support ${n} shader.`)}_generateTextureSampleLevel(e,t,n,i,r,s=this.shaderStage){return"fragment"!==s&&"compute"!==s||!1!==this.isUnfilterable(e)?this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,i):this.generateTextureLod(e,t,n,r,i):`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i} )`}generateWrapFunction(e){const t=`tsl_coord_${iN[e.wrapS]}S_${iN[e.wrapT]}_${e.isData3DTexture?"3d":"2d"}T`;let n=lN[t];if(void 0===n){const i=[],r=e.isData3DTexture?"vec3f":"vec2f";let s=`fn ${t}( coord : ${r} ) -> ${r} {\n\n\treturn ${r}(\n`;const a=(e,t)=>{e===q?(i.push(uN.repeatWrapping_float),s+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===$?(i.push(uN.clampWrapping_float),s+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===Y?(i.push(uN.mirrorWrapping_float),s+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(s+=`\t\tcoord.${t}`,console.warn(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),s+=",\n",a(e.wrapT,"y"),e.isData3DTexture&&(s+=",\n",a(e.wrapR,"z")),s+="\n\t);\n\n}\n",lN[t]=n=new pE(s,i)}return n.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,n){const i=this.getDataFromNode(e,this.shaderStage,this.globalCache);void 0===i.dimensionsSnippet&&(i.dimensionsSnippet={});let r=i.dimensionsSnippet[n];if(void 0===i.dimensionsSnippet[n]){let s,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),l=o>1;a=e.isData3DTexture?"vec3":"vec2",s=l||e.isVideoTexture||e.isStorageTexture?t:`${t}${n?`, u32( ${n} )`:""}`,r=new F_(new cv(`textureDimensions( ${s} )`,a)),i.dimensionsSnippet[n]=r,(e.isDataArrayTexture||e.isData3DTexture)&&(i.arrayLayerCount=new F_(new cv(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new F_(new cv("6u","u32")))}return r.build(this)}generateFilteredTexture(e,t,n,i="0u"){this._include("biquadraticTexture");return`tsl_biquadraticTexture( ${t}, ${this.generateWrapFunction(e)}( ${n} ), ${this.generateTextureDimension(e,t,i)}, u32( ${i} ) )`}generateTextureLod(e,t,n,i,r="0u"){const s=this.generateWrapFunction(e),a=this.generateTextureDimension(e,t,r),o=e.isData3DTexture?"vec3":"vec2",l=`${o}(${s}(${n}) * ${o}(${a}))`;return this.generateTextureLoad(e,t,l,i,r)}generateTextureLoad(e,t,n,i,r="0u"){return!0===e.isVideoTexture||!0===e.isStorageTexture?`textureLoad( ${t}, ${n} )`:i?`textureLoad( ${t}, ${n}, ${i}, u32( ${r} ) )`:`textureLoad( ${t}, ${n}, u32( ${r} ) )`}generateTextureStore(e,t,n,i){return`textureStore( ${t}, ${n}, ${i} )`}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===le||!1===this.isSampleCompare(e)&&e.minFilter===K&&e.magFilter===K||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,n,i,r=this.shaderStage){let s=null;return s=!0===e.isVideoTexture?this._generateVideoSample(t,n,r):this.isUnfilterable(e)?this.generateTextureLod(e,t,n,i,"0",r):this._generateTextureSample(e,t,n,i,r),s}generateTextureGrad(e,t,n,i,r,s=this.shaderStage){if("fragment"===s)return`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i[0]}, ${i[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${s} shader.`)}generateTextureCompare(e,t,n,i,r,s=this.shaderStage){if("fragment"===s)return`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${s} shader.`)}generateTextureLevel(e,t,n,i,r,s=this.shaderStage){let a=null;return a=!0===e.isVideoTexture?this._generateVideoSample(t,n,s):this._generateTextureSampleLevel(e,t,n,i,r,s),a}generateTextureBias(e,t,n,i,r,s=this.shaderStage){if("fragment"===s)return`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${s} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,n=e.type;return"texture"===n||"cubeTexture"===n||"storageTexture"===n||"texture3D"===n?t:"buffer"===n||"storageBuffer"===n||"indirectStorageBuffer"===n?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=aN[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?Zp:e.access}getStorageAccess(e,t){return nN[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,n,i=null){const r=super.getUniformFromNode(e,t,n,i),s=this.getDataFromNode(e,n,this.globalCache);if(void 0===s.uniformGPU){let a;const o=e.groupNode,l=o.name,u=this.getBindGroupArray(l,n);if("texture"===t||"cubeTexture"===t||"storageTexture"===t||"texture3D"===t){let i=null;const s=this.getNodeAccess(e,n);if("texture"===t||"storageTexture"===t?i=new VA(r.name,r.node,o,s):"cubeTexture"===t?i=new HA(r.name,r.node,o,s):"texture3D"===t&&(i=new jA(r.name,r.node,o,s)),i.store=!0===e.isStorageTextureNode,i.setVisibility(rN[n]),"fragment"!==n&&"compute"!==n||!1!==this.isUnfilterable(e.value)||!1!==i.store)u.push(i),a=[i];else{const e=new GC(`${r.name}_sampler`,r.node,o);e.setVisibility(rN[n]),u.push(e,i),a=[e,i]}}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const s=new("buffer"===t?OA:jC)(e,o);s.setVisibility(rN[n]),u.push(s),a=s,r.name=i||"NodeBuffer_"+r.id}else{const e=this.uniformGroups[n]||(this.uniformGroups[n]={});let i=e[l];void 0===i&&(i=new kA(l,o),i.setVisibility(rN[n]),e[l]=i,u.push(i)),a=this.getNodeUniform(r,t),i.addUniform(a)}s.uniformGPU=a}return r}getBuiltin(e,t,n,i=this.shaderStage){const r=this.builtins[i]||(this.builtins[i]=new Map);return!1===r.has(e)&&r.set(e,{name:e,property:t,type:n}),t}hasBuiltin(e,t=this.shaderStage){return void 0!==this.builtins[t]&&this.builtins[t].has(e)}getVertexIndex(){return"vertex"===this.shaderStage?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,n=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(e.name+" : "+this.getType(e.type));let r=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {\n${n.vars}\n${n.code}\n`;return n.result&&(r+=`\treturn ${n.result};\n`),r+="\n}\n",r}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],n=this.directives[e];if(void 0!==n)for(const e of n)t.push(`enable ${e};`);return t.join("\n")}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array`,"vertex")}getBuiltins(e){const t=[],n=this.builtins[e];if(void 0!==n)for(const{name:e,property:i,type:r}of n.values())t.push(`@builtin( ${e} ) ${i} : ${r}`);return t.join(",\n\t")}getScopedArray(e,t,n,i){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:n,bufferCount:i}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:n,bufferType:i,bufferCount:r}of this.scopedArrays.values()){const s=this.getType(i);t.push(`var<${n}> ${e}: array< ${s}, ${r} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3","attribute"),this.getBuiltin("local_invocation_id","localId","vec3","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const n=this.getAttributesArray();for(let e=0,i=n.length;e"),t.push(`\t${i+n.name} : ${r}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const n=this.structs[e];if(n.length>0){const e=[];for(const t of n){let n=`struct ${t.name} {\n`;n+=this.getStructMembers(t),n+="\n};",e.push(n)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,n=null){let i=`var ${t} : `;return i+=null!==n?this.generateArrayDeclaration(e,n):this.getType(e),i}getVars(e){const t=[],n=this.vars[e];if(void 0!==n)for(const e of n)t.push(`\t${this.getVar(e.type,e.name,e.count)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","Vertex","vec4","vertex"),"vertex"===e||"fragment"===e){const n=this.varyings,i=this.vars[e];for(let r=0;r1&&(s="_multisampled"),!0===t.isCubeTexture)i="texture_cube";else if(!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)i="texture_2d_array";else if(!0===t.isDepthTexture)i=`texture_depth${s}_2d`;else if(!0===t.isVideoTexture)i="texture_external";else if(!0===t.isData3DTexture)i="texture_3d";else if(!0===r.node.isStorageTextureNode){i=`texture_storage_2d<${YC(t)}, ${this.getStorageAccess(r.node,e)}>`}else{i=`texture${s}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}n.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${r.name} : ${i};`)}else if("buffer"===r.type||"storageBuffer"===r.type||"indirectStorageBuffer"===r.type){const t=r.node,n=this.getType(t.getNodeType(this)),s=t.bufferCount,o=s>0&&"buffer"===r.type?", "+s:"",l=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(r))i.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var<${l}> ${r.name} : ${n};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${n}>`:`${n}`}${o} >`;i.push(this._getWGSLStructBinding(r.name,e,l,a.binding++,a.group))}}else{const e=this.getType(this.getVectorType(r.type)),t=r.groupNode.name;(s[t]||(s[t]={index:a.binding++,id:a.group,snippets:[]})).snippets.push(`\t${r.name} : ${e}`)}}for(const e in s){const t=s[e];r.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}let a=n.join("\n");return a+=i.join("\n"),a+=r.join("\n"),a}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const n=e[t];n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.structs=this.getStructs(t),n.vars=this.getVars(t),n.codes=this.getCodes(t),n.directives=this.getDirectives(t),n.scopedArrays=this.getScopedArrays(t);let i="// code\n\n";i+=this.flowCode[t];const r=this.flowNodes[t],s=r[r.length-1],a=s.outputNode,o=void 0!==a&&!0===a.isOutputStructNode;for(const e of r){const r=this.getFlowData(e),l=e.name;if(l&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${l}\n`),i+=`${r.code}\n\t`,e===s&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.Vertex = ${r.result};`;else if("fragment"===t)if(o)n.returnType=a.getNodeType(this),n.structs+="var output : "+n.returnType+";",i+=`return ${r.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),n.returnType="OutputStruct",n.structs+=this._getWGSLStruct("OutputStruct",e),n.structs+="\nvar output : OutputStruct;",i+=`output.color = ${r.result};\n\n\treturn output;`}}n.flow=i}this.shaderStage=null,null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let n;return null!==t&&(n=this._getWGSLMethod(e+"_"+t)),void 0===n&&(n=this._getWGSLMethod(e)),n||e}getType(e){return oN[e]||e}isAvailable(e){let t=sN[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),sN[e]=t),t}_getWGSLMethod(e){return void 0!==uN[e]&&this._include(e),cN[e]}_include(e){const t=uN[e];return t.build(this),null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar varyings : VaryingsStruct;\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${hN}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${t}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${t});\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,n,i=0,r=0){const s=e+"Struct";return`${this._getWGSLStruct(s,t)}\n@binding( ${i} ) @group( ${r} )\nvar<${n}> ${e} : ${s};`}}class pN{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=zR.Depth24PlusStencil8:e.depth&&(t=zR.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const e=this.backend.renderer,n=e.getRenderTarget();t=n?n.samples:e.samples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const n=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:n?1:t,isMSAA:n}}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):this.getPreferredCanvasFormat(),t}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?vR:e.isLineSegments||e.isMesh&&!0===t.wireframe?yR:e.isLine?xR:e.isMesh?bR:void 0}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),2===t&&(t=4)),t}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===ne)return zR.BGRA8Unorm;if(e===ue)return zR.RGBA16Float;throw new Error("Unsupported outputType")}}const fN=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),mN=new Map([[Xi,["float16"]]]),gN=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class _N{constructor(e){this.backend=e}createAttribute(e,t){const n=this._getBufferAttribute(e),i=this.backend,r=i.get(n);let s=r.buffer;if(void 0===s){const a=i.device;let o=n.array;if(!1===e.normalized)if(o.constructor===Int16Array)o=new Int32Array(o);else if(o.constructor===Uint16Array&&(o=new Uint32Array(o),t&GPUBufferUsage.INDEX))for(let e=0;e1&&(i.multisampled=!0,n.texture.isDepthTexture||(i.sampleType=wC)),n.texture.isDepthTexture)i.sampleType=AC;else if(n.texture.isDataTexture||n.texture.isDataArrayTexture||n.texture.isData3DTexture){const e=n.texture.type;e===ae?i.sampleType=RC:e===oe?i.sampleType=CC:e===le&&(this.backend.hasFeature("float32-filterable")?i.sampleType=EC:i.sampleType=wC)}n.isSampledCubeTexture?i.viewDimension=LC:n.texture.isDataArrayTexture||n.texture.isCompressedArrayTexture?i.viewDimension=UC:n.isSampledTexture3D&&(i.viewDimension=IC),e.texture=i}else console.error(`WebGPUBindingUtils: Unsupported binding "${n}".`);i.push(e)}return n.createBindGroupLayout({entries:i})}createBindings(e,t,n,i=0){const{backend:r,bindGroupLayoutCache:s}=this,a=r.get(e);let o,l=s.get(e.bindingsReference);void 0===l&&(l=this.createBindingsLayout(e),s.set(e.bindingsReference,l)),n>0&&(void 0===a.groups&&(a.groups=[],a.versions=[]),a.versions[n]===i&&(o=a.groups[n])),void 0===o&&(o=this.createBindGroup(e,l),n>0&&(a.groups[n]=o,a.versions[n]=i)),a.group=o,a.layout=l}updateBinding(e){const t=this.backend,n=t.device,i=e.buffer,r=t.get(e).buffer;n.queue.writeBuffer(r,0,i,0)}createBindGroupIndex(e,t){const n=this.backend.device,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r=e[0],s=n.createBuffer({label:"bindingCameraIndex_"+r,size:16,usage:i});n.queue.writeBuffer(s,0,e,0);const a=[{binding:0,resource:{buffer:s}}];return n.createBindGroup({label:"bindGroupCameraIndex_"+r,layout:t,entries:a})}createBindGroup(e,t){const n=this.backend,i=n.device;let r=0;const s=[];for(const t of e.bindings){if(t.isUniformBuffer){const e=n.get(t);if(void 0===e.buffer){const n=t.byteLength,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,s=i.createBuffer({label:"bindingBuffer_"+t.name,size:n,usage:r});e.buffer=s}s.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=n.get(t);if(void 0===e.buffer){const i=t.attribute;e.buffer=n.get(i).buffer}s.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isSampler){const e=n.get(t.texture);s.push({binding:r,resource:e.sampler})}else if(t.isSampledTexture){const e=n.get(t.texture);let a;if(void 0!==e.externalTexture)a=i.importExternalTexture({source:e.externalTexture});else{const n=t.store?1:e.texture.mipLevelCount,i=`view-${e.texture.width}-${e.texture.height}-${n}`;if(a=e[i],void 0===a){const r=OC;let s;s=t.isSampledCubeTexture?LC:t.isSampledTexture3D?IC:t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?UC:DC,a=e[i]=e.texture.createView({aspect:r,dimension:s,mipLevelCount:n})}}s.push({binding:r,resource:a})}r++}return i.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:s})}}class yN{constructor(e){this.backend=e}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:n,material:i,geometry:r,pipeline:s}=e,{vertexProgram:a,fragmentProgram:o}=s,l=this.backend,u=l.device,c=l.utils,h=l.get(s),d=[];for(const t of e.getBindings()){const e=l.get(t);d.push(e.layout)}const p=l.attributeUtils.createShaderVertexBuffers(e);let f;!0===i.transparent&&0!==i.blending&&(f=this._getBlending(i));let m={};!0===i.stencilWrite&&(m={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const g=this._getColorWriteMask(i),_=[];if(null!==e.context.textures){const t=e.context.textures;for(let e=0;e1},layout:u.createPipelineLayout({bindGroupLayouts:d})},E={},w=e.context.depth,A=e.context.stencil;if(!0!==w&&!0!==A||(!0===w&&(E.format=S,E.depthWriteEnabled=i.depthWrite,E.depthCompare=b),!0===A&&(E.stencilFront=m,E.stencilBack={},E.stencilReadMask=i.stencilFuncMask,E.stencilWriteMask=i.stencilWriteMask),!0===i.polygonOffset&&(E.depthBias=i.polygonOffsetUnits,E.depthBiasSlopeScale=i.polygonOffsetFactor,E.depthBiasClamp=0),M.depthStencil=E),null===t)h.pipeline=u.createRenderPipeline(M);else{const e=new Promise((e=>{u.createRenderPipelineAsync(M).then((t=>{h.pipeline=t,e()}))}));t.push(e)}}createBundleEncoder(e){const t=this.backend,{utils:n,device:i}=t,r=n.getCurrentDepthStencilFormat(e),s={label:"renderBundleEncoder",colorFormats:[n.getCurrentColorFormat(e)],depthStencilFormat:r,sampleCount:this._getSampleCount(e)};return i.createRenderBundleEncoder(s)}createComputePipeline(e,t){const n=this.backend,i=n.device,r=n.get(e.computeProgram).module,s=n.get(e),a=[];for(const e of t){const t=n.get(e);a.push(t.layout)}s.pipeline=i.createComputePipeline({compute:r,layout:i.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,n;const i=e.blending,r=e.blendSrc,s=e.blendDst,a=e.blendEquation;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,o=null!==e.blendDstAlpha?e.blendDstAlpha:s,l=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(s),operation:this._getBlendOperation(a)},n={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(l)}}else{const r=(e,i,r,s)=>{t={srcFactor:e,dstFactor:i,operation:sC},n={srcFactor:r,dstFactor:s,operation:sC}};if(e.premultipliedAlpha)switch(i){case 1:r(qR,ZR,qR,ZR);break;case 2:r(qR,qR,qR,qR);break;case 3:r(XR,YR,XR,qR);break;case 4:r(XR,$R,XR,KR)}else switch(i){case 1:r(KR,ZR,qR,ZR);break;case 2:r(KR,qR,KR,qR);break;case 3:r(XR,YR,XR,qR);break;case 4:r(XR,$R,XR,$R)}}if(void 0!==t&&void 0!==n)return{color:t,alpha:n};console.error("THREE.WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case 200:t=XR;break;case 201:t=qR;break;case 202:t=$R;break;case 203:t=YR;break;case T:t=KR;break;case M:t=ZR;break;case 208:t=QR;break;case 209:t=JR;break;case 206:t=eC;break;case 207:t=tC;break;case 210:t=nC;break;case 211:t=iC;break;case 212:t=rC;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const n=e.stencilFunc;switch(n){case 512:t=TR;break;case 519:t=NR;break;case 513:t=MR;break;case 515:t=wR;break;case 514:t=ER;break;case 518:t=CR;break;case 516:t=AR;break;case 517:t=RR;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",n)}return t}_getStencilOperation(e){let t;switch(e){case ut:t=dC;break;case 0:t=pC;break;case 7681:t=fC;break;case 5386:t=mC;break;case 7682:t=gC;break;case 7683:t=_C;break;case 34055:t=vC;break;case 34056:t=yC;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case g:t=sC;break;case 101:t=aC;break;case 102:t=oC;break;case 103:t=lC;break;case 104:t=uC;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,n){const i={},r=this.backend.utils;switch(i.topology=r.getPrimitiveTopology(e,n),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?BR:kR),n.side){case 0:i.frontFace=LR,i.cullMode=FR;break;case 1:i.frontFace=LR,i.cullMode=OR;break;case 2:i.frontFace=LR,i.cullMode=IR;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",n.side)}return i}_getColorWriteMask(e){return!0===e.colorWrite?hC:cC}_getDepthCompare(e){let t;if(!1===e.depthTest)t=NR;else{const n=e.depthFunc;switch(n){case 0:t=TR;break;case 1:t=NR;break;case 2:t=MR;break;case 3:t=wR;break;case 4:t=ER;break;case 5:t=CR;break;case 6:t=AR;break;case 7:t=RR;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",n)}}return t}}class xN extends mR{constructor(e,t,n=2048){super(n),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const i=8*this.maxQueries;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return Vt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e.id,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,n=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const i=this.device.createCommandEncoder();i.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),i.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,n);const r=i.finish();if(this.device.queue.submit([r]),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,n),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const s=new BigUint64Array(this.resultBuffer.getMappedRange(0,n));let a=0;for(const[,t]of e){const e=s[t],n=s[t+1];a+=Number(n-e)/1e6}return this.resultBuffer.unmap(),this.lastValue=a,a}catch(e){return console.error("Error resolving queries:",e),"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){console.error("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){console.error("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class bN extends QA{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.trackTimestamp=!0===e.trackTimestamp,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new pN(this),this.attributeUtils=new _N(this),this.bindingUtils=new vN(this),this.pipelineUtils=new yN(this),this.textureUtils=new $C(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let n;if(void 0===t.device){const e={powerPreference:t.powerPreference},i="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(e):null;if(null===i)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const r=Object.values(kC),s=[];for(const e of r)i.features.has(e)&&s.push(e);const a={requiredFeatures:s,requiredLimits:t.requiredLimits};n=await i.requestDevice(a)}else n=t.device;n.lost.then((t=>{const n={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(n)}));const i=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.device=n,this.context=i;const r=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature(kC.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:r}),this.updateSize()}get coordinateSystem(){return St}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.defaultRenderPassdescriptor;if(null===e){const t=this.renderer;e={colorAttachments:[{view:null}]},!0!==this.renderer.depth&&!0!==this.renderer.stencil||(e.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(t.depth,t.stencil).createView()});const n=e.colorAttachments[0];this.renderer.samples>0?n.view=this.colorBuffer.createView():n.resolveTarget=void 0,this.defaultRenderPassdescriptor=e}const t=e.colorAttachments[0];return this.renderer.samples>0?t.resolveTarget=this.context.getCurrentTexture().createView():t.view=this.context.getCurrentTexture().createView(),e}_getRenderPassDescriptor(e,t={}){const n=e.renderTarget,i=this.get(n);let r=i.descriptors;if(void 0===r||i.width!==n.width||i.height!==n.height||i.dimensions!==n.dimensions||i.activeMipmapLevel!==n.activeMipmapLevel||i.activeCubeFace!==e.activeCubeFace||i.samples!==n.samples||i.loadOp!==t.loadOp){r={},i.descriptors=r;const e=()=>{n.removeEventListener("dispose",e),this.delete(n)};n.addEventListener("dispose",e)}const s=e.getCacheKey();let a=r[s];if(void 0===a){const o=e.textures,l=[];let u;for(let i=0;i0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,r=n.createQuerySet({type:"occlusion",count:i,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null),s=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:DR}),this.initTimestampQuery(e,s),s.occlusionQuerySet=r;const a=s.depthStencilAttachment;if(null!==e.textures){const t=s.colorAttachments;for(let n=0;n0&&t.currentPass.executeBundles(t.renderBundles),n>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery(),t.currentPass.end(),n>0){const i=8*n;let r=this.occludedResolveCache.get(i);void 0===r&&(r=this.device.createBuffer({size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(i,r));const s=this.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,n,r,0),t.encoder.copyBufferToBuffer(r,0,s,0,i),t.occlusionQueryBuffer=s,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;ea?(l.x=Math.min(t.dispatchCount,a),l.y=Math.ceil(t.dispatchCount/a)):l.x=t.dispatchCount,r.dispatchWorkgroups(l.x,l.y,l.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}async waitForGPU(){await this.device.queue.onSubmittedWorkDone()}draw(e,t){const{object:n,material:i,context:r,pipeline:s}=e,a=e.getBindings(),o=this.get(r),l=this.get(s).pipeline,u=o.currentSets,c=o.currentPass,h=e.getDrawParameters();if(null===h)return;u.pipeline!==l&&(c.setPipeline(l),u.pipeline=l);const d=u.bindingGroups;for(let e=0,t=a.length;e{if(!0===n.isBatchedMesh){const e=n._multiDrawStarts,i=n._multiDrawCounts,r=n._multiDrawCount,s=n._multiDrawInstances;null!==s&&Vt("THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let a=0;a1?0:a;!0===f?c.drawIndexed(i[a],r,e[a]/p.array.BYTES_PER_ELEMENT,0,o):c.draw(i[a],r,e[a],o),t.update(n,i[a],r)}}else if(!0===f){const{vertexCount:i,instanceCount:r,firstVertex:s}=h,a=e.getIndirect();if(null!==a){const e=this.get(a).buffer;c.drawIndexedIndirect(e,0)}else c.drawIndexed(i,r,s,0,0);t.update(n,i,r)}else{const{vertexCount:i,instanceCount:r,firstVertex:s}=h,a=e.getIndirect();if(null!==a){const e=this.get(a).buffer;c.drawIndirect(e,0)}else c.draw(i,r,s,0);t.update(n,i,r)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const t=this.get(e.camera),i=e.camera.cameras,s=e.getBindingGroup("cameraIndex");if(void 0===t.indexesGPU||t.indexesGPU.length!==i.length){const e=this.get(s),n=[],r=new Uint32Array([0,0,0,0]);for(let t=0,s=i.length;t(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new _R(e)));super(new t(e),e),this.library=new TN,this.isWebGPURenderer=!0}}const EN={type:"change"},wN={type:"start"},AN={type:"end"},RN=1e-6,CN=-1,NN=0,PN=1,DN=2,UN=3,LN=4,IN=new It,ON=new It,FN=new un,BN=new un,kN=new un,zN=new ln,GN=new un,VN=new un,HN=new un,jN=new un;class WN extends ma{constructor(e,t=null){super(e,t),this.enabled=!0,this.screen={left:0,top:0,width:0,height:0},this.rotateSpeed=1,this.zoomSpeed=1.2,this.panSpeed=.3,this.noRotate=!1,this.noZoom=!1,this.noPan=!1,this.staticMoving=!1,this.dynamicDampingFactor=.2,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.keys=["KeyA","KeyS","KeyD"],this.mouseButtons={LEFT:a,MIDDLE:o,RIGHT:l},this.state=CN,this.keyState=CN,this.target=new un,this._lastPosition=new un,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._lastAngle=0,this._eye=new un,this._movePrev=new It,this._moveCurr=new It,this._lastAxis=new un,this._zoomStart=new It,this._zoomEnd=new It,this._panStart=new It,this._panEnd=new It,this._pointers=[],this._pointerPositions={},this._onPointerMove=qN.bind(this),this._onPointerDown=XN.bind(this),this._onPointerUp=$N.bind(this),this._onPointerCancel=YN.bind(this),this._onContextMenu=nP.bind(this),this._onMouseWheel=tP.bind(this),this._onKeyDown=ZN.bind(this),this._onKeyUp=KN.bind(this),this._onTouchStart=iP.bind(this),this._onTouchMove=rP.bind(this),this._onTouchEnd=sP.bind(this),this._onMouseDown=QN.bind(this),this._onMouseMove=JN.bind(this),this._onMouseUp=eP.bind(this),this._target0=this.target.clone(),this._position0=this.object.position.clone(),this._up0=this.object.up.clone(),this._zoom0=this.object.zoom,null!==t&&(this.connect(),this.handleResize()),this.update()}connect(){window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}handleResize(){const e=this.domElement.getBoundingClientRect(),t=this.domElement.ownerDocument.documentElement;this.screen.left=e.left+window.pageXOffset-t.clientLeft,this.screen.top=e.top+window.pageYOffset-t.clientTop,this.screen.width=e.width,this.screen.height=e.height}update(){this._eye.subVectors(this.object.position,this.target),this.noRotate||this._rotateCamera(),this.noZoom||this._zoomCamera(),this.noPan||this._panCamera(),this.object.position.addVectors(this.target,this._eye),this.object.isPerspectiveCamera?(this._checkDistances(),this.object.lookAt(this.target),this._lastPosition.distanceToSquared(this.object.position)>RN&&(this.dispatchEvent(EN),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>RN||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent(EN),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=CN,this.keyState=CN,this.target.copy(this._target0),this.object.position.copy(this._position0),this.object.up.copy(this._up0),this.object.zoom=this._zoom0,this.object.updateProjectionMatrix(),this._eye.subVectors(this.object.position,this.target),this.object.lookAt(this.target),this.dispatchEvent(EN),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(ON.copy(this._panEnd).sub(this._panStart),ON.lengthSq()){if(this.object.isOrthographicCamera){const e=(this.object.right-this.object.left)/this.object.zoom/this.domElement.clientWidth,t=(this.object.top-this.object.bottom)/this.object.zoom/this.domElement.clientWidth;ON.x*=e,ON.y*=t}ON.multiplyScalar(this._eye.length()*this.panSpeed),BN.copy(this._eye).cross(this.object.up).setLength(ON.x),BN.add(FN.copy(this.object.up).setLength(ON.y)),this.object.position.add(BN),this.target.add(BN),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(ON.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){jN.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=jN.length();e?(this._eye.copy(this.object.position).sub(this.target),GN.copy(this._eye).normalize(),VN.copy(this.object.up).normalize(),HN.crossVectors(VN,GN).normalize(),VN.setLength(this._moveCurr.y-this._movePrev.y),HN.setLength(this._moveCurr.x-this._movePrev.x),jN.copy(VN.add(HN)),kN.crossVectors(jN,this._eye).normalize(),e*=this.rotateSpeed,zN.setFromAxisAngle(kN,e),this._eye.applyQuaternion(zN),this.object.up.applyQuaternion(zN),this._lastAxis.copy(kN),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),zN.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(zN),this.object.up.applyQuaternion(zN)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let e;this.state===LN?(e=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=Lt.clamp(this.object.zoom/e,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")):(e=1+(this._zoomEnd.y-this._zoomStart.y)*this.zoomSpeed,1!==e&&e>0&&(this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=Lt.clamp(this.object.zoom/e,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")),this.staticMoving?this._zoomStart.copy(this._zoomEnd):this._zoomStart.y+=(this._zoomEnd.y-this._zoomStart.y)*this.dynamicDampingFactor)}_getMouseOnScreen(e,t){return IN.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),IN}_getMouseOnCircle(e,t){return IN.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),IN}_addPointer(e){this._pointers.push(e)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;tthis.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()Math.PI&&(n-=pP),i<-Math.PI?i+=pP:i>Math.PI&&(i-=pP),this._spherical.theta=n<=i?Math.max(n,Math.min(i,this._spherical.theta)):this._spherical.theta>(n+i)/2?Math.max(n,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),!0===this.enableDamping?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 r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const e=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=e!=this._spherical.radius}if(dP.setFromSpherical(this._spherical),dP.applyQuaternion(this._quatInverse),t.copy(this.target).add(dP),this.object.lookAt(this.target),!0===this.enableDamping?(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){const t=dP.length();e=this._clampDistance(t*this._scale);const n=t-e;this.object.position.addScaledVector(this._dollyDirection,n),this.object.updateMatrixWorld(),r=!!n}else if(this.object.isOrthographicCamera){const t=new un(this._mouse.x,this._mouse.y,0);t.unproject(this.object);const n=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=n!==this.object.zoom;const i=new un(this._mouse.x,this._mouse.y,0);i.unproject(this.object),this.object.position.sub(i).add(t),this.object.updateMatrixWorld(),e=dP.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;null!==e&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(e).add(this.object.position):(uP.origin.copy(this.object.position),uP.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(uP.direction))SP||8*(1-this._lastQuaternion.dot(this.object.quaternion))>SP||this._lastTargetPosition.distanceToSquared(this.target)>SP)&&(this.dispatchEvent(aP),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?pP/60*this.autoRotateSpeed*e:pP/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(.01*e);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){dP.setFromMatrixColumn(t,0),dP.multiplyScalar(-e),this._panOffset.add(dP)}_panUp(e,t){!0===this.screenSpacePanning?dP.setFromMatrixColumn(t,1):(dP.setFromMatrixColumn(t,0),dP.crossVectors(this.object.up,dP)),dP.multiplyScalar(e),this._panOffset.add(dP)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;dP.copy(i).sub(this.target);let r=dP.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/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;const n=this.domElement.getBoundingClientRect(),i=e-n.left,r=t-n.top,s=n.width,a=n.height;this._mouse.x=i/s*2-1,this._mouse.y=-r/a*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);const t=this.domElement;this._rotateLeft(pP*this._rotateDelta.x/t.clientHeight),this._rotateUp(pP*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(pP*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(-pP*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(pP*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(-pP*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(1===this._pointers.length)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_handleTouchStartPan(e){if(1===this._pointers.length)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+i*i);this._dollyStart.set(0,r)}_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(1==this._pointers.length)this._rotateEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateEnd.set(n,i)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(pP*this._rotateDelta.x/t.clientHeight),this._rotateUp(pP*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(1===this._pointers.length)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(n,i)}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){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+i*i);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const s=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._updateZoomParameters(s,a)}_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;tFP||8*(1-this._lastQuaternion.dot(t.quaternion))>FP)&&(this.dispatchEvent(OP),this._lastQuaternion.copy(t.quaternion),this._lastPosition.copy(t.position))}_updateMovementVector(){const e=this._moveState.forward||this.autoForward&&!this._moveState.back?1:0;this._moveVector.x=-this._moveState.left+this._moveState.right,this._moveVector.y=-this._moveState.down+this._moveState.up,this._moveVector.z=-e+this._moveState.back}_updateRotationVector(){this._rotationVector.x=-this._moveState.pitchDown+this._moveState.pitchUp,this._rotationVector.y=-this._moveState.yawRight+this._moveState.yawLeft,this._rotationVector.z=-this._moveState.rollRight+this._moveState.rollLeft}_getContainerDimensions(){return this.domElement!=document?{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}:{size:[window.innerWidth,window.innerHeight],offset:[0,0]}}}function zP(e){if(!e.altKey&&!1!==this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=.1;break;case"KeyW":this._moveState.forward=1;break;case"KeyS":this._moveState.back=1;break;case"KeyA":this._moveState.left=1;break;case"KeyD":this._moveState.right=1;break;case"KeyR":this._moveState.up=1;break;case"KeyF":this._moveState.down=1;break;case"ArrowUp":this._moveState.pitchUp=1;break;case"ArrowDown":this._moveState.pitchDown=1;break;case"ArrowLeft":this._moveState.yawLeft=1;break;case"ArrowRight":this._moveState.yawRight=1;break;case"KeyQ":this._moveState.rollLeft=1;break;case"KeyE":this._moveState.rollRight=1}this._updateMovementVector(),this._updateRotationVector()}}function GP(e){if(!1!==this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=1;break;case"KeyW":this._moveState.forward=0;break;case"KeyS":this._moveState.back=0;break;case"KeyA":this._moveState.left=0;break;case"KeyD":this._moveState.right=0;break;case"KeyR":this._moveState.up=0;break;case"KeyF":this._moveState.down=0;break;case"ArrowUp":this._moveState.pitchUp=0;break;case"ArrowDown":this._moveState.pitchDown=0;break;case"ArrowLeft":this._moveState.yawLeft=0;break;case"ArrowRight":this._moveState.yawRight=0;break;case"KeyQ":this._moveState.rollLeft=0;break;case"KeyE":this._moveState.rollRight=0}this._updateMovementVector(),this._updateRotationVector()}}function VP(e){if(!1!==this.enabled)if(this.dragToLook)this._status++;else{switch(e.button){case 0:this._moveState.forward=1;break;case 2:this._moveState.back=1}this._updateMovementVector()}}function HP(e){if(!1!==this.enabled&&(!this.dragToLook||this._status>0)){const t=this._getContainerDimensions(),n=t.size[0]/2,i=t.size[1]/2;this._moveState.yawLeft=-(e.pageX-t.offset[0]-n)/n,this._moveState.pitchDown=(e.pageY-t.offset[1]-i)/i,this._updateRotationVector()}}function jP(e){if(!1!==this.enabled){if(this.dragToLook)this._status--,this._moveState.yawLeft=this._moveState.pitchDown=0;else{switch(e.button){case 0:this._moveState.forward=0;break;case 2:this._moveState.back=0}this._updateMovementVector()}this._updateRotationVector()}}function WP(){!1!==this.enabled&&(this.dragToLook?(this._status=0,this._moveState.yawLeft=this._moveState.pitchDown=0):(this._moveState.forward=0,this._moveState.back=0,this._updateMovementVector()),this._updateRotationVector())}function XP(e){!1!==this.enabled&&e.preventDefault()}const qP={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:"\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t}",fragmentShader:"\n\n\t\tuniform float opacity;\n\n\t\tuniform sampler2D tDiffuse;\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvec4 texel = texture2D( tDiffuse, vUv );\n\t\t\tgl_FragColor = opacity * texel;\n\n\n\t\t}"};class $P{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}}const YP=new Qs(-1,1,1,-1,0,1);const KP=new class extends tr{constructor(){super(),this.setAttribute("position",new qi([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new qi([0,2,0,0,2,0],2))}};class ZP{constructor(e){this._mesh=new pr(KP,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,YP)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class QP extends $P{constructor(e,t){super(),this.textureID=void 0!==t?t:"tDiffuse",e instanceof xr?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=yr.clone(e.uniforms),this.material=new xr({name:void 0!==e.name?e.name:"unspecified",defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this.fsQuad=new ZP(this.material)}render(e,t,n){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=n.texture),this.fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this.fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this.fsQuad.render(e))}dispose(){this.material.dispose(),this.fsQuad.dispose()}}class JP extends $P{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,n){const i=e.getContext(),r=e.state;let s,a;r.buffers.color.setMask(!1),r.buffers.depth.setMask(!1),r.buffers.color.setLocked(!0),r.buffers.depth.setLocked(!0),this.inverse?(s=0,a=1):(s=1,a=0),r.buffers.stencil.setTest(!0),r.buffers.stencil.setOp(i.REPLACE,i.REPLACE,i.REPLACE),r.buffers.stencil.setFunc(i.ALWAYS,s,4294967295),r.buffers.stencil.setClear(a),r.buffers.stencil.setLocked(!0),e.setRenderTarget(n),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),r.buffers.color.setLocked(!1),r.buffers.depth.setLocked(!1),r.buffers.color.setMask(!0),r.buffers.depth.setMask(!0),r.buffers.stencil.setLocked(!1),r.buffers.stencil.setFunc(i.EQUAL,1,4294967295),r.buffers.stencil.setOp(i.KEEP,i.KEEP,i.KEEP),r.buffers.stencil.setLocked(!0)}}class eD extends $P{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class tD{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),void 0===t){const n=e.getSize(new It);this._width=n.width,this._height=n.height,(t=new sn(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ue})).texture.name="EffectComposer.rt1"}else this._width=t.width,this._height=t.height;this.renderTarget1=t,this.renderTarget2=t.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new QP(qP),this.copyPass.material.blending=0,this.clock=new aa}swapBuffers(){const e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){const t=this.passes.indexOf(e);-1!==t&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t1?i-1:0),s=1;s=0&&r<1?(o=s,l=a):r>=1&&r<2?(o=a,l=s):r>=2&&r<3?(l=s,u=a):r>=3&&r<4?(l=a,u=s):r>=4&&r<5?(o=a,u=s):r>=5&&r<6&&(o=s,u=a);var c=n-s/2;return i(o+c,l+c,u+c)}var fD={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"};var mD=/^#[a-fA-F0-9]{6}$/,gD=/^#[a-fA-F0-9]{8}$/,_D=/^#[a-fA-F0-9]{3}$/,vD=/^#[a-fA-F0-9]{4}$/,yD=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,xD=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,bD=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,SD=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function TD(e){if("string"!=typeof e)throw new cD(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return fD[t]?"#"+fD[t]:e}(e);if(t.match(mD))return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16)};if(t.match(gD)){var n=parseFloat((parseInt(""+t[7]+t[8],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16),alpha:n}}if(t.match(_D))return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16)};if(t.match(vD)){var i=parseFloat((parseInt(""+t[4]+t[4],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16),alpha:i}}var r=yD.exec(t);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var s=xD.exec(t.substring(0,50));if(s)return{red:parseInt(""+s[1],10),green:parseInt(""+s[2],10),blue:parseInt(""+s[3],10),alpha:parseFloat(""+s[4])>1?parseFloat(""+s[4])/100:parseFloat(""+s[4])};var a=bD.exec(t);if(a){var o="rgb("+pD(parseInt(""+a[1],10),parseInt(""+a[2],10)/100,parseInt(""+a[3],10)/100)+")",l=yD.exec(o);if(!l)throw new cD(4,t,o);return{red:parseInt(""+l[1],10),green:parseInt(""+l[2],10),blue:parseInt(""+l[3],10)}}var u=SD.exec(t.substring(0,50));if(u){var c="rgb("+pD(parseInt(""+u[1],10),parseInt(""+u[2],10)/100,parseInt(""+u[3],10)/100)+")",h=yD.exec(c);if(!h)throw new cD(4,t,c);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10),alpha:parseFloat(""+u[4])>1?parseFloat(""+u[4])/100:parseFloat(""+u[4])}}throw new cD(5)}function MD(e){return function(e){var t,n=e.red/255,i=e.green/255,r=e.blue/255,s=Math.max(n,i,r),a=Math.min(n,i,r),o=(s+a)/2;if(s===a)return void 0!==e.alpha?{hue:0,saturation:0,lightness:o,alpha:e.alpha}:{hue:0,saturation:0,lightness:o};var l=s-a,u=o>.5?l/(2-s-a):l/(s+a);switch(s){case n:t=(i-r)/l+(i=1?ND(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new cD(7)}function DD(e){if("object"!=typeof e)throw new cD(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return PD(e);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&("number"!=typeof e.alpha||void 0===e.alpha)}(e))return ND(e);if(function(e){return"number"==typeof e.hue&&"number"==typeof e.saturation&&"number"==typeof e.lightness&&"number"==typeof e.alpha}(e))return function(e,t,n,i){if("object"==typeof e&&void 0===t&&void 0===n&&void 0===i)return e.alpha>=1?CD(e.hue,e.saturation,e.lightness):"rgba("+pD(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new cD(2)}(e);if(function(e){return"number"==typeof e.hue&&"number"==typeof e.saturation&&"number"==typeof e.lightness&&("number"!=typeof e.alpha||void 0===e.alpha)}(e))return function(e,t,n){if("object"==typeof e&&void 0===t&&void 0===n)return CD(e.hue,e.saturation,e.lightness);throw new cD(1)}(e);throw new cD(8)}function UD(e,t,n){return function(){var i=n.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):UD(e,t,i)}}function LD(e){return UD(e,e.length,[])}function ID(e,t,n){return Math.max(e,Math.min(t,n))}LD((function(e,t){if("transparent"===t)return t;var n=MD(t);return DD(iD({},n,{hue:n.hue+parseFloat(e)}))})),LD((function(e,t){if("transparent"===t)return t;var n=MD(t);return DD(iD({},n,{lightness:ID(0,1,n.lightness-parseFloat(e))}))})),LD((function(e,t){if("transparent"===t)return t;var n=MD(t);return DD(iD({},n,{saturation:ID(0,1,n.saturation-parseFloat(e))}))})),LD((function(e,t){if("transparent"===t)return t;var n=MD(t);return DD(iD({},n,{lightness:ID(0,1,n.lightness+parseFloat(e))}))}));var OD=LD((function(e,t,n){if("transparent"===t)return n;if("transparent"===n)return t;if(0===e)return n;var i=TD(t),r=iD({},i,{alpha:"number"==typeof i.alpha?i.alpha:1}),s=TD(n),a=iD({},s,{alpha:"number"==typeof s.alpha?s.alpha:1}),o=r.alpha-a.alpha,l=2*parseFloat(e)-1,u=((l*o==-1?l:l+o)/(1+l*o)+1)/2,c=1-u;return PD({red:Math.floor(r.red*u+a.red*c),green:Math.floor(r.green*u+a.green*c),blue:Math.floor(r.blue*u+a.blue*c),alpha:r.alpha*parseFloat(e)+a.alpha*(1-parseFloat(e))})})),FD=OD;var BD=LD((function(e,t){if("transparent"===t)return t;var n=TD(t);return PD(iD({},n,{alpha:ID(0,1,(100*("number"==typeof n.alpha?n.alpha:1)+100*parseFloat(e))/100)}))})),kD=BD;LD((function(e,t){if("transparent"===t)return t;var n=MD(t);return DD(iD({},n,{saturation:ID(0,1,n.saturation+parseFloat(e))}))})),LD((function(e,t){return"transparent"===t?t:DD(iD({},MD(t),{hue:parseFloat(e)}))})),LD((function(e,t){return"transparent"===t?t:DD(iD({},MD(t),{lightness:parseFloat(e)}))})),LD((function(e,t){return"transparent"===t?t:DD(iD({},MD(t),{saturation:parseFloat(e)}))})),LD((function(e,t){return"transparent"===t?t:FD(parseFloat(e),"rgb(0, 0, 0)",t)})),LD((function(e,t){return"transparent"===t?t:FD(parseFloat(e),"rgb(255, 255, 255)",t)})),LD((function(e,t){if("transparent"===t)return t;var n=TD(t);return PD(iD({},n,{alpha:ID(0,1,+(100*("number"==typeof n.alpha?n.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))}));var zD=Object.freeze({Linear:Object.freeze({None:function(e){return e},In:function(e){return e},Out:function(e){return e},InOut:function(e){return e}}),Quadratic:Object.freeze({In:function(e){return e*e},Out:function(e){return e*(2-e)},InOut:function(e){return(e*=2)<1?.5*e*e:-.5*(--e*(e-2)-1)}}),Cubic:Object.freeze({In:function(e){return e*e*e},Out:function(e){return--e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e:.5*((e-=2)*e*e+2)}}),Quartic:Object.freeze({In:function(e){return e*e*e*e},Out:function(e){return 1- --e*e*e*e},InOut:function(e){return(e*=2)<1?.5*e*e*e*e:-.5*((e-=2)*e*e*e-2)}}),Quintic:Object.freeze({In:function(e){return e*e*e*e*e},Out:function(e){return--e*e*e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e*e*e:.5*((e-=2)*e*e*e*e+2)}}),Sinusoidal:Object.freeze({In:function(e){return 1-Math.sin((1-e)*Math.PI/2)},Out:function(e){return Math.sin(e*Math.PI/2)},InOut:function(e){return.5*(1-Math.sin(Math.PI*(.5-e)))}}),Exponential:Object.freeze({In:function(e){return 0===e?0:Math.pow(1024,e-1)},Out:function(e){return 1===e?1:1-Math.pow(2,-10*e)},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?.5*Math.pow(1024,e-1):.5*(2-Math.pow(2,-10*(e-1)))}}),Circular:Object.freeze({In:function(e){return 1-Math.sqrt(1-e*e)},Out:function(e){return Math.sqrt(1- --e*e)},InOut:function(e){return(e*=2)<1?-.5*(Math.sqrt(1-e*e)-1):.5*(Math.sqrt(1-(e-=2)*e)+1)}}),Elastic:Object.freeze({In:function(e){return 0===e?0:1===e?1:-Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)},Out:function(e){return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(5*(e-.1)*Math.PI)+1},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?-.5*Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI):.5*Math.pow(2,-10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)+1}}),Back:Object.freeze({In:function(e){var t=1.70158;return 1===e?1:e*e*((t+1)*e-t)},Out:function(e){var t=1.70158;return 0===e?0:--e*e*((t+1)*e+t)+1},InOut:function(e){var t=2.5949095;return(e*=2)<1?e*e*((t+1)*e-t)*.5:.5*((e-=2)*e*((t+1)*e+t)+2)}}),Bounce:Object.freeze({In:function(e){return 1-zD.Bounce.Out(1-e)},Out:function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375},InOut:function(e){return e<.5?.5*zD.Bounce.In(2*e):.5*zD.Bounce.Out(2*e-1)+.5}}),generatePow:function(e){return void 0===e&&(e=4),e=(e=e1e4?1e4:e,{In:function(t){return Math.pow(t,e)},Out:function(t){return 1-Math.pow(1-t,e)},InOut:function(t){return t<.5?Math.pow(2*t,e)/2:(1-Math.pow(2-2*t,e))/2+.5}}}}),GD=function(){return performance.now()},VD=function(){function e(){for(var e=[],t=0;t0;){this._tweensAddedDuringUpdate={};for(var i=0;i1?s(e[n],e[n-1],n-i):s(e[r],e[r+1>n?n:r+1],i-r)},Utils:{Linear:function(e,t,n){return(t-e)*n+e}}},jD=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),WD=new VD,XD=function(){function e(e,t){this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=zD.Linear.None,this._interpolationFunction=HD.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=jD.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1,this._object=e,"object"==typeof t?(this._group=t,t.add(this)):!0===t&&(this._group=WD,WD.add(this))}return e.prototype.getId=function(){return this._id},e.prototype.isPlaying=function(){return this._isPlaying},e.prototype.isPaused=function(){return this._isPaused},e.prototype.getDuration=function(){return this._duration},e.prototype.to=function(e,t){if(void 0===t&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},e.prototype.duration=function(e){return void 0===e&&(e=1e3),this._duration=e<0?0:e,this},e.prototype.dynamic=function(e){return void 0===e&&(e=!1),this._isDynamic=e,this},e.prototype.start=function(e,t){if(void 0===e&&(e=GD()),void 0===t&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed)for(var n in this._reversed=!1,this._valuesStartRepeat)this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n];if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var r in this._valuesEnd)i[r]=this._valuesEnd[r];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},e.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},e.prototype._setupProperties=function(e,t,n,i,r){for(var s in n){var a=e[s],o=Array.isArray(a),l=o?"array":typeof a,u=!o&&Array.isArray(n[s]);if("undefined"!==l&&"function"!==l){if(u){if(0===(g=n[s]).length)continue;for(var c=[a],h=0,d=g.length;hl)return 1;var e=Math.trunc(a/o),t=a-e*o,n=Math.min(t/s._duration,1);return 0===n&&a===s._duration?1:n}(),c=this._easingFunction(u);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,c),this._onUpdateCallback&&this._onUpdateCallback(this._object,u),0===this._duration||a>=this._duration){if(this._repeat>0){var h=Math.min(Math.trunc((a-this._duration)/o)+1,this._repeat);for(r in isFinite(this._repeat)&&(this._repeat-=h),this._valuesStartRepeat)this._yoyo||"string"!=typeof this._valuesEnd[r]||(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=o*h,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var d=0,p=this._chainedTweens.length;d=0&&"xmlns"!==(t=e.slice(0,n))&&(e=e.slice(n+1)),YD.hasOwnProperty(t)?{space:YD[t],local:e}:e}function ZD(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===$D&&t.documentElement.namespaceURI===$D?t.createElement(e):t.createElementNS(n,e)}}function QD(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function JD(e){var t=KD(e);return(t.local?QD:ZD)(t)}function eU(){}function tU(e){return null==e?eU:function(){return this.querySelector(e)}}function nU(){return[]}function iU(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}function rU(e){return function(t){return t.matches(e)}}var sU=Array.prototype.find;function aU(){return this.firstElementChild}var oU=Array.prototype.filter;function lU(){return Array.from(this.children)}function uU(e){return new Array(e.length)}function cU(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function hU(e,t,n,i,r,s){for(var a,o=0,l=t.length,u=s.length;ot?1:e>=t?0:NaN}function gU(e){return function(){this.removeAttribute(e)}}function _U(e){return function(){this.removeAttributeNS(e.space,e.local)}}function vU(e,t){return function(){this.setAttribute(e,t)}}function yU(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function xU(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttribute(e):this.setAttribute(e,n)}}function bU(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function SU(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function TU(e){return function(){this.style.removeProperty(e)}}function MU(e,t,n){return function(){this.style.setProperty(e,t,n)}}function EU(e,t,n){return function(){var i=t.apply(this,arguments);null==i?this.style.removeProperty(e):this.style.setProperty(e,i,n)}}function wU(e){return function(){delete this[e]}}function AU(e,t){return function(){this[e]=t}}function RU(e,t){return function(){var n=t.apply(this,arguments);null==n?delete this[e]:this[e]=n}}function CU(e){return e.trim().split(/^|\s+/)}function NU(e){return e.classList||new PU(e)}function PU(e){this._node=e,this._names=CU(e.getAttribute("class")||"")}function DU(e,t){for(var n=NU(e),i=-1,r=t.length;++i=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var eL=[null];function tL(e,t){this._groups=e,this._parents=t}tL.prototype={constructor:tL,select:function(e){"function"!=typeof e&&(e=tU(e));for(var t=this._groups,n=t.length,i=new Array(n),r=0;r=x&&(x=y+1);!(v=g[x])&&++x=0;)(i=r[s])&&(a&&4^i.compareDocumentPosition(a)&&a.parentNode.insertBefore(i,a),a=i);return this},sort:function(e){function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}e||(e=mU);for(var n=this._groups,i=n.length,r=new Array(i),s=0;s1?this.each((null==t?TU:"function"==typeof t?EU:MU)(e,t,null==n?"":n)):function(e,t){return e.style.getPropertyValue(t)||SU(e).getComputedStyle(e,null).getPropertyValue(t)}(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?wU:"function"==typeof t?RU:AU)(e,t)):this.node()[e]},classed:function(e,t){var n=CU(e+"");if(arguments.length<2){for(var i=NU(this.node()),r=-1,s=n.length;++r=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}}))}(e+""),a=s.length;if(!(arguments.length<2)){for(o=t?KU:YU,i=0;io&&aL.sort(uL),e=aL.shift(),o=aL.length,e.__d&&(n=void 0,r=(i=(t=e).__v).__e,s=[],a=[],t.__P&&((n=vL({},i)).__v=i.__v+1,iL.vnode&&iL.vnode(n),LL(t.__P,n,i,t.__n,t.__P.namespaceURI,32&i.__u?[r]:null,s,null==r?TL(i):r,!!(32&i.__u),a),n.__v=i.__v,n.__.__k[n.__i]=n,IL(s,n,a),n.__e!=r&&ML(n)));wL.__r=0}function AL(e,t,n,i,r,s,a,o,l,u,c){var h,d,p,f,m,g,_=i&&i.__k||mL,v=t.length;for(l=RL(n,t,_,l,v),h=0;h0?xL(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):a).__=e,a.__b=e.__b+1,o=null,-1!==(u=a.__i=NL(a,n,l,h))&&(h--,(o=n[u])&&(o.__u|=2)),null==o||null===o.__v?(-1==u&&(r>c?d--:rl?d--:d++,a.__u|=4))):e.__k[s]=null;if(h)for(s=0;s(null==l||2&l.__u?0:1))for(r=n-1,s=n+1;r>=0||s=0){if((l=t[r])&&!(2&l.__u)&&a==l.key&&o===l.type)return r;r--}if(s2&&(a.children=arguments.length>3?nL.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(s in e.defaultProps)void 0===a[s]&&(a[s]=e.defaultProps[s]);return xL(e,a,i,r,null)}(bL,null,[e]),i||fL,fL,t.namespaceURI,i?null:t.firstChild?nL.call(t.childNodes):null,r,i?i.__e:t.firstChild,false,s),IL(r,e,s)}function VL(e,t,n){var i,r,s,a,o=vL({},e.props);for(s in e.type&&e.type.defaultProps&&(a=e.type.defaultProps),t)"key"==s?i=t[s]:"ref"==s?r=t[s]:o[s]=void 0===t[s]&&void 0!==a?a[s]:t[s];return arguments.length>2&&(o.children=arguments.length>3?nL.call(arguments,2):n),xL(e.type,o,i||e.key,r||e.ref,null)}function HL(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n2&&void 0!==arguments[2]?arguments[2]:{}).style,i=void 0===n?{}:n,r=function(e){return"string"==typeof e?new tL([[document.querySelector(e)]],[document.documentElement]):new tL([[e]],eL)}(!!e&&"object"===qL(e)&&!!e.node&&"function"==typeof e.node?e.node():e);"static"===r.style("position")&&r.style("position","relative"),t.tooltipEl=r.append("div").attr("class","float-tooltip-kap"),Object.entries(i).forEach((function(e){var n=XL(e,2),i=n[0],r=n[1];return t.tooltipEl.style(i,r)})),t.tooltipEl.style("left","-10000px").style("display","none");var s="tooltip-".concat(Math.round(1e12*Math.random()));t.mouseInside=!1,r.on("mousemove.".concat(s),(function(e){t.mouseInside=!0;var n=function(e,t){if(e=function(e){let t;for(;t=e.sourceEvent;)e=t;return e}(e),void 0===t&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var i=n.createSVGPoint();return i.x=e.clientX,i.y=e.clientY,[(i=i.matrixTransform(t.getScreenCTM().inverse())).x,i.y]}if(t.getBoundingClientRect){var r=t.getBoundingClientRect();return[e.clientX-r.left-t.clientLeft,e.clientY-r.top-t.clientTop]}}return[e.pageX,e.pageY]}(e),i=r.node(),s=i.offsetWidth,a=i.offsetHeight,o=[null===t.offsetX||void 0===t.offsetX?"-".concat(n[0]/s*100,"%"):"number"==typeof t.offsetX?"calc(-50% + ".concat(t.offsetX,"px)"):t.offsetX,null===t.offsetY||void 0===t.offsetY?a>130&&a-n[1]<100?"calc(-100% - 6px)":"21px":"number"==typeof t.offsetY?t.offsetY<0?"calc(-100% - ".concat(Math.abs(t.offsetY),"px)"):"".concat(t.offsetY,"px"):t.offsetY];t.tooltipEl.style("left",n[0]+"px").style("top",n[1]+"px").style("transform","translate(".concat(o.join(","),")")),t.content&&t.tooltipEl.style("display","inline")})),r.on("mouseover.".concat(s),(function(){t.mouseInside=!0,t.content&&t.tooltipEl.style("display","inline")})),r.on("mouseout.".concat(s),(function(){t.mouseInside=!1,t.tooltipEl.style("display","none")}))},update:function(e){var t,n;e.tooltipEl.style("display",e.content&&e.mouseInside?"inline":"none"),e.content?e.content instanceof HTMLElement?(e.tooltipEl.text(""),e.tooltipEl.append((function(){return e.content}))):"string"==typeof e.content?e.tooltipEl.html(e.content):!function(e){return sL(VL(e))}(e.content)?(e.tooltipEl.style("display","none"),console.warn("Tooltip content is invalid, skipping.",e.content,e.content.toString())):(e.tooltipEl.text(""),t=e.content,delete(n=e.tooltipEl.node()).__k,GL($L(t),n)):e.tooltipEl.text("")}});function KL(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n0),h=!!n.morphAttributes.position,d=!!n.morphAttributes.normal,p=!!n.morphAttributes.color;let f=0;i.toneMapped&&(null!==M&&!0!==M.isXRRenderTarget||(f=x.toneMapping));const m=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,g=void 0!==m?m.length:0,v=ee.get(i),y=_.state.lights;if(!0===G&&(!0===V||e!==w)){const t=e===w&&i.id===E;ye.setState(i,e,t)}let b=!1;i.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version||v.outputColorSpace!==o||r.isBatchedMesh&&!1===v.batching?b=!0:r.isBatchedMesh||!0!==v.batching?r.isBatchedMesh&&!0===v.batchingColor&&null===r.colorTexture||r.isBatchedMesh&&!1===v.batchingColor&&null!==r.colorTexture||r.isInstancedMesh&&!1===v.instancing?b=!0:r.isInstancedMesh||!0!==v.instancing?r.isSkinnedMesh&&!1===v.skinning?b=!0:r.isSkinnedMesh||!0!==v.skinning?r.isInstancedMesh&&!0===v.instancingColor&&null===r.instanceColor||r.isInstancedMesh&&!1===v.instancingColor&&null!==r.instanceColor||r.isInstancedMesh&&!0===v.instancingMorph&&null===r.morphTexture||r.isInstancedMesh&&!1===v.instancingMorph&&null!==r.morphTexture||v.envMap!==l||!0===i.fog&&v.fog!==s?b=!0:void 0===v.numClippingPlanes||v.numClippingPlanes===ye.numPlanes&&v.numIntersection===ye.numIntersection?(v.vertexAlphas!==u||v.vertexTangents!==c||v.morphTargets!==h||v.morphNormals!==d||v.morphColors!==p||v.toneMapping!==f||v.morphTargetsCount!==g)&&(b=!0):b=!0:b=!0:b=!0:b=!0:(b=!0,v.__version=i.version);let S=v.currentProgram;!0===b&&(S=Ye(i,t,r));let T=!1,A=!1,R=!1;const C=S.getUniforms(),N=v.uniforms;Q.useProgram(S.program)&&(T=!0,A=!0,R=!0);i.id!==E&&(E=i.id,A=!0);if(T||w!==e){Q.buffers.depth.getReversed()?(H.copy(e.projectionMatrix),function(e){const 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]}(H),function(e){const t=e.elements;-1===t[11]?(t[10]=-t[10]-1,t[14]=-t[14]):(t[10]=-t[10],t[14]=1-t[14])}(H),C.setValue(Pe,"projectionMatrix",H)):C.setValue(Pe,"projectionMatrix",e.projectionMatrix),C.setValue(Pe,"viewMatrix",e.matrixWorldInverse);const t=C.map.cameraPosition;void 0!==t&&t.setValue(Pe,W.setFromMatrixPosition(e.matrixWorld)),Z.logarithmicDepthBuffer&&C.setValue(Pe,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial)&&C.setValue(Pe,"isOrthographic",!0===e.isOrthographicCamera),w!==e&&(w=e,A=!0,R=!0)}if(r.isSkinnedMesh){C.setOptional(Pe,r,"bindMatrix"),C.setOptional(Pe,r,"bindMatrixInverse");const e=r.skeleton;e&&(null===e.boneTexture&&e.computeBoneTexture(),C.setValue(Pe,"boneTexture",e.boneTexture,ie))}r.isBatchedMesh&&(C.setOptional(Pe,r,"batchingTexture"),C.setValue(Pe,"batchingTexture",r._matricesTexture,ie),C.setOptional(Pe,r,"batchingIdTexture"),C.setValue(Pe,"batchingIdTexture",r._indirectTexture,ie),C.setOptional(Pe,r,"batchingColorTexture"),null!==r._colorsTexture&&C.setValue(Pe,"batchingColorTexture",r._colorsTexture,ie));const P=n.morphAttributes;void 0===P.position&&void 0===P.normal&&void 0===P.color||Te.update(r,n,S);(A||v.receiveShadow!==r.receiveShadow)&&(v.receiveShadow=r.receiveShadow,C.setValue(Pe,"receiveShadow",r.receiveShadow));i.isMeshGouraudMaterial&&null!==i.envMap&&(N.envMap.value=l,N.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1);i.isMeshStandardMaterial&&null===i.envMap&&null!==t.environment&&(N.envMapIntensity.value=t.environmentIntensity);A&&(C.setValue(Pe,"toneMappingExposure",x.toneMappingExposure),v.needsLights&&(I=R,(D=N).ambientLightColor.needsUpdate=I,D.lightProbe.needsUpdate=I,D.directionalLights.needsUpdate=I,D.directionalLightShadows.needsUpdate=I,D.pointLights.needsUpdate=I,D.pointLightShadows.needsUpdate=I,D.spotLights.needsUpdate=I,D.spotLightShadows.needsUpdate=I,D.rectAreaLights.needsUpdate=I,D.hemisphereLights.needsUpdate=I),s&&!0===i.fog&&ge.refreshFogUniforms(N,s),ge.refreshMaterialUniforms(N,i,L,U,_.state.transmissionRenderTarget[e.id]),ol.upload(Pe,Ke(v),N,ie));var D,I;i.isShaderMaterial&&!0===i.uniformsNeedUpdate&&(ol.upload(Pe,Ke(v),N,ie),i.uniformsNeedUpdate=!1);i.isSpriteMaterial&&C.setValue(Pe,"center",r.center);if(C.setValue(Pe,"modelViewMatrix",r.modelViewMatrix),C.setValue(Pe,"normalMatrix",r.normalMatrix),C.setValue(Pe,"modelMatrix",r.matrixWorld),i.isShaderMaterial||i.isRawShaderMaterial){const e=i.uniformsGroups;for(let t=0,n=e.length;t{function n(){i.forEach((function(e){ee.get(e).currentProgram.isReady()&&i.delete(e)})),0!==i.size?setTimeout(n,10):t(e)}null!==K.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)}))};let ze=null;function Ge(){He.stop()}function Ve(){He.start()}const He=new _a;function je(e,t,n,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)_.pushLight(e),e.castShadow&&_.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||z.intersectsSprite(e)){i&&X.setFromMatrixPosition(e.matrixWorld).applyMatrix4(j);const t=fe.update(e),r=e.material;r.visible&&g.push(e,t,r,n,X.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||z.intersectsObject(e))){const t=fe.update(e),r=e.material;if(i&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),X.copy(e.boundingSphere.center)):(null===t.boundingSphere&&t.computeBoundingSphere(),X.copy(t.boundingSphere.center)),X.applyMatrix4(e.matrixWorld).applyMatrix4(j)),Array.isArray(r)){const i=t.groups;for(let s=0,a=i.length;s0&&qe(r,t,n),s.length>0&&qe(s,t,n),a.length>0&&qe(a,t,n),Q.buffers.depth.setTest(!0),Q.buffers.depth.setMask(!0),Q.buffers.color.setMask(!0),Q.setPolygonOffset(!1)}function Xe(e,t,n,i){if(null!==(!0===n.isScene?n.overrideMaterial:null))return;void 0===_.state.transmissionRenderTarget[i.id]&&(_.state.transmissionRenderTarget[i.id]=new sn(1,1,{generateMipmaps:!0,type:K.has("EXT_color_buffer_half_float")||K.has("EXT_color_buffer_float")?ue:ne,minFilter:te,samples:4,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Xt.workingColorSpace}));const s=_.state.transmissionRenderTarget[i.id],a=i.viewport||A;s.setSize(a.z*x.transmissionResolutionScale,a.w*x.transmissionResolutionScale);const o=x.getRenderTarget();x.setRenderTarget(s),x.getClearColor(N),P=x.getClearAlpha(),P<1&&x.setClearColor(16777215,.5),x.clear(),$&&be.render(n);const l=x.toneMapping;x.toneMapping=0;const u=i.viewport;if(void 0!==i.viewport&&(i.viewport=void 0),_.setupLightsView(i),!0===G&&ye.setGlobalState(x.clippingPlanes,i),qe(e,n,i),ie.updateMultisampleRenderTarget(s),ie.updateRenderTargetMipmap(s),!1===K.has("WEBGL_multisampled_render_to_texture")){let e=!1;for(let r=0,s=t.length;r0)for(let t=0,s=n.length;t0&&Xe(i,r,e,t),$&&be.render(e),We(g,e,t);null!==M&&0===T&&(ie.updateMultisampleRenderTarget(M),ie.updateRenderTargetMipmap(M)),!0===e.isScene&&e.onAfterRender(x,e,t),Ce.resetDefaultState(),E=-1,w=null,y.pop(),y.length>0?(_=y[y.length-1],!0===G&&ye.setGlobalState(x.clippingPlanes,_.state.camera)):_=null,v.pop(),g=v.length>0?v[v.length-1]:null},this.getActiveCubeFace=function(){return S},this.getActiveMipmapLevel=function(){return T},this.getRenderTarget=function(){return M},this.setRenderTargetTextures=function(e,t,n){ee.get(e.texture).__webglTexture=t,ee.get(e.depthTexture).__webglTexture=n;const i=ee.get(e);i.__hasExternalTextures=!0,i.__autoAllocateDepthBuffer=void 0===n,i.__autoAllocateDepthBuffer||!0===K.has("WEBGL_multisampled_render_to_texture")&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),i.__useRenderToTexture=!1)},this.setRenderTargetFramebuffer=function(e,t){const n=ee.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=void 0===t};const Qe=Pe.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){M=e,S=t,T=n;let i=!0,r=null,s=!1,a=!1;if(e){const o=ee.get(e);if(void 0!==o.__useDefaultFramebuffer)Q.bindFramebuffer(Pe.FRAMEBUFFER,null),i=!1;else if(void 0===o.__webglFramebuffer)ie.setupRenderTarget(e);else if(o.__hasExternalTextures)ie.rebindTextures(e,ee.get(e.texture).__webglTexture,ee.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){const t=e.depthTexture;if(o.__boundDepthTexture!==t){if(null!==t&&ee.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");ie.setupDepthRenderbuffer(e)}}const l=e.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(a=!0);const u=ee.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(u[t])?u[t][n]:u[t],s=!0):r=e.samples>0&&!1===ie.useMultisampledRTT(e)?ee.get(e).__webglMultisampledFramebuffer:Array.isArray(u)?u[n]:u,A.copy(e.viewport),R.copy(e.scissor),C=e.scissorTest}else A.copy(F).multiplyScalar(L).floor(),R.copy(B).multiplyScalar(L).floor(),C=k;0!==n&&(r=Qe);if(Q.bindFramebuffer(Pe.FRAMEBUFFER,r)&&i&&Q.drawBuffers(e,r),Q.viewport(A),Q.scissor(R),Q.setScissorTest(C),s){const i=ee.get(e.texture);Pe.framebufferTexture2D(Pe.FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,Pe.TEXTURE_CUBE_MAP_POSITIVE_X+t,i.__webglTexture,n)}else if(a){const i=ee.get(e.texture),r=t;Pe.framebufferTextureLayer(Pe.FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,i.__webglTexture,n,r)}else if(null!==e&&0!==n){const t=ee.get(e.texture);Pe.framebufferTexture2D(Pe.FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,Pe.TEXTURE_2D,t.__webglTexture,n)}E=-1},this.readRenderTargetPixels=function(e,t,n,i,r,s,a){if(!e||!e.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=ee.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){Q.bindFramebuffer(Pe.FRAMEBUFFER,o);try{const a=e.texture,o=a.format,l=a.type;if(!Z.textureFormatReadable(o))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!Z.textureTypeReadable(l))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-i&&n>=0&&n<=e.height-r&&Pe.readPixels(t,n,i,r,Re.convert(o),Re.convert(l),s)}finally{const e=null!==M?ee.get(M).__webglFramebuffer:null;Q.bindFramebuffer(Pe.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,i,r,s,a){if(!e||!e.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=ee.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){const a=e.texture,l=a.format,u=a.type;if(!Z.textureFormatReadable(l))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Z.textureTypeReadable(u))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(t>=0&&t<=e.width-i&&n>=0&&n<=e.height-r){Q.bindFramebuffer(Pe.FRAMEBUFFER,o);const e=Pe.createBuffer();Pe.bindBuffer(Pe.PIXEL_PACK_BUFFER,e),Pe.bufferData(Pe.PIXEL_PACK_BUFFER,s.byteLength,Pe.STREAM_READ),Pe.readPixels(t,n,i,r,Re.convert(l),Re.convert(u),0);const a=null!==M?ee.get(M).__webglFramebuffer:null;Q.bindFramebuffer(Pe.FRAMEBUFFER,a);const c=Pe.fenceSync(Pe.SYNC_GPU_COMMANDS_COMPLETE,0);return Pe.flush(),await function(e,t,n){return new Promise((function(i,r){setTimeout((function s(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:r();break;case e.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:i()}}),n)}))}(Pe,c,4),Pe.bindBuffer(Pe.PIXEL_PACK_BUFFER,e),Pe.getBufferSubData(Pe.PIXEL_PACK_BUFFER,0,s),Pe.deleteBuffer(e),Pe.deleteSync(c),s}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(e,t=null,n=0){!0!==e.isTexture&&(Vt("WebGLRenderer: copyFramebufferToTexture function signature has changed."),t=arguments[0]||null,e=arguments[1]);const i=Math.pow(2,-n),r=Math.floor(e.image.width*i),s=Math.floor(e.image.height*i),a=null!==t?t.x:0,o=null!==t?t.y:0;ie.setTexture2D(e,0),Pe.copyTexSubImage2D(Pe.TEXTURE_2D,n,0,0,a,o,r,s),Q.unbindTexture()};const Je=Pe.createFramebuffer(),et=Pe.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,i=null,r=0,s=null){let a,o,l,u,c,h,d,p,f;!0!==e.isTexture&&(Vt("WebGLRenderer: copyTextureToTexture function signature has changed."),i=arguments[0]||null,e=arguments[1],t=arguments[2],s=arguments[3]||0,n=null),null===s&&(0!==r?(Vt("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),s=r,r=0):s=0);const m=e.isCompressedTexture?e.mipmaps[s]:e.image;if(null!==n)a=n.max.x-n.min.x,o=n.max.y-n.min.y,l=n.isBox3?n.max.z-n.min.z:1,u=n.min.x,c=n.min.y,h=n.isBox3?n.min.z:0;else{const t=Math.pow(2,-r);a=Math.floor(m.width*t),o=Math.floor(m.height*t),l=e.isDataArrayTexture?m.depth:e.isData3DTexture?Math.floor(m.depth*t):1,u=0,c=0,h=0}null!==i?(d=i.x,p=i.y,f=i.z):(d=0,p=0,f=0);const g=Re.convert(t.format),_=Re.convert(t.type);let v;t.isData3DTexture?(ie.setTexture3D(t,0),v=Pe.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(ie.setTexture2DArray(t,0),v=Pe.TEXTURE_2D_ARRAY):(ie.setTexture2D(t,0),v=Pe.TEXTURE_2D),Pe.pixelStorei(Pe.UNPACK_FLIP_Y_WEBGL,t.flipY),Pe.pixelStorei(Pe.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),Pe.pixelStorei(Pe.UNPACK_ALIGNMENT,t.unpackAlignment);const y=Pe.getParameter(Pe.UNPACK_ROW_LENGTH),x=Pe.getParameter(Pe.UNPACK_IMAGE_HEIGHT),b=Pe.getParameter(Pe.UNPACK_SKIP_PIXELS),S=Pe.getParameter(Pe.UNPACK_SKIP_ROWS),T=Pe.getParameter(Pe.UNPACK_SKIP_IMAGES);Pe.pixelStorei(Pe.UNPACK_ROW_LENGTH,m.width),Pe.pixelStorei(Pe.UNPACK_IMAGE_HEIGHT,m.height),Pe.pixelStorei(Pe.UNPACK_SKIP_PIXELS,u),Pe.pixelStorei(Pe.UNPACK_SKIP_ROWS,c),Pe.pixelStorei(Pe.UNPACK_SKIP_IMAGES,h);const M=e.isDataArrayTexture||e.isData3DTexture,E=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){const n=ee.get(e),i=ee.get(t),m=ee.get(n.__renderTarget),g=ee.get(i.__renderTarget);Q.bindFramebuffer(Pe.READ_FRAMEBUFFER,m.__webglFramebuffer),Q.bindFramebuffer(Pe.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:10,i=arguments.length,r=new Array(i>3?i-3:0),s=3;s2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:10,r=e.camera;if(t){var s=new tI.Vector3(0,0,0),a=2*Math.max.apply(Math,JL(Object.entries(t).map((function(e){var t=QL(e,2),n=t[0],i=t[1];return Math.max.apply(Math,JL(i.map((function(e){return Math.abs(s[n]-e)}))))})))),o=(1-2*i/e.height)*r.fov,l=a/Math.atan(o*Math.PI/180),u=l/r.aspect,c=Math.max(l,u);if(c>0){var h=s.clone().sub(r.position).normalize().multiplyScalar(-c);this.cameraPosition(h,s,n)}}return this},getBbox:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0},n=new tI.Box3(new tI.Vector3(0,0,0),new tI.Vector3(0,0,0)),i=e.objects.filter(t);return i.length?(i.forEach((function(e){return n.expandByObject(e)})),Object.assign.apply(Object,JL(["x","y","z"].map((function(e){return ZL({},e,[n.min[e],n.max[e]])}))))):null},getScreenCoords:function(e,t,n,i){var r=new tI.Vector3(t,n,i);return r.project(this.camera()),{x:(r.x+1)*e.width/2,y:-(r.y-1)*e.height/2}},getSceneCoords:function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,r=new tI.Vector2(t/e.width*2-1,-n/e.height*2+1),s=new tI.Raycaster;return s.setFromCamera(r,e.camera),Object.assign({},s.ray.at(i,new tI.Vector3))},intersectingObjects:function(e,t,n){var i=new tI.Vector2(t/e.width*2-1,-n/e.height*2+1),r=new tI.Raycaster;return r.params.Line.threshold=e.lineHoverPrecision,r.params.Points.threshold=e.pointsHoverPrecision,r.setFromCamera(i,e.camera),r.intersectObjects(e.objects,!0)},renderer:function(e){return e.renderer},scene:function(e){return e.scene},camera:function(e){return e.camera},postProcessingComposer:function(e){return e.postProcessingComposer},controls:function(e){return e.controls},tbControls:function(e){return e.controls}},stateInit:function(){return{scene:new tI.Scene,camera:new tI.PerspectiveCamera,clock:new tI.Clock,tweenGroup:new VD}},init:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=n.controlType,r=void 0===i?"trackball":i,s=n.useWebGPU,a=void 0!==s&&s,o=n.rendererConfig,l=void 0===o?{}:o,u=n.extraRenderers,c=void 0===u?[]:u,h=n.waitForLoadComplete,d=void 0===h||h;e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.className="scene-container",t.container.style.position="relative",t.container.appendChild(t.navInfo=document.createElement("div")),t.navInfo.className="scene-nav-info",t.navInfo.textContent={orbit:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",trackball:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",fly:"WASD: move, R|F: up | down, Q|E: roll, up|down: pitch, left|right: yaw"}[r]||"",t.navInfo.style.display=t.showNavInfo?null:"none",t.tooltip=new YL(t.container),t.pointerPos=new tI.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,["pointermove","pointerdown"].forEach((function(e){return t.container.addEventListener(e,(function(n){if("pointerdown"===e&&(t.isPointerPressed=!0),!t.isPointerDragging&&"pointermove"===n.type&&(n.pressure>0||t.isPointerPressed)&&("touch"!==n.pointerType||void 0===n.movementX||[n.movementX,n.movementY].some((function(e){return Math.abs(e)>1})))&&(t.isPointerDragging=!0),t.enablePointerInteraction){var i=(r=t.container,s=r.getBoundingClientRect(),a=window.pageXOffset||document.documentElement.scrollLeft,o=window.pageYOffset||document.documentElement.scrollTop,{top:s.top+o,left:s.left+a});t.pointerPos.x=n.pageX-i.left,t.pointerPos.y=n.pageY-i.top}var r,s,a,o}),{passive:!0})})),t.container.addEventListener("pointerup",(function(e){t.isPointerPressed=!1,t.isPointerDragging&&(t.isPointerDragging=!1,!t.clickAfterDrag)||requestAnimationFrame((function(){0===e.button&&t.onClick(t.hoverObj||null,e,t.intersection),2===e.button&&t.onRightClick&&t.onRightClick(t.hoverObj||null,e,t.intersection)}))}),{passive:!0,capture:!0}),t.container.addEventListener("contextmenu",(function(e){t.onRightClick&&e.preventDefault()})),t.renderer=new(a?MN:tI.WebGLRenderer)(Object.assign({antialias:!0,alpha:!0},l)),t.renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),t.container.appendChild(t.renderer.domElement),t.extraRenderers=c,t.extraRenderers.forEach((function(e){e.domElement.style.position="absolute",e.domElement.style.top="0px",e.domElement.style.pointerEvents="none",t.container.appendChild(e.domElement)})),t.postProcessingComposer=new tD(t.renderer),t.postProcessingComposer.addPass(new nD(t.scene,t.camera)),t.controls=new{trackball:WN,orbit:TP,fly:kP}[r](t.camera,t.renderer.domElement),"fly"===r&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),"trackball"!==r&&"orbit"!==r||(t.controls.minDistance=.1,t.controls.maxDistance=t.skyRadius,t.controls.addEventListener("start",(function(){t.controlsEngaged=!0})),t.controls.addEventListener("change",(function(){t.controlsEngaged&&(t.controlsDragging=!0)})),t.controls.addEventListener("end",(function(){t.controlsEngaged=!1,t.controlsDragging=!1}))),[t.renderer,t.postProcessingComposer].concat(JL(t.extraRenderers)).forEach((function(e){return e.setSize(t.width,t.height)})),t.camera.aspect=t.width/t.height,t.camera.updateProjectionMatrix(),t.camera.position.z=1e3,t.scene.add(t.skysphere=new tI.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!d,window.scene=t.scene},update:function(e,t){if(e.width&&e.height&&(t.hasOwnProperty("width")||t.hasOwnProperty("height"))){var n,i=e.width,r=e.height;e.container.style.width="".concat(i,"px"),e.container.style.height="".concat(r,"px"),[e.renderer,e.postProcessingComposer].concat(JL(e.extraRenderers)).forEach((function(e){return e.setSize(i,r)})),e.camera.aspect=i/r;var s=e.viewOffset.slice(0,2);s.some((function(e){return e}))&&(n=e.camera).setViewOffset.apply(n,[i,r].concat(JL(s),[i,r])),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){var a,o=e.width,l=e.height,u=e.viewOffset.slice(0,2);u.some((function(e){return e}))?(a=e.camera).setViewOffset.apply(a,[o,l].concat(JL(u),[o,l])):e.camera.clearViewOffset()}if(t.hasOwnProperty("skyRadius")&&e.skyRadius&&(e.controls.hasOwnProperty("maxDistance")&&t.skyRadius&&(e.controls.maxDistance=Math.min(e.controls.maxDistance,e.skyRadius)),e.camera.far=2.5*e.skyRadius,e.camera.updateProjectionMatrix(),e.skysphere.geometry=new tI.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var c=TD(e.backgroundColor).alpha;void 0===c&&(c=1),e.renderer.setClearColor(new tI.Color(kD(1,e.backgroundColor)),c)}function h(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new tI.TextureLoader).load(e.backgroundImageUrl,(function(t){t.colorSpace=tI.SRGBColorSpace,e.skysphere.material=new tI.MeshBasicMaterial({map:t,side:tI.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&h()})):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&h())),t.hasOwnProperty("showNavInfo")&&(e.navInfo.style.display=e.showNavInfo?null:"none"),t.hasOwnProperty("lights")&&((t.lights||[]).forEach((function(t){return e.scene.remove(t)})),e.lights.forEach((function(t){return e.scene.add(t)}))),t.hasOwnProperty("objects")&&((t.objects||[]).forEach((function(t){return e.scene.remove(t)})),e.objects.forEach((function(t){return e.scene.add(t)})))}});function iI(e,t){var n=new t;return n._destructor&&n._destructor(),{linkProp:function(t){return{default:n[t](),onChange:function(n,i){i[e][t](n)},triggerUpdate:!1}},linkMethod:function(t){return function(n){for(var i=n[e],r=arguments.length,s=new Array(r>1?r-1:0),a=1;a3?r-3:0),a=3;ae.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,l=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){l=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(l)throw a}}}}var u="undefined"==typeof window?null:window,c=u?u.navigator:null;u&&u.document;var d=e(""),h=e({}),p=e((function(){})),f="undefined"==typeof HTMLElement?"undefined":e(HTMLElement),g=function(e){return e&&e.instanceString&&y(e.instanceString)?e.instanceString():null},v=function(t){return null!=t&&e(t)==d},y=function(t){return null!=t&&e(t)===p},m=function(e){return!E(e)&&(Array.isArray?Array.isArray(e):null!=e&&e instanceof Array)},b=function(t){return null!=t&&e(t)===h&&!m(t)&&t.constructor===Object},x=function(t){return null!=t&&e(t)===e(1)&&!isNaN(t)},w=function(e){return"undefined"===f?void 0:null!=e&&e instanceof HTMLElement},E=function(e){return k(e)||C(e)},k=function(e){return"collection"===g(e)&&e._private.single},C=function(e){return"collection"===g(e)&&!e._private.single},S=function(e){return"core"===g(e)},P=function(e){return"stylesheet"===g(e)},D=function(e){return null==e||!(""!==e&&!e.match(/^\s+$/))},T=function(t){return function(t){return null!=t&&e(t)===h}(t)&&y(t.then)},_=function(e,t){t||(t=function(){if(1===arguments.length)return arguments[0];if(0===arguments.length)return"undefined";for(var e=[],t=0;tt?1:0},L=null!=Object.assign?Object.assign.bind(Object):function(e){for(var t=arguments,n=1;n255)return;t.push(Math.floor(a))}var o=r[1]||r[2]||r[3],s=r[1]&&r[2]&&r[3];if(o&&!s)return;var l=n[4];if(void 0!==l){if((l=parseFloat(l))<0||l>1)return;t.push(l)}}return t}(e)||function(e){var t,n,r,i,a,o,s,l;function u(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}var c=new RegExp("^hsl[a]?\\(((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?)))\\s*,\\s*((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))[%])\\s*,\\s*((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))[%])(?:\\s*,\\s*((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))))?\\)$").exec(e);if(c){if((n=parseInt(c[1]))<0?n=(360- -1*n%360)%360:n>360&&(n%=360),n/=360,(r=parseFloat(c[2]))<0||r>100)return;if(r/=100,(i=parseFloat(c[3]))<0||i>100)return;if(i/=100,void 0!==(a=c[4])&&((a=parseFloat(a))<0||a>1))return;if(0===r)o=s=l=Math.round(255*i);else{var d=i<.5?i*(1+r):i+r-i*r,h=2*i-d;o=Math.round(255*u(h,d,n+1/3)),s=Math.round(255*u(h,d,n)),l=Math.round(255*u(h,d,n-1/3))}t=[o,s,l,a]}return t}(e)},R={transparent:[0,0,0,0],aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],grey:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},V=function(e){for(var t=e.map,n=e.keys,r=n.length,i=0;i=t||n<0||d&&e-u>=a}function v(){var e=H();if(g(e))return y(e);s=setTimeout(v,function(e){var n=t-(e-l);return d?ge(n,a-(e-u)):n}(e))}function y(e){return s=void 0,h&&r?p(e):(r=i=void 0,o)}function m(){var e=H(),n=g(e);if(r=arguments,i=this,l=e,n){if(void 0===s)return f(l);if(d)return clearTimeout(s),s=setTimeout(v,t),p(l)}return void 0===s&&(s=setTimeout(v,t)),o}return t=pe(t)||0,j(n)&&(c=!!n.leading,a=(d="maxWait"in n)?fe(pe(n.maxWait)||0,t):a,h="trailing"in n?!!n.trailing:h),m.cancel=function(){void 0!==s&&clearTimeout(s),u=0,r=l=i=s=void 0},m.flush=function(){return void 0===s?o:y(H())},m},ye=u?u.performance:null,me=ye&&ye.now?function(){return ye.now()}:function(){return Date.now()},be=function(){if(u){if(u.requestAnimationFrame)return function(e){u.requestAnimationFrame(e)};if(u.mozRequestAnimationFrame)return function(e){u.mozRequestAnimationFrame(e)};if(u.webkitRequestAnimationFrame)return function(e){u.webkitRequestAnimationFrame(e)};if(u.msRequestAnimationFrame)return function(e){u.msRequestAnimationFrame(e)}}return function(e){e&&setTimeout((function(){e(me())}),1e3/60)}}(),xe=function(e){return be(e)},we=me,Ee=65599,ke=function(e){for(var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:9261,r=n;!(t=e.next()).done;)r=r*Ee+t.value|0;return r},Ce=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:9261;return t*Ee+e|0},Se=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5381;return(t<<5)+t+e|0},Pe=function(e){return 2097152*e[0]+e[1]},De=function(e,t){return[Ce(e[0],t[0]),Se(e[1],t[1])]},Te=function(e,t){var n={value:0,done:!1},r=0,i=e.length;return ke({next:function(){return r=0&&(e[r]!==t||(e.splice(r,1),!n));r--);},Ge=function(e){e.splice(0,e.length)},Ue=function(e,t,n){return n&&(t=N(n,t)),e[t]},Ze=function(e,t,n,r){n&&(t=N(n,t)),e[t]=r},$e="undefined"!=typeof Map?Map:function(){function e(){t(this,e),this._obj={}}return r(e,[{key:"set",value:function(e,t){return this._obj[e]=t,this}},{key:"delete",value:function(e){return this._obj[e]=void 0,this}},{key:"clear",value:function(){this._obj={}}},{key:"has",value:function(e){return void 0!==this._obj[e]}},{key:"get",value:function(e){return this._obj[e]}}]),e}(),Qe=function(){function e(n){if(t(this,e),this._obj=Object.create(null),this.size=0,null!=n){var r;r=null!=n.instanceString&&n.instanceString()===this.instanceString()?n.toArray():n;for(var i=0;i2&&void 0!==arguments[2])||arguments[2];if(void 0!==e&&void 0!==t&&S(e)){var r=t.group;if(null==r&&(r=t.data&&null!=t.data.source&&null!=t.data.target?"edges":"nodes"),"nodes"===r||"edges"===r){this.length=1,this[0]=this;var i=this._private={cy:e,single:!0,data:t.data||{},position:t.position||{x:0,y:0},autoWidth:void 0,autoHeight:void 0,autoPadding:void 0,compoundBoundsClean:!1,listeners:[],group:r,style:{},rstyle:{},styleCxts:[],styleKeys:{},removed:!0,selected:!!t.selected,selectable:void 0===t.selectable||!!t.selectable,locked:!!t.locked,grabbed:!1,grabbable:void 0===t.grabbable||!!t.grabbable,pannable:void 0===t.pannable?"edges"===r:!!t.pannable,active:!1,classes:new Je,animation:{current:[],queue:[]},rscratch:{},scratch:t.scratch||{},edges:[],children:[],parent:t.parent&&t.parent.isNode()?t.parent:null,traversalCache:{},backgrounding:!1,bbCache:null,bbCacheShift:{x:0,y:0},bodyBounds:null,overlayBounds:null,labelBounds:{all:null,source:null,target:null,main:null},arrowBounds:{source:null,target:null,"mid-source":null,"mid-target":null}};if(null==i.position.x&&(i.position.x=0),null==i.position.y&&(i.position.y=0),t.renderedPosition){var a=t.renderedPosition,o=e.pan(),s=e.zoom();i.position={x:(a.x-o.x)/s,y:(a.y-o.y)/s}}var l=[];m(t.classes)?l=t.classes:v(t.classes)&&(l=t.classes.split(/\s+/));for(var u=0,c=l.length;ut?1:0},u=function(e,t,i,a,o){var s;if(null==i&&(i=0),null==o&&(o=n),i<0)throw new Error("lo must be non-negative");for(null==a&&(a=e.length);in;0<=n?t++:t--)u.push(t);return u}.apply(this).reverse()).length;ag;0<=g?++h:--h)v.push(a(e,r));return v},f=function(e,t,r,i){var a,o,s;for(null==i&&(i=n),a=e[r];r>t&&i(a,o=e[s=r-1>>1])<0;)e[r]=o,r=s;return e[r]=a},g=function(e,t,r){var i,a,o,s,l;for(null==r&&(r=n),a=e.length,l=t,o=e[t],i=2*t+1;i0;){var k=m.pop(),C=g(k),S=k.id();if(d[S]=C,C!==1/0)for(var P=k.neighborhood().intersect(p),D=0;D0)for(n.unshift(t);c[i];){var a=c[i];n.unshift(a.edge),n.unshift(a.node),i=(r=a.node).id()}return o.spawn(n)}}}},ot={kruskal:function(e){e=e||function(e){return 1};for(var t=this.byGroup(),n=t.nodes,r=t.edges,i=n.length,a=new Array(i),o=n,s=function(e){for(var t=0;t0;){if(l=g.pop(),u=l.id(),v.delete(u),w++,u===d){for(var E=[],k=i,C=d,S=m[C];E.unshift(k),null!=S&&E.unshift(S),null!=(k=y[C]);)S=m[C=k.id()];return{found:!0,distance:h[u],path:this.spawn(E),steps:w}}f[u]=!0;for(var P=l._private.edges,D=0;DD&&(p[P]=D,m[P]=S,b[P]=w),!i){var T=S*u+C;!i&&p[T]>D&&(p[T]=D,m[T]=C,b[T]=w)}}}for(var _=0;_1&&void 0!==arguments[1]?arguments[1]:a,r=b(e),i=[],o=r;;){if(null==o)return t.spawn();var l=m(o),u=l.edge,c=l.pred;if(i.unshift(o[0]),o.same(n)&&i.length>0)break;null!=u&&i.unshift(u),o=c}return s.spawn(i)},hasNegativeWeightCycle:f,negativeWeightCycles:g}}},pt=Math.sqrt(2),ft=function(e,t,n){0===n.length&&Ve("Karger-Stein must be run on a connected (sub)graph");for(var r=n[e],i=r[1],a=r[2],o=t[i],s=t[a],l=n,u=l.length-1;u>=0;u--){var c=l[u],d=c[1],h=c[2];(t[d]===o&&t[h]===s||t[d]===s&&t[h]===o)&&l.splice(u,1)}for(var p=0;pr;){var i=Math.floor(Math.random()*t.length);t=ft(i,e,t),n--}return t},vt={kargerStein:function(){var e=this,t=this.byGroup(),n=t.nodes,r=t.edges;r.unmergeBy((function(e){return e.isLoop()}));var i=n.length,a=r.length,o=Math.ceil(Math.pow(Math.log(i)/Math.LN2,2)),s=Math.floor(i/pt);if(!(i<2)){for(var l=[],u=0;u0?1:e<0?-1:0},kt=function(e,t){return Math.sqrt(Ct(e,t))},Ct=function(e,t){var n=t.x-e.x,r=t.y-e.y;return n*n+r*r},St=function(e){for(var t=e.length,n=0,r=0;r=e.x1&&e.y2>=e.y1)return{x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,w:e.x2-e.x1,h:e.y2-e.y1};if(null!=e.w&&null!=e.h&&e.w>=0&&e.h>=0)return{x1:e.x1,y1:e.y1,x2:e.x1+e.w,y2:e.y1+e.h,w:e.w,h:e.h}}},Mt=function(e,t){e.x1=Math.min(e.x1,t.x1),e.x2=Math.max(e.x2,t.x2),e.w=e.x2-e.x1,e.y1=Math.min(e.y1,t.y1),e.y2=Math.max(e.y2,t.y2),e.h=e.y2-e.y1},Bt=function(e,t,n){e.x1=Math.min(e.x1,t),e.x2=Math.max(e.x2,t),e.w=e.x2-e.x1,e.y1=Math.min(e.y1,n),e.y2=Math.max(e.y2,n),e.h=e.y2-e.y1},Nt=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return e.x1-=t,e.x2+=t,e.y1-=t,e.y2+=t,e.w=e.x2-e.x1,e.h=e.y2-e.y1,e},zt=function(e){var t,n,r,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[0];if(1===o.length)t=n=r=i=o[0];else if(2===o.length)t=r=o[0],i=n=o[1];else if(4===o.length){var s=a(o,4);t=s[0],n=s[1],r=s[2],i=s[3]}return e.x1-=i,e.x2+=n,e.y1-=t,e.y2+=r,e.w=e.x2-e.x1,e.h=e.y2-e.y1,e},It=function(e,t){e.x1=t.x1,e.y1=t.y1,e.x2=t.x2,e.y2=t.y2,e.w=e.x2-e.x1,e.h=e.y2-e.y1},At=function(e,t){return!(e.x1>t.x2)&&(!(t.x1>e.x2)&&(!(e.x2t.y2)&&!(t.y1>e.y2)))))))},Lt=function(e,t,n){return e.x1<=t&&t<=e.x2&&e.y1<=n&&n<=e.y2},Ot=function(e,t){return Lt(e,t.x1,t.y1)&&Lt(e,t.x2,t.y2)},Rt=function(e,t,n,r,i,a,o){var s,l,u=arguments.length>7&&void 0!==arguments[7]?arguments[7]:"auto",c="auto"===u?nn(i,a):u,d=i/2,h=a/2,p=(c=Math.min(c,d,h))!==d,f=c!==h;if(p){var g=n-d+c-o,v=r-h-o,y=n+d-c+o,m=v;if((s=Zt(e,t,n,r,g,v,y,m,!1)).length>0)return s}if(f){var b=n+d+o,x=r-h+c-o,w=b,E=r+h-c+o;if((s=Zt(e,t,n,r,b,x,w,E,!1)).length>0)return s}if(p){var k=n-d+c-o,C=r+h+o,S=n+d-c+o,P=C;if((s=Zt(e,t,n,r,k,C,S,P,!1)).length>0)return s}if(f){var D=n-d-o,T=r-h+c-o,_=D,M=r+h-c+o;if((s=Zt(e,t,n,r,D,T,_,M,!1)).length>0)return s}var B=n-d+c,N=r-h+c;if((l=Gt(e,t,n,r,B,N,c+o)).length>0&&l[0]<=B&&l[1]<=N)return[l[0],l[1]];var z=n+d-c,I=r-h+c;if((l=Gt(e,t,n,r,z,I,c+o)).length>0&&l[0]>=z&&l[1]<=I)return[l[0],l[1]];var A=n+d-c,L=r+h-c;if((l=Gt(e,t,n,r,A,L,c+o)).length>0&&l[0]>=A&&l[1]>=L)return[l[0],l[1]];var O=n-d+c,R=r+h-c;return(l=Gt(e,t,n,r,O,R,c+o)).length>0&&l[0]<=O&&l[1]>=R?[l[0],l[1]]:[]},Vt=function(e,t,n,r,i,a,o){var s=o,l=Math.min(n,i),u=Math.max(n,i),c=Math.min(r,a),d=Math.max(r,a);return l-s<=e&&e<=u+s&&c-s<=t&&t<=d+s},Ft=function(e,t,n,r,i,a,o,s,l){var u=Math.min(n,o,i)-l,c=Math.max(n,o,i)+l,d=Math.min(r,s,a)-l,h=Math.max(r,s,a)+l;return!(ec||th)},jt=function(e,t,n,r,i,a,o,s){var l=[];!function(e,t,n,r,i){var a,o,s,l,u,c,d,h;0===e&&(e=1e-5),s=-27*(r/=e)+(t/=e)*(9*(n/=e)-t*t*2),a=(o=(3*n-t*t)/9)*o*o+(s/=54)*s,i[1]=0,d=t/3,a>0?(u=(u=s+Math.sqrt(a))<0?-Math.pow(-u,1/3):Math.pow(u,1/3),c=(c=s-Math.sqrt(a))<0?-Math.pow(-c,1/3):Math.pow(c,1/3),i[0]=-d+u+c,d+=(u+c)/2,i[4]=i[2]=-d,d=Math.sqrt(3)*(-c+u)/2,i[3]=d,i[5]=-d):(i[5]=i[3]=0,0===a?(h=s<0?-Math.pow(-s,1/3):Math.pow(s,1/3),i[0]=2*h-d,i[4]=i[2]=-(h+d)):(l=(o=-o)*o*o,l=Math.acos(s/Math.sqrt(l)),h=2*Math.sqrt(o),i[0]=-d+h*Math.cos(l/3),i[2]=-d+h*Math.cos((l+2*Math.PI)/3),i[4]=-d+h*Math.cos((l+4*Math.PI)/3)))}(1*n*n-4*n*i+2*n*o+4*i*i-4*i*o+o*o+r*r-4*r*a+2*r*s+4*a*a-4*a*s+s*s,9*n*i-3*n*n-3*n*o-6*i*i+3*i*o+9*r*a-3*r*r-3*r*s-6*a*a+3*a*s,3*n*n-6*n*i+n*o-n*e+2*i*i+2*i*e-o*e+3*r*r-6*r*a+r*s-r*t+2*a*a+2*a*t-s*t,1*n*i-n*n+n*e-i*e+r*a-r*r+r*t-a*t,l);for(var u=[],c=0;c<6;c+=2)Math.abs(l[c+1])<1e-7&&l[c]>=0&&l[c]<=1&&u.push(l[c]);u.push(1),u.push(0);for(var d,h,p,f=-1,g=0;g=0?pl?(e-i)*(e-i)+(t-a)*(t-a):u-d},Yt=function(e,t,n){for(var r,i,a,o,s=0,l=0;l=e&&e>=a||r<=e&&e<=a))continue;(e-r)/(a-r)*(o-i)+i>t&&s++}return s%2!=0},Xt=function(e,t,n,r,i,a,o,s,l){var u,c=new Array(n.length);null!=s[0]?(u=Math.atan(s[1]/s[0]),s[0]<0?u+=Math.PI/2:u=-u-Math.PI/2):u=s;for(var d,h=Math.cos(-u),p=Math.sin(-u),f=0;f0){var g=Ht(c,-l);d=Wt(g)}else d=c;return Yt(e,t,d)},Wt=function(e){for(var t,n,r,i,a,o,s,l,u=new Array(e.length/2),c=0;c=0&&f<=1&&v.push(f),g>=0&&g<=1&&v.push(g),0===v.length)return[];var y=v[0]*s[0]+e,m=v[0]*s[1]+t;return v.length>1?v[0]==v[1]?[y,m]:[y,m,v[1]*s[0]+e,v[1]*s[1]+t]:[y,m]},Ut=function(e,t,n){return t<=e&&e<=n||n<=e&&e<=t?e:e<=t&&t<=n||n<=t&&t<=e?t:n},Zt=function(e,t,n,r,i,a,o,s,l){var u=e-i,c=n-e,d=o-i,h=t-a,p=r-t,f=s-a,g=d*h-f*u,v=c*h-p*u,y=f*c-d*p;if(0!==y){var m=g/y,b=v/y;return-.001<=m&&m<=1.001&&-.001<=b&&b<=1.001||l?[e+m*c,t+m*p]:[]}return 0===g||0===v?Ut(e,n,o)===o?[o,s]:Ut(e,n,i)===i?[i,a]:Ut(i,o,n)===n?[n,r]:[]:[]},$t=function(e,t,n,r,i,a,o,s){var l,u,c,d,h,p,f=[],g=new Array(n.length),v=!0;if(null==a&&(v=!1),v){for(var y=0;y0){var m=Ht(g,-s);u=Wt(m)}else u=g}else u=n;for(var b=0;bu&&(u=t)},d=function(e){return l[e]},h=0;h0?b.edgesTo(m)[0]:m.edgesTo(b)[0];var w=r(x);m=m.id(),h[m]>h[v]+w&&(h[m]=h[v]+w,p.nodes.indexOf(m)<0?p.push(m):p.updateItem(m),u[m]=0,l[m]=[]),h[m]==h[v]+w&&(u[m]=u[m]+u[v],l[m].push(v))}else for(var E=0;E0;){for(var P=n.pop(),D=0;D0&&o.push(n[s]);0!==o.length&&i.push(r.collection(o))}return i}(c,l,t,r);return b=function(e){for(var t=0;t5&&void 0!==arguments[5]?arguments[5]:Cn,o=r,s=0;s=2?Mn(e,t,n,0,Dn,Tn):Mn(e,t,n,0,Pn)},squaredEuclidean:function(e,t,n){return Mn(e,t,n,0,Dn)},manhattan:function(e,t,n){return Mn(e,t,n,0,Pn)},max:function(e,t,n){return Mn(e,t,n,-1/0,_n)}};function Nn(e,t,n,r,i,a){var o;return o=y(e)?e:Bn[e]||Bn.euclidean,0===t&&y(e)?o(i,a):o(t,n,r,i,a)}Bn["squared-euclidean"]=Bn.squaredEuclidean,Bn.squaredeuclidean=Bn.squaredEuclidean;var zn=He({k:2,m:2,sensitivityThreshold:1e-4,distance:"euclidean",maxIterations:10,attributes:[],testMode:!1,testCentroids:null}),In=function(e){return zn(e)},An=function(e,t,n,r,i){var a="kMedoids"!==i?function(e){return n[e]}:function(e){return r[e](n)},o=n,s=t;return Nn(e,r.length,a,(function(e){return r[e](t)}),o,s)},Ln=function(e,t,n){for(var r=n.length,i=new Array(r),a=new Array(r),o=new Array(t),s=null,l=0;ln)return!1}return!0},jn=function(e,t,n){for(var r=0;ri&&(i=t[l][u],a=u);o[a].push(e[l])}for(var c=0;c=i.threshold||"dendrogram"===i.mode&&1===e.length)return!1;var p,f=t[o],g=t[r[o]];p="dendrogram"===i.mode?{left:f,right:g,key:f.key}:{value:f.value.concat(g.value),key:f.key},e[f.index]=p,e.splice(g.index,1),t[f.key]=p;for(var v=0;vn[g.key][y.key]&&(a=n[g.key][y.key])):"max"===i.linkage?(a=n[f.key][y.key],n[f.key][y.key]1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],a=!(arguments.length>5&&void 0!==arguments[5])||arguments[5];r?e=e.slice(t,n):(n0&&e.splice(0,t));for(var o=0,s=e.length-1;s>=0;s--){var l=e[s];a?isFinite(l)||(e[s]=-1/0,o++):e.splice(s,1)}i&&e.sort((function(e,t){return e-t}));var u=e.length,c=Math.floor(u/2);return u%2!=0?e[c+1+o]:(e[c-1+o]+e[c+o])/2}(e):"mean"===t?function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,r=0,i=0,a=t;a1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,r=1/0,i=t;i1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,r=-1/0,i=t;io&&(a=l,o=t[i*e+l])}a>0&&r.push(a)}for(var u=0;u=D?(T=D,D=M,_=B):M>T&&(T=M);for(var N=0;N0?1:0;C[k%u.minIterations*t+R]=V,O+=V}if(O>0&&(k>=u.minIterations-1||k==u.maxIterations-1)){for(var F=0,j=0;j0&&r.push(i);return r}(t,a,o),X=function(e,t,n){for(var r=rr(e,t,n),i=0;il&&(s=u,l=c)}n[i]=a[s]}return r=rr(e,t,n)}(t,r,Y),W={},H=0;H1)}}));var l=Object.keys(t).filter((function(e){return t[e].cutVertex})).map((function(t){return e.getElementById(t)}));return{cut:e.spawn(l),components:i}},lr=function(){var e=this,t={},n=0,r=[],i=[],a=e.spawn(e);return e.forEach((function(o){if(o.isNode()){var s=o.id();s in t||function o(s){if(i.push(s),t[s]={index:n,low:n++,explored:!1},e.getElementById(s).connectedEdges().intersection(e).forEach((function(e){var n=e.target().id();n!==s&&(n in t||o(n),t[n].explored||(t[s].low=Math.min(t[s].low,t[n].low)))})),t[s].index===t[s].low){for(var l=e.spawn();;){var u=i.pop();if(l.merge(e.getElementById(u)),t[u].low=t[s].index,t[u].explored=!0,u===s)break}var c=l.edgesWith(l),d=l.merge(c);r.push(d),a=a.difference(d)}}(s)}})),{cut:a,components:r}},ur={};[nt,at,ot,lt,ct,ht,vt,sn,un,dn,pn,kn,Kn,Jn,ar,{hierholzer:function(e){if(!b(e)){var t=arguments;e={root:t[0],directed:t[1]}}var n,r,i,a=or(e),o=a.root,s=a.directed,l=this,u=!1;o&&(i=v(o)?this.filter(o)[0].id():o[0].id());var c={},d={};s?l.forEach((function(e){var t=e.id();if(e.isNode()){var i=e.indegree(!0),a=e.outdegree(!0),o=i-a,s=a-i;1==o?n?u=!0:n=t:1==s?r?u=!0:r=t:(s>1||o>1)&&(u=!0),c[t]=[],e.outgoers().forEach((function(e){e.isEdge()&&c[t].push(e.id())}))}else d[t]=[void 0,e.target().id()]})):l.forEach((function(e){var t=e.id();e.isNode()?(e.degree(!0)%2&&(n?r?u=!0:r=t:n=t),c[t]=[],e.connectedEdges().forEach((function(e){return c[t].push(e.id())}))):d[t]=[e.source().id(),e.target().id()]}));var h={found:!1,trail:void 0};if(u)return h;if(r&&n)if(s){if(i&&r!=i)return h;i=r}else{if(i&&r!=i&&n!=i)return h;i||(i=r)}else i||(i=l[0].id());var p=function(e){for(var t,n,r,i=e,a=[e];c[i].length;)t=c[i].shift(),n=d[t][0],i!=(r=d[t][1])?(c[r]=c[r].filter((function(e){return e!=t})),i=r):s||i==n||(c[n]=c[n].filter((function(e){return e!=t})),i=n),a.unshift(t),a.unshift(i);return a},f=[],g=[];for(g=p(i);1!=g.length;)0==c[g[0]].length?(f.unshift(l.getElementById(g.shift())),f.unshift(l.getElementById(g.shift()))):g=p(g.shift()).concat(g);for(var y in f.unshift(l.getElementById(g.shift())),c)if(c[y].length)return h;return h.found=!0,h.trail=this.spawn(f,!0),h}},{hopcroftTarjanBiconnected:sr,htbc:sr,htb:sr,hopcroftTarjanBiconnectedComponents:sr},{tarjanStronglyConnected:lr,tsc:lr,tscc:lr,tarjanStronglyConnectedComponents:lr}].forEach((function(e){L(ur,e)})); +/*! + Embeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable + Copyright (c) 2013-2014 Ralf S. Engelschall (http://engelschall.com) + Licensed under The MIT License (http://opensource.org/licenses/MIT) + */ +var cr=function e(t){if(!(this instanceof e))return new e(t);this.id="Thenable/1.0.7",this.state=0,this.fulfillValue=void 0,this.rejectReason=void 0,this.onFulfilled=[],this.onRejected=[],this.proxy={then:this.then.bind(this)},"function"==typeof t&&t.call(this,this.fulfill.bind(this),this.reject.bind(this))};cr.prototype={fulfill:function(e){return dr(this,1,"fulfillValue",e)},reject:function(e){return dr(this,2,"rejectReason",e)},then:function(e,t){var n=new cr;return this.onFulfilled.push(fr(e,n,"fulfill")),this.onRejected.push(fr(t,n,"reject")),hr(this),n.proxy}};var dr=function(e,t,n,r){return 0===e.state&&(e.state=t,e[n]=r,hr(e)),e},hr=function(e){1===e.state?pr(e,"onFulfilled",e.fulfillValue):2===e.state&&pr(e,"onRejected",e.rejectReason)},pr=function(e,t,n){if(0!==e[t].length){var r=e[t];e[t]=[];var i=function(){for(var e=0;e0:void 0}},clearQueue:function(){return function(){var e=void 0!==this.length?this:[this];if(!(this._private.cy||this).styleEnabled())return this;for(var t=0;t-1};var ri=function(e,t){var n=this.__data__,r=Qr(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this};function ii(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t-1&&e%1==0&&e0&&this.spawn(n).updateStyle().emit("class"),this},addClass:function(e){return this.toggleClass(e,!0)},hasClass:function(e){var t=this[0];return null!=t&&t._private.classes.has(e)},toggleClass:function(e,t){m(e)||(e=e.match(/\S+/g)||[]);for(var n=void 0===t,r=[],i=0,a=this.length;i0&&this.spawn(r).updateStyle().emit("class"),this},removeClass:function(e){return this.toggleClass(e,!1)},flashClass:function(e,t){var n=this;if(null==t)t=250;else if(0===t)return n;return n.addClass(e),setTimeout((function(){n.removeClass(e)}),t),n}};qi.className=qi.classNames=qi.classes;var Yi={metaChar:"[\\!\\\"\\#\\$\\%\\&\\'\\(\\)\\*\\+\\,\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\]\\^\\`\\{\\|\\}\\~]",comparatorOp:"=|\\!=|>|>=|<|<=|\\$=|\\^=|\\*=",boolOp:"\\?|\\!|\\^",string:"\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'",number:I,meta:"degree|indegree|outdegree",separator:"\\s*,\\s*",descendant:"\\s+",child:"\\s+>\\s+",subject:"\\$",group:"node|edge|\\*",directedEdge:"\\s+->\\s+",undirectedEdge:"\\s+<->\\s+"};Yi.variable="(?:[\\w-.]|(?:\\\\"+Yi.metaChar+"))+",Yi.className="(?:[\\w-]|(?:\\\\"+Yi.metaChar+"))+",Yi.value=Yi.string+"|"+Yi.number,Yi.id=Yi.variable,function(){var e,t,n;for(e=Yi.comparatorOp.split("|"),n=0;n=0||"="!==t&&(Yi.comparatorOp+="|\\!"+t)}();var Xi=0,Wi=1,Hi=2,Ki=3,Gi=4,Ui=5,Zi=6,$i=7,Qi=8,Ji=9,ea=10,ta=11,na=12,ra=13,ia=14,aa=15,oa=16,sa=17,la=18,ua=19,ca=20,da=[{selector:":selected",matches:function(e){return e.selected()}},{selector:":unselected",matches:function(e){return!e.selected()}},{selector:":selectable",matches:function(e){return e.selectable()}},{selector:":unselectable",matches:function(e){return!e.selectable()}},{selector:":locked",matches:function(e){return e.locked()}},{selector:":unlocked",matches:function(e){return!e.locked()}},{selector:":visible",matches:function(e){return e.visible()}},{selector:":hidden",matches:function(e){return!e.visible()}},{selector:":transparent",matches:function(e){return e.transparent()}},{selector:":grabbed",matches:function(e){return e.grabbed()}},{selector:":free",matches:function(e){return!e.grabbed()}},{selector:":removed",matches:function(e){return e.removed()}},{selector:":inside",matches:function(e){return!e.removed()}},{selector:":grabbable",matches:function(e){return e.grabbable()}},{selector:":ungrabbable",matches:function(e){return!e.grabbable()}},{selector:":animated",matches:function(e){return e.animated()}},{selector:":unanimated",matches:function(e){return!e.animated()}},{selector:":parent",matches:function(e){return e.isParent()}},{selector:":childless",matches:function(e){return e.isChildless()}},{selector:":child",matches:function(e){return e.isChild()}},{selector:":orphan",matches:function(e){return e.isOrphan()}},{selector:":nonorphan",matches:function(e){return e.isChild()}},{selector:":compound",matches:function(e){return e.isNode()?e.isParent():e.source().isParent()||e.target().isParent()}},{selector:":loop",matches:function(e){return e.isLoop()}},{selector:":simple",matches:function(e){return e.isSimple()}},{selector:":active",matches:function(e){return e.active()}},{selector:":inactive",matches:function(e){return!e.active()}},{selector:":backgrounding",matches:function(e){return e.backgrounding()}},{selector:":nonbackgrounding",matches:function(e){return!e.backgrounding()}}].sort((function(e,t){return function(e,t){return-1*A(e,t)}(e.selector,t.selector)})),ha=function(){for(var e,t={},n=0;n0&&l.edgeCount>0)return je("The selector `"+e+"` is invalid because it uses both a compound selector and an edge selector"),!1;if(l.edgeCount>1)return je("The selector `"+e+"` is invalid because it uses multiple edge selectors"),!1;1===l.edgeCount&&je("The selector `"+e+"` is deprecated. Edge selectors do not take effect on changes to source and target nodes after an edge is added, for performance reasons. Use a class or data selector on edges instead, updating the class or data of an edge when your app detects a change in source or target nodes.")}return!0},toString:function(){if(null!=this.toStringCache)return this.toStringCache;for(var e=function(e){return null==e?"":e},t=function(t){return v(t)?'"'+t+'"':e(t)},n=function(e){return" "+e+" "},r=function(r,a){var o=r.type,s=r.value;switch(o){case Xi:var l=e(s);return l.substring(0,l.length-1);case Ki:var u=r.field,c=r.operator;return"["+u+n(e(c))+t(s)+"]";case Ui:var d=r.operator,h=r.field;return"["+e(d)+h+"]";case Gi:return"["+r.field+"]";case Zi:var p=r.operator;return"[["+r.field+n(e(p))+t(s)+"]]";case $i:return s;case Qi:return"#"+s;case Ji:return"."+s;case sa:case aa:return i(r.parent,a)+n(">")+i(r.child,a);case la:case oa:return i(r.ancestor,a)+" "+i(r.descendant,a);case ua:var f=i(r.left,a),g=i(r.subject,a),v=i(r.right,a);return f+(f.length>0?" ":"")+g+v;case ca:return""}},i=function(e,t){return e.checks.reduce((function(n,i,a){return n+(t===e&&0===a?"$":"")+r(i,t)}),"")},a="",o=0;o1&&o=0&&(t=t.replace("!",""),c=!0),t.indexOf("@")>=0&&(t=t.replace("@",""),u=!0),(o||l||u)&&(i=o||s?""+e:"",a=""+n),u&&(e=i=i.toLowerCase(),n=a=a.toLowerCase()),t){case"*=":r=i.indexOf(a)>=0;break;case"$=":r=i.indexOf(a,i.length-a.length)>=0;break;case"^=":r=0===i.indexOf(a);break;case"=":r=e===n;break;case">":d=!0,r=e>n;break;case">=":d=!0,r=e>=n;break;case"<":d=!0,r=e0;){var u=i.shift();t(u),a.add(u.id()),o&&r(i,a,u)}return e}function Ba(e,t,n){if(n.isParent())for(var r=n._private.children,i=0;i1&&void 0!==arguments[1])||arguments[1];return Ma(this,e,t,Ba)},_a.forEachUp=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ma(this,e,t,Na)},_a.forEachUpAndDown=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ma(this,e,t,za)},_a.ancestors=_a.parents,(Pa=Da={data:Fi.data({field:"data",bindingEvent:"data",allowBinding:!0,allowSetting:!0,settingEvent:"data",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,immutableKeys:{id:!0,source:!0,target:!0,parent:!0},updateStyle:!0}),removeData:Fi.removeData({field:"data",event:"data",triggerFnName:"trigger",triggerEvent:!0,immutableKeys:{id:!0,source:!0,target:!0,parent:!0},updateStyle:!0}),scratch:Fi.data({field:"scratch",bindingEvent:"scratch",allowBinding:!0,allowSetting:!0,settingEvent:"scratch",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeScratch:Fi.removeData({field:"scratch",event:"scratch",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0}),rscratch:Fi.data({field:"rscratch",allowBinding:!1,allowSetting:!0,settingTriggersEvent:!1,allowGetting:!0}),removeRscratch:Fi.removeData({field:"rscratch",triggerEvent:!1}),id:function(){var e=this[0];if(e)return e._private.data.id}}).attr=Pa.data,Pa.removeAttr=Pa.removeData;var Ia,Aa,La=Da,Oa={};function Ra(e){return function(t){if(void 0===t&&(t=!0),0!==this.length&&this.isNode()&&!this.removed()){for(var n=0,r=this[0],i=r._private.edges,a=0;at})),minIndegree:Va("indegree",(function(e,t){return et})),minOutdegree:Va("outdegree",(function(e,t){return et}))}),L(Oa,{totalDegree:function(e){for(var t=0,n=this.nodes(),r=0;r0,c=u;u&&(l=l[0]);var d=c?l.position():{x:0,y:0};return i={x:s.x-d.x,y:s.y-d.y},void 0===e?i:i[e]}for(var h=0;h0,y=g;g&&(f=f[0]);var m=y?f.position():{x:0,y:0};void 0!==t?p.position(e,t+m[e]):void 0!==i&&p.position({x:i.x+m.x,y:i.y+m.y})}}else if(!a)return;return this}}).modelPosition=Ia.point=Ia.position,Ia.modelPositions=Ia.points=Ia.positions,Ia.renderedPoint=Ia.renderedPosition,Ia.relativePoint=Ia.relativePosition;var qa,Ya,Xa=Aa;qa=Ya={},Ya.renderedBoundingBox=function(e){var t=this.boundingBox(e),n=this.cy(),r=n.zoom(),i=n.pan(),a=t.x1*r+i.x,o=t.x2*r+i.x,s=t.y1*r+i.y,l=t.y2*r+i.y;return{x1:a,x2:o,y1:s,y2:l,w:o-a,h:l-s}},Ya.dirtyCompoundBoundsCache=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.cy();return t.styleEnabled()&&t.hasCompoundNodes()?(this.forEachUp((function(t){if(t.isParent()){var n=t._private;n.compoundBoundsClean=!1,n.bbCache=null,e||t.emitAndNotify("bounds")}})),this):this},Ya.updateCompoundBounds=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.cy();if(!t.styleEnabled()||!t.hasCompoundNodes())return this;if(!e&&t.batching())return this;function n(e){if(e.isParent()){var t=e._private,n=e.children(),r="include"===e.pstyle("compound-sizing-wrt-labels").value,i={width:{val:e.pstyle("min-width").pfValue,left:e.pstyle("min-width-bias-left"),right:e.pstyle("min-width-bias-right")},height:{val:e.pstyle("min-height").pfValue,top:e.pstyle("min-height-bias-top"),bottom:e.pstyle("min-height-bias-bottom")}},a=n.boundingBox({includeLabels:r,includeOverlays:!1,useCache:!1}),o=t.position;0!==a.w&&0!==a.h||((a={w:e.pstyle("width").pfValue,h:e.pstyle("height").pfValue}).x1=o.x-a.w/2,a.x2=o.x+a.w/2,a.y1=o.y-a.h/2,a.y2=o.y+a.h/2);var s=i.width.left.value;"px"===i.width.left.units&&i.width.val>0&&(s=100*s/i.width.val);var l=i.width.right.value;"px"===i.width.right.units&&i.width.val>0&&(l=100*l/i.width.val);var u=i.height.top.value;"px"===i.height.top.units&&i.height.val>0&&(u=100*u/i.height.val);var c=i.height.bottom.value;"px"===i.height.bottom.units&&i.height.val>0&&(c=100*c/i.height.val);var d=y(i.width.val-a.w,s,l),h=d.biasDiff,p=d.biasComplementDiff,f=y(i.height.val-a.h,u,c),g=f.biasDiff,v=f.biasComplementDiff;t.autoPadding=function(e,t,n,r){if("%"!==n.units)return"px"===n.units?n.pfValue:0;switch(r){case"width":return e>0?n.pfValue*e:0;case"height":return t>0?n.pfValue*t:0;case"average":return e>0&&t>0?n.pfValue*(e+t)/2:0;case"min":return e>0&&t>0?e>t?n.pfValue*t:n.pfValue*e:0;case"max":return e>0&&t>0?e>t?n.pfValue*e:n.pfValue*t:0;default:return 0}}(a.w,a.h,e.pstyle("padding"),e.pstyle("padding-relative-to").value),t.autoWidth=Math.max(a.w,i.width.val),o.x=(-h+a.x1+a.x2+p)/2,t.autoHeight=Math.max(a.h,i.height.val),o.y=(-g+a.y1+a.y2+v)/2}function y(e,t,n){var r=0,i=0,a=t+n;return e>0&&a>0&&(r=t/a*e,i=n/a*e),{biasDiff:r,biasComplementDiff:i}}}for(var r=0;re.x2?r:e.x2,e.y1=ne.y2?i:e.y2,e.w=e.x2-e.x1,e.h=e.y2-e.y1)},Ka=function(e,t){return null==t?e:Ha(e,t.x1,t.y1,t.x2,t.y2)},Ga=function(e,t,n){return Ue(e,t,n)},Ua=function(e,t,n){if(!t.cy().headless()){var r,i,a=t._private,o=a.rstyle,s=o.arrowWidth/2;if("none"!==t.pstyle(n+"-arrow-shape").value){"source"===n?(r=o.srcX,i=o.srcY):"target"===n?(r=o.tgtX,i=o.tgtY):(r=o.midX,i=o.midY);var l=a.arrowBounds=a.arrowBounds||{},u=l[n]=l[n]||{};u.x1=r-s,u.y1=i-s,u.x2=r+s,u.y2=i+s,u.w=u.x2-u.x1,u.h=u.y2-u.y1,Nt(u,1),Ha(e,u.x1,u.y1,u.x2,u.y2)}}},Za=function(e,t,n){if(!t.cy().headless()){var r;r=n?n+"-":"";var i=t._private,a=i.rstyle;if(t.pstyle(r+"label").strValue){var o,s,l,u,c=t.pstyle("text-halign"),d=t.pstyle("text-valign"),h=Ga(a,"labelWidth",n),p=Ga(a,"labelHeight",n),f=Ga(a,"labelX",n),g=Ga(a,"labelY",n),v=t.pstyle(r+"text-margin-x").pfValue,y=t.pstyle(r+"text-margin-y").pfValue,m=t.isEdge(),b=t.pstyle(r+"text-rotation"),x=t.pstyle("text-outline-width").pfValue,w=t.pstyle("text-border-width").pfValue/2,E=t.pstyle("text-background-padding").pfValue,k=p,C=h,S=C/2,P=k/2;if(m)o=f-S,s=f+S,l=g-P,u=g+P;else{switch(c.value){case"left":o=f-C,s=f;break;case"center":o=f-S,s=f+S;break;case"right":o=f,s=f+C}switch(d.value){case"top":l=g-k,u=g;break;case"center":l=g-P,u=g+P;break;case"bottom":l=g,u=g+k}}o+=v-Math.max(x,w)-E-2,s+=v+Math.max(x,w)+E+2,l+=y-Math.max(x,w)-E-2,u+=y+Math.max(x,w)+E+2;var D=n||"main",T=i.labelBounds,_=T[D]=T[D]||{};_.x1=o,_.y1=l,_.x2=s,_.y2=u,_.w=s-o,_.h=u-l;var M=m&&"autorotate"===b.strValue,B=null!=b.pfValue&&0!==b.pfValue;if(M||B){var N=M?Ga(i.rstyle,"labelAngle",n):b.pfValue,z=Math.cos(N),I=Math.sin(N),A=(o+s)/2,L=(l+u)/2;if(!m){switch(c.value){case"left":A=s;break;case"right":A=o}switch(d.value){case"top":L=u;break;case"bottom":L=l}}var O=function(e,t){return{x:(e-=A)*z-(t-=L)*I+A,y:e*I+t*z+L}},R=O(o,l),V=O(o,u),F=O(s,l),j=O(s,u);o=Math.min(R.x,V.x,F.x,j.x),s=Math.max(R.x,V.x,F.x,j.x),l=Math.min(R.y,V.y,F.y,j.y),u=Math.max(R.y,V.y,F.y,j.y)}var q=D+"Rot",Y=T[q]=T[q]||{};Y.x1=o,Y.y1=l,Y.x2=s,Y.y2=u,Y.w=s-o,Y.h=u-l,Ha(e,o,l,s,u),Ha(i.labelBounds.all,o,l,s,u)}return e}},$a=function(e,t){var n,r,i,a,o,s,l,u=e._private.cy,c=u.styleEnabled(),d=u.headless(),h=_t(),p=e._private,f=e.isNode(),g=e.isEdge(),v=p.rstyle,y=f&&c?e.pstyle("bounds-expansion").pfValue:[0],m=function(e){return"none"!==e.pstyle("display").value},b=!c||m(e)&&(!g||m(e.source())&&m(e.target()));if(b){var x=0;c&&t.includeOverlays&&0!==e.pstyle("overlay-opacity").value&&(x=e.pstyle("overlay-padding").value);var w=0;c&&t.includeUnderlays&&0!==e.pstyle("underlay-opacity").value&&(w=e.pstyle("underlay-padding").value);var E=Math.max(x,w),k=0;if(c&&(k=e.pstyle("width").pfValue/2),f&&t.includeNodes){var C=e.position();o=C.x,s=C.y;var S=e.outerWidth()/2,P=e.outerHeight()/2;Ha(h,n=o-S,i=s-P,r=o+S,a=s+P),c&&t.includeOutlines&&function(e,t){if(!t.cy().headless()){var n,r,i,a=t.pstyle("outline-opacity").value,o=t.pstyle("outline-width").value;if(a>0&&o>0){var s=t.pstyle("outline-offset").value,l=t.pstyle("shape").value,u=o+s,c=(e.w+2*u)/e.w,d=(e.h+2*u)/e.h,h=0;["diamond","pentagon","round-triangle"].includes(l)?(c=(e.w+2.4*u)/e.w,h=-u/3.6):["concave-hexagon","rhomboid","right-rhomboid"].includes(l)?c=(e.w+2.4*u)/e.w:"star"===l?(c=(e.w+2.8*u)/e.w,d=(e.h+2.6*u)/e.h,h=-u/3.8):"triangle"===l?(c=(e.w+2.8*u)/e.w,d=(e.h+2.4*u)/e.h,h=-u/1.4):"vee"===l&&(c=(e.w+4.4*u)/e.w,d=(e.h+3.8*u)/e.h,h=.5*-u);var p=e.h*d-e.h,f=e.w*c-e.w;if(zt(e,[Math.ceil(p/2),Math.ceil(f/2)]),0!==h){var g=(r=0,i=h,{x1:(n=e).x1+r,x2:n.x2+r,y1:n.y1+i,y2:n.y2+i,w:n.w,h:n.h});Mt(e,g)}}}}(h,e)}else if(g&&t.includeEdges)if(c&&!d){var D=e.pstyle("curve-style").strValue;if(n=Math.min(v.srcX,v.midX,v.tgtX),r=Math.max(v.srcX,v.midX,v.tgtX),i=Math.min(v.srcY,v.midY,v.tgtY),a=Math.max(v.srcY,v.midY,v.tgtY),Ha(h,n-=k,i-=k,r+=k,a+=k),"haystack"===D){var T=v.haystackPts;if(T&&2===T.length){if(n=T[0].x,i=T[0].y,n>(r=T[1].x)){var _=n;n=r,r=_}if(i>(a=T[1].y)){var M=i;i=a,a=M}Ha(h,n-k,i-k,r+k,a+k)}}else if("bezier"===D||"unbundled-bezier"===D||D.endsWith("segments")||D.endsWith("taxi")){var B;switch(D){case"bezier":case"unbundled-bezier":B=v.bezierPts;break;case"segments":case"taxi":case"round-segments":case"round-taxi":B=v.linePts}if(null!=B)for(var N=0;N(r=A.x)){var L=n;n=r,r=L}if((i=I.y)>(a=A.y)){var O=i;i=a,a=O}Ha(h,n-=k,i-=k,r+=k,a+=k)}if(c&&t.includeEdges&&g&&(Ua(h,e,"mid-source"),Ua(h,e,"mid-target"),Ua(h,e,"source"),Ua(h,e,"target")),c)if("yes"===e.pstyle("ghost").value){var R=e.pstyle("ghost-offset-x").pfValue,V=e.pstyle("ghost-offset-y").pfValue;Ha(h,h.x1+R,h.y1+V,h.x2+R,h.y2+V)}var F=p.bodyBounds=p.bodyBounds||{};It(F,h),zt(F,y),Nt(F,1),c&&(n=h.x1,r=h.x2,i=h.y1,a=h.y2,Ha(h,n-E,i-E,r+E,a+E));var j=p.overlayBounds=p.overlayBounds||{};It(j,h),zt(j,y),Nt(j,1);var q=p.labelBounds=p.labelBounds||{};null!=q.all?((l=q.all).x1=1/0,l.y1=1/0,l.x2=-1/0,l.y2=-1/0,l.w=0,l.h=0):q.all=_t(),c&&t.includeLabels&&(t.includeMainLabels&&Za(h,e,null),g&&(t.includeSourceLabels&&Za(h,e,"source"),t.includeTargetLabels&&Za(h,e,"target")))}return h.x1=Wa(h.x1),h.y1=Wa(h.y1),h.x2=Wa(h.x2),h.y2=Wa(h.y2),h.w=Wa(h.x2-h.x1),h.h=Wa(h.y2-h.y1),h.w>0&&h.h>0&&b&&(zt(h,y),Nt(h,1)),h},Qa=function(e){var t=0,n=function(e){return(e?1:0)<0&&void 0!==arguments[0]?arguments[0]:bo,t=arguments.length>1?arguments[1]:void 0,n=0;n=0;s--)o(s);return this},wo.removeAllListeners=function(){return this.removeListener("*")},wo.emit=wo.trigger=function(e,t,n){var r=this.listeners,i=r.length;return this.emitting++,m(t)||(t=[t]),Co(this,(function(e,a){null!=n&&(r=[{event:a.event,type:a.type,namespace:a.namespace,callback:n}],i=r.length);for(var o=function(n){var i=r[n];if(i.type===a.type&&(!i.namespace||i.namespace===a.namespace||".*"===i.namespace)&&e.eventMatches(e.context,i,a)){var o=[a];null!=t&&function(e,t){for(var n=0;n1&&!r){var i=this.length-1,a=this[i],o=a._private.data.id;this[i]=void 0,this[e]=a,n.set(o,{ele:a,index:e})}return this.length--,this},unmergeOne:function(e){e=e[0];var t=this._private,n=e._private.data.id,r=t.map.get(n);if(!r)return this;var i=r.index;return this.unmergeAt(i),this},unmerge:function(e){var t=this._private.cy;if(!e)return this;if(e&&v(e)){var n=e;e=t.mutableElements().filter(n)}for(var r=0;r=0;t--){e(this[t])&&this.unmergeAt(t)}return this},map:function(e,t){for(var n=[],r=0;rr&&(r=o,n=a)}return{value:r,ele:n}},min:function(e,t){for(var n,r=1/0,i=0;i=0&&i1&&void 0!==arguments[1])||arguments[1],n=this[0],r=n.cy();if(r.styleEnabled()&&n){this.cleanStyle();var i=n._private.style[e];return null!=i?i:t?r.style().getDefaultProperty(e):null}},numericStyle:function(e){var t=this[0];if(t.cy().styleEnabled()&&t){var n=t.pstyle(e);return void 0!==n.pfValue?n.pfValue:n.value}},numericStyleUnits:function(e){var t=this[0];if(t.cy().styleEnabled())return t?t.pstyle(e).units:void 0},renderedStyle:function(e){var t=this.cy();if(!t.styleEnabled())return this;var n=this[0];return n?t.style().getRenderedStyle(n,e):void 0},style:function(e,t){var n=this.cy();if(!n.styleEnabled())return this;var r=n.style();if(b(e)){var i=e;r.applyBypass(this,i,!1),this.emitAndNotify("style")}else if(v(e)){if(void 0===t){var a=this[0];return a?r.getStylePropertyValue(a,e):void 0}r.applyBypass(this,e,t,!1),this.emitAndNotify("style")}else if(void 0===e){var o=this[0];return o?r.getRawStyle(o):void 0}return this},removeStyle:function(e){var t=this.cy();if(!t.styleEnabled())return this;var n=t.style();if(void 0===e)for(var r=0;r0&&t.push(c[0]),t.push(s[0])}return this.spawn(t,!0).filter(e)}),"neighborhood"),closedNeighborhood:function(e){return this.neighborhood().add(this).filter(e)},openNeighborhood:function(e){return this.neighborhood(e)}}),Go.neighbourhood=Go.neighborhood,Go.closedNeighbourhood=Go.closedNeighborhood,Go.openNeighbourhood=Go.openNeighborhood,L(Go,{source:Ta((function(e){var t,n=this[0];return n&&(t=n._private.source||n.cy().collection()),t&&e?t.filter(e):t}),"source"),target:Ta((function(e){var t,n=this[0];return n&&(t=n._private.target||n.cy().collection()),t&&e?t.filter(e):t}),"target"),sources:Qo({attr:"source"}),targets:Qo({attr:"target"})}),L(Go,{edgesWith:Ta(Jo(),"edgesWith"),edgesTo:Ta(Jo({thisIsSrc:!0}),"edgesTo")}),L(Go,{connectedEdges:Ta((function(e){for(var t=[],n=0;n0);return a},component:function(){var e=this[0];return e.cy().mutableElements().components(e)[0]}}),Go.componentsOf=Go.components;var ts=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(void 0!==e){var i=new $e,a=!1;if(t){if(t.length>0&&b(t[0])&&!k(t[0])){a=!0;for(var o=[],s=new Je,l=0,u=t.length;l0&&void 0!==arguments[0])||arguments[0],r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this,a=i.cy(),o=a._private,s=[],l=[],u=0,c=i.length;u0){for(var R=e.length===i.length?i:new ts(a,e),V=0;V0&&void 0!==arguments[0])||arguments[0],t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=this,r=[],i={},a=n._private.cy;function o(e){for(var t=e._private.edges,n=0;n0&&(e?D.emitAndNotify("remove"):t&&D.emit("remove"));for(var T=0;T1e-4&&Math.abs(s.v)>1e-4;);return a?function(e){return u[e*(u.length-1)|0]}:c}}(),as=function(e,t,n,r){var i=function(e,t,n,r){var i=4,a=.001,o=1e-7,s=10,l=11,u=1/(l-1),c="undefined"!=typeof Float32Array;if(4!==arguments.length)return!1;for(var d=0;d<4;++d)if("number"!=typeof arguments[d]||isNaN(arguments[d])||!isFinite(arguments[d]))return!1;e=Math.min(e,1),n=Math.min(n,1),e=Math.max(e,0),n=Math.max(n,0);var h=c?new Float32Array(l):new Array(l);function p(e,t){return 1-3*t+3*e}function f(e,t){return 3*t-6*e}function g(e){return 3*e}function v(e,t,n){return((p(t,n)*e+f(t,n))*e+g(t))*e}function y(e,t,n){return 3*p(t,n)*e*e+2*f(t,n)*e+g(t)}function m(t,r){for(var a=0;a0?i=l:r=l}while(Math.abs(a)>o&&++u=a?m(t,s):0===c?s:x(t,r,r+u)}var E=!1;function k(){E=!0,e===t&&n===r||b()}var C=function(i){return E||k(),e===t&&n===r?i:0===i?0:1===i?1:v(w(i),t,r)};C.getControlPoints=function(){return[{x:e,y:t},{x:n,y:r}]};var S="generateBezier("+[e,t,n,r]+")";return C.toString=function(){return S},C}(e,t,n,r);return function(e,t,n){return e+(t-e)*i(n)}},os={linear:function(e,t,n){return e+(t-e)*n},ease:as(.25,.1,.25,1),"ease-in":as(.42,0,1,1),"ease-out":as(0,0,.58,1),"ease-in-out":as(.42,0,.58,1),"ease-in-sine":as(.47,0,.745,.715),"ease-out-sine":as(.39,.575,.565,1),"ease-in-out-sine":as(.445,.05,.55,.95),"ease-in-quad":as(.55,.085,.68,.53),"ease-out-quad":as(.25,.46,.45,.94),"ease-in-out-quad":as(.455,.03,.515,.955),"ease-in-cubic":as(.55,.055,.675,.19),"ease-out-cubic":as(.215,.61,.355,1),"ease-in-out-cubic":as(.645,.045,.355,1),"ease-in-quart":as(.895,.03,.685,.22),"ease-out-quart":as(.165,.84,.44,1),"ease-in-out-quart":as(.77,0,.175,1),"ease-in-quint":as(.755,.05,.855,.06),"ease-out-quint":as(.23,1,.32,1),"ease-in-out-quint":as(.86,0,.07,1),"ease-in-expo":as(.95,.05,.795,.035),"ease-out-expo":as(.19,1,.22,1),"ease-in-out-expo":as(1,0,0,1),"ease-in-circ":as(.6,.04,.98,.335),"ease-out-circ":as(.075,.82,.165,1),"ease-in-out-circ":as(.785,.135,.15,.86),spring:function(e,t,n){if(0===n)return os.linear;var r=is(e,t,n);return function(e,t,n){return e+(t-e)*r(n)}},"cubic-bezier":as};function ss(e,t,n,r,i){if(1===r)return n;if(t===n)return n;var a=i(t,n,r);return null==e||((e.roundValue||e.color)&&(a=Math.round(a)),void 0!==e.min&&(a=Math.max(a,e.min)),void 0!==e.max&&(a=Math.min(a,e.max))),a}function ls(e,t){return null!=e.pfValue||null!=e.value?null==e.pfValue||null!=t&&"%"===t.type.units?e.value:e.pfValue:e}function us(e,t,n,r,i){var a=null!=i?i.type:null;n<0?n=0:n>1&&(n=1);var o=ls(e,i),s=ls(t,i);if(x(o)&&x(s))return ss(a,o,s,n,r);if(m(o)&&m(s)){for(var l=[],u=0;u0?("spring"===d&&h.push(o.duration),o.easingImpl=os[d].apply(null,h)):o.easingImpl=os[d]}var p,f=o.easingImpl;if(p=0===o.duration?1:(n-l)/o.duration,o.applying&&(p=o.progress),p<0?p=0:p>1&&(p=1),null==o.delay){var g=o.startPosition,y=o.position;if(y&&i&&!e.locked()){var m={};ds(g.x,y.x)&&(m.x=us(g.x,y.x,p,f)),ds(g.y,y.y)&&(m.y=us(g.y,y.y,p,f)),e.position(m)}var b=o.startPan,x=o.pan,w=a.pan,E=null!=x&&r;E&&(ds(b.x,x.x)&&(w.x=us(b.x,x.x,p,f)),ds(b.y,x.y)&&(w.y=us(b.y,x.y,p,f)),e.emit("pan"));var k=o.startZoom,C=o.zoom,S=null!=C&&r;S&&(ds(k,C)&&(a.zoom=Tt(a.minZoom,us(k,C,p,f),a.maxZoom)),e.emit("zoom")),(E||S)&&e.emit("viewport");var P=o.style;if(P&&P.length>0&&i){for(var D=0;D=0;t--){(0,e[t])()}e.splice(0,e.length)},c=a.length-1;c>=0;c--){var d=a[c],h=d._private;h.stopped?(a.splice(c,1),h.hooked=!1,h.playing=!1,h.started=!1,u(h.frames)):(h.playing||h.applying)&&(h.playing&&h.applying&&(h.applying=!1),h.started||hs(0,d,e),cs(t,d,e,n),h.applying&&(h.applying=!1),u(h.frames),null!=h.step&&h.step(e),d.completed()&&(a.splice(c,1),h.hooked=!1,h.playing=!1,h.started=!1,u(h.completes)),s=!0)}return n||0!==a.length||0!==o.length||r.push(t),s}for(var a=!1,o=0;o0?t.notify("draw",n):t.notify("draw")),n.unmerge(r),t.emit("step")}var fs={animate:Fi.animate(),animation:Fi.animation(),animated:Fi.animated(),clearQueue:Fi.clearQueue(),delay:Fi.delay(),delayAnimation:Fi.delayAnimation(),stop:Fi.stop(),addToAnimationPool:function(e){this.styleEnabled()&&this._private.aniEles.merge(e)},stopAnimationLoop:function(){this._private.animationsRunning=!1},startAnimationLoop:function(){var e=this;if(e._private.animationsRunning=!0,e.styleEnabled()){var t=e.renderer();t&&t.beforeRender?t.beforeRender((function(t,n){ps(n,e)}),t.beforeRenderPriorities.animations):function t(){e._private.animationsRunning&&xe((function(n){ps(n,e),t()}))}()}}},gs={qualifierCompare:function(e,t){return null==e||null==t?null==e&&null==t:e.sameText(t)},eventMatches:function(e,t,n){var r=t.qualifier;return null==r||e!==n.target&&k(n.target)&&r.matches(n.target)},addEventFields:function(e,t){t.cy=e,t.target=e},callbackContext:function(e,t,n){return null!=t.qualifier?n.target:e}},vs=function(e){return v(e)?new ka(e):e},ys={createEmitter:function(){var e=this._private;return e.emitter||(e.emitter=new xo(gs,this)),this},emitter:function(){return this._private.emitter},on:function(e,t,n){return this.emitter().on(e,vs(t),n),this},removeListener:function(e,t,n){return this.emitter().removeListener(e,vs(t),n),this},removeAllListeners:function(){return this.emitter().removeAllListeners(),this},one:function(e,t,n){return this.emitter().one(e,vs(t),n),this},once:function(e,t,n){return this.emitter().one(e,vs(t),n),this},emit:function(e,t){return this.emitter().emit(e,t),this},emitAndNotify:function(e,t){return this.emit(e),this.notify(e,t),this}};Fi.eventAliasesOn(ys);var ms={png:function(e){return e=e||{},this._private.renderer.png(e)},jpg:function(e){var t=this._private.renderer;return(e=e||{}).bg=e.bg||"#fff",t.jpg(e)}};ms.jpeg=ms.jpg;var bs={layout:function(e){if(null!=e)if(null!=e.name){var t=e.name,n=this.extension("layout",t);if(null!=n){var r;r=v(e.eles)?this.$(e.eles):null!=e.eles?e.eles:this.$();var i=new n(L({},e,{cy:this,eles:r}));return i}Ve("No such layout `"+t+"` found. Did you forget to import it and `cytoscape.use()` it?")}else Ve("A `name` must be specified to make a layout");else Ve("Layout options must be specified to make a layout")}};bs.createLayout=bs.makeLayout=bs.layout;var xs={notify:function(e,t){var n=this._private;if(this.batching()){n.batchNotifications=n.batchNotifications||{};var r=n.batchNotifications[e]=n.batchNotifications[e]||this.collection();null!=t&&r.merge(t)}else if(n.notificationsEnabled){var i=this.renderer();!this.destroyed()&&i&&i.notify(e,t)}},notifications:function(e){var t=this._private;return void 0===e?t.notificationsEnabled:(t.notificationsEnabled=!!e,this)},noNotifications:function(e){this.notifications(!1),e(),this.notifications(!0)},batching:function(){return this._private.batchCount>0},startBatch:function(){var e=this._private;return null==e.batchCount&&(e.batchCount=0),0===e.batchCount&&(e.batchStyleEles=this.collection(),e.batchNotifications={}),e.batchCount++,this},endBatch:function(){var e=this._private;if(0===e.batchCount)return this;if(e.batchCount--,0===e.batchCount){e.batchStyleEles.updateStyle();var t=this.renderer();Object.keys(e.batchNotifications).forEach((function(n){var r=e.batchNotifications[n];r.empty()?t.notify(n):t.notify(n,r)}))}return this},batch:function(e){return this.startBatch(),e(),this.endBatch(),this},batchData:function(e){var t=this;return this.batch((function(){for(var n=Object.keys(e),r=0;r0;)e.removeChild(e.childNodes[0]);this._private.renderer=null,this.mutableElements().forEach((function(e){var t=e._private;t.rscratch={},t.rstyle={},t.animation.current=[],t.animation.queue=[]}))},onRender:function(e){return this.on("render",e)},offRender:function(e){return this.off("render",e)}};Es.invalidateDimensions=Es.resize;var ks={collection:function(e,t){return v(e)?this.$(e):E(e)?e.collection():m(e)?(t||(t={}),new ts(this,e,t.unique,t.removed)):new ts(this)},nodes:function(e){var t=this.$((function(e){return e.isNode()}));return e?t.filter(e):t},edges:function(e){var t=this.$((function(e){return e.isEdge()}));return e?t.filter(e):t},$:function(e){var t=this._private.elements;return e?t.filter(e):t.spawnSelf()},mutableElements:function(){return this._private.elements}};ks.elements=ks.filter=ks.$;var Cs={};Cs.apply=function(e){for(var t=this._private.cy.collection(),n=0;n0;if(d||c&&h){var p=void 0;d&&h||d?p=l.properties:h&&(p=l.mappedProperties);for(var f=0;f1&&(g=1),s.color){var w=i.valueMin[0],E=i.valueMax[0],k=i.valueMin[1],C=i.valueMax[1],S=i.valueMin[2],P=i.valueMax[2],D=null==i.valueMin[3]?1:i.valueMin[3],T=null==i.valueMax[3]?1:i.valueMax[3],_=[Math.round(w+(E-w)*g),Math.round(k+(C-k)*g),Math.round(S+(P-S)*g),Math.round(D+(T-D)*g)];n={bypass:i.bypass,name:i.name,value:_,strValue:"rgb("+_[0]+", "+_[1]+", "+_[2]+")"}}else{if(!s.number)return!1;var M=i.valueMin+(i.valueMax-i.valueMin)*g;n=this.parse(i.name,M,i.bypass,"mapping")}if(!n)return f(),!1;n.mapping=i,i=n;break;case o.data:for(var B=i.field.split("."),N=d.data,z=0;z0&&a>0){for(var s={},l=!1,u=0;u0?e.delayAnimation(o).play().promise().then(t):t()})).then((function(){return e.animation({style:s,duration:a,easing:e.pstyle("transition-timing-function").value,queue:!1}).play().promise()})).then((function(){n.removeBypasses(e,i),e.emitAndNotify("style"),r.transitioning=!1}))}else r.transitioning&&(this.removeBypasses(e,i),e.emitAndNotify("style"),r.transitioning=!1)},Cs.checkTrigger=function(e,t,n,r,i,a){var o=this.properties[t],s=i(o);null!=s&&s(n,r)&&a(o)},Cs.checkZOrderTrigger=function(e,t,n,r){var i=this;this.checkTrigger(e,t,n,r,(function(e){return e.triggersZOrder}),(function(){i._private.cy.notify("zorder",e)}))},Cs.checkBoundsTrigger=function(e,t,n,r){this.checkTrigger(e,t,n,r,(function(e){return e.triggersBounds}),(function(i){e.dirtyCompoundBoundsCache(),e.dirtyBoundingBoxCache(),!i.triggersBoundsOfParallelBeziers||"curve-style"!==t||"bezier"!==n&&"bezier"!==r||e.parallelEdges().forEach((function(e){e.isBundledBezier()&&e.dirtyBoundingBoxCache()})),!i.triggersBoundsOfConnectedEdges||"display"!==t||"none"!==n&&"none"!==r||e.connectedEdges().forEach((function(e){e.dirtyBoundingBoxCache()}))}))},Cs.checkTriggers=function(e,t,n,r){e.dirtyStyleCache(),this.checkZOrderTrigger(e,t,n,r),this.checkBoundsTrigger(e,t,n,r)};var Ss={applyBypass:function(e,t,n,r){var i=[];if("*"===t||"**"===t){if(void 0!==n)for(var a=0;at.length?i.substr(t.length):""}function o(){n=n.length>r.length?n.substr(r.length):""}for(i=i.replace(/[/][*](\s|.)+?[*][/]/g,"");;){if(i.match(/^\s*$/))break;var s=i.match(/^\s*((?:.|\s)+?)\s*\{((?:.|\s)+?)\}/);if(!s){je("Halting stylesheet parsing: String stylesheet contains more to parse but no selector and block found in: "+i);break}t=s[0];var l=s[1];if("core"!==l)if(new ka(l).invalid){je("Skipping parsing of block: Invalid selector found in string stylesheet: "+l),a();continue}var u=s[2],c=!1;n=u;for(var d=[];;){if(n.match(/^\s*$/))break;var h=n.match(/^\s*(.+?)\s*:\s*(.+?)(?:\s*;|\s*$)/);if(!h){je("Skipping parsing of block: Invalid formatting of style property and value definitions found in:"+u),c=!0;break}r=h[0];var p=h[1],f=h[2];if(this.properties[p])this.parse(p,f)?(d.push({name:p,val:f}),o()):(je("Skipping property: Invalid property definition in: "+r),o());else je("Skipping property: Invalid property name in: "+r),o()}if(c){a();break}this.selector(l);for(var g=0;g=7&&"d"===t[0]&&(l=new RegExp(o.data.regex).exec(t))){if(n)return!1;var d=o.data;return{name:e,value:l,strValue:""+t,mapped:d,field:l[1],bypass:n}}if(t.length>=10&&"m"===t[0]&&(u=new RegExp(o.mapData.regex).exec(t))){if(n)return!1;if(c.multiple)return!1;var h=o.mapData;if(!c.color&&!c.number)return!1;var p=this.parse(e,u[4]);if(!p||p.mapped)return!1;var f=this.parse(e,u[5]);if(!f||f.mapped)return!1;if(p.pfValue===f.pfValue||p.strValue===f.strValue)return je("`"+e+": "+t+"` is not a valid mapper because the output range is zero; converting to `"+e+": "+p.strValue+"`"),this.parse(e,p.strValue);if(c.color){var g=p.value,b=f.value;if(!(g[0]!==b[0]||g[1]!==b[1]||g[2]!==b[2]||g[3]!==b[3]&&(null!=g[3]&&1!==g[3]||null!=b[3]&&1!==b[3])))return!1}return{name:e,value:u,strValue:""+t,mapped:h,field:u[1],fieldMin:parseFloat(u[2]),fieldMax:parseFloat(u[3]),valueMin:p.value,valueMax:f.value,bypass:n}}}if(c.multiple&&"multiple"!==r){var w;if(w=s?t.split(/\s+/):m(t)?t:[t],c.evenMultiple&&w.length%2!=0)return null;for(var E=[],k=[],C=[],S="",P=!1,D=0;D0?" ":"")+T.strValue}return c.validate&&!c.validate(E,k)?null:c.singleEnum&&P?1===E.length&&v(E[0])?{name:e,value:E[0],strValue:E[0],bypass:n}:null:{name:e,value:E,pfValue:C,strValue:S,bypass:n,units:k}}var _,B,N=function(){for(var r=0;rc.max||c.strictMax&&t===c.max))return null;var V={name:e,value:t,strValue:""+t+(z||""),units:z,bypass:n};return c.unitless||"px"!==z&&"em"!==z?V.pfValue=t:V.pfValue="px"!==z&&z?this.getEmSizeInPixels()*t:t,"ms"!==z&&"s"!==z||(V.pfValue="ms"===z?t:1e3*t),"deg"!==z&&"rad"!==z||(V.pfValue="rad"===z?t:(_=t,Math.PI*_/180)),"%"===z&&(V.pfValue=t/100),V}if(c.propList){var F=[],j=""+t;if("none"===j);else{for(var q=j.split(/\s*,\s*|\s+/),Y=0;Y0&&l>0&&!isNaN(n.w)&&!isNaN(n.h)&&n.w>0&&n.h>0)return{zoom:o=(o=(o=Math.min((s-2*t)/n.w,(l-2*t)/n.h))>this._private.maxZoom?this._private.maxZoom:o)=n.minZoom&&(n.maxZoom=t),this},minZoom:function(e){return void 0===e?this._private.minZoom:this.zoomRange({min:e})},maxZoom:function(e){return void 0===e?this._private.maxZoom:this.zoomRange({max:e})},getZoomedViewport:function(e){var t,n,r=this._private,i=r.pan,a=r.zoom,o=!1;if(r.zoomingEnabled||(o=!0),x(e)?n=e:b(e)&&(n=e.level,null!=e.position?t=yt(e.position,a,i):null!=e.renderedPosition&&(t=e.renderedPosition),null==t||r.panningEnabled||(o=!0)),n=(n=n>r.maxZoom?r.maxZoom:n)t.maxZoom||!t.zoomingEnabled?a=!0:(t.zoom=s,i.push("zoom"))}if(r&&(!a||!e.cancelOnFailedZoom)&&t.panningEnabled){var l=e.pan;x(l.x)&&(t.pan.x=l.x,o=!1),x(l.y)&&(t.pan.y=l.y,o=!1),o||i.push("pan")}return i.length>0&&(i.push("viewport"),this.emit(i.join(" ")),this.notify("viewport")),this},center:function(e){var t=this.getCenterPan(e);return t&&(this._private.pan=t,this.emit("pan viewport"),this.notify("viewport")),this},getCenterPan:function(e,t){if(this._private.panningEnabled){if(v(e)){var n=e;e=this.mutableElements().filter(n)}else E(e)||(e=this.mutableElements());if(0!==e.length){var r=e.boundingBox(),i=this.width(),a=this.height();return{x:(i-(t=void 0===t?this._private.zoom:t)*(r.x1+r.x2))/2,y:(a-t*(r.y1+r.y2))/2}}}},reset:function(){return this._private.panningEnabled&&this._private.zoomingEnabled?(this.viewport({pan:{x:0,y:0},zoom:1}),this):this},invalidateSize:function(){this._private.sizeCache=null},size:function(){var e,t,n=this._private,r=n.container,i=this;return n.sizeCache=n.sizeCache||(r?(e=i.window().getComputedStyle(r),t=function(t){return parseFloat(e.getPropertyValue(t))},{width:r.clientWidth-t("padding-left")-t("padding-right"),height:r.clientHeight-t("padding-top")-t("padding-bottom")}):{width:1,height:1})},width:function(){return this.size().width},height:function(){return this.size().height},extent:function(){var e=this._private.pan,t=this._private.zoom,n=this.renderedExtent(),r={x1:(n.x1-e.x)/t,x2:(n.x2-e.x)/t,y1:(n.y1-e.y)/t,y2:(n.y2-e.y)/t};return r.w=r.x2-r.x1,r.h=r.y2-r.y1,r},renderedExtent:function(){var e=this.width(),t=this.height();return{x1:0,y1:0,x2:e,y2:t,w:e,h:t}},multiClickDebounceTime:function(e){return e?(this._private.multiClickDebounceTime=e,this):this._private.multiClickDebounceTime}};As.centre=As.center,As.autolockNodes=As.autolock,As.autoungrabifyNodes=As.autoungrabify;var Ls={data:Fi.data({field:"data",bindingEvent:"data",allowBinding:!0,allowSetting:!0,settingEvent:"data",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeData:Fi.removeData({field:"data",event:"data",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0}),scratch:Fi.data({field:"scratch",bindingEvent:"scratch",allowBinding:!0,allowSetting:!0,settingEvent:"scratch",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeScratch:Fi.removeData({field:"scratch",event:"scratch",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0})};Ls.attr=Ls.data,Ls.removeAttr=Ls.removeData;var Os=function(e){var t=this,n=(e=L({},e)).container;n&&!w(n)&&w(n[0])&&(n=n[0]);var r=n?n._cyreg:null;(r=r||{})&&r.cy&&(r.cy.destroy(),r={});var i=r.readies=r.readies||[];n&&(n._cyreg=r),r.cy=t;var a=void 0!==u&&void 0!==n&&!e.headless,o=e;o.layout=L({name:a?"grid":"null"},o.layout),o.renderer=L({name:a?"canvas":"null"},o.renderer);var s=function(e,t,n){return void 0!==t?t:void 0!==n?n:e},l=this._private={container:n,ready:!1,options:o,elements:new ts(this),listeners:[],aniEles:new ts(this),data:o.data||{},scratch:{},layout:null,renderer:null,destroyed:!1,notificationsEnabled:!0,minZoom:1e-50,maxZoom:1e50,zoomingEnabled:s(!0,o.zoomingEnabled),userZoomingEnabled:s(!0,o.userZoomingEnabled),panningEnabled:s(!0,o.panningEnabled),userPanningEnabled:s(!0,o.userPanningEnabled),boxSelectionEnabled:s(!0,o.boxSelectionEnabled),autolock:s(!1,o.autolock,o.autolockNodes),autoungrabify:s(!1,o.autoungrabify,o.autoungrabifyNodes),autounselectify:s(!1,o.autounselectify),styleEnabled:void 0===o.styleEnabled?a:o.styleEnabled,zoom:x(o.zoom)?o.zoom:1,pan:{x:b(o.pan)&&x(o.pan.x)?o.pan.x:0,y:b(o.pan)&&x(o.pan.y)?o.pan.y:0},animation:{current:[],queue:[]},hasCompoundNodes:!1,multiClickDebounceTime:s(250,o.multiClickDebounceTime)};this.createEmitter(),this.selectionType(o.selectionType),this.zoomRange({min:o.minZoom,max:o.maxZoom});l.styleEnabled&&t.setStyle([]);var c=L({},o,o.renderer);t.initRenderer(c);!function(e,t){if(e.some(T))return vr.all(e).then(t);t(e)}([o.style,o.elements],(function(e){var n=e[0],a=e[1];l.styleEnabled&&t.style().append(n),function(e,n,r){t.notifications(!1);var i=t.mutableElements();i.length>0&&i.remove(),null!=e&&(b(e)||m(e))&&t.add(e),t.one("layoutready",(function(e){t.notifications(!0),t.emit(e),t.one("load",n),t.emitAndNotify("load")})).one("layoutstop",(function(){t.one("done",r),t.emit("done")}));var a=L({},t._private.options.layout);a.eles=t.elements(),t.layout(a).run()}(a,(function(){t.startAnimationLoop(),l.ready=!0,y(o.ready)&&t.on("ready",o.ready);for(var e=0;e0,u=_t(n.boundingBox?n.boundingBox:{x1:0,y1:0,w:r.width(),h:r.height()});if(E(n.roots))e=n.roots;else if(m(n.roots)){for(var c=[],d=0;d0;){var N=_.shift(),z=T(N,M);if(z)N.outgoers().filter((function(e){return e.isNode()&&i.has(e)})).forEach(B);else if(null===z){je("Detected double maximal shift for node `"+N.id()+"`. Bailing maximal adjustment due to cycle. Use `options.maximal: true` only on DAGs.");break}}}D();var I=0;if(n.avoidOverlap)for(var L=0;L0&&b[0].length<=3?l/2:0),d=2*Math.PI/b[r].length*i;return 0===r&&1===b[0].length&&(c=1),{x:G+c*Math.cos(d),y:U+c*Math.sin(d)}}return{x:G+(i+1-(a+1)/2)*o,y:(r+1)*s}})),this};var Xs={fit:!0,padding:30,boundingBox:void 0,avoidOverlap:!0,nodeDimensionsIncludeLabels:!1,spacingFactor:void 0,radius:void 0,startAngle:1.5*Math.PI,sweep:void 0,clockwise:!0,sort:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function Ws(e){this.options=L({},Xs,e)}Ws.prototype.run=function(){var e=this.options,t=e,n=e.cy,r=t.eles,i=void 0!==t.counterclockwise?!t.counterclockwise:t.clockwise,a=r.nodes().not(":parent");t.sort&&(a=a.sort(t.sort));for(var o,s=_t(t.boundingBox?t.boundingBox:{x1:0,y1:0,w:n.width(),h:n.height()}),l=s.x1+s.w/2,u=s.y1+s.h/2,c=(void 0===t.sweep?2*Math.PI-2*Math.PI/a.length:t.sweep)/Math.max(1,a.length-1),d=0,h=0;h1&&t.avoidOverlap){d*=1.75;var v=Math.cos(c)-Math.cos(0),y=Math.sin(c)-Math.sin(0),m=Math.sqrt(d*d/(v*v+y*y));o=Math.max(m,o)}return r.nodes().layoutPositions(this,t,(function(e,n){var r=t.startAngle+n*c*(i?1:-1),a=o*Math.cos(r),s=o*Math.sin(r);return{x:l+a,y:u+s}})),this};var Hs,Ks={fit:!0,padding:30,startAngle:1.5*Math.PI,sweep:void 0,clockwise:!0,equidistant:!1,minNodeSpacing:10,boundingBox:void 0,avoidOverlap:!0,nodeDimensionsIncludeLabels:!1,height:void 0,width:void 0,spacingFactor:void 0,concentric:function(e){return e.degree()},levelWidth:function(e){return e.maxDegree()/4},animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function Gs(e){this.options=L({},Ks,e)}Gs.prototype.run=function(){for(var e=this.options,t=e,n=void 0!==t.counterclockwise?!t.counterclockwise:t.clockwise,r=e.cy,i=t.eles,a=i.nodes().not(":parent"),o=_t(t.boundingBox?t.boundingBox:{x1:0,y1:0,w:r.width(),h:r.height()}),s=o.x1+o.w/2,l=o.y1+o.h/2,u=[],c=0,d=0;d0)Math.abs(m[0].value-x.value)>=v&&(m=[],y.push(m));m.push(x)}var w=c+t.minNodeSpacing;if(!t.avoidOverlap){var E=y.length>0&&y[0].length>1,k=(Math.min(o.w,o.h)/2-w)/(y.length+E?1:0);w=Math.min(w,k)}for(var C=0,S=0;S1&&t.avoidOverlap){var _=Math.cos(T)-Math.cos(0),M=Math.sin(T)-Math.sin(0),B=Math.sqrt(w*w/(_*_+M*M));C=Math.max(B,C)}P.r=C,C+=w}if(t.equidistant){for(var N=0,z=0,I=0;I=e.numIter)&&(rl(r,e),r.temperature=r.temperature*e.coolingFactor,!(r.temperature=e.animationThreshold&&a(),xe(t)):(gl(r,e),s())}()}else{for(;u;)u=o(l),l++;gl(r,e),s()}return this},Zs.prototype.stop=function(){return this.stopped=!0,this.thread&&this.thread.stop(),this.emit("layoutstop"),this},Zs.prototype.destroy=function(){return this.thread&&this.thread.stop(),this};var $s=function(e,t,n){for(var r=n.eles.edges(),i=n.eles.nodes(),a=_t(n.boundingBox?n.boundingBox:{x1:0,y1:0,w:e.width(),h:e.height()}),o={isCompound:e.hasCompoundNodes(),layoutNodes:[],idToIndex:{},nodeSize:i.size(),graphSet:[],indexToGraph:[],layoutEdges:[],edgeSize:r.size(),temperature:n.initialTemp,clientWidth:a.w,clientHeight:a.h,boundingBox:a},s=n.eles.components(),l={},u=0;u0){o.graphSet.push(E);for(u=0;ur.count?0:r.graph},Js=function e(t,n,r,i){var a=i.graphSet[r];if(-10)var s=(u=r.nodeOverlap*o)*i/(g=Math.sqrt(i*i+a*a)),l=u*a/g;else{var u,c=ll(e,i,a),d=ll(t,-1*i,-1*a),h=d.x-c.x,p=d.y-c.y,f=h*h+p*p,g=Math.sqrt(f);s=(u=(e.nodeRepulsion+t.nodeRepulsion)/f)*h/g,l=u*p/g}e.isLocked||(e.offsetX-=s,e.offsetY-=l),t.isLocked||(t.offsetX+=s,t.offsetY+=l)}},sl=function(e,t,n,r){if(n>0)var i=e.maxX-t.minX;else i=t.maxX-e.minX;if(r>0)var a=e.maxY-t.minY;else a=t.maxY-e.minY;return i>=0&&a>=0?Math.sqrt(i*i+a*a):0},ll=function(e,t,n){var r=e.positionX,i=e.positionY,a=e.height||1,o=e.width||1,s=n/t,l=a/o,u={};return 0===t&&0n?(u.x=r,u.y=i+a/2,u):0t&&-1*l<=s&&s<=l?(u.x=r-o/2,u.y=i-o*n/2/t,u):0=l)?(u.x=r+a*t/2/n,u.y=i+a/2,u):0>n&&(s<=-1*l||s>=l)?(u.x=r-a*t/2/n,u.y=i-a/2,u):u},ul=function(e,t){for(var n=0;n1){var f=t.gravity*d/p,g=t.gravity*h/p;c.offsetX+=f,c.offsetY+=g}}}}},dl=function(e,t){var n=[],r=0,i=-1;for(n.push.apply(n,e.graphSet[0]),i+=e.graphSet[0].length;r<=i;){var a=n[r++],o=e.idToIndex[a],s=e.layoutNodes[o],l=s.children;if(0n)var i={x:n*e/r,y:n*t/r};else i={x:e,y:t};return i},fl=function e(t,n){var r=t.parentId;if(null!=r){var i=n.layoutNodes[n.idToIndex[r]],a=!1;return(null==i.maxX||t.maxX+i.padRight>i.maxX)&&(i.maxX=t.maxX+i.padRight,a=!0),(null==i.minX||t.minX-i.padLefti.maxY)&&(i.maxY=t.maxY+i.padBottom,a=!0),(null==i.minY||t.minY-i.padTopf&&(d+=p+t.componentSpacing,c=0,h=0,p=0)}}},vl={fit:!0,padding:30,boundingBox:void 0,avoidOverlap:!0,avoidOverlapPadding:10,nodeDimensionsIncludeLabels:!1,spacingFactor:void 0,condense:!1,rows:void 0,cols:void 0,position:function(e){},sort:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function yl(e){this.options=L({},vl,e)}yl.prototype.run=function(){var e=this.options,t=e,n=e.cy,r=t.eles,i=r.nodes().not(":parent");t.sort&&(i=i.sort(t.sort));var a=_t(t.boundingBox?t.boundingBox:{x1:0,y1:0,w:n.width(),h:n.height()});if(0===a.h||0===a.w)r.nodes().layoutPositions(this,t,(function(e){return{x:a.x1,y:a.y1}}));else{var o=i.size(),s=Math.sqrt(o*a.h/a.w),l=Math.round(s),u=Math.round(a.w/a.h*s),c=function(e){if(null==e)return Math.min(l,u);Math.min(l,u)==l?l=e:u=e},d=function(e){if(null==e)return Math.max(l,u);Math.max(l,u)==l?l=e:u=e},h=t.rows,p=null!=t.cols?t.cols:t.columns;if(null!=h&&null!=p)l=h,u=p;else if(null!=h&&null==p)l=h,u=Math.ceil(o/l);else if(null==h&&null!=p)u=p,l=Math.ceil(o/u);else if(u*l>o){var f=c(),g=d();(f-1)*g>=o?c(f-1):(g-1)*f>=o&&d(g-1)}else for(;u*l=o?d(y+1):c(v+1)}var m=a.w/u,b=a.h/l;if(t.condense&&(m=0,b=0),t.avoidOverlap)for(var x=0;x=u&&(B=0,M++)},z={},I=0;I(r=qt(e,t,x[w],x[w+1],x[w+2],x[w+3])))return v(n,r),!0}else if("bezier"===a.edgeType||"multibezier"===a.edgeType||"self"===a.edgeType||"compound"===a.edgeType)for(x=a.allpts,w=0;w+5(r=jt(e,t,x[w],x[w+1],x[w+2],x[w+3],x[w+4],x[w+5])))return v(n,r),!0;m=m||i.source,b=b||i.target;var E=o.getArrowWidth(l,c),k=[{name:"source",x:a.arrowStartX,y:a.arrowStartY,angle:a.srcArrowAngle},{name:"target",x:a.arrowEndX,y:a.arrowEndY,angle:a.tgtArrowAngle},{name:"mid-source",x:a.midX,y:a.midY,angle:a.midsrcArrowAngle},{name:"mid-target",x:a.midX,y:a.midY,angle:a.midtgtArrowAngle}];for(w=0;w0&&(y(m),y(b))}function b(e,t,n){return Ue(e,t,n)}function x(n,r){var i,a=n._private,o=f;i=r?r+"-":"",n.boundingBox();var s=a.labelBounds[r||"main"],l=n.pstyle(i+"label").value;if("yes"===n.pstyle("text-events").strValue&&l){var u=b(a.rscratch,"labelX",r),c=b(a.rscratch,"labelY",r),d=b(a.rscratch,"labelAngle",r),h=n.pstyle(i+"text-margin-x").pfValue,p=n.pstyle(i+"text-margin-y").pfValue,g=s.x1-o-h,y=s.x2+o-h,m=s.y1-o-p,x=s.y2+o-p;if(d){var w=Math.cos(d),E=Math.sin(d),k=function(e,t){return{x:(e-=u)*w-(t-=c)*E+u,y:e*E+t*w+c}},C=k(g,m),S=k(g,x),P=k(y,m),D=k(y,x),T=[C.x+h,C.y+p,P.x+h,P.y+p,D.x+h,D.y+p,S.x+h,S.y+p];if(Yt(e,t,T))return v(n),!0}else if(Lt(s,e,t))return v(n),!0}}n&&(l=l.interactive);for(var w=l.length-1;w>=0;w--){var E=l[w];E.isNode()?y(E)||x(E):m(E)||x(E)||x(E,"source")||x(E,"target")}return u},getAllInBox:function(e,t,n,r){for(var i,a,o=this.getCachedZSortedEles().interactive,s=[],l=Math.min(e,n),u=Math.max(e,n),c=Math.min(t,r),d=Math.max(t,r),h=_t({x1:e=l,y1:t=c,x2:n=u,y2:r=d}),p=0;p0?-(Math.PI-a.ang):Math.PI+a.ang),Zl(t,n,Ul),zl=Gl.nx*Ul.ny-Gl.ny*Ul.nx,Il=Gl.nx*Ul.nx-Gl.ny*-Ul.ny,Ol=Math.asin(Math.max(-1,Math.min(1,zl))),Math.abs(Ol)<1e-6)return Bl=t.x,Nl=t.y,void(Vl=jl=0);Al=1,Ll=!1,Il<0?Ol<0?Ol=Math.PI+Ol:(Ol=Math.PI-Ol,Al=-1,Ll=!0):Ol>0&&(Al=-1,Ll=!0),jl=void 0!==t.radius?t.radius:r,Rl=Ol/2,ql=Math.min(Gl.len/2,Ul.len/2),i?(Fl=Math.abs(Math.cos(Rl)*jl/Math.sin(Rl)))>ql?(Fl=ql,Vl=Math.abs(Fl*Math.sin(Rl)/Math.cos(Rl))):Vl=jl:(Fl=Math.min(ql,jl),Vl=Math.abs(Fl*Math.sin(Rl)/Math.cos(Rl))),Wl=t.x+Ul.nx*Fl,Hl=t.y+Ul.ny*Fl,Bl=Wl-Ul.ny*Vl*Al,Nl=Hl+Ul.nx*Vl*Al,Yl=t.x+Gl.nx*Fl,Xl=t.y+Gl.ny*Fl,Kl=t};function Ql(e,t){0===t.radius?e.lineTo(t.cx,t.cy):e.arc(t.cx,t.cy,t.radius,t.startAngle,t.endAngle,t.counterClockwise)}function Jl(e,t,n,r){var i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];return 0===r||0===t.radius?{cx:t.x,cy:t.y,radius:0,startX:t.x,startY:t.y,stopX:t.x,stopY:t.y,startAngle:void 0,endAngle:void 0,counterClockwise:void 0}:($l(e,t,n,r,i),{cx:Bl,cy:Nl,radius:Vl,startX:Yl,startY:Xl,stopX:Wl,stopY:Hl,startAngle:Gl.ang+Math.PI/2*Al,endAngle:Ul.ang-Math.PI/2*Al,counterClockwise:Ll})}var eu={};function tu(e){var t=[];if(null!=e){for(var n=0;n0?Math.max(e-t,0):Math.min(e+t,0)},w=x(m,v),E=x(b,y),k=!1;"auto"===c?u=Math.abs(w)>Math.abs(E)?"horizontal":"vertical":"upward"===c||"downward"===c?(u="vertical",k=!0):"leftward"!==c&&"rightward"!==c||(u="horizontal",k=!0);var C,S="vertical"===u,P=S?E:w,D=S?b:m,T=Et(D),_=!1;(k&&(h||f)||!("downward"===c&&D<0||"upward"===c&&D>0||"leftward"===c&&D>0||"rightward"===c&&D<0)||(P=(T*=-1)*Math.abs(P),_=!0),h)?C=(p<0?1+p:p)*P:C=(p<0?P:0)+p*T;var M=function(e){return Math.abs(e)=Math.abs(P)},B=M(C),N=M(Math.abs(P)-Math.abs(C));if((B||N)&&!_)if(S){var z=Math.abs(D)<=a/2,I=Math.abs(m)<=o/2;if(z){var A=(r.x1+r.x2)/2,L=r.y1,O=r.y2;n.segpts=[A,L,A,O]}else if(I){var R=(r.y1+r.y2)/2,V=r.x1,F=r.x2;n.segpts=[V,R,F,R]}else n.segpts=[r.x1,r.y2]}else{var j=Math.abs(D)<=i/2,q=Math.abs(b)<=s/2;if(j){var Y=(r.y1+r.y2)/2,X=r.x1,W=r.x2;n.segpts=[X,Y,W,Y]}else if(q){var H=(r.x1+r.x2)/2,K=r.y1,G=r.y2;n.segpts=[H,K,H,G]}else n.segpts=[r.x2,r.y1]}else if(S){var U=r.y1+C+(l?a/2*T:0),Z=r.x1,$=r.x2;n.segpts=[Z,U,$,U]}else{var Q=r.x1+C+(l?i/2*T:0),J=r.y1,ee=r.y2;n.segpts=[Q,J,Q,ee]}if(n.isRound){var te=e.pstyle("taxi-radius").value,ne="arc-radius"===e.pstyle("radius-type").value[0];n.radii=new Array(n.segpts.length/2).fill(te),n.isArcRadius=new Array(n.segpts.length/2).fill(ne)}},eu.tryToCorrectInvalidPoints=function(e,t){var n=e._private.rscratch;if("bezier"===n.edgeType){var r=t.srcPos,i=t.tgtPos,a=t.srcW,o=t.srcH,s=t.tgtW,l=t.tgtH,u=t.srcShape,c=t.tgtShape,d=t.srcCornerRadius,h=t.tgtCornerRadius,p=t.srcRs,f=t.tgtRs,g=!x(n.startX)||!x(n.startY),v=!x(n.arrowStartX)||!x(n.arrowStartY),y=!x(n.endX)||!x(n.endY),m=!x(n.arrowEndX)||!x(n.arrowEndY),b=3*(this.getArrowWidth(e.pstyle("width").pfValue,e.pstyle("arrow-scale").value)*this.arrowShapeWidth),w=kt({x:n.ctrlpts[0],y:n.ctrlpts[1]},{x:n.startX,y:n.startY}),E=wh.poolIndex()){var p=d;d=h,h=p}var f=s.srcPos=d.position(),g=s.tgtPos=h.position(),v=s.srcW=d.outerWidth(),y=s.srcH=d.outerHeight(),m=s.tgtW=h.outerWidth(),b=s.tgtH=h.outerHeight(),w=s.srcShape=n.nodeShapes[t.getNodeShape(d)],E=s.tgtShape=n.nodeShapes[t.getNodeShape(h)],k=s.srcCornerRadius="auto"===d.pstyle("corner-radius").value?"auto":d.pstyle("corner-radius").pfValue,C=s.tgtCornerRadius="auto"===h.pstyle("corner-radius").value?"auto":h.pstyle("corner-radius").pfValue,S=s.tgtRs=h._private.rscratch,P=s.srcRs=d._private.rscratch;s.dirCounts={north:0,west:0,south:0,east:0,northwest:0,southwest:0,northeast:0,southeast:0};for(var D=0;D0){var H=u,K=Ct(H,bt(t)),G=Ct(H,bt(W)),U=K;if(G2)Ct(H,{x:W[2],y:W[3]})0){var le=c,ue=Ct(le,bt(t)),ce=Ct(le,bt(se)),de=ue;if(ce2)Ct(le,{x:se[2],y:se[3]})=c||b){d={cp:v,segment:m};break}}if(d)break}var x=d.cp,w=d.segment,E=(c-p)/w.length,k=w.t1-w.t0,C=u?w.t0+k*E:w.t1-k*E;C=Tt(0,C,1),t=Dt(x.p0,x.p1,x.p2,C),l=function(e,t,n,r){var i=Tt(0,r-.001,1),a=Tt(0,r+.001,1),o=Dt(e,t,n,i),s=Dt(e,t,n,a);return su(o,s)}(x.p0,x.p1,x.p2,C);break;case"straight":case"segments":case"haystack":for(var S,P,D,T,_=0,M=r.allpts.length,B=0;B+3=c));B+=2);var N=(c-P)/S;N=Tt(0,N,1),t=function(e,t,n,r){var i=t.x-e.x,a=t.y-e.y,o=kt(e,t),s=i/o,l=a/o;return n=null==n?0:n,r=null!=r?r:n*o,{x:e.x+s*r,y:e.y+l*r}}(D,T,N),l=su(D,T)}o("labelX",s,t.x),o("labelY",s,t.y),o("labelAutoAngle",s,l)}};l("source"),l("target"),this.applyLabelDimensions(e)}},au.applyLabelDimensions=function(e){this.applyPrefixedLabelDimensions(e),e.isEdge()&&(this.applyPrefixedLabelDimensions(e,"source"),this.applyPrefixedLabelDimensions(e,"target"))},au.applyPrefixedLabelDimensions=function(e,t){var n=e._private,r=this.getLabelText(e,t),i=this.calculateLabelDimensions(e,r),a=e.pstyle("line-height").pfValue,o=e.pstyle("text-wrap").strValue,s=Ue(n.rscratch,"labelWrapCachedLines",t)||[],l="wrap"!==o?1:Math.max(s.length,1),u=i.height/l,c=u*a,d=i.width,h=i.height+(l-1)*(a-1)*u;Ze(n.rstyle,"labelWidth",t,d),Ze(n.rscratch,"labelWidth",t,d),Ze(n.rstyle,"labelHeight",t,h),Ze(n.rscratch,"labelHeight",t,h),Ze(n.rscratch,"labelLineHeight",t,c)},au.getLabelText=function(e,t){var n=e._private,r=t?t+"-":"",i=e.pstyle(r+"label").strValue,a=e.pstyle("text-transform").value,o=function(e,r){return r?(Ze(n.rscratch,e,t,r),r):Ue(n.rscratch,e,t)};if(!i)return"";"none"==a||("uppercase"==a?i=i.toUpperCase():"lowercase"==a&&(i=i.toLowerCase()));var s=e.pstyle("text-wrap").value;if("wrap"===s){var u=o("labelKey");if(null!=u&&o("labelWrapKey")===u)return o("labelWrapCachedText");for(var c=i.split("\n"),d=e.pstyle("text-max-width").pfValue,h="anywhere"===e.pstyle("text-overflow-wrap").value,p=[],f=/[\s\u200b]+|$/g,g=0;gd){var b,x="",w=0,E=l(v.matchAll(f));try{for(E.s();!(b=E.n()).done;){var k=b.value,C=k[0],S=v.substring(w,k.index);w=k.index+C.length;var P=0===x.length?S:x+S+C;this.calculateLabelDimensions(e,P).width<=d?x+=S+C:(x&&p.push(x),x=S+C)}}catch(e){E.e(e)}finally{E.f()}x.match(/^[\s\u200b]+$/)||p.push(x)}else p.push(v)}o("labelWrapCachedLines",p),i=o("labelWrapCachedText",p.join("\n")),o("labelWrapKey",u)}else if("ellipsis"===s){var D=e.pstyle("text-max-width").pfValue,T="",_=!1;if(this.calculateLabelDimensions(e,i).widthD)break;T+=i[M],M===i.length-1&&(_=!0)}return _||(T+="…"),T}return i},au.getLabelJustification=function(e){var t=e.pstyle("text-justification").strValue,n=e.pstyle("text-halign").strValue;if("auto"!==t)return t;if(!e.isNode())return"center";switch(n){case"left":return"right";case"right":return"left";default:return"center"}},au.calculateLabelDimensions=function(e,t){var n=this,r=n.cy.window().document,i=Te(t,e._private.labelDimsKey),a=n.labelDimCache||(n.labelDimCache=[]),o=a[i];if(null!=o)return o;var s=e.pstyle("font-style").strValue,l=e.pstyle("font-size").pfValue,u=e.pstyle("font-family").strValue,c=e.pstyle("font-weight").strValue,d=this.labelCalcCanvas,h=this.labelCalcCanvasContext;if(!d){d=this.labelCalcCanvas=r.createElement("canvas"),h=this.labelCalcCanvasContext=d.getContext("2d");var p=d.style;p.position="absolute",p.left="-9999px",p.top="-9999px",p.zIndex="-1",p.visibility="hidden",p.pointerEvents="none"}h.font="".concat(s," ").concat(c," ").concat(l,"px ").concat(u);for(var f=0,g=0,v=t.split("\n"),y=0;y1&&void 0!==arguments[1])||arguments[1];if(t.merge(e),n)for(var r=0;r=e.desktopTapThreshold2}var D=i(t);v&&(e.hoverData.tapholdCancelled=!0);n=!0,r(g,["mousemove","vmousemove","tapdrag"],t,{x:c[0],y:c[1]});var T=function(){e.data.bgActivePosistion=void 0,e.hoverData.selecting||o.emit({originalEvent:t,type:"boxstart",position:{x:c[0],y:c[1]}}),f[4]=1,e.hoverData.selecting=!0,e.redrawHint("select",!0),e.redraw()};if(3===e.hoverData.which){if(v){var _={originalEvent:t,type:"cxtdrag",position:{x:c[0],y:c[1]}};m?m.emit(_):o.emit(_),e.hoverData.cxtDragged=!0,e.hoverData.cxtOver&&g===e.hoverData.cxtOver||(e.hoverData.cxtOver&&e.hoverData.cxtOver.emit({originalEvent:t,type:"cxtdragout",position:{x:c[0],y:c[1]}}),e.hoverData.cxtOver=g,g&&g.emit({originalEvent:t,type:"cxtdragover",position:{x:c[0],y:c[1]}}))}}else if(e.hoverData.dragging){if(n=!0,o.panningEnabled()&&o.userPanningEnabled()){var M;if(e.hoverData.justStartedPan){var B=e.hoverData.mdownPos;M={x:(c[0]-B[0])*s,y:(c[1]-B[1])*s},e.hoverData.justStartedPan=!1}else M={x:b[0]*s,y:b[1]*s};o.panBy(M),o.emit("dragpan"),e.hoverData.dragged=!0}c=e.projectIntoViewport(t.clientX,t.clientY)}else if(1!=f[4]||null!=m&&!m.pannable()){if(m&&m.pannable()&&m.active()&&m.unactivate(),m&&m.grabbed()||g==y||(y&&r(y,["mouseout","tapdragout"],t,{x:c[0],y:c[1]}),g&&r(g,["mouseover","tapdragover"],t,{x:c[0],y:c[1]}),e.hoverData.last=g),m)if(v){if(o.boxSelectionEnabled()&&D)m&&m.grabbed()&&(d(w),m.emit("freeon"),w.emit("free"),e.dragData.didDrag&&(m.emit("dragfreeon"),w.emit("dragfree"))),T();else if(m&&m.grabbed()&&e.nodeIsDraggable(m)){var N=!e.dragData.didDrag;N&&e.redrawHint("eles",!0),e.dragData.didDrag=!0,e.hoverData.draggingEles||u(w,{inDragLayer:!0});var z={x:0,y:0};if(x(b[0])&&x(b[1])&&(z.x+=b[0],z.y+=b[1],N)){var I=e.hoverData.dragDelta;I&&x(I[0])&&x(I[1])&&(z.x+=I[0],z.y+=I[1])}e.hoverData.draggingEles=!0,w.silentShift(z).emit("position drag"),e.redrawHint("drag",!0),e.redraw()}}else!function(){var t=e.hoverData.dragDelta=e.hoverData.dragDelta||[];0===t.length?(t.push(b[0]),t.push(b[1])):(t[0]+=b[0],t[1]+=b[1])}();n=!0}else if(v){if(e.hoverData.dragging||!o.boxSelectionEnabled()||!D&&o.panningEnabled()&&o.userPanningEnabled()){if(!e.hoverData.selecting&&o.panningEnabled()&&o.userPanningEnabled()){a(m,e.hoverData.downs)&&(e.hoverData.dragging=!0,e.hoverData.justStartedPan=!0,f[4]=0,e.data.bgActivePosistion=bt(h),e.redrawHint("select",!0),e.redraw())}}else T();m&&m.pannable()&&m.active()&&m.unactivate()}return f[2]=c[0],f[3]=c[1],n?(t.stopPropagation&&t.stopPropagation(),t.preventDefault&&t.preventDefault(),!1):void 0}}),!1),e.registerBinding(t,"mouseup",(function(t){if((1!==e.hoverData.which||1===t.which||!e.hoverData.capture)&&e.hoverData.capture){e.hoverData.capture=!1;var a=e.cy,o=e.projectIntoViewport(t.clientX,t.clientY),s=e.selection,l=e.findNearestElement(o[0],o[1],!0,!1),u=e.dragData.possibleDragElements,c=e.hoverData.down,h=i(t);if(e.data.bgActivePosistion&&(e.redrawHint("select",!0),e.redraw()),e.hoverData.tapholdCancelled=!0,e.data.bgActivePosistion=void 0,c&&c.unactivate(),3===e.hoverData.which){var p={originalEvent:t,type:"cxttapend",position:{x:o[0],y:o[1]}};if(c?c.emit(p):a.emit(p),!e.hoverData.cxtDragged){var f={originalEvent:t,type:"cxttap",position:{x:o[0],y:o[1]}};c?c.emit(f):a.emit(f)}e.hoverData.cxtDragged=!1,e.hoverData.which=null}else if(1===e.hoverData.which){if(r(l,["mouseup","tapend","vmouseup"],t,{x:o[0],y:o[1]}),e.dragData.didDrag||e.hoverData.dragged||e.hoverData.selecting||e.hoverData.isOverThresholdDrag||(r(c,["click","tap","vclick"],t,{x:o[0],y:o[1]}),b=!1,t.timeStamp-w<=a.multiClickDebounceTime()?(m&&clearTimeout(m),b=!0,w=null,r(c,["dblclick","dbltap","vdblclick"],t,{x:o[0],y:o[1]})):(m=setTimeout((function(){b||r(c,["oneclick","onetap","voneclick"],t,{x:o[0],y:o[1]})}),a.multiClickDebounceTime()),w=t.timeStamp)),null!=c||e.dragData.didDrag||e.hoverData.selecting||e.hoverData.dragged||i(t)||(a.$(n).unselect(["tapunselect"]),u.length>0&&e.redrawHint("eles",!0),e.dragData.possibleDragElements=u=a.collection()),l!=c||e.dragData.didDrag||e.hoverData.selecting||null!=l&&l._private.selectable&&(e.hoverData.dragging||("additive"===a.selectionType()||h?l.selected()?l.unselect(["tapunselect"]):l.select(["tapselect"]):h||(a.$(n).unmerge(l).unselect(["tapunselect"]),l.select(["tapselect"]))),e.redrawHint("eles",!0)),e.hoverData.selecting){var g=a.collection(e.getAllInBox(s[0],s[1],s[2],s[3]));e.redrawHint("select",!0),g.length>0&&e.redrawHint("eles",!0),a.emit({type:"boxend",originalEvent:t,position:{x:o[0],y:o[1]}});var v=function(e){return e.selectable()&&!e.selected()};"additive"===a.selectionType()||h||a.$(n).unmerge(g).unselect(),g.emit("box").stdFilter(v).select().emit("boxselect"),e.redraw()}if(e.hoverData.dragging&&(e.hoverData.dragging=!1,e.redrawHint("select",!0),e.redrawHint("eles",!0),e.redraw()),!s[4]){e.redrawHint("drag",!0),e.redrawHint("eles",!0);var y=c&&c.grabbed();d(u),y&&(c.emit("freeon"),u.emit("free"),e.dragData.didDrag&&(c.emit("dragfreeon"),u.emit("dragfree")))}}s[4]=0,e.hoverData.down=null,e.hoverData.cxtStarted=!1,e.hoverData.draggingEles=!1,e.hoverData.selecting=!1,e.hoverData.isOverThresholdDrag=!1,e.dragData.didDrag=!1,e.hoverData.dragged=!1,e.hoverData.dragDelta=[],e.hoverData.mdownPos=null,e.hoverData.mdownGPos=null,e.hoverData.which=null}}),!1);var k,C,S,P,D,T,_,M,B,N,z,I,A,L=function(t){if(!e.scrollingPage){var n=e.cy,r=n.zoom(),i=n.pan(),a=e.projectIntoViewport(t.clientX,t.clientY),o=[a[0]*r+i.x,a[1]*r+i.y];if(e.hoverData.draggingEles||e.hoverData.dragging||e.hoverData.cxtStarted||0!==e.selection[4])t.preventDefault();else if(n.panningEnabled()&&n.userPanningEnabled()&&n.zoomingEnabled()&&n.userZoomingEnabled()){var s;t.preventDefault(),e.data.wheelZooming=!0,clearTimeout(e.data.wheelTimeout),e.data.wheelTimeout=setTimeout((function(){e.data.wheelZooming=!1,e.redrawHint("eles",!0),e.redraw()}),150),s=null!=t.deltaY?t.deltaY/-250:null!=t.wheelDeltaY?t.wheelDeltaY/1e3:t.wheelDelta/1e3,s*=e.wheelSensitivity,1===t.deltaMode&&(s*=33);var l=n.zoom()*Math.pow(10,s);"gesturechange"===t.type&&(l=e.gestureStartZoom*t.scale),n.zoom({level:l,renderedPosition:{x:o[0],y:o[1]}}),n.emit("gesturechange"===t.type?"pinchzoom":"scrollzoom")}}};e.registerBinding(e.container,"wheel",L,!0),e.registerBinding(t,"scroll",(function(t){e.scrollingPage=!0,clearTimeout(e.scrollingPageTimeout),e.scrollingPageTimeout=setTimeout((function(){e.scrollingPage=!1}),250)}),!0),e.registerBinding(e.container,"gesturestart",(function(t){e.gestureStartZoom=e.cy.zoom(),e.hasTouchStarted||t.preventDefault()}),!0),e.registerBinding(e.container,"gesturechange",(function(t){e.hasTouchStarted||L(t)}),!0),e.registerBinding(e.container,"mouseout",(function(t){var n=e.projectIntoViewport(t.clientX,t.clientY);e.cy.emit({originalEvent:t,type:"mouseout",position:{x:n[0],y:n[1]}})}),!1),e.registerBinding(e.container,"mouseover",(function(t){var n=e.projectIntoViewport(t.clientX,t.clientY);e.cy.emit({originalEvent:t,type:"mouseover",position:{x:n[0],y:n[1]}})}),!1);var O,R,V,F,j,q,Y,X=function(e,t,n,r){return Math.sqrt((n-e)*(n-e)+(r-t)*(r-t))},W=function(e,t,n,r){return(n-e)*(n-e)+(r-t)*(r-t)};if(e.registerBinding(e.container,"touchstart",O=function(t){if(e.hasTouchStarted=!0,E(t)){p(),e.touchData.capture=!0,e.data.bgActivePosistion=void 0;var n=e.cy,i=e.touchData.now,a=e.touchData.earlier;if(t.touches[0]){var o=e.projectIntoViewport(t.touches[0].clientX,t.touches[0].clientY);i[0]=o[0],i[1]=o[1]}if(t.touches[1]){o=e.projectIntoViewport(t.touches[1].clientX,t.touches[1].clientY);i[2]=o[0],i[3]=o[1]}if(t.touches[2]){o=e.projectIntoViewport(t.touches[2].clientX,t.touches[2].clientY);i[4]=o[0],i[5]=o[1]}if(t.touches[1]){e.touchData.singleTouchMoved=!0,d(e.dragData.touchDragEles);var l=e.findContainerClientCoords();B=l[0],N=l[1],z=l[2],I=l[3],k=t.touches[0].clientX-B,C=t.touches[0].clientY-N,S=t.touches[1].clientX-B,P=t.touches[1].clientY-N,A=0<=k&&k<=z&&0<=S&&S<=z&&0<=C&&C<=I&&0<=P&&P<=I;var h=n.pan(),f=n.zoom();D=X(k,C,S,P),T=W(k,C,S,P),M=[((_=[(k+S)/2,(C+P)/2])[0]-h.x)/f,(_[1]-h.y)/f];if(T<4e4&&!t.touches[2]){var g=e.findNearestElement(i[0],i[1],!0,!0),v=e.findNearestElement(i[2],i[3],!0,!0);return g&&g.isNode()?(g.activate().emit({originalEvent:t,type:"cxttapstart",position:{x:i[0],y:i[1]}}),e.touchData.start=g):v&&v.isNode()?(v.activate().emit({originalEvent:t,type:"cxttapstart",position:{x:i[0],y:i[1]}}),e.touchData.start=v):n.emit({originalEvent:t,type:"cxttapstart",position:{x:i[0],y:i[1]}}),e.touchData.start&&(e.touchData.start._private.grabbed=!1),e.touchData.cxt=!0,e.touchData.cxtDragged=!1,e.data.bgActivePosistion=void 0,void e.redraw()}}if(t.touches[2])n.boxSelectionEnabled()&&t.preventDefault();else if(t.touches[1]);else if(t.touches[0]){var y=e.findNearestElements(i[0],i[1],!0,!0),m=y[0];if(null!=m&&(m.activate(),e.touchData.start=m,e.touchData.starts=y,e.nodeIsGrabbable(m))){var b=e.dragData.touchDragEles=n.collection(),x=null;e.redrawHint("eles",!0),e.redrawHint("drag",!0),m.selected()?(x=n.$((function(t){return t.selected()&&e.nodeIsGrabbable(t)})),u(x,{addToList:b})):c(m,{addToList:b}),s(m);var w=function(e){return{originalEvent:t,type:e,position:{x:i[0],y:i[1]}}};m.emit(w("grabon")),x?x.forEach((function(e){e.emit(w("grab"))})):m.emit(w("grab"))}r(m,["touchstart","tapstart","vmousedown"],t,{x:i[0],y:i[1]}),null==m&&(e.data.bgActivePosistion={x:o[0],y:o[1]},e.redrawHint("select",!0),e.redraw()),e.touchData.singleTouchMoved=!1,e.touchData.singleTouchStartTime=+new Date,clearTimeout(e.touchData.tapholdTimeout),e.touchData.tapholdTimeout=setTimeout((function(){!1!==e.touchData.singleTouchMoved||e.pinching||e.touchData.selecting||r(e.touchData.start,["taphold"],t,{x:i[0],y:i[1]})}),e.tapholdDuration)}if(t.touches.length>=1){for(var L=e.touchData.startPosition=[null,null,null,null,null,null],O=0;O=e.touchTapThreshold2}if(n&&e.touchData.cxt){t.preventDefault();var w=t.touches[0].clientX-B,_=t.touches[0].clientY-N,z=t.touches[1].clientX-B,I=t.touches[1].clientY-N,L=W(w,_,z,I);if(L/T>=2.25||L>=22500){e.touchData.cxt=!1,e.data.bgActivePosistion=void 0,e.redrawHint("select",!0);var O={originalEvent:t,type:"cxttapend",position:{x:s[0],y:s[1]}};e.touchData.start?(e.touchData.start.unactivate().emit(O),e.touchData.start=null):o.emit(O)}}if(n&&e.touchData.cxt){O={originalEvent:t,type:"cxtdrag",position:{x:s[0],y:s[1]}};e.data.bgActivePosistion=void 0,e.redrawHint("select",!0),e.touchData.start?e.touchData.start.emit(O):o.emit(O),e.touchData.start&&(e.touchData.start._private.grabbed=!1),e.touchData.cxtDragged=!0;var R=e.findNearestElement(s[0],s[1],!0,!0);e.touchData.cxtOver&&R===e.touchData.cxtOver||(e.touchData.cxtOver&&e.touchData.cxtOver.emit({originalEvent:t,type:"cxtdragout",position:{x:s[0],y:s[1]}}),e.touchData.cxtOver=R,R&&R.emit({originalEvent:t,type:"cxtdragover",position:{x:s[0],y:s[1]}}))}else if(n&&t.touches[2]&&o.boxSelectionEnabled())t.preventDefault(),e.data.bgActivePosistion=void 0,this.lastThreeTouch=+new Date,e.touchData.selecting||o.emit({originalEvent:t,type:"boxstart",position:{x:s[0],y:s[1]}}),e.touchData.selecting=!0,e.touchData.didSelect=!0,i[4]=1,i&&0!==i.length&&void 0!==i[0]?(i[2]=(s[0]+s[2]+s[4])/3,i[3]=(s[1]+s[3]+s[5])/3):(i[0]=(s[0]+s[2]+s[4])/3,i[1]=(s[1]+s[3]+s[5])/3,i[2]=(s[0]+s[2]+s[4])/3+1,i[3]=(s[1]+s[3]+s[5])/3+1),e.redrawHint("select",!0),e.redraw();else if(n&&t.touches[1]&&!e.touchData.didSelect&&o.zoomingEnabled()&&o.panningEnabled()&&o.userZoomingEnabled()&&o.userPanningEnabled()){if(t.preventDefault(),e.data.bgActivePosistion=void 0,e.redrawHint("select",!0),ee=e.dragData.touchDragEles){e.redrawHint("drag",!0);for(var V=0;V0&&!e.hoverData.draggingEles&&!e.swipePanning&&null!=e.data.bgActivePosistion&&(e.data.bgActivePosistion=void 0,e.redrawHint("select",!0),e.redraw())}},!1),e.registerBinding(t,"touchcancel",V=function(t){var n=e.touchData.start;e.touchData.capture=!1,n&&n.unactivate()}),e.registerBinding(t,"touchend",F=function(t){var i=e.touchData.start;if(e.touchData.capture){0===t.touches.length&&(e.touchData.capture=!1),t.preventDefault();var a=e.selection;e.swipePanning=!1,e.hoverData.draggingEles=!1;var o,s=e.cy,l=s.zoom(),u=e.touchData.now,c=e.touchData.earlier;if(t.touches[0]){var h=e.projectIntoViewport(t.touches[0].clientX,t.touches[0].clientY);u[0]=h[0],u[1]=h[1]}if(t.touches[1]){h=e.projectIntoViewport(t.touches[1].clientX,t.touches[1].clientY);u[2]=h[0],u[3]=h[1]}if(t.touches[2]){h=e.projectIntoViewport(t.touches[2].clientX,t.touches[2].clientY);u[4]=h[0],u[5]=h[1]}if(i&&i.unactivate(),e.touchData.cxt){if(o={originalEvent:t,type:"cxttapend",position:{x:u[0],y:u[1]}},i?i.emit(o):s.emit(o),!e.touchData.cxtDragged){var p={originalEvent:t,type:"cxttap",position:{x:u[0],y:u[1]}};i?i.emit(p):s.emit(p)}return e.touchData.start&&(e.touchData.start._private.grabbed=!1),e.touchData.cxt=!1,e.touchData.start=null,void e.redraw()}if(!t.touches[2]&&s.boxSelectionEnabled()&&e.touchData.selecting){e.touchData.selecting=!1;var f=s.collection(e.getAllInBox(a[0],a[1],a[2],a[3]));a[0]=void 0,a[1]=void 0,a[2]=void 0,a[3]=void 0,a[4]=0,e.redrawHint("select",!0),s.emit({type:"boxend",originalEvent:t,position:{x:u[0],y:u[1]}});f.emit("box").stdFilter((function(e){return e.selectable()&&!e.selected()})).select().emit("boxselect"),f.nonempty()&&e.redrawHint("eles",!0),e.redraw()}if(null!=i&&i.unactivate(),t.touches[2])e.data.bgActivePosistion=void 0,e.redrawHint("select",!0);else if(t.touches[1]);else if(t.touches[0]);else if(!t.touches[0]){e.data.bgActivePosistion=void 0,e.redrawHint("select",!0);var g=e.dragData.touchDragEles;if(null!=i){var v=i._private.grabbed;d(g),e.redrawHint("drag",!0),e.redrawHint("eles",!0),v&&(i.emit("freeon"),g.emit("free"),e.dragData.didDrag&&(i.emit("dragfreeon"),g.emit("dragfree"))),r(i,["touchend","tapend","vmouseup","tapdragout"],t,{x:u[0],y:u[1]}),i.unactivate(),e.touchData.start=null}else{var y=e.findNearestElement(u[0],u[1],!0,!0);r(y,["touchend","tapend","vmouseup","tapdragout"],t,{x:u[0],y:u[1]})}var m=e.touchData.startPosition[0]-u[0],b=m*m,x=e.touchData.startPosition[1]-u[1],w=(b+x*x)*l*l;e.touchData.singleTouchMoved||(i||s.$(":selected").unselect(["tapunselect"]),r(i,["tap","vclick"],t,{x:u[0],y:u[1]}),j=!1,t.timeStamp-Y<=s.multiClickDebounceTime()?(q&&clearTimeout(q),j=!0,Y=null,r(i,["dbltap","vdblclick"],t,{x:u[0],y:u[1]})):(q=setTimeout((function(){j||r(i,["onetap","voneclick"],t,{x:u[0],y:u[1]})}),s.multiClickDebounceTime()),Y=t.timeStamp)),null!=i&&!e.dragData.didDrag&&i._private.selectable&&w2){for(var p=[c[0],c[1]],f=Math.pow(p[0]-e,2)+Math.pow(p[1]-t,2),g=1;g0)return g[0]}return null},p=Object.keys(d),f=0;f0?u:Rt(i,a,e,t,n,r,o,s)},checkPoint:function(e,t,n,r,i,a,o,s){var l=2*(s="auto"===s?nn(r,i):s);if(Xt(e,t,this.points,a,o,r,i-l,[0,-1],n))return!0;if(Xt(e,t,this.points,a,o,r-l,i,[0,-1],n))return!0;var u=r/2+2*n,c=i/2+2*n;return!!Yt(e,t,[a-u,o-c,a-u,o,a+u,o,a+u,o-c])||(!!Kt(e,t,l,l,a+r/2-s,o+i/2-s,n)||!!Kt(e,t,l,l,a-r/2+s,o+i/2-s,n))}}},gu.registerNodeShapes=function(){var e=this.nodeShapes={},t=this;this.generateEllipse(),this.generatePolygon("triangle",Jt(3,0)),this.generateRoundPolygon("round-triangle",Jt(3,0)),this.generatePolygon("rectangle",Jt(4,0)),e.square=e.rectangle,this.generateRoundRectangle(),this.generateCutRectangle(),this.generateBarrel(),this.generateBottomRoundrectangle();var n=[0,1,1,0,0,-1,-1,0];this.generatePolygon("diamond",n),this.generateRoundPolygon("round-diamond",n),this.generatePolygon("pentagon",Jt(5,0)),this.generateRoundPolygon("round-pentagon",Jt(5,0)),this.generatePolygon("hexagon",Jt(6,0)),this.generateRoundPolygon("round-hexagon",Jt(6,0)),this.generatePolygon("heptagon",Jt(7,0)),this.generateRoundPolygon("round-heptagon",Jt(7,0)),this.generatePolygon("octagon",Jt(8,0)),this.generateRoundPolygon("round-octagon",Jt(8,0));var r=new Array(20),i=tn(5,0),a=tn(5,Math.PI/5),o=.5*(3-Math.sqrt(5));o*=1.57;for(var s=0;s=e.deqFastCost*g)break}else if(i){if(p>=e.deqCost*l||p>=e.deqAvgCost*s)break}else if(f>=e.deqNoDrawCost*(1e3/60))break;var v=e.deq(t,d,c);if(!(v.length>0))break;for(var y=0;y0&&(e.onDeqd(t,u),!i&&e.shouldRedraw(t,u,d,c)&&r())}),i(t))}}},wu=function(){function e(n){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Le;t(this,e),this.idsByKey=new $e,this.keyForId=new $e,this.cachesByLvl=new $e,this.lvls=[],this.getKey=n,this.doesEleInvalidateKey=r}return r(e,[{key:"getIdsFor",value:function(e){null==e&&Ve("Can not get id list for null key");var t=this.idsByKey,n=this.idsByKey.get(e);return n||(n=new Je,t.set(e,n)),n}},{key:"addIdForKey",value:function(e,t){null!=e&&this.getIdsFor(e).add(t)}},{key:"deleteIdForKey",value:function(e,t){null!=e&&this.getIdsFor(e).delete(t)}},{key:"getNumberOfIdsForKey",value:function(e){return null==e?0:this.getIdsFor(e).size}},{key:"updateKeyMappingFor",value:function(e){var t=e.id(),n=this.keyForId.get(t),r=this.getKey(e);this.deleteIdForKey(n,t),this.addIdForKey(r,t),this.keyForId.set(t,r)}},{key:"deleteKeyMappingFor",value:function(e){var t=e.id(),n=this.keyForId.get(t);this.deleteIdForKey(n,t),this.keyForId.delete(t)}},{key:"keyHasChangedFor",value:function(e){var t=e.id();return this.keyForId.get(t)!==this.getKey(e)}},{key:"isInvalid",value:function(e){return this.keyHasChangedFor(e)||this.doesEleInvalidateKey(e)}},{key:"getCachesAt",value:function(e){var t=this.cachesByLvl,n=this.lvls,r=t.get(e);return r||(r=new $e,t.set(e,r),n.push(e)),r}},{key:"getCache",value:function(e,t){return this.getCachesAt(t).get(e)}},{key:"get",value:function(e,t){var n=this.getKey(e),r=this.getCache(n,t);return null!=r&&this.updateKeyMappingFor(e),r}},{key:"getForCachedKey",value:function(e,t){var n=this.keyForId.get(e.id());return this.getCache(n,t)}},{key:"hasCache",value:function(e,t){return this.getCachesAt(t).has(e)}},{key:"has",value:function(e,t){var n=this.getKey(e);return this.hasCache(n,t)}},{key:"setCache",value:function(e,t,n){n.key=e,this.getCachesAt(t).set(e,n)}},{key:"set",value:function(e,t,n){var r=this.getKey(e);this.setCache(r,t,n),this.updateKeyMappingFor(e)}},{key:"deleteCache",value:function(e,t){this.getCachesAt(t).delete(e)}},{key:"delete",value:function(e,t){var n=this.getKey(e);this.deleteCache(n,t)}},{key:"invalidateKey",value:function(e){var t=this;this.lvls.forEach((function(n){return t.deleteCache(e,n)}))}},{key:"invalidate",value:function(e){var t=e.id(),n=this.keyForId.get(t);this.deleteKeyMappingFor(e);var r=this.doesEleInvalidateKey(e);return r&&this.invalidateKey(n),r||0===this.getNumberOfIdsForKey(n)}}]),e}(),Eu={dequeue:"dequeue",downscale:"downscale",highQuality:"highQuality"},ku=He({getKey:null,doesEleInvalidateKey:Le,drawElement:null,getBoundingBox:null,getRotationPoint:null,getRotationOffset:null,isVisible:Ae,allowEdgeTxrCaching:!0,allowParentTxrCaching:!0}),Cu=function(e,t){this.renderer=e,this.onDequeues=[];var n=ku(t);L(this,n),this.lookup=new wu(n.getKey,n.doesEleInvalidateKey),this.setupDequeueing()},Su=Cu.prototype;Su.reasons=Eu,Su.getTextureQueue=function(e){return this.eleImgCaches=this.eleImgCaches||{},this.eleImgCaches[e]=this.eleImgCaches[e]||[]},Su.getRetiredTextureQueue=function(e){var t=this.eleImgCaches.retired=this.eleImgCaches.retired||{};return t[e]=t[e]||[]},Su.getElementQueue=function(){return this.eleCacheQueue=this.eleCacheQueue||new rt((function(e,t){return t.reqs-e.reqs}))},Su.getElementKeyToQueue=function(){return this.eleKeyToCacheQueue=this.eleKeyToCacheQueue||{}},Su.getElement=function(e,t,n,r,i){var a=this,o=this.renderer,s=o.cy.zoom(),l=this.lookup;if(!t||0===t.w||0===t.h||isNaN(t.w)||isNaN(t.h)||!e.visible()||e.removed())return null;if(!a.allowEdgeTxrCaching&&e.isEdge()||!a.allowParentTxrCaching&&e.isParent())return null;if(null==r&&(r=Math.ceil(wt(s*n))),r<-4)r=-4;else if(s>=7.99||r>3)return null;var u=Math.pow(2,r),c=t.h*u,d=t.w*u,h=o.eleTextBiggerThanMin(e,u);if(!this.isVisible(e,h))return null;var p,f=l.get(e,r);if(f&&f.invalidated&&(f.invalidated=!1,f.texture.invalidatedWidth-=f.width),f)return f;if(p=c<=25?25:c<=50?50:50*Math.ceil(c/50),c>1024||d>1024)return null;var g=a.getTextureQueue(p),v=g[g.length-2],y=function(){return a.recycleTexture(p,d)||a.addTexture(p,d)};v||(v=g[g.length-1]),v||(v=y()),v.width-v.usedWidthr;D--)S=a.getElement(e,t,n,D,Eu.downscale);P()}else{var T;if(!x&&!w&&!E)for(var _=r-1;_>=-4;_--){var M=l.get(e,_);if(M){T=M;break}}if(b(T))return a.queueElement(e,r),T;v.context.translate(v.usedWidth,0),v.context.scale(u,u),this.drawElement(v.context,e,t,h,!1),v.context.scale(1/u,1/u),v.context.translate(-v.usedWidth,0)}return f={x:v.usedWidth,texture:v,level:r,scale:u,width:d,height:c,scaledLabelShown:h},v.usedWidth+=Math.ceil(d+8),v.eleCaches.push(f),l.set(e,r,f),a.checkTextureFullness(v),f},Su.invalidateElements=function(e){for(var t=0;t=.2*e.width&&this.retireTexture(e)},Su.checkTextureFullness=function(e){var t=this.getTextureQueue(e.height);e.usedWidth/e.width>.8&&e.fullnessChecks>=10?Ke(t,e):e.fullnessChecks++},Su.retireTexture=function(e){var t=e.height,n=this.getTextureQueue(t),r=this.lookup;Ke(n,e),e.retired=!0;for(var i=e.eleCaches,a=0;a=t)return a.retired=!1,a.usedWidth=0,a.invalidatedWidth=0,a.fullnessChecks=0,Ge(a.eleCaches),a.context.setTransform(1,0,0,1,0,0),a.context.clearRect(0,0,a.width,a.height),Ke(r,a),n.push(a),a}},Su.queueElement=function(e,t){var n=this.getElementQueue(),r=this.getElementKeyToQueue(),i=this.getKey(e),a=r[i];if(a)a.level=Math.max(a.level,t),a.eles.merge(e),a.reqs++,n.updateItem(a);else{var o={eles:e.spawn().merge(e),level:t,reqs:1,key:i};n.push(o),r[i]=o}},Su.dequeue=function(e){for(var t=this.getElementQueue(),n=this.getElementKeyToQueue(),r=[],i=this.lookup,a=0;a<1&&t.size()>0;a++){var o=t.pop(),s=o.key,l=o.eles[0],u=i.hasCache(l,o.level);if(n[s]=null,!u){r.push(o);var c=this.getBoundingBox(l);this.getElement(l,c,e,o.level,Eu.dequeue)}}return r},Su.removeFromQueue=function(e){var t=this.getElementQueue(),n=this.getElementKeyToQueue(),r=this.getKey(e),i=n[r];null!=i&&(1===i.eles.length?(i.reqs=Ie,t.updateItem(i),t.pop(),n[r]=null):i.eles.unmerge(e))},Su.onDequeue=function(e){this.onDequeues.push(e)},Su.offDequeue=function(e){Ke(this.onDequeues,e)},Su.setupDequeueing=xu({deqRedrawThreshold:100,deqCost:.15,deqAvgCost:.1,deqNoDrawCost:.9,deqFastCost:.9,deq:function(e,t,n){return e.dequeue(t,n)},onDeqd:function(e,t){for(var n=0;n=3.99||n>2)return null;r.validateLayersElesOrdering(n,e);var o,s,l=r.layersByLevel,u=Math.pow(2,n),c=l[n]=l[n]||[];if(r.levelIsComplete(n,e))return c;!function(){var t=function(t){if(r.validateLayersElesOrdering(t,e),r.levelIsComplete(t,e))return s=l[t],!0},i=function(e){if(!s)for(var r=n+e;-4<=r&&r<=2&&!t(r);r+=e);};i(1),i(-1);for(var a=c.length-1;a>=0;a--){var o=c[a];o.invalid&&Ke(c,o)}}();var d=function(t){var i=(t=t||{}).after;if(function(){if(!o){o=_t();for(var t=0;t16e6)return null;var a=r.makeLayer(o,n);if(null!=i){var s=c.indexOf(i)+1;c.splice(s,0,a)}else(void 0===t.insert||t.insert)&&c.unshift(a);return a};if(r.skipping&&!a)return null;for(var h=null,p=e.length/1,f=!a,g=0;g=p||!Ot(h.bb,v.boundingBox()))&&!(h=d({insert:!0,after:h})))return null;s||f?r.queueLayer(h,v):r.drawEleInLayer(h,v,n,t),h.eles.push(v),m[n]=h}}return s||(f?null:c)},Du.getEleLevelForLayerLevel=function(e,t){return e},Du.drawEleInLayer=function(e,t,n,r){var i=this.renderer,a=e.context,o=t.boundingBox();0!==o.w&&0!==o.h&&t.visible()&&(n=this.getEleLevelForLayerLevel(n,r),i.setImgSmoothing(a,!1),i.drawCachedElement(a,t,null,null,n,!0),i.setImgSmoothing(a,!0))},Du.levelIsComplete=function(e,t){var n=this.layersByLevel[e];if(!n||0===n.length)return!1;for(var r=0,i=0;i0)return!1;if(a.invalid)return!1;r+=a.eles.length}return r===t.length},Du.validateLayersElesOrdering=function(e,t){var n=this.layersByLevel[e];if(n)for(var r=0;r0){e=!0;break}}return e},Du.invalidateElements=function(e){var t=this;0!==e.length&&(t.lastInvalidationTime=we(),0!==e.length&&t.haveLayers()&&t.updateElementsInLayers(e,(function(e,n,r){t.invalidateLayer(e)})))},Du.invalidateLayer=function(e){if(this.lastInvalidationTime=we(),!e.invalid){var t=e.level,n=e.eles,r=this.layersByLevel[t];Ke(r,e),e.elesQueue=[],e.invalid=!0,e.replacement&&(e.replacement.invalid=!0);for(var i=0;i3&&void 0!==arguments[3])||arguments[3],i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],a=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],o=this,s=t._private.rscratch;if((!a||t.visible())&&!s.badLine&&null!=s.allpts&&!isNaN(s.allpts[0])){var l;n&&(l=n,e.translate(-l.x1,-l.y1));var u=a?t.pstyle("opacity").value:1,c=a?t.pstyle("line-opacity").value:1,d=t.pstyle("curve-style").value,h=t.pstyle("line-style").value,p=t.pstyle("width").pfValue,f=t.pstyle("line-cap").value,g=t.pstyle("line-outline-width").value,v=t.pstyle("line-outline-color").value,y=u*c,m=u*c,b=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:y;"straight-triangle"===d?(o.eleStrokeStyle(e,t,n),o.drawEdgeTrianglePath(t,e,s.allpts)):(e.lineWidth=p,e.lineCap=f,o.eleStrokeStyle(e,t,n),o.drawEdgePath(t,e,s.allpts,h),e.lineCap="butt")},x=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:y;e.lineWidth=p+g,e.lineCap=f,g>0?(o.colorStrokeStyle(e,v[0],v[1],v[2],n),"straight-triangle"===d?o.drawEdgeTrianglePath(t,e,s.allpts):(o.drawEdgePath(t,e,s.allpts,h),e.lineCap="butt")):e.lineCap="butt"},w=function(){i&&o.drawEdgeOverlay(e,t)},E=function(){i&&o.drawEdgeUnderlay(e,t)},k=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m;o.drawArrowheads(e,t,n)},C=function(){o.drawElementText(e,t,null,r)};e.lineJoin="round";var S="yes"===t.pstyle("ghost").value;if(S){var P=t.pstyle("ghost-offset-x").pfValue,D=t.pstyle("ghost-offset-y").pfValue,T=t.pstyle("ghost-opacity").value,_=y*T;e.translate(P,D),b(_),k(_),e.translate(-P,-D)}else x();E(),b(),k(),w(),C(),n&&e.translate(l.x1,l.y1)}}},Wu=function(e){if(!["overlay","underlay"].includes(e))throw new Error("Invalid state");return function(t,n){if(n.visible()){var r=n.pstyle("".concat(e,"-opacity")).value;if(0!==r){var i=this,a=i.usePaths(),o=n._private.rscratch,s=2*n.pstyle("".concat(e,"-padding")).pfValue,l=n.pstyle("".concat(e,"-color")).value;t.lineWidth=s,"self"!==o.edgeType||a?t.lineCap="round":t.lineCap="butt",i.colorStrokeStyle(t,l[0],l[1],l[2],r),i.drawEdgePath(n,t,o.allpts,"solid")}}}};Xu.drawEdgeOverlay=Wu("overlay"),Xu.drawEdgeUnderlay=Wu("underlay"),Xu.drawEdgePath=function(e,t,n,r){var i,a=e._private.rscratch,o=t,s=!1,u=this.usePaths(),c=e.pstyle("line-dash-pattern").pfValue,d=e.pstyle("line-dash-offset").pfValue;if(u){var h=n.join("$");a.pathCacheKey&&a.pathCacheKey===h?(i=t=a.pathCache,s=!0):(i=t=new Path2D,a.pathCacheKey=h,a.pathCache=i)}if(o.setLineDash)switch(r){case"dotted":o.setLineDash([1,1]);break;case"dashed":o.setLineDash(c),o.lineDashOffset=d;break;case"solid":o.setLineDash([])}if(!s&&!a.badLine)switch(t.beginPath&&t.beginPath(),t.moveTo(n[0],n[1]),a.edgeType){case"bezier":case"self":case"compound":case"multibezier":for(var p=2;p+35&&void 0!==arguments[5]?arguments[5]:5,o=arguments.length>6?arguments[6]:void 0;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(),o?e.stroke():e.fill()}Ku.eleTextBiggerThanMin=function(e,t){if(!t){var n=e.cy().zoom(),r=this.getPixelRatio(),i=Math.ceil(wt(n*r));t=Math.pow(2,i)}return!(e.pstyle("font-size").pfValue*t5&&void 0!==arguments[5])||arguments[5],o=this;if(null==r){if(a&&!o.eleTextBiggerThanMin(t))return}else if(!1===r)return;if(t.isNode()){var s=t.pstyle("label");if(!s||!s.value)return;var l=o.getLabelJustification(t);e.textAlign=l,e.textBaseline="bottom"}else{var u=t.element()._private.rscratch.badLine,c=t.pstyle("label"),d=t.pstyle("source-label"),h=t.pstyle("target-label");if(u||(!c||!c.value)&&(!d||!d.value)&&(!h||!h.value))return;e.textAlign="center",e.textBaseline="bottom"}var p,f=!n;n&&(p=n,e.translate(-p.x1,-p.y1)),null==i?(o.drawText(e,t,null,f,a),t.isEdge()&&(o.drawText(e,t,"source",f,a),o.drawText(e,t,"target",f,a))):o.drawText(e,t,i,f,a),n&&e.translate(p.x1,p.y1)},Ku.getFontCache=function(e){var t;this.fontCaches=this.fontCaches||[];for(var n=0;n2&&void 0!==arguments[2])||arguments[2],r=t.pstyle("font-style").strValue,i=t.pstyle("font-size").pfValue+"px",a=t.pstyle("font-family").strValue,o=t.pstyle("font-weight").strValue,s=n?t.effectiveOpacity()*t.pstyle("text-opacity").value:1,l=t.pstyle("text-outline-opacity").value*s,u=t.pstyle("color").value,c=t.pstyle("text-outline-color").value;e.font=r+" "+o+" "+i+" "+a,e.lineJoin="round",this.colorFillStyle(e,u[0],u[1],u[2],s),this.colorStrokeStyle(e,c[0],c[1],c[2],l)},Ku.getTextAngle=function(e,t){var n=e._private.rscratch,r=t?t+"-":"",i=e.pstyle(r+"text-rotation"),a=Ue(n,"labelAngle",t);return"autorotate"===i.strValue?e.isEdge()?a:0:"none"===i.strValue?0:i.pfValue},Ku.drawText=function(e,t,n){var r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],a=t._private,o=a.rscratch,s=i?t.effectiveOpacity():1;if(!i||0!==s&&0!==t.pstyle("text-opacity").value){"main"===n&&(n=null);var l,u,c=Ue(o,"labelX",n),d=Ue(o,"labelY",n),h=this.getLabelText(t,n);if(null!=h&&""!==h&&!isNaN(c)&&!isNaN(d)){this.setupTextStyle(e,t,i);var p,f=n?n+"-":"",g=Ue(o,"labelWidth",n),v=Ue(o,"labelHeight",n),y=t.pstyle(f+"text-margin-x").pfValue,m=t.pstyle(f+"text-margin-y").pfValue,b=t.isEdge(),x=t.pstyle("text-halign").value,w=t.pstyle("text-valign").value;switch(b&&(x="center",w="center"),c+=y,d+=m,0!==(p=r?this.getTextAngle(t,n):0)&&(l=c,u=d,e.translate(l,u),e.rotate(p),c=0,d=0),w){case"top":break;case"center":d+=v/2;break;case"bottom":d+=v}var E=t.pstyle("text-background-opacity").value,k=t.pstyle("text-border-opacity").value,C=t.pstyle("text-border-width").pfValue,S=t.pstyle("text-background-padding").pfValue,P=t.pstyle("text-background-shape").strValue,D=0===P.indexOf("round"),T=2;if(E>0||C>0&&k>0){var _=c-S;switch(x){case"left":_-=g;break;case"center":_-=g/2}var M=d-v-S,B=g+2*S,N=v+2*S;if(E>0){var z=e.fillStyle,I=t.pstyle("text-background-color").value;e.fillStyle="rgba("+I[0]+","+I[1]+","+I[2]+","+E*s+")",D?Gu(e,_,M,B,N,T):e.fillRect(_,M,B,N),e.fillStyle=z}if(C>0&&k>0){var A=e.strokeStyle,L=e.lineWidth,O=t.pstyle("text-border-color").value,R=t.pstyle("text-border-style").value;if(e.strokeStyle="rgba("+O[0]+","+O[1]+","+O[2]+","+k*s+")",e.lineWidth=C,e.setLineDash)switch(R){case"dotted":e.setLineDash([1,1]);break;case"dashed":e.setLineDash([4,2]);break;case"double":e.lineWidth=C/4,e.setLineDash([]);break;case"solid":e.setLineDash([])}if(D?Gu(e,_,M,B,N,T,"stroke"):e.strokeRect(_,M,B,N),"double"===R){var V=C/2;D?Gu(e,_+V,M+V,B-2*V,N-2*V,T,"stroke"):e.strokeRect(_+V,M+V,B-2*V,N-2*V)}e.setLineDash&&e.setLineDash([]),e.lineWidth=L,e.strokeStyle=A}}var F=2*t.pstyle("text-outline-width").pfValue;if(F>0&&(e.lineWidth=F),"wrap"===t.pstyle("text-wrap").value){var j=Ue(o,"labelWrapCachedLines",n),q=Ue(o,"labelLineHeight",n),Y=g/2,X=this.getLabelJustification(t);switch("auto"===X||("left"===x?"left"===X?c+=-g:"center"===X&&(c+=-Y):"center"===x?"left"===X?c+=-Y:"right"===X&&(c+=Y):"right"===x&&("center"===X?c+=Y:"right"===X&&(c+=g))),w){case"top":d-=(j.length-1)*q;break;case"center":case"bottom":d-=(j.length-1)*q}for(var W=0;W0&&e.strokeText(j[W],c,d),e.fillText(j[W],c,d),d+=q}else F>0&&e.strokeText(h,c,d),e.fillText(h,c,d);0!==p&&(e.rotate(-p),e.translate(-l,-u))}}};var Uu={drawNode:function(e,t,n){var r,i,a=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],o=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],s=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],l=this,u=t._private,c=u.rscratch,d=t.position();if(x(d.x)&&x(d.y)&&(!s||t.visible())){var h,p,f=s?t.effectiveOpacity():1,g=l.usePaths(),v=!1,y=t.padding();r=t.width()+2*y,i=t.height()+2*y,n&&(p=n,e.translate(-p.x1,-p.y1));for(var m=t.pstyle("background-image"),b=m.value,w=new Array(b.length),E=new Array(b.length),k=0,C=0;C0&&void 0!==arguments[0]?arguments[0]:M;l.eleFillStyle(e,t,n)},H=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:R;l.colorStrokeStyle(e,B[0],B[1],B[2],t)},K=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:q;l.colorStrokeStyle(e,F[0],F[1],F[2],t)},G=function(e,t,n,r){var i,a=l.nodePathCache=l.nodePathCache||[],o=_e("polygon"===n?n+","+r.join(","):n,""+t,""+e,""+X),s=a[o],u=!1;return null!=s?(i=s,u=!0,c.pathCache=i):(i=new Path2D,a[o]=c.pathCache=i),{path:i,cacheHit:u}},U=t.pstyle("shape").strValue,Z=t.pstyle("shape-polygon-points").pfValue;if(g){e.translate(d.x,d.y);var $=G(r,i,U,Z);h=$.path,v=$.cacheHit}var Q=function(){if(!v){var n=d;g&&(n={x:0,y:0}),l.nodeShapes[l.getNodeShape(t)].draw(h||e,n.x,n.y,r,i,X,c)}g?e.fill(h):e.fill()},J=function(){for(var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:f,r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=u.backgrounding,a=0,o=0;o0&&void 0!==arguments[0]&&arguments[0],a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:f;l.hasPie(t)&&(l.drawPie(e,t,a),n&&(g||l.nodeShapes[l.getNodeShape(t)].draw(e,d.x,d.y,r,i,X,c)))},te=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:f,n=(T>0?T:-T)*t,r=T>0?0:255;0!==T&&(l.colorFillStyle(e,r,r,r,n),g?e.fill(h):e.fill())},ne=function(){if(_>0){if(e.lineWidth=_,e.lineCap=I,e.lineJoin=z,e.setLineDash)switch(N){case"dotted":e.setLineDash([1,1]);break;case"dashed":e.setLineDash(L),e.lineDashOffset=O;break;case"solid":case"double":e.setLineDash([])}if("center"!==A){if(e.save(),e.lineWidth*=2,"inside"===A)g?e.clip(h):e.clip();else{var t=new Path2D;t.rect(-r/2-_,-i/2-_,r+2*_,i+2*_),t.addPath(h),e.clip(t,"evenodd")}g?e.stroke(h):e.stroke(),e.restore()}else g?e.stroke(h):e.stroke();if("double"===N){e.lineWidth=_/3;var n=e.globalCompositeOperation;e.globalCompositeOperation="destination-out",g?e.stroke(h):e.stroke(),e.globalCompositeOperation=n}e.setLineDash&&e.setLineDash([])}},re=function(){if(V>0){if(e.lineWidth=V,e.lineCap="butt",e.setLineDash)switch(j){case"dotted":e.setLineDash([1,1]);break;case"dashed":e.setLineDash([4,2]);break;case"solid":case"double":e.setLineDash([])}var n=d;g&&(n={x:0,y:0});var a=l.getNodeShape(t),o=_;"inside"===A&&(o=0),"outside"===A&&(o*=2);var s,u=(r+o+(V+Y))/r,c=(i+o+(V+Y))/i,h=r*u,p=i*c,f=l.nodeShapes[a].points;if(g)s=G(h,p,a,f).path;if("ellipse"===a)l.drawEllipsePath(s||e,n.x,n.y,h,p);else if(["round-diamond","round-heptagon","round-hexagon","round-octagon","round-pentagon","round-polygon","round-triangle","round-tag"].includes(a)){var v=0,y=0,m=0;"round-diamond"===a?v=1.4*(o+Y+V):"round-heptagon"===a?(v=1.075*(o+Y+V),m=-(o/2+Y+V)/35):"round-hexagon"===a?v=1.12*(o+Y+V):"round-pentagon"===a?(v=1.13*(o+Y+V),m=-(o/2+Y+V)/15):"round-tag"===a?(v=1.12*(o+Y+V),y=.07*(o/2+V+Y)):"round-triangle"===a&&(v=(o+Y+V)*(Math.PI/2),m=-(o+Y/2+V)/Math.PI),0!==v&&(h=r*(u=(r+v)/r),["round-hexagon","round-tag"].includes(a)||(p=i*(c=(i+v)/i)));for(var b=h/2,x=p/2,w=(X="auto"===X?rn(h,p):X)+(o+V+Y)/2,E=new Array(f.length/2),k=new Array(f.length/2),C=0;C0){if(r=r||n.position(),null==i||null==a){var d=n.padding();i=n.width()+2*d,a=n.height()+2*d}this.colorFillStyle(t,l[0],l[1],l[2],s),this.nodeShapes[u].draw(t,r.x,r.y,i+2*o,a+2*o,c),t.fill()}}}};Uu.drawNodeOverlay=Zu("overlay"),Uu.drawNodeUnderlay=Zu("underlay"),Uu.hasPie=function(e){return(e=e[0])._private.hasPie},Uu.drawPie=function(e,t,n,r){t=t[0],r=r||t.position();var i=t.cy().style(),a=t.pstyle("pie-size"),o=r.x,s=r.y,l=t.width(),u=t.height(),c=Math.min(l,u)/2,d=0;this.usePaths()&&(o=0,s=0),"%"===a.units?c*=a.pfValue:void 0!==a.pfValue&&(c=a.pfValue/2);for(var h=1;h<=i.pieBackgroundN;h++){var p=t.pstyle("pie-"+h+"-background-size").value,f=t.pstyle("pie-"+h+"-background-color").value,g=t.pstyle("pie-"+h+"-background-opacity").value*n,v=p/100;v+d>1&&(v=1-d);var y=1.5*Math.PI+2*Math.PI*d,m=y+2*Math.PI*v;0===p||d>=1||d+v>1||(e.beginPath(),e.moveTo(o,s),e.arc(o,s,c,y,m),e.closePath(),this.colorFillStyle(e,f[0],f[1],f[2],g),e.fill(),d+=v)}};var $u={};$u.getPixelRatio=function(){var e=this.data.contexts[0];if(null!=this.forcedPixelRatio)return this.forcedPixelRatio;var t=this.cy.window(),n=e.backingStorePixelRatio||e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1;return(t.devicePixelRatio||1)/n},$u.paintCache=function(e){for(var t,n=this.paintCaches=this.paintCaches||[],r=!0,i=0;io.minMbLowQualFrames&&(o.motionBlurPxRatio=o.mbPxRBlurry)),o.clearingMotionBlur&&(o.motionBlurPxRatio=1),o.textureDrawLastFrame&&!d&&(c[o.NODE]=!0,c[o.SELECT_BOX]=!0);var m=l.style(),b=l.zoom(),x=void 0!==i?i:b,w=l.pan(),E={x:w.x,y:w.y},k={zoom:b,pan:{x:w.x,y:w.y}},C=o.prevViewport;void 0===C||k.zoom!==C.zoom||k.pan.x!==C.pan.x||k.pan.y!==C.pan.y||g&&!f||(o.motionBlurPxRatio=1),a&&(E=a),x*=s,E.x*=s,E.y*=s;var S=o.getCachedZSortedEles();function P(e,t,n,r,i){var a=e.globalCompositeOperation;e.globalCompositeOperation="destination-out",o.colorFillStyle(e,255,255,255,o.motionBlurTransparency),e.fillRect(t,n,r,i),e.globalCompositeOperation=a}function D(e,r){var s,l,c,d;o.clearingMotionBlur||e!==u.bufferContexts[o.MOTIONBLUR_BUFFER_NODE]&&e!==u.bufferContexts[o.MOTIONBLUR_BUFFER_DRAG]?(s=E,l=x,c=o.canvasWidth,d=o.canvasHeight):(s={x:w.x*p,y:w.y*p},l=b*p,c=o.canvasWidth*p,d=o.canvasHeight*p),e.setTransform(1,0,0,1,0,0),"motionBlur"===r?P(e,0,0,c,d):t||void 0!==r&&!r||e.clearRect(0,0,c,d),n||(e.translate(s.x,s.y),e.scale(l,l)),a&&e.translate(a.x,a.y),i&&e.scale(i,i)}if(d||(o.textureDrawLastFrame=!1),d){if(o.textureDrawLastFrame=!0,!o.textureCache){o.textureCache={},o.textureCache.bb=l.mutableElements().boundingBox(),o.textureCache.texture=o.data.bufferCanvases[o.TEXTURE_BUFFER];var T=o.data.bufferContexts[o.TEXTURE_BUFFER];T.setTransform(1,0,0,1,0,0),T.clearRect(0,0,o.canvasWidth*o.textureMult,o.canvasHeight*o.textureMult),o.render({forcedContext:T,drawOnlyNodeLayer:!0,forcedPxRatio:s*o.textureMult}),(k=o.textureCache.viewport={zoom:l.zoom(),pan:l.pan(),width:o.canvasWidth,height:o.canvasHeight}).mpan={x:(0-k.pan.x)/k.zoom,y:(0-k.pan.y)/k.zoom}}c[o.DRAG]=!1,c[o.NODE]=!1;var _=u.contexts[o.NODE],M=o.textureCache.texture;k=o.textureCache.viewport;_.setTransform(1,0,0,1,0,0),h?P(_,0,0,k.width,k.height):_.clearRect(0,0,k.width,k.height);var B=m.core("outside-texture-bg-color").value,N=m.core("outside-texture-bg-opacity").value;o.colorFillStyle(_,B[0],B[1],B[2],N),_.fillRect(0,0,k.width,k.height);b=l.zoom();D(_,!1),_.clearRect(k.mpan.x,k.mpan.y,k.width/k.zoom/s,k.height/k.zoom/s),_.drawImage(M,k.mpan.x,k.mpan.y,k.width/k.zoom/s,k.height/k.zoom/s)}else o.textureOnViewport&&!t&&(o.textureCache=null);var z=l.extent(),I=o.pinching||o.hoverData.dragging||o.swipePanning||o.data.wheelZooming||o.hoverData.draggingEles||o.cy.animated(),A=o.hideEdgesOnViewport&&I,L=[];if(L[o.NODE]=!c[o.NODE]&&h&&!o.clearedForMotionBlur[o.NODE]||o.clearingMotionBlur,L[o.NODE]&&(o.clearedForMotionBlur[o.NODE]=!0),L[o.DRAG]=!c[o.DRAG]&&h&&!o.clearedForMotionBlur[o.DRAG]||o.clearingMotionBlur,L[o.DRAG]&&(o.clearedForMotionBlur[o.DRAG]=!0),c[o.NODE]||n||r||L[o.NODE]){var O=h&&!L[o.NODE]&&1!==p;D(_=t||(O?o.data.bufferContexts[o.MOTIONBLUR_BUFFER_NODE]:u.contexts[o.NODE]),h&&!O?"motionBlur":void 0),A?o.drawCachedNodes(_,S.nondrag,s,z):o.drawLayeredElements(_,S.nondrag,s,z),o.debug&&o.drawDebugPoints(_,S.nondrag),n||h||(c[o.NODE]=!1)}if(!r&&(c[o.DRAG]||n||L[o.DRAG])){O=h&&!L[o.DRAG]&&1!==p;D(_=t||(O?o.data.bufferContexts[o.MOTIONBLUR_BUFFER_DRAG]:u.contexts[o.DRAG]),h&&!O?"motionBlur":void 0),A?o.drawCachedNodes(_,S.drag,s,z):o.drawCachedElements(_,S.drag,s,z),o.debug&&o.drawDebugPoints(_,S.drag),n||h||(c[o.DRAG]=!1)}if(o.showFps||!r&&c[o.SELECT_BOX]&&!n){if(D(_=t||u.contexts[o.SELECT_BOX]),1==o.selection[4]&&(o.hoverData.selecting||o.touchData.selecting)){b=o.cy.zoom();var R=m.core("selection-box-border-width").value/b;_.lineWidth=R,_.fillStyle="rgba("+m.core("selection-box-color").value[0]+","+m.core("selection-box-color").value[1]+","+m.core("selection-box-color").value[2]+","+m.core("selection-box-opacity").value+")",_.fillRect(o.selection[0],o.selection[1],o.selection[2]-o.selection[0],o.selection[3]-o.selection[1]),R>0&&(_.strokeStyle="rgba("+m.core("selection-box-border-color").value[0]+","+m.core("selection-box-border-color").value[1]+","+m.core("selection-box-border-color").value[2]+","+m.core("selection-box-opacity").value+")",_.strokeRect(o.selection[0],o.selection[1],o.selection[2]-o.selection[0],o.selection[3]-o.selection[1]))}if(u.bgActivePosistion&&!o.hoverData.selecting){b=o.cy.zoom();var V=u.bgActivePosistion;_.fillStyle="rgba("+m.core("active-bg-color").value[0]+","+m.core("active-bg-color").value[1]+","+m.core("active-bg-color").value[2]+","+m.core("active-bg-opacity").value+")",_.beginPath(),_.arc(V.x,V.y,m.core("active-bg-size").pfValue/b,0,2*Math.PI),_.fill()}var F=o.lastRedrawTime;if(o.showFps&&F){F=Math.round(F);var j=Math.round(1e3/F);_.setTransform(1,0,0,1,0,0),_.fillStyle="rgba(255, 0, 0, 0.75)",_.strokeStyle="rgba(255, 0, 0, 0.75)",_.lineWidth=1,_.fillText("1 frame = "+F+" ms = "+j+" fps",0,20);_.strokeRect(0,30,250,20),_.fillRect(0,30,250*Math.min(j/60,1),20)}n||(c[o.SELECT_BOX]=!1)}if(h&&1!==p){var q=u.contexts[o.NODE],Y=o.data.bufferCanvases[o.MOTIONBLUR_BUFFER_NODE],X=u.contexts[o.DRAG],W=o.data.bufferCanvases[o.MOTIONBLUR_BUFFER_DRAG],H=function(e,t,n){e.setTransform(1,0,0,1,0,0),n||!y?e.clearRect(0,0,o.canvasWidth,o.canvasHeight):P(e,0,0,o.canvasWidth,o.canvasHeight);var r=p;e.drawImage(t,0,0,o.canvasWidth*r,o.canvasHeight*r,0,0,o.canvasWidth,o.canvasHeight)};(c[o.NODE]||L[o.NODE])&&(H(q,Y,L[o.NODE]),c[o.NODE]=!1),(c[o.DRAG]||L[o.DRAG])&&(H(X,W,L[o.DRAG]),c[o.DRAG]=!1)}o.prevViewport=k,o.clearingMotionBlur&&(o.clearingMotionBlur=!1,o.motionBlurCleared=!0,o.motionBlur=!0),h&&(o.motionBlurTimeout=setTimeout((function(){o.motionBlurTimeout=null,o.clearedForMotionBlur[o.NODE]=!1,o.clearedForMotionBlur[o.DRAG]=!1,o.motionBlur=!1,o.clearingMotionBlur=!d,o.mbFrames=0,c[o.NODE]=!0,c[o.DRAG]=!0,o.redraw()}),100)),t||l.emit("render")};for(var Qu={drawPolygonPath:function(e,t,n,r,i,a){var o=r/2,s=i/2;e.beginPath&&e.beginPath(),e.moveTo(t+o*a[0],n+s*a[1]);for(var l=1;l0&&a>0){h.clearRect(0,0,i,a),h.globalCompositeOperation="source-over";var p=this.getCachedZSortedEles();if(e.full)h.translate(-n.x1*l,-n.y1*l),h.scale(l,l),this.drawElements(h,p),h.scale(1/l,1/l),h.translate(n.x1*l,n.y1*l);else{var f=t.pan(),g={x:f.x*l,y:f.y*l};l*=t.zoom(),h.translate(g.x,g.y),h.scale(l,l),this.drawElements(h,p),h.scale(1/l,1/l),h.translate(-g.x,-g.y)}e.bg&&(h.globalCompositeOperation="destination-over",h.fillStyle=e.bg,h.rect(0,0,i,a),h.fill())}return d},ac.png=function(e){return sc(e,this.bufferCanvasImage(e),"image/png")},ac.jpg=function(e){return sc(e,this.bufferCanvasImage(e),"image/jpeg")};var lc={nodeShapeImpl:function(e,t,n,r,i,a,o,s){switch(e){case"ellipse":return this.drawEllipsePath(t,n,r,i,a);case"polygon":return this.drawPolygonPath(t,n,r,i,a,o);case"round-polygon":return this.drawRoundPolygonPath(t,n,r,i,a,o,s);case"roundrectangle":case"round-rectangle":return this.drawRoundRectanglePath(t,n,r,i,a,s);case"cutrectangle":case"cut-rectangle":return this.drawCutRectanglePath(t,n,r,i,a,o,s);case"bottomroundrectangle":case"bottom-round-rectangle":return this.drawBottomRoundRectanglePath(t,n,r,i,a,s);case"barrel":return this.drawBarrelPath(t,n,r,i,a)}}},uc=dc,cc=dc.prototype;function dc(e){var t=this,n=t.cy.window().document;t.data={canvases:new Array(cc.CANVAS_LAYERS),contexts:new Array(cc.CANVAS_LAYERS),canvasNeedsRedraw:new Array(cc.CANVAS_LAYERS),bufferCanvases:new Array(cc.BUFFER_COUNT),bufferContexts:new Array(cc.CANVAS_LAYERS)};t.data.canvasContainer=n.createElement("div");var r=t.data.canvasContainer.style;t.data.canvasContainer.style["-webkit-tap-highlight-color"]="rgba(0,0,0,0)",r.position="relative",r.zIndex="0",r.overflow="hidden";var i=e.cy.container();i.appendChild(t.data.canvasContainer),i.style["-webkit-tap-highlight-color"]="rgba(0,0,0,0)";var a={"-webkit-user-select":"none","-moz-user-select":"-moz-none","user-select":"none","-webkit-tap-highlight-color":"rgba(0,0,0,0)","outline-style":"none"};c&&c.userAgent.match(/msie|trident|edge/i)&&(a["-ms-touch-action"]="none",a["touch-action"]="none");for(var o=0;o{var explorer_templates_default={"explorer-head.mustache":` + + + + +{{{pageTitle}}} · {{{siteTitle}}} + + + + + +
+ {{{siteTitle}}} model explorer + + + +
+
+ +`,"explorer-foot.mustache":`
+
Built from explorer.json by the metaobjects docs-site generator{{#stamp}} · {{{stamp}}}{{/stamp}}. Static: no server, no LLM call.
+ +{{#needsGraph}}{{/needsGraph}} + + + +`,"explorer-card.mustache":`
+

{{{levelHtml}}}{{{linkHtml}}} {{{statusHtml}}}{{{verdictHtml}}}

+
{{{statement}}}
+
{{{barHtml}}}
{{{countsLine}}}
+ {{#hasChildren}}
    {{#children}}
  • {{{levelHtml}}}{{{linkHtml}}} {{{glyphHtml}}}
  • {{/children}}
{{/hasChildren}} +
Summary from the levels below
No summary is generated in this build.
+
+`,"explorer-overview.html.mustache":`

{{{heading}}}

+
Built from {{{sourcesLine}}}. Every number below is computed from the project's metadata or the gate's own output.
+
+{{#tiles}}
{{{n}}}
{{{l}}}
+{{/tiles}}
+{{#hasRequirements}}{{{legendHtml}}}{{/hasRequirements}} +{{#hasRequirements}} +

Features requirement.functional, by level

+{{#hasFeatures}}
+{{#featureCards}}{{> card}}{{/featureCards}} +
{{/hasFeatures}} +{{^hasFeatures}}
No requirement.functional is declared.
{{/hasFeatures}} +

Qualities requirement.architectural, the non-functional policies

+{{#hasQualities}}
+{{#qualityCards}}{{> card}}{{/qualityCards}} +
{{/hasQualities}} +{{^hasQualities}}
No requirement.architectural is declared.
{{/hasQualities}} +{{/hasRequirements}} +{{^hasRequirements}} +
This model declares no requirements yet, so this page cannot say what each part is for. Declare requirement.functional entries (levels 1 to 3 for the problem, 4 and 5 naming the model) and this page opens on them, with every entity traced to the feature it serves.
+{{/hasRequirements}} +

Packages what the model holds

+
+{{#packageCards}}

{{{name}}}

{{{kindLineHtml}}}
{{{membersHtml}}}
+{{/packageCards}}
+`,"explorer-map.html.mustache":`

Model map

+
Entities and the references between them. A slice is the set of model nodes a requirement subtree claims, a package holds, or a prompt reads and returns.
+
+ + + + + + + +
+
Click a node to see why it exists, what it holds and what was generated from it. Double-click to open its page.
+
+ +`,"explorer-object.html.mustache":`
{{{crumbsHtml}}}
+

{{{name}}} {{#isAbstract}}abstract{{/isAbstract}}{{#isReadOnly}}read-only view{{/isReadOnly}}{{#isUnclaimed}}unclaimed{{/isUnclaimed}}

+ +{{#description}}
{{{description}}}
{{/description}} +
{{{kindLabel}}} · {{{storageLine}}}{{#extendsHtml}} · extends {{{extendsHtml}}}{{/extendsHtml}}
+
+
+

Why it exists

+ {{#hasWhy}}
+ {{#whyRows}} + {{/whyRows}}
CapabilityRequirementLevelStatusOn
{{{capabilityHtml}}}{{{reqHtml}}}
{{{statement}}}
{{{levelHtml}}}{{{statusHtml}}}{{{onHtml}}}
{{/hasWhy}} + {{^hasWhy}}
{{{whyEmptyHtml}}}
{{/hasWhy}} + {{#projection}} +

Read model

+
+ {{#basesHtml}}
Surfaces fields of {{{basesHtml}}}.
{{/basesHtml}} + {{#hasOrigins}}
{{#origins}}{{/origins}}
FieldOriginDefinition
{{{field}}}{{{origin}}}{{{definitionHtml}}}
{{/hasOrigins}} +
+ {{/projection}} + {{#report}} +

Report

+
+ {{#fromHtml}}{{/fromHtml}} + {{#spineHtml}}{{/spineHtml}} + {{#dimensionsHtml}}{{/dimensionsHtml}} + {{#measuresHtml}}{{/measuresHtml}} + {{#segmentHtml}}{{/segmentHtml}} + {{#filterHtml}}{{/filterHtml}} +
From{{{fromHtml}}}
Spine{{{spineHtml}}}
Dimensions{{{dimensionsHtml}}}
Measures{{{measuresHtml}}}
Segment{{{segmentHtml}}}
Filter{{{filterHtml}}}
+ {{/report}} + {{#hasFields}}

Fields

+
{{#hasColumn}}{{/hasColumn}}{{#showClaims}}{{/showClaims}} + {{#fields}}{{#hasColumn}}{{/hasColumn}}{{#showClaims}}{{/showClaims}} + {{/fields}}
FieldTypeColumnFlagsClaimed at L5
{{{name}}} {{{inheritedHtml}}}{{{type}}}{{{refHtml}}}{{{valuesHtml}}}{{{column}}}{{{flagsHtml}}}{{{claimsHtml}}}
{{/hasFields}} + {{#hasKeys}}

Keys and references

+
{{#keys}}{{/keys}}
{{{kind}}} {{{name}}} {{{inheritedHtml}}}{{{shape}}}{{{targetHtml}}}
{{/hasKeys}} + {{#hasReporting}}

Reporting vocabulary

+
{{#reporting}}{{/reporting}}
NameKindDefinition
{{{name}}}{{{kind}}}{{{definitionHtml}}}
{{/hasReporting}} + {{#hasLayouts}}

Screens declared

{{#layouts}}
{{{kind}}} {{{name}}}{{#detailHtml}}: {{{detailHtml}}}{{/detailHtml}}
{{/layouts}}{{/hasLayouts}} +
+ +
+`,"explorer-node.html.mustache":`
{{{crumbsHtml}}}
+

{{{name}}} {{#isAbstract}}abstract{{/isAbstract}}

+ +{{#description}}
{{{description}}}
{{/description}} +
{{{kindLabel}}}{{#extendsHtml}} · extends {{{extendsHtml}}}{{/extendsHtml}}
+
+
+

Why it exists

+ {{#hasWhy}}
+ {{#whyRows}} + {{/whyRows}}
CapabilityRequirementLevelStatusOn
{{{capabilityHtml}}}{{{reqHtml}}}
{{{statement}}}
{{{levelHtml}}}{{{statusHtml}}}{{{onHtml}}}
{{/hasWhy}} + {{^hasWhy}}
{{{whyEmptyHtml}}}
{{/hasWhy}} + {{#hasAttrs}}

Attributes

+
{{#attrs}}{{/attrs}}
@{{{name}}}{{{valueHtml}}}
{{/hasAttrs}} + {{#hasMembers}}

Members

+
+ {{#members}} + {{/members}}
NameTypeAttributes
{{{nameHtml}}}{{#below}} +{{below}}{{/below}}{{{kind}}}{{{attrsHtml}}}
{{/hasMembers}} +
+ +
+`,"explorer-prompt.html.mustache":`
{{{crumbsHtml}}}
+

{{{name}}} {{#isUnclaimed}}unclaimed{{/isUnclaimed}}

+ +{{#description}}
{{{description}}}
{{/description}} +
{{{attrsHtml}}}
+
+
+

Payload: {{{payloadHtml}}}

+ {{#hasPayload}}
{{#payloadRows}}{{/payloadRows}}
FieldTypeUsed in text
{{{name}}} {{{requiredHtml}}}{{{type}}}{{{refHtml}}}{{{usedHtml}}}
{{/hasPayload}} + {{^hasPayload}}
No payload: the text renders from nothing typed.
{{/hasPayload}} +

Reply: {{{replyHtml}}}

+ {{#hasReply}}
{{#replyRows}}{{/replyRows}}
FieldType
{{{name}}}{{{type}}}{{{valuesHtml}}}
{{/hasReply}} + {{^hasReply}}
Outbound only: no reply parser.
{{/hasReply}} +

Why it exists

+ {{#hasWhy}}
{{#whyRows}}{{/whyRows}}
CapabilityRequirementLevelStatus
{{{capabilityHtml}}}{{{reqHtml}}}
{{{statement}}}
{{{levelHtml}}}{{{statusHtml}}}
{{/hasWhy}} + {{^hasWhy}}
{{{whyEmptyHtml}}}
{{/hasWhy}} +
+
+

Text {{{textMeta}}}

+ {{#hasText}}
{{{textHtml}}}
{{/hasText}} + {{^hasText}}
The text {{{textRef}}} was not found beside the model, so this page cannot show it.
{{/hasText}} +

Generated

+ {{#hasGenerated}}{{#generated}}
{{{generator}}}{{#files}}
{{{.}}}
{{/files}}
{{/generated}}{{/hasGenerated}} + {{^hasGenerated}}
{{{generatedNote}}}
{{/hasGenerated}} +
Proven today: meta verify --templates fails if the text names a variable the payload lacks. This page shows the other direction too: payload fields the text never uses.
+
+
+`,"explorer-prompts.html.mustache":`

Prompts

+
Each declared template, its typed payload, its reply type, and the requirements that claim it.
+{{#hasRows}}
+{{#rows}} +{{/rows}}
TemplatePayloadReplyClaimed by
{{{linkHtml}}} {{{kind}}}{{#description}}
{{{description}}}
{{/description}}
{{{payloadHtml}}}{{{replyHtml}}}{{{claimsHtml}}}
{{/hasRows}} +{{^hasRows}}
This model declares no template.*.
{{/hasRows}} +`,"explorer-requirements.html.mustache":`

Requirements

+
Hierarchy is nesting. L1 to L3 describe the problem; only L4 (an object or prompt) and L5 (a member) may name the model.
+ +{{{legendHtml}}} +{{#hasTree}}
{{{treeHtml}}}
{{/hasTree}} +{{^hasTree}}
{{{emptyNote}}}
{{/hasTree}} +`,"explorer-requirement.html.mustache":`
{{{crumbsHtml}}}
+

{{{levelHtml}}}{{{name}}} {{{statusHtml}}}{{{dispositionHtml}}}{{{verdictHtml}}}

+ +
{{{address}}}
+
+
+

Statement

{{{statement}}}

Counterexample

{{{counterexample}}}{{#hasDescription}}

Scope

{{{description}}}
{{/hasDescription}}
+

Implemented by

+ {{#hasLinks}}
{{#linkRows}}{{/linkRows}}
ReferenceKindResolves
{{{refHtml}}}{{{kind}}}{{{resolvesHtml}}}
{{/hasLinks}} + {{^hasLinks}}
{{{linksEmpty}}}
{{/hasLinks}} + {{#hasBelow}}

Below ({{childCount}}){{#deeper}} {{belowCount}} in all{{/deeper}}

{{{belowBarHtml}}}
    {{#children}}
  • {{{levelHtml}}}{{{linkHtml}}} {{{statusHtml}}}
  • {{/children}}
{{/hasBelow}} +
{{#sliceHref}}Show this slice on the model map{{/sliceHref}}{{#sliceHref}}{{#traceHref}} · {{/traceHref}}{{/sliceHref}}{{#traceHref}}Trace to code{{/traceHref}}
+
+
+

What the build proves about this entry

+
{{#proof}}{{/proof}}
{{{what}}}{{{verdictHtml}}}{{{howHtml}}}
+ {{#trackedHtml}}

Tracked by

{{{trackedHtml}}}{{/trackedHtml}} + {{#digest}}

Statement digest

{{{digest}}}
Moves when the statement changes; a summary of this entry would be pinned to it.
{{/digest}} +
+
+`,"explorer-matrix.html.mustache":`

Traceability matrix

+
Rows are requirements that name the model; columns are stored entities and prompts, most claimed first. An empty column is a node nothing claims; a cell's colour and glyph are the row's declared status.
+{{#hasRows}}
{{{legendHtml}}}
+
{{{tableHtml}}}
{{/hasRows}} +{{^hasRows}}
{{#hasRequirements}}No requirement names the model yet: only L4 and L5 entries do.{{/hasRequirements}}{{^hasRequirements}}This model declares no requirements, so there is nothing to trace.{{/hasRequirements}}
{{/hasRows}} +`,"explorer-trace.html.mustache":`

Trace

+
From intent to code: requirement levels, then the model nodes they name, then the files generated from those nodes.
+{{#hasStarts}}
+ +
Hand-written modules that import the generated files are not scanned in this build, so the trace stops at the generated files. Click a requirement or a model node to open its page.
{{/hasStarts}} +{{^hasStarts}}
This model declares no requirements, so there is nothing to trace from. Every object's generated files are listed on its own page.
{{/hasStarts}} +`,"explorer-gaps.html.mustache":`

Gaps

+
What the model and the gate can already point at. Each card says whether it comes from the shipped gate or is a check this explorer adds.
+
+{{#cards}}

{{{title}}} {{{count}}} {{{source}}}

{{{whyHtml}}}
{{{bodyHtml}}}
+{{/cards}}
+`,"explorer-api.html.mustache":`

API

+{{#recorded}}
Every route the generated code mounts, by the object it serves: {{{summary}}}.
+{{#hasGroups}}
{{#groups}}

{{{linkHtml}}} {{{kind}}}{{#isReadOnly}} read-only{{/isReadOnly}}

{{#routes}}
{{{method}}} {{{path}}}
{{/routes}}
{{/groups}}
{{/hasGroups}} +{{^hasGroups}}
The run generated no routes.
{{/hasGroups}}{{/recorded}} +{{^recorded}}
The run that built this site recorded no routes: it generated none, or ran without the routes generator.
{{/recorded}} +`,"explorer-model.html.mustache":`

Packages

+
Every package in the model and what it declares.
+
+{{#packageCards}}

{{{name}}}

{{{kindLineHtml}}}
{{{membersHtml}}}
+{{/packageCards}}
+`,"explorer-package.html.mustache":`
{{{crumbsHtml}}}
+

{{{name}}}

+
+{{#rows}} +{{/rows}}
NameKindStorageFieldsClaim
{{{linkHtml}}} {{{abstractHtml}}}{{#description}}
{{{description}}}
{{/description}}
{{{kind}}}{{{storage}}}{{fieldCount}}{{{statusHtml}}}
+`};/*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */var objectToString=Object.prototype.toString,isArray=Array.isArray||function(object){return objectToString.call(object)==="[object Array]"};function isFunction(object){return typeof object==="function"}function typeStr(obj){return isArray(obj)?"array":typeof obj}function escapeRegExp(string){return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function hasProperty(obj,propName){return obj!=null&&typeof obj==="object"&&propName in obj}function primitiveHasOwnProperty(primitive,propName){return primitive!=null&&typeof primitive!=="object"&&primitive.hasOwnProperty&&primitive.hasOwnProperty(propName)}var regExpTest=RegExp.prototype.test;function testRegExp(re,string){return regExpTest.call(re,string)}var nonSpaceRe=/\S/;function isWhitespace(string){return!testRegExp(nonSpaceRe,string)}var entityMap={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function escapeHtml(string){return String(string).replace(/[&<>"'`=\/]/g,function(s){return entityMap[s]})}var whiteRe=/\s*/,spaceRe=/\s+/,equalsRe=/\s*=/,curlyRe=/\s*\}/,tagRe=/#|\^|\/|>|\{|&|=|!/;function parseTemplate(template,tags){if(!template)return[];var lineHasNonSpace=!1,sections=[],tokens=[],spaces=[],hasTag=!1,nonSpace=!1,indentation="",tagIndex=0;function stripSpace(){if(hasTag&&!nonSpace)while(spaces.length)delete tokens[spaces.pop()];else spaces=[];hasTag=!1,nonSpace=!1}var openingTagRe,closingTagRe,closingCurlyRe;function compileTags(tagsToCompile){if(typeof tagsToCompile==="string")tagsToCompile=tagsToCompile.split(spaceRe,2);if(!isArray(tagsToCompile)||tagsToCompile.length!==2)throw Error("Invalid tags: "+tagsToCompile);openingTagRe=new RegExp(escapeRegExp(tagsToCompile[0])+"\\s*"),closingTagRe=new RegExp("\\s*"+escapeRegExp(tagsToCompile[1])),closingCurlyRe=new RegExp("\\s*"+escapeRegExp("}"+tagsToCompile[1]))}compileTags(tags||mustache.tags);var scanner=new Scanner(template),start,type,value,chr,token,openSection;while(!scanner.eos()){if(start=scanner.pos,value=scanner.scanUntil(openingTagRe),value)for(var i=0,valueLength=value.length;i")token=[type,value,start,scanner.pos,indentation,tagIndex,lineHasNonSpace];else token=[type,value,start,scanner.pos];if(tagIndex++,tokens.push(token),type==="#"||type==="^")sections.push(token);else if(type==="/"){if(openSection=sections.pop(),!openSection)throw Error('Unopened section "'+value+'" at '+start);if(openSection[1]!==value)throw Error('Unclosed section "'+openSection[1]+'" at '+start)}else if(type==="name"||type==="{"||type==="&")nonSpace=!0;else if(type==="=")compileTags(value)}if(stripSpace(),openSection=sections.pop(),openSection)throw Error('Unclosed section "'+openSection[1]+'" at '+scanner.pos);return nestTokens(squashTokens(tokens))}function squashTokens(tokens){var squashedTokens=[],token,lastToken;for(var i=0,numTokens=tokens.length;i0?sections[sections.length-1][4]:nestedTokens;break;default:collector.push(token)}return nestedTokens}function Scanner(string){this.string=string,this.tail=string,this.pos=0}Scanner.prototype.eos=function(){return this.tail===""};Scanner.prototype.scan=function(re){var match=this.tail.match(re);if(!match||match.index!==0)return"";var string=match[0];return this.tail=this.tail.substring(string.length),this.pos+=string.length,string};Scanner.prototype.scanUntil=function(re){var index=this.tail.search(re),match;switch(index){case-1:match=this.tail,this.tail="";break;case 0:match="";break;default:match=this.tail.substring(0,index),this.tail=this.tail.substring(index)}return this.pos+=match.length,match};function Context(view,parentContext){this.view=view,this.cache={".":this.view},this.parent=parentContext}Context.prototype.push=function(view){return new Context(view,this)};Context.prototype.lookup=function(name){var cache=this.cache,value;if(cache.hasOwnProperty(name))value=cache[name];else{var context=this,intermediateValue,names,index,lookupHit=!1;while(context){if(name.indexOf(".")>0){intermediateValue=context.view,names=name.split("."),index=0;while(intermediateValue!=null&&index")value=this.renderPartial(token,context,partials,config);else if(symbol==="&")value=this.unescapedValue(token,context);else if(symbol==="name")value=this.escapedValue(token,context,config);else if(symbol==="text")value=this.rawValue(token);if(value!==void 0)buffer+=value}return buffer};Writer.prototype.renderSection=function(token,context,partials,originalTemplate,config){var self=this,buffer="",value=context.lookup(token[1]);function subRender(template){return self.render(template,context,partials,config)}if(!value)return;if(isArray(value))for(var j=0,valueLength=value.length;j0||!lineHasNonSpace))partialByNl[i]=filteredIndentation+partialByNl[i];return partialByNl.join(` +`)};Writer.prototype.renderPartial=function(token,context,partials,config){if(!partials)return;var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;if(tagIndex==0&&indentation)indentedValue=this.indentPartial(value,indentation,lineHasNonSpace);var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}};Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(value!=null)return typeof value==="number"&&escape===mustache.escape?String(value):escape(value)};Writer.prototype.rawValue=function(token){return token[1]};Writer.prototype.getConfigTags=function(config){if(isArray(config))return config;else if(config&&typeof config==="object")return config.tags;else return};Writer.prototype.getConfigEscape=function(config){if(config&&typeof config==="object"&&!isArray(config))return config.escape;else return};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials,config){if(typeof template!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+typeStr(template)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(template,view,partials,config)};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;var mustache_default=mustache;var xml=(s)=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),STRICT_NUMERIC=/^-?[0-9]+(\.[0-9]+)?$/,injectionGuard=(s)=>/^[=+\-@\t\r]/.test(s)&&!STRICT_NUMERIC.test(s)?"'"+s:s,csv=(s)=>{let v=injectionGuard(s);return/[",\n\r]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},json=(s)=>JSON.stringify(s).slice(1,-1),raw=(s)=>s,ESCAPERS={text:raw,markdown:raw,html:xml,xml,json,csv,spreadsheet:(s)=>injectionGuard(xml(s))};var HAS_PREFIX="has";function hasAccessorName(fieldName){return"has"+capitalize(fieldName)}var LAST_ACCESSOR="-last";function capitalize(s){if(s.length===0)return s;let c0=s.charAt(0);if(c0===c0.toUpperCase()&&c0!==c0.toLowerCase())return s;return c0.toUpperCase()+s.slice(1)}function accessorValue(value){if(value===null||value===void 0)return!1;if(typeof value==="string")return value.trim().length>0;if(Array.isArray(value))return value.length>0;if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return;return typeof value==="object"}function withDerivedAccessors(payload,depth=0){return derive(payload,depth,void 0)}function derive(payload,depth,last){if(depth>32)return payload;if(Array.isArray(payload)){let end=payload.length-1;return payload.map((v,i)=>derive(v,depth+1,i===end))}if(payload===null||typeof payload!=="object")return payload;let proto=Object.getPrototypeOf(payload);if(proto!==Object.prototype&&proto!==null)return typedView(payload,depth,last);let src=payload,out={};for(let[k,v]of Object.entries(src))out[k]=derive(v,depth+1,void 0);for(let[k,v]of Object.entries(src)){let name=hasAccessorName(k);if(Object.prototype.hasOwnProperty.call(src,name))continue;let derived=accessorValue(v);if(derived!==void 0)out[name]=derived}if(last!==void 0&&!Object.prototype.hasOwnProperty.call(src,LAST_ACCESSOR))out[LAST_ACCESSOR]=last;return out}function decapitalize(s){return s.length===0?s:s.charAt(0).toLowerCase()+s.slice(1)}function typedView(target,depth,last){let members=new Map,member=(key)=>{if(members.has(key))return members.get(key);let raw2=Reflect.get(target,key,target),value=typeof raw2==="function"?(...args)=>derive(Reflect.apply(raw2,target,args),depth+1,void 0):derive(raw2,depth+1,void 0);return members.set(key,value),value},derived=(key)=>{if(typeof key!=="string")return;if(key===LAST_ACCESSOR)return last;if(!key.startsWith("has"))return;let rest=key.slice(3);for(let field of[decapitalize(rest),rest]){if(!(field in target)||hasAccessorName(field)!==key)continue;let raw2=Reflect.get(target,field,target);if(typeof raw2==="function")continue;let value=accessorValue(raw2);if(value!==void 0)return value}return};return new Proxy(Object.create(null),{has:(_stand,key)=>(key in target)||derived(key)!==void 0,get:(_stand,key)=>(key in target)?member(key):derived(key)})}var TEMPLATE_ENGINES=["mustache","jinja"],TEMPLATE_ENGINE_MUSTACHE="mustache",TEMPLATE_ENGINE_JINJA="jinja";var JINJA_EXTENSIONS=[".jinja",".j2",".jinja2"];function partialEngineMismatch(provider,ref,including){let known=provider.engineOf?.(ref);return known!==void 0&&known!==including}function partialEngineMessage(ref,including){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${ref} is not a ${including} template; a ${including} body includes only ${including} partials`}function templateEngineOf(provider,ref,explicit){if(explicit!==void 0){if(!TEMPLATE_ENGINES.includes(explicit))throw Error(`unknown template engine ${JSON.stringify(explicit)}; expected one of ${TEMPLATE_ENGINES.join(", ")}`);return explicit}if(provider!==void 0&&ref!==void 0){let known=provider.engineOf?.(ref);if(known!==void 0)return known}return"mustache"}var ERR_VAR_NOT_ON_PAYLOAD="ERR_VAR_NOT_ON_PAYLOAD",ERR_PARTIAL_UNRESOLVED="ERR_PARTIAL_UNRESOLVED",ERR_REQUIRED_SLOT_UNUSED="ERR_REQUIRED_SLOT_UNUSED";var ERR_TEMPLATE_NOT_STATIC="ERR_TEMPLATE_NOT_STATIC",ERR_TEMPLATE_SYNTAX="ERR_TEMPLATE_SYNTAX",ERR_TEMPLATE_ENGINE_UNSUPPORTED="ERR_TEMPLATE_ENGINE_UNSUPPORTED",MAX_DEPTH=32,TAG_OPEN_DELIMS=new Set([">"," ","\t",` +`,"\r"]);function hasOpenTag(text,tag){let needle=`<${tag}`;for(let i=text.indexOf(needle);i!==-1;i=text.indexOf(needle,i+1)){let next=text[i+needle.length];if(next!==void 0&&TAG_OPEN_DELIMS.has(next))return!0}return!1}function hasCloseTag(text,tag){return text.includes(``)}function slotAndTagFindings(referencedAtRoot,staticTexts,opts){let errors=[];for(let slot of opts?.requiredSlots??[])if(!referencedAtRoot.has(slot))errors.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:slot});let requiredTags=opts?.requiredTags??[];if(requiredTags.length>0){let haystack=staticTexts.join(` +`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'
';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return``}function pct(x){return`${(Math.round(x*1e4)/100).toString()}%`}function legendHtml(withUnclaimed){return`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
${values.map(esc).join(" | ")}
`:"",column:esc(str(f.attrs[FIELD_ATTR_COLUMN])??""),flagsHtml:flags.map((x)=>`${esc(x)}`).join(""),claimsHtml:claims.map((c)=>`${statusGlyph(c.req.status)} ${esc(this.reqLabel(c.req))}`).join("
")}}keyRow(from,c){let fields=strs(c.attrs[IDENTITY_ATTR_FIELDS]),target=this.refHtml(from,c,IDENTITY_REFERENCE_ATTR_REFERENCES)||this.refHtml(from,c,RELATIONSHIP_ATTR_OBJECT_REF),through=str(c.attrs[RELATIONSHIP_ATTR_THROUGH]),card=str(c.attrs[RELATIONSHIP_ATTR_CARDINALITY]),shape=c.type===TYPE_RELATIONSHIP?[card,through!==void 0?`through ${localName(through)}`:void 0].filter((x)=>x!==void 0).join(", "):`(${fields.join(", ")})`;return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),inheritedHtml:c.inheritedFrom!==void 0?'inherited':"",shape:esc(shape),targetHtml:target!==""?`→ ${target}`:""}}reportingRow(from,c){let a=c.attrs,parts=[],agg=str(a[REPORTING_ATTR_AGG]),of=this.refHtml(from,c,REPORTING_ATTR_OF,localName);if(agg!==void 0)parts.push(`${esc(agg)}(${of})`);else if(of!=="")parts.push(`of ${of}`);let num=str(a[REPORTING_ATTR_NUMERATOR]),den=str(a[REPORTING_ATTR_DENOMINATOR]);if(num!==void 0&&den!==void 0)parts.push(`${esc(num)} ÷ ${esc(den)}`);let via=str(a[REPORTING_ATTR_VIA]);if(via!==void 0)parts.push(`via ${esc(localName(via))}`);let grains=strs(a[REPORTING_ATTR_GRAINS]);if(grains.length>0)parts.push(`grains ${grains.map((g)=>`${esc(g)}`).join(" ")}`);let seg=str(a[REPORTING_ATTR_SEGMENT]);if(seg!==void 0)parts.push(`segment ${esc(seg)}`);if(a[REPORTING_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[REPORTING_ATTR_FILTER]))}`);if(a[REPORTING_ATTR_DEFAULT]!==void 0)parts.push(`default ${esc(fmt(a[REPORTING_ATTR_DEFAULT]))}`);return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),definitionHtml:parts.join(" · ")}}layoutRow(l){let parts=[],cols=strs(l.attrs[LAYOUT_DATA_GRID_ATTR_COLUMNS]);if(cols.length>0)parts.push(`columns ${cols.map((c)=>`${esc(c)}`).join(", ")}`);let sort=str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD]);if(sort!==void 0)parts.push(`sorted by ${esc(sort)}${str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER])!==void 0?` ${esc(str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER]))}`:""}`);if(typeof l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]==="number")parts.push(`${l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]} per page`);return{kind:esc(`${l.type}.${l.subType}`),name:esc(l.name),detailHtml:parts.join(", ")}}projectionBlock(from,n){let ix=this.ix,rows=[],bases=new Set;for(let f of ix.fields(n.id)){if(f.extends!==void 0)bases.add(ix.ownerOf(f.extends));for(let o of ix.children(f.id).filter((c)=>c.type===TYPE_ORIGIN)){let def=this.originDefinition(from,o);for(let src of this.refLinks(o,ORIGIN_PASSTHROUGH_ATTR_FROM))bases.add(ix.ownerOf(src.id));rows.push({field:esc(f.name),origin:esc(`origin.${o.subType}`),definitionHtml:def})}}return{basesHtml:[...bases].filter((b)=>b!==n.id).sort(byCodeUnit2).map((b)=>this.link(from,b)).join(", "),origins:rows,hasOrigins:rows.length>0}}originDefinition(from,o){let a=o.attrs,ref=(name)=>this.attrValues(o,name).map((v)=>v.link!==null&&!v.link.unresolved?this.link(from,v.link.id,localName(v.text)):`${esc(localName(v.text))}`).join(", "),parts=[],agg=str(a[ORIGIN_AGGREGATE_ATTR_AGG]);if(agg!==void 0)parts.push(`${esc(agg)}(${ref(ORIGIN_AGGREGATE_ATTR_OF)})`);else if(a[ORIGIN_AGGREGATE_ATTR_OF]!==void 0)parts.push(`of ${ref(ORIGIN_AGGREGATE_ATTR_OF)}`);if(a[ORIGIN_PASSTHROUGH_ATTR_FROM]!==void 0)parts.push(`from ${ref(ORIGIN_PASSTHROUGH_ATTR_FROM)}`);if(a[ORIGIN_AGGREGATE_ATTR_VIA]!==void 0)parts.push(`via ${esc(localName(String(a[ORIGIN_AGGREGATE_ATTR_VIA])))}`);if(a[ORIGIN_COMPUTED_ATTR_EXPR]!==void 0)parts.push(`${esc(fmt(a[ORIGIN_COMPUTED_ATTR_EXPR]))}`);if(a[ORIGIN_AGGREGATE_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[ORIGIN_AGGREGATE_ATTR_FILTER]))}`);return parts.join(" · ")}reportBlock(from,n){let a=n.attrs,fromId=this.refLinks(n,OBJECT_REPORT_ATTR_FROM)[0]?.id??str(a[OBJECT_REPORT_ATTR_FROM]),resolve2=(name,kindType)=>{let hit=[fromId!==void 0?`${fromId}.${name}`:void 0,`${n.package===""?"":`${n.package}::`}${name}`].filter((x)=>x!==void 0).find((c)=>this.ix.byId.get(c)?.type===kindType||this.ix.byId.has(c)&&name.includes("."));return hit!==void 0?this.link(from,hit,name):`${esc(name)}`},spine=str(a[OBJECT_REPORT_ATTR_SPINE]);return{fromHtml:this.refHtml(from,n,OBJECT_REPORT_ATTR_FROM),spineHtml:spine!==void 0?`${esc(spine)}`:"",dimensionsHtml:strs(a[OBJECT_REPORT_ATTR_DIMENSIONS]).map((d)=>resolve2(d,TYPE_DIMENSION)).join(", "),measuresHtml:strs(a[OBJECT_REPORT_ATTR_MEASURES]).map((m)=>resolve2(m,TYPE_MEASURE)).join(", "),segmentHtml:strs(a[OBJECT_REPORT_ATTR_SEGMENT]).map((s)=>resolve2(s,TYPE_SEGMENT)).join(", "),filterHtml:a[OBJECT_REPORT_ATTR_FILTER]!==void 0?`${esc(fmt(a[OBJECT_REPORT_ATTR_FILTER]))}`:""}}generatedGroups(id){let groups=new Map;for(let f of this.ix.generated(id))groups.set(f.generatedBy,[...groups.get(f.generatedBy)??[],f.path]);return[...groups.keys()].sort(byCodeUnit2).map((g)=>({generator:esc(g),files:(groups.get(g)??[]).map((p)=>esc(p))}))}node(n){let ix=this.ix,from=this.objectPage(n),kindLabel=`${n.type}.${n.subType}`,whyRows=this.whyRows(from,n),attrs=this.attrRows(from,n),referrers=[...(ix.top(n.id)?.referencedBy??[]).map((e)=>e.from.id),...ix.claims(n.id).map((c)=>this.topOf(c.req).node.id)],refBy=[...new Set(referrers.filter((id)=>id!==n.id))].sort(byCodeUnit2).map((id)=>this.link(from,id));return{id:esc(n.id),name:esc(n.name),kindLabel:esc(kindLabel),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › ${esc(kindLabel)}`,isAbstract:n.abstract===!0,description:this.description(n),extendsHtml:n.extends!==void 0?this.link(from,n.extends):"",attrs,hasAttrs:attrs.length>0,members:ix.children(n.id).map((c)=>({anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),nameHtml:ix.reqById.has(c.id)?this.link(from,c.id):esc(c.name===""?`#${c.order}`:c.name),attrsHtml:this.attrRows(from,c).map((a)=>`@${a.name} ${a.valueHtml}`).join("
"),below:ix.children(c.id).length})),hasMembers:ix.children(n.id).length>0,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(from,n){return n.view.attrs.map((a)=>{let links=a.values.filter((v)=>v.link!==null&&!v.link.unresolved);return{name:esc(a.name),valueHtml:links.length>0&&links.length===a.values.length?links.map((v)=>this.link(from,v.link.id)).join(", "):`${esc(fmt(a.value))}`}})}prompt(n,text){let ix=this.ix,from=this.objectPage(n),payloadId=this.refLinks(n,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id,replyId=this.refLinks(n,TEMPLATE_ATTR_RESPONSE_REF)[0]?.id,vars=text!==void 0?templateVariables(text):void 0,payload=payloadId!==void 0?ix.byId.get(payloadId):void 0,reply=replyId!==void 0?ix.byId.get(replyId):void 0,payloadRows=payload!==void 0?ix.fields(payload.id).map((f)=>({name:esc(f.name),requiredHtml:f.attrs[FIELD_ATTR_REQUIRED]===!0?'required':"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)!==""?` → ${this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)}`:"",usedHtml:vars===void 0?'text not read':vars.has(f.name)?"yes":'no'})):[],replyRows=reply!==void 0?ix.fields(reply.id).map((f)=>({name:esc(f.name),type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),valuesHtml:f.subType===FIELD_SUBTYPE_ENUM?`
${strs(f.attrs[FIELD_ATTR_VALUES]).map(esc).join(" | ")}
`:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(` +`).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
    ${tops.map((r)=>this.treeNode(page,r)).join("")}
`:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
  • ${`
    ${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}${dispositionPill(r)}${verdictBadge(r)}${bar}${links.join("")}
    ${esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??"")}
    `}${r.children.length>0?`
      ${r.children.map((c)=>this.treeNode(from,c)).join("")}
    `:""}
  • `}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join("
    "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join("
    "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`${cols.map((o)=>`
    ${this.link(from,o.id)}
    `).join("")}`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLink(from,top)}${cols.map(()=>'').join("")}`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`${levelBadge(r)}${esc(label)}${cols.map((o)=>tg.has(o.id)?`${statusGlyph(r.status)}`:'').join("")}`)}}return{tableHtml:rows.length>0?`${head}${rows.join("")}
    `:"",hasRows:rows.length>0,hasRequirements:ix.hasRequirements()}}trace(){let starts=this.ix.requirements.filter((r)=>r.level!==void 0&&r.level<=REQUIREMENT_LEVEL_SERVICE),fallback=starts.length===0?this.ix.topRequirements:[];return{options:[...starts,...fallback].map((r)=>({value:esc(r.node.id),label:esc(`${" ".repeat(Math.max(0,(r.level??1)-1))}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)}`)})),hasStarts:starts.length+fallback.length>0,hasUsage:!1}}gaps(){let ix=this.ix,from=PAGE_GAPS,cards=[],card=(title,count,source,why,bodyHtml)=>{cards.push({title:esc(title),count:esc(String(count)),source:esc(source),isGate:source==="meta verify",whyHtml:why,bodyHtml})};if(ix.view.sources.requirements){let findingsOf=(gate2)=>[...ix.requirements.flatMap((req)=>req.req.diagnostics.filter((d)=>d.source===GATE_SOURCE===gate2).map((d)=>({req,d}))),...ix.view.advisories.filter((d)=>d.path===""&&d.source===GATE_SOURCE===gate2).map((d)=>({d}))],table=(rows,chip)=>rows.length===0?'
    None.
    ':`${rows.map(({req,d})=>``).join("")}
    ${esc(d.code)}${req!==void 0?this.reqLink(from,req):""}
    ${esc(d.message)}
    `,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
    None.
    ');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
    None.
    ')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
    Not scanned.
    ');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
    No prompt text was read.
    ':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
    None.
    ':`
      ${items.map((i)=>`
    • ${i}
    • `).join("")}
    `}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found

    No such page

    ${escapeHtml2(r.path)} is not a page of this model.

    Overview

    `,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="

    No model yet

    The explorer is waiting for the running application's docs view.

    ";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="

    No model

    The source parameter is not a URL.

    ",paintLive();return}follow(source);return}if(!build())document.body.innerHTML="

    No model

    explorer-model.js did not load. Run meta gen to write it beside this page.

    ";else show(!1);setTimeout(poll,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()}function escapeHtml2(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}})(); diff --git a/server/rust/metaobjects-codegen/explorer-app/assets/explorer.css b/server/rust/metaobjects-codegen/explorer-app/assets/explorer.css new file mode 100644 index 0000000000..2be025a594 --- /dev/null +++ b/server/rust/metaobjects-codegen/explorer-app/assets/explorer.css @@ -0,0 +1,238 @@ +/* The model explorer's theme. `meta eject docs-site` copies this file to + codegen/docs-site/assets/, where an edit wins over the bundled copy. + + Colour rules (design report §4.2), which the classes below keep apart: + .s- a DECLARED status: filled chip, with its glyph in the text + .v- a GATE verdict: an outline (ring), never a fill + .bar .b-* a ROLL-UP of what sits below: a separate stacked bar + No class here colours a test result. */ + +:root { + --bg: #f7f7f5; --panel: #ffffff; --ink: #1d1f23; --muted: #5f6670; --line: #e2e3e0; + --accent: #3b5bdb; --accent-soft: #e8ecfd; --accent-ink: #ffffff; + --live: #2f9e44; --live-soft: #e3f5e7; --partial: #e8890c; --partial-soft: #fdf0dc; + --planned: #4c6ef5; --planned-soft: #e9edff; --retired: #868e96; --retired-soft: #eef0f2; + --bad: #e03131; --bad-soft: #fde8e8; --warn: #e8890c; --code: #f1f2ef; + --entity: #495057; --value: #7048e8; --prompt: #0c8599; --projection: #1971c2; --report: #c2255c; + --shadow: 0 1px 2px rgba(16, 24, 40, .04), 0 1px 3px rgba(16, 24, 40, .06); + --shadow-lift: 0 4px 14px rgba(16, 24, 40, .10); + color-scheme: light; +} +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --bg: #15171a; --panel: #1d2024; --ink: #e7e9ec; --muted: #9aa2ab; --line: #2e3238; + --accent: #8da2fb; --accent-soft: #252c47; --accent-ink: #15171a; + --live: #51cf66; --live-soft: #1e3324; --partial: #ffa94d; --partial-soft: #3a2c17; + --planned: #91a7ff; --planned-soft: #232a45; --retired: #adb5bd; --retired-soft: #2a2d31; + --bad: #ff6b6b; --bad-soft: #3a1f1f; --warn: #ffa94d; --code: #24272c; + --entity: #ced4da; --value: #b197fc; --prompt: #3bc9db; --projection: #74c0fc; --report: #f783ac; + --shadow: 0 1px 2px rgba(0, 0, 0, .3); --shadow-lift: 0 4px 14px rgba(0, 0, 0, .45); + color-scheme: dark; + } +} +:root[data-theme="dark"] { + --bg: #15171a; --panel: #1d2024; --ink: #e7e9ec; --muted: #9aa2ab; --line: #2e3238; + --accent: #8da2fb; --accent-soft: #252c47; --accent-ink: #15171a; + --live: #51cf66; --live-soft: #1e3324; --partial: #ffa94d; --partial-soft: #3a2c17; + --planned: #91a7ff; --planned-soft: #232a45; --retired: #adb5bd; --retired-soft: #2a2d31; + --bad: #ff6b6b; --bad-soft: #3a1f1f; --warn: #ffa94d; --code: #24272c; + --entity: #ced4da; --value: #b197fc; --prompt: #3bc9db; --projection: #74c0fc; --report: #f783ac; + --shadow: 0 1px 2px rgba(0, 0, 0, .3); --shadow-lift: 0 4px 14px rgba(0, 0, 0, .45); + color-scheme: dark; +} + +* { box-sizing: border-box; } +html { -webkit-text-size-adjust: 100%; } +body { margin: 0; background: var(--bg); color: var(--ink); font: 14px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; } +a { color: var(--accent); text-decoration: none; } +a:hover { text-decoration: underline; } +code, .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12.5px; } +code { background: var(--code); border-radius: 4px; padding: 0 4px; } +code.digest { display: block; overflow-wrap: anywhere; font-size: 11.5px; padding: 4px 6px; } +pre code, .mono code { background: none; padding: 0; } + +/* ── Header ─────────────────────────────────────────────────────────────── */ +header.top { position: sticky; top: 0; z-index: 10; background: var(--panel); border-bottom: 1px solid var(--line); display: flex; gap: 16px; align-items: center; padding: 10px 20px; flex-wrap: wrap; } +.brand { font-weight: 700; letter-spacing: .2px; color: var(--ink); white-space: nowrap; } +.brand:hover { text-decoration: none; } +.brand small { font-weight: 400; color: var(--muted); margin-left: 6px; } +.nav { display: flex; gap: 4px; flex-wrap: wrap; } +.nav a { padding: 5px 10px; border-radius: 6px; color: var(--ink); white-space: nowrap; } +.nav a:hover { background: var(--code); text-decoration: none; } +.nav a.on { background: var(--accent-soft); color: var(--accent); font-weight: 600; } +#search { margin-left: auto; position: relative; } +#search input { width: 260px; max-width: 60vw; padding: 6px 10px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--ink); font: inherit; } +#search input:focus { outline: 2px solid var(--accent-soft); border-color: var(--accent); } +#results { position: absolute; right: 0; top: 36px; width: 420px; max-width: 90vw; max-height: 60vh; overflow: auto; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; box-shadow: var(--shadow-lift); display: none; } +#results a { display: block; padding: 7px 12px; border-bottom: 1px solid var(--line); color: var(--ink); } +#results a:hover, #results a.sel { background: var(--accent-soft); text-decoration: none; } +#results a small { color: var(--muted); display: block; } +#results .none { padding: 8px 12px; color: var(--muted); } +#theme { padding: 5px 9px; } + +/* ── Page ───────────────────────────────────────────────────────────────── */ +main { padding: 24px 20px 20px; max-width: 1400px; margin: 0 auto; } +h1 { font-size: 22px; margin: 0 0 4px; line-height: 1.3; display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } +h2 { font-size: 16px; margin: 26px 0 10px; } +h3 { font-size: 14px; margin: 16px 0 6px; } +h3.first { margin-top: 0; } +.h-sub { color: var(--muted); font-weight: 400; } +.sub { color: var(--muted); } +.small { font-size: 12px; } +.crumbs { color: var(--muted); font-size: 12.5px; margin-bottom: 6px; } +.meta-line { margin-top: 4px; } +.page { margin-top: 14px; } +.card { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 14px 16px; box-shadow: var(--shadow); min-width: 0; } +.grid { display: grid; gap: 12px; } +.tiles { grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); margin: 18px 0; } +a.tile { color: var(--ink); transition: box-shadow .15s, border-color .15s, transform .15s; } +a.tile:hover { text-decoration: none; border-color: var(--accent); box-shadow: var(--shadow-lift); transform: translateY(-1px); } +.tile .n { font-size: 26px; font-weight: 700; letter-spacing: -.3px; font-variant-numeric: tabular-nums; } +.tile .l { color: var(--muted); font-size: 12.5px; line-height: 1.4; } +.two { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } +.side { grid-template-columns: minmax(0, 1fr) 340px; align-items: start; } +.apis { grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); } +@media (max-width: 1000px) { .side { grid-template-columns: minmax(0, 1fr); } } +@media (max-width: 900px) { .two { grid-template-columns: minmax(0, 1fr); } } + +table { border-collapse: collapse; width: 100%; } +th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; } +th { font-size: 12px; color: var(--muted); font-weight: 600; } +tr:target td { background: var(--accent-soft); } +table.kv th { width: 120px; } +.tablewrap { overflow-x: auto; } + +/* ── Status, verdict and roll-up ────────────────────────────────────────── */ +.chip { display: inline-flex; align-items: center; gap: 4px; padding: 1px 8px; border-radius: 999px; font-size: 12px; border: 1px solid var(--line); white-space: nowrap; margin: 1px 2px 1px 0; font-weight: 500; line-height: 1.6; } +h1 .chip { font-size: 12.5px; } +.s-live { background: var(--live-soft); color: var(--live); border-color: transparent; } +.s-partial { background: var(--partial-soft); color: var(--partial); border-color: transparent; } +.s-planned { background: var(--planned-soft); color: var(--planned); border-color: transparent; } +.s-retired { background: var(--retired-soft); color: var(--retired); border-color: transparent; text-decoration: line-through; } +.v-error, .v-unclaimed { background: transparent; color: var(--bad); border: 1.5px solid var(--bad); } +.v-warn { background: transparent; color: var(--warn); border: 1.5px solid var(--warn); } +.glyph { font-size: 12px; } +.g-live { color: var(--live); } .g-partial { color: var(--partial); } .g-planned { color: var(--planned); } .g-retired { color: var(--retired); } +.lvl { display: inline-block; min-width: 24px; text-align: center; font-size: 11px; font-weight: 700; border-radius: 4px; background: var(--code); color: var(--muted); padding: 0 4px; margin-right: 6px; line-height: 18px; } +h1 .lvl { font-size: 12px; line-height: 22px; } +.bar { display: flex; height: 8px; border-radius: 4px; overflow: hidden; background: var(--code); min-width: 80px; } +.bar span { display: block; height: 100%; } +.b-live { background: var(--live); } .b-partial { background: var(--partial); } .b-planned { background: var(--planned); } .b-retired { background: var(--retired); } +.minibar { display: inline-block; width: 90px; vertical-align: middle; margin: 0 4px; } +.legend { display: flex; gap: 8px; flex-wrap: wrap; font-size: 12px; color: var(--muted); align-items: center; margin: 4px 0; } +.legend-row { margin: 10px 0; } +.pill { font-size: 11px; color: var(--muted); border: 1px solid var(--line); border-radius: 4px; padding: 0 5px; margin-left: 4px; white-space: nowrap; } +.pill.gate { color: var(--accent); border-color: var(--accent); } +a.k-entity { color: var(--accent); font-weight: 500; } +span.k-entity { color: var(--entity); } .k-value { color: var(--value); } .k-prompt, .k-template { color: var(--prompt); } +.k-projection { color: var(--projection); } .k-report { color: var(--report); } +.kdot { font-size: 10px; } +.kdot.k-entity { color: var(--entity); } .kdot.k-value { color: var(--value); } .kdot.k-prompt { color: var(--prompt); } +.k-badge { color: var(--projection); } +.vals { color: var(--muted); font-size: 11.5px; } + +/* ── S1 cards ───────────────────────────────────────────────────────────── */ +.cap { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 12px; } +.cap .card h3 { margin-top: 0; display: flex; gap: 6px; align-items: center; flex-wrap: wrap; } +.capcard .statement { margin: 2px 0 0; } +.rollup { margin: 10px 0 4px; } +.rollup .sub { margin-top: 3px; } +ul { padding-left: 18px; margin: 6px 0; } +.cap li, .kids li { margin: 4px 0; } +.members { margin-top: 8px; line-height: 1.9; } +details.summary { margin-top: 6px; } +details > summary { cursor: pointer; color: var(--muted); font-size: 12px; } +.note { border-left: 3px solid var(--accent); background: var(--accent-soft); padding: 8px 12px; border-radius: 6px; font-size: 13px; margin: 8px 0; } +.note.intro { margin: 4px 0 8px; font-size: 13.5px; } + +/* ── S5 tree ────────────────────────────────────────────────────────────── */ +.tabs { display: flex; gap: 6px; margin: 12px 0; flex-wrap: wrap; } +.tabs a { padding: 5px 12px; border: 1px solid var(--line); border-radius: 6px; color: var(--ink); background: var(--panel); } +.tabs a.on { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); } +.tree { margin-top: 10px; } +.tree ul { list-style: none; padding-left: 18px; border-left: 1px dashed var(--line); margin-left: 8px; } +.tree > ul { border-left: none; padding-left: 0; margin-left: 0; } +.tree li { margin: 4px 0; } +.tree .row { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; } +.tree .stmt { color: var(--muted); font-size: 12.5px; flex-basis: 100%; margin-left: 30px; } + +/* ── Graphs ─────────────────────────────────────────────────────────────── */ +.graph { width: 100%; background: var(--panel); border: 1px solid var(--line); border-radius: 10px; } +#cy, #g3d { height: 640px; } #cymini { height: 260px; } #cytrace { height: 680px; } +#g3d { overflow: hidden; position: relative; } .graph[hidden] { display: none; } +.panel h3 { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; } +.maplegend { margin-top: 8px; } +.toolbar { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; margin: 10px 0; } +select, button { padding: 5px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--panel); color: var(--ink); font: inherit; max-width: 100%; } +button { cursor: pointer; } +button:hover { border-color: var(--accent); } +.layout, .gen, .route { margin: 4px 0; } +.gen .pill { margin-left: 0; } + +/* ── S4 text ────────────────────────────────────────────────────────────── */ +pre { background: var(--code); padding: 10px 12px; border-radius: 8px; overflow: auto; font-size: 12px; white-space: pre-wrap; word-break: break-word; } +pre.text { max-height: 560px; } +.var { color: var(--prompt); } + +/* ── S6 proof ───────────────────────────────────────────────────────────── */ +.proof { font-size: 12.5px; } +.proof td:first-child { white-space: nowrap; font-weight: 500; } + +/* ── S7 matrix ──────────────────────────────────────────────────────────── */ +.mx { overflow: auto; max-height: 78vh; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); } +.mx table { width: auto; border-collapse: separate; border-spacing: 0; } +/* The header row is sticky as a whole: a sticky cell per column would paint over the slanted + label of the column before it. */ +.mx thead { position: sticky; top: 0; z-index: 2; background: var(--panel); } +.mx th.col { height: 150px; white-space: nowrap; vertical-align: bottom; padding: 0; } +.mx th.col.corner { position: sticky; left: 0; background: var(--panel); } +.mx th.col div { transform: rotate(-60deg); transform-origin: left bottom; width: 18px; margin-left: 12px; font-weight: 500; font-size: 11.5px; max-width: 18px; } +.mx th.col div a { display: inline-block; max-width: 150px; overflow: hidden; text-overflow: ellipsis; vertical-align: bottom; } +.mx th.col.unc div a { color: var(--bad); } +.mx td.c { width: 20px; min-width: 20px; height: 22px; padding: 0; text-align: center; font-size: 11px; border-right: 1px solid var(--line); } +.mx td.rh { position: sticky; left: 0; background: var(--panel); z-index: 1; border-right: 1px solid var(--line); white-space: nowrap; max-width: 360px; overflow: hidden; text-overflow: ellipsis; font-size: 12px; } +.mx tr.grp td { background: var(--code); font-weight: 600; } +.mx td.c.live { background: var(--live-soft); } .mx td.c.planned { background: var(--planned-soft); } +.mx td.c.partial { background: var(--partial-soft); } .mx td.c.retired { background: var(--retired-soft); } + +/* ── S9 gaps, API ───────────────────────────────────────────────────────── */ +.gap h3 { display: flex; gap: 8px; align-items: center; margin-top: 0; flex-wrap: wrap; } +.gap .why { margin-bottom: 8px; } +.count { font-weight: 700; font-size: 12px; border-radius: 999px; padding: 0 8px; background: var(--code); } +.method { display: inline-block; min-width: 52px; text-align: center; font: 600 11px ui-monospace, SFMono-Regular, Menlo, monospace; border-radius: 4px; padding: 1px 4px; background: var(--code); color: var(--muted); } +.m-GET, .m-get { background: var(--live-soft); color: var(--live); } +.m-POST, .m-post { background: var(--planned-soft); color: var(--planned); } +.m-PUT, .m-put, .m-PATCH, .m-patch { background: var(--partial-soft); color: var(--partial); } +.m-DELETE, .m-delete { background: var(--bad-soft); color: var(--bad); } + +footer { color: var(--muted); font-size: 12px; padding: 24px 20px; text-align: center; } + +/* ── Phone ──────────────────────────────────────────────────────────────── */ +@media (max-width: 700px) { + header.top { gap: 8px 12px; padding: 10px 16px; } + .nav { order: 3; flex-basis: 100%; flex-wrap: nowrap; overflow-x: auto; margin: 0 -16px; padding: 0 16px 2px; scrollbar-width: none; } + .nav::-webkit-scrollbar { display: none; } + #search { order: 4; margin-left: 0; flex-basis: 100%; } + #search input { width: 100%; max-width: none; } + #results { left: 0; right: 0; width: auto; max-width: none; } + #theme { margin-left: auto; } + main { padding: 16px; } + h1 { font-size: 20px; } + .tiles { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; } + .tile .n { font-size: 22px; } + .cap { grid-template-columns: minmax(0, 1fr); } + .apis { grid-template-columns: minmax(0, 1fr); } + #cy, #g3d { height: 440px; } #cytrace { height: 520px; } + .mx { max-height: none; } + /* A wide table scrolls inside its own box, never the page. */ + main table { display: block; max-width: 100%; overflow-x: auto; } + .mx table { display: table; max-width: none; } + .tree .stmt { margin-left: 0; } + .tree ul { padding-left: 12px; margin-left: 4px; } +} +@media print { header.top, #search, #theme, .toolbar { display: none; } .card { box-shadow: none; } } + +/* ── The app following a running application (`index.html?source=`) ── */ +.live-source { position: fixed; right: 12px; bottom: 12px; z-index: 20; max-width: min(520px, calc(100vw - 24px)); background: var(--panel); border: 1px solid var(--line); border-radius: 8px; box-shadow: var(--shadow-lift); padding: 6px 10px; font-size: 12px; color: var(--muted); overflow-wrap: anywhere; } +.live-source b { color: var(--live); font-weight: 600; } +.live-source.down b { color: var(--bad); } diff --git a/server/rust/metaobjects-codegen/explorer-app/assets/explorer.js b/server/rust/metaobjects-codegen/explorer-app/assets/explorer.js new file mode 100644 index 0000000000..6cc6dff139 --- /dev/null +++ b/server/rust/metaobjects-codegen/explorer-app/assets/explorer.js @@ -0,0 +1,422 @@ +// The model explorer's scripts: search, the theme toggle, and the three graphs (the model map, +// an object page's one-hop mini-map, the trace). They read window.MO_EXPLORER, which the +// explorer app computes from the docs view (or, on a static export, assets/explorer-data.js +// sets); nothing here derives a model fact. +// `meta eject docs-site` copies this file to codegen/docs-site/assets/. +// +// On a static page this runs once, as it loads. In the explorer app (window.MO_APP is set) it +// runs again for every page the app draws, and the app supplies four things a page would +// otherwise take from its own URL: link targets, the query string, writing the query string +// back, and document listeners the app drops when the reader leaves the page. +(function () { + "use strict"; + function run() { + var APP = window.MO_APP || null; + var D = window.MO_EXPLORER || { nodes: [], edges: [], slices: {}, features: [], reqs: [], generated: {}, search: [] }; + var ROOT = document.body.getAttribute("data-root") || ""; + var query = function () { return APP ? APP.search() : location.search; }; + var setQuery = function (search) { if (APP) APP.replaceQuery(search); else history.replaceState(null, "", search ? location.pathname + search : location.pathname); }; + var listen = function (type, f) { if (APP) APP.listen(type, f); else document.addEventListener(type, f); }; + // A graph the app draws is destroyed when the reader leaves its page. + var graph = function (opts) { var c = cytoscape(opts); if (APP) APP.onLeave(function () { if (!c.destroyed()) c.destroy(); }); return c; }; + var $ = function (s, r) { return (r || document).querySelector(s); }; + var esc = function (s) { return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) { return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]; }); }; + var css = function (v) { return getComputedStyle(document.documentElement).getPropertyValue(v).trim(); }; + var STATUS = ["live", "partial", "planned", "retired"]; + var GLYPH = { live: "●", partial: "◐", planned: "○", retired: "⊘" }; + var PAL = ["#1971c2", "#e8590c", "#2b8a3e", "#ae3ec9", "#c2255c", "#0b7285", "#5c940d", "#f08c00"]; + var byId = {}; + D.nodes.forEach(function (n) { byId[n.id] = n; }); + var reqById = {}; + D.reqs.forEach(function (r) { reqById[r.id] = r; }); + var href = function (rel) { return APP ? APP.href(rel) : ROOT + rel; }; + var redraw = []; + + // ── Theme ─────────────────────────────────────────────────────────────── + var themeBtn = $("#theme"); + if (themeBtn) themeBtn.onclick = function () { + var cur = document.documentElement.getAttribute("data-theme"); + var dark = cur ? cur === "dark" : matchMedia("(prefers-color-scheme: dark)").matches; + var next = dark ? "light" : "dark"; + document.documentElement.setAttribute("data-theme", next); + try { localStorage.setItem("mo-theme", next); } catch (e) { /* private window: the toggle still works for this page */ } + redraw.forEach(function (f) { f(); }); + }; + + // ── Search ────────────────────────────────────────────────────────────── + // The built-in index ships in explorer-data.js and works from file://. When the site has been + // indexed with Pagefind (`npx pagefind --site `) and is served over http, Pagefind's + // full-text index answers instead. + var q = $("#q"), res = $("#results"), pagefind = null, pagefindTried = false, sel = -1; + function loadPagefind() { + // The app draws its own pages; a Pagefind index (of a static export) would link out of it. + if (APP || pagefindTried || !/^https?:$/.test(location.protocol)) return Promise.resolve(null); + pagefindTried = true; + // Pagefind takes its base URL from where pagefind.js loads, so loading it from ROOT makes every + // result URL carry the path the site is served under (a sub-path included). + var url = new URL(ROOT + "pagefind/pagefind.js", location.href).href; + return fetch(url, { method: "HEAD" }).then(function (r) { + if (!r.ok) return null; + return import(url).then(function (m) { pagefind = m; return m; }); + }).catch(function () { return null; }); + } + function show(items) { + sel = -1; + res.innerHTML = items.length ? items.map(function (x) { return '' + esc(x.t) + "" + esc(x.s) + ""; }).join("") : '
    No match
    '; + res.style.display = "block"; + } + function builtIn(v) { + var words = v.split(/\s+/).filter(Boolean); + return D.search.filter(function (x) { return words.every(function (w) { return x.k.indexOf(w) >= 0; }); }) + .sort(function (a, b) { return (a.t.toLowerCase().indexOf(words[0]) === 0 ? 0 : 1) - (b.t.toLowerCase().indexOf(words[0]) === 0 ? 0 : 1); }) + .slice(0, 25).map(function (x) { return { t: x.t, s: x.s, h: href(x.h) }; }); + } + if (q && res) { + q.addEventListener("input", function () { + var v = q.value.trim().toLowerCase(); + if (!v) { res.style.display = "none"; return; } + show(builtIn(v)); + loadPagefind().then(function (pf) { + if (!pf || q.value.trim().toLowerCase() !== v) return; + pf.search(v).then(function (r) { + return Promise.all(r.results.slice(0, 12).map(function (x) { return x.data(); })); + }).then(function (rows) { + if (q.value.trim().toLowerCase() !== v || !rows.length) return; + show(rows.map(function (d) { return { t: (d.meta && d.meta.title) || d.url, s: (d.excerpt || "").replace(/<[^>]+>/g, ""), h: d.url }; })); + }).catch(function () { /* keep the built-in results */ }); + }); + }); + q.addEventListener("keydown", function (e) { + var links = res.querySelectorAll("a"); + if (e.key === "ArrowDown" || e.key === "ArrowUp") { + e.preventDefault(); + sel = Math.max(0, Math.min(links.length - 1, sel + (e.key === "ArrowDown" ? 1 : -1))); + links.forEach(function (a, i) { a.classList.toggle("sel", i === sel); }); + } else if (e.key === "Enter" && links.length) { + location.href = links[Math.max(0, sel)].href; + } else if (e.key === "Escape") { res.style.display = "none"; q.blur(); } + }); + listen("click", function (e) { if (!$("#search").contains(e.target)) res.style.display = "none"; }); + listen("keydown", function (e) { + if (e.key === "/" && document.activeElement !== q && !/^(INPUT|SELECT|TEXTAREA)$/.test(document.activeElement.tagName)) { e.preventDefault(); q.focus(); } + }); + } + + if (typeof window.cytoscape !== "function") { + document.querySelectorAll(".graph").forEach(function (g) { + g.innerHTML = '
    The graph library did not load. Every node still has its own page.
    '; + }); + return; + } + + // ── Colours ───────────────────────────────────────────────────────────── + // Fill: the kind, the feature, or the DECLARED status of the claims on a node. + // Ring: a gate verdict (unclaimed). Never a test result. + function kindColour(n) { + return css({ entity: "--entity", value: "--value", prompt: "--prompt", template: "--prompt", projection: "--projection", report: "--report" }[n.kind] || "--entity"); + } + function fill(n, mode) { + if (n.abstract) return css("--retired"); + if (mode === "kind") return kindColour(n); + if (mode === "api") return n.api.length ? css("--accent") : css("--retired-soft"); + if (mode === "claims") return n.claims > 8 ? css("--live") : n.claims > 2 ? css("--partial") : n.claims > 0 ? css("--planned") : css("--retired-soft"); + if (mode === "cap") return n.feature >= 0 ? PAL[n.feature % PAL.length] : n.quality ? css("--retired") : css("--retired-soft"); + return n.status === "unclaimed" ? css("--retired-soft") : css("--" + n.status); + } + function legend(mode) { + var ring = D.hasClaims ? 'red ring: unclaimed (gate)' : ""; + if (mode === "cap") return '
    ' + D.features.map(function (f, i) { return '● ' + esc(f.label) + ""; }).join("") + '● qualities only○ no claim' + ring + "Fill is the feature (L1) with the most claims on the node; size is fields plus claims.
    "; + if (mode === "status") return '
    ' + STATUS.map(function (s) { return '' + GLYPH[s] + " " + s + ""; }).join("") + '○ no claim' + ring + "Fill is the best declared status among the requirements that claim the node.
    "; + if (mode === "api") return '
    ● mounted routes○ none
    '; + if (mode === "claims") return '
    ● more than 8 claims● 3 to 8● 1 or 2○ none' + ring + "
    "; + return '
    ' + ["entity", "value", "projection", "report", "prompt"].map(function (k) { return '● ' + k + ""; }).join("") + "Abstract bases are dashed and grey.
    "; + } + function shape(n) { return n.kind === "prompt" || n.kind === "template" ? "diamond" : n.kind === "value" ? "round-triangle" : n.kind === "projection" || n.kind === "report" ? "round-hexagon" : n.abstract ? "round-rectangle" : "ellipse"; } + function baseStyle() { + return [ + { selector: "node", style: { "background-color": "data(col)", label: "data(label)", width: "data(size)", height: "data(size)", shape: "data(shape)", color: css("--ink"), "font-size": 10, "text-valign": "bottom", "text-margin-y": 3, "border-width": 1, "border-color": css("--line"), "text-wrap": "none" } }, + { selector: "node[dashed = 1]", style: { "border-style": "dashed", "border-width": 2, "background-opacity": 0.4 } }, + { selector: "node[ring = 1]", style: { "border-width": 3, "border-color": css("--bad") } }, + { selector: "node[faded = 1]", style: { opacity: 0.18 } }, + { selector: "edge", style: { width: 1.2, "line-color": css("--muted"), "target-arrow-color": css("--muted"), "target-arrow-shape": "triangle", "curve-style": "bezier", "arrow-scale": 0.7, opacity: 0.6 } }, + { selector: "edge[ext = 1]", style: { "line-style": "dashed", "target-arrow-shape": "triangle-tee" } }, + { selector: "edge[faded = 1]", style: { opacity: 0.08 } }, + { selector: ":selected", style: { "border-width": 3, "border-color": css("--accent") } }, + ]; + } + var bar = function (c) { + var t = STATUS.reduce(function (a, s) { return a + (c[s] || 0); }, 0); + if (!t) return '
    '; + return '
    ' + STATUS.filter(function (s) { return c[s]; }).map(function (s) { return ''; }).join("") + "
    "; + }; + var chip = function (s) { return s ? '' + (GLYPH[s] || "") + " " + esc(s) + "" : ""; }; + var nodeLink = function (id) { var n = byId[id]; return n ? '' + esc(n.name) + "" : esc(id); }; + + // ── S2: the model map ─────────────────────────────────────────────────── + // cose from a grid (not from one point) gives the same picture on every load. + var COSE = { name: "cose", animate: false, randomize: false, nodeRepulsion: 12000, nodeOverlap: 24, idealEdgeLength: 90, componentSpacing: 90, gravity: 0.6, padding: 24, nodeDimensionsIncludeLabels: true }; + function seedGrid(els) { + var nodes = els.filter(function (e) { return !e.data.source; }), cols = Math.ceil(Math.sqrt(nodes.length || 1)); + nodes.forEach(function (e, i) { e.position = { x: (i % cols) * 120, y: Math.floor(i / cols) * 100 }; }); + } + var cyEl = $("#cy"); + if (cyEl) { + var cy = null; + var params = new URLSearchParams(query()); + var sliceSel = $("#slice"), colourSel = $("#colour"); + if (params.get("slice") && sliceSel.querySelector('option[value="' + CSS.escape(params.get("slice")) + '"]')) sliceSel.value = params.get("slice"); + if (params.get("colour") && colourSel.querySelector('option[value="' + CSS.escape(params.get("colour")) + '"]')) colourSel.value = params.get("colour"); + var focus = params.get("focus"); + // The 3D mode: the same nodes and edges as the flat map, drawn by 3d-force-graph, which the + // page loads only when a reader switches to it. An owned map template without the toggle + // simply has no 3D mode. + var dimSel = $("#dim"), g3dEl = $("#g3d"), g3d = null, g3dLast = null; + if (!dimSel || !g3dEl) dimSel = null; + else if (params.get("view") === "3d") dimSel.value = "3d"; + var drop3d = function () { + if (g3d) { g3d.pauseAnimation(); g3d._destructor(); g3d = null; } + if (g3dEl) g3dEl.innerHTML = ""; + }; + var fit3d = function () { if (g3d) g3d.width(g3dEl.clientWidth).height(g3dEl.clientHeight); }; + window.addEventListener("resize", fit3d); + if (APP) APP.onLeave(function () { window.removeEventListener("resize", fit3d); drop3d(); }); + var load3d = function (done) { + if (typeof window.ForceGraph3D === "function") return done(); + var s = document.createElement("script"); + s.src = g3dEl.getAttribute("data-src"); + s.onload = s.onerror = function () { s.remove(); done(); }; + document.head.appendChild(s); + }; + var draw3d = function (nodes, edges, inSlice, mode) { + drop3d(); + g3dEl.innerHTML = '
    Loading the 3D view…
    '; + load3d(function () { + // The reader may have left the page, or switched back, while the library loaded. + if (!g3dEl.isConnected || dimSel.value !== "3d") return; + if (typeof window.ForceGraph3D !== "function") { + g3dEl.innerHTML = '
    The 3D library did not load. The 2D map and every node page still work.
    '; + return; + } + g3dEl.innerHTML = ""; + var muted = css("--retired-soft"); + var data = { + nodes: nodes.map(function (n) { + return { id: n.id, name: n.name, pkg: n.pkg, col: inSlice && !inSlice[n.id] ? muted : fill(n, mode), val: 1 + Math.min(20, n.fields / 3 + n.claims / 2) }; + }), + links: edges.map(function (e) { return { source: e.s, target: e.t, label: e.v || e.k }; }), + }; + g3d = window.ForceGraph3D()(g3dEl) + .width(g3dEl.clientWidth).height(g3dEl.clientHeight) + .backgroundColor(css("--panel") || "#ffffff") + .nodeLabel(function (n) { return esc(n.name) + " · " + esc(n.pkg); }) + .nodeColor(function (n) { return n.col; }) + .nodeVal(function (n) { return n.val; }) + .nodeOpacity(0.95) + .linkLabel(function (l) { return esc(l.label); }) + .linkColor(function () { return css("--muted"); }) + .linkOpacity(0.45) + .linkDirectionalArrowLength(3).linkDirectionalArrowRelPos(1) + // One click shows the side panel, as a tap does on the flat map; a second click on + // the same node opens its page, as a double tap does. + .onNodeClick(function (n) { + var now = Date.now(); + if (g3dLast && g3dLast.id === n.id && now - g3dLast.t < 450) { + var node = byId[n.id]; + if (node) location.href = href(node.href); + g3dLast = null; + return; + } + g3dLast = { id: n.id, t: now }; + showPanel(n.id); + }) + .graphData(data); + // The drawn graph, for a script that drives the page (a test finds a node's position). + g3dEl.moGraph = g3d; + g3dEl.setAttribute("data-nodes", String(data.nodes.length)); + g3dEl.setAttribute("data-links", String(data.links.length)); + }); + }; + var promptSet = function () { + var s = {}; + D.nodes.forEach(function (n) { if (n.kind === "prompt" || n.kind === "template") s[n.id] = 1; }); + D.edges.forEach(function (e) { if (s[e.s] && (e.k === "payloadRef" || e.k === "responseRef")) s[e.t] = 1; }); + D.edges.forEach(function (e) { if (s[e.s] && byId[e.s] && byId[e.s].kind === "value" && e.k === "objectRef") s[e.t] = 1; }); + return s; + }; + var build = function (relayout) { + var slice = sliceSel.value, mode = colourSel.value, hide = $("#hideOut").checked, showExt = $("#showExt").checked; + $("#maplegend").innerHTML = legend(mode); + var inSlice = null; + if (slice === "@prompts") inSlice = promptSet(); + else if (slice && D.slices[slice]) { inSlice = {}; D.slices[slice].forEach(function (id) { inSlice[id] = 1; }); } + var showVals = $("#showValues").checked || slice === "@prompts" || (inSlice && Object.keys(inSlice).some(function (id) { return byId[id] && byId[id].kind !== "entity"; })); + var entityCount = D.nodes.filter(function (n) { return n.kind === "entity"; }).length; + if (!entityCount) showVals = true; + var nodes = D.nodes.filter(function (n) { return (n.kind === "entity" || showVals) && (!hide || !inSlice || inSlice[n.id]); }); + var ids = {}; + nodes.forEach(function (n) { ids[n.id] = 1; }); + var els = nodes.map(function (n) { + return { data: { id: n.id, label: n.name, col: fill(n, mode), size: 18 + Math.min(40, n.fields * 1.6 + n.claims * 2), shape: shape(n), faded: inSlice && !inSlice[n.id] ? 1 : 0, dashed: n.abstract, ring: n.unclaimed } }; + }); + D.edges.forEach(function (e, i) { + if (!ids[e.s] || !ids[e.t] || (!showExt && e.k === "extends")) return; + els.push({ data: { id: "e" + i, source: e.s, target: e.t, label: e.v || e.k, ext: e.k === "extends" ? 1 : 0, faded: inSlice && !(inSlice[e.s] && inSlice[e.t]) ? 1 : 0 } }); + }); + var three = dimSel !== null && dimSel.value === "3d"; + cyEl.hidden = three; + if (g3dEl) g3dEl.hidden = !three; + var qs3 = new URLSearchParams(query()); + if (three) qs3.set("view", "3d"); else qs3.delete("view"); + if (three) { + if (cy) { cy.destroy(); cy = null; } + draw3d(nodes, D.edges.filter(function (e) { return ids[e.s] && ids[e.t] && (showExt || e.k !== "extends"); }), inSlice, mode); + var sliceReq3 = slice.indexOf("requirement:") === 0 ? reqById[slice.slice("requirement:".length)] : null; + if (sliceReq3) $("#panel").innerHTML = slicePanel(sliceReq3, D.slices[slice] || []); + if (focus && byId[focus]) { showPanel(focus); focus = null; } + if (slice) qs3.set("slice", slice); else qs3.delete("slice"); + qs3.set("colour", mode); + setQuery("?" + qs3.toString()); + return; + } + drop3d(); + seedGrid(els); + var pan = cy && !relayout ? { pos: {} } : null; + if (pan) cy.nodes().forEach(function (n) { pan.pos[n.id()] = n.position(); }); + if (cy) cy.destroy(); + var keep = pan && els.every(function (el) { return el.data.source || pan.pos[el.data.id]; }); + cy = graph({ + container: cyEl, elements: els, wheelSensitivity: 0.3, maxZoom: 1.5, style: baseStyle(), + layout: keep ? { name: "preset", positions: function (n) { return pan.pos[n.id()]; }, fit: true, padding: 20 } : COSE, + }); + cy.on("tap", "node", function (ev) { showPanel(ev.target.id()); }); + cy.on("dbltap", "node", function (ev) { var n = byId[ev.target.id()]; if (n) location.href = href(n.href); }); + var sliceReq = slice.indexOf("requirement:") === 0 ? reqById[slice.slice("requirement:".length)] : null; + if (sliceReq) $("#panel").innerHTML = slicePanel(sliceReq, D.slices[slice] || []); + if (focus && byId[focus] && cy.getElementById(focus).length) { cy.getElementById(focus).select(); showPanel(focus); focus = null; } + var qs = qs3; + if (slice) qs.set("slice", slice); else qs.delete("slice"); + qs.set("colour", mode); + setQuery("?" + qs.toString()); + }; + ["#slice", "#colour", "#hideOut", "#showValues", "#showExt"].forEach(function (s) { $(s).onchange = function () { build(false); }; }); + if (dimSel) dimSel.onchange = function () { build(true); }; + $("#relayout").onclick = function () { + if (cy) cy.layout(Object.assign({}, COSE, { randomize: true })).run(); + if (g3d) g3d.d3ReheatSimulation(); + }; + redraw.push(function () { build(false); }); + build(true); + } + function slicePanel(r, nodes) { + return '
    Slice

    ' + (r.level ? "L" + r.level : "—") + '' + esc(r.label) + " " + chip(r.status) + "

    " + esc(r.statement) + "
    " + + "

    " + r.claimed + " model node" + (r.claimed === 1 ? "" : "s") + " claimed below

    " + nodes.map(nodeLink).join(", ") + + "

    Status below

    " + bar(r.rollup); + } + function showPanel(id) { + var n = byId[id], p = $("#panel"); + if (!n || !p) return; + var claims = D.reqs.filter(function (r) { return r.targets.indexOf(id) >= 0; }); + var byTop = {}; + claims.forEach(function (r) { var t = r; while (t.parent && reqById[t.parent]) t = reqById[t.parent]; (byTop[t.id] = byTop[t.id] || []).push(r); }); + var refs = D.edges.filter(function (e) { return e.s === id || e.t === id; }).length; + var gen = (D.generated[id] || []).map(function (g) { return '' + esc(g[0]) + " " + g[1]; }).join(" · "); + p.innerHTML = '
    ' + esc(n.pkg) + " · " + esc(n.kind) + (n.storage ? " · " + esc(n.storage) : "") + "
    " + + '

    ' + nodeLink(id) + (n.unclaimed ? ' unclaimed' : "") + "

    " + + "

    Why it exists (" + claims.length + " claim" + (claims.length === 1 ? "" : "s") + ")

    " + + (claims.length ? Object.keys(byTop).map(function (t) { + return "
    " + esc(reqById[t].label) + ": " + byTop[t].slice(0, 6).map(function (r) { return '' + (GLYPH[r.status] || "") + " " + esc(r.label) + ""; }).join(", ") + (byTop[t].length > 6 ? " +" + (byTop[t].length - 6) : "") + "
    "; + }).join("") : 'No requirement claims this node.') + + "

    Shape

    " + n.fields + " field" + (n.fields === 1 ? "" : "s") + ", " + refs + " reference" + (refs === 1 ? "" : "s") + + (n.api.length ? "

    API

    " + n.api.map(function (a) { return "
    " + esc(a) + "
    "; }).join("") : "") + + "

    Generated

    " + (gen || 'nothing traced'); + } + + // ── S3: the one-hop mini-map ──────────────────────────────────────────── + var mini = $("#cymini"); + if (mini) { + var me = mini.getAttribute("data-node"); + var drawMini = function () { + var es = D.edges.filter(function (e) { return e.s === me || e.t === me; }); + var ids = {}; + ids[me] = 1; + es.forEach(function (e) { ids[e.s] = 1; ids[e.t] = 1; }); + var els = Object.keys(ids).filter(function (id) { return byId[id]; }).sort().map(function (id) { + var n = byId[id]; + return { data: { id: id, label: n.name, col: fill(n, D.hasClaims ? "status" : "kind"), me: id === me ? 1 : 0, ring: n.unclaimed, shape: shape(n) } }; + }).concat(es.map(function (e, i) { return { data: { id: "m" + i, source: e.s, target: e.t, label: e.v || e.k } }; })); + mini.innerHTML = ""; + var c = graph({ + container: mini, elements: els, maxZoom: 1.3, + style: [ + { selector: "node", style: { "background-color": "data(col)", label: "data(label)", shape: "data(shape)", "font-size": 10, color: css("--ink"), "text-valign": "bottom", "text-margin-y": 2, width: 18, height: 18, "border-width": 1, "border-color": css("--line") } }, + { selector: "node[ring = 1]", style: { "border-width": 3, "border-color": css("--bad") } }, + { selector: "node[me = 1]", style: { width: 30, height: 30, "border-width": 3, "border-color": css("--accent") } }, + { selector: "edge", style: { width: 1, label: "data(label)", "font-size": 8, color: css("--muted"), "line-color": css("--muted"), "target-arrow-shape": "triangle", "target-arrow-color": css("--muted"), "curve-style": "bezier", "text-rotation": "autorotate", "text-background-color": css("--panel"), "text-background-opacity": 1, "text-background-padding": 2 } }, + ], + layout: { name: "concentric", concentric: function (n) { return n.data("me") ? 2 : 1; }, levelWidth: function () { return 1; }, startAngle: Math.PI, padding: 30, minNodeSpacing: 60 }, + }); + c.on("tap", "node", function (ev) { var n = byId[ev.target.id()]; if (n && n.id !== me) location.href = href(n.href); }); + }; + redraw.push(drawMini); + drawMini(); + } + + // ── S8: the trace ─────────────────────────────────────────────────────── + var tr = $("#cytrace"), tstart = $("#tstart"); + if (tr && tstart) { + var p2 = new URLSearchParams(query()).get("start"); + if (p2 && reqById[p2]) tstart.value = p2; + var drawTrace = function () { + var r0 = reqById[tstart.value]; + if (!r0) return; + var kids = {}; + D.reqs.forEach(function (r) { if (r.parent) (kids[r.parent] = kids[r.parent] || []).push(r); }); + var reqs = [], walk = function (r) { reqs.push(r); (kids[r.id] || []).forEach(walk); }; + walk(r0); + var cols = [[], [], [], []], els = [], seen = {}; + var add = function (id, label, col, data) { if (seen[id]) return; seen[id] = 1; cols[col].push(id); data.id = id; data.label = label; els.push({ data: data }); }; + reqs.forEach(function (r) { add("r:" + r.id, (r.level ? "L" + r.level + " " : "") + r.label, r.level >= 4 ? 1 : 0, { col: r.status ? css("--" + r.status) : css("--muted"), shape: "round-rectangle", go: r.href }); }); + reqs.forEach(function (r) { if (r.parent && seen["r:" + r.parent]) els.push({ data: { id: "pe:" + r.id, source: "r:" + r.parent, target: "r:" + r.id } }); }); + reqs.forEach(function (r) { + r.targets.forEach(function (t) { + var n = byId[t]; + if (!n) return; + add("o:" + t, n.name, 2, { col: kindColour(n), shape: shape(n), go: n.href, ring: n.unclaimed }); + if (!seen["le:" + r.id + ">" + t]) { seen["le:" + r.id + ">" + t] = 1; els.push({ data: { id: "le:" + r.id + ">" + t, source: "r:" + r.id, target: "o:" + t, col: r.status ? css("--" + r.status) : css("--muted") } }); } + }); + }); + cols[2].slice().forEach(function (oid) { + var id = oid.slice(2); + var gen = D.generated[id] || []; + if (!gen.length) return; + var total = gen.reduce(function (a, g) { return a + g[1]; }, 0); + var gid = "g:" + id; + add(gid, total + " generated (" + gen.map(function (g) { return g[0]; }).join(", ") + ")", 3, { col: css("--accent"), shape: "tag", go: byId[id].href }); + els.push({ data: { id: "ge:" + gid, source: oid, target: gid } }); + }); + var pos = {}; + cols.forEach(function (c, ci) { c.forEach(function (id, i) { pos[id] = { x: ci * 260, y: (i - c.length / 2) * 26 }; }); }); + tr.innerHTML = ""; + var c = graph({ + container: tr, elements: els, wheelSensitivity: 0.3, maxZoom: 1.6, + style: [ + { selector: "node", style: { "background-color": "data(col)", label: "data(label)", shape: "data(shape)", "font-size": 11, color: css("--ink"), "text-halign": "right", "text-valign": "center", "text-margin-x": 6, width: 12, height: 12 } }, + { selector: "node[ring = 1]", style: { "border-width": 2, "border-color": css("--bad") } }, + { selector: "edge", style: { width: 1, "line-color": "data(col)", opacity: 0.5, "curve-style": "unbundled-bezier" } }, + { selector: "edge[!col]", style: { "line-color": css("--muted") } }, + ], + layout: { name: "preset", positions: function (n) { return pos[n.id()]; }, fit: true, padding: 24 }, + }); + c.on("tap", "node", function (ev) { var go = ev.target.data("go"); if (go) location.href = href(go); }); + }; + tstart.onchange = function () { + var qs = new URLSearchParams(query()); qs.set("start", tstart.value); setQuery("?" + qs.toString()); + drawTrace(); + }; + redraw.push(drawTrace); + drawTrace(); + } + } + window.MO_THEME = run; + if (!window.MO_APP) run(); +})(); diff --git a/server/rust/metaobjects-codegen/explorer-app/index.html b/server/rust/metaobjects-codegen/explorer-app/index.html new file mode 100644 index 0000000000..6a91a98f6b --- /dev/null +++ b/server/rust/metaobjects-codegen/explorer-app/index.html @@ -0,0 +1,20 @@ + + + + + +Model explorer + + + + + +

    Loading the model…

    + + + + + + + + diff --git a/server/rust/metaobjects-codegen/src/client.rs b/server/rust/metaobjects-codegen/src/client.rs index 22dae76346..005a2b3ff3 100644 --- a/server/rust/metaobjects-codegen/src/client.rs +++ b/server/rust/metaobjects-codegen/src/client.rs @@ -206,10 +206,9 @@ fn client_crate( } lib_items.push((s.module(), exports)); let text = parts.entity_file(plan, s, route, &mut deps)?; - files.push(EmittedFile::new( - format!("{name}/src/{}.rs", s.module()), - text, - )); + files.push( + EmittedFile::new(format!("{name}/src/{}.rs", s.module()), text).from_node(&s.key), + ); } lib_items.sort(); files.push(EmittedFile::new( diff --git a/server/rust/metaobjects-codegen/src/commands.rs b/server/rust/metaobjects-codegen/src/commands.rs index a90b83e4aa..407bd6a962 100644 --- a/server/rust/metaobjects-codegen/src/commands.rs +++ b/server/rust/metaobjects-codegen/src/commands.rs @@ -184,10 +184,9 @@ fn command_crate( let route = s.route.as_ref().expect("a served entity has a route"); groups.push((s.module(), s.type_name.clone(), route.path.clone())); let text = parts.entity_file(s, route, cname, &client_crate)?; - files.push(EmittedFile::new( - format!("{name}/src/{}.rs", s.module()), - text, - )); + files.push( + EmittedFile::new(format!("{name}/src/{}.rs", s.module()), text).from_node(&s.key), + ); } groups.sort(); let manifest = parts.manifest(&name, c, &[cname, &client_crate]); diff --git a/server/rust/metaobjects-codegen/src/docs_site.rs b/server/rust/metaobjects-codegen/src/docs_site.rs new file mode 100644 index 0000000000..433bd945d7 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/docs_site.rs @@ -0,0 +1,458 @@ +//! `docs-site`: the model explorer, one browser app over the project's docs view, written with +//! no Node on the path (the Rust side of TypeScript's `docsSiteFile()`, `output: "app"`, and of +//! the JVM's `DocsSiteGenerator`; every port writes the same bytes). +//! +//! It builds the docs view from the model this run loaded ([`metaobjects::docs_view::build`]), +//! lists the files generated for each node (`generatedBy` and `sourceNode`, from +//! [`GenContext::generated_files`]: this run's, and the ones the hash manifest records outside +//! it), and writes, under `site/` (the `subDir` option; `""` writes at the output root): +//! +//! ```text +//! index.html, assets/explorer-app.js, the app: the same bytes in every port, from the +//! assets/cytoscape.min.js, repository's explorer-app/ (synced into this +//! assets/3d-force-graph.min.js crate by scripts/sync-explorer-app.sh) +//! assets/explorer.css, assets/explorer.js the theme, or the project's owned copy +//! explorer-model.js the docs view, the prompt texts, the title, the +//! footer and any owned templates, as one script +//! explorer-stamp.js the model's hash, which the open app polls +//! explorer.json the docs view itself, byte for byte +//! ``` +//! +//! The engine runs it after every other generator ([`Generator::reads_run_output`]), so a write +//! run and `verify` list the same files. Outside a run it lists what the hash manifest records. +//! +//! Options: `subDir` (default `site`); `title` (default: the project directory's name); `stamp` +//! (footer text, default none, so the site depends on the model alone); `prompts` (a directory, +//! relative to the project, holding prompt `.mustache` sources outside the metadata directories +//! and `templates/`); `verifyFile` (a `verify --format json` payload whose requirement rows the +//! explorer shows); `routesFile` (the routes the application mounts, `[{ node, method, path }]` +//! with `node` a resolution key). +//! +//! The site builder is engine, not an ejectable generator (the shared registry's `docs-site` +//! exemption): what an adopter changes is the theme. A project that owns it has its +//! `codegen/docs-site/assets/explorer.css`, `assets/explorer.js` and +//! `templates/explorer-*.mustache` used in place of the shipped ones. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use metaobjects::docs_view; +use serde_json::Value; + +use crate::generator::{EmittedFile, GenContext, GenError, Generator, Options, unknown_options}; +use crate::hashes::HashManifest; +use crate::sha256::sha256_hex; + +/// Bump when the emitted text changes shape, so a stored skip key never survives it. +const FORMAT: u32 = 1; +/// The failure of this generator. +const ERR_DOCS_SITE: &str = "ERR_DOCS_SITE"; + +const NAME: &str = "docs-site"; +const OPTION_SUB_DIR: &str = "subDir"; +const OPTION_TITLE: &str = "title"; +const OPTION_STAMP: &str = "stamp"; +const OPTION_PROMPTS: &str = "prompts"; +const OPTION_VERIFY_FILE: &str = "verifyFile"; +const OPTION_ROUTES_FILE: &str = "routesFile"; +const OPTIONS: &[&str] = &[ + OPTION_SUB_DIR, + OPTION_TITLE, + OPTION_STAMP, + OPTION_PROMPTS, + OPTION_VERIFY_FILE, + OPTION_ROUTES_FILE, +]; + +/// The default sub-directory of the output the site is written under. +pub const DEFAULT_SUB_DIR: &str = "site"; +/// Where an owned explorer theme lives, under the project (TypeScript's `OWNED_DOCS_SITE_DIR`). +pub const OWNED_DOCS_SITE_DIR: &str = "codegen/docs-site"; +/// The project's templates directory, searched for prompt sources. +const TEMPLATES_DIR: &str = "templates"; +/// The gen-state directory, under the project, whose manifest lists files outside a run. +const GEN_STATE_DIR: &str = ".metaobjects/.gen-state"; +/// The title when the project directory has no name. +const DEFAULT_TITLE: &str = "Metadata"; +/// The attribute naming a prompt's text. +const ATTR_TEXT_REF: &str = "textRef"; +const MUSTACHE: &str = ".mustache"; + +/// The data files the app reads, beside its shell. +pub const MODEL_FILE: &str = "explorer-model.js"; +pub const STAMP_FILE: &str = "explorer-stamp.js"; +pub const VIEW_FILE: &str = "explorer.json"; + +const ASSETS: &str = "assets/"; + +/// The app's files and this crate's copy of each (`explorer-app/`, synced from the repository +/// root's): every port ships the same bytes (TypeScript's `EXPLORER_APP_FILES`). +pub const APP_FILES: &[(&str, &str)] = &[ + ("index.html", include_str!("../explorer-app/index.html")), + ( + "assets/explorer-app.js", + include_str!("../explorer-app/assets/explorer-app.js"), + ), + ( + "assets/explorer.css", + include_str!("../explorer-app/assets/explorer.css"), + ), + ( + "assets/explorer.js", + include_str!("../explorer-app/assets/explorer.js"), + ), + ( + "assets/cytoscape.min.js", + include_str!("../explorer-app/assets/cytoscape.min.js"), + ), + ( + "assets/3d-force-graph.min.js", + include_str!("../explorer-app/assets/3d-force-graph.min.js"), + ), +]; + +/// The theme pair a project may own (`assets/` under the owned docs-site directory). +pub const THEME_ASSETS: &[&str] = &["explorer.css", "explorer.js"]; + +/// The templates an owned theme may replace; the app uses an owned one in place of its own. +pub const TEMPLATE_NAMES: &[&str] = &[ + "explorer-head.mustache", + "explorer-foot.mustache", + "explorer-card.mustache", + "explorer-overview.html.mustache", + "explorer-map.html.mustache", + "explorer-object.html.mustache", + "explorer-node.html.mustache", + "explorer-prompt.html.mustache", + "explorer-prompts.html.mustache", + "explorer-requirements.html.mustache", + "explorer-requirement.html.mustache", + "explorer-matrix.html.mustache", + "explorer-trace.html.mustache", + "explorer-gaps.html.mustache", + "explorer-api.html.mustache", + "explorer-model.html.mustache", + "explorer-package.html.mustache", +]; + +/// The docs-site generator, as shipped (no options). +#[derive(Debug, Clone, Copy, Default)] +pub struct DocsSiteGenerator; + +/// The generator as a project configured it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct DocsSite { + pub sub_dir: Option, + pub title: Option, + pub stamp: Option, + pub prompts: Option, + pub verify_file: Option, + pub routes_file: Option, +} + +impl Generator for DocsSiteGenerator { + fn name(&self) -> &str { + NAME + } + + fn identity(&self) -> String { + DocsSite::default().identity() + } + + fn extra_inputs(&self) -> Vec { + DocsSite::default().extra_inputs() + } + + fn reads_run_output(&self) -> bool { + true + } + + fn configure(&self, options: &Options) -> Result, GenError> { + Ok(Box::new(DocsSite::from_options(options)?)) + } + + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + DocsSite::default().generate(ctx) + } +} + +impl Generator for DocsSite { + fn name(&self) -> &str { + NAME + } + + fn identity(&self) -> String { + format!("{NAME}:{FORMAT}:{self:?}") + } + + /// The owned theme, the prompts directory and the verify and routes files are read beside + /// the model (ADR-0064): editing one regenerates. The hash manifest is not an input here: + /// the whole-run skip already re-runs when a recorded file changes or goes. + fn extra_inputs(&self) -> Vec { + let mut inputs = vec![OWNED_DOCS_SITE_DIR.to_string()]; + inputs.extend(self.prompts.clone()); + inputs.extend(self.verify_file.clone()); + inputs.extend(self.routes_file.clone()); + inputs + } + + fn reads_run_output(&self) -> bool { + true + } + + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + let project = &ctx.collection.config_dir; + let verify = self + .verify_file + .as_deref() + .map(|f| read_json(&project.join(f))) + .transpose()?; + let routes = self + .routes_file + .as_deref() + .map(|f| read_json(&project.join(f))) + .transpose()?; + let recorded; + let files = match ctx.generated_files { + Some(f) => Some(f), + None => { + let m = HashManifest::load(&project.join(GEN_STATE_DIR)); + recorded = m.existed().then(|| m.entries().clone()); + recorded.as_ref() + } + }; + let manifest = files.map(|f| Value::Object(f.clone())); + let view = docs_view::build( + ctx.tree, + ctx.root, + verify.as_ref(), + manifest.as_ref(), + routes.as_ref(), + ); + let owned = project.join(OWNED_DOCS_SITE_DIR); + let title = self.title.clone().unwrap_or_else(|| { + project.file_name().map_or_else( + || DEFAULT_TITLE.to_string(), + |n| n.to_string_lossy().into_owned(), + ) + }); + let texts = read_prompt_texts(&view, &self.prompt_dirs(ctx)); + let site = emit(&SiteInput { + view: &view, + title: &title, + footer: self.stamp.as_deref().unwrap_or_default(), + texts: &texts, + assets_dir: Some(owned.join("assets")).filter(|d| d.is_dir()), + templates_dir: Some(owned.join(TEMPLATES_DIR)).filter(|d| d.is_dir()), + })?; + let prefix = match self.sub_dir.as_deref().unwrap_or(DEFAULT_SUB_DIR) { + "" => String::new(), + dir => format!("{dir}/"), + }; + Ok(site + .into_iter() + .map(|(path, text)| EmittedFile::new(format!("{prefix}{path}"), text)) + .collect()) + } +} + +impl DocsSite { + /// The generator from a project's options for it. + pub fn from_options(options: &Options) -> Result { + if options.keys().any(|k| !OPTIONS.contains(&k.as_str())) { + return Err(unknown_options(NAME, options, OPTIONS)); + } + let text = |key: &str| -> Result, GenError> { + match options.get(key) { + None => Ok(None), + Some(Value::String(s)) => Ok(Some(s.clone())), + Some(other) => Err(GenError::new( + ERR_DOCS_SITE, + format!("the generator {NAME} takes \"{key}\" as a string, got {other}"), + )), + } + }; + Ok(Self { + sub_dir: text(OPTION_SUB_DIR)?.map(|s| s.trim_end_matches('/').to_string()), + title: text(OPTION_TITLE)?, + stamp: text(OPTION_STAMP)?, + prompts: text(OPTION_PROMPTS)?, + verify_file: text(OPTION_VERIFY_FILE)?, + routes_file: text(OPTION_ROUTES_FILE)?, + }) + } + + /// Where prompt `.mustache` sources are looked for: the directories the model was loaded + /// from, the project's `templates/` and the `prompts` directory, each once. + fn prompt_dirs(&self, ctx: &GenContext<'_>) -> Vec { + let project = &ctx.collection.config_dir; + let mut dirs: Vec = Vec::new(); + let mut add = |d: PathBuf| { + if d.is_dir() && !dirs.contains(&d) { + dirs.push(d); + } + }; + for root in &ctx.collection.source_roots { + add(if root.is_dir() { + root.clone() + } else { + root.parent().map(Path::to_path_buf).unwrap_or_default() + }); + } + add(project.join(TEMPLATES_DIR)); + if let Some(p) = &self.prompts { + add(project.join(p)); + } + dirs + } +} + +fn read_json(path: &Path) -> Result { + let text = std::fs::read_to_string(path).map_err(|e| { + GenError::new( + ERR_DOCS_SITE, + format!("{NAME}: could not read {}: {e}", path.display()), + ) + })?; + serde_json::from_str(&text).map_err(|e| { + GenError::new( + ERR_DOCS_SITE, + format!("{NAME}: {} is not JSON: {e}", path.display()), + ) + }) +} + +/// What the site is built from. +pub struct SiteInput<'a> { + /// The docs view ([`docs_view::build`]). + pub view: &'a Value, + /// The project's name, as the header and the home page print it. + pub title: &'a str, + /// Printed in every footer; `""` for none. + pub footer: &'a str, + /// Prompt text by template node id. + pub texts: &'a BTreeMap, + /// An owned theme directory (holding `explorer.css`, `explorer.js`). + pub assets_dir: Option, + /// An owned templates directory. + pub templates_dir: Option, +} + +/// Every file of the site, site-relative, in write order. +pub fn emit(input: &SiteInput<'_>) -> Result, GenError> { + let mut files: Vec<(String, String)> = Vec::new(); + for (path, text) in APP_FILES { + let theme = path + .strip_prefix(ASSETS) + .is_some_and(|a| THEME_ASSETS.contains(&a)); + if !theme { + files.push(((*path).to_string(), (*text).to_string())); + } + } + for asset in THEME_ASSETS { + let path = format!("{ASSETS}{asset}"); + let text = match read_if_present(input.assets_dir.as_deref(), asset)? { + Some(owned) => owned, + None => app_file(&path).to_string(), + }; + files.push((path, text)); + } + let mut templates = BTreeMap::new(); + for name in TEMPLATE_NAMES { + if let Some(owned) = read_if_present(input.templates_dir.as_deref(), name)? { + templates.insert((*name).to_string(), owned); + } + } + let (script, stamp) = model_script( + input.title, + input.footer, + input.texts, + &templates, + input.view, + ); + files.push((MODEL_FILE.to_string(), script)); + files.push((STAMP_FILE.to_string(), docs_view::stamp_script(&stamp))); + files.push((VIEW_FILE.to_string(), docs_view::serialize(input.view))); + Ok(files) +} + +/// This crate's copy of an app file. +fn app_file(path: &str) -> &'static str { + APP_FILES + .iter() + .find(|(p, _)| *p == path) + .map(|(_, t)| *t) + .unwrap_or_default() +} + +fn read_if_present(dir: Option<&Path>, name: &str) -> Result, GenError> { + let Some(p) = dir.map(|d| d.join(name)).filter(|p| p.is_file()) else { + return Ok(None); + }; + std::fs::read_to_string(&p).map(Some).map_err(|e| { + GenError::new( + ERR_DOCS_SITE, + format!("{NAME}: could not read {}: {e}", p.display()), + ) + }) +} + +/// The app's data script and the stamp it carries: the first 16 hex digits of the SHA-256 of +/// the payload ([`docs_view::model_payload`]). The same bytes as TypeScript's +/// `explorerModelScript`. +pub fn model_script( + title: &str, + footer: &str, + texts: &BTreeMap, + templates: &BTreeMap, + view: &Value, +) -> (String, String) { + let payload = docs_view::model_payload(title, footer, texts, templates, view); + let stamp = sha256_hex(payload.as_bytes())[..16].to_string(); + (docs_view::model_script(&stamp, &payload), stamp) +} + +/// Each prompt's `.mustache` text from the directories its `@textRef` resolves in, by template +/// node id. A ref that is absolute or climbs out with `..` is not read, so a model cannot pull +/// an arbitrary file into a published page. +pub fn read_prompt_texts(view: &Value, dirs: &[PathBuf]) -> BTreeMap { + let mut out = BTreeMap::new(); + for n in view["nodes"].as_array().into_iter().flatten() { + let mut text_ref = None; + for a in n["attrs"].as_array().into_iter().flatten() { + if a["name"] == ATTR_TEXT_REF + && let Some(v) = a["value"].as_str() + { + text_ref = Some(v); + } + } + let Some(r) = text_ref else { + continue; + }; + let segments: Vec<&str> = r.split(['/', '\\']).collect(); + let unsafe_ref = Path::new(r).is_absolute() + || r.starts_with('/') + || r.starts_with('\\') + || segments.iter().any(|s| s.is_empty() || *s == ".."); + if unsafe_ref { + continue; + } + for d in dirs { + let mut p = d.clone(); + for (i, s) in segments.iter().enumerate() { + if i == segments.len() - 1 { + p.push(format!("{s}{MUSTACHE}")); + } else { + p.push(s); + } + } + if let Ok(text) = std::fs::read_to_string(&p) { + if let Some(id) = n["id"].as_str() { + out.insert(id.to_string(), text); + } + break; + } + } + } + out +} diff --git a/server/rust/metaobjects-codegen/src/eject.rs b/server/rust/metaobjects-codegen/src/eject.rs index b258316b92..259161acbc 100644 --- a/server/rust/metaobjects-codegen/src/eject.rs +++ b/server/rust/metaobjects-codegen/src/eject.rs @@ -50,6 +50,10 @@ pub struct Reference { /// unless asked, and a project with no list does not run it. The transport is one: it /// brings a web framework into the build. pub opt_in: bool, + /// Listed and run like any other, never ejected: the generator is engine and what an + /// adopter owns is something it reads (the shared registry's eject exemption). `source` is + /// empty, and `gen --list` marks it `[package-only]`. + pub package_only: bool, /// One line for `gen --list`. pub summary: &'static str, /// The shipped source, which is also the owned copy's text. @@ -79,6 +83,7 @@ pub const REFERENCES: &[Reference] = &[ name: "entity", tier: "native", opt_in: false, + package_only: false, layer: "model", module: "entity", type_name: "EntityGenerator", @@ -91,6 +96,7 @@ pub const REFERENCES: &[Reference] = &[ name: "rules-names", tier: "native", opt_in: false, + package_only: false, layer: "model", module: "rules_names", type_name: "RulesNamesGenerator", @@ -104,6 +110,7 @@ pub const REFERENCES: &[Reference] = &[ name: "contract-types", tier: "native", opt_in: false, + package_only: false, layer: "model", module: "contract_types", type_name: "ContractTypesGenerator", @@ -117,6 +124,7 @@ pub const REFERENCES: &[Reference] = &[ name: "repository", tier: "native", opt_in: false, + package_only: false, layer: "persistence", module: "repository", type_name: "RepositoryGenerator", @@ -130,6 +138,7 @@ pub const REFERENCES: &[Reference] = &[ name: "service", tier: "native", opt_in: false, + package_only: false, layer: "service", module: "service", type_name: "ServiceGenerator", @@ -144,6 +153,7 @@ pub const REFERENCES: &[Reference] = &[ name: "service-routes", tier: "native", opt_in: true, + package_only: false, layer: "api", module: "service_routes", type_name: "ServiceRoutesGenerator", @@ -164,6 +174,7 @@ pub const REFERENCES: &[Reference] = &[ name: "client", tier: "native", opt_in: false, + package_only: false, layer: "client", module: "client", type_name: "ClientGenerator", @@ -176,6 +187,7 @@ pub const REFERENCES: &[Reference] = &[ name: "commands", tier: "native", opt_in: false, + package_only: false, layer: "client", module: "commands", type_name: "CommandsGenerator", @@ -188,6 +200,7 @@ pub const REFERENCES: &[Reference] = &[ name: "render-helper", tier: "native", opt_in: false, + package_only: false, layer: "capability", module: "render_helper", type_name: "RenderHelperGenerator", @@ -201,6 +214,7 @@ pub const REFERENCES: &[Reference] = &[ name: "output-parser", tier: "native", opt_in: false, + package_only: false, layer: "capability", module: "output_parser", type_name: "OutputParserGenerator", @@ -214,6 +228,7 @@ pub const REFERENCES: &[Reference] = &[ name: "output-prompt", tier: "native", opt_in: false, + package_only: false, layer: "capability", module: "output_prompt", type_name: "OutputPromptGenerator", @@ -226,6 +241,7 @@ pub const REFERENCES: &[Reference] = &[ name: "metamodel-docs", tier: "neutral", opt_in: true, + package_only: false, layer: "docs", module: "metamodel_docs", type_name: "MetamodelDocsGenerator", @@ -235,6 +251,20 @@ pub const REFERENCES: &[Reference] = &[ (reads no model; templates/metamodel/ in the project wins)", source: include_str!("metamodel_docs.rs"), }, + Reference { + name: "docs-site", + tier: "neutral", + opt_in: true, + package_only: true, + layer: "docs", + module: "docs_site", + type_name: "DocsSiteGenerator", + needs: &[], + summary: "the model explorer: one browser app over the docs view (explorer.json), with \ + each node's generated files; run last. Own its theme in codegen/docs-site/ \ + (assets/explorer.css, assets/explorer.js, templates/explorer-*.mustache)", + source: "", + }, ]; /// The shipped generator of that name. @@ -245,6 +275,7 @@ pub fn reference(name: &str) -> Option<&'static Reference> { fn names_list() -> String { REFERENCES .iter() + .filter(|r| !r.package_only) .map(|r| r.name) .collect::>() .join(", ") @@ -320,6 +351,7 @@ pub struct OwnedCopy { pub fn owned_copies(project_root: &Path) -> Vec { REFERENCES .iter() + .filter(|r| !r.package_only) .filter_map(|r| { let text = std::fs::read_to_string(project_root.join(r.owned_path())).ok()?; Some(OwnedCopy { @@ -371,6 +403,20 @@ fn io(what: &str, path: &Path, e: &std::io::Error) -> EjectError { } fn resolve(names: &[String]) -> Result, EjectError> { + let package_only: Vec<&str> = names + .iter() + .map(String::as_str) + .filter(|n| reference(n).is_some_and(|r| r.package_only)) + .collect(); + if !package_only.is_empty() { + return Err(EjectError::Usage(format!( + "{} stays in the package and has no copy to eject: what a project owns is what it \ + reads (for docs-site, its theme under {}/); ejectable: {}", + package_only.join(", "), + crate::docs_site::OWNED_DOCS_SITE_DIR, + names_list() + ))); + } let unknown: Vec<&str> = names .iter() .map(String::as_str) diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index db01261e30..6a8f9ccd24 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -17,6 +17,8 @@ //! compares with disk (`compare`), and writes nothing at all. use std::collections::{BTreeMap, HashSet}; + +use serde_json::{Map, Value}; use std::path::{Path, PathBuf}; use std::time::Instant; @@ -758,26 +760,52 @@ fn prepare<'g>( }) } -/// Run the selected generators in memory. Two files claiming one path is an error. -fn render(p: &mut Prepared<'_>, opts: &RunOptions) -> Result, RunError> { +/// A file a generator emitted, with the name of the generator that emitted it. +struct Rendered { + file: EmittedFile, + generated_by: String, +} + +/// Run the selected generators in memory. Two files claiming one path is an error. A +/// generator that reads the run's output runs after every other, and sees what they +/// emitted plus what the manifest records outside this run. +fn render(p: &mut Prepared<'_>, opts: &RunOptions) -> Result, RunError> { let start = Instant::now(); - let ctx = GenContext { + let mut ctx = GenContext { tree: &p.loaded.result.tree, root: p.loaded.result.root, entities: &opts.entities, collection: &p.loaded.collection, reference_nodes: &p.loaded.reference_nodes, + generated_files: None, }; - let mut emitted: Vec = Vec::new(); - for g in &p.selected { - emitted.extend(g.generate(&ctx).map_err(RunError::Generator)?); + let mut emitted: Vec = Vec::new(); + let emit = |g: &Selected<'_>, ctx: &GenContext<'_>, out: &mut Vec| { + let files = g.generate(ctx).map_err(RunError::Generator)?; + out.extend(files.into_iter().map(|file| Rendered { + file, + generated_by: g.name().to_string(), + })); + Ok::<(), RunError>(()) + }; + for g in p.selected.iter().filter(|g| !g.reads_run_output()) { + emit(g, &ctx, &mut emitted)?; + } + let readers: Vec<&Selected<'_>> = p.selected.iter().filter(|g| g.reads_run_output()).collect(); + let run_files; + if !readers.is_empty() { + run_files = generated_files(p, opts, &emitted); + ctx.generated_files = Some(&run_files); + for g in readers { + emit(g, &ctx, &mut emitted)?; + } } let mut seen: HashSet<&str> = HashSet::with_capacity(emitted.len()); - for f in &emitted { - if !seen.insert(f.path.as_str()) { + for r in &emitted { + if !seen.insert(r.file.path.as_str()) { return Err(RunError::Generator(GenError::new( ERR_PATH_COLLISION, - format!("two generated files claim the path {}", f.path), + format!("two generated files claim the path {}", r.file.path), ))); } } @@ -785,6 +813,43 @@ fn render(p: &mut Prepared<'_>, opts: &RunOptions) -> Result, R Ok(emitted) } +/// The generated files a reader of the run's output sees: every manifest entry that names +/// its generator and node, less the ones this run owns (under its output directory, unless +/// the run is narrowed and cannot tell), then this run's own files. +fn generated_files( + p: &Prepared<'_>, + opts: &RunOptions, + emitted: &[Rendered], +) -> Map { + let prefix = format!("{}/", p.out_rel); + let narrowed = narrowed(opts); + let mut out = Map::new(); + for (key, _) in p.manifest.records() { + if !narrowed && key.starts_with(&prefix) { + continue; + } + if let Some((by, node)) = p.manifest.provenance_of(key) { + out.insert(key.to_string(), provenance(by, Some(node))); + } + } + for r in emitted { + out.insert( + p.key_of(&r.file), + provenance(&r.generated_by, r.file.source_node.as_deref()), + ); + } + out +} + +fn provenance(generated_by: &str, source_node: Option<&str>) -> Value { + let mut o = Map::new(); + o.insert("generatedBy".into(), Value::String(generated_by.into())); + if let Some(n) = source_node { + o.insert("sourceNode".into(), Value::String(n.into())); + } + Value::Object(o) +} + /// Run `generators` over the project: the whole pipeline. pub fn run(opts: &RunOptions, generators: &[Box]) -> Result { let mut p = prepare(opts, generators)?; @@ -844,7 +909,8 @@ pub fn run(opts: &RunOptions, generators: &[Box]) -> Result = HashSet::new(); let mut written_hashes: BTreeMap = BTreeMap::new(); - for f in &emitted { + for r in &emitted { + let f = &r.file; let key = p.key_of(f); let path = p.project_root.join(&key); let fresh_hash = content_hash(&f.content); @@ -879,6 +945,8 @@ pub fn run(opts: &RunOptions, generators: &[Box]) -> Result return Err(io_error("reading", &path, &e)), } + p.manifest + .record_provenance(&key, &r.generated_by, f.source_node.as_deref()); written_hashes.insert(key, fresh_hash); } @@ -1035,7 +1103,8 @@ pub fn verify( let mut drifted = Vec::new(); let mut missing = Vec::new(); let mut emitted_keys: HashSet = HashSet::with_capacity(emitted.len()); - for f in &emitted { + for r in &emitted { + let f = &r.file; let key = p.key_of(f); let path = p.project_root.join(&key); match std::fs::read(&path) { diff --git a/server/rust/metaobjects-codegen/src/entity.rs b/server/rust/metaobjects-codegen/src/entity.rs index 08ab6a2e61..d80b755d97 100644 --- a/server/rust/metaobjects-codegen/src/entity.rs +++ b/server/rust/metaobjects-codegen/src/entity.rs @@ -269,10 +269,9 @@ fn model_crate( exports.extend(s.enums.iter().map(|e| e.type_name.clone())); lib_items.push((s.module(), exports)); let text = parts.struct_file(plan, s, cname, &q)?; - files.push(EmittedFile::new( - format!("{cname}/src/{}.rs", s.module()), - text, - )); + files.push( + EmittedFile::new(format!("{cname}/src/{}.rs", s.module()), text).from_node(&s.key), + ); } for (_, e) in &c.shared_enums { let module = module_name(&e.type_name); diff --git a/server/rust/metaobjects-codegen/src/generator.rs b/server/rust/metaobjects-codegen/src/generator.rs index d2338d2c71..c582a43182 100644 --- a/server/rust/metaobjects-codegen/src/generator.rs +++ b/server/rust/metaobjects-codegen/src/generator.rs @@ -9,13 +9,19 @@ use std::fmt; use metaobjects::collection::Collection; use metaobjects::node::{NodeId, Tree}; +use serde_json::{Map, Value}; -/// One generated file: its path relative to the output directory (always `/`-separated) -/// and its text. +/// One generated file: its path relative to the output directory (always `/`-separated), +/// its text and, for a file rendered from one node, that node's resolution key. #[derive(Debug, Clone, PartialEq, Eq)] pub struct EmittedFile { pub path: String, pub content: String, + /// The resolution key of the node this file was rendered from (`acme::shop::Order`), or + /// `None` for a file drawn from the whole model. The engine records it, with the + /// generator's name, in the hash manifest (`generatedBy`, `sourceNode`): the docs view + /// lists a node's files from it. + pub source_node: Option, } impl EmittedFile { @@ -23,8 +29,16 @@ impl EmittedFile { Self { path: path.into(), content: content.into(), + source_node: None, } } + + /// This file, rendered from the node whose resolution key is `key`. + #[must_use] + pub fn from_node(mut self, key: impl Into) -> Self { + self.source_node = Some(key.into()); + self + } } /// What a generator reads: the loaded model, the project's settings and the run's entity @@ -39,6 +53,11 @@ pub struct GenContext<'a> { pub collection: &'a Collection, /// Resolution keys of the nodes only reference sources declare (computed once at load). pub reference_nodes: &'a BTreeSet, + /// The generated files a generator that reads the run's output sees + /// ([`Generator::reads_run_output`]): project-relative path to + /// `{ generatedBy, sourceNode }`, this run's and the ones the manifest records outside + /// it. `None` for every other generator, and outside a run. + pub generated_files: Option<&'a Map>, } /// A generator failed: a shared-style error code and a message for people. @@ -150,6 +169,13 @@ pub trait Generator { Err(unknown_options(self.name(), options, &[])) } + /// Whether this generator reads what the rest of the run generated + /// ([`GenContext::generated_files`]). The engine runs every such generator after every + /// other, so a write run and `verify` list the same files. + fn reads_run_output(&self) -> bool { + false + } + /// Produce the generator's files for the loaded model. fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError>; } diff --git a/server/rust/metaobjects-codegen/src/hashes.rs b/server/rust/metaobjects-codegen/src/hashes.rs index 344609ae95..725c240d4c 100644 --- a/server/rust/metaobjects-codegen/src/hashes.rs +++ b/server/rust/metaobjects-codegen/src/hashes.rs @@ -32,6 +32,9 @@ pub const HASHES_DIR: &str = ".hashes"; pub const ROOT_FILE: &str = ".root.json"; const PACKAGE_SEP: &str = "::"; +const HASH_FIELD: &str = "hash"; +const GENERATED_BY_FIELD: &str = "generatedBy"; +const SOURCE_NODE_FIELD: &str = "sourceNode"; const GITIGNORE_RULE: &str = ".gen-state/*"; const GITIGNORE_LEGACY: &str = "!.gen-state/.hashes.json"; const GITIGNORE_DIR: &str = "!.gen-state/.hashes/"; @@ -44,7 +47,7 @@ pub fn content_hash(content: &str) -> String { fn entry_hash(value: &Value) -> Option<&str> { match value { Value::String(s) => Some(s), - Value::Object(o) => o.get("hash").and_then(Value::as_str), + Value::Object(o) => o.get(HASH_FIELD).and_then(Value::as_str), _ => None, } } @@ -78,7 +81,7 @@ pub fn package_file_name(package: Option<&str>) -> String { pub fn place(path: &str, entry: &Value, objects: &[(String, String)]) -> Option { if let Some(node) = entry .as_object() - .and_then(|o| o.get("sourceNode")) + .and_then(|o| o.get(SOURCE_NODE_FIELD)) .and_then(Value::as_str) { let object = node.split('.').next().unwrap_or(node); @@ -305,7 +308,7 @@ impl HashManifest { } match self.entries.get_mut(key) { Some(Value::Object(o)) => { - o.insert("hash".into(), Value::String(hash.into())); + o.insert(HASH_FIELD.into(), Value::String(hash.into())); } _ => { self.entries.insert(key.into(), Value::String(hash.into())); @@ -314,6 +317,59 @@ impl HashManifest { self.dirty = true; } + /// Record which generator wrote `key` and, for a file rendered from one node, that + /// node's resolution key (the docs view's `files`). With a source node the entry becomes + /// `{ hash, , generatedBy, sourceNode }`; without one it returns to + /// the plain hash, or to `{ hash, }`. A path with no recorded hash is left + /// alone: provenance never records a write. A no-op when nothing changes. + pub fn record_provenance(&mut self, key: &str, generated_by: &str, source_node: Option<&str>) { + let Some(current) = self.entries.get(key) else { + return; + }; + let Some(hash) = entry_hash(current).map(str::to_string) else { + return; + }; + let mut next = Map::new(); + next.insert(HASH_FIELD.into(), Value::String(hash.clone())); + if let Value::Object(o) = current { + for (k, v) in o { + if k != HASH_FIELD && k != GENERATED_BY_FIELD && k != SOURCE_NODE_FIELD { + next.insert(k.clone(), v.clone()); + } + } + } + if let Some(node) = source_node { + next.insert( + GENERATED_BY_FIELD.into(), + Value::String(generated_by.into()), + ); + next.insert(SOURCE_NODE_FIELD.into(), Value::String(node.into())); + } + let next = if next.len() == 1 { + Value::String(hash) + } else { + Value::Object(next) + }; + if self.entries.get(key) != Some(&next) { + self.entries.insert(key.into(), next); + self.dirty = true; + } + } + + /// The generator and source node recorded for `key`, when it has both. + pub fn provenance_of(&self, key: &str) -> Option<(&str, &str)> { + let o = self.entries.get(key)?.as_object()?; + Some(( + o.get(GENERATED_BY_FIELD)?.as_str()?, + o.get(SOURCE_NODE_FIELD)?.as_str()?, + )) + } + + /// Every recorded entry as the docs view reads the manifest: path to its raw entry. + pub fn entries(&self) -> &Map { + &self.entries + } + /// Drop the record for `key`. pub fn remove(&mut self, key: &str) { if self.entries.shift_remove(key).is_some() { diff --git a/server/rust/metaobjects-codegen/src/lib.rs b/server/rust/metaobjects-codegen/src/lib.rs index 873f651361..5d4b11d5e6 100644 --- a/server/rust/metaobjects-codegen/src/lib.rs +++ b/server/rust/metaobjects-codegen/src/lib.rs @@ -21,6 +21,7 @@ extern crate self as metaobjects_codegen; pub mod client; pub mod commands; pub mod contract_types; +pub mod docs_site; pub mod eject; pub mod emitted; pub mod engine; @@ -49,6 +50,7 @@ pub mod writer; pub use client::ClientGenerator; pub use commands::CommandsGenerator; pub use contract_types::ContractTypesGenerator; +pub use docs_site::DocsSiteGenerator; pub use engine::{ Change, ChangeKind, ExtraFile, FileCounts, Outcome, Refusal, RunError, RunOptions, RunReport, VerifyReport, run, verify, @@ -82,5 +84,6 @@ pub fn shipped_generators() -> Vec> { Box::new(OutputParserGenerator), Box::new(OutputPromptGenerator), Box::new(MetamodelDocsGenerator), + Box::new(DocsSiteGenerator), ] } diff --git a/server/rust/metaobjects-codegen/src/output_parser.rs b/server/rust/metaobjects-codegen/src/output_parser.rs index 3e148cc7bd..3af022f4e3 100644 --- a/server/rust/metaobjects-codegen/src/output_parser.rs +++ b/server/rust/metaobjects-codegen/src/output_parser.rs @@ -168,6 +168,8 @@ pub fn render( /// What one prompt's parser needs. pub struct ParserPlan { pub template: String, + /// The template's resolution key: the node its file is rendered from. + pub key: String, pub module: String, pub response_name: String, pub response_crate: String, @@ -205,6 +207,7 @@ fn parser_of( let format = reply_format(tree, t); Ok(ParserPlan { template: n.name.clone(), + key: tree.resolution_key(t), module: snake(&n.name), response_name: tree.node(response).name.clone(), response_crate: s.crate_name.clone(), @@ -230,10 +233,10 @@ fn parsers_crate( files: &mut Vec, ) -> Result<(), GenError> { for p in &c.parsers { - files.push(EmittedFile::new( - format!("{name}/src/{}.rs", p.module), - parts.parser_file(p)?, - )); + files.push( + EmittedFile::new(format!("{name}/src/{}.rs", p.module), parts.parser_file(p)?) + .from_node(&p.key), + ); } files.push(EmittedFile::new( format!("{name}/Cargo.toml"), diff --git a/server/rust/metaobjects-codegen/src/output_prompt.rs b/server/rust/metaobjects-codegen/src/output_prompt.rs index 59c54ea993..46138f3f17 100644 --- a/server/rust/metaobjects-codegen/src/output_prompt.rs +++ b/server/rust/metaobjects-codegen/src/output_prompt.rs @@ -155,6 +155,8 @@ pub fn render( /// What one prompt's fragment needs. pub struct FragmentPlan { pub template: String, + /// The template's resolution key: the node its file is rendered from. + pub key: String, pub module: String, pub response: NodeId, pub response_name: String, @@ -166,6 +168,7 @@ fn fragment_of(tree: &Tree, index: &ObjectIndex, t: NodeId) -> Option( files: &mut Vec, ) -> Result<(), GenError> { for f in &c.fragments { - files.push(EmittedFile::new( - format!("{name}/src/{}.rs", f.module), - parts.fragment_file(f)?, - )); + files.push( + EmittedFile::new( + format!("{name}/src/{}.rs", f.module), + parts.fragment_file(f)?, + ) + .from_node(&f.key), + ); } files.push(EmittedFile::new( format!("{name}/Cargo.toml"), diff --git a/server/rust/metaobjects-codegen/src/render_helper.rs b/server/rust/metaobjects-codegen/src/render_helper.rs index 4b55c05862..270fc79010 100644 --- a/server/rust/metaobjects-codegen/src/render_helper.rs +++ b/server/rust/metaobjects-codegen/src/render_helper.rs @@ -360,6 +360,8 @@ pub struct PartPlan<'t> { /// What one template's helper needs. pub struct HelperPlan<'t> { pub template: String, + /// The template's resolution key: the node its file is rendered from. + pub key: String, pub function: String, pub module: String, pub is_email: bool, @@ -435,6 +437,7 @@ fn helper_of<'t>( let module = snake(&n.name); Ok(HelperPlan { template: n.name.clone(), + key: tree.resolution_key(t), function: format!("render_{module}"), module, is_email, @@ -539,10 +542,10 @@ fn prompts_crate( ) -> Result<(), GenError> { let mut modules: Vec<(&str, &str)> = Vec::new(); for h in &c.helpers { - files.push(EmittedFile::new( - format!("{name}/src/{}.rs", h.module), - parts.helper_file(h)?, - )); + files.push( + EmittedFile::new(format!("{name}/src/{}.rs", h.module), parts.helper_file(h)?) + .from_node(&h.key), + ); modules.push((&h.module, &h.function)); } modules.sort(); diff --git a/server/rust/metaobjects-codegen/src/repository.rs b/server/rust/metaobjects-codegen/src/repository.rs index 25d5076128..427c9a62a2 100644 --- a/server/rust/metaobjects-codegen/src/repository.rs +++ b/server/rust/metaobjects-codegen/src/repository.rs @@ -130,10 +130,13 @@ pub fn render( let mut files = Vec::new(); for sc in stored_crates_in(ctx, &plan)? { for e in &sc.entities { - files.push(EmittedFile::new( - format!("{}/src/{}.rs", sc.name, e.module), - parts.entity_file(e)?, - )); + files.push( + EmittedFile::new( + format!("{}/src/{}.rs", sc.name, e.module), + parts.entity_file(e)?, + ) + .from_node(ctx.tree.resolution_key(e.node)), + ); } let mut modules: Vec = sc.entities.iter().map(|e| e.module.clone()).collect(); modules.sort(); diff --git a/server/rust/metaobjects-codegen/src/service.rs b/server/rust/metaobjects-codegen/src/service.rs index bca985f1a7..d4bdd8b1b8 100644 --- a/server/rust/metaobjects-codegen/src/service.rs +++ b/server/rust/metaobjects-codegen/src/service.rs @@ -130,10 +130,13 @@ pub fn render( files.push(file("rustfmt.toml", RUSTFMT_TOML.to_string())); files.push(file("src/lib.rs", parts.lib_file(&s))); for e in &s.entities { - files.push(file( - &format!("src/{}.rs", e.store.module), - parts.entity_file(&s, e), - )); + files.push( + file( + &format!("src/{}.rs", e.store.module), + parts.entity_file(&s, e), + ) + .from_node(ctx.tree.resolution_key(e.store.node)), + ); } if !s.operations.is_empty() { files.push(file("src/operations.rs", parts.operations_file(&s))); diff --git a/server/rust/metaobjects-codegen/src/service_routes.rs b/server/rust/metaobjects-codegen/src/service_routes.rs index 9b2a3750be..766729139d 100644 --- a/server/rust/metaobjects-codegen/src/service_routes.rs +++ b/server/rust/metaobjects-codegen/src/service_routes.rs @@ -425,8 +425,14 @@ pub fn render( files.push(file("rustfmt.toml", RUSTFMT_TOML.to_string())); files.push(file("src/lib.rs", parts.lib_file(&r))); for e in &r.entities { - let module = &r.service.entities[e.index].store.module; - files.push(file(&format!("src/{module}.rs"), parts.entity_file(&r, e))); + let store = &r.service.entities[e.index].store; + files.push( + file( + &format!("src/{}.rs", store.module), + parts.entity_file(&r, e), + ) + .from_node(ctx.tree.resolution_key(store.node)), + ); } } if !files.is_empty() { diff --git a/server/rust/metaobjects-codegen/tests/common/mod.rs b/server/rust/metaobjects-codegen/tests/common/mod.rs index 53bcc1bd69..38f28dedf3 100644 --- a/server/rust/metaobjects-codegen/tests/common/mod.rs +++ b/server/rust/metaobjects-codegen/tests/common/mod.rs @@ -180,12 +180,13 @@ pub fn cargo(dir: &Path, args: &[&str]) -> std::process::Output { .expect("cargo runs") } -/// The shipped generators that write crates: every one but `metamodel-docs`, whose Markdown -/// pages are not a crate and are held to their own corpus (`tests/metamodel_docs.rs`). +/// The shipped generators that write crates: every one but the two docs generators, +/// `metamodel-docs` and `docs-site`, whose pages are not a crate. Each is held to its own corpus +/// (`tests/metamodel_docs.rs`, `tests/docs_site.rs`). pub fn crate_generators() -> Vec> { shipped_generators() .into_iter() - .filter(|g| g.name() != "metamodel-docs") + .filter(|g| !matches!(g.name(), "metamodel-docs" | "docs-site")) .collect() } diff --git a/server/rust/metaobjects-codegen/tests/docs_site.rs b/server/rust/metaobjects-codegen/tests/docs_site.rs new file mode 100644 index 0000000000..dba9c2ba74 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/docs_site.rs @@ -0,0 +1,231 @@ +//! The `docs-site` generator: the model explorer app over the docs view, the same bytes as the +//! other ports write (`fixtures/explorer-conformance/`, the repository's `explorer-app/`). + +mod common; + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use common::Scratch; +use metaobjects_codegen::docs_site::{ + APP_FILES, MODEL_FILE, STAMP_FILE, SiteInput, THEME_ASSETS, VIEW_FILE, emit, model_script, + read_prompt_texts, +}; +use metaobjects_codegen::sha256::sha256_hex; +use metaobjects_codegen::{RunOptions, run, shipped_generators, verify}; +use serde_json::Value; + +fn repo() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../..") +} + +fn fixture(name: &str) -> PathBuf { + repo().join("fixtures/explorer-conformance").join(name) +} + +fn expected_view(name: &str) -> Value { + serde_json::from_str(&std::fs::read_to_string(fixture(name).join("expected.json")).unwrap()) + .unwrap() +} + +fn read(p: &Path) -> String { + std::fs::read_to_string(p).unwrap_or_else(|e| panic!("{}: {e}", p.display())) +} + +#[test] +fn the_model_script_is_typescripts_bytes() { + let texts = BTreeMap::from([ + ("b".to_string(), "B\n".to_string()), + ("a".to_string(), "A é".to_string()), + ]); + let templates = BTreeMap::from([("explorer-head.mustache".to_string(), "".to_string())]); + let (script, stamp) = model_script( + "Shop \u{2028}", + "v1", + &texts, + &templates, + &expected_view("shop"), + ); + // The title carries U+2028, which JSON.stringify leaves unescaped. + // explorerModelScript({ title: "Shop \u2028", footer: "v1", texts, templates, view }) in + // @metaobjectsdev/docs-site, over the same shop view, gives this stamp and these bytes. + assert_eq!(stamp, "05b57283a47416e2"); + assert_eq!( + sha256_hex(script.as_bytes()), + "02f2d4321101c0ab9fa9e22db542ff8f71f1e952748e8f894d388bd43feeb6bc" + ); + assert_eq!( + metaobjects::docs_view::stamp_script(&stamp), + "window.MO_STAMP = \"05b57283a47416e2\";\n" + ); +} + +#[test] +fn the_site_is_the_shared_app_and_the_views_bytes() { + let view = expected_view("model-alone"); + let files = emit(&SiteInput { + view: &view, + title: "t", + footer: "", + texts: &BTreeMap::new(), + assets_dir: None, + templates_dir: None, + }) + .unwrap(); + let by_path: BTreeMap<&str, &str> = files + .iter() + .map(|(p, t)| (p.as_str(), t.as_str())) + .collect(); + for (path, _) in APP_FILES { + assert_eq!( + by_path[path], + read(&repo().join("explorer-app").join(path)), + "{path}: the crate's copy is the repository's" + ); + } + assert_eq!( + by_path[VIEW_FILE], + read(&fixture("model-alone").join("expected.json")) + ); + let order: Vec<&str> = files.iter().map(|(p, _)| p.as_str()).collect(); + assert_eq!( + order, + [ + "index.html", + "assets/explorer-app.js", + "assets/cytoscape.min.js", + "assets/3d-force-graph.min.js", + "assets/explorer.css", + "assets/explorer.js", + MODEL_FILE, + STAMP_FILE, + VIEW_FILE, + ] + ); +} + +#[test] +fn an_owned_theme_replaces_the_shipped_one() { + let s = Scratch::new("docs-site-theme"); + s.write("assets/explorer.css", "body{}"); + s.write("templates/explorer-head.mustache", ""); + let view = expected_view("model-alone"); + let files: BTreeMap = emit(&SiteInput { + view: &view, + title: "t", + footer: "", + texts: &BTreeMap::new(), + assets_dir: Some(s.path().join("assets")), + templates_dir: Some(s.path().join("templates")), + }) + .unwrap() + .into_iter() + .collect(); + assert_eq!(files["assets/explorer.css"], "body{}"); + assert_eq!( + files["assets/explorer.js"], + read(&repo().join("explorer-app/assets/explorer.js")), + "a theme file the project does not own stays the shipped one" + ); + assert!( + files[MODEL_FILE].contains("\"templates\":{\"explorer-head.mustache\":\"\"}"), + "the owned template is carried" + ); + assert_eq!(THEME_ASSETS, ["explorer.css", "explorer.js"]); +} + +#[test] +fn prompt_texts_are_read_by_text_ref_and_never_outside_the_dirs() { + let view = expected_view("shop"); + let dirs = [fixture("shop").join("project/prompts")]; + let texts = read_prompt_texts(&view, &dirs); + assert_eq!(texts.len(), 1, "{texts:?}"); + assert_eq!( + texts.values().next().unwrap(), + &read(&fixture("shop").join("project/prompts/shop/order-note.mustache")) + ); + let climbing: Value = serde_json::json!({ "nodes": [ + { "id": "x", "attrs": [{ "name": "textRef", "value": "../shop/order-note" }] }, + { "id": "y", "attrs": [{ "name": "textRef", "value": "/etc/passwd" }] } + ] }); + assert!( + read_prompt_texts(&climbing, &[fixture("shop").join("project/prompts/shop")]).is_empty() + ); +} + +/// Copy a directory tree. +fn copy_dir(from: &Path, to: &Path) { + for e in std::fs::read_dir(from).unwrap().flatten() { + let dest = to.join(e.file_name()); + if e.path().is_dir() { + std::fs::create_dir_all(&dest).unwrap(); + copy_dir(&e.path(), &dest); + } else { + std::fs::copy(e.path(), dest).unwrap(); + } + } +} + +#[test] +fn a_run_writes_the_explorer_over_the_files_the_manifest_records() { + let p = Scratch::project("docs-site-run", &[]); + copy_dir(&fixture("shop").join("project"), p.path()); + for f in ["verify.json", "routes.json"] { + std::fs::copy(fixture("shop").join(f), p.path().join(f)).unwrap(); + } + // The fixture's hashes.json, as the legacy single-file manifest a project may still hold: + // its files are under src/, outside this run's output directory, so the site lists them. + p.write( + ".metaobjects/.gen-state/.hashes.json", + &read(&fixture("shop").join("hashes.json")), + ); + p.write( + "metaobjects.config.json", + r#"{ "generators": [{ "name": "docs-site", "options": { + "subDir": "", "prompts": "prompts", "verifyFile": "verify.json", "routesFile": "routes.json" + } }] }"#, + ); + let mut opts = RunOptions::new(p.path()); + opts.out_dir = PathBuf::from("generated"); + run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("gen failed: {e}")); + + assert_eq!( + p.read("generated/explorer.json"), + read(&fixture("shop").join("expected.json")), + "the run's explorer.json is the conformance view" + ); + let model = p.read("generated/explorer-model.js"); + assert!( + model.starts_with("window.MO_MODEL = {\"stamp\":"), + "{}", + &model[..40] + ); + assert!(model.contains("\"title\":\""), "a title"); + assert!( + model.contains("\"texts\":{\""), + "the prompt text is carried" + ); + for (path, _) in APP_FILES { + assert!(p.exists(&format!("generated/{path}")), "{path}"); + } + let report = + verify(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("verify failed: {e}")); + assert!( + report.drifted.is_empty() && report.missing.is_empty(), + "verify lists the same files the run wrote: {:?} {:?}", + report.drifted, + report.missing + ); +} + +#[test] +fn a_project_with_no_list_does_not_run_it() { + let p = Scratch::project("docs-site-unlisted", &common::shop_files()); + let mut opts = RunOptions::new(p.path()); + opts.out_dir = PathBuf::from("generated"); + run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("gen failed: {e}")); + assert!( + !p.exists("generated/site/explorer.json"), + "docs-site is opt-in" + ); +} diff --git a/server/rust/metaobjects-codegen/tests/entity_edges.rs b/server/rust/metaobjects-codegen/tests/entity_edges.rs index 6002d6c26e..42d3ac1d81 100644 --- a/server/rust/metaobjects-codegen/tests/entity_edges.rs +++ b/server/rust/metaobjects-codegen/tests/entity_edges.rs @@ -27,6 +27,7 @@ fn generate_named( entities: &names, collection: &loaded.collection, reference_nodes: &loaded.reference_nodes, + generated_files: None, }; EntityGenerator .generate(&ctx) diff --git a/server/rust/metaobjects-codegen/tests/generator_registry.rs b/server/rust/metaobjects-codegen/tests/generator_registry.rs index cd646fc149..ac9e0f2052 100644 --- a/server/rust/metaobjects-codegen/tests/generator_registry.rs +++ b/server/rust/metaobjects-codegen/tests/generator_registry.rs @@ -69,16 +69,29 @@ fn completeness_every_generator_ships_eject_source_in_run_order() { let registry = registry(); let generators = shipped_generators(); let shipped: Vec<&str> = generators.iter().map(|g| g.name()).collect(); - let ejectable: Vec<&str> = REFERENCES.iter().map(|r| r.name).collect(); + let listed: Vec<&str> = REFERENCES.iter().map(|r| r.name).collect(); assert_eq!( - ejectable, shipped, - "`eject` offers exactly the shipped generators, in run order" + listed, shipped, + "`eject` knows exactly the shipped generators, in run order" ); for (name, entry) in expected(®istry) { - assert_eq!( - entry["eject"], "full", - "{name}: the Rust port has no eject exemption" - ); + let r = REFERENCES.iter().find(|r| r.name == name).unwrap(); + if r.package_only { + // An exemption is the shared file's ruling, with its reason; the port only follows it. + assert!( + entry["eject"]["exempt"].is_string() && entry["eject"]["ruling"].is_string(), + "{name}: package-only here, but the registry does not exempt it" + ); + assert!( + r.source.is_empty(), + "{name}: a package-only generator ships no copy" + ); + } else { + assert_eq!( + entry["eject"], "full", + "{name}: ejectable here, but the registry exempts it" + ); + } } let pending = registry["eject"]["pending"].as_array().unwrap(); assert!( @@ -153,7 +166,7 @@ fn depth_an_owned_copy_names_nothing_outside_the_engine_surface() { exported_engine_modules(), "the registry's engine surface and the modules the crate exports differ; edit both together" ); - for r in REFERENCES { + for r in REFERENCES.iter().filter(|r| !r.package_only) { assert!( !engine.contains(r.module), "{}: a generator's own module is not engine", diff --git a/server/rust/metaobjects-codegen/tests/golden.rs b/server/rust/metaobjects-codegen/tests/golden.rs index 7104e5004e..a0c7a36f44 100644 --- a/server/rust/metaobjects-codegen/tests/golden.rs +++ b/server/rust/metaobjects-codegen/tests/golden.rs @@ -27,6 +27,7 @@ fn generate(files: &[(&str, &str)]) -> BTreeMap { entities: &[], collection: &loaded.collection, reference_nodes: &loaded.reference_nodes, + generated_files: None, }; common::crate_generators() .iter() @@ -116,6 +117,7 @@ fn the_support_crate_is_the_emitted_modules() { entities: &[], collection: &loaded.collection, reference_nodes: &loaded.reference_nodes, + generated_files: None, }; let files = EntityGenerator .generate(&ctx) diff --git a/server/rust/metaobjects-codegen/tests/hash_manifest.rs b/server/rust/metaobjects-codegen/tests/hash_manifest.rs index fd78bce477..b87d6846ee 100644 --- a/server/rust/metaobjects-codegen/tests/hash_manifest.rs +++ b/server/rust/metaobjects-codegen/tests/hash_manifest.rs @@ -158,6 +158,62 @@ fn a_legacy_manifest_splits_exactly_as_the_vector_says() { let _ = std::fs::remove_dir_all(&root); } +#[test] +fn provenance_follows_the_vectors() { + let v = vectors(); + let prov = &v["provenance"]; + let root = scratch("provenance"); + let gs = gen_state(&root); + std::fs::create_dir_all(gs.join(HASHES_DIR)).unwrap(); + for (name, entries) in prov["beforeFiles"].as_object().unwrap() { + let mut text = serde_json::to_string_pretty(entries).unwrap(); + text.push('\n'); + std::fs::write(gs.join(HASHES_DIR).join(name), text).unwrap(); + } + let record = |gs: &Path| { + let mut m = HashManifest::load(gs); + m.set_objects(objects(&v)); + for r in prov["records"].as_array().unwrap() { + m.record_provenance( + r["path"].as_str().unwrap(), + r["generatedBy"].as_str().unwrap(), + r["sourceNode"].as_str(), + ); + } + m.save().unwrap() + }; + assert!(record(&gs)); + let got = files_of(&gs); + let want = prov["afterFiles"].as_object().unwrap(); + let mut want_names: Vec<&String> = want.keys().collect(); + want_names.sort(); + assert_eq!(got.keys().collect::>(), want_names); + for (name, text) in &got { + // Byte-compare: field order inside an entry is part of the contract. + let mut expect = serde_json::to_string_pretty(&want[name]).unwrap(); + expect.push('\n'); + let parsed: Value = serde_json::from_str(&expect).unwrap(); + let sorted: Map = { + let mut keys: Vec<_> = parsed.as_object().unwrap().keys().cloned().collect(); + keys.sort(); + keys.into_iter() + .map(|k| (k.clone(), parsed[&k].clone())) + .collect() + }; + let mut expect = serde_json::to_string_pretty(&Value::Object(sorted)).unwrap(); + expect.push('\n'); + assert_eq!(text, &expect, "{name}"); + } + let golden = prov["goldenFile"].as_str().unwrap(); + assert_eq!(got[golden], prov["goldenText"].as_str().unwrap()); + + // Recording the same records again changes no file. + let before = files_of(&gs); + assert!(!record(&gs), "a second identical recording writes nothing"); + assert_eq!(files_of(&gs), before); + let _ = std::fs::remove_dir_all(&root); +} + #[test] fn the_gitignore_is_left_alone_when_it_has_the_line_or_no_rule() { let after = vectors()["legacySplit"]["gitignoreAfter"] diff --git a/server/rust/metaobjects-codegen/tests/list_query_conformance.rs b/server/rust/metaobjects-codegen/tests/list_query_conformance.rs index af75b4267e..8958ab6c00 100644 --- a/server/rust/metaobjects-codegen/tests/list_query_conformance.rs +++ b/server/rust/metaobjects-codegen/tests/list_query_conformance.rs @@ -60,6 +60,7 @@ fn ticket_spec() -> ListSpec { entities: &[], collection: &loaded.collection, reference_nodes: &loaded.reference_nodes, + generated_files: None, }; let plan = Plan::of(&ctx).expect("the model plans"); let ticket = plan diff --git a/server/rust/metaobjects-codegen/tests/reference_nodes.rs b/server/rust/metaobjects-codegen/tests/reference_nodes.rs index 6867f2c878..4d64896b9c 100644 --- a/server/rust/metaobjects-codegen/tests/reference_nodes.rs +++ b/server/rust/metaobjects-codegen/tests/reference_nodes.rs @@ -44,6 +44,7 @@ fn a_reference_node_is_loaded_and_not_generated() { entities: &[], collection: &loaded.collection, reference_nodes: &loaded.reference_nodes, + generated_files: None, }; let files = EntityGenerator.generate(&ctx).expect("generates"); let all: String = files.iter().map(|f| f.content.as_str()).collect(); diff --git a/server/rust/metaobjects-codegen/tests/rules_inert.rs b/server/rust/metaobjects-codegen/tests/rules_inert.rs index a4bb200eaf..ce7d41963e 100644 --- a/server/rust/metaobjects-codegen/tests/rules_inert.rs +++ b/server/rust/metaobjects-codegen/tests/rules_inert.rs @@ -51,6 +51,8 @@ enum Pick { DataAccess, Service, Transport, + /// The model explorer: it documents every node, so it is meant to show the rules. + Docs, } fn pick_of(name: &str) -> Pick { @@ -62,6 +64,8 @@ fn pick_of(name: &str) -> Pick { Pick::Service } else if TRANSPORT.contains(&name) { Pick::Transport + } else if name == "docs-site" { + Pick::Docs } else { Pick::Flat } @@ -87,6 +91,7 @@ fn emit(variant: &str, pick: Pick) -> BTreeMap { entities: &[], collection: &loaded.collection, reference_nodes: &loaded.reference_nodes, + generated_files: None, }; let mut files = BTreeMap::new(); for g in shipped_generators() { @@ -120,6 +125,18 @@ fn a_model_with_operations_and_transitions_generates_what_it_does_without_them() } } +#[test] +fn the_model_explorer_documents_operations_and_transitions() { + let with = emit("with", Pick::Docs); + let without = emit("without", Pick::Docs); + let view = "site/explorer.json"; + assert!(with.contains_key(view) && without.contains_key(view)); + assert_ne!( + with[view], without[view], + "the explorer lists the rules nodes" + ); +} + #[test] fn the_rules_layer_generators_write_nothing_without_the_vocabulary_and_only_their_own_files_with_it() { diff --git a/server/rust/metaobjects-codegen/tests/run_engine.rs b/server/rust/metaobjects-codegen/tests/run_engine.rs index 6bca97644f..94775c95e4 100644 --- a/server/rust/metaobjects-codegen/tests/run_engine.rs +++ b/server/rust/metaobjects-codegen/tests/run_engine.rs @@ -60,6 +60,25 @@ fn a_first_run_writes_every_file_and_records_them_all() { assert_eq!(names, [STAGE_LOAD, STAGE_PLAN, STAGE_RENDER, STAGE_WRITE]); } +#[test] +fn a_run_records_which_generator_and_node_each_file_came_from() { + let p = Scratch::project("provenance", &shop_files()); + gen_ok(&p); + let manifest: serde_json::Value = serde_json::from_str(&p.read(MANIFEST)).unwrap(); + let order = &manifest["generated/shop/src/order.rs"]; + assert_eq!(order["generatedBy"], "entity", "{manifest}"); + assert_eq!(order["sourceNode"], "shop::Order", "{manifest}"); + let root: serde_json::Value = + serde_json::from_str(&p.read(".metaobjects/.gen-state/.hashes/.root.json")).unwrap(); + assert!( + root["generated/shop/Cargo.toml"].is_string(), + "a whole-crate file is the plain hash: {root}" + ); + // A second run records the same thing and so writes no manifest. + let again = gen_with(&p, |o| o.force = true).unwrap(); + assert!(!again.manifest_written); +} + #[test] fn an_unchanged_project_skips_without_touching_any_file() { let p = Scratch::project("skip", &shop_files()); @@ -203,9 +222,10 @@ fn an_orphan_with_a_hand_edit_is_never_deleted_and_fails_the_run_by_name() { other => panic!("expected a refusal, got {other}"), } assert_eq!(p.read(orphan), "// mine\n", "the edit is left in place"); - // The object is gone, so nothing places the orphan any more: it is filed under the root. + // The object is gone, but the entry still names the node it was rendered from + // (`sourceNode`), and that places it: it stays in its package's manifest. assert!( - p.read(".metaobjects/.gen-state/.hashes/.root.json") + p.read(".metaobjects/.gen-state/.hashes/shop.billing.json") .contains(orphan), "and it stays recorded" ); diff --git a/server/rust/metaobjects/src/docs_view.rs b/server/rust/metaobjects/src/docs_view.rs new file mode 100644 index 0000000000..bf8feb95be --- /dev/null +++ b/server/rust/metaobjects/src/docs_view.rs @@ -0,0 +1,1431 @@ +//! The docs view of a loaded model: one port-neutral document, the facts every documentation +//! page reads and what the model explorer draws (`docs/features/docs-view.md`). +//! +//! The Rust port of TypeScript's `buildDocsView` (`@metaobjectsdev/metadata`, +//! `src/docs-view/build.ts`), held to the same bytes by `fixtures/explorer-conformance/`. It +//! reads the model the loader built and resolved, and re-derives none of it: ids and pages from +//! the effective tree walked once in declaration order ([`Tree::children`], the order the +//! effective canonical serializer writes); inheritance from a child whose parent is another +//! node; references from the loader's own resolution ([`reference_targets`], the node an +//! `extends` bound); claims through the rules the requirement gate uses. +//! +//! Three optional inputs add what the model does not hold, each as parsed JSON and each left +//! out when absent or malformed: the `meta verify --format json` payload, the generation +//! manifest (`path → { generatedBy, sourceNode }`) and the routes (`[{ node, method, path }]`). +//! The result is deterministic: [`serialize`] gives the same bytes for the same inputs. + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}; + +use serde_json::{Map, Value, json}; + +use crate::json::{js_quote, to_js_compact, to_js_pretty}; +use crate::loader::{is_ref_bearing_attr, reference_targets, split_child_tail}; +use crate::node::{NodeId, PACKAGE_SEP, Tree}; +use crate::parser::TYPE_OBJECT; +use crate::serializer::normalize; +use crate::validate::util::ObjectIndex; + +/// Bumped when a field changes meaning or is removed. +pub const FORMAT: &str = "metaobjects-docs-view/1"; + +const TYPE_REQUIREMENT: &str = "requirement"; +const TYPE_TEMPLATE: &str = "template"; +const TYPE_FIELD: &str = "field"; +const SUBTYPE_FUNCTIONAL: &str = "functional"; +const SUBTYPE_ARCHITECTURAL: &str = "architectural"; +const EXTENDS: &str = "extends"; +const ATTR_IS_ABSTRACT: &str = "isAbstract"; +const ATTR_IS_ARRAY: &str = "isArray"; +const ATTR_TITLE: &str = "title"; +const ATTR_DESCRIPTION: &str = "description"; +const ATTR_SUMMARY: &str = "summary"; +const ATTR_LEVEL: &str = "level"; +const ATTR_STATUS: &str = "status"; +const ATTR_DISPOSITION: &str = "disposition"; +const ATTR_TRACKED_BY: &str = "trackedBy"; +const ATTR_STATEMENT: &str = "statement"; +const ATTR_COUNTEREXAMPLE: &str = "counterexample"; +const ATTR_IMPLEMENTED_BY: &str = "implementedBy"; +/// The requirement statuses, in declaration order (the order the view counts them in). +const STATUSES: &[&str] = &["planned", "live", "partial", "retired"]; +/// The level from which a requirement links the model (`requirement.*` `@level` 4). +const LEVEL_OBJECT: i64 = 4; +const CODE_OBJECT_UNCLAIMED: &str = "WARN_REQUIREMENT_OBJECT_UNCLAIMED"; +const DOT: &str = "."; +const NUL: &str = "\u{0}"; + +/// The file's bytes: two-space JSON, as `JSON.stringify(view, null, 2)`, and one trailing +/// newline. +pub fn serialize(view: &Value) -> String { + let mut out = to_js_pretty(view); + out.push('\n'); + out +} + +/// What the explorer app's model script carries besides its stamp, as compact JSON +/// (`JSON.stringify({ title, footer, texts, templates, view })`), texts and templates in key +/// order. Its SHA-256 is the stamp ([`model_script`]). +pub fn model_payload( + title: &str, + footer: &str, + texts: &BTreeMap, + templates: &BTreeMap, + view: &Value, +) -> String { + let strings = |m: &BTreeMap| { + Value::Object( + m.iter() + .map(|(k, v)| (k.clone(), Value::String(v.clone()))) + .collect::>(), + ) + }; + let mut rest = Map::new(); + rest.insert("title".into(), Value::String(title.into())); + rest.insert("footer".into(), Value::String(footer.into())); + rest.insert("texts".into(), strings(texts)); + rest.insert("templates".into(), strings(templates)); + rest.insert("view".into(), view.clone()); + to_js_compact(&Value::Object(rest)) +} + +/// The explorer app's data script, `window.MO_MODEL = {"stamp":...,};` and a newline: +/// the bytes TypeScript's `explorerModelScript` writes. `stamp` is the first 16 hex digits of +/// the SHA-256 of `payload` ([`model_payload`]). +pub fn model_script(stamp: &str, payload: &str) -> String { + let body = payload.strip_prefix('{').unwrap_or(payload); + format!( + "window.MO_MODEL = {{\"stamp\":{},{body};\n", + js_quote(stamp) + ) +} + +/// The stamp file the open app polls, `window.MO_STAMP = "";` and a newline. +pub fn stamp_script(stamp: &str) -> String { + format!("window.MO_STAMP = {};\n", js_quote(stamp)) +} + +/// The docs view of the model alone. +pub fn build_model(tree: &Tree, root: NodeId) -> Value { + build(tree, root, None, None, None) +} + +/// Build the docs view of the model at `root`. `verify`, `manifest` and `routes` are optional; +/// a malformed one only leaves its part out. +pub fn build( + tree: &Tree, + root: NodeId, + verify: Option<&Value>, + manifest: Option<&Value>, + routes: Option<&Value>, +) -> Value { + Build::new(tree, root).run(verify, manifest, routes) +} + +// ---- the walk ------------------------------------------------------------------------------ + +/// A node as walked: where it sits, and the ids and pages it gets. Indexes are into +/// [`Build::walked`]. +struct Walked { + node: NodeId, + id: String, + plain: String, + top: usize, + parent: Option, + direct: Option, + requirement: Option, + order: usize, + canonical: bool, + declared_on: Option, + anchor: String, + path: String, + children: Vec, + address: String, +} + +/// One row of the verify payload's requirement ledger. +struct Ledger { + digest: String, + verdict: String, + diagnostics: Vec, + sup_ref: String, + sup_resolves: bool, + sup_target: String, + has_sup: bool, +} + +struct Build<'t> { + tree: &'t Tree, + root: NodeId, + objects: ObjectIndex, + walked: Vec, + tops: Vec, + by_id: HashMap, + canonical: HashMap, + by_plain: HashMap, + requirements: Vec, +} + +impl<'t> Build<'t> { + fn new(tree: &'t Tree, root: NodeId) -> Self { + let mut b = Self { + tree, + root, + objects: ObjectIndex::build(tree, root), + walked: Vec::new(), + tops: Vec::new(), + by_id: HashMap::new(), + canonical: HashMap::new(), + by_plain: HashMap::new(), + requirements: Vec::new(), + }; + b.walk(); + b + } + + fn walk(&mut self) { + let top_level: Vec = self.tree.children(self.root).to_vec(); + // Top-level nodes of different types may share a package and a name. The object keeps + // the plain id, since every reference in the model names an object, else the first + // declared; each other one is qualified by its type. + let mut holder: HashMap = HashMap::new(); + for &n in &top_level { + let id = self.plain_of(n); + let replace = match holder.get(&id) { + None => true, + Some(&held) => { + self.tree.node(held).type_name != TYPE_OBJECT + && self.tree.node(n).type_name == TYPE_OBJECT + } + }; + if replace { + holder.insert(id, n); + } + } + let mut seen: HashSet = HashSet::new(); + for (i, &n) in top_level.iter().enumerate() { + self.visit(n, i, None, "", &holder, &mut seen); + } + for i in 0..self.walked.len() { + self.walked[i].path = self.path_of(i); + } + } + + fn visit( + &mut self, + n: NodeId, + index: usize, + parent: Option, + req_prefix: &str, + holder: &HashMap, + seen: &mut HashSet, + ) { + let node = self.tree.node(n); + let name = node.name.as_str(); + let (mut id, plain) = match parent { + None => { + let plain = if name.is_empty() { + format!("#{index}") + } else { + self.plain_of(n) + }; + let mut id = plain.clone(); + let held = holder.get(&plain).copied(); + if !name.is_empty() + && held != Some(n) + && held.is_none_or(|h| self.tree.node(h).type_name != node.type_name) + { + id = qualified(&plain, self.tree, n); + } + (id, plain) + } + Some(p) => { + let pw = &self.walked[p]; + if name.is_empty() { + ( + format!("{}#{index}", pw.id), + format!("{}#{index}", pw.plain), + ) + } else { + ( + format!("{}{DOT}{name}", pw.id), + format!("{}{DOT}{name}", pw.plain), + ) + } + } + }; + // The first sibling of a name keeps the plain id; a later one of another type is + // qualified by type. + if parent.is_some() && !name.is_empty() && seen.contains(&id) { + id = qualified(&id, self.tree, n); + } + assert!( + !seen.contains(&id), + "docs view: two nodes share the id \"{id}\" — the model names two siblings alike" + ); + seen.insert(id.clone()); + let is_req = node.type_name == TYPE_REQUIREMENT; + let address = if is_req { + if req_prefix.is_empty() { + name.to_string() + } else { + format!("{req_prefix}{DOT}{name}") + } + } else { + req_prefix.to_string() + }; + let inherited = parent.is_some_and(|p| node.parent != Some(self.walked[p].node)); + let me = self.walked.len(); + let (top, direct, requirement, canonical) = match parent { + None => (me, None, is_req.then_some(me), true), + Some(p) => { + let pw = &self.walked[p]; + let direct = if pw.parent.is_none() { + Some(me) + } else { + pw.direct + }; + let requirement = if is_req { Some(me) } else { pw.requirement }; + (pw.top, direct, requirement, pw.canonical && !inherited) + } + }; + let anchor = if direct == Some(me) { + member_anchor(self.tree, n, name, index) + } else { + String::new() + }; + self.walked.push(Walked { + node: n, + id: id.clone(), + plain: plain.clone(), + top, + parent, + direct, + requirement, + order: index, + canonical, + declared_on: if inherited { node.parent } else { None }, + anchor, + path: String::new(), + children: Vec::new(), + address: if is_req { + address.clone() + } else { + String::new() + }, + }); + self.by_id.insert(id, me); + let top_w = &self.walked[top]; + if top_w.id == top_w.plain && !self.by_plain.contains_key(&plain) { + self.by_plain.insert(plain, me); + } + if canonical { + self.canonical.insert(n, me); + } + match parent { + None => self.tops.push(me), + Some(p) => self.walked[p].children.push(me), + } + if is_req { + self.requirements.push(me); + } + let kids: Vec = self.tree.children(n).to_vec(); + for (i, k) in kids.into_iter().enumerate() { + self.visit(k, i, Some(me), &address, holder, seen); + } + } + + fn path_of(&self, w: usize) -> String { + let walked = &self.walked[w]; + if let Some(r) = walked.requirement { + let r = &self.walked[r]; + let top = self.walked[r.top].node; + return format!( + "requirements/{}/{}.html", + package_dir(&self.package_of(top)), + page_stem(&r.address) + ); + } + let top = &self.walked[walked.top]; + let tn = self.tree.node(top.node); + let qualifier = format!("[{}.{}]", tn.type_name, tn.sub_type); + let typed = if top.id.ends_with(&qualifier) { + format!(".{}-{}", tn.type_name, tn.sub_type) + } else { + String::new() + }; + let page = format!( + "model/{}/{}{typed}.html", + package_dir(&self.package_of(top.node)), + page_stem(&tn.name) + ); + match walked.direct { + None => page, + Some(d) => format!("{page}#{}", self.walked[d].anchor), + } + } + + /// The package of the top-level node holding `n`, as every reference resolves in it. + fn package_of(&self, n: NodeId) -> String { + self.tree.effective_package(self.tree.top_level_of(n)) + } + + fn plain_of(&self, n: NodeId) -> String { + let pkg = self.package_of(n); + let name = &self.tree.node(n).name; + if pkg.is_empty() { + name.clone() + } else { + format!("{pkg}{PACKAGE_SEP}{name}") + } + } + + fn link(&self, w: usize) -> Value { + let walked = &self.walked[w]; + let node = self.tree.node(walked.node); + let label = if walked.requirement == Some(w) { + let title = str_attr(self.tree, walked.node, ATTR_TITLE); + if title.is_empty() { + node.name.clone() + } else { + title + } + } else if walked.top == w { + node.name.clone() + } else { + let top = &self.walked[walked.top]; + format!( + "{}{}", + self.tree.node(top.node).name, + &walked.id[top.id.len()..] + ) + }; + json!({ + "label": label, + "id": walked.id, + "path": walked.path, + "kind": format!("{}.{}", node.type_name, node.sub_type), + "unresolved": false, + }) + } + + fn link_to(&self, n: Option, text: &str) -> Value { + match n.and_then(|n| self.canonical.get(&n)) { + Some(&w) => self.link(w), + None => unresolved(text), + } + } + + /// The link a reference value lands on: the owner's row for the member its dotted tail + /// names, else the owner the loader bound. + fn ref_link(&self, owner: Option, value: &str) -> Value { + let Some(owner) = owner else { + return unresolved(value); + }; + let tail = split_child_tail(value).1; + let row = (!tail.is_empty()) + .then(|| { + self.by_plain + .get(&format!("{}{tail}", self.plain_of(owner))) + }) + .flatten(); + match row { + Some(&w) => self.link(w), + None => self.link_to(Some(owner), value), + } + } + + // ---- the build --------------------------------------------------------------------- + + fn run( + &self, + verify_in: Option<&Value>, + manifest: Option<&Value>, + routes_in: Option<&Value>, + ) -> Value { + let mut ledger = ledger_rows(verify_in); + let has_verify = ledger.is_some(); + let verify = verify_in.and_then(Value::as_object); + + // ── Requirements: claims first, since nodes and members list them. ── + let mut claims_on: HashMap> = HashMap::new(); + let mut req_links: HashMap> = HashMap::new(); + let mut req_targets: HashMap> = HashMap::new(); + for &r in &self.requirements { + let rn = self.walked[r].node; + let referrer_pkg = self.package_of(rn); + let mut links = Vec::new(); + let mut targets = Vec::new(); + for reference in string_list(self.tree.attr(rn, ATTR_IMPLEMENTED_BY)) { + let (owner, path) = split_member_ref(&reference); + let node = self.resolve_claim_target(owner, &referrer_pkg); + let member = match node { + Some(n) if !path.is_empty() => resolve_member(self.tree, n, &path), + other => other, + }; + let key = match node { + None => String::new(), + Some(n) if path.is_empty() => self.plain_of(n), + Some(n) => format!("{}{DOT}{}", self.plain_of(n), path.join(DOT)), + }; + let w = member.and_then(|_| self.by_plain.get(&key).copied()); + let Some(w) = w else { + links.push(req_link(&reference, false, unresolved(&reference))); + continue; + }; + links.push(req_link(&reference, true, self.link(w))); + targets.push(w); + let claim = json!({ + "requirement": self.link(r), + "member": if self.walked[w].top == w { String::new() } else { self.member_path(w) }, + "status": attr_text(self.tree, rn, ATTR_STATUS), + "level": level_of(self.tree, rn).map_or(Value::Null, Value::from), + }); + // The claim is on the top-level node and on every member down to the one it names. + let mut x = Some(w); + while let Some(i) = x { + claims_on.entry(i).or_default().push(claim.clone()); + x = self.walked[i].parent; + } + } + req_links.insert(r, links); + req_targets.insert(r, targets); + } + + // ── Files and routes. ── + let mut files_of: HashMap>> = HashMap::new(); + let manifest = manifest.and_then(Value::as_object); + if let Some(m) = manifest { + for (path, entry) in m { + let Some(entry) = entry.as_object() else { + continue; + }; + let Some(source) = string_of(entry, "sourceNode") else { + continue; + }; + let Some(&w) = self.by_plain.get(source) else { + continue; + }; + files_of + .entry(self.walked[w].top) + .or_default() + .entry( + string_of(entry, "generatedBy") + .unwrap_or_default() + .to_string(), + ) + .or_default() + .push(path.clone()); + } + } + let mut routes_of: HashMap> = HashMap::new(); + let routes_in = routes_in.and_then(Value::as_array); + if let Some(rs) = routes_in { + for r in rs { + let Some(r) = r.as_object() else { + continue; + }; + let (Some(node), Some(method), Some(path)) = ( + string_of(r, "node"), + string_of(r, "method"), + string_of(r, "path"), + ) else { + continue; + }; + let Some(&w) = self.by_plain.get(node) else { + continue; + }; + let method = js_upper(method); + routes_of.entry(self.walked[w].top).or_default().insert( + format!("{path}{NUL}{method}"), + json!({ "method": method, "path": path }), + ); + } + } + + // ── Advisories. ── + let mut advisories = Vec::new(); + let mut unclaimed_ids: HashSet = HashSet::new(); + let rows = verify + .filter(|_| has_verify) + .and_then(|v| v.get("requirements")) + .and_then(Value::as_object) + .and_then(|r| r.get("rows")) + .and_then(Value::as_array); + for d in rows.into_iter().flatten() { + let Some(d) = d.as_object() else { + continue; + }; + let node = string_of(d, "node").unwrap_or_default(); + let subject = if node.is_empty() { + Value::Null + } else { + match self.by_plain.get(node) { + Some(&w) => self.link(self.walked[w].top), + None => unresolved(node), + } + }; + let code = string_of(d, "code").unwrap_or_default(); + if code == CODE_OBJECT_UNCLAIMED + && let Some(id) = subject.get("id").and_then(Value::as_str) + { + unclaimed_ids.insert(id.to_string()); + } + advisories.push(json!({ + "code": code, + "path": string_of(d, "path").unwrap_or_default(), + "subject": subject, + "severity": string_of(d, "severity").unwrap_or_default(), + "source": string_of(d, "source").unwrap_or_default(), + "message": string_of(d, "message").unwrap_or_default(), + })); + } + + // ── Members and references. ── + let mut refs_from: HashMap> = HashMap::new(); + let mut nodes: Vec = Vec::new(); + let mut node_refs: HashMap> = HashMap::new(); + for &t in &self.tops { + let tn = self.walked[t].node; + let (attrs, attr_refs) = self.attrs_of(tn); + let ext = self.extends_link(tn); + let members: Vec = self.walked[t] + .children + .iter() + .map(|&c| self.member(c, &claims_on, &mut refs_from)) + .collect(); + let member_groups = group_members(members); + let mut all: Vec = Vec::new(); + if is_resolved(&ext) { + all.push(reference(EXTENDS, Value::Null, ext.clone())); + } + for (name, link) in attr_refs { + all.push(reference(&name, Value::Null, link)); + } + self.below(t, &refs_from, &mut all); + + let mut files = Vec::new(); + let mut file_count = 0usize; + if let Some(by_gen) = files_of.get(&t) { + for (generated_by, paths) in by_gen { + let mut paths = paths.clone(); + paths.sort(); + file_count += paths.len(); + files.push(json!({ "generatedBy": generated_by, "paths": paths })); + } + } + let routes: Vec = routes_of + .get(&t) + .map(|m| m.values().cloned().collect()) + .unwrap_or_default(); + let claims = claims_on.get(&t).cloned().unwrap_or_default(); + let walked = &self.walked[t]; + let node = self.tree.node(tn); + let counts = json!({ + "members": walked.children.len(), + "refs": all.len(), + "referencedBy": 0, + "claims": claims.len(), + "files": file_count, + "routes": routes.len(), + }); + nodes.push(json!({ + "id": walked.id, + "name": node.name, + "package": self.package_of(tn), + "type": node.type_name, + "subType": node.sub_type, + "order": walked.order, + "path": walked.path, + "title": str_attr(self.tree, tn, ATTR_TITLE), + "description": str_attr(self.tree, tn, ATTR_DESCRIPTION), + "summary": str_attr(self.tree, tn, ATTR_SUMMARY), + "abstract": is_abstract(self.tree, tn), + "extends": ext, + "attrs": attrs, + "memberGroups": member_groups, + "refs": all.clone(), + "referencedBy": [], + "claims": claims, + "files": files, + "routes": routes, + "unclaimed": unclaimed_ids.contains(&walked.id), + "counts": counts, + })); + node_refs.insert(t, all); + } + + // referencedBy: every reference into a top-level node (or a member of it) from another one. + let mut incoming: HashMap> = HashMap::new(); + for &t in &self.tops { + for r in node_refs.get(&t).into_iter().flatten() { + let target = &r["target"]; + let target_id = target["id"].as_str().unwrap_or_default(); + let Some(&tw) = self.by_id.get(target_id) else { + continue; + }; + if self.walked[tw].top == t { + continue; + } + let via = &r["via"]; + let attr = r["attr"].as_str().unwrap_or_default(); + let via_id = via.get("id").and_then(Value::as_str).unwrap_or_default(); + let key = [self.walked[t].id.as_str(), attr, via_id, target_id].join(NUL); + incoming + .entry(self.walked[self.walked[tw].top].id.clone()) + .or_default() + .insert( + key, + json!({ "attr": attr, "from": self.link(t), "via": via, "target": target }), + ); + } + } + for n in &mut nodes { + let id = n["id"].as_str().unwrap_or_default().to_string(); + if let Some(by) = incoming.get(&id) { + let by: Vec = by.values().cloned().collect(); + n["counts"]["referencedBy"] = Value::from(by.len()); + n["referencedBy"] = Value::Array(by); + } + } + nodes.sort_by(|a, c| id_of(a).cmp(id_of(c))); + + // ── The requirement list, flat, in document order. ── + let mut req_children: HashMap> = HashMap::new(); + for &r in &self.requirements { + if let Some(p) = self.req_parent(r) { + req_children.entry(p).or_default().push(r); + } + } + let mut reqs: Vec = Vec::new(); + for &r in &self.requirements { + let rw = &self.walked[r]; + let rn = rw.node; + let pkg = self.package_of(rn); + let qualified_path = qualify(&pkg, &rw.address); + let row = ledger + .as_mut() + .and_then(|l| l.get_mut(&qualified_path)) + .and_then(VecDeque::pop_front); + let mut chain = Vec::new(); + let mut p = self.req_parent(r); + while let Some(x) = p { + chain.insert(0, x); + p = self.req_parent(x); + } + let mut sub = Vec::new(); + subtree(r, &req_children, &mut sub); + let linked: Vec = sub + .iter() + .copied() + .filter(|&x| { + let xn = self.walked[x].node; + let level = level_of(self.tree, xn); + level.unwrap_or(0) >= LEVEL_OBJECT + || (level.is_none() + && !string_list(self.tree.attr(xn, ATTR_IMPLEMENTED_BY)).is_empty()) + }) + .collect(); + let counted = if linked.is_empty() { vec![r] } else { linked }; + let statuses: Vec = counted + .iter() + .map(|&x| attr_text(self.tree, self.walked[x].node, ATTR_STATUS)) + .filter(|s| !s.is_empty()) + .collect(); + let mut target_tops: BTreeMap = BTreeMap::new(); + for &x in &sub { + for &w in req_targets.get(&x).into_iter().flatten() { + let top = self.walked[w].top; + target_tops + .entry(self.walked[top].id.clone()) + .or_insert(top); + } + } + let children = req_children.get(&r).cloned().unwrap_or_default(); + let superseded_by = match &row { + Some(row) if row.has_sup => { + let target = (!row.sup_target.is_empty()) + .then(|| { + self.requirements.iter().copied().find(|&x| { + let xw = &self.walked[x]; + qualify(&self.package_of(xw.node), &xw.address) == row.sup_target + }) + }) + .flatten(); + req_link( + &row.sup_ref, + row.sup_resolves, + target.map_or_else(|| unresolved(&row.sup_ref), |t| self.link(t)), + ) + } + _ => Value::Null, + }; + let link = self.link(r); + reqs.push(json!({ + "id": rw.id, + "name": self.tree.node(rn).name, + "label": link["label"], + "path": rw.path, + "address": rw.address, + "package": pkg, + "qualifiedPath": qualified_path, + "subType": self.tree.node(rn).sub_type, + "level": level_of(self.tree, rn).map_or(Value::Null, Value::from), + "status": attr_text(self.tree, rn, ATTR_STATUS), + "disposition": attr_text(self.tree, rn, ATTR_DISPOSITION), + "statement": str_attr(self.tree, rn, ATTR_STATEMENT), + "counterexample": str_attr(self.tree, rn, ATTR_COUNTEREXAMPLE), + "title": str_attr(self.tree, rn, ATTR_TITLE), + "description": str_attr(self.tree, rn, ATTR_DESCRIPTION), + "trackedBy": string_list(self.tree.attr(rn, ATTR_TRACKED_BY)), + "depth": chain.len(), + "parent": chain.last().map_or(Value::Null, |&p| self.link(p)), + "breadcrumbs": chain.iter().map(|&x| self.link(x)).collect::>(), + "children": children.iter().map(|&x| self.link(x)).collect::>(), + "implementedBy": req_links.get(&r).cloned().unwrap_or_default(), + "supersededBy": superseded_by, + "inLedger": row.is_some(), + "verdict": row.as_ref().map_or("", |r| r.verdict.as_str()), + "digest": row.as_ref().map_or("", |r| r.digest.as_str()), + "diagnostics": row.as_ref().map_or_else(Vec::new, |r| r.diagnostics.clone()), + "rollup": status_counts(&statuses), + "rollupTotal": statuses.len(), + "belowCount": sub.len() - 1, + "childCount": children.len(), + "targets": target_tops.values().map(|&w| self.link(w)).collect::>(), + "targetCount": target_tops.len(), + })); + } + + // ── Packages, counts, slices. ── + let pkg_names: BTreeSet<&str> = nodes.iter().map(package_of_view).collect(); + let mut packages = Vec::new(); + for name in &pkg_names { + let mut groups: BTreeMap = BTreeMap::new(); + let mut count = 0usize; + for n in nodes.iter().filter(|n| package_of_view(n) == *name) { + count += 1; + let type_name = n["type"].as_str().unwrap_or_default(); + let sub_type = n["subType"].as_str().unwrap_or_default(); + let g = groups + .entry(format!("{type_name}.{sub_type}")) + .or_insert_with(|| { + json!({ "type": type_name, "subType": sub_type, "count": 0, "nodes": [] }) + }); + g["count"] = Value::from(g["count"].as_u64().unwrap_or(0) + 1); + if let Some(&w) = self.by_id.get(id_of(n)) + && let Some(arr) = g["nodes"].as_array_mut() + { + arr.push(self.link(w)); + } + } + packages.push(json!({ + "name": name, + "count": count, + "groups": groups.into_values().collect::>(), + })); + } + + let vc = verify + .and_then(|v| v.get("requirementCounts")) + .and_then(Value::as_object); + let mut all_files: HashSet<&str> = HashSet::new(); + let mut route_count = 0usize; + for n in &nodes { + for g in n["files"].as_array().into_iter().flatten() { + for p in g["paths"].as_array().into_iter().flatten() { + all_files.insert(p.as_str().unwrap_or_default()); + } + } + route_count += n["routes"].as_array().map_or(0, Vec::len); + } + let mut functional = 0usize; + let mut architectural = 0usize; + let mut claim_count = 0usize; + let mut req_statuses = Vec::new(); + for r in &reqs { + match r["subType"].as_str() { + Some(SUBTYPE_FUNCTIONAL) => functional += 1, + Some(SUBTYPE_ARCHITECTURAL) => architectural += 1, + _ => {} + } + req_statuses.push(r["status"].as_str().unwrap_or_default().to_string()); + claim_count += r["implementedBy"] + .as_array() + .into_iter() + .flatten() + .filter(|l| l["resolves"] == Value::Bool(true)) + .count(); + } + let num = |key: &str| { + vc.and_then(|o| o.get(key)) + .filter(|v| v.is_number()) + .cloned() + .unwrap_or(Value::from(0)) + }; + let counts = json!({ + "nodes": nodes.len(), + "packages": packages.len(), + "requirements": reqs.len(), + "functional": functional, + "architectural": architectural, + "byStatus": status_counts(&req_statuses), + "claims": claim_count, + "files": all_files.len(), + "routes": route_count, + "undecided": num("undecided"), + "coverageMeasured": vc.and_then(|o| o.get("entitiesTotal")).is_some_and(Value::is_number), + "entitiesClaimed": num("entitiesClaimed"), + "entitiesTotal": num("entitiesTotal"), + }); + let slices = self.slices(&nodes, &reqs); + json!({ + "format": FORMAT, + "sources": { + "requirements": has_verify, + "files": manifest.is_some(), + "routes": routes_in.is_some(), + }, + "counts": counts, + "packages": packages, + "nodes": nodes, + "requirements": reqs, + "advisories": advisories, + "slices": slices, + }) + } + + fn slices(&self, nodes: &[Value], reqs: &[Value]) -> Vec { + let mut slices = Vec::new(); + let pkgs: BTreeSet<&str> = nodes.iter().map(package_of_view).collect(); + for pkg in pkgs { + let ids: BTreeSet = nodes + .iter() + .filter(|n| package_of_view(n) == pkg) + .map(|n| id_of(n).to_string()) + .collect(); + slices.push(slice("package", pkg, ids)); + } + // A requirement with requirements below it: the subtree, each node it claims, and the + // top-level node holding a claimed member. + let req_by_id: HashMap<&str, &Value> = reqs.iter().map(|r| (id_of(r), r)).collect(); + for r in reqs { + if r["childCount"].as_u64().unwrap_or(0) == 0 { + continue; + } + let mut ids = BTreeSet::new(); + self.slice_visit(r, &req_by_id, &mut ids); + slices.push(slice("requirement", id_of(r), ids)); + } + // A template: itself and what its own attributes reference. + for n in nodes { + if n["type"].as_str() != Some(TYPE_TEMPLATE) { + continue; + } + let mut ids = BTreeSet::new(); + ids.insert(id_of(n).to_string()); + for r in n["refs"].as_array().into_iter().flatten() { + if !r["via"].is_null() { + continue; + } + let tid = r["target"]["id"].as_str().unwrap_or_default(); + ids.insert(match self.by_id.get(tid) { + Some(&w) => self.walked[self.walked[w].top].id.clone(), + None => tid.to_string(), + }); + } + slices.push(slice("prompt", id_of(n), ids)); + } + slices.sort_by(|a, c| id_of(a).cmp(id_of(c))); + slices + } + + fn slice_visit( + &self, + x: &Value, + req_by_id: &HashMap<&str, &Value>, + ids: &mut BTreeSet, + ) { + ids.insert(id_of(x).to_string()); + for l in x["implementedBy"].as_array().into_iter().flatten() { + if l["resolves"] != Value::Bool(true) { + continue; + } + let tid = l["target"]["id"].as_str().unwrap_or_default(); + ids.insert(tid.to_string()); + if let Some(&w) = self.by_id.get(tid) { + ids.insert(self.walked[self.walked[w].top].id.clone()); + } + } + for c in x["children"].as_array().into_iter().flatten() { + if let Some(child) = req_by_id.get(id_of(c)) { + self.slice_visit(child, req_by_id, ids); + } + } + } + + fn req_parent(&self, r: usize) -> Option { + self.walked[r] + .parent + .and_then(|p| self.walked[p].requirement) + } + + fn below(&self, w: usize, refs_from: &HashMap>, all: &mut Vec) { + for &c in &self.walked[w].children { + all.extend(refs_from.get(&c).into_iter().flatten().cloned()); + self.below(c, refs_from, all); + } + } + + fn member( + &self, + w: usize, + claims_on: &HashMap>, + refs_from: &mut HashMap>, + ) -> Value { + let n = self.walked[w].node; + let (attrs, attr_refs) = self.attrs_of(n); + let ext = self.extends_link(n); + let mut own = Vec::new(); + if is_resolved(&ext) { + own.push(reference(EXTENDS, self.link(w), ext.clone())); + } + for (name, link) in attr_refs { + own.push(reference(&name, self.link(w), link)); + } + refs_from.insert(w, own.clone()); + let walked = &self.walked[w]; + let node = self.tree.node(n); + let declared_on = walked.declared_on.map_or(Value::Null, |d| { + self.link_to(Some(d), &self.tree.node(d).name) + }); + let children: Vec = walked.children.clone(); + let members: Vec = children + .into_iter() + .map(|c| self.member(c, claims_on, refs_from)) + .collect(); + json!({ + "id": walked.id, + "name": node.name, + "type": node.type_name, + "subType": node.sub_type, + "order": walked.order, + "anchor": walked.anchor, + "path": walked.path, + "abstract": is_abstract(self.tree, n), + "isArray": node.type_name == TYPE_FIELD && is_array(self.tree, n), + "extends": ext, + "declaredOn": declared_on, + "attrs": attrs, + "refs": own, + "claims": claims_on.get(&w).cloned().unwrap_or_default(), + "memberGroups": group_members(members), + }) + } + + fn extends_link(&self, n: NodeId) -> Value { + let node = self.tree.node(n); + let written = node + .authored_super_ref + .as_deref() + .or(node.super_ref.as_deref()); + if node.super_node.is_none() && written.is_none() { + return Value::Null; + } + self.link_to(node.super_node, written.unwrap_or_default()) + } + + /// A node's effective attributes, by name, each value linked where the loader resolved it; + /// and the links that resolved, in order, as `(attr, link)`. + fn attrs_of(&self, n: NodeId) -> (Vec, Vec<(String, Value)>) { + let type_name = self.tree.node(n).type_name.as_str(); + let effective = self.tree.attrs(n); + let by_name: BTreeMap<&String, &Value> = effective + .iter() + // `isAbstract` and `isArray` are native flags in the view, not attributes. + .filter(|(k, _)| k.as_str() != ATTR_IS_ABSTRACT && k.as_str() != ATTR_IS_ARRAY) + .collect(); + let mut attrs = Vec::new(); + let mut refs = Vec::new(); + for (name, raw) in by_name { + let value = canonical_value(normalize(raw.clone())); + let is_ref = is_ref_bearing_attr(type_name, name); + let resolved = if is_ref { + self.declaring_targets(n, name) + } else { + Vec::new() + }; + let mut values = Vec::new(); + match &value { + Value::String(text) => { + let link = if is_ref { + self.ref_link(resolved.first().copied().flatten(), text) + } else { + Value::Null + }; + if is_resolved(&link) { + refs.push((name.clone(), link.clone())); + } + values.push(attr_value(text, link)); + } + Value::Array(items) if items.iter().all(Value::is_string) => { + for (i, item) in items.iter().enumerate() { + let item = item.as_str().unwrap_or_default(); + let link = if is_ref { + self.ref_link(resolved.get(i).copied().flatten(), item) + } else { + Value::Null + }; + if is_resolved(&link) { + refs.push((name.clone(), link.clone())); + } + values.push(attr_value(item, link)); + } + } + other => values.push(attr_value(&to_js_compact(other), Value::Null)), + } + attrs.push(json!({ "name": name, "value": value, "values": values })); + } + (attrs, refs) + } + + /// What the loader bound for `name` on the layer that declares it (own, else the nearest + /// `extends` ancestor). + fn declaring_targets(&self, n: NodeId, name: &str) -> Vec> { + let mut seen = HashSet::new(); + let mut cur = Some(n); + while let Some(x) = cur { + if !seen.insert(x) { + break; + } + // ADR-0039: own — locating the layer that declares the attr, walking the super chain. + if self.tree.own_attr(x, name).is_some() { + return reference_targets(self.tree, &self.objects, x, name); + } + cur = self.tree.node(x).super_node; + } + Vec::new() + } + + /// Resolve the owner of an `@implementedBy` reference: objects first, as every reference + /// resolves; then root-level nodes that are neither objects nor requirements (a + /// `template.prompt` and its siblings). An ambiguous bare name binds nothing. + fn resolve_claim_target(&self, owner: &str, referrer_pkg: &str) -> Option { + if let Some(o) = self.objects.resolve(owner, referrer_pkg) { + return Some(o); + } + // ADR-0039 own: the root's top-level nodes are its declared children; a root extends nothing. + let candidates: Vec = self + .tree + .own_children(self.root) + .iter() + .copied() + .filter(|&c| { + let t = &self.tree.node(c).type_name; + t != TYPE_OBJECT && t != TYPE_REQUIREMENT + }) + .collect(); + let key = |c: NodeId| self.tree.resolution_key(c); + if owner.contains(PACKAGE_SEP) { + return candidates.into_iter().find(|&c| key(c) == owner); + } + let one = |matches: Vec| (matches.len() == 1).then(|| matches[0]); + if !referrer_pkg.is_empty() { + let local = format!("{referrer_pkg}{PACKAGE_SEP}{owner}"); + if let Some(c) = one(candidates + .iter() + .copied() + .filter(|&c| key(c) == local) + .collect()) + { + return Some(c); + } + } + one(candidates + .into_iter() + .filter(|&c| self.tree.node(c).name == owner && key(c) == owner) + .collect()) + } + + /// A member's id after its top-level node's. + fn member_path(&self, w: usize) -> String { + let walked = &self.walked[w]; + let rest = &walked.id[self.walked[walked.top].id.len()..]; + rest.strip_prefix(DOT).unwrap_or(rest).to_string() + } +} + +// ---- helpers ------------------------------------------------------------------------------- + +/// Split an `@implementedBy` reference into its owner and its dotted member path, at the first +/// `.` after the last `::`. +fn split_member_ref(r: &str) -> (&str, Vec) { + let from = r.rfind(PACKAGE_SEP).map_or(0, |i| i + PACKAGE_SEP.len()); + match r[from..].find('.') { + None => (r, Vec::new()), + Some(dot) => { + let (owner, rest) = r.split_at(from + dot); + (owner, rest[1..].split('.').map(str::to_string).collect()) + } + } +} + +/// Walk dotted member segments by child name from a node, through its effective children. +fn resolve_member(tree: &Tree, n: NodeId, path: &[String]) -> Option { + let mut cur = n; + for seg in path { + cur = tree + .children(cur) + .iter() + .copied() + .find(|&c| tree.node(c).name == *seg)?; + } + Some(cur) +} + +fn qualified(id: &str, tree: &Tree, n: NodeId) -> String { + let node = tree.node(n); + format!("{id}[{}.{}]", node.type_name, node.sub_type) +} + +/// `m-` for a field, `m--` for anything else, `m--` with no name. +fn member_anchor(tree: &Tree, n: NodeId, name: &str, order: usize) -> String { + let t = &tree.node(n).type_name; + if name.is_empty() { + format!("m-{t}-{order}") + } else if t == TYPE_FIELD { + format!("m-{name}") + } else { + format!("m-{t}-{name}") + } +} + +fn package_dir(pkg: &str) -> String { + if pkg.is_empty() { + "-root".to_string() + } else { + pkg.split(PACKAGE_SEP).collect::>().join("/") + } +} + +fn page_stem(name: &str) -> String { + if name.to_lowercase() == "index" { + format!("{name}.node") + } else { + name.to_string() + } +} + +fn qualify(pkg: &str, address: &str) -> String { + if pkg.is_empty() { + address.to_string() + } else { + format!("{pkg}{PACKAGE_SEP}{address}") + } +} + +/// `@isAbstract` is a declaration-layer marker, never inherited. +fn is_abstract(tree: &Tree, n: NodeId) -> bool { + // ADR-0039: own — @isAbstract is a declaration-layer marker, never inherited. + tree.node(n).is_abstract + || tree.own_attr(n, ATTR_IS_ABSTRACT).map(|a| &a.value) == Some(&Value::Bool(true)) +} + +fn is_array(tree: &Tree, n: NodeId) -> bool { + tree.resolved_is_array(n) || tree.attr(n, ATTR_IS_ARRAY) == Some(&Value::Bool(true)) +} + +/// A string attribute's effective value, `""` when it is absent or not a string. +fn str_attr(tree: &Tree, n: NodeId, name: &str) -> String { + match tree.attr(n, name) { + Some(Value::String(s)) => s.clone(), + _ => String::new(), + } +} + +/// An attribute's effective value as text (a number as JavaScript prints it), `""` when absent. +fn attr_text(tree: &Tree, n: NodeId, name: &str) -> String { + match tree.attr(n, name) { + None | Some(Value::Null) => String::new(), + Some(v) => crate::json::js_display(v), + } +} + +/// A requirement's `@level`: a number (saturated to 32 bits) or a numeric string. +fn level_of(tree: &Tree, n: NodeId) -> Option { + let saturate = |v: i64| v.clamp(i64::from(i32::MIN), i64::from(i32::MAX)); + match tree.attr(n, ATTR_LEVEL)? { + Value::Number(num) => num + .as_i64() + .or_else(|| { + #[allow(clippy::cast_possible_truncation)] + num.as_f64().map(|f| f.trunc() as i64) + }) + .map(saturate), + Value::String(s) => s.trim().parse::().ok().map(saturate), + _ => None, + } +} + +/// A list attribute: a list of strings, or one comma-separated string. +fn string_list(v: Option<&Value>) -> Vec { + match v { + Some(Value::Array(items)) => items + .iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect(), + Some(Value::String(s)) => s + .split(',') + .map(str::trim) + .filter(|p| !p.is_empty()) + .map(str::to_string) + .collect(), + _ => Vec::new(), + } +} + +/// JavaScript's `toUpperCase`, locale-independent. +fn js_upper(s: &str) -> String { + s.to_uppercase() +} + +fn unresolved(text: &str) -> Value { + json!({ "label": text, "id": "", "path": "", "kind": "", "unresolved": true }) +} + +fn is_resolved(link: &Value) -> bool { + link.get("unresolved") == Some(&Value::Bool(false)) +} + +fn req_link(r: &str, resolves: bool, target: Value) -> Value { + json!({ "ref": r, "resolves": resolves, "target": target }) +} + +fn reference(attr: &str, via: Value, target: Value) -> Value { + json!({ "attr": attr, "via": via, "target": target }) +} + +fn attr_value(text: &str, link: Value) -> Value { + json!({ "text": text, "link": link }) +} + +fn id_of(v: &Value) -> &str { + v["id"].as_str().unwrap_or_default() +} + +fn package_of_view(v: &Value) -> &str { + v["package"].as_str().unwrap_or_default() +} + +fn string_of<'a>(o: &'a Map, key: &str) -> Option<&'a str> { + o.get(key).and_then(Value::as_str) +} + +fn group_members(members: Vec) -> Vec { + let mut order: Vec = Vec::new(); + let mut groups: HashMap> = HashMap::new(); + for m in members { + let t = m["type"].as_str().unwrap_or_default().to_string(); + if !groups.contains_key(&t) { + order.push(t.clone()); + } + groups.entry(t).or_default().push(m); + } + order + .into_iter() + .map(|t| { + let members = groups.remove(&t).unwrap_or_default(); + json!({ "type": t, "count": members.len(), "members": members }) + }) + .collect() +} + +fn status_counts(statuses: &[String]) -> Vec { + STATUSES + .iter() + .map(|s| json!({ "status": s, "count": statuses.iter().filter(|x| x == s).count() })) + .collect() +} + +fn slice(kind: &str, anchor: &str, ids: BTreeSet) -> Value { + json!({ + "id": format!("{kind}:{anchor}"), + "kind": kind, + "anchor": anchor, + "nodes": ids.into_iter().collect::>(), + }) +} + +fn subtree(r: usize, req_children: &HashMap>, out: &mut Vec) { + out.push(r); + for &c in req_children.get(&r).into_iter().flatten() { + subtree(c, req_children, out); + } +} + +/// The verify payload's requirement ledger, by qualified path (a path may have more than one +/// row, used in document order); `None` when the payload has no ledger. +fn ledger_rows(verify: Option<&Value>) -> Option>> { + let ledger = verify?.as_object()?.get("requirementLedger")?.as_array()?; + let mut out: HashMap> = HashMap::new(); + for raw in ledger { + let Some(raw) = raw.as_object() else { + continue; + }; + let Some(qp) = string_of(raw, "qualifiedPath") else { + continue; + }; + let diagnostics = raw + .get("diagnostics") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_object) + .map(|d| { + let f = |k: &str| string_of(d, k).unwrap_or_default(); + json!({ + "code": f("code"), + "severity": f("severity"), + "source": f("source"), + "message": f("message"), + }) + }) + .collect(); + let sup = raw + .get("supersededBy") + .and_then(Value::as_object) + .filter(|s| string_of(s, "ref").is_some()); + let sup_str = |k: &str| { + sup.and_then(|s| string_of(s, k)) + .unwrap_or_default() + .to_string() + }; + out.entry(qp.to_string()).or_default().push_back(Ledger { + digest: string_of(raw, "digest").unwrap_or_default().to_string(), + verdict: string_of(raw, "verdict").unwrap_or_default().to_string(), + diagnostics, + sup_ref: sup_str("ref"), + sup_resolves: sup.and_then(|s| s.get("resolves")) == Some(&Value::Bool(true)), + sup_target: sup_str("target"), + has_sup: sup.is_some(), + }); + } + Some(out) +} + +/// A value with every object's keys in code-unit order, as the canonical serializer writes them. +fn canonical_value(v: Value) -> Value { + match v { + Value::Array(items) => Value::Array(items.into_iter().map(canonical_value).collect()), + Value::Object(map) => { + let sorted: BTreeMap = map.into_iter().collect(); + Value::Object( + sorted + .into_iter() + .map(|(k, v)| (k, canonical_value(v))) + .collect(), + ) + } + other => other, + } +} diff --git a/server/rust/metaobjects/src/json.rs b/server/rust/metaobjects/src/json.rs index cc09e92de5..a8045d7904 100644 --- a/server/rust/metaobjects/src/json.rs +++ b/server/rust/metaobjects/src/json.rs @@ -14,11 +14,27 @@ use serde_json::{Map, Number, Value}; /// Serialize `value` as `JSON.stringify(value, null, 2)` would. pub fn to_js_pretty(value: &Value) -> String { let mut out = String::new(); - write_value(&mut out, value, 0); + write_value(&mut out, value, Some(0)); out } -fn write_value(out: &mut String, value: &Value, depth: usize) { +/// Serialize `value` as `JSON.stringify(value)` would: no whitespace. +pub fn to_js_compact(value: &Value) -> String { + let mut out = String::new(); + write_value(&mut out, value, None); + out +} + +/// A string as a JSON string literal, as `JSON.stringify(s)` writes it. +pub fn js_quote(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 2); + write_string(&mut out, s); + out +} + +/// `depth` is the indentation level of a pretty write, `None` for a compact one. +fn write_value(out: &mut String, value: &Value, depth: Option) { + let inner = depth.map(|d| d + 1); match value { Value::Null => out.push_str("null"), Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }), @@ -34,8 +50,8 @@ fn write_value(out: &mut String, value: &Value, depth: usize) { if i > 0 { out.push(','); } - newline(out, depth + 1); - write_value(out, item, depth + 1); + newline(out, inner); + write_value(out, item, inner); } newline(out, depth); out.push(']'); @@ -50,10 +66,10 @@ fn write_value(out: &mut String, value: &Value, depth: usize) { if i > 0 { out.push(','); } - newline(out, depth + 1); + newline(out, inner); write_string(out, key); - out.push_str(": "); - write_value(out, item, depth + 1); + out.push_str(if depth.is_some() { ": " } else { ":" }); + write_value(out, item, inner); } newline(out, depth); out.push('}'); @@ -61,7 +77,10 @@ fn write_value(out: &mut String, value: &Value, depth: usize) { } } -fn newline(out: &mut String, depth: usize) { +fn newline(out: &mut String, depth: Option) { + let Some(depth) = depth else { + return; + }; out.push('\n'); for _ in 0..depth { out.push_str(" "); @@ -205,6 +224,14 @@ mod tests { ); } + #[test] + fn compact_has_no_whitespace() { + let v: Value = serde_json::from_str(r#"{"b":[1.0,{"2":true}],"1":"x"}"#).unwrap(); + assert_eq!(to_js_compact(&v), r#"{"1":"x","b":[1,{"2":true}]}"#); + assert_eq!(to_js_compact(&json!([])), "[]"); + assert_eq!(js_quote("a\u{1}<>&"), "\"a\\u0001<>&\""); + } + #[test] fn control_characters_escape_like_javascript() { assert_eq!(to_js_pretty(&json!("a\"\u{1}\n")), "\"a\\\"\\u0001\\n\""); diff --git a/server/rust/metaobjects/src/lib.rs b/server/rust/metaobjects/src/lib.rs index 623428e964..55b797339c 100644 --- a/server/rust/metaobjects/src/lib.rs +++ b/server/rust/metaobjects/src/lib.rs @@ -8,11 +8,13 @@ pub mod collection; pub mod config; +pub mod docs_view; pub mod errors; pub mod json; pub mod library; pub mod loader; pub mod manifest; +pub mod meta_endpoint; pub mod metamodel_docs; pub mod naming; pub mod node; diff --git a/server/rust/metaobjects/src/loader.rs b/server/rust/metaobjects/src/loader.rs index 72b5b49f45..8d5943aa95 100644 --- a/server/rust/metaobjects/src/loader.rs +++ b/server/rust/metaobjects/src/loader.rs @@ -969,7 +969,7 @@ fn resolve_references(tree: &mut Tree, root: NodeId, top: &TopLevel) { .map(|(k, _)| k.clone()) .collect(); for name in names { - let ref_pkg = referrer_package(tree, top, id, &name, &decl_pkg); + let ref_pkg = referrer_package(tree, &top.objects, id, &name, &decl_pkg); resolve_attr(tree, top, id, &name, &ref_pkg, &decl_pkg); } } @@ -996,14 +996,20 @@ fn resolve_one( /// dimension's `@of` resolves in the package of the entity its `@via` walk reaches; /// a report's `@spine` in the package of its `@from`; everything else in the package /// of the top-level node that declares it. -fn referrer_package(tree: &Tree, top: &TopLevel, id: NodeId, attr: &str, decl_pkg: &str) -> String { +fn referrer_package( + tree: &Tree, + objects: &ObjectIndex, + id: NodeId, + attr: &str, + decl_pkg: &str, +) -> String { let node = tree.node(id); if node.type_name == "dimension" && attr == "of" { // ADR-0039: resolving: the @via that governs this @of may be inherited. if let (Some(Value::String(via)), Some(declaring)) = (tree.attr(id, "via"), node.parent) && !via.is_empty() { - return match dimension_via_terminal(tree, top, declaring, via) { + return match dimension_via_terminal(tree, objects, declaring, via) { Some(t) => tree.effective_package(t), None => decl_pkg.to_string(), }; @@ -1013,7 +1019,7 @@ fn referrer_package(tree: &Tree, top: &TopLevel, id: NodeId, attr: &str, decl_pk // ADR-0039: resolving: @from may be inherited. if let Some(Value::String(from)) = tree.attr(id, "from") && !from.is_empty() - && let Some(from_node) = top.objects.resolve(from, decl_pkg) + && let Some(from_node) = objects.resolve(from, decl_pkg) { return tree.effective_package(from_node); } @@ -1026,7 +1032,7 @@ fn referrer_package(tree: &Tree, top: &TopLevel, id: NodeId, attr: &str, decl_pk /// when the walk fails (the reporting pass reports why). fn dimension_via_terminal( tree: &Tree, - top: &TopLevel, + objects: &ObjectIndex, declaring: NodeId, via: &str, ) -> Option { @@ -1037,11 +1043,46 @@ fn dimension_via_terminal( for hop_name in parts { any = true; let (hop, is_ref) = find_hop(tree, current, hop_name)?; - current = top.objects.hop_target(tree, hop, is_ref)?; + current = objects.hop_target(tree, hop, is_ref)?; } any.then_some(current) } +/// The object each value of the reference attribute `attr` that `id` declares itself +/// resolves to, as the loader resolved it (ADR-0059 R3-R5): one entry for a string value, +/// one per item for a list of strings, none for anything else. An entry is `None` for a +/// value that resolves to no object. `objects` is the loaded root's [`ObjectIndex`]. +/// +/// The loader rewrites a resolved value to its canonical spelling and keeps no node for it, +/// so a reader that needs the node (the docs view's links) asks here, in the package the +/// loader resolved that attribute in. +pub fn reference_targets( + tree: &Tree, + objects: &ObjectIndex, + id: NodeId, + attr: &str, +) -> Vec> { + // ADR-0039: own — the layer that declares the attribute is the one the loader resolved. + let Some(a) = tree.own_attr(id, attr) else { + return Vec::new(); + }; + let decl_pkg = tree.effective_package(tree.top_level_of(id)); + let pkg = referrer_package(tree, objects, id, attr, &decl_pkg); + let one = |s: &str| { + (!s.is_empty()) + .then(|| objects.resolve(split_child_tail(s).0, &pkg)) + .flatten() + }; + match &a.value { + Value::String(s) => vec![one(s)], + Value::Array(items) if items.iter().all(Value::is_string) => items + .iter() + .map(|v| one(v.as_str().unwrap_or_default())) + .collect(), + _ => Vec::new(), + } +} + fn resolve_attr( tree: &mut Tree, top: &TopLevel, diff --git a/server/rust/metaobjects/src/meta_endpoint.rs b/server/rust/metaobjects/src/meta_endpoint.rs new file mode 100644 index 0000000000..59df283f0d --- /dev/null +++ b/server/rust/metaobjects/src/meta_endpoint.rs @@ -0,0 +1,113 @@ +//! The running application's metadata routes, framework-free: `GET /_meta` (the effective +//! canonical model) and `GET /_meta/docs` (the docs view the explorer reads), as +//! `docs/features/metadata-api.md` specifies them. The same symbols as TypeScript's +//! `@metaobjectsdev/runtime-ts` and Java's `MetaEndpoint`. +//! +//! Both routes are opt-in: nothing here mounts anything. The host mounts them on its own web +//! framework, behind the guard the rest of its API uses, so this crate takes no web dependency. +//! With axum, for example: +//! +//! ```text +//! // root: the model this app loaded. Built once: the model does not change after load. +//! let docs = Arc::new(meta_endpoint::docs(&tree, root, None)); +//! let route = format!("/api{}", meta_endpoint::META_DOCS_ROUTE_PATH); +//! app.route(&route, get(move |headers: HeaderMap| async move { +//! let tag = headers.get(IF_NONE_MATCH).and_then(|v| v.to_str().ok()); +//! let common = [(ETAG, docs.etag.clone()), (CACHE_CONTROL, "no-cache".into())]; +//! if docs.matches(tag) { +//! (StatusCode::NOT_MODIFIED, common).into_response() +//! } else { +//! (common, [(CONTENT_TYPE, "application/json")], docs.body.clone()).into_response() +//! } +//! })); +//! ``` + +use serde_json::Value; + +use crate::docs_view; +use crate::node::{NodeId, Tree}; +use crate::serializer::canonical_serialize_effective; + +/// Where the model is served, under the application's API prefix. +pub const META_ROUTE_PATH: &str = "/_meta"; +/// Where the docs view is served, beside the model. +pub const META_DOCS_ROUTE_PATH: &str = "/_meta/docs"; + +/// The `/_meta` body: the model as the effective canonical serializer writes it. +pub fn meta_json(tree: &Tree, root: NodeId) -> String { + canonical_serialize_effective(tree, root) +} + +/// The `/_meta/docs` body: the docs view of the loaded model, with the routes the application +/// mounts when it names them (`[{ node, method, path }]`, `node` a resolution key). It carries no +/// requirement ledger and no generated files: those are build facts, which the docs-site +/// generator reads. +pub fn meta_docs_json(tree: &Tree, root: NodeId, routes: Option<&Value>) -> String { + docs_view::serialize(&docs_view::build(tree, root, None, None, routes)) +} + +/// The docs view body, built once, with its ETag. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Docs { + pub body: String, + pub etag: String, +} + +impl Docs { + /// Whether a request's `If-None-Match` names this body, so the answer is a 304. + pub fn matches(&self, if_none_match: Option<&str>) -> bool { + etag_matches(if_none_match, &self.etag) + } +} + +/// The docs view of the loaded model and its ETag ([`meta_docs_json`]). +pub fn docs(tree: &Tree, root: NodeId, routes: Option<&Value>) -> Docs { + let body = meta_docs_json(tree, root, routes); + let etag = meta_docs_etag(&body); + Docs { body, etag } +} + +/// A strong ETag for a docs view body: its length and the 32-bit FNV-1a hash of its UTF-16 code +/// units, quoted, the value TypeScript's mount sends. A client compares it and never parses it. +pub fn meta_docs_etag(body: &str) -> String { + let mut h: u32 = 0x811c_9dc5; + let mut units: usize = 0; + for c in body.encode_utf16() { + h ^= u32::from(c); + h = h.wrapping_mul(0x0100_0193); + units += 1; + } + format!("\"{units:x}-{h:08x}\"") +} + +/// Whether an `If-None-Match` header value names `etag` (or is `*`). +pub fn etag_matches(if_none_match: Option<&str>, etag: &str) -> bool { + if_none_match.is_some_and(|v| { + v.split(',').any(|t| { + let t = t.trim(); + let t = t.strip_prefix("W/").unwrap_or(t); + t == "*" || t == etag + }) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_etag_counts_utf16_units() { + // metaDocsEtag("é😀") in TypeScript: three UTF-16 units. + assert_eq!(meta_docs_etag("é\u{1F600}"), "\"3-44cc4da1\""); + } + + #[test] + fn if_none_match_lists_weak_tags_and_the_wildcard() { + let tag = "\"3-44cc4da1\""; + assert!(etag_matches(Some("\"x\", W/\"3-44cc4da1\""), tag)); + assert!(etag_matches(Some("*"), tag)); + assert!(!etag_matches(Some("\"x\""), tag)); + assert!(!etag_matches(None, tag)); + assert!(!etag_matches(Some(""), tag)); + } +} diff --git a/server/rust/metaobjects/src/providers.rs b/server/rust/metaobjects/src/providers.rs index c1254ef409..3f1415c142 100644 --- a/server/rust/metaobjects/src/providers.rs +++ b/server/rust/metaobjects/src/providers.rs @@ -238,6 +238,10 @@ fn children_of(v: &Value) -> Vec { fn parse_definition(file: &str, raw: &str) -> ProviderDefinition { let doc: Value = serde_json::from_str(raw) .unwrap_or_else(|e| panic!("spec/metamodel/{file}.json is not valid JSON: {e}")); + definition_of(&doc) +} + +fn definition_of(doc: &Value) -> ProviderDefinition { let types = doc .get("types") .and_then(Value::as_array) @@ -276,7 +280,7 @@ fn parse_definition(file: &str, raw: &str) -> ProviderDefinition { }) .unwrap_or_default(); ProviderDefinition { - provider: s(&doc, "provider").unwrap_or_default(), + provider: s(doc, "provider").unwrap_or_default(), types, extends, } @@ -484,6 +488,17 @@ fn define_from_data( Ok(out) } +/// Register a provider definition written in the shared `spec/metamodel/*.json` format +/// (its `types` and its `extends`), as the built-in providers register theirs. This is how +/// an application, or a test, adds vocabulary the core does not ship from data: call it +/// inside [`TypeRegistry::run_as_provider`] before sealing the registry. +pub fn apply_provider_definition( + registry: &mut TypeRegistry, + definition: &Value, +) -> Result<(), MetaError> { + apply_definition(registry, &definition_of(definition)) +} + fn apply_definition( registry: &mut TypeRegistry, data: &ProviderDefinition, diff --git a/server/rust/metaobjects/tests/docs_view_conformance.rs b/server/rust/metaobjects/tests/docs_view_conformance.rs new file mode 100644 index 0000000000..420731e69d --- /dev/null +++ b/server/rust/metaobjects/tests/docs_view_conformance.rs @@ -0,0 +1,119 @@ +//! The docs view corpus (`fixtures/explorer-conformance/`, `docs/features/docs-view.md`): each +//! fixture's project is loaded strictly, its committed optional inputs are read, and +//! [`docs_view::build`] must reproduce the fixture's `expected.json` byte for byte, as the +//! TypeScript reference does. A fixture's `provider.json` is registered before loading. +//! +//! Set `DOCS_VIEW_ACTUAL_DIR` to write each actual view there, for diffing. + +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +use metaobjects::collection::resolve_collection; +use metaobjects::docs_view; +use metaobjects::loader::Loader; +use metaobjects::naming::NamingRegistry; +use metaobjects::providers::{apply_provider_definition, compose_registry, core_providers}; + +fn corpus() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/explorer-conformance") +} + +fn read_json(dir: &Path, name: &str) -> Option { + let text = std::fs::read_to_string(dir.join(name)).ok()?; + Some(serde_json::from_str(&text).expect("a fixture input is JSON")) +} + +fn actual(dir: &Path) -> String { + let mut registry = compose_registry(&core_providers()).expect("the core providers compose"); + if let Some(def) = read_json(dir, "provider.json") { + let id = def["provider"].as_str().unwrap_or("fixture").to_string(); + registry + .run_as_provider(&id, |r| apply_provider_definition(r, &def)) + .expect("the fixture's provider registers"); + } + registry.seal(); + let project = dir.join("project"); + let collection = resolve_collection(&project, None, &NamingRegistry::builtin()) + .expect("the fixture's project resolves"); + let (sources, read_errors) = collection.read_sources(); + assert!(read_errors.is_empty(), "{read_errors:?}"); + let loaded = Loader::new(®istry).strict(true).load_sources(&sources); + assert!( + loaded.errors.is_empty(), + "{}: {:?}", + dir.display(), + loaded.errors + ); + let view = docs_view::build( + &loaded.tree, + loaded.root, + read_json(dir, "verify.json").as_ref(), + read_json(dir, "hashes.json").as_ref(), + read_json(dir, "routes.json").as_ref(), + ); + docs_view::serialize(&view) +} + +#[test] +fn every_fixture_reproduces_its_expected_view() { + let mut names: Vec = std::fs::read_dir(corpus()) + .expect("the corpus exists") + .filter_map(Result::ok) + .filter(|e| e.path().is_dir()) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + assert!(names.len() >= 3, "the corpus has its fixtures: {names:?}"); + let out_dir = std::env::var_os("DOCS_VIEW_ACTUAL_DIR").map(PathBuf::from); + let mut failed = Vec::new(); + for name in &names { + let dir = corpus().join(name); + let got = actual(&dir); + if let Some(out) = &out_dir { + std::fs::create_dir_all(out).unwrap(); + std::fs::write(out.join(format!("{name}.json")), &got).unwrap(); + } + let want = std::fs::read_to_string(dir.join("expected.json")).unwrap(); + if got != want { + failed.push(name.clone()); + } + } + assert!( + failed.is_empty(), + "docs view differs from expected.json for {failed:?}" + ); +} + +#[test] +fn the_view_is_deterministic() { + let dir = corpus().join("shop"); + assert_eq!(actual(&dir), actual(&dir)); +} + +/// `GET /_meta/docs` is the docs view of the loaded model alone: over the fixture with no build +/// inputs, the route's body is that fixture's expected view, and its ETag is TypeScript's. +#[test] +fn the_docs_route_serves_the_model_alone_view() { + use metaobjects::meta_endpoint::{META_DOCS_ROUTE_PATH, META_ROUTE_PATH, docs, meta_json}; + let dir = corpus().join("model-alone"); + let registry = { + let mut r = compose_registry(&core_providers()).unwrap(); + r.seal(); + r + }; + let collection = + resolve_collection(&dir.join("project"), None, &NamingRegistry::builtin()).unwrap(); + let (sources, _) = collection.read_sources(); + let loaded = Loader::new(®istry).strict(true).load_sources(&sources); + let d = docs(&loaded.tree, loaded.root, None); + assert_eq!( + d.body, + std::fs::read_to_string(dir.join("expected.json")).unwrap() + ); + // metaDocsEtag(body) in @metaobjectsdev/runtime-ts over the same bytes. + assert_eq!(d.etag, "\"4c8c-0068e2ba\""); + assert!(d.matches(Some("\"4c8c-0068e2ba\""))); + assert_eq!(META_DOCS_ROUTE_PATH, format!("{META_ROUTE_PATH}/docs")); + assert!(meta_json(&loaded.tree, loaded.root).starts_with('{')); +} From a5417e2e7760129cf3f6c51a32fa8fdb526f579f Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 06:12:00 -0500 Subject: [PATCH 2/4] no-mistakes(review): Close docs-site skip gaps, init list, dead API --- docs/ports/rust.md | 3 +- .../GenSkipConformanceTests.cs | 26 +++++++++++++ .../csharp/MetaObjects.Codegen/CodegenCli.cs | 10 ++++- .../csharp/MetaObjects.Codegen/Generator.cs | 8 ++++ .../Generators/DocsSiteGenerator.cs | 3 ++ server/python/src/metaobjects/cli.py | 8 ++++ .../src/metaobjects/codegen/generator.py | 8 ++++ .../codegen/generators/docs_site_generator.py | 13 ++++--- .../python/tests/test_gen_skip_conformance.py | 38 +++++++++++++++++++ server/rust/metaobjects-cli/src/lib.rs | 3 +- server/rust/metaobjects-codegen/build.rs | 12 ++++-- .../rust/metaobjects-codegen/src/docs_site.rs | 25 +++++++----- server/rust/metaobjects-codegen/src/engine.rs | 7 ++++ .../rust/metaobjects-codegen/src/generator.rs | 22 +++++++++++ .../metaobjects-codegen/src/generator_list.rs | 22 ++++++++--- .../metaobjects-codegen/tests/docs_site.rs | 34 ++++++++++++++++- server/rust/metaobjects/src/docs_view.rs | 5 --- 17 files changed, 212 insertions(+), 35 deletions(-) diff --git a/docs/ports/rust.md b/docs/ports/rust.md index b4aeb48501..2dd78f4e7e 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -70,7 +70,8 @@ and the same `git` + `rev` on a `metaobjects` dependency). The candidate log The generators a project runs are the list in `metaobjects.config.json` at the project root, the way the other ports choose theirs (`metaobjects.config.ts`, `codegen/Generators.cs`, the pom, `metaobjects.config.yaml`). `cargo meta init` writes every shipped generator but the opt-in -transport, `service-routes`, which `cargo meta init --transport` adds; delete a line to stop running +ones: the transport, `service-routes`, which `cargo meta init --transport` adds, and the two docs +generators, `metamodel-docs` and `docs-site`, which you add by name. Delete a line to stop running one, and no eject is needed: ```json diff --git a/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs index ffa928e955..3ab19e77c6 100644 --- a/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs @@ -53,6 +53,15 @@ public sealed class GenSkipConformanceTests : IDisposable ]}} """; + private const string NotePrompt = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.value": { "name": "NoteRequest", "children": [ + { "field.string": { "name": "text" } } + ]}}, + { "template.prompt": { "name": "NotePrompt", "@payloadRef": "NoteRequest", "@textRef": "note-text", "@format": "text" } } + ]}} + """; + /// A generator that declares an extra input and can mark itself uncacheable. private sealed class Custom(bool cacheable) : IGenerator { @@ -316,6 +325,23 @@ public void An_entities_run_renders_never_stores_and_leaves_the_full_run_key_alo Assert.Contains(GenSkipped, RunGen(Declared()).Out); } + [Fact] + public void Editing_a_prompt_beside_the_metadata_regenerates_the_docs_site() + { + File.WriteAllText(P("metaobjects/meta.note.json"), NotePrompt); + File.WriteAllText(P("metaobjects/note-text.mustache"), "first text"); + IReadOnlyList declared = [.. Declared(), new DocsSiteGenerator()]; + var first = RunGen(declared); + Assert.True(first.Exit == 0, first.Out + first.Err); + var model = Path.Combine(OutDir, "site", "explorer-model.js"); + Assert.Contains("first text", File.ReadAllText(model)); + + File.WriteAllText(P("metaobjects/note-text.mustache"), "second text"); + Assert.Equal("regenerate", GenDecision(declared, [])); + Assert.Contains("second text", File.ReadAllText(model)); + Assert.DoesNotContain("first text", File.ReadAllText(model)); + } + [Fact] public void An_edit_regenerates_and_the_next_run_skips_again() { diff --git a/server/csharp/MetaObjects.Codegen/CodegenCli.cs b/server/csharp/MetaObjects.Codegen/CodegenCli.cs index cdfba9eab7..1560fa76e7 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenCli.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenCli.cs @@ -709,6 +709,12 @@ private static int RunGenArgs(string[] rest, IReadOnlyList declared, TemplateSpec = a.TemplateSpecPath, Entities = a.Entities, EmitAbstractShapes = a.EmitAbstractShapes, Strict = a.Strict, Baseline = a.Baseline, }; + /// The extra inputs of a run: every entry's , and the + /// metadata directory when an entry reads files beside the metadata. + private static IEnumerable KeyExtras(IReadOnlyList suite, ResolvedMetadata meta) => + suite.SelectMany(g => g.ExtraInputs) + .Concat(suite.Any(g => g.ReadsMetadataDirectory) ? [meta.Directory] : []); + private static int RunGenCore(string[] rest, IReadOnlyList declared, KeyGate gate, Func? configure) { var a = OwnedArgs.Parse(rest, GenCommandName, GenValueFlags, GenBoolFlags); @@ -841,7 +847,7 @@ private static int RunGenCore(string[] rest, IReadOnlyList declared, var cwd = Directory.GetCurrentDirectory(); var modelHash = ModelHash.Of(genLoad.Root).Model; var identity = GenFingerprint.Key(GenFingerprint.IdentityEntries( - projectRoot, cwd, KeyOptions(a, a.OutDir, a.Namespace ?? meta.Namespace), suite.SelectMany(g => g.ExtraInputs))); + projectRoot, cwd, KeyOptions(a, a.OutDir, a.Namespace ?? meta.Namespace), KeyExtras(suite, meta))); // An --entities run is narrowed and forces exactly those entities: it never skips, never // stores a key, and leaves the stored full-run key alone (it can neither write nor satisfy it). var wholeRun = a.Entities is null; @@ -1098,7 +1104,7 @@ private static int RunVerifyArgs(string[] rest, IReadOnlyList declar projectRoot, ModelHash.Of(load.Root).Model, GenFingerprint.Key(GenFingerprint.IdentityEntries( projectRoot, Directory.GetCurrentDirectory(), KeyOptions(a, a.OutDir, a.Namespace ?? meta.Namespace), - suite.SelectMany(g => g.ExtraInputs))), + KeyExtras(suite, meta))), a.Full)) { Console.WriteLine($"{VerifyCommandName}: OK (nothing changed since the last gen; --full renders and compares)"); diff --git a/server/csharp/MetaObjects.Codegen/Generator.cs b/server/csharp/MetaObjects.Codegen/Generator.cs index 36fffe6a4b..5fa00a3946 100644 --- a/server/csharp/MetaObjects.Codegen/Generator.cs +++ b/server/csharp/MetaObjects.Codegen/Generator.cs @@ -673,6 +673,12 @@ public interface IGenerator /// The runner runs every such entry after every other one, keeping their declared order. /// bool ReadsRunOutput => false; + + /// + /// ADR-0064 — whether this entry reads files beside the metadata, in the metadata directory + /// (prompt texts). That directory then joins the run's identity, whole. + /// + bool ReadsMetadataDirectory => false; } /// A generator entry's handEdits setting: what a run does with a hand-edited file. @@ -714,6 +720,8 @@ internal sealed class HandEditsGenerator(IGenerator inner, HandEdits handEdits) public IReadOnlyList ExtraInputs => Inner.ExtraInputs; public bool ReadsRunOutput => Inner.ReadsRunOutput; /// + public bool ReadsMetadataDirectory => Inner.ReadsMetadataDirectory; + /// public IEnumerable Generate(GenContext ctx) => Inner.Generate(ctx); } diff --git a/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs index 3bc5525f09..f9f60186a9 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs @@ -54,6 +54,9 @@ public sealed class DocsSiteGenerator : IGenerator public IReadOnlyList ExtraInputs => new[] { OwnedDocsSiteDir, Prompts, VerifyFile, RoutesFile }.OfType().ToList(); + /// Prompt texts beside the metadata are read too, so the metadata directory is an input. + public bool ReadsMetadataDirectory => true; + public IEnumerable Generate(GenContext ctx) { // A run that names no project reads nothing beside the model it was handed: no committed diff --git a/server/python/src/metaobjects/cli.py b/server/python/src/metaobjects/cli.py index 536fc3f7f4..b5ed92deb6 100644 --- a/server/python/src/metaobjects/cli.py +++ b/server/python/src/metaobjects/cli.py @@ -137,6 +137,7 @@ SelectedGenerator, generator_cacheable, generator_extra_inputs, + generator_reads_metadata_dir, ) from metaobjects.codegen import model_key, skip from metaobjects.codegen.generators.entity_model import entity_model @@ -1844,6 +1845,13 @@ def selected(gen: Generator, token: str) -> bool: every = [g for _t, gens, spec_gens, _o in plan for g in (*gens, *spec_gens)] skip_info.cacheable = all(generator_cacheable(g) for g in every) skip_info.extras = {p for g in every for p in generator_extra_inputs(g)} + if any(generator_reads_metadata_dir(g) for g in every): + meta_dir = Path(config.metadata_dir()).resolve() + try: + meta_rel = meta_dir.relative_to(Path(project_root or ".").resolve()).as_posix() + except ValueError: + meta_rel = str(meta_dir) + skip_info.extras.add(meta_rel) skip_info.extra_entries = skip.extras_entries( Path(project_root or "."), skip_info.extras) diff --git a/server/python/src/metaobjects/codegen/generator.py b/server/python/src/metaobjects/codegen/generator.py index ea689e7d65..87d5380f70 100644 --- a/server/python/src/metaobjects/codegen/generator.py +++ b/server/python/src/metaobjects/codegen/generator.py @@ -79,6 +79,9 @@ class Generator(Protocol): - ``declared_extra_inputs: tuple[str, ...]`` (default ``()``). Project-relative paths the generator reads beyond the model, the config and the template roots; their content is part of the run's key. + - ``reads_metadata_dir: bool`` (default ``False``). ``True`` means the generator reads + files beside the metadata (prompt texts); the metadata directory is then part of the + run's key, whole. """ name: str @@ -143,6 +146,11 @@ def generator_extra_inputs(gen: object) -> tuple[str, ...]: return tuple(getattr(gen, "declared_extra_inputs", ()) or ()) +def generator_reads_metadata_dir(gen: object) -> bool: + """Whether ``gen`` reads files beside the metadata, in the metadata directory.""" + return bool(getattr(gen, "reads_metadata_dir", False)) + + def per_entity( fn: Callable[[MetaObject, GenContext], "EmittedFile | list[EmittedFile]"], ) -> Callable[[GenContext], list[EmittedFile]]: diff --git a/server/python/src/metaobjects/codegen/generators/docs_site_generator.py b/server/python/src/metaobjects/codegen/generators/docs_site_generator.py index e0626101f9..f01c3b4c7e 100644 --- a/server/python/src/metaobjects/codegen/generators/docs_site_generator.py +++ b/server/python/src/metaobjects/codegen/generators/docs_site_generator.py @@ -166,6 +166,8 @@ class DocsSiteGenerator: name = "docs-site" #: The runner runs a generator that reads the run's output after every other one. reads_run_output = True + #: Prompt texts beside the metadata are read, so the metadata directory is an input. + reads_metadata_dir = True def __init__( self, @@ -182,12 +184,13 @@ def __init__( self.prompts = prompts self.verify_file = verify_file self.routes_file = routes_file - #: The owned theme, the prompts directory and the verify and routes files are read beside - #: the model (ADR-0064): editing one regenerates. The hash manifest is not an input: the - #: files the site lists are this run's and the manifest's, and the whole-run skip already - #: re-runs when the manifest gains, loses or changes a file. + #: The owned theme, ``templates/``, the prompts directory and the verify and routes files + #: are read beside the model (ADR-0064), and so is the metadata directory + #: (``reads_metadata_dir``): editing one regenerates. The hash manifest is not an input: + #: the files the site lists are this run's and the manifest's, and the whole-run skip + #: already re-runs when the manifest gains, loses or changes a file. self.declared_extra_inputs: tuple[str, ...] = tuple( - p for p in (OWNED_DOCS_SITE_DIR, prompts, verify_file, routes_file) if p + p for p in (OWNED_DOCS_SITE_DIR, "templates", prompts, verify_file, routes_file) if p ) def generate(self, ctx: GenContext) -> list[EmittedFile]: diff --git a/server/python/tests/test_gen_skip_conformance.py b/server/python/tests/test_gen_skip_conformance.py index 75b5e0dd01..e78d9ed3ba 100644 --- a/server/python/tests/test_gen_skip_conformance.py +++ b/server/python/tests/test_gen_skip_conformance.py @@ -429,3 +429,41 @@ def test_a_run_that_names_entities_renders_and_leaves_the_full_run_key_alone( # It neither wrote nor forgot the full-run key, so the next full run still skips. assert stored.read_bytes() == key assert h.gen() == (0, True) + + +_NOTE_PROMPT = { + "metadata.root": { + "package": "skip", + "children": [ + {"object.value": {"name": "NoteRequest", "children": [ + {"field.string": {"name": "text"}}, + ]}}, + {"template.prompt": { + "name": "NotePrompt", "@payloadRef": "NoteRequest", + "@textRef": "note-text", "@format": "text", + }}, + ], + } +} + + +def test_editing_a_prompt_in_templates_regenerates_the_docs_site( + tmp_path: Path, monkeypatch, capsys +) -> None: + project = _project(tmp_path) + (tmp_path / "metaobjects" / "meta.note.json").write_text(json.dumps(_NOTE_PROMPT)) + (tmp_path / "templates").mkdir() + prompt = tmp_path / "templates" / "note-text.mustache" + prompt.write_text("first text") + project.write_config("[entity, docs-site]") + h = Harness(project, monkeypatch, capsys) + rc, skipped = h.gen() + assert rc == 0 and not skipped, h.out + h.err + model = tmp_path / "generated" / "site" / "explorer-model.js" + assert "first text" in model.read_text() + + prompt.write_text("second text") + rc, skipped = h.gen() + assert rc == 0 and not skipped, "an edited prompt is an input" + text = model.read_text() + assert "second text" in text and "first text" not in text diff --git a/server/rust/metaobjects-cli/src/lib.rs b/server/rust/metaobjects-cli/src/lib.rs index 7f6a47de85..4ea4c4c6ca 100644 --- a/server/rust/metaobjects-cli/src/lib.rs +++ b/server/rust/metaobjects-cli/src/lib.rs @@ -95,7 +95,8 @@ OPTIONS (everywhere): GENERATORS: a project chooses what runs in metaobjects.config.json, `{ \"generators\": [..] }`, by name. Edit the list; no eject is needed. With no such file every generator runs but the -opt-in transport (service-routes), which `init --transport` lists. +opt-in ones: the transport (service-routes), which `init --transport` lists, and the docs +generators (metamodel-docs, docs-site), which run only when listed. ENTITY names limit `gen` to the crates that contain them plus the crates those depend on. Such a run never skips, never stores the skip key and never removes a file. diff --git a/server/rust/metaobjects-codegen/build.rs b/server/rust/metaobjects-codegen/build.rs index b32ec70571..53a78f84ec 100644 --- a/server/rust/metaobjects-codegen/build.rs +++ b/server/rust/metaobjects-codegen/build.rs @@ -20,10 +20,12 @@ fn collect(dir: &Path, out: &mut Vec) { for p in entries { if p.is_dir() { collect(&p, out); - } else if p - .extension() - .is_some_and(|e| e == "rs" || e == "toml" || e == "mustache" || e == "json") - { + } else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| { + matches!( + e, + "rs" | "toml" | "mustache" | "json" | "js" | "css" | "html" + ) + }) { out.push(p); } } @@ -39,6 +41,8 @@ fn main() { // The shipped Mustache templates and the embedded metamodel provider definitions. manifest.join("templates"), manifest.join("../metaobjects/data"), + // The shipped explorer app the docs-site generator copies. + manifest.join("explorer-app"), ]; let mut hasher = sha256::Sha256::new(); for root in &roots { diff --git a/server/rust/metaobjects-codegen/src/docs_site.rs b/server/rust/metaobjects-codegen/src/docs_site.rs index 433bd945d7..9a37dbfe55 100644 --- a/server/rust/metaobjects-codegen/src/docs_site.rs +++ b/server/rust/metaobjects-codegen/src/docs_site.rs @@ -167,6 +167,10 @@ impl Generator for DocsSiteGenerator { true } + fn reads_source_dirs(&self) -> bool { + true + } + fn configure(&self, options: &Options) -> Result, GenError> { Ok(Box::new(DocsSite::from_options(options)?)) } @@ -185,11 +189,12 @@ impl Generator for DocsSite { format!("{NAME}:{FORMAT}:{self:?}") } - /// The owned theme, the prompts directory and the verify and routes files are read beside - /// the model (ADR-0064): editing one regenerates. The hash manifest is not an input here: - /// the whole-run skip already re-runs when a recorded file changes or goes. + /// The owned theme, `templates/`, the prompts directory and the verify and routes files are + /// read beside the model (ADR-0064), and so are the metadata directories + /// ([`Generator::reads_source_dirs`]): editing one regenerates. The hash manifest is not an + /// input here: the whole-run skip already re-runs when a recorded file changes or goes. fn extra_inputs(&self) -> Vec { - let mut inputs = vec![OWNED_DOCS_SITE_DIR.to_string()]; + let mut inputs = vec![OWNED_DOCS_SITE_DIR.to_string(), TEMPLATES_DIR.to_string()]; inputs.extend(self.prompts.clone()); inputs.extend(self.verify_file.clone()); inputs.extend(self.routes_file.clone()); @@ -200,6 +205,10 @@ impl Generator for DocsSite { true } + fn reads_source_dirs(&self) -> bool { + true + } + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { let project = &ctx.collection.config_dir; let verify = self @@ -292,12 +301,8 @@ impl DocsSite { dirs.push(d); } }; - for root in &ctx.collection.source_roots { - add(if root.is_dir() { - root.clone() - } else { - root.parent().map(Path::to_path_buf).unwrap_or_default() - }); + for dir in crate::generator::source_dirs(&ctx.collection.source_roots) { + add(dir); } add(project.join(TEMPLATES_DIR)); if let Some(p) = &self.prompts { diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index 6a8f9ccd24..0e61dd4ffc 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -728,6 +728,13 @@ fn prepare<'g>( let digest = hash_tree(&project_root.join(&extra)); entries.push(InputEntry::new(KIND_EXTRA, extra, digest)); } + if g.reads_source_dirs() { + for dir in crate::generator::source_dirs(&loaded.collection.source_roots) { + let name = dir.strip_prefix(&project_root).unwrap_or(&dir); + let name = name.to_string_lossy().replace('\\', "/"); + entries.push(InputEntry::new(KIND_EXTRA, name, hash_tree(&dir))); + } + } } // The owned generator crate, whole: the generator list is the adopter's file and may pull // in any module beside it (`mod util;`), so naming the files the scaffold writes would diff --git a/server/rust/metaobjects-codegen/src/generator.rs b/server/rust/metaobjects-codegen/src/generator.rs index c582a43182..bf223860ef 100644 --- a/server/rust/metaobjects-codegen/src/generator.rs +++ b/server/rust/metaobjects-codegen/src/generator.rs @@ -6,6 +6,7 @@ use std::collections::BTreeSet; use std::fmt; +use std::path::{Path, PathBuf}; use metaobjects::collection::Collection; use metaobjects::node::{NodeId, Tree}; @@ -176,6 +177,27 @@ pub trait Generator { false } + /// Whether this generator reads files beside the metadata, in the directories the model was + /// loaded from (prompt texts). Those directories are then part of the skip key, whole. + fn reads_source_dirs(&self) -> bool { + false + } + /// Produce the generator's files for the loaded model. fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError>; } + +/// The directories the model was loaded from: each source root, or the directory of a root +/// that is a file. +pub(crate) fn source_dirs(roots: &[PathBuf]) -> Vec { + roots + .iter() + .map(|root| { + if root.is_dir() { + root.clone() + } else { + root.parent().map(Path::to_path_buf).unwrap_or_default() + } + }) + .collect() +} diff --git a/server/rust/metaobjects-codegen/src/generator_list.rs b/server/rust/metaobjects-codegen/src/generator_list.rs index 04dc05f103..9723b5fbe1 100644 --- a/server/rust/metaobjects-codegen/src/generator_list.rs +++ b/server/rust/metaobjects-codegen/src/generator_list.rs @@ -177,6 +177,9 @@ pub fn check(names: &[String], available: &[&str]) -> Result<(), String> { Ok(()) } +/// The opt-in axum transport, the one opt-in generator `cargo meta init --transport` lists. +const TRANSPORT: &str = "service-routes"; + /// Every shipped generator's name, in the order a run applies them. pub fn shipped_names() -> Vec<&'static str> { eject::REFERENCES.iter().map(|r| r.name).collect() @@ -198,13 +201,13 @@ fn example() -> String { ) } -/// The text `cargo meta init` writes: every shipped generator but the opt-in ones, and those -/// too with `opt_in`, so a new project generates what it always has and removes one by deleting -/// a line. -pub fn scaffold(opt_in: bool) -> String { +/// The text `cargo meta init` writes: every shipped generator but the opt-in ones, and the axum +/// transport (`service-routes`) too with `transport`, so a new project generates what it always +/// has and removes one by deleting a line. The docs generators are never listed. +pub fn scaffold(transport: bool) -> String { let items = eject::REFERENCES .iter() - .filter(|r| opt_in || !r.opt_in) + .filter(|r| !r.opt_in || (transport && r.name == TRANSPORT)) .map(|r| format!(" \"{}\"", r.name)) .collect::>() .join(",\n"); @@ -238,11 +241,18 @@ mod tests { ); assert!(check(&names(&parse(&scaffold(false)).unwrap()), &shipped_names()).is_ok()); let all = names(&parse(&scaffold(true)).unwrap()); - assert_eq!(all, s(&shipped_names())); + let mut without_transport = all.clone(); + without_transport.retain(|n| n != "service-routes"); + assert_eq!(all.len(), without_transport.len() + 1); + assert_eq!(without_transport, names(&parse(&scaffold(false)).unwrap())); assert!(check(&all, &shipped_names()).is_ok()); + for docs in ["metamodel-docs", "docs-site"] { + assert!(!all.iter().any(|n| n == docs), "{docs}"); + } assert!( !runs_unlisted("service-routes") && !runs_unlisted("metamodel-docs") + && !runs_unlisted("docs-site") && runs_unlisted("entity") ); } diff --git a/server/rust/metaobjects-codegen/tests/docs_site.rs b/server/rust/metaobjects-codegen/tests/docs_site.rs index dba9c2ba74..d7fcd71420 100644 --- a/server/rust/metaobjects-codegen/tests/docs_site.rs +++ b/server/rust/metaobjects-codegen/tests/docs_site.rs @@ -12,7 +12,7 @@ use metaobjects_codegen::docs_site::{ read_prompt_texts, }; use metaobjects_codegen::sha256::sha256_hex; -use metaobjects_codegen::{RunOptions, run, shipped_generators, verify}; +use metaobjects_codegen::{Outcome, RunOptions, run, shipped_generators, verify}; use serde_json::Value; fn repo() -> PathBuf { @@ -218,6 +218,38 @@ fn a_run_writes_the_explorer_over_the_files_the_manifest_records() { ); } +#[test] +fn editing_a_prompt_beside_the_metadata_or_in_templates_regenerates_the_site() { + for dir in ["metaobjects", "templates"] { + let p = Scratch::project(&format!("docs-site-prompt-{dir}"), &[]); + copy_dir(&fixture("shop").join("project"), p.path()); + std::fs::remove_dir_all(p.path().join("prompts")).unwrap(); + let prompt = format!("{dir}/shop/order-note.mustache"); + p.write(&prompt, "first text"); + p.write( + "metaobjects.config.json", + r#"{ "generators": [{ "name": "docs-site", "options": { "subDir": "" } }] }"#, + ); + let mut opts = RunOptions::new(p.path()); + opts.out_dir = PathBuf::from("generated"); + run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("gen failed: {e}")); + assert!(p.read("generated/explorer-model.js").contains("first text")); + + p.write(&prompt, "second text"); + let r = run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("gen failed: {e}")); + assert_ne!( + r.outcome, + Outcome::Skipped, + "{dir}: an edited prompt is an input" + ); + let model = p.read("generated/explorer-model.js"); + assert!( + model.contains("second text") && !model.contains("first text"), + "{dir}: the site carries the edited prompt" + ); + } +} + #[test] fn a_project_with_no_list_does_not_run_it() { let p = Scratch::project("docs-site-unlisted", &common::shop_files()); diff --git a/server/rust/metaobjects/src/docs_view.rs b/server/rust/metaobjects/src/docs_view.rs index bf8feb95be..e8e90b5578 100644 --- a/server/rust/metaobjects/src/docs_view.rs +++ b/server/rust/metaobjects/src/docs_view.rs @@ -104,11 +104,6 @@ pub fn stamp_script(stamp: &str) -> String { format!("window.MO_STAMP = {};\n", js_quote(stamp)) } -/// The docs view of the model alone. -pub fn build_model(tree: &Tree, root: NodeId) -> Value { - build(tree, root, None, None, None) -} - /// Build the docs view of the model at `root`. `verify`, `manifest` and `routes` are optional; /// a malformed one only leaves its part out. pub fn build( From 6010c7cea881e057ce88f3c8aafbcd2f4f440415 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 06:22:04 -0500 Subject: [PATCH 3/4] no-mistakes(review): Key docs-site skip on prompt files, not dirs --- .../GenSkipConformanceTests.cs | 3 +- .../csharp/MetaObjects.Codegen/CodegenCli.cs | 13 ++- .../MetaObjects.Codegen/Docs/ExplorerSite.cs | 27 ++++-- .../csharp/MetaObjects.Codegen/Generator.cs | 8 +- .../Generators/DocsSiteGenerator.cs | 25 ++++-- server/python/src/metaobjects/cli.py | 16 ++-- .../src/metaobjects/codegen/generator.py | 14 +-- .../metaobjects/codegen/generator_registry.py | 2 +- .../codegen/generators/docs_site_generator.py | 54 ++++++++---- .../python/tests/test_gen_skip_conformance.py | 27 ++++-- .../rust/metaobjects-codegen/src/docs_site.rs | 88 ++++++++++++------- server/rust/metaobjects-codegen/src/engine.rs | 10 +-- .../rust/metaobjects-codegen/src/generator.rs | 25 ++---- .../metaobjects-codegen/tests/docs_site.rs | 44 ++++++++-- 14 files changed, 224 insertions(+), 132 deletions(-) diff --git a/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs index 3ab19e77c6..413722331f 100644 --- a/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs @@ -326,7 +326,7 @@ public void An_entities_run_renders_never_stores_and_leaves_the_full_run_key_alo } [Fact] - public void Editing_a_prompt_beside_the_metadata_regenerates_the_docs_site() + public void An_unchanged_run_skips_and_an_edited_prompt_beside_the_metadata_regenerates_the_docs_site() { File.WriteAllText(P("metaobjects/meta.note.json"), NotePrompt); File.WriteAllText(P("metaobjects/note-text.mustache"), "first text"); @@ -335,6 +335,7 @@ public void Editing_a_prompt_beside_the_metadata_regenerates_the_docs_site() Assert.True(first.Exit == 0, first.Out + first.Err); var model = Path.Combine(OutDir, "site", "explorer-model.js"); Assert.Contains("first text", File.ReadAllText(model)); + Assert.Equal("skip", GenDecision(declared, [])); File.WriteAllText(P("metaobjects/note-text.mustache"), "second text"); Assert.Equal("regenerate", GenDecision(declared, [])); diff --git a/server/csharp/MetaObjects.Codegen/CodegenCli.cs b/server/csharp/MetaObjects.Codegen/CodegenCli.cs index 1560fa76e7..34d146a708 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenCli.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenCli.cs @@ -709,11 +709,10 @@ private static int RunGenArgs(string[] rest, IReadOnlyList declared, TemplateSpec = a.TemplateSpecPath, Entities = a.Entities, EmitAbstractShapes = a.EmitAbstractShapes, Strict = a.Strict, Baseline = a.Baseline, }; - /// The extra inputs of a run: every entry's , and the - /// metadata directory when an entry reads files beside the metadata. - private static IEnumerable KeyExtras(IReadOnlyList suite, ResolvedMetadata meta) => - suite.SelectMany(g => g.ExtraInputs) - .Concat(suite.Any(g => g.ReadsMetadataDirectory) ? [meta.Directory] : []); + /// The extra inputs of a run: every entry's and + /// . + private static IEnumerable KeyExtras(IReadOnlyList suite, MetaRoot root, string projectRoot) => + suite.SelectMany(g => g.ExtraInputs).Concat(suite.SelectMany(g => g.ModelInputs(root, projectRoot))); private static int RunGenCore(string[] rest, IReadOnlyList declared, KeyGate gate, Func? configure) { @@ -847,7 +846,7 @@ private static int RunGenCore(string[] rest, IReadOnlyList declared, var cwd = Directory.GetCurrentDirectory(); var modelHash = ModelHash.Of(genLoad.Root).Model; var identity = GenFingerprint.Key(GenFingerprint.IdentityEntries( - projectRoot, cwd, KeyOptions(a, a.OutDir, a.Namespace ?? meta.Namespace), KeyExtras(suite, meta))); + projectRoot, cwd, KeyOptions(a, a.OutDir, a.Namespace ?? meta.Namespace), KeyExtras(suite, genLoad.Root, projectRoot))); // An --entities run is narrowed and forces exactly those entities: it never skips, never // stores a key, and leaves the stored full-run key alone (it can neither write nor satisfy it). var wholeRun = a.Entities is null; @@ -1104,7 +1103,7 @@ private static int RunVerifyArgs(string[] rest, IReadOnlyList declar projectRoot, ModelHash.Of(load.Root).Model, GenFingerprint.Key(GenFingerprint.IdentityEntries( projectRoot, Directory.GetCurrentDirectory(), KeyOptions(a, a.OutDir, a.Namespace ?? meta.Namespace), - KeyExtras(suite, meta))), + KeyExtras(suite, load.Root, projectRoot))), a.Full)) { Console.WriteLine($"{VerifyCommandName}: OK (nothing changed since the last gen; --full renders and compares)"); diff --git a/server/csharp/MetaObjects.Codegen/Docs/ExplorerSite.cs b/server/csharp/MetaObjects.Codegen/Docs/ExplorerSite.cs index f816227fa7..ab9714120f 100644 --- a/server/csharp/MetaObjects.Codegen/Docs/ExplorerSite.cs +++ b/server/csharp/MetaObjects.Codegen/Docs/ExplorerSite.cs @@ -97,16 +97,9 @@ public static SortedDictionary ReadPromptTexts(JsonObject view, && attr["value"] is JsonValue v && v.TryGetValue(out var s)) textRef = s; } - if (textRef is null) continue; - var segments = textRef.Split('/', '\\'); - bool unsafeRef = Path.IsPathRooted(textRef) || textRef.StartsWith('/') || textRef.StartsWith('\\') - || segments.Any(seg => seg.Length == 0 || seg == ".."); - if (unsafeRef) continue; - foreach (var dir in dirs) + if (textRef is null || PromptCandidates(textRef, dirs) is not { } candidates) continue; + foreach (var p in candidates) { - var parts = segments.ToArray(); - parts[^1] += ".mustache"; - var p = Path.Combine([dir, .. parts]); if (!File.Exists(p)) continue; texts[node["id"]!.GetValue()] = File.ReadAllText(p); break; @@ -115,6 +108,22 @@ public static SortedDictionary ReadPromptTexts(JsonObject view, return texts; } + /// + /// Where a @textRef is looked for, in search order: <dir>/<ref>.mustache for + /// each of . null for a ref that is absolute or climbs out with + /// .., which is never read. + /// + public static IReadOnlyList? PromptCandidates(string textRef, IReadOnlyList dirs) + { + var segments = textRef.Split('/', '\\'); + bool unsafeRef = Path.IsPathRooted(textRef) || textRef.StartsWith('/') || textRef.StartsWith('\\') + || segments.Any(seg => seg.Length == 0 || seg == ".."); + if (unsafeRef) return null; + var parts = segments.ToArray(); + parts[^1] += ".mustache"; + return [.. dirs.Select(dir => Path.Combine([dir, .. parts]))]; + } + private static string? ReadIfPresent(string? dir, string name) { if (dir is null) return null; diff --git a/server/csharp/MetaObjects.Codegen/Generator.cs b/server/csharp/MetaObjects.Codegen/Generator.cs index 5fa00a3946..7c7892139f 100644 --- a/server/csharp/MetaObjects.Codegen/Generator.cs +++ b/server/csharp/MetaObjects.Codegen/Generator.cs @@ -675,10 +675,10 @@ public interface IGenerator bool ReadsRunOutput => false; /// - /// ADR-0064 — whether this entry reads files beside the metadata, in the metadata directory - /// (prompt texts). That directory then joins the run's identity, whole. + /// ADR-0064 — the files this entry reads because the loaded model names them (a prompt's + /// @textRef text), each one present or not. Their content joins the run's identity. /// - bool ReadsMetadataDirectory => false; + IReadOnlyList ModelInputs(MetaRoot root, string projectRoot) => []; } /// A generator entry's handEdits setting: what a run does with a hand-edited file. @@ -720,7 +720,7 @@ internal sealed class HandEditsGenerator(IGenerator inner, HandEdits handEdits) public IReadOnlyList ExtraInputs => Inner.ExtraInputs; public bool ReadsRunOutput => Inner.ReadsRunOutput; /// - public bool ReadsMetadataDirectory => Inner.ReadsMetadataDirectory; + public IReadOnlyList ModelInputs(MetaRoot root, string projectRoot) => Inner.ModelInputs(root, projectRoot); /// public IEnumerable Generate(GenContext ctx) => Inner.Generate(ctx); } diff --git a/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs index f9f60186a9..e55d0da7e7 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs @@ -11,6 +11,8 @@ using System.Text.Json.Nodes; using MetaObjects.Codegen.Docs; using MetaObjects.Config; +using MetaObjects.Meta; +using static MetaObjects.Template.TemplateConstants; namespace MetaObjects.Codegen.Generators; @@ -54,8 +56,21 @@ public sealed class DocsSiteGenerator : IGenerator public IReadOnlyList ExtraInputs => new[] { OwnedDocsSiteDir, Prompts, VerifyFile, RoutesFile }.OfType().ToList(); - /// Prompt texts beside the metadata are read too, so the metadata directory is an input. - public bool ReadsMetadataDirectory => true; + /// Every path a prompt's @textRef may be read from, in every directory searched. + public IReadOnlyList ModelInputs(MetaRoot root, string projectRoot) + { + var dirs = PromptDirs(Path.GetFullPath(projectRoot), projectKnown: true, warn: null); + var files = new SortedSet(StringComparer.Ordinal); + var stack = new Stack([root]); + while (stack.TryPop(out var node)) + { + if (node.Attr(TEMPLATE_ATTR_TEXT_REF) is string textRef + && ExplorerSite.PromptCandidates(textRef, dirs) is { } candidates) + files.UnionWith(candidates); + foreach (var child in node.Children()) stack.Push(child); + } + return [.. files]; + } public IEnumerable Generate(GenContext ctx) { @@ -80,7 +95,7 @@ public IEnumerable Generate(GenContext ctx) view, Title ?? (known is not null && Path.GetFileName(project.TrimEnd(Path.DirectorySeparatorChar)) is { Length: > 0 } dir ? dir : "Metadata"), Stamp, - ExplorerSite.ReadPromptTexts(view, PromptDirs(ctx, project, known is not null)), + ExplorerSite.ReadPromptTexts(view, PromptDirs(project, known is not null, ctx.Warn)), known is not null && Directory.Exists(assets) ? assets : null, known is not null && Directory.Exists(templates) ? templates : null)); var prefix = SubDir.TrimEnd('/') is { Length: > 0 } sub ? sub + "/" : ""; @@ -102,7 +117,7 @@ private static JsonObject ProvenanceJson(IReadOnlyDictionaryWhere a template's @textRef is looked up: the metadata directory, the /// project's templates/ and prompts/, then . - private List PromptDirs(GenContext ctx, string project, bool projectKnown) + private List PromptDirs(string project, bool projectKnown, Action? warn) { var dirs = new List(); void Add(string? d) @@ -122,7 +137,7 @@ void Add(string? d) if (Prompts is not null) { if (Directory.Exists(Path.Combine(project, Prompts))) Add(Prompts); - else ctx.Warn($"docs-site: the prompts directory does not exist: {Prompts}"); + else warn?.Invoke($"docs-site: the prompts directory does not exist: {Prompts}"); } return dirs; } diff --git a/server/python/src/metaobjects/cli.py b/server/python/src/metaobjects/cli.py index b5ed92deb6..33d56713f0 100644 --- a/server/python/src/metaobjects/cli.py +++ b/server/python/src/metaobjects/cli.py @@ -137,7 +137,7 @@ SelectedGenerator, generator_cacheable, generator_extra_inputs, - generator_reads_metadata_dir, + generator_model_inputs, ) from metaobjects.codegen import model_key, skip from metaobjects.codegen.generators.entity_model import entity_model @@ -1845,13 +1845,13 @@ def selected(gen: Generator, token: str) -> bool: every = [g for _t, gens, spec_gens, _o in plan for g in (*gens, *spec_gens)] skip_info.cacheable = all(generator_cacheable(g) for g in every) skip_info.extras = {p for g in every for p in generator_extra_inputs(g)} - if any(generator_reads_metadata_dir(g) for g in every): - meta_dir = Path(config.metadata_dir()).resolve() - try: - meta_rel = meta_dir.relative_to(Path(project_root or ".").resolve()).as_posix() - except ValueError: - meta_rel = str(meta_dir) - skip_info.extras.add(meta_rel) + base = Path(project_root or ".").resolve() + for g in every: + for f in generator_model_inputs(g, root, base): + try: + skip_info.extras.add(f.relative_to(base).as_posix()) + except ValueError: + skip_info.extras.add(str(f)) skip_info.extra_entries = skip.extras_entries( Path(project_root or "."), skip_info.extras) diff --git a/server/python/src/metaobjects/codegen/generator.py b/server/python/src/metaobjects/codegen/generator.py index 87d5380f70..90eec55aee 100644 --- a/server/python/src/metaobjects/codegen/generator.py +++ b/server/python/src/metaobjects/codegen/generator.py @@ -3,6 +3,7 @@ from __future__ import annotations from dataclasses import dataclass, field +from pathlib import Path from typing import Callable, Protocol from metaobjects.meta.core.object.meta_object import MetaObject @@ -79,9 +80,9 @@ class Generator(Protocol): - ``declared_extra_inputs: tuple[str, ...]`` (default ``()``). Project-relative paths the generator reads beyond the model, the config and the template roots; their content is part of the run's key. - - ``reads_metadata_dir: bool`` (default ``False``). ``True`` means the generator reads - files beside the metadata (prompt texts); the metadata directory is then part of the - run's key, whole. + - ``model_inputs(root, project_root) -> list[Path]`` (default none). The files the + generator reads because the loaded model names them (a prompt's ``@textRef`` text), + each one present or not; their content is part of the run's key. """ name: str @@ -146,9 +147,10 @@ def generator_extra_inputs(gen: object) -> tuple[str, ...]: return tuple(getattr(gen, "declared_extra_inputs", ()) or ()) -def generator_reads_metadata_dir(gen: object) -> bool: - """Whether ``gen`` reads files beside the metadata, in the metadata directory.""" - return bool(getattr(gen, "reads_metadata_dir", False)) +def generator_model_inputs(gen: object, root: object, project_root: Path) -> list[Path]: + """The files ``gen`` reads because the loaded model names them.""" + inputs = getattr(gen, "model_inputs", None) + return list(inputs(root, project_root)) if callable(inputs) else [] def per_entity( diff --git a/server/python/src/metaobjects/codegen/generator_registry.py b/server/python/src/metaobjects/codegen/generator_registry.py index 4d7d0caa3b..ef5fdb6a95 100644 --- a/server/python/src/metaobjects/codegen/generator_registry.py +++ b/server/python/src/metaobjects/codegen/generator_registry.py @@ -573,7 +573,7 @@ def _render_helper_default(ctx: GeneratorBuildContext) -> Generator: ), tier="neutral", layer="docs", - factory=lambda ctx: docs_site_generator(**ctx.options), + factory=lambda ctx: docs_site_generator(**ctx.options, source_files=ctx.source_files or ()), # Not ejectable: the site builder is engine (ADR-0034 Amendment 9); what an adopter owns # is the theme under codegen/docs-site/. source=None, diff --git a/server/python/src/metaobjects/codegen/generators/docs_site_generator.py b/server/python/src/metaobjects/codegen/generators/docs_site_generator.py index f01c3b4c7e..12b745de16 100644 --- a/server/python/src/metaobjects/codegen/generators/docs_site_generator.py +++ b/server/python/src/metaobjects/codegen/generators/docs_site_generator.py @@ -111,19 +111,22 @@ def read_prompt_texts(view: dict[str, Any], dirs: list[Path]) -> dict[str, str]: for a in n["attrs"]: if a["name"] == TEMPLATE_ATTR_TEXT_REF and isinstance(a["value"], str): ref = a["value"] - if ref is None: - continue - segments = ref.replace("\\", "/").split("/") - if ref.startswith(("/", "\\")) or os.path.isabs(ref) or any(s in ("", "..") for s in segments): - continue - for d in dirs: - p = d.joinpath(*segments[:-1], segments[-1] + ".mustache") + for p in _prompt_candidates(ref, dirs) if ref is not None else (): if p.is_file(): out[n["id"]] = p.read_text(encoding="utf-8") break return dict(sorted(out.items())) +def _prompt_candidates(ref: str, dirs: list[Path]) -> list[Path]: + """Where a ``@textRef`` is looked for, in search order: ``/.mustache`` for each of + *dirs*. Empty for a ref that is absolute or climbs out with ``..``, which is never read.""" + segments = ref.replace("\\", "/").split("/") + if ref.startswith(("/", "\\")) or os.path.isabs(ref) or any(s in ("", "..") for s in segments): + return [] + return [d.joinpath(*segments[:-1], segments[-1] + ".mustache") for d in dirs] + + def emit_site( view: dict[str, Any], title: str, @@ -166,8 +169,6 @@ class DocsSiteGenerator: name = "docs-site" #: The runner runs a generator that reads the run's output after every other one. reads_run_output = True - #: Prompt texts beside the metadata are read, so the metadata directory is an input. - reads_metadata_dir = True def __init__( self, @@ -177,6 +178,7 @@ def __init__( prompts: str | None = None, verify_file: str | None = None, routes_file: str | None = None, + source_files: tuple[str, ...] = (), ) -> None: self.sub_dir = sub_dir.strip("/") self.title = title @@ -184,9 +186,11 @@ def __init__( self.prompts = prompts self.verify_file = verify_file self.routes_file = routes_file + #: The project's own metadata files: a prompt text is looked for beside them. + self.source_files = source_files #: The owned theme, ``templates/``, the prompts directory and the verify and routes files - #: are read beside the model (ADR-0064), and so is the metadata directory - #: (``reads_metadata_dir``): editing one regenerates. The hash manifest is not an input: + #: are read beside the model (ADR-0064), and so is each prompt text the model names + #: (``model_inputs``): editing one regenerates. The hash manifest is not an input: #: the files the site lists are this run's and the manifest's, and the whole-run skip #: already re-runs when the manifest gains, loses or changes a file. self.declared_extra_inputs: tuple[str, ...] = tuple( @@ -213,7 +217,7 @@ def generate(self, ctx: GenContext) -> list[EmittedFile]: view, self.title if self.title is not None else ((project.name if known else "") or "Metadata"), self.stamp, - read_prompt_texts(view, self._prompt_dirs(root, project, known)), + read_prompt_texts(view, self._prompt_dirs(project, known)), owned / "assets" if known and (owned / "assets").is_dir() else None, owned / "templates" if known and (owned / "templates").is_dir() else None, ) @@ -241,14 +245,26 @@ def _provenance(ctx: GenContext) -> dict[str, Any] | None: out[path] = {"generatedBy": entry.get("generatedBy", ""), "sourceNode": entry["sourceNode"]} return out if raw else None - def _prompt_dirs(self, root: Any, project: Path, config_known: bool = True) -> list[Path]: - """Where prompt ``.mustache`` sources are looked for: the directories the model was - loaded from, the project's ``templates/`` and the ``prompts`` directory, each once.""" + def model_inputs(self, root: Any, project_root: Path) -> list[Path]: + """Every path a prompt's ``@textRef`` may be read from, in every directory searched.""" + dirs = self._prompt_dirs(project_root.resolve()) + files: set[Path] = set() + stack = [root] + while stack: + node = stack.pop() + ref = node.attrs().get(TEMPLATE_ATTR_TEXT_REF) + if isinstance(ref, str): + files.update(_prompt_candidates(ref, dirs)) + stack.extend(node.children()) + return sorted(files) + + def _prompt_dirs(self, project: Path, config_known: bool = True) -> list[Path]: + """Where prompt ``.mustache`` sources are looked for: the directories the project's own + metadata files are in, the project's ``templates/`` and the ``prompts`` directory, each + once.""" dirs: dict[Path, None] = {} - for node in root.children(): - for f in getattr(node.source, "files", ()) or (): - parent = Path(f).resolve().parent - dirs.setdefault(parent, None) + for f in self.source_files: + dirs.setdefault(Path(f).resolve().parent, None) templates = project / "templates" if config_known and templates.is_dir(): dirs.setdefault(templates, None) diff --git a/server/python/tests/test_gen_skip_conformance.py b/server/python/tests/test_gen_skip_conformance.py index e78d9ed3ba..7f3bf73044 100644 --- a/server/python/tests/test_gen_skip_conformance.py +++ b/server/python/tests/test_gen_skip_conformance.py @@ -447,23 +447,36 @@ def test_a_run_that_names_entities_renders_and_leaves_the_full_run_key_alone( } -def test_editing_a_prompt_in_templates_regenerates_the_docs_site( - tmp_path: Path, monkeypatch, capsys +@pytest.mark.parametrize("case", ["metaobjects", "templates", "root-file"]) +def test_an_unchanged_run_skips_and_an_edited_prompt_regenerates_the_docs_site( + case: str, tmp_path: Path, monkeypatch, capsys ) -> None: + # A prompt beside the metadata, in `templates/`, or beside a model file at the project root. project = _project(tmp_path) - (tmp_path / "metaobjects" / "meta.note.json").write_text(json.dumps(_NOTE_PROMPT)) - (tmp_path / "templates").mkdir() - prompt = tmp_path / "templates" / "note-text.mustache" + if case == "root-file": + (tmp_path / "meta.note.json").write_text(json.dumps(_NOTE_PROMPT)) + prompt = tmp_path / "note-text.mustache" + project.config.write_text( + "metadata: meta.note.json\n" + "targets:\n app:\n outDir: generated\n generators: [docs-site]\n", + encoding="utf-8", + ) + else: + (tmp_path / "metaobjects" / "meta.note.json").write_text(json.dumps(_NOTE_PROMPT)) + (tmp_path / case).mkdir(exist_ok=True) + prompt = tmp_path / case / "note-text.mustache" + project.write_config("[entity, docs-site]") prompt.write_text("first text") - project.write_config("[entity, docs-site]") h = Harness(project, monkeypatch, capsys) rc, skipped = h.gen() assert rc == 0 and not skipped, h.out + h.err model = tmp_path / "generated" / "site" / "explorer-model.js" assert "first text" in model.read_text() + rc, skipped = h.gen() + assert rc == 0 and skipped, f"{case}: nothing changed\n{h.out}{h.err}" prompt.write_text("second text") rc, skipped = h.gen() - assert rc == 0 and not skipped, "an edited prompt is an input" + assert rc == 0 and not skipped, f"{case}: an edited prompt is an input" text = model.read_text() assert "second text" in text and "first text" not in text diff --git a/server/rust/metaobjects-codegen/src/docs_site.rs b/server/rust/metaobjects-codegen/src/docs_site.rs index 9a37dbfe55..5f7d6e160d 100644 --- a/server/rust/metaobjects-codegen/src/docs_site.rs +++ b/server/rust/metaobjects-codegen/src/docs_site.rs @@ -33,10 +33,12 @@ //! `codegen/docs-site/assets/explorer.css`, `assets/explorer.js` and //! `templates/explorer-*.mustache` used in place of the shipped ones. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; +use metaobjects::collection::Collection; use metaobjects::docs_view; +use metaobjects::node::{NodeId, Tree}; use serde_json::Value; use crate::generator::{EmittedFile, GenContext, GenError, Generator, Options, unknown_options}; @@ -167,8 +169,8 @@ impl Generator for DocsSiteGenerator { true } - fn reads_source_dirs(&self) -> bool { - true + fn model_inputs(&self, tree: &Tree, root: NodeId, collection: &Collection) -> Vec { + DocsSite::default().model_inputs(tree, root, collection) } fn configure(&self, options: &Options) -> Result, GenError> { @@ -190,8 +192,8 @@ impl Generator for DocsSite { } /// The owned theme, `templates/`, the prompts directory and the verify and routes files are - /// read beside the model (ADR-0064), and so are the metadata directories - /// ([`Generator::reads_source_dirs`]): editing one regenerates. The hash manifest is not an + /// read beside the model (ADR-0064), and so is each prompt text the model names + /// ([`Generator::model_inputs`]): editing one regenerates. The hash manifest is not an /// input here: the whole-run skip already re-runs when a recorded file changes or goes. fn extra_inputs(&self) -> Vec { let mut inputs = vec![OWNED_DOCS_SITE_DIR.to_string(), TEMPLATES_DIR.to_string()]; @@ -205,8 +207,18 @@ impl Generator for DocsSite { true } - fn reads_source_dirs(&self) -> bool { - true + /// Every path a prompt's `@textRef` may be read from, in every directory searched. + fn model_inputs(&self, tree: &Tree, root: NodeId, collection: &Collection) -> Vec { + let dirs = self.prompt_dirs(collection); + let mut files = BTreeSet::new(); + let mut stack = vec![root]; + while let Some(id) = stack.pop() { + if let Some(r) = tree.attr(id, ATTR_TEXT_REF).and_then(Value::as_str) { + files.extend(prompt_candidates(r, &dirs).into_iter().flatten()); + } + stack.extend(tree.children(id).iter().copied()); + } + files.into_iter().collect() } fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { @@ -245,7 +257,7 @@ impl Generator for DocsSite { |n| n.to_string_lossy().into_owned(), ) }); - let texts = read_prompt_texts(&view, &self.prompt_dirs(ctx)); + let texts = read_prompt_texts(&view, &self.prompt_dirs(ctx.collection)); let site = emit(&SiteInput { view: &view, title: &title, @@ -293,16 +305,20 @@ impl DocsSite { /// Where prompt `.mustache` sources are looked for: the directories the model was loaded /// from, the project's `templates/` and the `prompts` directory, each once. - fn prompt_dirs(&self, ctx: &GenContext<'_>) -> Vec { - let project = &ctx.collection.config_dir; + fn prompt_dirs(&self, collection: &Collection) -> Vec { + let project = &collection.config_dir; let mut dirs: Vec = Vec::new(); let mut add = |d: PathBuf| { if d.is_dir() && !dirs.contains(&d) { dirs.push(d); } }; - for dir in crate::generator::source_dirs(&ctx.collection.source_roots) { - add(dir); + for root in &collection.source_roots { + add(if root.is_dir() { + root.clone() + } else { + root.parent().map(Path::to_path_buf).unwrap_or_default() + }); } add(project.join(TEMPLATES_DIR)); if let Some(p) = &self.prompts { @@ -431,26 +447,10 @@ pub fn read_prompt_texts(view: &Value, dirs: &[PathBuf]) -> BTreeMap = r.split(['/', '\\']).collect(); - let unsafe_ref = Path::new(r).is_absolute() - || r.starts_with('/') - || r.starts_with('\\') - || segments.iter().any(|s| s.is_empty() || *s == ".."); - if unsafe_ref { - continue; - } - for d in dirs { - let mut p = d.clone(); - for (i, s) in segments.iter().enumerate() { - if i == segments.len() - 1 { - p.push(format!("{s}{MUSTACHE}")); - } else { - p.push(s); - } - } + for p in candidates { if let Ok(text) = std::fs::read_to_string(&p) { if let Some(id) = n["id"].as_str() { out.insert(id.to_string(), text); @@ -461,3 +461,31 @@ pub fn read_prompt_texts(view: &Value, dirs: &[PathBuf]) -> BTreeMap/.mustache` for each of +/// `dirs`. `None` for a ref that is absolute or climbs out with `..`, which is never read. +fn prompt_candidates(r: &str, dirs: &[PathBuf]) -> Option> { + let segments: Vec<&str> = r.split(['/', '\\']).collect(); + let unsafe_ref = Path::new(r).is_absolute() + || r.starts_with('/') + || r.starts_with('\\') + || segments.iter().any(|s| s.is_empty() || *s == ".."); + if unsafe_ref { + return None; + } + Some( + dirs.iter() + .map(|d| { + let mut p = d.clone(); + for (i, s) in segments.iter().enumerate() { + if i == segments.len() - 1 { + p.push(format!("{s}{MUSTACHE}")); + } else { + p.push(s); + } + } + p + }) + .collect(), + ) +} diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index 0e61dd4ffc..0703d31e5a 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -728,12 +728,10 @@ fn prepare<'g>( let digest = hash_tree(&project_root.join(&extra)); entries.push(InputEntry::new(KIND_EXTRA, extra, digest)); } - if g.reads_source_dirs() { - for dir in crate::generator::source_dirs(&loaded.collection.source_roots) { - let name = dir.strip_prefix(&project_root).unwrap_or(&dir); - let name = name.to_string_lossy().replace('\\', "/"); - entries.push(InputEntry::new(KIND_EXTRA, name, hash_tree(&dir))); - } + for file in g.model_inputs(tree, loaded.result.root, &loaded.collection) { + let name = file.strip_prefix(&project_root).unwrap_or(&file); + let name = name.to_string_lossy().replace('\\', "/"); + entries.push(InputEntry::new(KIND_EXTRA, name, hash_file(&file))); } } // The owned generator crate, whole: the generator list is the adopter's file and may pull diff --git a/server/rust/metaobjects-codegen/src/generator.rs b/server/rust/metaobjects-codegen/src/generator.rs index bf223860ef..839943cb2d 100644 --- a/server/rust/metaobjects-codegen/src/generator.rs +++ b/server/rust/metaobjects-codegen/src/generator.rs @@ -6,7 +6,7 @@ use std::collections::BTreeSet; use std::fmt; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use metaobjects::collection::Collection; use metaobjects::node::{NodeId, Tree}; @@ -177,27 +177,12 @@ pub trait Generator { false } - /// Whether this generator reads files beside the metadata, in the directories the model was - /// loaded from (prompt texts). Those directories are then part of the skip key, whole. - fn reads_source_dirs(&self) -> bool { - false + /// The files this generator reads because the loaded model names them (a prompt's + /// `@textRef` text), each one present or not. Their content is part of the skip key. + fn model_inputs(&self, _tree: &Tree, _root: NodeId, _collection: &Collection) -> Vec { + Vec::new() } /// Produce the generator's files for the loaded model. fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError>; } - -/// The directories the model was loaded from: each source root, or the directory of a root -/// that is a file. -pub(crate) fn source_dirs(roots: &[PathBuf]) -> Vec { - roots - .iter() - .map(|root| { - if root.is_dir() { - root.clone() - } else { - root.parent().map(Path::to_path_buf).unwrap_or_default() - } - }) - .collect() -} diff --git a/server/rust/metaobjects-codegen/tests/docs_site.rs b/server/rust/metaobjects-codegen/tests/docs_site.rs index d7fcd71420..74ff678152 100644 --- a/server/rust/metaobjects-codegen/tests/docs_site.rs +++ b/server/rust/metaobjects-codegen/tests/docs_site.rs @@ -219,12 +219,33 @@ fn a_run_writes_the_explorer_over_the_files_the_manifest_records() { } #[test] -fn editing_a_prompt_beside_the_metadata_or_in_templates_regenerates_the_site() { - for dir in ["metaobjects", "templates"] { - let p = Scratch::project(&format!("docs-site-prompt-{dir}"), &[]); +fn an_unchanged_run_skips_and_an_edited_prompt_regenerates_the_site() { + // (case, the `sources` path, where the prompt lives): the default metadata directory, + // `templates/`, and a model whose source is a file at the project root. + for (case, source, dir) in [ + ("metaobjects", None, "metaobjects"), + ("templates", None, "templates"), + ("root-file", Some("meta.shop.json"), ""), + ] { + let p = Scratch::project(&format!("docs-site-prompt-{case}"), &[]); copy_dir(&fixture("shop").join("project"), p.path()); std::fs::remove_dir_all(p.path().join("prompts")).unwrap(); - let prompt = format!("{dir}/shop/order-note.mustache"); + if let Some(source) = source { + std::fs::rename( + p.path().join("metaobjects/meta.shop.json"), + p.path().join("meta.shop.json"), + ) + .unwrap(); + std::fs::remove_dir_all(p.path().join("metaobjects")).unwrap(); + p.write( + ".metaobjects/config.json", + &format!(r#"{{ "schema_version": 1, "sources": [{{ "path": "{source}" }}] }}"#), + ); + } + let prompt = format!( + "{dir}{}shop/order-note.mustache", + if dir.is_empty() { "" } else { "/" } + ); p.write(&prompt, "first text"); p.write( "metaobjects.config.json", @@ -232,20 +253,25 @@ fn editing_a_prompt_beside_the_metadata_or_in_templates_regenerates_the_site() { ); let mut opts = RunOptions::new(p.path()); opts.out_dir = PathBuf::from("generated"); - run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("gen failed: {e}")); - assert!(p.read("generated/explorer-model.js").contains("first text")); + run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("{case}: gen failed: {e}")); + assert!( + p.read("generated/explorer-model.js").contains("first text"), + "{case}: the site carries the prompt" + ); + let again = run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("{case}: {e}")); + assert_eq!(again.outcome, Outcome::Skipped, "{case}: nothing changed"); p.write(&prompt, "second text"); - let r = run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("gen failed: {e}")); + let r = run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("{case}: {e}")); assert_ne!( r.outcome, Outcome::Skipped, - "{dir}: an edited prompt is an input" + "{case}: an edited prompt is an input" ); let model = p.read("generated/explorer-model.js"); assert!( model.contains("second text") && !model.contains("first text"), - "{dir}: the site carries the edited prompt" + "{case}: the site carries the edited prompt" ); } } From ac2a0eda8ea6a28713f6d9dfa67aa868446105ae Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 06:35:45 -0500 Subject: [PATCH 4/4] no-mistakes(document): Rust docs view docs mostly current; fixed CONFORMANCE explorer row and paragraph; --transport question left open --- docs/CONFORMANCE.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 6dbf31b04f..2ae59a0255 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -73,7 +73,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | — | | [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 88 cases (31 core + 10 TypeScript + 9 Java + 12 Kotlin + 6 C# + 12 Python + 8 Rust) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | ✓ (core and Kotlin dialect; `KotlinWriter` in `codegen-kotlin`) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | ✓ (core and Rust dialect) | | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 22 cases (17 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | — | -| [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the docs view: a loaded project + the verify payload, manifest and routes in, one `explorer.json` out) | 3 cases (`shop`, `crm`, `model-alone`) | ✓ | ✓ (`DocsView`, and the `docs-site` generator end to end) | ✓ (the JVM builder, through `codegen-kotlin`'s `docs-site`) | ✓ (`MetaObjects.DocsView`, and the `docs-site` generator end to end) | ✓ (`metaobjects.docs_view`, and the `docs-site` generator end to end) | — | +| [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the docs view: a loaded project + the verify payload, manifest and routes in, one `explorer.json` out) | 3 cases (`shop`, `crm`, `model-alone`) | ✓ | ✓ (`DocsView`, and the `docs-site` generator end to end) | ✓ (the JVM builder, through `codegen-kotlin`'s `docs-site`) | ✓ (`MetaObjects.DocsView`, and the `docs-site` generator end to end) | ✓ (`metaobjects.docs_view`, and the `docs-site` generator end to end) | ✓ (`metaobjects::docs_view`, and the `docs-site` generator end to end) | **Rust (ADR-0065)** joined the table with its service stack. Its ledgers (the metamodel corpus's `server/rust/metaobjects/tests/conformance-expected-failures.json`, empty; the YAML @@ -916,7 +916,8 @@ Java (`metadata`'s `DocsViewConformanceTest`, and `codegen-base`'s `ExplorerSite generator) and Kotlin (`KotlinDocsSiteConformanceTest`, through its registry's `docs-site`) build every case byte for byte; the JVM has one builder, which Kotlin calls rather than re-implements. C# (`MetaObjects.DocsView`, through `DocsSiteGenerator` and `MetaEndpoint.MetaDocs`) and Python -(`metaobjects.docs_view`, through `docs-site` and `meta_docs`) build every case byte for byte too. +(`metaobjects.docs_view`, through `docs-site` and `meta_docs`) build every case byte for byte too; and Rust +(`metaobjects::docs_view`, through `docs-site` and `meta_endpoint::docs`) does too. **TypeScript runs it** in `server/typescript/packages/metadata/test/docs-view-conformance.test.ts` (the view) and